diff --git a/lib/geom/part/geom_part.c b/lib/geom/part/geom_part.c index b21ebf7ef8d8..41131646e246 100644 --- a/lib/geom/part/geom_part.c +++ b/lib/geom/part/geom_part.c @@ -1,1346 +1,1347 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2007, 2008 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "core/geom.h" #include "misc/subr.h" #ifdef STATIC_GEOM_CLASSES #define PUBSYM(x) gpart_##x #else #define PUBSYM(x) x #endif uint32_t PUBSYM(lib_version) = G_LIB_VERSION; uint32_t PUBSYM(version) = 0; static char sstart[32]; static char ssize[32]; volatile sig_atomic_t undo_restore; #define GPART_AUTOFILL "*" #define GPART_FLAGS "C" #define GPART_PARAM_BOOTCODE "bootcode" #define GPART_PARAM_INDEX "index" #define GPART_PARAM_PARTCODE "partcode" #define GPART_PARAM_SKIP_DSN "skip_dsn" static struct gclass *find_class(struct gmesh *, const char *); static struct ggeom * find_geom(struct gclass *, const char *); static int geom_is_withered(struct ggeom *); static const char *find_geomcfg(struct ggeom *, const char *); static const char *find_provcfg(struct gprovider *, const char *); static struct gprovider *find_provider(struct ggeom *, off_t); static const char *fmtsize(int64_t); static int gpart_autofill(struct gctl_req *); static int gpart_autofill_resize(struct gctl_req *); static void gpart_bootcode(struct gctl_req *, unsigned int); static void *gpart_bootfile_read(const char *, ssize_t *); static _Noreturn void gpart_issue(struct gctl_req *, unsigned int); static void gpart_show(struct gctl_req *, unsigned int); static void gpart_show_geom(struct ggeom *, const char *, int); static int gpart_show_hasopt(struct gctl_req *, const char *, const char *); static void gpart_write_partcode(struct ggeom *, int, void *, ssize_t); static void gpart_write_partcode_vtoc8(struct ggeom *, int, void *); static void gpart_print_error(const char *); static void gpart_backup(struct gctl_req *, unsigned int); static void gpart_restore(struct gctl_req *, unsigned int); struct g_command PUBSYM(class_commands)[] = { { "add", 0, gpart_issue, { { 'a', "alignment", GPART_AUTOFILL, G_TYPE_STRING }, { 'b', "start", GPART_AUTOFILL, G_TYPE_STRING }, { 's', "size", GPART_AUTOFILL, G_TYPE_STRING }, { 't', "type", NULL, G_TYPE_STRING }, { 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER }, { 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-t type [-a alignment] [-b start] [-s size] [-i index] " "[-l label] [-f flags] geom" }, { "backup", 0, gpart_backup, G_NULL_OPTS, "geom" }, { "bootcode", 0, gpart_bootcode, { { 'b', GPART_PARAM_BOOTCODE, G_VAL_OPTIONAL, G_TYPE_STRING }, { 'p', GPART_PARAM_PARTCODE, G_VAL_OPTIONAL, G_TYPE_STRING }, { 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, { 'N', GPART_PARAM_SKIP_DSN, NULL, G_TYPE_BOOL }, G_OPT_SENTINEL }, "[-N] [-b bootcode] [-p partcode -i index] [-f flags] geom" }, { "commit", 0, gpart_issue, G_NULL_OPTS, "geom" }, { "create", 0, gpart_issue, { { 's', "scheme", NULL, G_TYPE_STRING }, { 'n', "entries", G_VAL_OPTIONAL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-s scheme [-n entries] [-f flags] provider" }, { "delete", 0, gpart_issue, { { 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-i index [-f flags] geom" }, { "destroy", 0, gpart_issue, { { 'F', "force", NULL, G_TYPE_BOOL }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "[-F] [-f flags] geom" }, { "modify", 0, gpart_issue, { { 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER }, { 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING }, { 't', "type", G_VAL_OPTIONAL, G_TYPE_STRING }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-i index [-l label] [-t type] [-f flags] geom" }, { "set", 0, gpart_issue, { { 'a', "attrib", NULL, G_TYPE_STRING }, { 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-a attrib [-i index] [-f flags] geom" }, { "show", 0, gpart_show, { { 'l', "show_label", NULL, G_TYPE_BOOL }, { 'r', "show_rawtype", NULL, G_TYPE_BOOL }, { 'p', "show_providers", NULL, G_TYPE_BOOL }, G_OPT_SENTINEL }, "[-l | -r] [-p] [geom ...]" }, { "undo", 0, gpart_issue, G_NULL_OPTS, "geom" }, { "unset", 0, gpart_issue, { { 'a', "attrib", NULL, G_TYPE_STRING }, { 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-a attrib [-i index] [-f flags] geom" }, { "resize", 0, gpart_issue, { { 'a', "alignment", GPART_AUTOFILL, G_TYPE_STRING }, { 's', "size", GPART_AUTOFILL, G_TYPE_STRING }, { 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "-i index [-a alignment] [-s size] [-f flags] geom" }, { "restore", 0, gpart_restore, { { 'F', "force", NULL, G_TYPE_BOOL }, { 'l', "restore_labels", NULL, G_TYPE_BOOL }, { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "[-lF] [-f flags] provider [...]" }, { "recover", 0, gpart_issue, { { 'f', "flags", GPART_FLAGS, G_TYPE_STRING }, G_OPT_SENTINEL }, "[-f flags] geom" }, G_CMD_SENTINEL }; static struct gclass * find_class(struct gmesh *mesh, const char *name) { struct gclass *classp; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { if (strcmp(classp->lg_name, name) == 0) return (classp); } return (NULL); } static struct ggeom * find_geom(struct gclass *classp, const char *name) { struct ggeom *gp, *wgp; if (strncmp(name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) name += sizeof(_PATH_DEV) - 1; wgp = NULL; LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (strcmp(gp->lg_name, name) != 0) continue; if (!geom_is_withered(gp)) return (gp); else wgp = gp; } return (wgp); } static int geom_is_withered(struct ggeom *gp) { struct gconfig *gc; LIST_FOREACH(gc, &gp->lg_config, lg_config) { if (!strcmp(gc->lg_name, "wither")) return (1); } return (0); } static const char * find_geomcfg(struct ggeom *gp, const char *cfg) { struct gconfig *gc; LIST_FOREACH(gc, &gp->lg_config, lg_config) { if (!strcmp(gc->lg_name, cfg)) return (gc->lg_val); } return (NULL); } static const char * find_provcfg(struct gprovider *pp, const char *cfg) { struct gconfig *gc; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (!strcmp(gc->lg_name, cfg)) return (gc->lg_val); } return (NULL); } static struct gprovider * find_provider(struct ggeom *gp, off_t minsector) { struct gprovider *pp, *bestpp; const char *s; off_t sector, bestsector; bestpp = NULL; bestsector = 0; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "start"); sector = (off_t)strtoimax(s, NULL, 0); if (sector < minsector) continue; if (bestpp != NULL && sector >= bestsector) continue; bestpp = pp; bestsector = sector; } return (bestpp); } static const char * fmtsize(int64_t rawsz) { static char buf[5]; humanize_number(buf, sizeof(buf), rawsz, "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL); return (buf); } static const char * fmtattrib(struct gprovider *pp) { static char buf[128]; struct gconfig *gc; u_int idx; buf[0] = '\0'; idx = 0; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "attrib") != 0) continue; idx += snprintf(buf + idx, sizeof(buf) - idx, "%s%s", (idx == 0) ? " [" : ",", gc->lg_val); } if (idx > 0) snprintf(buf + idx, sizeof(buf) - idx, "] "); return (buf); } #define ALIGNDOWN(d, a) ((d) - (d) % (a)) #define ALIGNUP(d, a) ((d) % (a) ? (d) - (d) % (a) + (a): (d)) static int gpart_autofill_resize(struct gctl_req *req) { struct gmesh mesh; struct gclass *cp; struct ggeom *gp; struct gprovider *pp; off_t last, size, start, new_size; off_t lba, new_lba, alignment, offset; const char *s; int error, idx, has_alignment; idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX); if (idx < 1) errx(EXIT_FAILURE, "invalid partition index"); error = geom_gettree(&mesh); if (error) return (error); s = gctl_get_ascii(req, "class"); if (s == NULL) abort(); cp = find_class(&mesh, s); if (cp == NULL) errx(EXIT_FAILURE, "Class %s not found.", s); s = gctl_get_ascii(req, "arg0"); if (s == NULL) abort(); gp = find_geom(cp, s); if (gp == NULL) errx(EXIT_FAILURE, "No such geom: %s.", s); pp = LIST_FIRST(&gp->lg_consumer)->lg_provider; if (pp == NULL) errx(EXIT_FAILURE, "Provider for geom %s not found.", s); s = gctl_get_ascii(req, "alignment"); has_alignment = (*s == '*') ? 0 : 1; alignment = 1; if (has_alignment) { error = g_parse_lba(s, pp->lg_sectorsize, &alignment); if (error) errc(EXIT_FAILURE, error, "Invalid alignment param"); if (alignment == 0) errx(EXIT_FAILURE, "Invalid alignment param"); } else { lba = pp->lg_stripesize / pp->lg_sectorsize; if (lba > 0) alignment = lba; } error = gctl_delete_param(req, "alignment"); if (error) errc(EXIT_FAILURE, error, "internal error"); s = gctl_get_ascii(req, "size"); if (*s == '*') new_size = 0; else { error = g_parse_lba(s, pp->lg_sectorsize, &new_size); if (error) errc(EXIT_FAILURE, error, "Invalid size param"); /* no autofill necessary. */ if (has_alignment == 0) goto done; } offset = (pp->lg_stripeoffset / pp->lg_sectorsize) % alignment; s = find_geomcfg(gp, "last"); if (s == NULL) errx(EXIT_FAILURE, "Final block not found for geom %s", gp->lg_name); last = (off_t)strtoimax(s, NULL, 0); LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "index"); if (s == NULL) continue; if (atoi(s) == idx) break; } if (pp == NULL) errx(EXIT_FAILURE, "invalid partition index"); s = find_provcfg(pp, "start"); start = (off_t)strtoimax(s, NULL, 0); s = find_provcfg(pp, "end"); lba = (off_t)strtoimax(s, NULL, 0); size = lba - start + 1; pp = find_provider(gp, lba + 1); if (new_size > 0 && (new_size <= size || pp == NULL)) { /* The start offset may be not aligned, so we align the end * offset and then calculate the size. */ new_size = ALIGNDOWN(start + offset + new_size, alignment) - start - offset; goto done; } if (pp == NULL) { new_size = ALIGNDOWN(last + offset + 1, alignment) - start - offset; if (new_size < size) return (ENOSPC); } else { s = find_provcfg(pp, "start"); new_lba = (off_t)strtoimax(s, NULL, 0); /* * Is there any free space between current and * next providers? */ new_lba = ALIGNDOWN(new_lba + offset, alignment) - offset; if (new_lba > lba) new_size = new_lba - start; else { geom_deletetree(&mesh); return (ENOSPC); } } done: snprintf(ssize, sizeof(ssize), "%jd", (intmax_t)new_size); gctl_change_param(req, "size", -1, ssize); geom_deletetree(&mesh); return (0); } static int gpart_autofill(struct gctl_req *req) { struct gmesh mesh; struct gclass *cp; struct ggeom *gp; struct gprovider *pp; off_t first, last, a_first; off_t size, start, a_lba; off_t lba, len, alignment, offset; uintmax_t grade; const char *s; int error, has_size, has_start, has_alignment; s = gctl_get_ascii(req, "verb"); if (strcmp(s, "resize") == 0) return gpart_autofill_resize(req); if (strcmp(s, "add") != 0) return (0); error = geom_gettree(&mesh); if (error) return (error); s = gctl_get_ascii(req, "class"); if (s == NULL) abort(); cp = find_class(&mesh, s); if (cp == NULL) errx(EXIT_FAILURE, "Class %s not found.", s); s = gctl_get_ascii(req, "arg0"); if (s == NULL) abort(); gp = find_geom(cp, s); if (gp == NULL) { if (g_device_path(s) == NULL) { errx(EXIT_FAILURE, "No such geom %s.", s); } else { /* * We don't free memory allocated by g_device_path() as * we are about to exit. */ errx(EXIT_FAILURE, "No partitioning scheme found on geom %s. Create one first using 'gpart create'.", s); } } pp = LIST_FIRST(&gp->lg_consumer)->lg_provider; if (pp == NULL) errx(EXIT_FAILURE, "Provider for geom %s not found.", s); s = gctl_get_ascii(req, "alignment"); has_alignment = (*s == '*') ? 0 : 1; alignment = 1; if (has_alignment) { error = g_parse_lba(s, pp->lg_sectorsize, &alignment); if (error) errc(EXIT_FAILURE, error, "Invalid alignment param"); if (alignment == 0) errx(EXIT_FAILURE, "Invalid alignment param"); } error = gctl_delete_param(req, "alignment"); if (error) errc(EXIT_FAILURE, error, "internal error"); s = gctl_get_ascii(req, "size"); has_size = (*s == '*') ? 0 : 1; size = 0; if (has_size) { error = g_parse_lba(s, pp->lg_sectorsize, &size); if (error) errc(EXIT_FAILURE, error, "Invalid size param"); } s = gctl_get_ascii(req, "start"); has_start = (*s == '*') ? 0 : 1; start = 0ULL; if (has_start) { error = g_parse_lba(s, pp->lg_sectorsize, &start); if (error) errc(EXIT_FAILURE, error, "Invalid start param"); } /* No autofill necessary. */ if (has_size && has_start && !has_alignment) goto done; len = pp->lg_stripesize / pp->lg_sectorsize; if (len > 0 && !has_alignment) alignment = len; /* Adjust parameters to stripeoffset */ offset = (pp->lg_stripeoffset / pp->lg_sectorsize) % alignment; start = ALIGNUP(start + offset, alignment); if (size > alignment) size = ALIGNDOWN(size, alignment); s = find_geomcfg(gp, "first"); if (s == NULL) errx(EXIT_FAILURE, "Starting block not found for geom %s", gp->lg_name); first = (off_t)strtoimax(s, NULL, 0); s = find_geomcfg(gp, "last"); if (s == NULL) errx(EXIT_FAILURE, "Final block not found for geom %s", gp->lg_name); last = (off_t)strtoimax(s, NULL, 0); grade = ~0ULL; a_first = ALIGNUP(first + offset, alignment); last = ALIGNDOWN(last + offset + 1, alignment) - 1; if (a_first < start) a_first = start; while ((pp = find_provider(gp, first)) != NULL) { s = find_provcfg(pp, "start"); lba = (off_t)strtoimax(s, NULL, 0); a_lba = ALIGNDOWN(lba + offset, alignment); if (first < a_lba && a_first < a_lba) { /* Free space [first, lba> */ len = a_lba - a_first; if (has_size) { if (len >= size && (uintmax_t)(len - size) < grade) { start = a_first; grade = len - size; } } else if (has_start) { if (start >= a_first && start < a_lba) { size = a_lba - start; grade = start - a_first; } } else { if (grade == ~0ULL || len > size) { start = a_first; size = len; grade = 0; } } } s = find_provcfg(pp, "end"); first = (off_t)strtoimax(s, NULL, 0) + 1; if (first + offset > a_first) a_first = ALIGNUP(first + offset, alignment); } if (a_first <= last) { /* Free space [first-last] */ len = ALIGNDOWN(last - a_first + 1, alignment); if (has_size) { if (len >= size && (uintmax_t)(len - size) < grade) { start = a_first; grade = len - size; } } else if (has_start) { if (start >= a_first && start <= last) { size = ALIGNDOWN(last - start + 1, alignment); grade = start - a_first; } } else { if (grade == ~0ULL || len > size) { start = a_first; size = len; grade = 0; } } } if (grade == ~0ULL) { geom_deletetree(&mesh); return (ENOSPC); } start -= offset; /* Return back to real offset */ done: snprintf(ssize, sizeof(ssize), "%jd", (intmax_t)size); gctl_change_param(req, "size", -1, ssize); snprintf(sstart, sizeof(sstart), "%jd", (intmax_t)start); gctl_change_param(req, "start", -1, sstart); geom_deletetree(&mesh); return (0); } static void gpart_show_geom(struct ggeom *gp, const char *element, int show_providers) { struct gprovider *pp; const char *s, *scheme; off_t first, last, sector, end; off_t length, secsz; int idx, wblocks, wname, wmax; if (geom_is_withered(gp)) return; scheme = find_geomcfg(gp, "scheme"); if (scheme == NULL) errx(EXIT_FAILURE, "Scheme not found for geom %s", gp->lg_name); s = find_geomcfg(gp, "first"); if (s == NULL) errx(EXIT_FAILURE, "Starting block not found for geom %s", gp->lg_name); first = (off_t)strtoimax(s, NULL, 0); s = find_geomcfg(gp, "last"); if (s == NULL) errx(EXIT_FAILURE, "Final block not found for geom %s", gp->lg_name); last = (off_t)strtoimax(s, NULL, 0); wblocks = strlen(s); s = find_geomcfg(gp, "state"); if (s == NULL) errx(EXIT_FAILURE, "State not found for geom %s", gp->lg_name); if (s != NULL && *s != 'C') s = NULL; wmax = strlen(gp->lg_name); if (show_providers) { LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { wname = strlen(pp->lg_name); if (wname > wmax) wmax = wname; } } wname = wmax; pp = LIST_FIRST(&gp->lg_consumer)->lg_provider; secsz = pp->lg_sectorsize; printf("=>%*jd %*jd %*s %s (%s)%s\n", wblocks, (intmax_t)first, wblocks, (intmax_t)(last - first + 1), wname, gp->lg_name, scheme, fmtsize(pp->lg_mediasize), s ? " [CORRUPT]": ""); while ((pp = find_provider(gp, first)) != NULL) { s = find_provcfg(pp, "start"); sector = (off_t)strtoimax(s, NULL, 0); s = find_provcfg(pp, "end"); end = (off_t)strtoimax(s, NULL, 0); length = end - sector + 1; s = find_provcfg(pp, "index"); idx = atoi(s); if (first < sector) { printf(" %*jd %*jd %*s - free - (%s)\n", wblocks, (intmax_t)first, wblocks, (intmax_t)(sector - first), wname, "", fmtsize((sector - first) * secsz)); } if (show_providers) { printf(" %*jd %*jd %*s %s %s (%s)\n", wblocks, (intmax_t)sector, wblocks, (intmax_t)length, wname, pp->lg_name, find_provcfg(pp, element), fmtattrib(pp), fmtsize(pp->lg_mediasize)); } else printf(" %*jd %*jd %*d %s %s (%s)\n", wblocks, (intmax_t)sector, wblocks, (intmax_t)length, wname, idx, find_provcfg(pp, element), fmtattrib(pp), fmtsize(pp->lg_mediasize)); first = end + 1; } if (first <= last) { length = last - first + 1; printf(" %*jd %*jd %*s - free - (%s)\n", wblocks, (intmax_t)first, wblocks, (intmax_t)length, wname, "", fmtsize(length * secsz)); } printf("\n"); } static int gpart_show_hasopt(struct gctl_req *req, const char *opt, const char *elt) { if (!gctl_get_int(req, "%s", opt)) return (0); if (elt != NULL) errx(EXIT_FAILURE, "-l and -r are mutually exclusive"); return (1); } static void gpart_show(struct gctl_req *req, unsigned int fl __unused) { struct gmesh mesh; struct gclass *classp; struct ggeom *gp; const char *element, *name; int error, i, nargs, show_providers; element = NULL; if (gpart_show_hasopt(req, "show_label", element)) element = "label"; if (gpart_show_hasopt(req, "show_rawtype", element)) element = "rawtype"; if (element == NULL) element = "type"; name = gctl_get_ascii(req, "class"); if (name == NULL) abort(); error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, name); if (classp == NULL) { geom_deletetree(&mesh); errx(EXIT_FAILURE, "Class %s not found.", name); } show_providers = gctl_get_int(req, "show_providers"); nargs = gctl_get_int(req, "nargs"); if (nargs > 0) { for (i = 0; i < nargs; i++) { name = gctl_get_ascii(req, "arg%d", i); gp = find_geom(classp, name); if (gp != NULL) gpart_show_geom(gp, element, show_providers); else errx(EXIT_FAILURE, "No such geom: %s.", name); } } else { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { gpart_show_geom(gp, element, show_providers); } } geom_deletetree(&mesh); } static void gpart_backup(struct gctl_req *req, unsigned int fl __unused) { struct gmesh mesh; struct gclass *classp; struct gprovider *pp; struct ggeom *gp; const char *s, *scheme; off_t sector, end; off_t length; int error, i, windex, wblocks, wtype; if (gctl_get_int(req, "nargs") != 1) errx(EXIT_FAILURE, "Invalid number of arguments."); error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); s = gctl_get_ascii(req, "class"); if (s == NULL) abort(); classp = find_class(&mesh, s); if (classp == NULL) { geom_deletetree(&mesh); errx(EXIT_FAILURE, "Class %s not found.", s); } s = gctl_get_ascii(req, "arg0"); if (s == NULL) abort(); gp = find_geom(classp, s); if (gp == NULL) errx(EXIT_FAILURE, "No such geom: %s.", s); scheme = find_geomcfg(gp, "scheme"); if (scheme == NULL) abort(); pp = LIST_FIRST(&gp->lg_consumer)->lg_provider; s = find_geomcfg(gp, "last"); if (s == NULL) abort(); wblocks = strlen(s); wtype = 0; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "type"); i = strlen(s); if (i > wtype) wtype = i; } s = find_geomcfg(gp, "entries"); if (s == NULL) abort(); windex = strlen(s); printf("%s %s\n", scheme, s); LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "start"); sector = (off_t)strtoimax(s, NULL, 0); s = find_provcfg(pp, "end"); end = (off_t)strtoimax(s, NULL, 0); length = end - sector + 1; s = find_provcfg(pp, "label"); printf("%-*s %*s %*jd %*jd %s %s\n", windex, find_provcfg(pp, "index"), wtype, find_provcfg(pp, "type"), wblocks, (intmax_t)sector, wblocks, (intmax_t)length, (s != NULL) ? s: "", fmtattrib(pp)); } geom_deletetree(&mesh); } static int skip_line(const char *p) { while (*p != '\0') { if (*p == '#') return (1); if (isspace(*p) == 0) return (0); p++; } return (1); } static void gpart_sighndl(int sig __unused) { undo_restore = 1; } static void gpart_restore(struct gctl_req *req, unsigned int fl __unused) { struct gmesh mesh; struct gclass *classp; struct gctl_req *r; struct ggeom *gp; struct sigaction si_sa; const char *s, *flags, *errstr, *label; char **ap, *argv[6], line[BUFSIZ], *pline; int error, forced, i, l, nargs, created, rl; intmax_t n; nargs = gctl_get_int(req, "nargs"); if (nargs < 1) errx(EXIT_FAILURE, "Invalid number of arguments."); forced = gctl_get_int(req, "force"); flags = gctl_get_ascii(req, "flags"); rl = gctl_get_int(req, "restore_labels"); s = gctl_get_ascii(req, "class"); if (s == NULL) abort(); error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, s); if (classp == NULL) { geom_deletetree(&mesh); errx(EXIT_FAILURE, "Class %s not found.", s); } sigemptyset(&si_sa.sa_mask); si_sa.sa_flags = 0; si_sa.sa_handler = gpart_sighndl; if (sigaction(SIGINT, &si_sa, 0) == -1) err(EXIT_FAILURE, "sigaction SIGINT"); if (forced) { /* destroy existent partition table before restore */ for (i = 0; i < nargs; i++) { s = gctl_get_ascii(req, "arg%d", i); gp = find_geom(classp, s); if (gp != NULL) { r = gctl_get_handle(); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "destroy"); gctl_ro_param(r, "flags", -1, "restore"); gctl_ro_param(r, "force", sizeof(forced), &forced); gctl_ro_param(r, "arg0", -1, s); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_print_error(errstr); gctl_free(r); goto backout; } gctl_free(r); } } } created = 0; while (undo_restore == 0 && fgets(line, sizeof(line) - 1, stdin) != NULL) { /* Format of backup entries: * * [label] ['['attrib[,attrib]']'] */ pline = (char *)line; pline[strlen(line) - 1] = 0; if (skip_line(pline)) continue; for (ap = argv; (*ap = strsep(&pline, " \t")) != NULL;) if (**ap != '\0' && ++ap >= &argv[6]) break; l = ap - &argv[0]; label = pline = NULL; if (l == 1 || l == 2) { /* create table */ if (created) errx(EXIT_FAILURE, "Incorrect backup format."); if (l == 2) n = strtoimax(argv[1], NULL, 0); for (i = 0; i < nargs; i++) { s = gctl_get_ascii(req, "arg%d", i); r = gctl_get_handle(); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "create"); gctl_ro_param(r, "scheme", -1, argv[0]); if (l == 2) gctl_ro_param(r, "entries", sizeof(n), &n); gctl_ro_param(r, "flags", -1, "restore"); gctl_ro_param(r, "arg0", -1, s); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_print_error(errstr); gctl_free(r); goto backout; } gctl_free(r); } created = 1; continue; } else if (l < 4 || created == 0) errx(EXIT_FAILURE, "Incorrect backup format."); else if (l == 5) { if (strchr(argv[4], '[') == NULL) label = argv[4]; else pline = argv[4]; } else if (l == 6) { label = argv[4]; pline = argv[5]; } /* Add partitions to each table */ for (i = 0; i < nargs; i++) { s = gctl_get_ascii(req, "arg%d", i); r = gctl_get_handle(); n = strtoimax(argv[0], NULL, 0); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "add"); gctl_ro_param(r, "flags", -1, "restore"); gctl_ro_param(r, GPART_PARAM_INDEX, sizeof(n), &n); gctl_ro_param(r, "type", -1, argv[1]); gctl_ro_param(r, "start", -1, argv[2]); gctl_ro_param(r, "size", -1, argv[3]); if (rl != 0 && label != NULL) gctl_ro_param(r, "label", -1, argv[4]); gctl_ro_param(r, "alignment", -1, GPART_AUTOFILL); gctl_ro_param(r, "arg0", -1, s); error = gpart_autofill(r); if (error != 0) errc(EXIT_FAILURE, error, "autofill"); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_print_error(errstr); gctl_free(r); goto backout; } gctl_free(r); } if (pline == NULL || *pline != '[') continue; /* set attributes */ pline++; for (ap = argv; (*ap = strsep(&pline, ",]")) != NULL;) if (**ap != '\0' && ++ap >= &argv[6]) break; for (i = 0; i < nargs; i++) { l = ap - &argv[0]; s = gctl_get_ascii(req, "arg%d", i); while (l > 0) { r = gctl_get_handle(); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "set"); gctl_ro_param(r, "flags", -1, "restore"); gctl_ro_param(r, GPART_PARAM_INDEX, sizeof(n), &n); gctl_ro_param(r, "attrib", -1, argv[--l]); gctl_ro_param(r, "arg0", -1, s); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_print_error(errstr); gctl_free(r); goto backout; } gctl_free(r); } } } if (undo_restore) goto backout; /* commit changes if needed */ if (strchr(flags, 'C') != NULL) { for (i = 0; i < nargs; i++) { s = gctl_get_ascii(req, "arg%d", i); r = gctl_get_handle(); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "commit"); gctl_ro_param(r, "arg0", -1, s); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_print_error(errstr); gctl_free(r); goto backout; } gctl_free(r); } } gctl_free(req); geom_deletetree(&mesh); exit(EXIT_SUCCESS); backout: for (i = 0; i < nargs; i++) { s = gctl_get_ascii(req, "arg%d", i); r = gctl_get_handle(); gctl_ro_param(r, "class", -1, classp->lg_name); gctl_ro_param(r, "verb", -1, "undo"); gctl_ro_param(r, "arg0", -1, s); gctl_issue(r); gctl_free(r); } gctl_free(req); geom_deletetree(&mesh); exit(EXIT_FAILURE); } static void * gpart_bootfile_read(const char *bootfile, ssize_t *size) { struct stat sb; void *code; int fd; if (stat(bootfile, &sb) == -1) err(EXIT_FAILURE, "%s", bootfile); if (!S_ISREG(sb.st_mode)) errx(EXIT_FAILURE, "%s: not a regular file", bootfile); if (sb.st_size == 0) errx(EXIT_FAILURE, "%s: empty file", bootfile); if (*size > 0 && sb.st_size > *size) errx(EXIT_FAILURE, "%s: file too big (%zu limit)", bootfile, *size); *size = sb.st_size; fd = open(bootfile, O_RDONLY); if (fd == -1) err(EXIT_FAILURE, "%s", bootfile); code = malloc(*size); if (code == NULL) err(EXIT_FAILURE, NULL); if (read(fd, code, *size) != *size) err(EXIT_FAILURE, "%s", bootfile); close(fd); return (code); } static void gpart_write_partcode(struct ggeom *gp, int idx, void *code, ssize_t size) { char dsf[128]; struct gprovider *pp; const char *s; char *buf; off_t bsize; int fd; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "index"); if (s == NULL) continue; if (atoi(s) == idx) break; } if (pp != NULL) { snprintf(dsf, sizeof(dsf), "/dev/%s", pp->lg_name); if (pp->lg_mediasize < size) errx(EXIT_FAILURE, "%s: not enough space", dsf); fd = open(dsf, O_WRONLY); if (fd == -1) err(EXIT_FAILURE, "%s", dsf); /* * When writing to a disk device, the write must be * sector aligned and not write to any partial sectors, * so round up the buffer size to the next sector and zero it. */ bsize = (size + pp->lg_sectorsize - 1) / pp->lg_sectorsize * pp->lg_sectorsize; buf = calloc(1, bsize); if (buf == NULL) err(EXIT_FAILURE, "%s", dsf); bcopy(code, buf, size); if (write(fd, buf, bsize) != bsize) err(EXIT_FAILURE, "%s", dsf); free(buf); close(fd); printf("partcode written to %s\n", pp->lg_name); } else errx(EXIT_FAILURE, "invalid partition index"); } static void gpart_write_partcode_vtoc8(struct ggeom *gp, int idx, void *code) { char dsf[128]; struct gprovider *pp; const char *s; int installed, fd; installed = 0; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { s = find_provcfg(pp, "index"); if (s == NULL) continue; if (idx != 0 && atoi(s) != idx) continue; snprintf(dsf, sizeof(dsf), "/dev/%s", pp->lg_name); if (pp->lg_sectorsize != sizeof(struct vtoc8)) errx(EXIT_FAILURE, "%s: unexpected sector " "size (%d)\n", dsf, pp->lg_sectorsize); if (pp->lg_mediasize < VTOC_BOOTSIZE) continue; fd = open(dsf, O_WRONLY); if (fd == -1) err(EXIT_FAILURE, "%s", dsf); /* * We ignore the first VTOC_BOOTSIZE bytes of boot code in * order to avoid overwriting the label. */ if (lseek(fd, sizeof(struct vtoc8), SEEK_SET) != sizeof(struct vtoc8)) err(EXIT_FAILURE, "%s", dsf); if (write(fd, (caddr_t)code + sizeof(struct vtoc8), VTOC_BOOTSIZE - sizeof(struct vtoc8)) != VTOC_BOOTSIZE - sizeof(struct vtoc8)) err(EXIT_FAILURE, "%s", dsf); installed++; close(fd); if (idx != 0 && atoi(s) == idx) break; } if (installed == 0) errx(EXIT_FAILURE, "%s: no partitions", gp->lg_name); else printf("partcode written to %s\n", idx != 0 ? pp->lg_name: gp->lg_name); } static void gpart_bootcode(struct gctl_req *req, unsigned int fl) { struct gmesh mesh; struct gclass *classp; struct ggeom *gp; const char *s; void *bootcode, *partcode; size_t bootsize, partsize; int error, idx, vtoc8; if (gctl_has_param(req, GPART_PARAM_BOOTCODE)) { s = gctl_get_ascii(req, GPART_PARAM_BOOTCODE); bootsize = 800 * 1024; /* Arbitrary limit. */ bootcode = gpart_bootfile_read(s, &bootsize); error = gctl_change_param(req, GPART_PARAM_BOOTCODE, bootsize, bootcode); if (error) errc(EXIT_FAILURE, error, "internal error"); } else bootcode = NULL; s = gctl_get_ascii(req, "class"); if (s == NULL) abort(); error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, s); if (classp == NULL) { geom_deletetree(&mesh); errx(EXIT_FAILURE, "Class %s not found.", s); } if (gctl_get_int(req, "nargs") != 1) errx(EXIT_FAILURE, "Invalid number of arguments."); s = gctl_get_ascii(req, "arg0"); if (s == NULL) abort(); gp = find_geom(classp, s); if (gp == NULL) errx(EXIT_FAILURE, "No such geom: %s.", s); s = find_geomcfg(gp, "scheme"); if (s == NULL) errx(EXIT_FAILURE, "Scheme not found for geom %s", gp->lg_name); if (strcmp(s, "VTOC8") == 0) vtoc8 = 1; else vtoc8 = 0; if (gctl_has_param(req, GPART_PARAM_PARTCODE)) { s = gctl_get_ascii(req, GPART_PARAM_PARTCODE); if (vtoc8 != 0) partsize = VTOC_BOOTSIZE; else partsize = 1024 * 1024; /* Arbitrary limit. */ partcode = gpart_bootfile_read(s, &partsize); error = gctl_delete_param(req, GPART_PARAM_PARTCODE); if (error) errc(EXIT_FAILURE, error, "internal error"); } else partcode = NULL; if (gctl_has_param(req, GPART_PARAM_INDEX)) { if (partcode == NULL) errx(EXIT_FAILURE, "-i is only valid with -p"); idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX); if (idx < 1) errx(EXIT_FAILURE, "invalid partition index"); error = gctl_delete_param(req, GPART_PARAM_INDEX); if (error) errc(EXIT_FAILURE, error, "internal error"); } else idx = 0; if (partcode != NULL) { if (vtoc8 == 0) { if (idx == 0) errx(EXIT_FAILURE, "missing -i option"); gpart_write_partcode(gp, idx, partcode, partsize); } else { if (partsize != VTOC_BOOTSIZE) errx(EXIT_FAILURE, "invalid bootcode"); gpart_write_partcode_vtoc8(gp, idx, partcode); } } else if (bootcode == NULL) errx(EXIT_FAILURE, "no -b nor -p"); if (bootcode != NULL) gpart_issue(req, fl); geom_deletetree(&mesh); free(partcode); } static void gpart_print_error(const char *errstr) { char *errmsg; int error; error = strtol(errstr, &errmsg, 0); if (errmsg != errstr) { while (errmsg[0] == ' ') errmsg++; if (errmsg[0] != '\0') warnc(error, "%s", errmsg); else warnc(error, NULL); } else warnx("%s", errmsg); } static _Noreturn void gpart_issue(struct gctl_req *req, unsigned int fl __unused) { char buf[4096]; const char *errstr; int error, status; if (gctl_get_int(req, "nargs") != 1) errx(EXIT_FAILURE, "Invalid number of arguments."); (void)gctl_delete_param(req, "nargs"); /* autofill parameters (if applicable). */ error = gpart_autofill(req); if (error) { warnc(error, "autofill"); status = EXIT_FAILURE; goto done; } - bzero(buf, sizeof(buf)); - gctl_rw_param(req, "output", sizeof(buf), buf); + buf[0] = '\0'; + gctl_add_param(req, "output", sizeof(buf), buf, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(req); if (errstr == NULL || errstr[0] == '\0') { if (buf[0] != '\0') printf("%s", buf); status = EXIT_SUCCESS; goto done; } gpart_print_error(errstr); status = EXIT_FAILURE; done: gctl_free(req); exit(status); } diff --git a/lib/libgeom/geom_ctl.c b/lib/libgeom/geom_ctl.c index 1d5c52fc3779..b60c4c297257 100644 --- a/lib/libgeom/geom_ctl.c +++ b/lib/libgeom/geom_ctl.c @@ -1,239 +1,239 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 2003 Poul-Henning Kamp * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the authors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #define GCTL_TABLE 1 #include /* * Global pointer to a string that is used to avoid an errorneous free in * gctl_free. */ static char nomemmsg[] = "Could not allocate memory"; void gctl_dump(struct gctl_req *req, FILE *f) { unsigned int i; int j; struct gctl_req_arg *ap; if (req == NULL) { fprintf(f, "Dump of gctl request at NULL\n"); return; } fprintf(f, "Dump of gctl request at %p:\n", req); if (req->error != NULL) fprintf(f, " error:\t\"%s\"\n", req->error); else fprintf(f, " error:\tNULL\n"); for (i = 0; i < req->narg; i++) { ap = &req->arg[i]; fprintf(f, " param:\t\"%s\" (%d)", ap->name, ap->nlen); fprintf(f, " [%s%s", ap->flag & GCTL_PARAM_RD ? "R" : "", ap->flag & GCTL_PARAM_WR ? "W" : ""); fflush(f); if (ap->flag & GCTL_PARAM_ASCII) fprintf(f, "%d] = \"%s\"", ap->len, (char *)ap->value); else if (ap->len > 0) { fprintf(f, "%d] = ", ap->len); fflush(f); for (j = 0; j < ap->len; j++) { fprintf(f, " %02x", ((u_char *)ap->value)[j]); } } else { fprintf(f, "0] = %p", ap->value); } fprintf(f, "\n"); } } /* * Set an error message, if one does not already exist. */ static void gctl_set_error(struct gctl_req *req, const char *error, ...) { va_list ap; if (req->error != NULL) return; va_start(ap, error); vasprintf(&req->error, error, ap); va_end(ap); } /* * Check that a malloc operation succeeded, and set a consistent error * message if not. */ static void gctl_check_alloc(struct gctl_req *req, void *ptr) { if (ptr != NULL) return; gctl_set_error(req, nomemmsg); if (req->error == NULL) req->error = nomemmsg; } /* * Allocate a new request handle of the specified type. * XXX: Why bother checking the type ? */ struct gctl_req * gctl_get_handle(void) { return (calloc(1, sizeof(struct gctl_req))); } /* * Allocate space for another argument. */ static struct gctl_req_arg * gctl_new_arg(struct gctl_req *req) { struct gctl_req_arg *ap; req->narg++; req->arg = reallocf(req->arg, sizeof *ap * req->narg); gctl_check_alloc(req, req->arg); if (req->arg == NULL) { req->narg = 0; return (NULL); } ap = req->arg + (req->narg - 1); memset(ap, 0, sizeof *ap); return (ap); } -static void -gctl_param_add(struct gctl_req *req, const char *name, int len, void *value, +void +gctl_add_param(struct gctl_req *req, const char *name, int len, void *value, int flag) { struct gctl_req_arg *ap; if (req == NULL || req->error != NULL) return; ap = gctl_new_arg(req); if (ap == NULL) return; ap->name = strdup(name); gctl_check_alloc(req, ap->name); if (ap->name == NULL) return; ap->nlen = strlen(ap->name) + 1; ap->value = value; ap->flag = flag; if (len >= 0) ap->len = len; else if (len < 0) { ap->flag |= GCTL_PARAM_ASCII; ap->len = strlen(value) + 1; } } void gctl_ro_param(struct gctl_req *req, const char *name, int len, const void* value) { - gctl_param_add(req, name, len, __DECONST(void *, value), GCTL_PARAM_RD); + gctl_add_param(req, name, len, __DECONST(void *, value), GCTL_PARAM_RD); } void gctl_rw_param(struct gctl_req *req, const char *name, int len, void *value) { - gctl_param_add(req, name, len, value, GCTL_PARAM_RW); + gctl_add_param(req, name, len, value, GCTL_PARAM_RW); } const char * gctl_issue(struct gctl_req *req) { int fd, error; if (req == NULL) return ("NULL request pointer"); if (req->error != NULL) return (req->error); req->version = GCTL_VERSION; req->lerror = BUFSIZ; /* XXX: arbitrary number */ req->error = calloc(1, req->lerror); if (req->error == NULL) { gctl_check_alloc(req, req->error); return (req->error); } req->lerror--; fd = open(_PATH_DEV PATH_GEOM_CTL, O_RDONLY); if (fd < 0) return(strerror(errno)); error = ioctl(fd, GEOM_CTL, req); close(fd); if (req->error[0] != '\0') return (req->error); if (error != 0) return(strerror(errno)); return (NULL); } void gctl_free(struct gctl_req *req) { unsigned int i; if (req == NULL) return; for (i = 0; i < req->narg; i++) { if (req->arg[i].name != NULL) free(req->arg[i].name); } free(req->arg); if (req->error != NULL && req->error != nomemmsg) free(req->error); free(req); } diff --git a/lib/libgeom/libgeom.h b/lib/libgeom/libgeom.h index fc593b234302..9be27208a98c 100644 --- a/lib/libgeom/libgeom.h +++ b/lib/libgeom/libgeom.h @@ -1,172 +1,174 @@ /*- * SPDX-License-Identifier: BSD-3-Clause-FreeBSD * * Copyright (c) 2003 Poul-Henning Kamp * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the authors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #ifndef _LIBGEOM_H_ #define _LIBGEOM_H_ #include #include #include #include __BEGIN_DECLS #ifndef DEBUG_LIBGEOM #define DEBUG_LIBGEOM 0 #endif void geom_stats_close(void); void geom_stats_resync(void); int geom_stats_open(void); void *geom_stats_snapshot_get(void); void geom_stats_snapshot_free(void *); void geom_stats_snapshot_timestamp(void *, struct timespec *); void geom_stats_snapshot_reset(void *); struct devstat *geom_stats_snapshot_next(void *); char *geom_getxml(void); /* geom_xml2tree.c */ /* * These structs are used to build the tree based on the XML. * they're named as the kernel variant without the first '_'. */ struct gclass; struct ggeom; struct gconsumer; struct gprovider; LIST_HEAD(gconf, gconfig); struct gident { void *lg_id; void *lg_ptr; enum { ISCLASS, ISGEOM, ISPROVIDER, ISCONSUMER } lg_what; }; struct gmesh { LIST_HEAD(, gclass) lg_class; struct gident *lg_ident; }; struct gconfig { LIST_ENTRY(gconfig) lg_config; char *lg_name; char *lg_val; }; struct gclass { void *lg_id; char *lg_name; LIST_ENTRY(gclass) lg_class; LIST_HEAD(, ggeom) lg_geom; struct gconf lg_config; }; struct ggeom { void *lg_id; struct gclass *lg_class; char *lg_name; u_int lg_rank; LIST_ENTRY(ggeom) lg_geom; LIST_HEAD(, gconsumer) lg_consumer; LIST_HEAD(, gprovider) lg_provider; struct gconf lg_config; }; struct gconsumer { void *lg_id; struct ggeom *lg_geom; LIST_ENTRY(gconsumer) lg_consumer; struct gprovider *lg_provider; LIST_ENTRY(gconsumer) lg_consumers; char *lg_mode; struct gconf lg_config; }; struct gprovider { void *lg_id; char *lg_name; struct ggeom *lg_geom; LIST_ENTRY(gprovider) lg_provider; LIST_HEAD(, gconsumer) lg_consumers; char *lg_mode; off_t lg_mediasize; u_int lg_sectorsize; off_t lg_stripeoffset; off_t lg_stripesize; struct gconf lg_config; }; struct gident * geom_lookupid(struct gmesh *, const void *); int geom_xml2tree(struct gmesh *, char *); int geom_gettree(struct gmesh *); void geom_deletetree(struct gmesh *); /* geom_ctl.c */ struct gctl_req; #ifdef _STDIO_H_ /* limit #include pollution */ void gctl_dump(struct gctl_req *, FILE *); #endif void gctl_free(struct gctl_req *); struct gctl_req *gctl_get_handle(void); const char *gctl_issue(struct gctl_req *); +void gctl_add_param(struct gctl_req *req, const char *name, int len, + void *value, int flag); void gctl_ro_param(struct gctl_req *, const char *, int, const void *); void gctl_rw_param(struct gctl_req *, const char *, int, void *); /* geom_util.c */ int g_open(const char *, int); int g_close(int); off_t g_mediasize(int); ssize_t g_sectorsize(int); off_t g_stripeoffset(int); off_t g_stripesize(int); int g_flush(int); int g_delete(int, off_t, off_t); int g_get_ident(int, char *, size_t); int g_get_name(const char *, char *, size_t); int g_open_by_ident(const char *, int, char *, size_t); char *g_device_path(const char *); char *g_providername(int); __END_DECLS #endif /* _LIBGEOM_H_ */ diff --git a/sbin/ccdconfig/ccdconfig.c b/sbin/ccdconfig/ccdconfig.c index 6d22b14deed8..1429426e8638 100644 --- a/sbin/ccdconfig/ccdconfig.c +++ b/sbin/ccdconfig/ccdconfig.c @@ -1,452 +1,456 @@ /*- * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2003 Poul-Henning Kamp * Copyright (c) 1996 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * NetBSD: ccdconfig.c,v 1.6 1996/05/16 07:11:18 thorpej Exp $ */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #define CCDF_UNIFORM 0x02 /* use LCCD of sizes for uniform interleave */ #define CCDF_MIRROR 0x04 /* use mirroring */ #define CCDF_NO_OFFSET 0x08 /* do not leave space in front */ #define CCDF_LINUX 0x10 /* use Linux compatibility mode */ #include "pathnames.h" static int lineno = 0; static int verbose = 0; static const char *ccdconf = _PATH_CCDCONF; static struct flagval { const char *fv_flag; int fv_val; } flagvaltab[] = { { "CCDF_UNIFORM", CCDF_UNIFORM }, { "uniform", CCDF_UNIFORM }, { "CCDF_MIRROR", CCDF_MIRROR }, { "mirror", CCDF_MIRROR }, { "CCDF_NO_OFFSET", CCDF_NO_OFFSET }, { "no_offset", CCDF_NO_OFFSET }, { "CCDF_LINUX", CCDF_LINUX }, { "linux", CCDF_LINUX }, { "none", 0 }, { NULL, 0 }, }; #define CCD_CONFIG 0 /* configure a device */ #define CCD_CONFIGALL 1 /* configure all devices */ #define CCD_UNCONFIG 2 /* unconfigure a device */ #define CCD_UNCONFIGALL 3 /* unconfigure all devices */ #define CCD_DUMP 4 /* dump a ccd's configuration */ static int do_single(int, char **, int); static int do_all(int); static int dump_ccd(int, char **); static int flags_to_val(char *); static int resolve_ccdname(char *); static void usage(void); int main(int argc, char *argv[]) { int ch, options = 0, action = CCD_CONFIG; while ((ch = getopt(argc, argv, "cCf:guUv")) != -1) { switch (ch) { case 'c': action = CCD_CONFIG; ++options; break; case 'C': action = CCD_CONFIGALL; ++options; break; case 'f': ccdconf = optarg; break; case 'g': action = CCD_DUMP; break; case 'u': action = CCD_UNCONFIG; ++options; break; case 'U': action = CCD_UNCONFIGALL; ++options; break; case 'v': verbose = 1; break; default: usage(); } } argc -= optind; argv += optind; if (options > 1) usage(); if (modfind("g_ccd") < 0) { /* Not present in kernel, try loading it */ if (kldload("geom_ccd") < 0 || modfind("g_ccd") < 0) warn("geom_ccd module not available!"); } switch (action) { case CCD_CONFIG: case CCD_UNCONFIG: exit(do_single(argc, argv, action)); /* NOTREACHED */ case CCD_CONFIGALL: case CCD_UNCONFIGALL: exit(do_all(action)); /* NOTREACHED */ case CCD_DUMP: exit(dump_ccd(argc, argv)); /* NOTREACHED */ } /* NOTREACHED */ return (0); } static int do_single(int argc, char **argv, int action) { char *cp, *cp2; int ccd, noflags = 0, i, ileave, flags = 0; struct gctl_req *grq; char const *errstr; char buf1[BUFSIZ]; int ex; /* * If unconfiguring, all arguments are treated as ccds. */ if (action == CCD_UNCONFIG || action == CCD_UNCONFIGALL) { ex = 0; for (; argc != 0;) { cp = *argv++; --argc; if ((ccd = resolve_ccdname(cp)) < 0) { warnx("invalid ccd name: %s", cp); continue; } grq = gctl_get_handle(); gctl_ro_param(grq, "verb", -1, "destroy geom"); gctl_ro_param(grq, "class", -1, "CCD"); sprintf(buf1, "ccd%d", ccd); gctl_ro_param(grq, "geom", -1, buf1); errstr = gctl_issue(grq); if (errstr == NULL) { if (verbose) printf("%s unconfigured\n", cp); gctl_free(grq); continue; } warnx( "%s\nor possibly kernel and ccdconfig out of sync", errstr); ex = 1; } return (ex); } /* Make sure there are enough arguments. */ if (argc < 4) { if (argc == 3) { /* Assume that no flags are specified. */ noflags = 1; } else { if (action == CCD_CONFIGALL) { warnx("%s: bad line: %d", ccdconf, lineno); return (1); } else usage(); } } /* First argument is the ccd to configure. */ cp = *argv++; --argc; if ((ccd = resolve_ccdname(cp)) < 0) { warnx("invalid ccd name: %s", cp); return (1); } /* Next argument is the interleave factor. */ cp = *argv++; --argc; errno = 0; /* to check for ERANGE */ ileave = (int)strtol(cp, &cp2, 10); if ((errno == ERANGE) || (ileave < 0) || (*cp2 != '\0')) { warnx("invalid interleave factor: %s", cp); return (1); } if (noflags == 0) { /* Next argument is the ccd configuration flags. */ cp = *argv++; --argc; if ((flags = flags_to_val(cp)) < 0) { warnx("invalid flags argument: %s", cp); return (1); } } grq = gctl_get_handle(); gctl_ro_param(grq, "verb", -1, "create geom"); gctl_ro_param(grq, "class", -1, "CCD"); gctl_ro_param(grq, "unit", sizeof(ccd), &ccd); gctl_ro_param(grq, "ileave", sizeof(ileave), &ileave); if (flags & CCDF_UNIFORM) gctl_ro_param(grq, "uniform", -1, ""); if (flags & CCDF_MIRROR) gctl_ro_param(grq, "mirror", -1, ""); if (flags & CCDF_NO_OFFSET) gctl_ro_param(grq, "no_offset", -1, ""); if (flags & CCDF_LINUX) gctl_ro_param(grq, "linux", -1, ""); gctl_ro_param(grq, "nprovider", sizeof(argc), &argc); for (i = 0; i < argc; i++) { sprintf(buf1, "provider%d", i); cp = argv[i]; if (!strncmp(cp, _PATH_DEV, strlen(_PATH_DEV))) cp += strlen(_PATH_DEV); gctl_ro_param(grq, buf1, -1, cp); } - gctl_rw_param(grq, "output", sizeof(buf1), buf1); + buf1[0] = '\0'; + gctl_add_param(grq, "output", sizeof(buf1), buf1, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(grq); if (errstr == NULL) { if (verbose) { printf("%s", buf1); } gctl_free(grq); return (0); } warnx( "%s\nor possibly kernel and ccdconfig out of sync", errstr); return (1); } static int do_all(int action) { FILE *f; char line[_POSIX2_LINE_MAX]; char *cp, **argv; int argc, rval; gid_t egid; rval = 0; egid = getegid(); if (setegid(getgid()) != 0) err(1, "setegid failed"); if ((f = fopen(ccdconf, "r")) == NULL) { if (setegid(egid) != 0) err(1, "setegid failed"); warn("fopen: %s", ccdconf); return (1); } if (setegid(egid) != 0) err(1, "setegid failed"); while (fgets(line, sizeof(line), f) != NULL) { argc = 0; argv = NULL; ++lineno; if ((cp = strrchr(line, '\n')) != NULL) *cp = '\0'; /* Break up the line and pass it's contents to do_single(). */ if (line[0] == '\0') goto end_of_line; for (cp = line; (cp = strtok(cp, " \t")) != NULL; cp = NULL) { if (*cp == '#') break; if ((argv = realloc(argv, sizeof(char *) * ++argc)) == NULL) { warnx("no memory to configure ccds"); return (1); } argv[argc - 1] = cp; /* * If our action is to unconfigure all, then pass * just the first token to do_single() and ignore * the rest. Since this will be encountered on * our first pass through the line, the Right * Thing will happen. */ if (action == CCD_UNCONFIGALL) { if (do_single(argc, argv, action)) rval = 1; goto end_of_line; } } if (argc != 0) if (do_single(argc, argv, action)) rval = 1; end_of_line: if (argv != NULL) free(argv); } (void)fclose(f); return (rval); } static int resolve_ccdname(char *name) { if (!strncmp(name, _PATH_DEV, strlen(_PATH_DEV))) name += strlen(_PATH_DEV); if (strncmp(name, "ccd", 3)) return -1; name += 3; if (!isdigit(*name)) return -1; return (strtoul(name, NULL, 10)); } static int dumpout(int unit) { static int v; struct gctl_req *grq; int ncp; char *cp; char const *errstr; grq = gctl_get_handle(); ncp = 65536; cp = malloc(ncp); + cp[0] = '\0'; gctl_ro_param(grq, "verb", -1, "list"); gctl_ro_param(grq, "class", -1, "CCD"); gctl_ro_param(grq, "unit", sizeof(unit), &unit); - gctl_rw_param(grq, "output", ncp, cp); + gctl_add_param(grq, "output", ncp, cp, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(grq); if (errstr != NULL) errx(1, "%s\nor possibly kernel and ccdconfig out of sync", errstr); if (strlen(cp) == 0) errx(1, "ccd%d not configured", unit); if (verbose && !v) { printf("# ccd\t\tileave\tflags\tcomponent devices\n"); v = 1; } printf("%s", cp); free(cp); return (0); } static int dump_ccd(int argc, char **argv) { int i, error; if (argc == 0) { error = dumpout(-1); } else { error = 0; for (i = 0; error == 0 && i < argc; i++) error = dumpout(resolve_ccdname(argv[i])); } return (error); } static int flags_to_val(char *flags) { char *cp, *tok; int i, tmp, val; errno = 0; /* to check for ERANGE */ val = (int)strtol(flags, &cp, 0); if ((errno != ERANGE) && (*cp == '\0')) { if (val & ~(CCDF_UNIFORM|CCDF_MIRROR)) return (-1); return (val); } /* Check for values represented by strings. */ if ((cp = strdup(flags)) == NULL) err(1, "no memory to parse flags"); tmp = 0; for (tok = cp; (tok = strtok(tok, ",")) != NULL; tok = NULL) { for (i = 0; flagvaltab[i].fv_flag != NULL; ++i) if (strcmp(tok, flagvaltab[i].fv_flag) == 0) break; if (flagvaltab[i].fv_flag == NULL) { free(cp); return (-1); } tmp |= flagvaltab[i].fv_val; } /* If we get here, the string was ok. */ free(cp); return (tmp); } static void usage(void) { fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n", "usage: ccdconfig [-cv] ccd ileave [flags] dev ...", " ccdconfig -C [-v] [-f config_file]", " ccdconfig -u [-v] ccd ...", " ccdconfig -U [-v] [-f config_file]", " ccdconfig -g [ccd ...]"); exit(1); } diff --git a/sbin/geom/core/geom.c b/sbin/geom/core/geom.c index 0202be9a063e..9d93e9b9989f 100644 --- a/sbin/geom/core/geom.c +++ b/sbin/geom/core/geom.c @@ -1,1401 +1,1402 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2004-2009 Pawel Jakub Dawidek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "misc/subr.h" #ifdef STATIC_GEOM_CLASSES extern uint32_t gpart_version; extern struct g_command gpart_class_commands[]; extern uint32_t glabel_version; extern struct g_command glabel_class_commands[]; #endif static char comm[MAXPATHLEN], *class_name = NULL, *gclass_name = NULL; static uint32_t *version = NULL; static int verbose = 0; static struct g_command *class_commands = NULL; #define GEOM_CLASS_CMDS 0x01 #define GEOM_STD_CMDS 0x02 #define GEOM_CLASS_WIDTH 10 static struct g_command *find_command(const char *cmdstr, int flags); static void list_one_geom_by_provider(const char *provider_name); static int std_available(const char *name); static void std_help(struct gctl_req *req, unsigned flags); static void std_list(struct gctl_req *req, unsigned flags); static void std_status(struct gctl_req *req, unsigned flags); static void std_load(struct gctl_req *req, unsigned flags); static void std_unload(struct gctl_req *req, unsigned flags); static struct g_command std_commands[] = { { "help", 0, std_help, G_NULL_OPTS, NULL }, { "list", 0, std_list, { { 'a', "all", NULL, G_TYPE_BOOL }, G_OPT_SENTINEL }, "[-a] [name ...]" }, { "status", 0, std_status, { { 'a', "all", NULL, G_TYPE_BOOL }, { 'g', "geoms", NULL, G_TYPE_BOOL }, { 's', "script", NULL, G_TYPE_BOOL }, G_OPT_SENTINEL }, "[-ags] [name ...]" }, { "load", G_FLAG_VERBOSE | G_FLAG_LOADKLD, std_load, G_NULL_OPTS, NULL }, { "unload", G_FLAG_VERBOSE, std_unload, G_NULL_OPTS, NULL }, G_CMD_SENTINEL }; static void usage_command(struct g_command *cmd, const char *prefix) { struct g_option *opt; unsigned i; if (cmd->gc_usage != NULL) { char *pos, *ptr, *sptr; sptr = ptr = strdup(cmd->gc_usage); while ((pos = strsep(&ptr, "\n")) != NULL) { if (*pos == '\0') continue; fprintf(stderr, "%s %s %s %s\n", prefix, comm, cmd->gc_name, pos); } free(sptr); return; } fprintf(stderr, "%s %s %s", prefix, comm, cmd->gc_name); if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0) fprintf(stderr, " [-v]"); for (i = 0; ; i++) { opt = &cmd->gc_options[i]; if (opt->go_name == NULL) break; if (opt->go_val != NULL || G_OPT_TYPE(opt) == G_TYPE_BOOL) fprintf(stderr, " ["); else fprintf(stderr, " "); fprintf(stderr, "-%c", opt->go_char); if (G_OPT_TYPE(opt) != G_TYPE_BOOL) fprintf(stderr, " %s", opt->go_name); if (opt->go_val != NULL || G_OPT_TYPE(opt) == G_TYPE_BOOL) fprintf(stderr, "]"); } fprintf(stderr, "\n"); } static void usage(void) { if (class_name == NULL) { fprintf(stderr, "usage: geom [options]\n"); fprintf(stderr, " geom -p \n"); fprintf(stderr, " geom -t\n"); exit(EXIT_FAILURE); } else { struct g_command *cmd; const char *prefix; unsigned i; prefix = "usage:"; if (class_commands != NULL) { for (i = 0; ; i++) { cmd = &class_commands[i]; if (cmd->gc_name == NULL) break; usage_command(cmd, prefix); prefix = " "; } } for (i = 0; ; i++) { cmd = &std_commands[i]; if (cmd->gc_name == NULL) break; /* * If class defines command, which has the same name as * standard command, skip it, because it was already * shown on usage(). */ if (find_command(cmd->gc_name, GEOM_CLASS_CMDS) != NULL) continue; usage_command(cmd, prefix); prefix = " "; } exit(EXIT_FAILURE); } } static void load_module(void) { char name1[64], name2[64]; snprintf(name1, sizeof(name1), "g_%s", class_name); snprintf(name2, sizeof(name2), "geom_%s", class_name); if (modfind(name1) < 0) { /* Not present in kernel, try loading it. */ if (kldload(name2) < 0 || modfind(name1) < 0) { if (errno != EEXIST) { err(EXIT_FAILURE, "cannot load %s", name2); } } } } static int strlcatf(char *str, size_t size, const char *format, ...) { size_t len; va_list ap; int ret; len = strlen(str); str += len; size -= len; va_start(ap, format); ret = vsnprintf(str, size, format, ap); va_end(ap); return (ret); } /* * Find given option in options available for given command. */ static struct g_option * find_option(struct g_command *cmd, char ch) { struct g_option *opt; unsigned i; for (i = 0; ; i++) { opt = &cmd->gc_options[i]; if (opt->go_name == NULL) return (NULL); if (opt->go_char == ch) return (opt); } /* NOTREACHED */ return (NULL); } /* * Add given option to gctl_req. */ static void set_option(struct gctl_req *req, struct g_option *opt, const char *val) { const char *optname; uint64_t number; void *ptr; if (G_OPT_ISMULTI(opt)) { size_t optnamesize; if (G_OPT_NUM(opt) == UCHAR_MAX) errx(EXIT_FAILURE, "Too many -%c options.", opt->go_char); /* * Base option name length plus 3 bytes for option number * (max. 255 options) plus 1 byte for terminating '\0'. */ optnamesize = strlen(opt->go_name) + 3 + 1; ptr = malloc(optnamesize); if (ptr == NULL) errx(EXIT_FAILURE, "No memory."); snprintf(ptr, optnamesize, "%s%u", opt->go_name, G_OPT_NUM(opt)); G_OPT_NUMINC(opt); optname = ptr; } else { optname = opt->go_name; } if (G_OPT_TYPE(opt) == G_TYPE_NUMBER) { if (expand_number(val, &number) == -1) { err(EXIT_FAILURE, "Invalid value for '%c' argument", opt->go_char); } ptr = malloc(sizeof(intmax_t)); if (ptr == NULL) errx(EXIT_FAILURE, "No memory."); *(intmax_t *)ptr = number; opt->go_val = ptr; gctl_ro_param(req, optname, sizeof(intmax_t), opt->go_val); } else if (G_OPT_TYPE(opt) == G_TYPE_STRING) { gctl_ro_param(req, optname, -1, val); } else if (G_OPT_TYPE(opt) == G_TYPE_BOOL) { ptr = malloc(sizeof(int)); if (ptr == NULL) errx(EXIT_FAILURE, "No memory."); *(int *)ptr = *val - '0'; opt->go_val = ptr; gctl_ro_param(req, optname, sizeof(int), opt->go_val); } else { assert(!"Invalid type"); } if (G_OPT_ISMULTI(opt)) free(__DECONST(char *, optname)); } /* * 1. Add given argument by caller. * 2. Add default values of not given arguments. * 3. Add the rest of arguments. */ static void parse_arguments(struct g_command *cmd, struct gctl_req *req, int *argc, char ***argv) { struct g_option *opt; char opts[64]; unsigned i; int ch, vcount; *opts = '\0'; if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0) strlcat(opts, "v", sizeof(opts)); for (i = 0; ; i++) { opt = &cmd->gc_options[i]; if (opt->go_name == NULL) break; assert(G_OPT_TYPE(opt) != 0); assert((opt->go_type & ~(G_TYPE_MASK | G_TYPE_MULTI)) == 0); /* Multiple bool arguments makes no sense. */ assert(G_OPT_TYPE(opt) != G_TYPE_BOOL || (opt->go_type & G_TYPE_MULTI) == 0); strlcatf(opts, sizeof(opts), "%c", opt->go_char); if (G_OPT_TYPE(opt) != G_TYPE_BOOL) strlcat(opts, ":", sizeof(opts)); } /* * Add specified arguments. */ vcount = 0; while ((ch = getopt(*argc, *argv, opts)) != -1) { /* Standard (not passed to kernel) options. */ if (ch == 'v' && (cmd->gc_flags & G_FLAG_VERBOSE) != 0) verbose = 1; /* Options passed to kernel. */ opt = find_option(cmd, ch); if (opt == NULL) { if (ch == 'v' && (cmd->gc_flags & G_FLAG_VERBOSE) != 0){ if (++vcount < 2) continue; else warnx("Option 'v' specified twice."); } usage(); } if (!G_OPT_ISMULTI(opt) && G_OPT_ISDONE(opt)) { warnx("Option '%c' specified twice.", opt->go_char); usage(); } G_OPT_DONE(opt); if (G_OPT_TYPE(opt) == G_TYPE_BOOL) set_option(req, opt, "1"); else set_option(req, opt, optarg); } *argc -= optind; *argv += optind; /* * Add not specified arguments, but with default values. */ for (i = 0; ; i++) { opt = &cmd->gc_options[i]; if (opt->go_name == NULL) break; if (G_OPT_ISDONE(opt)) continue; if (G_OPT_TYPE(opt) == G_TYPE_BOOL) { assert(opt->go_val == NULL); set_option(req, opt, "0"); } else { if (opt->go_val == NULL) { warnx("Option '%c' not specified.", opt->go_char); usage(); } else if (opt->go_val == G_VAL_OPTIONAL) { /* add nothing. */ } else { set_option(req, opt, opt->go_val); } } } /* * Add rest of given arguments. */ gctl_ro_param(req, "nargs", sizeof(int), argc); for (i = 0; i < (unsigned)*argc; i++) { char argname[16]; snprintf(argname, sizeof(argname), "arg%u", i); gctl_ro_param(req, argname, -1, (*argv)[i]); } } /* * Find given command in commands available for given class. */ static struct g_command * find_command(const char *cmdstr, int flags) { struct g_command *cmd; unsigned i; /* * First try to find command defined by loaded library. */ if ((flags & GEOM_CLASS_CMDS) != 0 && class_commands != NULL) { for (i = 0; ; i++) { cmd = &class_commands[i]; if (cmd->gc_name == NULL) break; if (strcmp(cmd->gc_name, cmdstr) == 0) return (cmd); } } /* * Now try to find in standard commands. */ if ((flags & GEOM_STD_CMDS) != 0) { for (i = 0; ; i++) { cmd = &std_commands[i]; if (cmd->gc_name == NULL) break; if (strcmp(cmd->gc_name, cmdstr) == 0) return (cmd); } } return (NULL); } static unsigned set_flags(struct g_command *cmd) { unsigned flags = 0; if ((cmd->gc_flags & G_FLAG_VERBOSE) != 0 && verbose) flags |= G_FLAG_VERBOSE; return (flags); } /* * Run command. */ static void run_command(int argc, char *argv[]) { struct g_command *cmd; struct gctl_req *req; const char *errstr; char buf[4096]; /* First try to find a command defined by a class. */ cmd = find_command(argv[0], GEOM_CLASS_CMDS); if (cmd == NULL) { /* Now, try to find a standard command. */ cmd = find_command(argv[0], GEOM_STD_CMDS); if (cmd == NULL) { warnx("Unknown command: %s.", argv[0]); usage(); } if (!std_available(cmd->gc_name)) { warnx("Command '%s' not available; " "try 'load' first.", argv[0]); exit(EXIT_FAILURE); } } if ((cmd->gc_flags & G_FLAG_LOADKLD) != 0) load_module(); req = gctl_get_handle(); gctl_ro_param(req, "class", -1, gclass_name); gctl_ro_param(req, "verb", -1, argv[0]); if (version != NULL) gctl_ro_param(req, "version", sizeof(*version), version); parse_arguments(cmd, req, &argc, &argv); - bzero(buf, sizeof(buf)); + buf[0] = '\0'; if (cmd->gc_func != NULL) { unsigned flags; flags = set_flags(cmd); cmd->gc_func(req, flags); errstr = req->error; } else { - gctl_rw_param(req, "output", sizeof(buf), buf); + gctl_add_param(req, "output", sizeof(buf), buf, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(req); } if (errstr != NULL && errstr[0] != '\0') { warnx("%s", errstr); if (strncmp(errstr, "warning: ", strlen("warning: ")) != 0) { gctl_free(req); exit(EXIT_FAILURE); } } if (buf[0] != '\0') printf("%s", buf); gctl_free(req); if (verbose) printf("Done.\n"); exit(EXIT_SUCCESS); } #ifndef STATIC_GEOM_CLASSES static const char * library_path(void) { const char *path; path = getenv("GEOM_LIBRARY_PATH"); if (path == NULL) path = GEOM_CLASS_DIR; return (path); } static void load_library(void) { char *curpath, path[MAXPATHLEN], *tofree, *totalpath; uint32_t *lib_version; void *dlh; int ret; ret = 0; tofree = totalpath = strdup(library_path()); if (totalpath == NULL) err(EXIT_FAILURE, "Not enough memory for library path"); if (strchr(totalpath, ':') != NULL) curpath = strsep(&totalpath, ":"); else curpath = totalpath; /* Traverse the paths to find one that contains the library we want. */ while (curpath != NULL) { snprintf(path, sizeof(path), "%s/geom_%s.so", curpath, class_name); ret = access(path, F_OK); if (ret == -1) { if (errno == ENOENT) { /* * If we cannot find library, try the next * path. */ curpath = strsep(&totalpath, ":"); continue; } err(EXIT_FAILURE, "Cannot access library"); } break; } free(tofree); /* No library was found, but standard commands can still be used */ if (ret == -1) return; dlh = dlopen(path, RTLD_NOW); if (dlh == NULL) errx(EXIT_FAILURE, "Cannot open library: %s.", dlerror()); lib_version = dlsym(dlh, "lib_version"); if (lib_version == NULL) { warnx("Cannot find symbol %s: %s.", "lib_version", dlerror()); dlclose(dlh); exit(EXIT_FAILURE); } if (*lib_version != G_LIB_VERSION) { dlclose(dlh); errx(EXIT_FAILURE, "%s and %s are not synchronized.", getprogname(), path); } version = dlsym(dlh, "version"); if (version == NULL) { warnx("Cannot find symbol %s: %s.", "version", dlerror()); dlclose(dlh); exit(EXIT_FAILURE); } class_commands = dlsym(dlh, "class_commands"); if (class_commands == NULL) { warnx("Cannot find symbol %s: %s.", "class_commands", dlerror()); dlclose(dlh); exit(EXIT_FAILURE); } } #endif /* !STATIC_GEOM_CLASSES */ /* * Class name should be all capital letters. */ static void set_class_name(void) { char *s1, *s2; s1 = class_name; for (; *s1 != '\0'; s1++) *s1 = tolower(*s1); gclass_name = malloc(strlen(class_name) + 1); if (gclass_name == NULL) errx(EXIT_FAILURE, "No memory"); s1 = gclass_name; s2 = class_name; for (; *s2 != '\0'; s2++) *s1++ = toupper(*s2); *s1 = '\0'; } static void get_class(int *argc, char ***argv) { snprintf(comm, sizeof(comm), "%s", basename((*argv)[0])); if (strcmp(comm, "geom") == 0) { if (*argc < 2) usage(); else if (*argc == 2) { if (strcmp((*argv)[1], "-h") == 0 || strcmp((*argv)[1], "help") == 0) { usage(); } } strlcatf(comm, sizeof(comm), " %s", (*argv)[1]); class_name = (*argv)[1]; *argc -= 2; *argv += 2; } else if (*comm == 'g') { class_name = comm + 1; *argc -= 1; *argv += 1; } else { errx(EXIT_FAILURE, "Invalid utility name."); } #ifndef STATIC_GEOM_CLASSES load_library(); #else if (!strcasecmp(class_name, "part")) { version = &gpart_version; class_commands = gpart_class_commands; } else if (!strcasecmp(class_name, "label")) { version = &glabel_version; class_commands = glabel_class_commands; } #endif /* !STATIC_GEOM_CLASSES */ set_class_name(); /* If we can't load or list, it's not a class. */ if (!std_available("load") && !std_available("list")) errx(EXIT_FAILURE, "Invalid class name '%s'.", class_name); if (*argc < 1) usage(); } static struct ggeom * find_geom_by_provider(struct gmesh *mesh, const char *name) { struct gclass *classp; struct ggeom *gp; struct gprovider *pp; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { if (strcmp(pp->lg_name, name) == 0) return (gp); } } } return (NULL); } static int compute_tree_width_geom(struct gmesh *mesh, struct ggeom *gp, int indent) { struct gclass *classp2; struct ggeom *gp2; struct gconsumer *cp2; struct gprovider *pp; int max_width, width; max_width = width = indent + strlen(gp->lg_name); LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { LIST_FOREACH(classp2, &mesh->lg_class, lg_class) { LIST_FOREACH(gp2, &classp2->lg_geom, lg_geom) { LIST_FOREACH(cp2, &gp2->lg_consumer, lg_consumer) { if (pp != cp2->lg_provider) continue; width = compute_tree_width_geom(mesh, gp2, indent + 2); if (width > max_width) max_width = width; } } } } return (max_width); } static int compute_tree_width(struct gmesh *mesh) { struct gclass *classp; struct ggeom *gp; int max_width, width; max_width = width = 0; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (!LIST_EMPTY(&gp->lg_consumer)) continue; width = compute_tree_width_geom(mesh, gp, 0); if (width > max_width) max_width = width; } } return (max_width); } static void show_tree_geom(struct gmesh *mesh, struct ggeom *gp, int indent, int width) { struct gclass *classp2; struct ggeom *gp2; struct gconsumer *cp2; struct gprovider *pp; if (LIST_EMPTY(&gp->lg_provider)) { printf("%*s%-*.*s %-*.*s\n", indent, "", width - indent, width - indent, gp->lg_name, GEOM_CLASS_WIDTH, GEOM_CLASS_WIDTH, gp->lg_class->lg_name); return; } LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { printf("%*s%-*.*s %-*.*s %s\n", indent, "", width - indent, width - indent, gp->lg_name, GEOM_CLASS_WIDTH, GEOM_CLASS_WIDTH, gp->lg_class->lg_name, pp->lg_name); LIST_FOREACH(classp2, &mesh->lg_class, lg_class) { LIST_FOREACH(gp2, &classp2->lg_geom, lg_geom) { LIST_FOREACH(cp2, &gp2->lg_consumer, lg_consumer) { if (pp != cp2->lg_provider) continue; show_tree_geom(mesh, gp2, indent + 2, width); } } } } } static void show_tree(void) { struct gmesh mesh; struct gclass *classp; struct ggeom *gp; int error, width; error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); width = compute_tree_width(&mesh); printf("%-*.*s %-*.*s %s\n", width, width, "Geom", GEOM_CLASS_WIDTH, GEOM_CLASS_WIDTH, "Class", "Provider"); LIST_FOREACH(classp, &mesh.lg_class, lg_class) { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (!LIST_EMPTY(&gp->lg_consumer)) continue; show_tree_geom(&mesh, gp, 0, width); } } } int main(int argc, char *argv[]) { char *provider_name; bool tflag; int ch; provider_name = NULL; tflag = false; if (strcmp(getprogname(), "geom") == 0) { while ((ch = getopt(argc, argv, "hp:t")) != -1) { switch (ch) { case 'p': provider_name = strdup(optarg); if (provider_name == NULL) err(1, "strdup"); break; case 't': tflag = true; break; case 'h': default: usage(); } } /* * Don't adjust argc and argv, it would break get_class(). */ } if (tflag && provider_name != NULL) { errx(EXIT_FAILURE, "At most one of -P and -t may be specified."); } if (provider_name != NULL) { list_one_geom_by_provider(provider_name); return (0); } if (tflag) { show_tree(); return (0); } get_class(&argc, &argv); run_command(argc, argv); /* NOTREACHED */ exit(EXIT_FAILURE); } static struct gclass * find_class(struct gmesh *mesh, const char *name) { struct gclass *classp; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { if (strcmp(classp->lg_name, name) == 0) return (classp); } return (NULL); } static struct ggeom * find_geom(struct gclass *classp, const char *name) { struct ggeom *gp; if (strncmp(name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) name += sizeof(_PATH_DEV) - 1; LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (strcmp(gp->lg_name, name) == 0) return (gp); } return (NULL); } static void list_one_provider(struct gprovider *pp, const char *prefix) { struct gconfig *conf; char buf[5]; printf("Name: %s\n", pp->lg_name); humanize_number(buf, sizeof(buf), (int64_t)pp->lg_mediasize, "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL); printf("%sMediasize: %jd (%s)\n", prefix, (intmax_t)pp->lg_mediasize, buf); printf("%sSectorsize: %u\n", prefix, pp->lg_sectorsize); if (pp->lg_stripesize > 0 || pp->lg_stripeoffset > 0) { printf("%sStripesize: %ju\n", prefix, pp->lg_stripesize); printf("%sStripeoffset: %ju\n", prefix, pp->lg_stripeoffset); } printf("%sMode: %s\n", prefix, pp->lg_mode); LIST_FOREACH(conf, &pp->lg_config, lg_config) { printf("%s%s: %s\n", prefix, conf->lg_name, conf->lg_val); } } static void list_one_consumer(struct gconsumer *cp, const char *prefix) { struct gprovider *pp; struct gconfig *conf; pp = cp->lg_provider; if (pp == NULL) printf("[no provider]\n"); else { char buf[5]; printf("Name: %s\n", pp->lg_name); humanize_number(buf, sizeof(buf), (int64_t)pp->lg_mediasize, "", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL); printf("%sMediasize: %jd (%s)\n", prefix, (intmax_t)pp->lg_mediasize, buf); printf("%sSectorsize: %u\n", prefix, pp->lg_sectorsize); if (pp->lg_stripesize > 0 || pp->lg_stripeoffset > 0) { printf("%sStripesize: %ju\n", prefix, pp->lg_stripesize); printf("%sStripeoffset: %ju\n", prefix, pp->lg_stripeoffset); } printf("%sMode: %s\n", prefix, cp->lg_mode); } LIST_FOREACH(conf, &cp->lg_config, lg_config) { printf("%s%s: %s\n", prefix, conf->lg_name, conf->lg_val); } } static void list_one_geom(struct ggeom *gp) { struct gprovider *pp; struct gconsumer *cp; struct gconfig *conf; unsigned n; printf("Geom name: %s\n", gp->lg_name); LIST_FOREACH(conf, &gp->lg_config, lg_config) { printf("%s: %s\n", conf->lg_name, conf->lg_val); } if (!LIST_EMPTY(&gp->lg_provider)) { printf("Providers:\n"); n = 1; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { printf("%u. ", n++); list_one_provider(pp, " "); } } if (!LIST_EMPTY(&gp->lg_consumer)) { printf("Consumers:\n"); n = 1; LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) { printf("%u. ", n++); list_one_consumer(cp, " "); } } printf("\n"); } static void list_one_geom_by_provider(const char *provider_name) { struct gmesh mesh; struct ggeom *gp; int error; error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); gp = find_geom_by_provider(&mesh, provider_name); if (gp == NULL) errx(EXIT_FAILURE, "Cannot find provider '%s'.", provider_name); printf("Geom class: %s\n", gp->lg_class->lg_name); list_one_geom(gp); } static void std_help(struct gctl_req *req __unused, unsigned flags __unused) { usage(); } static int std_list_available(void) { struct gmesh mesh; struct gclass *classp; int error; error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, gclass_name); geom_deletetree(&mesh); if (classp != NULL) return (1); return (0); } static void std_list(struct gctl_req *req, unsigned flags __unused) { struct gmesh mesh; struct gclass *classp; struct ggeom *gp; const char *name; int all, error, i, nargs; error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, gclass_name); if (classp == NULL) { geom_deletetree(&mesh); errx(EXIT_FAILURE, "Class '%s' not found.", gclass_name); } nargs = gctl_get_int(req, "nargs"); all = gctl_get_int(req, "all"); if (nargs > 0) { for (i = 0; i < nargs; i++) { name = gctl_get_ascii(req, "arg%d", i); gp = find_geom(classp, name); if (gp == NULL) { errx(EXIT_FAILURE, "Class '%s' does not have " "an instance named '%s'.", gclass_name, name); } list_one_geom(gp); } } else { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (LIST_EMPTY(&gp->lg_provider) && !all) continue; list_one_geom(gp); } } geom_deletetree(&mesh); } static int std_status_available(void) { /* 'status' command is available when 'list' command is. */ return (std_list_available()); } static void status_update_len(struct ggeom *gp, int *name_len, int *status_len) { struct gconfig *conf; int len; assert(gp != NULL); assert(name_len != NULL); assert(status_len != NULL); len = strlen(gp->lg_name); if (*name_len < len) *name_len = len; LIST_FOREACH(conf, &gp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { len = strlen(conf->lg_val); if (*status_len < len) *status_len = len; } } } static void status_update_len_prs(struct ggeom *gp, int *name_len, int *status_len) { struct gprovider *pp; struct gconfig *conf; int len, glen; assert(gp != NULL); assert(name_len != NULL); assert(status_len != NULL); glen = 0; LIST_FOREACH(conf, &gp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { glen = strlen(conf->lg_val); break; } } LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { len = strlen(pp->lg_name); if (*name_len < len) *name_len = len; len = glen; LIST_FOREACH(conf, &pp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { len = strlen(conf->lg_val); break; } } if (*status_len < len) *status_len = len; } } static char * status_one_consumer(struct gconsumer *cp) { static char buf[256]; struct gprovider *pp; struct gconfig *conf; const char *state, *syncr; pp = cp->lg_provider; if (pp == NULL) return (NULL); state = NULL; syncr = NULL; LIST_FOREACH(conf, &cp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) state = conf->lg_val; if (strcasecmp(conf->lg_name, "synchronized") == 0) syncr = conf->lg_val; } if (state == NULL && syncr == NULL) snprintf(buf, sizeof(buf), "%s", pp->lg_name); else if (state != NULL && syncr != NULL) { snprintf(buf, sizeof(buf), "%s (%s, %s)", pp->lg_name, state, syncr); } else { snprintf(buf, sizeof(buf), "%s (%s)", pp->lg_name, state ? state : syncr); } return (buf); } static void status_one_geom(struct ggeom *gp, int script, int name_len, int status_len) { struct gconsumer *cp; struct gconfig *conf; const char *name, *status, *component; int gotone; name = gp->lg_name; status = "N/A"; LIST_FOREACH(conf, &gp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { status = conf->lg_val; break; } } gotone = 0; LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) { component = status_one_consumer(cp); if (component == NULL) continue; gotone = 1; printf("%*s %*s %s\n", name_len, name, status_len, status, component); if (!script) name = status = ""; } if (!gotone) { printf("%*s %*s %s\n", name_len, name, status_len, status, "N/A"); } } static void status_one_geom_prs(struct ggeom *gp, int script, int name_len, int status_len) { struct gprovider *pp; struct gconsumer *cp; struct gconfig *conf; const char *name, *status, *component; int gotone; LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { name = pp->lg_name; status = "N/A"; LIST_FOREACH(conf, &gp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { status = conf->lg_val; break; } } LIST_FOREACH(conf, &pp->lg_config, lg_config) { if (strcasecmp(conf->lg_name, "state") == 0) { status = conf->lg_val; break; } } gotone = 0; LIST_FOREACH(cp, &gp->lg_consumer, lg_consumer) { component = status_one_consumer(cp); if (component == NULL) continue; gotone = 1; printf("%*s %*s %s\n", name_len, name, status_len, status, component); if (!script) name = status = ""; } if (!gotone) { printf("%*s %*s %s\n", name_len, name, status_len, status, "N/A"); } } } static void std_status(struct gctl_req *req, unsigned flags __unused) { struct gmesh mesh; struct gclass *classp; struct ggeom *gp; const char *name; int name_len, status_len; int all, error, geoms, i, n, nargs, script; error = geom_gettree(&mesh); if (error != 0) errc(EXIT_FAILURE, error, "Cannot get GEOM tree"); classp = find_class(&mesh, gclass_name); if (classp == NULL) errx(EXIT_FAILURE, "Class %s not found.", gclass_name); nargs = gctl_get_int(req, "nargs"); all = gctl_get_int(req, "all"); geoms = gctl_get_int(req, "geoms"); script = gctl_get_int(req, "script"); if (script) { name_len = 0; status_len = 0; } else { name_len = strlen("Name"); status_len = strlen("Status"); } if (nargs > 0) { for (i = 0, n = 0; i < nargs; i++) { name = gctl_get_ascii(req, "arg%d", i); gp = find_geom(classp, name); if (gp == NULL) errx(EXIT_FAILURE, "No such geom: %s.", name); if (geoms) { status_update_len(gp, &name_len, &status_len); } else { status_update_len_prs(gp, &name_len, &status_len); } n++; } if (n == 0) goto end; } else { n = 0; LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (LIST_EMPTY(&gp->lg_provider) && !all) continue; if (geoms) { status_update_len(gp, &name_len, &status_len); } else { status_update_len_prs(gp, &name_len, &status_len); } n++; } if (n == 0) goto end; } if (!script) { printf("%*s %*s %s\n", name_len, "Name", status_len, "Status", "Components"); } if (nargs > 0) { for (i = 0; i < nargs; i++) { name = gctl_get_ascii(req, "arg%d", i); gp = find_geom(classp, name); if (gp == NULL) continue; if (geoms) { status_one_geom(gp, script, name_len, status_len); } else { status_one_geom_prs(gp, script, name_len, status_len); } } } else { LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { if (LIST_EMPTY(&gp->lg_provider) && !all) continue; if (geoms) { status_one_geom(gp, script, name_len, status_len); } else { status_one_geom_prs(gp, script, name_len, status_len); } } } end: geom_deletetree(&mesh); } static int std_load_available(void) { char name[MAXPATHLEN], paths[MAXPATHLEN * 8], *p; struct stat sb; size_t len; snprintf(name, sizeof(name), "g_%s", class_name); /* * If already in kernel, "load" command is not available. */ if (modfind(name) >= 0) return (0); bzero(paths, sizeof(paths)); len = sizeof(paths); if (sysctlbyname("kern.module_path", paths, &len, NULL, 0) < 0) err(EXIT_FAILURE, "sysctl(kern.module_path)"); for (p = strtok(paths, ";"); p != NULL; p = strtok(NULL, ";")) { snprintf(name, sizeof(name), "%s/geom_%s.ko", p, class_name); /* * If geom_.ko file exists, "load" command is available. */ if (stat(name, &sb) == 0) return (1); } return (0); } static void std_load(struct gctl_req *req __unused, unsigned flags) { /* * Do nothing special here, because of G_FLAG_LOADKLD flag, * module is already loaded. */ if ((flags & G_FLAG_VERBOSE) != 0) printf("Module available.\n"); } static int std_unload_available(void) { char name[64]; int id; snprintf(name, sizeof(name), "geom_%s", class_name); id = kldfind(name); if (id >= 0) return (1); return (0); } static void std_unload(struct gctl_req *req, unsigned flags __unused) { char name[64]; int id; snprintf(name, sizeof(name), "geom_%s", class_name); id = kldfind(name); if (id < 0) { gctl_error(req, "Could not find module: %s.", strerror(errno)); return; } if (kldunload(id) < 0) { gctl_error(req, "Could not unload module: %s.", strerror(errno)); return; } } static int std_available(const char *name) { if (strcmp(name, "help") == 0) return (1); else if (strcmp(name, "list") == 0) return (std_list_available()); else if (strcmp(name, "status") == 0) return (std_status_available()); else if (strcmp(name, "load") == 0) return (std_load_available()); else if (strcmp(name, "unload") == 0) return (std_unload_available()); else assert(!"Unknown standard command."); return (0); } diff --git a/sbin/gvinum/gvinum.c b/sbin/gvinum/gvinum.c index 50947a30a725..5a081e92a8df 100644 --- a/sbin/gvinum/gvinum.c +++ b/sbin/gvinum/gvinum.c @@ -1,1445 +1,1452 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2004 Lukas Ertl * Copyright (c) 2005 Chris Jones * Copyright (c) 2007 Ulf Lilleengen * All rights reserved. * * Portions of this software were developed for the FreeBSD Project * by Chris Jones thanks to the support of Google's Summer of Code * program and mentoring by Lukas Ertl. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gvinum.h" static void gvinum_attach(int, char * const *); static void gvinum_concat(int, char * const *); static void gvinum_create(int, char * const *); static void gvinum_detach(int, char * const *); static void gvinum_grow(int, char * const *); static void gvinum_help(void); static void gvinum_list(int, char * const *); static void gvinum_move(int, char * const *); static void gvinum_mirror(int, char * const *); static void gvinum_parityop(int, char * const * , int); static void gvinum_printconfig(int, char * const *); static void gvinum_raid5(int, char * const *); static void gvinum_rename(int, char * const *); static void gvinum_resetconfig(int, char * const *); static void gvinum_rm(int, char * const *); static void gvinum_saveconfig(void); static void gvinum_setstate(int, char * const *); static void gvinum_start(int, char * const *); static void gvinum_stop(int, char * const *); static void gvinum_stripe(int, char * const *); static void parseline(int, char * const *); static void printconfig(FILE *, const char *); static char *create_drive(const char *); static void create_volume(int, char * const * , const char *); static char *find_name(const char *, int, int); static const char *find_pattern(char *, const char *); static void copy_device(struct gv_drive *, const char *); #define find_drive() \ find_name("gvinumdrive", GV_TYPE_DRIVE, GV_MAXDRIVENAME) int main(int argc, char **argv) { int tokens; char buffer[BUFSIZ], *inputline, *token[GV_MAXARGS]; /* Load the module if necessary. */ if (modfind(GVINUMMOD) < 0) { if (kldload(GVINUMKLD) < 0 && modfind(GVINUMMOD) < 0) err(1, GVINUMKLD ": Kernel module not available"); } /* Arguments given on the command line. */ if (argc > 1) { argc--; argv++; parseline(argc, argv); /* Interactive mode. */ } else { for (;;) { inputline = readline("gvinum -> "); if (inputline == NULL) { if (ferror(stdin)) { err(1, "can't read input"); } else { printf("\n"); exit(0); } } else if (*inputline) { add_history(inputline); strcpy(buffer, inputline); free(inputline); tokens = gv_tokenize(buffer, token, GV_MAXARGS); if (tokens) parseline(tokens, token); } } } exit(0); } /* Attach a plex to a volume or a subdisk to a plex. */ static void gvinum_attach(int argc, char * const *argv) { struct gctl_req *req; const char *errstr; int rename; off_t offset; rename = 0; offset = -1; if (argc < 3) { warnx("usage:\tattach [rename] " "[]\n" "\tattach [rename]"); return; } if (argc > 3) { if (!strcmp(argv[3], "rename")) { rename = 1; if (argc == 5) offset = strtol(argv[4], NULL, 0); } else offset = strtol(argv[3], NULL, 0); } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "attach"); gctl_ro_param(req, "child", -1, argv[1]); gctl_ro_param(req, "parent", -1, argv[2]); gctl_ro_param(req, "offset", sizeof(off_t), &offset); gctl_ro_param(req, "rename", sizeof(int), &rename); errstr = gctl_issue(req); if (errstr != NULL) warnx("attach failed: %s", errstr); gctl_free(req); } static void gvinum_create(int argc, char * const *argv) { struct gctl_req *req; struct gv_drive *d; struct gv_plex *p; struct gv_sd *s; struct gv_volume *v; FILE *tmp; int drives, errors, fd, flags, i, line, plexes, plex_in_volume; int sd_in_plex, status, subdisks, tokens, undeffd, volumes; const char *errstr; char buf[BUFSIZ], buf1[BUFSIZ], commandline[BUFSIZ], *sdname; const char *ed; char original[BUFSIZ], tmpfile[20], *token[GV_MAXARGS]; char plex[GV_MAXPLEXNAME], volume[GV_MAXVOLNAME]; tmp = NULL; flags = 0; for (i = 1; i < argc; i++) { /* Force flag used to ignore already created drives. */ if (!strcmp(argv[i], "-f")) { flags |= GV_FLAG_F; /* Else it must be a file. */ } else { if ((tmp = fopen(argv[i], "r")) == NULL) { warn("can't open '%s' for reading", argv[i]); return; } } } /* We didn't get a file. */ if (tmp == NULL) { snprintf(tmpfile, sizeof(tmpfile), "/tmp/gvinum.XXXXXX"); if ((fd = mkstemp(tmpfile)) == -1) { warn("temporary file not accessible"); return; } if ((tmp = fdopen(fd, "w")) == NULL) { warn("can't open '%s' for writing", tmpfile); return; } printconfig(tmp, "# "); fclose(tmp); ed = getenv("EDITOR"); if (ed == NULL) ed = _PATH_VI; snprintf(commandline, sizeof(commandline), "%s %s", ed, tmpfile); status = system(commandline); if (status != 0) { warn("couldn't exec %s; status: %d", ed, status); return; } if ((tmp = fopen(tmpfile, "r")) == NULL) { warn("can't open '%s' for reading", tmpfile); return; } } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "create"); gctl_ro_param(req, "flags", sizeof(int), &flags); drives = volumes = plexes = subdisks = 0; plex_in_volume = sd_in_plex = undeffd = 0; plex[0] = '\0'; errors = 0; line = 1; while ((fgets(buf, BUFSIZ, tmp)) != NULL) { /* Skip empty lines and comments. */ if (*buf == '\0' || *buf == '#') { line++; continue; } /* Kill off the newline. */ buf[strlen(buf) - 1] = '\0'; /* * Copy the original input line in case we need it for error * output. */ strlcpy(original, buf, sizeof(original)); tokens = gv_tokenize(buf, token, GV_MAXARGS); if (tokens <= 0) { line++; continue; } /* Volume definition. */ if (!strcmp(token[0], "volume")) { v = gv_new_volume(tokens, token); if (v == NULL) { warnx("line %d: invalid volume definition", line); warnx("line %d: '%s'", line, original); errors++; line++; continue; } /* Reset plex count for this volume. */ plex_in_volume = 0; /* * Set default volume name for following plex * definitions. */ strlcpy(volume, v->name, sizeof(volume)); snprintf(buf1, sizeof(buf1), "volume%d", volumes); gctl_ro_param(req, buf1, sizeof(*v), v); volumes++; /* Plex definition. */ } else if (!strcmp(token[0], "plex")) { p = gv_new_plex(tokens, token); if (p == NULL) { warnx("line %d: invalid plex definition", line); warnx("line %d: '%s'", line, original); errors++; line++; continue; } /* Reset subdisk count for this plex. */ sd_in_plex = 0; /* Default name. */ if (strlen(p->name) == 0) { snprintf(p->name, sizeof(p->name), "%s.p%d", volume, plex_in_volume++); } /* Default volume. */ if (strlen(p->volume) == 0) { snprintf(p->volume, sizeof(p->volume), "%s", volume); } /* * Set default plex name for following subdisk * definitions. */ strlcpy(plex, p->name, sizeof(plex)); snprintf(buf1, sizeof(buf1), "plex%d", plexes); gctl_ro_param(req, buf1, sizeof(*p), p); plexes++; /* Subdisk definition. */ } else if (!strcmp(token[0], "sd")) { s = gv_new_sd(tokens, token); if (s == NULL) { warnx("line %d: invalid subdisk " "definition:", line); warnx("line %d: '%s'", line, original); errors++; line++; continue; } /* Default name. */ if (strlen(s->name) == 0) { if (strlen(plex) == 0) { sdname = find_name("gvinumsubdisk.p", GV_TYPE_SD, GV_MAXSDNAME); snprintf(s->name, sizeof(s->name), "%s.s%d", sdname, undeffd++); free(sdname); } else { snprintf(s->name, sizeof(s->name), "%s.s%d",plex, sd_in_plex++); } } /* Default plex. */ if (strlen(s->plex) == 0) snprintf(s->plex, sizeof(s->plex), "%s", plex); snprintf(buf1, sizeof(buf1), "sd%d", subdisks); gctl_ro_param(req, buf1, sizeof(*s), s); subdisks++; /* Subdisk definition. */ } else if (!strcmp(token[0], "drive")) { d = gv_new_drive(tokens, token); if (d == NULL) { warnx("line %d: invalid drive definition:", line); warnx("line %d: '%s'", line, original); errors++; line++; continue; } snprintf(buf1, sizeof(buf1), "drive%d", drives); gctl_ro_param(req, buf1, sizeof(*d), d); drives++; /* Everything else is bogus. */ } else { warnx("line %d: invalid definition:", line); warnx("line %d: '%s'", line, original); errors++; } line++; } fclose(tmp); unlink(tmpfile); if (!errors && (volumes || plexes || subdisks || drives)) { gctl_ro_param(req, "volumes", sizeof(int), &volumes); gctl_ro_param(req, "plexes", sizeof(int), &plexes); gctl_ro_param(req, "subdisks", sizeof(int), &subdisks); gctl_ro_param(req, "drives", sizeof(int), &drives); errstr = gctl_issue(req); if (errstr != NULL) warnx("create failed: %s", errstr); } gctl_free(req); } /* Create a concatenated volume. */ static void gvinum_concat(int argc, char * const *argv) { if (argc < 2) { warnx("usage:\tconcat [-fv] [-n name] drives\n"); return; } create_volume(argc, argv, "concat"); } /* Create a drive quick and dirty. */ static char * create_drive(const char *device) { struct gv_drive *d; struct gctl_req *req; const char *errstr; char *drivename, *dname; int drives, i, flags, volumes, subdisks, plexes; int found = 0; flags = plexes = subdisks = volumes = 0; drives = 1; dname = NULL; drivename = find_drive(); if (drivename == NULL) return (NULL); req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "create"); d = gv_alloc_drive(); if (d == NULL) err(1, "unable to allocate for gv_drive object"); strlcpy(d->name, drivename, sizeof(d->name)); copy_device(d, device); gctl_ro_param(req, "drive0", sizeof(*d), d); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "drives", sizeof(int), &drives); gctl_ro_param(req, "volumes", sizeof(int), &volumes); gctl_ro_param(req, "plexes", sizeof(int), &plexes); gctl_ro_param(req, "subdisks", sizeof(int), &subdisks); errstr = gctl_issue(req); if (errstr != NULL) { warnx("error creating drive: %s", errstr); drivename = NULL; } else { /* XXX: This is needed because we have to make sure the drives * are created before we return. */ /* Loop until it's in the config. */ for (i = 0; i < 100000; i++) { dname = find_name("gvinumdrive", GV_TYPE_DRIVE, GV_MAXDRIVENAME); /* If we got a different name, quit. */ if (dname == NULL) continue; if (strcmp(dname, drivename)) found = 1; free(dname); dname = NULL; if (found) break; usleep(100000); /* Sleep for 0.1s */ } if (found == 0) { warnx("error creating drive"); drivename = NULL; } } gctl_free(req); return (drivename); } /* * General routine for creating a volume. Mainly for use by concat, mirror, * raid5 and stripe commands. */ static void create_volume(int argc, char * const *argv, const char *verb) { struct gctl_req *req; const char *errstr; char buf[BUFSIZ], *drivename, *volname; int drives, flags, i; off_t stripesize; flags = 0; drives = 0; volname = NULL; stripesize = 262144; /* XXX: Should we check for argument length? */ req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-f")) { flags |= GV_FLAG_F; } else if (!strcmp(argv[i], "-n")) { volname = argv[++i]; } else if (!strcmp(argv[i], "-v")) { flags |= GV_FLAG_V; } else if (!strcmp(argv[i], "-s")) { flags |= GV_FLAG_S; if (!strcmp(verb, "raid5")) stripesize = gv_sizespec(argv[++i]); } else { /* Assume it's a drive. */ snprintf(buf, sizeof(buf), "drive%d", drives++); /* First we create the drive. */ drivename = create_drive(argv[i]); if (drivename == NULL) goto bad; /* Then we add it to the request. */ gctl_ro_param(req, buf, -1, drivename); } } gctl_ro_param(req, "stripesize", sizeof(off_t), &stripesize); /* Find a free volume name. */ if (volname == NULL) volname = find_name("gvinumvolume", GV_TYPE_VOL, GV_MAXVOLNAME); /* Then we send a request to actually create the volumes. */ gctl_ro_param(req, "verb", -1, verb); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "drives", sizeof(int), &drives); gctl_ro_param(req, "name", -1, volname); errstr = gctl_issue(req); if (errstr != NULL) warnx("creating %s volume failed: %s", verb, errstr); bad: gctl_free(req); } /* Parse a line of the config, return the word after . */ static const char * find_pattern(char *line, const char *pattern) { char *ptr; ptr = strsep(&line, " "); while (ptr != NULL) { if (!strcmp(ptr, pattern)) { /* Return the next. */ ptr = strsep(&line, " "); return (ptr); } ptr = strsep(&line, " "); } return (NULL); } /* Find a free name for an object given a prefix. */ static char * find_name(const char *prefix, int type, int namelen) { struct gctl_req *req; char comment[1], buf[GV_CFG_LEN - 1], *sname, *ptr; const char *errstr, *name; int i, n, begin, len, conflict; char line[1024]; comment[0] = '\0'; + buf[0] = '\0'; /* Find a name. Fetch out configuration first. */ req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "getconfig"); gctl_ro_param(req, "comment", -1, comment); - gctl_rw_param(req, "config", sizeof(buf), buf); + gctl_add_param(req, "config", sizeof(buf), buf, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't get configuration: %s", errstr); return (NULL); } gctl_free(req); begin = 0; len = strlen(buf); i = 0; sname = malloc(namelen + 1); /* XXX: Max object setting? */ for (n = 0; n < 10000; n++) { snprintf(sname, namelen, "%s%d", prefix, n); conflict = 0; begin = 0; /* Loop through the configuration line by line. */ for (i = 0; i < len; i++) { if (buf[i] == '\n' || buf[i] == '\0') { ptr = buf + begin; strlcpy(line, ptr, (i - begin) + 1); begin = i + 1; switch (type) { case GV_TYPE_DRIVE: name = find_pattern(line, "drive"); break; case GV_TYPE_VOL: name = find_pattern(line, "volume"); break; case GV_TYPE_PLEX: case GV_TYPE_SD: name = find_pattern(line, "name"); break; default: printf("Invalid type given\n"); continue; } if (name == NULL) continue; if (!strcmp(sname, name)) { conflict = 1; /* XXX: Could quit the loop earlier. */ } } } if (!conflict) return (sname); } free(sname); return (NULL); } static void copy_device(struct gv_drive *d, const char *device) { if (strncmp(device, "/dev/", 5) == 0) strlcpy(d->device, (device + 5), sizeof(d->device)); else strlcpy(d->device, device, sizeof(d->device)); } /* Detach a plex or subdisk from its parent. */ static void gvinum_detach(int argc, char * const *argv) { const char *errstr; struct gctl_req *req; int flags, i; flags = 0; optreset = 1; optind = 1; while ((i = getopt(argc, argv, "f")) != -1) { switch (i) { case 'f': flags |= GV_FLAG_F; break; default: warn("invalid flag: %c", i); return; } } argc -= optind; argv += optind; if (argc != 1) { warnx("usage: detach [-f] | "); return; } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "detach"); gctl_ro_param(req, "object", -1, argv[0]); gctl_ro_param(req, "flags", sizeof(int), &flags); errstr = gctl_issue(req); if (errstr != NULL) warnx("detach failed: %s", errstr); gctl_free(req); } static void gvinum_help(void) { printf("COMMANDS\n" "checkparity [-f] plex\n" " Check the parity blocks of a RAID-5 plex.\n" "create [-f] description-file\n" " Create as per description-file or open editor.\n" "attach plex volume [rename]\n" "attach subdisk plex [offset] [rename]\n" " Attach a plex to a volume, or a subdisk to a plex\n" "concat [-fv] [-n name] drives\n" " Create a concatenated volume from the specified drives.\n" "detach [-f] [plex | subdisk]\n" " Detach a plex or a subdisk from the volume or plex to\n" " which it is attached.\n" "grow plex drive\n" " Grow plex by creating a properly sized subdisk on drive\n" "l | list [-r] [-v] [-V] [volume | plex | subdisk]\n" " List information about specified objects.\n" "ld [-r] [-v] [-V] [volume]\n" " List information about drives.\n" "ls [-r] [-v] [-V] [subdisk]\n" " List information about subdisks.\n" "lp [-r] [-v] [-V] [plex]\n" " List information about plexes.\n" "lv [-r] [-v] [-V] [volume]\n" " List information about volumes.\n" "mirror [-fsv] [-n name] drives\n" " Create a mirrored volume from the specified drives.\n" "move | mv -f drive object ...\n" " Move the object(s) to the specified drive.\n" "quit Exit the vinum program when running in interactive mode." " Nor-\n" " mally this would be done by entering the EOF character.\n" "raid5 [-fv] [-s stripesize] [-n name] drives\n" " Create a RAID-5 volume from the specified drives.\n" "rename [-r] [drive | subdisk | plex | volume] newname\n" " Change the name of the specified object.\n" "rebuildparity plex [-f]\n" " Rebuild the parity blocks of a RAID-5 plex.\n" "resetconfig [-f]\n" " Reset the complete gvinum configuration\n" "rm [-r] [-f] volume | plex | subdisk | drive\n" " Remove an object.\n" "saveconfig\n" " Save vinum configuration to disk after configuration" " failures.\n" "setstate [-f] state [volume | plex | subdisk | drive]\n" " Set state without influencing other objects, for" " diagnostic pur-\n" " poses only.\n" "start [-S size] volume | plex | subdisk\n" " Allow the system to access the objects.\n" "stripe [-fv] [-n name] drives\n" " Create a striped volume from the specified drives.\n" ); } static void gvinum_setstate(int argc, char * const *argv) { struct gctl_req *req; int flags, i; const char *errstr; flags = 0; optreset = 1; optind = 1; while ((i = getopt(argc, argv, "f")) != -1) { switch (i) { case 'f': flags |= GV_FLAG_F; break; case '?': default: warn("invalid flag: %c", i); return; } } argc -= optind; argv += optind; if (argc != 2) { warnx("usage: setstate [-f] "); return; } /* * XXX: This hack is needed to avoid tripping over (now) invalid * 'classic' vinum states and will go away later. */ if (strcmp(argv[0], "up") && strcmp(argv[0], "down") && strcmp(argv[0], "stale")) { warnx("invalid state '%s'", argv[0]); return; } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "setstate"); gctl_ro_param(req, "state", -1, argv[0]); gctl_ro_param(req, "object", -1, argv[1]); gctl_ro_param(req, "flags", sizeof(int), &flags); errstr = gctl_issue(req); if (errstr != NULL) warnx("%s", errstr); gctl_free(req); } static void gvinum_list(int argc, char * const *argv) { struct gctl_req *req; int flags, i, j; const char *errstr; char buf[20], config[GV_CFG_LEN + 1]; const char *cmd; flags = 0; cmd = "list"; if (argc) { optreset = 1; optind = 1; cmd = argv[0]; while ((j = getopt(argc, argv, "rsvV")) != -1) { switch (j) { case 'r': flags |= GV_FLAG_R; break; case 's': flags |= GV_FLAG_S; break; case 'v': flags |= GV_FLAG_V; break; case 'V': flags |= GV_FLAG_V; flags |= GV_FLAG_VV; break; case '?': default: return; } } argc -= optind; argv += optind; } + config[0] = '\0'; + req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "list"); gctl_ro_param(req, "cmd", -1, cmd); gctl_ro_param(req, "argc", sizeof(int), &argc); gctl_ro_param(req, "flags", sizeof(int), &flags); - gctl_rw_param(req, "config", sizeof(config), config); + gctl_add_param(req, "config", sizeof(config), config, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); if (argc) { for (i = 0; i < argc; i++) { snprintf(buf, sizeof(buf), "argv%d", i); gctl_ro_param(req, buf, -1, argv[i]); } } errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't get configuration: %s", errstr); gctl_free(req); return; } printf("%s", config); gctl_free(req); } /* Create a mirrored volume. */ static void gvinum_mirror(int argc, char * const *argv) { if (argc < 2) { warnx("usage\tmirror [-fsv] [-n name] drives\n"); return; } create_volume(argc, argv, "mirror"); } /* Note that move is currently of form '[-r] target object [...]' */ static void gvinum_move(int argc, char * const *argv) { struct gctl_req *req; const char *errstr; char buf[20]; int flags, i, j; flags = 0; if (argc) { optreset = 1; optind = 1; while ((j = getopt(argc, argv, "f")) != -1) { switch (j) { case 'f': flags |= GV_FLAG_F; break; case '?': default: return; } } argc -= optind; argv += optind; } switch (argc) { case 0: warnx("no destination or object(s) to move specified"); return; case 1: warnx("no object(s) to move specified"); return; default: break; } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "move"); gctl_ro_param(req, "argc", sizeof(int), &argc); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "destination", -1, argv[0]); for (i = 1; i < argc; i++) { snprintf(buf, sizeof(buf), "argv%d", i); gctl_ro_param(req, buf, -1, argv[i]); } errstr = gctl_issue(req); if (errstr != NULL) warnx("can't move object(s): %s", errstr); gctl_free(req); } static void gvinum_printconfig(int argc __unused, char * const *argv __unused) { printconfig(stdout, ""); } static void gvinum_parityop(int argc, char * const *argv, int rebuild) { struct gctl_req *req; int flags, i; const char *errstr; const char *op; if (rebuild) { op = "rebuildparity"; } else { op = "checkparity"; } optreset = 1; optind = 1; flags = 0; while ((i = getopt(argc, argv, "fv")) != -1) { switch (i) { case 'f': flags |= GV_FLAG_F; break; case 'v': flags |= GV_FLAG_V; break; default: warnx("invalid flag '%c'", i); return; } } argc -= optind; argv += optind; if (argc != 1) { warn("usage: %s [-f] [-v] ", op); return; } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, op); gctl_ro_param(req, "rebuild", sizeof(int), &rebuild); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "plex", -1, argv[0]); errstr = gctl_issue(req); if (errstr) warnx("%s\n", errstr); gctl_free(req); } /* Create a RAID-5 volume. */ static void gvinum_raid5(int argc, char * const *argv) { if (argc < 2) { warnx("usage:\traid5 [-fv] [-s stripesize] [-n name] drives\n"); return; } create_volume(argc, argv, "raid5"); } static void gvinum_rename(int argc, char * const *argv) { struct gctl_req *req; const char *errstr; int flags, j; flags = 0; if (argc) { optreset = 1; optind = 1; while ((j = getopt(argc, argv, "r")) != -1) { switch (j) { case 'r': flags |= GV_FLAG_R; break; default: return; } } argc -= optind; argv += optind; } switch (argc) { case 0: warnx("no object to rename specified"); return; case 1: warnx("no new name specified"); return; case 2: break; default: warnx("more than one new name specified"); return; } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "rename"); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "object", -1, argv[0]); gctl_ro_param(req, "newname", -1, argv[1]); errstr = gctl_issue(req); if (errstr != NULL) warnx("can't rename object: %s", errstr); gctl_free(req); } static void gvinum_rm(int argc, char * const *argv) { struct gctl_req *req; int flags, i, j; const char *errstr; char buf[20]; flags = 0; optreset = 1; optind = 1; while ((j = getopt(argc, argv, "rf")) != -1) { switch (j) { case 'f': flags |= GV_FLAG_F; break; case 'r': flags |= GV_FLAG_R; break; default: return; } } argc -= optind; argv += optind; req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "remove"); gctl_ro_param(req, "argc", sizeof(int), &argc); gctl_ro_param(req, "flags", sizeof(int), &flags); if (argc) { for (i = 0; i < argc; i++) { snprintf(buf, sizeof(buf), "argv%d", i); gctl_ro_param(req, buf, -1, argv[i]); } } errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't remove: %s", errstr); gctl_free(req); return; } gctl_free(req); } static void gvinum_resetconfig(int argc, char * const *argv) { struct gctl_req *req; const char *errstr; char reply[32]; int flags, i; flags = 0; while ((i = getopt(argc, argv, "f")) != -1) { switch (i) { case 'f': flags |= GV_FLAG_F; break; default: warn("invalid flag: %c", i); return; } } if ((flags & GV_FLAG_F) == 0) { if (!isatty(STDIN_FILENO)) { warn("Please enter this command from a tty device\n"); return; } printf(" WARNING! This command will completely wipe out" " your gvinum configuration.\n" " All data will be lost. If you really want to do this," " enter the text\n\n" " NO FUTURE\n" " Enter text -> "); fgets(reply, sizeof(reply), stdin); if (strcmp(reply, "NO FUTURE\n")) { printf("\n No change\n"); return; } } req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "resetconfig"); errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't reset config: %s", errstr); gctl_free(req); return; } gctl_free(req); printf("gvinum configuration obliterated\n"); } static void gvinum_saveconfig(void) { struct gctl_req *req; const char *errstr; req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "saveconfig"); errstr = gctl_issue(req); if (errstr != NULL) warnx("can't save configuration: %s", errstr); gctl_free(req); } static void gvinum_start(int argc, char * const *argv) { struct gctl_req *req; int i, initsize, j; const char *errstr; char buf[20]; /* 'start' with no arguments is a no-op. */ if (argc == 1) return; initsize = 0; optreset = 1; optind = 1; while ((j = getopt(argc, argv, "S")) != -1) { switch (j) { case 'S': initsize = atoi(optarg); break; default: return; } } argc -= optind; argv += optind; if (!initsize) initsize = 512; req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "start"); gctl_ro_param(req, "argc", sizeof(int), &argc); gctl_ro_param(req, "initsize", sizeof(int), &initsize); if (argc) { for (i = 0; i < argc; i++) { snprintf(buf, sizeof(buf), "argv%d", i); gctl_ro_param(req, buf, -1, argv[i]); } } errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't start: %s", errstr); gctl_free(req); return; } gctl_free(req); } static void gvinum_stop(int argc __unused, char * const *argv __unused) { int err, fileid; fileid = kldfind(GVINUMKLD); if (fileid == -1) { if (modfind(GVINUMMOD) < 0) warn("cannot find " GVINUMKLD); return; } /* * This little hack prevents that we end up in an infinite loop in * g_unload_class(). gv_unload() will return EAGAIN so that the GEOM * event thread will be free for the g_wither_geom() call from * gv_unload(). It's silly, but it works. */ printf("unloading " GVINUMKLD " kernel module... "); fflush(stdout); if ((err = kldunload(fileid)) != 0 && (errno == EAGAIN)) { sleep(1); err = kldunload(fileid); } if (err != 0) { printf(" failed!\n"); warn("cannot unload " GVINUMKLD); return; } printf("done\n"); exit(0); } /* Create a striped volume. */ static void gvinum_stripe(int argc, char * const *argv) { if (argc < 2) { warnx("usage:\tstripe [-fv] [-n name] drives\n"); return; } create_volume(argc, argv, "stripe"); } /* Grow a subdisk by adding disk backed by provider. */ static void gvinum_grow(int argc, char * const *argv) { struct gctl_req *req; char *drive, *sdname; char sdprefix[GV_MAXSDNAME]; struct gv_drive *d; struct gv_sd *s; const char *errstr; int drives, volumes, plexes, subdisks, flags; flags = 0; drives = volumes = plexes = subdisks = 0; if (argc < 3) { warnx("usage:\tgrow plex drive\n"); return; } s = gv_alloc_sd(); if (s == NULL) { warn("unable to create subdisk"); return; } d = gv_alloc_drive(); if (d == NULL) { warn("unable to create drive"); free(s); return; } /* Lookup device and set an appropriate drive name. */ drive = find_drive(); if (drive == NULL) { warn("unable to find an appropriate drive name"); free(s); free(d); return; } strlcpy(d->name, drive, sizeof(d->name)); copy_device(d, argv[2]); drives = 1; /* We try to use the plex name as basis for the subdisk name. */ snprintf(sdprefix, sizeof(sdprefix), "%s.s", argv[1]); sdname = find_name(sdprefix, GV_TYPE_SD, GV_MAXSDNAME); if (sdname == NULL) { warn("unable to find an appropriate subdisk name"); free(s); free(d); free(drive); return; } strlcpy(s->name, sdname, sizeof(s->name)); free(sdname); strlcpy(s->plex, argv[1], sizeof(s->plex)); strlcpy(s->drive, d->name, sizeof(s->drive)); subdisks = 1; req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "create"); gctl_ro_param(req, "flags", sizeof(int), &flags); gctl_ro_param(req, "volumes", sizeof(int), &volumes); gctl_ro_param(req, "plexes", sizeof(int), &plexes); gctl_ro_param(req, "subdisks", sizeof(int), &subdisks); gctl_ro_param(req, "drives", sizeof(int), &drives); gctl_ro_param(req, "drive0", sizeof(*d), d); gctl_ro_param(req, "sd0", sizeof(*s), s); errstr = gctl_issue(req); free(drive); if (errstr != NULL) { warnx("unable to grow plex: %s", errstr); free(s); free(d); return; } gctl_free(req); } static void parseline(int argc, char * const *argv) { if (argc <= 0) return; if (!strcmp(argv[0], "create")) gvinum_create(argc, argv); else if (!strcmp(argv[0], "exit") || !strcmp(argv[0], "quit")) exit(0); else if (!strcmp(argv[0], "attach")) gvinum_attach(argc, argv); else if (!strcmp(argv[0], "detach")) gvinum_detach(argc, argv); else if (!strcmp(argv[0], "concat")) gvinum_concat(argc, argv); else if (!strcmp(argv[0], "grow")) gvinum_grow(argc, argv); else if (!strcmp(argv[0], "help")) gvinum_help(); else if (!strcmp(argv[0], "list") || !strcmp(argv[0], "l")) gvinum_list(argc, argv); else if (!strcmp(argv[0], "ld")) gvinum_list(argc, argv); else if (!strcmp(argv[0], "lp")) gvinum_list(argc, argv); else if (!strcmp(argv[0], "ls")) gvinum_list(argc, argv); else if (!strcmp(argv[0], "lv")) gvinum_list(argc, argv); else if (!strcmp(argv[0], "mirror")) gvinum_mirror(argc, argv); else if (!strcmp(argv[0], "move")) gvinum_move(argc, argv); else if (!strcmp(argv[0], "mv")) gvinum_move(argc, argv); else if (!strcmp(argv[0], "printconfig")) gvinum_printconfig(argc, argv); else if (!strcmp(argv[0], "raid5")) gvinum_raid5(argc, argv); else if (!strcmp(argv[0], "rename")) gvinum_rename(argc, argv); else if (!strcmp(argv[0], "resetconfig")) gvinum_resetconfig(argc, argv); else if (!strcmp(argv[0], "rm")) gvinum_rm(argc, argv); else if (!strcmp(argv[0], "saveconfig")) gvinum_saveconfig(); else if (!strcmp(argv[0], "setstate")) gvinum_setstate(argc, argv); else if (!strcmp(argv[0], "start")) gvinum_start(argc, argv); else if (!strcmp(argv[0], "stop")) gvinum_stop(argc, argv); else if (!strcmp(argv[0], "stripe")) gvinum_stripe(argc, argv); else if (!strcmp(argv[0], "checkparity")) gvinum_parityop(argc, argv, 0); else if (!strcmp(argv[0], "rebuildparity")) gvinum_parityop(argc, argv, 1); else printf("unknown command '%s'\n", argv[0]); } /* * The guts of printconfig. This is called from gvinum_printconfig and from * gvinum_create when called without an argument, in order to give the user * something to edit. */ static void printconfig(FILE *of, const char *comment) { struct gctl_req *req; struct utsname uname_s; const char *errstr; time_t now; char buf[GV_CFG_LEN + 1]; - + uname(&uname_s); time(&now); + buf[0] = '\0'; req = gctl_get_handle(); gctl_ro_param(req, "class", -1, "VINUM"); gctl_ro_param(req, "verb", -1, "getconfig"); gctl_ro_param(req, "comment", -1, comment); - gctl_rw_param(req, "config", sizeof(buf), buf); + gctl_add_param(req, "config", sizeof(buf), buf, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(req); if (errstr != NULL) { warnx("can't get configuration: %s", errstr); return; } gctl_free(req); fprintf(of, "# Vinum configuration of %s, saved at %s", uname_s.nodename, ctime(&now)); if (*comment != '\0') fprintf(of, "# Current configuration:\n"); fprintf(of, "%s", buf); } diff --git a/usr.sbin/bsdinstall/partedit/gpart_ops.c b/usr.sbin/bsdinstall/partedit/gpart_ops.c index b49ff1c9fd42..f95cc514903b 100644 --- a/usr.sbin/bsdinstall/partedit/gpart_ops.c +++ b/usr.sbin/bsdinstall/partedit/gpart_ops.c @@ -1,1460 +1,1462 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2011 Nathan Whitehorn * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include "partedit.h" #define GPART_FLAGS "x" /* Do not commit changes by default */ static void gpart_show_error(const char *title, const char *explanation, const char *errstr) { char *errmsg; char message[512]; int error; if (explanation == NULL) explanation = ""; error = strtol(errstr, &errmsg, 0); if (errmsg != errstr) { while (errmsg[0] == ' ') errmsg++; if (errmsg[0] != '\0') sprintf(message, "%s%s. %s", explanation, strerror(error), errmsg); else sprintf(message, "%s%s", explanation, strerror(error)); } else { sprintf(message, "%s%s", explanation, errmsg); } dialog_msgbox(title, message, 0, 0, TRUE); } static int scheme_supports_labels(const char *scheme) { if (strcmp(scheme, "APM") == 0) return (1); if (strcmp(scheme, "GPT") == 0) return (1); return (0); } static void newfs_command(const char *fstype, char *command, int use_default) { if (strcmp(fstype, "freebsd-ufs") == 0) { int i; DIALOG_LISTITEM items[] = { {"UFS1", "UFS Version 1", "Use version 1 of the UFS file system instead " "of version 2 (not recommended)", 0 }, {"SU", "Softupdates", "Enable softupdates (default)", 1 }, {"SUJ", "Softupdates journaling", "Enable file system journaling (default - " "turn off for SSDs)", 1 }, {"TRIM", "Enable SSD TRIM support", "Enable TRIM support, useful on solid-state drives", 0 }, }; if (!use_default) { int choice; choice = dlg_checklist("UFS Options", "", 0, 0, 0, nitems(items), items, NULL, FLAG_CHECK, &i); if (choice == 1) /* Cancel */ return; } strcpy(command, "newfs "); for (i = 0; i < (int)nitems(items); i++) { if (items[i].state == 0) continue; if (strcmp(items[i].name, "UFS1") == 0) strcat(command, "-O1 "); else if (strcmp(items[i].name, "SU") == 0) strcat(command, "-U "); else if (strcmp(items[i].name, "SUJ") == 0) strcat(command, "-j "); else if (strcmp(items[i].name, "TRIM") == 0) strcat(command, "-t "); } } else if (strcmp(fstype, "freebsd-zfs") == 0) { int i; DIALOG_LISTITEM items[] = { {"fletcher4", "checksum algorithm: fletcher4", "Use fletcher4 for data integrity checking. " "(default)", 1 }, {"fletcher2", "checksum algorithm: fletcher2", "Use fletcher2 for data integrity checking. " "(not recommended)", 0 }, {"sha256", "checksum algorithm: sha256", "Use sha256 for data integrity checking. " "(not recommended)", 0 }, {"atime", "Update atimes for files", "Disable atime update", 0 }, }; if (!use_default) { int choice; choice = dlg_checklist("ZFS Options", "", 0, 0, 0, nitems(items), items, NULL, FLAG_CHECK, &i); if (choice == 1) /* Cancel */ return; } strcpy(command, "zpool create -f -m none "); if (getenv("BSDINSTALL_TMPBOOT") != NULL) { char zfsboot_path[MAXPATHLEN]; snprintf(zfsboot_path, sizeof(zfsboot_path), "%s/zfs", getenv("BSDINSTALL_TMPBOOT")); mkdir(zfsboot_path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); sprintf(command, "%s -o cachefile=%s/zpool.cache ", command, zfsboot_path); } for (i = 0; i < (int)nitems(items); i++) { if (items[i].state == 0) continue; if (strcmp(items[i].name, "fletcher4") == 0) strcat(command, "-O checksum=fletcher4 "); else if (strcmp(items[i].name, "fletcher2") == 0) strcat(command, "-O checksum=fletcher2 "); else if (strcmp(items[i].name, "sha256") == 0) strcat(command, "-O checksum=sha256 "); else if (strcmp(items[i].name, "atime") == 0) strcat(command, "-O atime=off "); } } else if (strcmp(fstype, "fat32") == 0 || strcmp(fstype, "efi") == 0 || strcmp(fstype, "ms-basic-data") == 0) { int i; DIALOG_LISTITEM items[] = { {"FAT32", "FAT Type 32", "Create a FAT32 filesystem (default)", 1 }, {"FAT16", "FAT Type 16", "Create a FAT16 filesystem", 0 }, {"FAT12", "FAT Type 12", "Create a FAT12 filesystem", 0 }, }; if (!use_default) { int choice; choice = dlg_checklist("FAT Options", "", 0, 0, 0, nitems(items), items, NULL, FLAG_RADIO, &i); if (choice == 1) /* Cancel */ return; } strcpy(command, "newfs_msdos "); for (i = 0; i < (int)nitems(items); i++) { if (items[i].state == 0) continue; if (strcmp(items[i].name, "FAT32") == 0) strcat(command, "-F 32 -c 1"); else if (strcmp(items[i].name, "FAT16") == 0) strcat(command, "-F 16 "); else if (strcmp(items[i].name, "FAT12") == 0) strcat(command, "-F 12 "); } } else { if (!use_default) dialog_msgbox("Error", "No configurable options exist " "for this filesystem.", 0, 0, TRUE); command[0] = '\0'; } } const char * choose_part_type(const char *def_scheme) { int cancel, choice; const char *scheme = NULL; DIALOG_LISTITEM items[] = { {"APM", "Apple Partition Map", "Bootable on PowerPC Apple Hardware", 0 }, {"BSD", "BSD Labels", "Bootable on most x86 systems", 0 }, {"GPT", "GUID Partition Table", "Bootable on most x86 systems and EFI aware ARM64", 0 }, {"MBR", "DOS Partitions", "Bootable on most x86 systems", 0 }, }; parttypemenu: dialog_vars.default_item = __DECONST(char *, def_scheme); cancel = dlg_menu("Partition Scheme", "Select a partition scheme for this volume:", 0, 0, 0, nitems(items), items, &choice, NULL); dialog_vars.default_item = NULL; if (cancel) return NULL; if (!is_scheme_bootable(items[choice].name)) { char message[512]; sprintf(message, "This partition scheme (%s) is not " "bootable on this platform. Are you sure you want " "to proceed?", items[choice].name); dialog_vars.defaultno = TRUE; cancel = dialog_yesno("Warning", message, 0, 0); dialog_vars.defaultno = FALSE; if (cancel) /* cancel */ goto parttypemenu; } scheme = items[choice].name; return scheme; } int gpart_partition(const char *lg_name, const char *scheme) { int cancel; struct gctl_req *r; const char *errstr; schememenu: if (scheme == NULL) { scheme = choose_part_type(default_scheme()); if (scheme == NULL) return (-1); if (!is_scheme_bootable(scheme)) { char message[512]; sprintf(message, "This partition scheme (%s) is not " "bootable on this platform. Are you sure you want " "to proceed?", scheme); dialog_vars.defaultno = TRUE; cancel = dialog_yesno("Warning", message, 0, 0); dialog_vars.defaultno = FALSE; if (cancel) { /* cancel */ /* Reset scheme so user can choose another */ scheme = NULL; goto schememenu; } } } r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, lg_name); gctl_ro_param(r, "flags", -1, GPART_FLAGS); gctl_ro_param(r, "scheme", -1, scheme); gctl_ro_param(r, "verb", -1, "create"); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_show_error("Error", NULL, errstr); gctl_free(r); scheme = NULL; goto schememenu; } gctl_free(r); if (bootcode_path(scheme) != NULL) get_part_metadata(lg_name, 1)->bootcode = 1; return (0); } static void gpart_activate(struct gprovider *pp) { struct gconfig *gc; struct gctl_req *r; const char *errstr, *scheme; const char *attribute = NULL; intmax_t idx; /* * Some partition schemes need this partition to be marked 'active' * for it to be bootable. */ LIST_FOREACH(gc, &pp->lg_geom->lg_config, lg_config) { if (strcmp(gc->lg_name, "scheme") == 0) { scheme = gc->lg_val; break; } } if (strcmp(scheme, "MBR") == 0 || strcmp(scheme, "EBR") == 0) attribute = "active"; else return; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "index") == 0) { idx = atoi(gc->lg_val); break; } } r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, pp->lg_geom->lg_name); gctl_ro_param(r, "verb", -1, "set"); gctl_ro_param(r, "attrib", -1, attribute); gctl_ro_param(r, "index", sizeof(idx), &idx); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') gpart_show_error("Error", "Error marking partition active:", errstr); gctl_free(r); } void gpart_set_root(const char *lg_name, const char *attribute) { struct gctl_req *r; const char *errstr; r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, lg_name); gctl_ro_param(r, "flags", -1, "C"); gctl_ro_param(r, "verb", -1, "set"); gctl_ro_param(r, "attrib", -1, attribute); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') gpart_show_error("Error", "Error setting parameter on disk:", errstr); gctl_free(r); } static void gpart_bootcode(struct ggeom *gp) { const char *bootcode; struct gconfig *gc; struct gctl_req *r; const char *errstr, *scheme; uint8_t *boot; size_t bootsize, bytes; int bootfd; /* * Write default bootcode to the newly partitioned disk, if that * applies on this platform. */ LIST_FOREACH(gc, &gp->lg_config, lg_config) { if (strcmp(gc->lg_name, "scheme") == 0) { scheme = gc->lg_val; break; } } bootcode = bootcode_path(scheme); if (bootcode == NULL) return; bootfd = open(bootcode, O_RDONLY); if (bootfd < 0) { dialog_msgbox("Bootcode Error", strerror(errno), 0, 0, TRUE); return; } bootsize = lseek(bootfd, 0, SEEK_END); boot = malloc(bootsize); lseek(bootfd, 0, SEEK_SET); bytes = 0; while (bytes < bootsize) bytes += read(bootfd, boot + bytes, bootsize - bytes); close(bootfd); r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, gp->lg_name); gctl_ro_param(r, "verb", -1, "bootcode"); gctl_ro_param(r, "bootcode", bootsize, boot); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') gpart_show_error("Bootcode Error", NULL, errstr); gctl_free(r); free(boot); } static void gpart_partcode(struct gprovider *pp, const char *fstype) { struct gconfig *gc; const char *scheme; const char *indexstr; char message[255], command[255]; LIST_FOREACH(gc, &pp->lg_geom->lg_config, lg_config) { if (strcmp(gc->lg_name, "scheme") == 0) { scheme = gc->lg_val; break; } } /* Make sure this partition scheme needs partcode on this platform */ if (partcode_path(scheme, fstype) == NULL) return; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "index") == 0) { indexstr = gc->lg_val; break; } } /* Shell out to gpart for partcode for now */ sprintf(command, "gpart bootcode -p %s -i %s %s", partcode_path(scheme, fstype), indexstr, pp->lg_geom->lg_name); if (system(command) != 0) { sprintf(message, "Error installing partcode on partition %s", pp->lg_name); dialog_msgbox("Error", message, 0, 0, TRUE); } } void gpart_destroy(struct ggeom *lg_geom) { struct gctl_req *r; struct gprovider *pp; const char *errstr; int force = 1; /* Delete all child metadata */ LIST_FOREACH(pp, &lg_geom->lg_provider, lg_provider) gpart_delete(pp); /* Revert any local changes to get this geom into a pristine state */ r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, lg_geom->lg_name); gctl_ro_param(r, "verb", -1, "undo"); gctl_issue(r); /* Ignore errors -- these are non-fatal */ gctl_free(r); /* Now destroy the geom itself */ r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, lg_geom->lg_name); gctl_ro_param(r, "flags", -1, GPART_FLAGS); gctl_ro_param(r, "force", sizeof(force), &force); gctl_ro_param(r, "verb", -1, "destroy"); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { /* * Check if we reverted away the existence of the geom * altogether. Show all other errors to the user. */ if (strtol(errstr, NULL, 0) != EINVAL) gpart_show_error("Error", NULL, errstr); } gctl_free(r); /* And any metadata associated with the partition scheme itself */ delete_part_metadata(lg_geom->lg_name); } void gpart_edit(struct gprovider *pp) { struct gctl_req *r; struct gconfig *gc; struct gconsumer *cp; struct ggeom *geom; const char *errstr, *oldtype, *scheme; struct partition_metadata *md; char sizestr[32]; char newfs[255]; intmax_t idx; int hadlabel, choice, junk, nitems; unsigned i; DIALOG_FORMITEM items[] = { {0, "Type:", 5, 0, 0, FALSE, "", 11, 0, 12, 15, 0, FALSE, "Filesystem type (e.g. freebsd-ufs, freebsd-zfs, " "freebsd-swap)", FALSE}, {0, "Size:", 5, 1, 0, FALSE, "", 11, 1, 12, 0, 0, FALSE, "Partition size. Append K, M, G for kilobytes, " "megabytes or gigabytes.", FALSE}, {0, "Mountpoint:", 11, 2, 0, FALSE, "", 11, 2, 12, 15, 0, FALSE, "Path at which to mount this partition (leave blank " "for swap, set to / for root filesystem)", FALSE}, {0, "Label:", 7, 3, 0, FALSE, "", 11, 3, 12, 15, 0, FALSE, "Partition name. Not all partition schemes support this.", FALSE}, }; /* * Find the PART geom we are manipulating. This may be a consumer of * this provider, or its parent. Check the consumer case first. */ geom = NULL; LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers) if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) { /* Check for zombie geoms, treating them as blank */ scheme = NULL; LIST_FOREACH(gc, &cp->lg_geom->lg_config, lg_config) { if (strcmp(gc->lg_name, "scheme") == 0) { scheme = gc->lg_val; break; } } if (scheme == NULL || strcmp(scheme, "(none)") == 0) { gpart_partition(cp->lg_geom->lg_name, NULL); return; } /* If this is a nested partition, edit as usual */ if (strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0) break; /* Destroy the geom and all sub-partitions */ gpart_destroy(cp->lg_geom); /* Now re-partition and return */ gpart_partition(cp->lg_geom->lg_name, NULL); return; } if (geom == NULL && strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0) geom = pp->lg_geom; if (geom == NULL) { /* Disk not partitioned, so partition it */ gpart_partition(pp->lg_name, NULL); return; } LIST_FOREACH(gc, &geom->lg_config, lg_config) { if (strcmp(gc->lg_name, "scheme") == 0) { scheme = gc->lg_val; break; } } nitems = scheme_supports_labels(scheme) ? 4 : 3; /* Edit editable parameters of a partition */ hadlabel = 0; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "type") == 0) { oldtype = gc->lg_val; items[0].text = gc->lg_val; } if (strcmp(gc->lg_name, "label") == 0 && gc->lg_val != NULL) { hadlabel = 1; items[3].text = gc->lg_val; } if (strcmp(gc->lg_name, "index") == 0) idx = atoi(gc->lg_val); } TAILQ_FOREACH(md, &part_metadata, metadata) { if (md->name != NULL && strcmp(md->name, pp->lg_name) == 0) { if (md->fstab != NULL) items[2].text = md->fstab->fs_file; break; } } humanize_number(sizestr, 7, pp->lg_mediasize, "B", HN_AUTOSCALE, HN_NOSPACE | HN_DECIMAL); items[1].text = sizestr; editpart: choice = dlg_form("Edit Partition", "", 0, 0, 0, nitems, items, &junk); if (choice) /* Cancel pressed */ goto endedit; /* If this is the root partition, check that this fs is bootable */ if (strcmp(items[2].text, "/") == 0 && !is_fs_bootable(scheme, items[0].text)) { char message[512]; sprintf(message, "This file system (%s) is not bootable " "on this system. Are you sure you want to proceed?", items[0].text); dialog_vars.defaultno = TRUE; choice = dialog_yesno("Warning", message, 0, 0); dialog_vars.defaultno = FALSE; if (choice == 1) /* cancel */ goto editpart; } /* Check if the label has a / in it */ if (strchr(items[3].text, '/') != NULL) { dialog_msgbox("Error", "Label contains a /, which is not an " "allowed character.", 0, 0, TRUE); goto editpart; } r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, geom->lg_name); gctl_ro_param(r, "flags", -1, GPART_FLAGS); gctl_ro_param(r, "verb", -1, "modify"); gctl_ro_param(r, "index", sizeof(idx), &idx); if (hadlabel || items[3].text[0] != '\0') gctl_ro_param(r, "label", -1, items[3].text); gctl_ro_param(r, "type", -1, items[0].text); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_show_error("Error", NULL, errstr); gctl_free(r); goto editpart; } gctl_free(r); newfs_command(items[0].text, newfs, 1); set_default_part_metadata(pp->lg_name, scheme, items[0].text, items[2].text, (strcmp(oldtype, items[0].text) != 0) ? newfs : NULL); endedit: if (strcmp(oldtype, items[0].text) != 0 && cp != NULL) gpart_destroy(cp->lg_geom); if (strcmp(oldtype, items[0].text) != 0 && strcmp(items[0].text, "freebsd") == 0) gpart_partition(pp->lg_name, "BSD"); for (i = 0; i < nitems(items); i++) if (items[i].text_free) free(items[i].text); } void set_default_part_metadata(const char *name, const char *scheme, const char *type, const char *mountpoint, const char *newfs) { struct partition_metadata *md; char *zpool_name = NULL; const char *default_bootmount = NULL; int i; /* Set part metadata */ md = get_part_metadata(name, 1); if (newfs) { if (md->newfs != NULL) { free(md->newfs); md->newfs = NULL; } if (newfs != NULL && newfs[0] != '\0') { md->newfs = malloc(strlen(newfs) + strlen(" /dev/") + strlen(mountpoint) + 5 + strlen(name) + 1); if (strcmp("freebsd-zfs", type) == 0) { zpool_name = strdup((strlen(mountpoint) == 1) ? "root" : &mountpoint[1]); for (i = 0; zpool_name[i] != 0; i++) if (!isalnum(zpool_name[i])) zpool_name[i] = '_'; sprintf(md->newfs, "%s %s /dev/%s", newfs, zpool_name, name); } else { sprintf(md->newfs, "%s /dev/%s", newfs, name); } } } if (strcmp(type, "freebsd-swap") == 0) mountpoint = "none"; if (strcmp(type, bootpart_type(scheme, &default_bootmount)) == 0) { if (default_bootmount == NULL) md->bootcode = 1; else if (mountpoint == NULL || strlen(mountpoint) == 0) mountpoint = default_bootmount; } if (mountpoint == NULL || mountpoint[0] == '\0') { if (md->fstab != NULL) { free(md->fstab->fs_spec); free(md->fstab->fs_file); free(md->fstab->fs_vfstype); free(md->fstab->fs_mntops); free(md->fstab->fs_type); free(md->fstab); md->fstab = NULL; } } else { if (md->fstab == NULL) { md->fstab = malloc(sizeof(struct fstab)); } else { free(md->fstab->fs_spec); free(md->fstab->fs_file); free(md->fstab->fs_vfstype); free(md->fstab->fs_mntops); free(md->fstab->fs_type); } if (strcmp("freebsd-zfs", type) == 0) { md->fstab->fs_spec = strdup(zpool_name); } else { md->fstab->fs_spec = malloc(strlen(name) + strlen("/dev/") + 1); sprintf(md->fstab->fs_spec, "/dev/%s", name); } md->fstab->fs_file = strdup(mountpoint); /* Get VFS from text after freebsd-, if possible */ if (strncmp("freebsd-", type, 8) == 0) md->fstab->fs_vfstype = strdup(&type[8]); else if (strcmp("fat32", type) == 0 || strcmp("efi", type) == 0 || strcmp("ms-basic-data", type) == 0) md->fstab->fs_vfstype = strdup("msdosfs"); else md->fstab->fs_vfstype = strdup(type); /* Guess */ if (strcmp(type, "freebsd-swap") == 0) { md->fstab->fs_type = strdup(FSTAB_SW); md->fstab->fs_freq = 0; md->fstab->fs_passno = 0; } else if (strcmp(type, "freebsd-zfs") == 0) { md->fstab->fs_type = strdup(FSTAB_RW); md->fstab->fs_freq = 0; md->fstab->fs_passno = 0; } else { md->fstab->fs_type = strdup(FSTAB_RW); if (strcmp(mountpoint, "/") == 0) { md->fstab->fs_freq = 1; md->fstab->fs_passno = 1; } else { md->fstab->fs_freq = 2; md->fstab->fs_passno = 2; } } md->fstab->fs_mntops = strdup(md->fstab->fs_type); } if (zpool_name != NULL) free(zpool_name); } static int part_compare(const void *xa, const void *xb) { struct gprovider **a = (struct gprovider **)xa; struct gprovider **b = (struct gprovider **)xb; intmax_t astart, bstart; struct gconfig *gc; astart = bstart = 0; LIST_FOREACH(gc, &(*a)->lg_config, lg_config) if (strcmp(gc->lg_name, "start") == 0) { astart = strtoimax(gc->lg_val, NULL, 0); break; } LIST_FOREACH(gc, &(*b)->lg_config, lg_config) if (strcmp(gc->lg_name, "start") == 0) { bstart = strtoimax(gc->lg_val, NULL, 0); break; } if (astart < bstart) return -1; else if (astart > bstart) return 1; else return 0; } intmax_t gpart_max_free(struct ggeom *geom, intmax_t *npartstart) { struct gconfig *gc; struct gprovider *pp, **providers; intmax_t sectorsize, stripesize, offset; intmax_t lastend; intmax_t start, end; intmax_t maxsize, maxstart; intmax_t partstart, partend; int i, nparts; /* Now get the maximum free size and free start */ start = end = 0; LIST_FOREACH(gc, &geom->lg_config, lg_config) { if (strcmp(gc->lg_name, "first") == 0) start = strtoimax(gc->lg_val, NULL, 0); if (strcmp(gc->lg_name, "last") == 0) end = strtoimax(gc->lg_val, NULL, 0); } i = nparts = 0; LIST_FOREACH(pp, &geom->lg_provider, lg_provider) nparts++; providers = calloc(nparts, sizeof(providers[0])); LIST_FOREACH(pp, &geom->lg_provider, lg_provider) providers[i++] = pp; qsort(providers, nparts, sizeof(providers[0]), part_compare); lastend = start - 1; maxsize = 0; for (i = 0; i < nparts; i++) { pp = providers[i]; LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "start") == 0) partstart = strtoimax(gc->lg_val, NULL, 0); if (strcmp(gc->lg_name, "end") == 0) partend = strtoimax(gc->lg_val, NULL, 0); } if (partstart - lastend > maxsize) { maxsize = partstart - lastend - 1; maxstart = lastend + 1; } lastend = partend; } if (end - lastend > maxsize) { maxsize = end - lastend; maxstart = lastend + 1; } pp = LIST_FIRST(&geom->lg_consumer)->lg_provider; /* * Round the start and size of the largest available space up to * the nearest multiple of the adjusted stripe size. * * The adjusted stripe size is the least common multiple of the * actual stripe size, or the sector size if no stripe size was * reported, and 4096. The reason for this is that contemporary * disks often have 4096-byte physical sectors but report 512 * bytes instead for compatibility with older / broken operating * systems and BIOSes. For the same reasons, virtualized storage * may also report a 512-byte stripe size, or none at all. */ sectorsize = pp->lg_sectorsize; if ((stripesize = pp->lg_stripesize) == 0) stripesize = sectorsize; while (stripesize % 4096 != 0) stripesize *= 2; if ((offset = maxstart * sectorsize % stripesize) != 0) { offset = (stripesize - offset) / sectorsize; maxstart += offset; maxsize -= offset; } if (npartstart != NULL) *npartstart = maxstart; return (maxsize); } static size_t add_boot_partition(struct ggeom *geom, struct gprovider *pp, const char *scheme, int interactive) { struct gconfig *gc; struct gprovider *ppi; int choice; /* Check for existing freebsd-boot partition */ LIST_FOREACH(ppi, &geom->lg_provider, lg_provider) { struct partition_metadata *md; const char *bootmount = NULL; LIST_FOREACH(gc, &ppi->lg_config, lg_config) if (strcmp(gc->lg_name, "type") == 0) break; if (gc == NULL) continue; if (strcmp(gc->lg_val, bootpart_type(scheme, &bootmount)) != 0) continue; /* * If the boot partition is not mountable and needs partcode, * but doesn't have it, it doesn't satisfy our requirements. */ md = get_part_metadata(ppi->lg_name, 0); if (bootmount == NULL && (md == NULL || !md->bootcode)) continue; /* If it is mountable, but mounted somewhere else, remount */ if (bootmount != NULL && md != NULL && md->fstab != NULL && strlen(md->fstab->fs_file) > 0 && strcmp(md->fstab->fs_file, bootmount) != 0) continue; /* If it is mountable, but mountpoint is not set, mount it */ if (bootmount != NULL && md == NULL) set_default_part_metadata(ppi->lg_name, scheme, gc->lg_val, bootmount, NULL); /* Looks good at this point, no added data needed */ return (0); } if (interactive) choice = dialog_yesno("Boot Partition", "This partition scheme requires a boot partition " "for the disk to be bootable. Would you like to " "make one now?", 0, 0); else choice = 0; if (choice == 0) { /* yes */ struct partition_metadata *md; const char *bootmount = NULL; char *bootpartname = NULL; char sizestr[7]; humanize_number(sizestr, 7, bootpart_size(scheme), "B", HN_AUTOSCALE, HN_NOSPACE | HN_DECIMAL); gpart_create(pp, bootpart_type(scheme, &bootmount), sizestr, bootmount, &bootpartname, 0); if (bootpartname == NULL) /* Error reported to user already */ return 0; /* If the part is not mountable, make sure newfs isn't set */ if (bootmount == NULL) { md = get_part_metadata(bootpartname, 0); if (md != NULL && md->newfs != NULL) { free(md->newfs); md->newfs = NULL; } } free(bootpartname); return (bootpart_size(scheme)); } return (0); } void gpart_create(struct gprovider *pp, const char *default_type, const char *default_size, const char *default_mountpoint, char **partname, int interactive) { struct gctl_req *r; struct gconfig *gc; struct gconsumer *cp; struct ggeom *geom; const char *errstr, *scheme; char sizestr[32], startstr[32], output[64], *newpartname; char newfs[255], options_fstype[64]; intmax_t maxsize, size, sector, firstfree, stripe; uint64_t bytes; int nitems, choice, junk; unsigned i; DIALOG_FORMITEM items[] = { {0, "Type:", 5, 0, 0, FALSE, "freebsd-ufs", 11, 0, 12, 15, 0, FALSE, "Filesystem type (e.g. freebsd-ufs, freebsd-zfs, " "freebsd-swap)", FALSE}, {0, "Size:", 5, 1, 0, FALSE, "", 11, 1, 12, 15, 0, FALSE, "Partition size. Append K, M, G for kilobytes, " "megabytes or gigabytes.", FALSE}, {0, "Mountpoint:", 11, 2, 0, FALSE, "", 11, 2, 12, 15, 0, FALSE, "Path at which to mount partition (blank for " "swap, / for root filesystem)", FALSE}, {0, "Label:", 7, 3, 0, FALSE, "", 11, 3, 12, 15, 0, FALSE, "Partition name. Not all partition schemes support this.", FALSE}, }; if (partname != NULL) *partname = NULL; /* Record sector and stripe sizes */ sector = pp->lg_sectorsize; stripe = pp->lg_stripesize; /* * Find the PART geom we are manipulating. This may be a consumer of * this provider, or its parent. Check the consumer case first. */ geom = NULL; LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers) if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) { geom = cp->lg_geom; break; } if (geom == NULL && strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0) geom = pp->lg_geom; /* Now get the partition scheme */ scheme = NULL; if (geom != NULL) { LIST_FOREACH(gc, &geom->lg_config, lg_config) if (strcmp(gc->lg_name, "scheme") == 0) scheme = gc->lg_val; } if (geom == NULL || scheme == NULL || strcmp(scheme, "(none)") == 0) { if (gpart_partition(pp->lg_name, NULL) == 0) dialog_msgbox("", "The partition table has been successfully created." " Please press Create again to create partitions.", 0, 0, TRUE); return; } /* * If we still don't have a geom, either the user has * canceled partitioning or there has been an error which has already * been displayed, so bail. */ if (geom == NULL) return; maxsize = size = gpart_max_free(geom, &firstfree); if (size <= 0) { dialog_msgbox("Error", "No free space left on device.", 0, 0, TRUE); return; } humanize_number(sizestr, 7, size*sector, "B", HN_AUTOSCALE, HN_NOSPACE | HN_DECIMAL); items[1].text = sizestr; /* Special-case the MBR default type for nested partitions */ if (strcmp(scheme, "MBR") == 0) { items[0].text = "freebsd"; items[0].help = "Filesystem type (e.g. freebsd, fat32)"; } nitems = scheme_supports_labels(scheme) ? 4 : 3; if (default_type != NULL) items[0].text = (char *)default_type; if (default_size != NULL) items[1].text = (char *)default_size; if (default_mountpoint != NULL) items[2].text = (char *)default_mountpoint; /* Default options */ strncpy(options_fstype, items[0].text, sizeof(options_fstype)); newfs_command(options_fstype, newfs, 1); addpartform: if (interactive) { dialog_vars.extra_label = "Options"; dialog_vars.extra_button = TRUE; choice = dlg_form("Add Partition", "", 0, 0, 0, nitems, items, &junk); dialog_vars.extra_button = FALSE; switch (choice) { case 0: /* OK */ break; case 1: /* Cancel */ return; case 3: /* Options */ strncpy(options_fstype, items[0].text, sizeof(options_fstype)); newfs_command(options_fstype, newfs, 0); goto addpartform; } } /* * If the user changed the fs type after specifying options, undo * their choices in favor of the new filesystem's defaults. */ if (strcmp(options_fstype, items[0].text) != 0) { strncpy(options_fstype, items[0].text, sizeof(options_fstype)); newfs_command(options_fstype, newfs, 1); } size = maxsize; if (strlen(items[1].text) > 0) { if (expand_number(items[1].text, &bytes) != 0) { char error[512]; sprintf(error, "Invalid size: %s\n", strerror(errno)); dialog_msgbox("Error", error, 0, 0, TRUE); goto addpartform; } size = MIN((intmax_t)(bytes/sector), maxsize); } /* Check if the label has a / in it */ if (strchr(items[3].text, '/') != NULL) { dialog_msgbox("Error", "Label contains a /, which is not an " "allowed character.", 0, 0, TRUE); goto addpartform; } /* Warn if no mountpoint set */ if (strcmp(items[0].text, "freebsd-ufs") == 0 && items[2].text[0] != '/') { choice = 0; if (interactive) { dialog_vars.defaultno = TRUE; choice = dialog_yesno("Warning", "This partition does not have a valid mountpoint " "(for the partition from which you intend to boot the " "operating system, the mountpoint should be /). Are you " "sure you want to continue?" , 0, 0); dialog_vars.defaultno = FALSE; } if (choice == 1) /* cancel */ goto addpartform; } /* * Error if this scheme needs nested partitions, this is one, and * a mountpoint was set. */ if (strcmp(items[0].text, "freebsd") == 0 && strlen(items[2].text) > 0) { dialog_msgbox("Error", "Partitions of type \"freebsd\" are " "nested BSD-type partition schemes and cannot have " "mountpoints. After creating one, select it and press " "Create again to add the actual file systems.", 0, 0, TRUE); goto addpartform; } /* If this is the root partition, check that this scheme is bootable */ if (strcmp(items[2].text, "/") == 0 && !is_scheme_bootable(scheme)) { char message[512]; sprintf(message, "This partition scheme (%s) is not bootable " "on this platform. Are you sure you want to proceed?", scheme); dialog_vars.defaultno = TRUE; choice = dialog_yesno("Warning", message, 0, 0); dialog_vars.defaultno = FALSE; if (choice == 1) /* cancel */ goto addpartform; } /* If this is the root partition, check that this fs is bootable */ if (strcmp(items[2].text, "/") == 0 && !is_fs_bootable(scheme, items[0].text)) { char message[512]; sprintf(message, "This file system (%s) is not bootable " "on this system. Are you sure you want to proceed?", items[0].text); dialog_vars.defaultno = TRUE; choice = dialog_yesno("Warning", message, 0, 0); dialog_vars.defaultno = FALSE; if (choice == 1) /* cancel */ goto addpartform; } /* * If this is the root partition, and we need a boot partition, ask * the user to add one. */ if ((strcmp(items[0].text, "freebsd") == 0 || strcmp(items[2].text, "/") == 0) && bootpart_size(scheme) > 0) { size_t bytes = add_boot_partition(geom, pp, scheme, interactive); /* Now adjust the part we are really adding forward */ if (bytes > 0) { firstfree += bytes / sector; size -= (bytes + stripe)/sector; if (stripe > 0 && (firstfree*sector % stripe) != 0) firstfree += (stripe - ((firstfree*sector) % stripe)) / sector; } } + output[0] = '\0'; + r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, geom->lg_name); gctl_ro_param(r, "flags", -1, GPART_FLAGS); gctl_ro_param(r, "verb", -1, "add"); - gctl_ro_param(r, "type", -1, items[0].text); snprintf(sizestr, sizeof(sizestr), "%jd", size); gctl_ro_param(r, "size", -1, sizestr); snprintf(startstr, sizeof(startstr), "%jd", firstfree); gctl_ro_param(r, "start", -1, startstr); if (items[3].text[0] != '\0') gctl_ro_param(r, "label", -1, items[3].text); - gctl_rw_param(r, "output", sizeof(output), output); + gctl_add_param(r, "output", sizeof(output), output, + GCTL_PARAM_WR | GCTL_PARAM_ASCII); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_show_error("Error", NULL, errstr); gctl_free(r); goto addpartform; } newpartname = strtok(output, " "); gctl_free(r); /* * Try to destroy any geom that gpart picked up already here from * dirty blocks. */ r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, newpartname); gctl_ro_param(r, "flags", -1, GPART_FLAGS); junk = 1; gctl_ro_param(r, "force", sizeof(junk), &junk); gctl_ro_param(r, "verb", -1, "destroy"); gctl_issue(r); /* Error usually expected and non-fatal */ gctl_free(r); if (strcmp(items[0].text, "freebsd") == 0) gpart_partition(newpartname, "BSD"); else set_default_part_metadata(newpartname, scheme, items[0].text, items[2].text, newfs); for (i = 0; i < nitems(items); i++) if (items[i].text_free) free(items[i].text); if (partname != NULL) *partname = strdup(newpartname); } void gpart_delete(struct gprovider *pp) { struct gconfig *gc; struct ggeom *geom; struct gconsumer *cp; struct gctl_req *r; const char *errstr; intmax_t idx; int is_partition; /* Is it a partition? */ is_partition = (strcmp(pp->lg_geom->lg_class->lg_name, "PART") == 0); /* Find out if this is the root of a gpart geom */ geom = NULL; LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers) if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) { geom = cp->lg_geom; break; } /* If so, destroy all children */ if (geom != NULL) { gpart_destroy(geom); /* If this is a partition, revert it, so it can be deleted */ if (is_partition) { r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, geom->lg_name); gctl_ro_param(r, "verb", -1, "undo"); gctl_issue(r); /* Ignore non-fatal errors */ gctl_free(r); } } /* * If this is not a partition, see if that is a problem, complain if * necessary, and return always, since we need not do anything further, * error or no. */ if (!is_partition) { if (geom == NULL) dialog_msgbox("Error", "Only partitions can be deleted.", 0, 0, TRUE); return; } r = gctl_get_handle(); gctl_ro_param(r, "class", -1, pp->lg_geom->lg_class->lg_name); gctl_ro_param(r, "arg0", -1, pp->lg_geom->lg_name); gctl_ro_param(r, "flags", -1, GPART_FLAGS); gctl_ro_param(r, "verb", -1, "delete"); LIST_FOREACH(gc, &pp->lg_config, lg_config) { if (strcmp(gc->lg_name, "index") == 0) { idx = atoi(gc->lg_val); gctl_ro_param(r, "index", sizeof(idx), &idx); break; } } errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') { gpart_show_error("Error", NULL, errstr); gctl_free(r); return; } gctl_free(r); delete_part_metadata(pp->lg_name); } void gpart_revert_all(struct gmesh *mesh) { struct gclass *classp; struct gconfig *gc; struct ggeom *gp; struct gctl_req *r; const char *modified; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { if (strcmp(classp->lg_name, "PART") == 0) break; } if (strcmp(classp->lg_name, "PART") != 0) { dialog_msgbox("Error", "gpart not found!", 0, 0, TRUE); return; } LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { modified = "true"; /* XXX: If we don't know (kernel too old), * assume there are modifications. */ LIST_FOREACH(gc, &gp->lg_config, lg_config) { if (strcmp(gc->lg_name, "modified") == 0) { modified = gc->lg_val; break; } } if (strcmp(modified, "false") == 0) continue; r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, gp->lg_name); gctl_ro_param(r, "verb", -1, "undo"); gctl_issue(r); gctl_free(r); } } void gpart_commit(struct gmesh *mesh) { struct partition_metadata *md; struct gclass *classp; struct ggeom *gp; struct gconfig *gc; struct gconsumer *cp; struct gprovider *pp; struct gctl_req *r; const char *errstr; const char *modified; const char *rootfs; LIST_FOREACH(classp, &mesh->lg_class, lg_class) { if (strcmp(classp->lg_name, "PART") == 0) break; } /* Figure out what filesystem / uses */ rootfs = "ufs"; /* Assume ufs if nothing else present */ TAILQ_FOREACH(md, &part_metadata, metadata) { if (md->fstab != NULL && strcmp(md->fstab->fs_file, "/") == 0) { rootfs = md->fstab->fs_vfstype; break; } } if (strcmp(classp->lg_name, "PART") != 0) { dialog_msgbox("Error", "gpart not found!", 0, 0, TRUE); return; } LIST_FOREACH(gp, &classp->lg_geom, lg_geom) { modified = "true"; /* XXX: If we don't know (kernel too old), * assume there are modifications. */ LIST_FOREACH(gc, &gp->lg_config, lg_config) { if (strcmp(gc->lg_name, "modified") == 0) { modified = gc->lg_val; break; } } if (strcmp(modified, "false") == 0) continue; /* Add bootcode if necessary, before the commit */ md = get_part_metadata(gp->lg_name, 0); if (md != NULL && md->bootcode) gpart_bootcode(gp); /* Now install partcode on its partitions, if necessary */ LIST_FOREACH(pp, &gp->lg_provider, lg_provider) { md = get_part_metadata(pp->lg_name, 0); if (md == NULL || !md->bootcode) continue; /* Mark this partition active if that's required */ gpart_activate(pp); /* Check if the partition has sub-partitions */ LIST_FOREACH(cp, &pp->lg_consumers, lg_consumers) if (strcmp(cp->lg_geom->lg_class->lg_name, "PART") == 0) break; if (cp == NULL) /* No sub-partitions */ gpart_partcode(pp, rootfs); } r = gctl_get_handle(); gctl_ro_param(r, "class", -1, "PART"); gctl_ro_param(r, "arg0", -1, gp->lg_name); gctl_ro_param(r, "verb", -1, "commit"); errstr = gctl_issue(r); if (errstr != NULL && errstr[0] != '\0') gpart_show_error("Error", NULL, errstr); gctl_free(r); } }