Index: head/lib/geom/part/geom_part.c =================================================================== --- head/lib/geom/part/geom_part.c (revision 341066) +++ head/lib/geom/part/geom_part.c (revision 341067) @@ -1,1344 +1,1346 @@ /*- * 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 }, - "[-b bootcode] [-p partcode -i index] [-f flags] geom" + "[-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); 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); } Index: head/lib/geom/part/gpart.8 =================================================================== --- head/lib/geom/part/gpart.8 (revision 341066) +++ head/lib/geom/part/gpart.8 (revision 341067) @@ -1,1441 +1,1450 @@ .\" 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. .\" .\" $FreeBSD$ .\" .Dd June 17, 2018 .Dt GPART 8 .Os .Sh NAME .Nm gpart .Nd "control utility for the disk partitioning GEOM class" .Sh SYNOPSIS .\" ==== ADD ==== .Nm .Cm add .Fl t Ar type .Op Fl a Ar alignment .Op Fl b Ar start .Op Fl s Ar size .Op Fl i Ar index .Op Fl l Ar label .Op Fl f Ar flags .Ar geom .\" ==== BACKUP ==== .Nm .Cm backup .Ar geom .\" ==== BOOTCODE ==== .Nm .Cm bootcode +.Op Fl N .Op Fl b Ar bootcode .Op Fl p Ar partcode Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== COMMIT ==== .Nm .Cm commit .Ar geom .\" ==== CREATE ==== .Nm .Cm create .Fl s Ar scheme .Op Fl n Ar entries .Op Fl f Ar flags .Ar provider .\" ==== DELETE ==== .Nm .Cm delete .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== DESTROY ==== .Nm .Cm destroy .Op Fl F .Op Fl f Ar flags .Ar geom .\" ==== MODIFY ==== .Nm .Cm modify .Fl i Ar index .Op Fl l Ar label .Op Fl t Ar type .Op Fl f Ar flags .Ar geom .\" ==== RECOVER ==== .Nm .Cm recover .Op Fl f Ar flags .Ar geom .\" ==== RESIZE ==== .Nm .Cm resize .Fl i Ar index .Op Fl a Ar alignment .Op Fl s Ar size .Op Fl f Ar flags .Ar geom .\" ==== RESTORE ==== .Nm .Cm restore .Op Fl lF .Op Fl f Ar flags .Ar provider .Op Ar ... .\" ==== SET ==== .Nm .Cm set .Fl a Ar attrib .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" ==== SHOW ==== .Nm .Cm show .Op Fl l | r .Op Fl p .Op Ar geom ... .\" ==== UNDO ==== .Nm .Cm undo .Ar geom .\" ==== UNSET ==== .Nm .Cm unset .Fl a Ar attrib .Fl i Ar index .Op Fl f Ar flags .Ar geom .\" .Nm .Cm list .Nm .Cm status .Nm .Cm load .Nm .Cm unload .Sh DESCRIPTION The .Nm utility is used to partition GEOM providers, normally disks. The first argument is the action to be taken: .Bl -tag -width ".Cm bootcode" .\" ==== ADD ==== .It Cm add Add a new partition to the partitioning scheme given by .Ar geom . The partition type must be specified with .Fl t Ar type . The partition's location, size, and other attributes will be calculated automatically if the corresponding options are not specified. .Pp The .Cm add command accepts these options: .Bl -tag -width 12n .It Fl a Ar alignment If specified, then .Nm utility tries to align .Ar start offset and partition .Ar size to be multiple of .Ar alignment value. .It Fl b Ar start The logical block address where the partition will begin. A SI unit suffix is allowed. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index The index in the partition table at which the new partition is to be placed. The index determines the name of the device special file used to represent the partition. .It Fl l Ar label The label attached to the partition. This option is only valid when used on partitioning schemes that support partition labels. .It Fl s Ar size Create a partition of size .Ar size . A SI unit suffix is allowed. .It Fl t Ar type Create a partition of type .Ar type . Partition types are discussed below in the section entitled .Sx "PARTITION TYPES" . .El .\" ==== BACKUP ==== .It Cm backup Dump a partition table to standard output in a special format used by the .Cm restore action. .\" ==== BOOTCODE ==== .It Cm bootcode Embed bootstrap code into the partitioning scheme's metadata on the .Ar geom (using .Fl b Ar bootcode ) or write bootstrap code into a partition (using .Fl p Ar partcode and .Fl i Ar index ) . .Pp The .Cm bootcode command accepts these options: .Bl -tag -width 10n +.It Fl N +Don't preserve the Volume Serial Number for MBR. +MBR bootcode contains Volume Serial Number by default, and +.Nm +tries to preserve it when installing new bootstrap code. +This option allows to skip the preservation to help with some versions of +.Xr boot0 8 +that don't support Volume Serial Number. .It Fl b Ar bootcode Embed bootstrap code from the file .Ar bootcode into the partitioning scheme's metadata for .Ar geom . Not all partitioning schemes have embedded bootstrap code, so the .Fl b Ar bootcode option is scheme-specific in nature (see the section entitled .Sx BOOTSTRAPPING below). The .Ar bootcode file must match the partitioning scheme's requirements for file content and size. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specify the target partition for .Fl p Ar partcode . .It Fl p Ar partcode Write the bootstrap code from the file .Ar partcode into the .Ar geom partition specified by .Fl i Ar index . The size of the file must be smaller than the size of the partition. .El .\" ==== COMMIT ==== .It Cm commit Commit any pending changes for geom .Ar geom . All actions are committed by default and will not result in pending changes. Actions can be modified with the .Fl f Ar flags option so that they are not committed, but become pending. Pending changes are reflected by the geom and the .Nm utility, but they are not actually written to disk. The .Cm commit action will write all pending changes to disk. .\" ==== CREATE ==== .It Cm create Create a new partitioning scheme on a provider given by .Ar provider . The scheme to use must be specified with the .Fl s Ar scheme option. .Pp The .Cm create command accepts these options: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl n Ar entries The number of entries in the partition table. Every partitioning scheme has a minimum and maximum number of entries. This option allows tables to be created with a number of entries that is within the limits. Some schemes have a maximum equal to the minimum and some schemes have a maximum large enough to be considered unlimited. By default, partition tables are created with the minimum number of entries. .It Fl s Ar scheme Specify the partitioning scheme to use. The kernel must have support for a particular scheme before that scheme can be used to partition a disk. .El .\" ==== DELETE ==== .It Cm delete Delete a partition from geom .Ar geom and further identified by the .Fl i Ar index option. The partition cannot be actively used by the kernel. .Pp The .cm delete command accepts these options: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specifies the index of the partition to be deleted. .El .\" ==== DESTROY ==== .It Cm destroy Destroy the partitioning scheme as implemented by geom .Ar geom . .Pp The .Cm destroy command accepts these options: .Bl -tag -width 10n .It Fl F Forced destroying of the partition table even if it is not empty. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== MODIFY ==== .It Cm modify Modify a partition from geom .Ar geom and further identified by the .Fl i Ar index option. Only the type and/or label of the partition can be modified. Not all partitioning schemes support labels and it is invalid to try to change a partition label in such cases. .Pp The .Cm modify command accepts these options: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specifies the index of the partition to be modified. .It Fl l Ar label Change the partition label to .Ar label . .It Fl t Ar type Change the partition type to .Ar type . .El .\" ==== RECOVER ==== .It Cm recover Recover a corrupt partition's scheme metadata on the geom .Ar geom . See the section entitled .Sx RECOVERING below for the additional information. .Pp The .Cm recover command accepts these options: .Bl -tag -width 10n .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .El .\" ==== RESIZE ==== .It Cm resize Resize a partition from geom .Ar geom and further identified by the .Fl i Ar index option. If the new size is not specified it is automatically calculated to be the maximum available from .Ar geom . .Pp The .Cm resize command accepts these options: .Bl -tag -width 12n .It Fl a Ar alignment If specified, then .Nm utility tries to align partition .Ar size to be a multiple of the .Ar alignment value. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specifies the index of the partition to be resized. .It Fl s Ar size Specifies the new size of the partition, in logical blocks. A SI unit suffix is allowed. .El .\" ==== RESTORE ==== .It Cm restore Restore the partition table from a backup previously created by the .Cm backup action and read from standard input. Only the partition table is restored. This action does not affect the content of partitions. After restoring the partition table and writing bootcode if needed, user data must be restored from backup. .Pp The .Cm restore command accepts these options: .Bl -tag -width 10n .It Fl F Destroy partition table on the given .Ar provider before doing restore. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl l Restore partition labels for partitioning schemes that support them. .El .\" ==== SET ==== .It Cm set Set the named attribute on the partition entry. See the section entitled .Sx ATTRIBUTES below for a list of available attributes. .Pp The .Cm set command accepts these options: .Bl -tag -width 10n .It Fl a Ar attrib Specifies the attribute to set. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specifies the index of the partition on which the attribute will be set. .El .\" ==== SHOW ==== .It Cm show Show current partition information for the specified geoms, or all geoms if none are specified. The default output includes the logical starting block of each partition, the partition size in blocks, the partition index number, the partition type, and a human readable partition size. Block sizes and locations are based on the device's Sectorsize as shown by .Cm gpart list . .Pp The .Cm show command accepts these options: .Bl -tag -width 10n .It Fl l For partitioning schemes that support partition labels, print them instead of partition type. .It Fl p Show provider names instead of partition indexes. .It Fl r Show raw partition type instead of symbolic name. .El .\" ==== UNDO ==== .It Cm undo Revert any pending changes for geom .Ar geom . This action is the opposite of the .Cm commit action and can be used to undo any changes that have not been committed. .\" ==== UNSET ==== .It Cm unset Clear the named attribute on the partition entry. See the section entitled .Sx ATTRIBUTES below for a list of available attributes. .Pp The .Cm unset command accepts these options: .Bl -tag -width 10n .It Fl a Ar attrib Specifies the attribute to clear. .It Fl f Ar flags Additional operational flags. See the section entitled .Sx "OPERATIONAL FLAGS" below for a discussion about its use. .It Fl i Ar index Specifies the index of the partition on which the attribute will be cleared. .El .It Cm list See .Xr geom 8 . .It Cm status See .Xr geom 8 . .It Cm load See .Xr geom 8 . .It Cm unload See .Xr geom 8 . .El .Sh PARTITIONING SCHEMES Several partitioning schemes are supported by the .Nm utility: .Bl -tag -width ".Cm VTOC8" .It Cm APM Apple Partition Map, used by PowerPC(R) Macintosh(R) computers. Requires the .Cd GEOM_PART_APM kernel option. .It Cm BSD Traditional BSD disklabel, usually used to subdivide MBR partitions. .Po This scheme can also be used as the sole partitioning method, without an MBR. Partition editing tools from other operating systems often do not understand the bare disklabel partition layout, so this is sometimes called .Dq dangerously dedicated . .Pc Requires the .Cm GEOM_PART_BSD kernel option. .It Cm BSD64 64-bit implementation of BSD disklabel used in DragonFlyBSD to subdivide MBR or GPT partitions. Requires the .Cm GEOM_PART_BSD64 kernel option. .It Cm LDM The Logical Disk Manager is an implementation of volume manager for Microsoft Windows NT. Requires the .Cd GEOM_PART_LDM kernel option. .It Cm GPT GUID Partition Table is used on Intel-based Macintosh computers and gradually replacing MBR on most PCs and other systems. Requires the .Cm GEOM_PART_GPT kernel option. .It Cm MBR Master Boot Record is used on PCs and removable media. Requires the .Cm GEOM_PART_MBR kernel option. The .Cm GEOM_PART_EBR option adds support for the Extended Boot Record (EBR), which is used to define a logical partition. The .Cm GEOM_PART_EBR_COMPAT option enables backward compatibility for partition names in the EBR scheme. It also prevents any type of actions on such partitions. .It Cm VTOC8 Sun's SMI Volume Table Of Contents, used by .Tn SPARC64 and .Tn UltraSPARC computers. Requires the .Cm GEOM_PART_VTOC8 kernel option. .El .Sh PARTITION TYPES Partition types are identified on disk by particular strings or magic values. The .Nm utility uses symbolic names for common partition types so the user does not need to know these values or other details of the partitioning scheme in question. The .Nm utility also allows the user to specify scheme-specific partition types for partition types that do not have symbolic names. Symbolic names currently understood and used by .Fx are: .Bl -tag -width ".Cm dragonfly-disklabel64" .It Cm apple-boot The system partition dedicated to storing boot loaders on some Apple systems. The scheme-specific types are .Qq Li "!171" for MBR, .Qq Li "!Apple_Bootstrap" for APM, and .Qq Li "!426f6f74-0000-11aa-aa11-00306543ecac" for GPT. .It Cm bios-boot The system partition dedicated to second stage of the boot loader program. Usually it is used by the GRUB 2 loader for GPT partitioning schemes. The scheme-specific type is .Qq Li "!21686148-6449-6E6F-744E-656564454649" . .It Cm efi The system partition for computers that use the Extensible Firmware Interface (EFI). The scheme-specific types are .Qq Li "!239" for MBR, and .Qq Li "!c12a7328-f81f-11d2-ba4b-00a0c93ec93b" for GPT. .It Cm freebsd A .Fx partition subdivided into filesystems with a .Bx disklabel. This is a legacy partition type and should not be used for the APM or GPT schemes. The scheme-specific types are .Qq Li "!165" for MBR, .Qq Li "!FreeBSD" for APM, and .Qq Li "!516e7cb4-6ecf-11d6-8ff8-00022d09712b" for GPT. .It Cm freebsd-boot A .Fx partition dedicated to bootstrap code. The scheme-specific type is .Qq Li "!83bd6b9d-7f41-11dc-be0b-001560b84f0f" for GPT. .It Cm freebsd-swap A .Fx partition dedicated to swap space. The scheme-specific types are .Qq Li "!FreeBSD-swap" for APM, .Qq Li "!516e7cb5-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0901 for VTOC8. .It Cm freebsd-ufs A .Fx partition that contains a UFS or UFS2 filesystem. The scheme-specific types are .Qq Li "!FreeBSD-UFS" for APM, .Qq Li "!516e7cb6-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0902 for VTOC8. .It Cm freebsd-vinum A .Fx partition that contains a Vinum volume. The scheme-specific types are .Qq Li "!FreeBSD-Vinum" for APM, .Qq Li "!516e7cb8-6ecf-11d6-8ff8-00022d09712b" for GPT, and tag 0x0903 for VTOC8. .It Cm freebsd-zfs A .Fx partition that contains a ZFS volume. The scheme-specific types are .Qq Li "!FreeBSD-ZFS" for APM, .Qq Li "!516e7cba-6ecf-11d6-8ff8-00022d09712b" for GPT, and 0x0904 for VTOC8. .El .Pp Another symbolic names that can be used with .Cm gpart utility are: .Bl -tag -width ".Cm dragonfly-disklabel64" .It Cm apple-apfs An Apple macOS partition used for the Apple file system, APFS. .It Cm apple-core-storage An Apple Mac OS X partition used by logical volume manager known as Core Storage. The scheme-specific type is .Qq Li "!53746f72-6167-11aa-aa11-00306543ecac" for GPT. .It Cm apple-hfs An Apple Mac OS X partition that contains a HFS or HFS+ filesystem. The scheme-specific types are .Qq Li "!175" for MBR, .Qq Li "!Apple_HFS" for APM and .Qq Li "!48465300-0000-11aa-aa11-00306543ecac" for GPT. .It Cm apple-label An Apple Mac OS X partition dedicated to partition metadata that descibes disk device. The scheme-specific type is .Qq Li "!4c616265-6c00-11aa-aa11-00306543ecac" for GPT. .It Cm apple-raid An Apple Mac OS X partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!52414944-0000-11aa-aa11-00306543ecac" for GPT. .It Cm apple-raid-offline An Apple Mac OS X partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!52414944-5f4f-11aa-aa11-00306543ecac" for GPT. .It Cm apple-tv-recovery An Apple Mac OS X partition used by Apple TV. The scheme-specific type is .Qq Li "!5265636f-7665-11aa-aa11-00306543ecac" for GPT. .It Cm apple-ufs An Apple Mac OS X partition that contains a UFS filesystem. The scheme-specific types are .Qq Li "!168" for MBR, .Qq Li "!Apple_UNIX_SVR2" for APM and .Qq Li "!55465300-0000-11aa-aa11-00306543ecac" for GPT. .It Cm dragonfly-label32 A DragonFlyBSD partition subdivided into filesystems with a .Bx disklabel. The scheme-specific type is .Qq Li "!9d087404-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-label64 A DragonFlyBSD partition subdivided into filesystems with a disklabel64. The scheme-specific type is .Qq Li "!3d48ce54-1d16-11dc-8696-01301bb8a9f5" for GPT. .It Cm dragonfly-legacy A legacy partition type used in DragonFlyBSD. The scheme-specific type is .Qq Li "!bd215ab2-1d16-11dc-8696-01301bb8a9f5" for GPT. .It Cm dragonfly-ccd A DragonFlyBSD partition used with Concatenated Disk driver. The scheme-specific type is .Qq Li "!dbd5211b-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-hammer A DragonFlyBSD partition that contains a Hammer filesystem. The scheme-specific type is .Qq Li "!61dc63ac-6e38-11dc-8513-01301bb8a9f5" for GPT. .It Cm dragonfly-hammer2 A DragonFlyBSD partition that contains a Hammer2 filesystem. The scheme-specific type is .Qq Li "!5cbb9ad1-862d-11dc-a94d-01301bb8a9f5" for GPT. .It Cm dragonfly-swap A DragonFlyBSD partition dedicated to swap space. The scheme-specific type is .Qq Li "!9d58fdbd-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-ufs A DragonFlyBSD partition that contains an UFS1 filesystem. The scheme-specific type is .Qq Li "!9d94ce7c-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm dragonfly-vinum A DragonFlyBSD partition used with Logical Volume Manager. The scheme-specific type is .Qq Li "!9dd4478f-1ca5-11dc-8817-01301bb8a9f5" for GPT. .It Cm ebr A partition subdivided into filesystems with a EBR. The scheme-specific type is .Qq Li "!5" for MBR. .It Cm fat16 A partition that contains a FAT16 filesystem. The scheme-specific type is .Qq Li "!6" for MBR. .It Cm fat32 A partition that contains a FAT32 filesystem. The scheme-specific type is .Qq Li "!11" for MBR. .It Cm fat32lba A partition that contains a FAT32 (LBA) filesystem. The scheme-specific type is .Qq Li "!12" for MBR. .It Cm linux-data A Linux partition that contains some filesystem with data. The scheme-specific types are .Qq Li "!131" for MBR and .Qq Li "!0fc63daf-8483-4772-8e79-3d69d8477de4" for GPT. .It Cm linux-lvm A Linux partition dedicated to Logical Volume Manager. The scheme-specific types are .Qq Li "!142" for MBR and .Qq Li "!e6d6d379-f507-44c2-a23c-238f2a3df928" for GPT. .It Cm linux-raid A Linux partition used in a software RAID configuration. The scheme-specific types are .Qq Li "!253" for MBR and .Qq Li "!a19d880f-05fc-4d3b-a006-743f0f84911e" for GPT. .It Cm linux-swap A Linux partition dedicated to swap space. The scheme-specific types are .Qq Li "!130" for MBR and .Qq Li "!0657fd6d-a4ab-43c4-84e5-0933c84b4f4f" for GPT. .It Cm mbr A partition that is sub-partitioned by a Master Boot Record (MBR). This type is known as .Qq Li "!024dee41-33e7-11d3-9d69-0008c781f39f" by GPT. .It Cm ms-basic-data A basic data partition (BDP) for Microsoft operating systems. In the GPT this type is the equivalent to partition types .Cm fat16 , fat32 and .Cm ntfs in MBR. The scheme-specific type is .Qq Li "!ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" for GPT. .It Cm ms-ldm-data A partition that contains Logical Disk Manager (LDM) volumes. The scheme-specific types are .Qq Li "!66" for MBR, .Qq Li "!af9b60a0-1431-4f62-bc68-3311714a69ad" for GPT. .It Cm ms-ldm-metadata A partition that contains Logical Disk Manager (LDM) database. The scheme-specific type is .Qq Li "!5808c8aa-7e8f-42e0-85d2-e1e90434cfb3" for GPT. .It Cm netbsd-ccd A NetBSD partition used with Concatenated Disk driver. The scheme-specific type is .Qq Li "!2db519c4-b10f-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-cgd An encrypted NetBSD partition. The scheme-specific type is .Qq Li "!2db519ec-b10f-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-ffs A NetBSD partition that contains an UFS filesystem. The scheme-specific type is .Qq Li "!49f48d5a-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-lfs A NetBSD partition that contains an LFS filesystem. The scheme-specific type is .Qq Li "!49f48d82-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-raid A NetBSD partition used in a software RAID configuration. The scheme-specific type is .Qq Li "!49f48daa-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm netbsd-swap A NetBSD partition dedicated to swap space. The scheme-specific type is .Qq Li "!49f48d32-b10e-11dc-b99b-0019d1879648" for GPT. .It Cm ntfs A partition that contains a NTFS or exFAT filesystem. The scheme-specific type is .Qq Li "!7" for MBR. .It Cm prep-boot The system partition dedicated to storing boot loaders on some PowerPC systems, notably those made by IBM. The scheme-specific types are .Qq Li "!65" for MBR and .Qq Li "!0x9e1a2d38-c612-4316-aa26-8b49521e5a8b" for GPT. .It Cm vmware-vmfs A partition that contains a VMware File System (VMFS). The scheme-specific types are .Qq Li "!251" for MBR and .Qq Li "!aa31e02a-400f-11db-9590-000c2911d1b8" for GPT. .It Cm vmware-vmkdiag A partition that contains a VMware diagostic filesystem. The scheme-specific types are .Qq Li "!252" for MBR and .Qq Li "!9d275380-40ad-11db-bf97-000c2911d1b8" for GPT. .It Cm vmware-reserved A VMware reserved partition. The scheme-specific type is .Qq Li "!9198effc-31c0-11db-8f-78-000c2911d1b8" for GPT. .It Cm vmware-vsanhdr A partition claimed by VMware VSAN. The scheme-specific type is .Qq Li "!381cfccc-7288-11e0-92ee-000c2911d0b2" for GPT. .El .Sh ATTRIBUTES The scheme-specific attributes for EBR: .Bl -tag -width ".Cm active" .It Cm active .El .Pp The scheme-specific attributes for GPT: .Bl -tag -width ".Cm bootfailed" .It Cm bootme When set, the .Nm gptboot stage 1 boot loader will try to boot the system from this partition. Multiple partitions can be marked with the .Cm bootme attribute. See .Xr gptboot 8 for more details. .It Cm bootonce Setting this attribute automatically sets the .Cm bootme attribute. When set, the .Nm gptboot stage 1 boot loader will try to boot the system from this partition only once. Multiple partitions can be marked with the .Cm bootonce and .Cm bootme attribute pairs. See .Xr gptboot 8 for more details. .It Cm bootfailed This attribute should not be manually managed. It is managed by the .Nm gptboot stage 1 boot loader and the .Pa /etc/rc.d/gptboot start-up script. See .Xr gptboot 8 for more details. .It Cm lenovofix Setting this attribute overwrites the Protective MBR with a new one where the 0xee partition is the second, rather than the first record. This resolves a BIOS compatibility issue with some Lenovo models including the X220, T420, and T520, allowing them to boot from GPT partitioned disks without using EFI. .El .Pp The scheme-specific attributes for MBR: .Bl -tag -width ".Cm active" .It Cm active .El .Sh BOOTSTRAPPING .Fx supports several partitioning schemes and each scheme uses different bootstrap code. The bootstrap code is located in a specific disk area for each partitioning scheme, and may vary in size for different schemes. .Pp Bootstrap code can be separated into two types. The first type is embedded in the partitioning scheme's metadata, while the second type is located on a specific partition. Embedding bootstrap code should only be done with the .Cm gpart bootcode command with the .Fl b Ar bootcode option. The GEOM PART class knows how to safely embed bootstrap code into specific partitioning scheme metadata without causing any damage. .Pp The Master Boot Record (MBR) uses a 512-byte bootstrap code image, embedded into the partition table's metadata area. There are two variants of this bootstrap code: .Pa /boot/mbr and .Pa /boot/boot0 . .Pa /boot/mbr searches for a partition with the .Cm active attribute (see the .Sx ATTRIBUTES section) in the partition table. Then it runs next bootstrap stage. The .Pa /boot/boot0 image contains a boot manager with some additional interactive functions for multi-booting from a user-selected partition. .Pp A BSD disklabel is usually created inside an MBR partition (slice) with type .Cm freebsd (see the .Sx "PARTITION TYPES" section). It uses 8 KB size bootstrap code image .Pa /boot/boot , embedded into the partition table's metadata area. .Pp Both types of bootstrap code are used to boot from the GUID Partition Table. First, a protective MBR is embedded into the first disk sector from the .Pa /boot/pmbr image. It searches through the GPT for a .Cm freebsd-boot partition (see the .Sx "PARTITION TYPES" section) and runs the next bootstrap stage from it. The .Cm freebsd-boot partition should be smaller than 545 KB. It can be located either before or after other .Fx partitions on the disk. There are two variants of bootstrap code to write to this partition: .Pa /boot/gptboot and .Pa /boot/gptzfsboot . .Pp .Pa /boot/gptboot is used to boot from UFS partitions. .Cm gptboot searches through .Cm freebsd-ufs partitions in the GPT and selects one to boot based on the .Cm bootonce and .Cm bootme attributes. If neither attribute is found, .Pa /boot/gptboot boots from the first .Cm freebsd-ufs partition. .Pa /boot/loader .Pq the third bootstrap stage is loaded from the first partition that matches these conditions. See .Xr gptboot 8 for more information. .Pp .Pa /boot/gptzfsboot is used to boot from ZFS. It searches through the GPT for .Cm freebsd-zfs partitions, trying to detect ZFS pools. After all pools are detected, .Pa /boot/loader is started from the first one found set as bootable. .Pp The VTOC8 scheme does not support embedding bootstrap code. Instead, the 8 KBytes bootstrap code image .Pa /boot/boot1 should be written with the .Cm gpart bootcode command with the .Fl p Ar bootcode option to all sufficiently large VTOC8 partitions. To do this the .Fl i Ar index option could be omitted. .Pp The APM scheme also does not support embedding bootstrap code. Instead, the 800 KBytes bootstrap code image .Pa /boot/boot1.hfs should be written with the .Cm gpart bootcode command to a partition of type .Cm apple-boot , which should also be 800 KB in size. .Sh OPERATIONAL FLAGS Actions other than the .Cm commit and .Cm undo actions take an optional .Fl f Ar flags option. This option is used to specify action-specific operational flags. By default, the .Nm utility defines the .Ql C flag so that the action is immediately committed. The user can specify .Dq Fl f Cm x to have the action result in a pending change that can later, with other pending changes, be committed as a single compound change with the .Cm commit action or reverted with the .Cm undo action. .Sh RECOVERING The GEOM PART class supports recovering of partition tables only for GPT. The GPT primary metadata is stored at the beginning of the device. For redundancy, a secondary .Pq backup copy of the metadata is stored at the end of the device. As a result of having two copies, some corruption of metadata is not fatal to the working of GPT. When the kernel detects corrupt metadata, it marks this table as corrupt and reports the problem. .Cm destroy and .Cm recover are the only operations allowed on corrupt tables. .Pp If one GPT header appears to be corrupt but the other copy remains intact, the kernel will log the following: .Bd -literal -offset indent GEOM: provider: the primary GPT table is corrupt or invalid. GEOM: provider: using the secondary instead -- recovery strongly advised. .Ed .Pp or .Bd -literal -offset indent GEOM: provider: the secondary GPT table is corrupt or invalid. GEOM: provider: using the primary only -- recovery suggested. .Ed .Pp Also .Nm commands such as .Cm show , status and .Cm list will report about corrupt tables. .Pp If the size of the device has changed (e.g.,\& volume expansion) the secondary GPT header will no longer be located in the last sector. This is not a metadata corruption, but it is dangerous because any corruption of the primary GPT will lead to loss of the partition table. This problem is reported by the kernel with the message: .Bd -literal -offset indent GEOM: provider: the secondary GPT header is not in the last LBA. .Ed .Pp This situation can be recovered with the .Cm recover command. This command reconstructs the corrupt metadata using known valid metadata and relocates the secondary GPT to the end of the device. .Pp .Em NOTE : The GEOM PART class can detect the same partition table visible through different GEOM providers, and some of them will be marked as corrupt. Be careful when choosing a provider for recovery. If you choose incorrectly you can destroy the metadata of another GEOM class, e.g.,\& GEOM MIRROR or GEOM LABEL. .Sh SYSCTL VARIABLES The following .Xr sysctl 8 variables can be used to control the behavior of the .Nm PART GEOM class. The default value is shown next to each variable. .Bl -tag -width indent .It Va kern.geom.part.auto_resize: No 1 This variable controls automatic resize behavior of .Nm GEOM class. When this variable is enable and new size of provider is detected, the schema metadata is resized but all changes are not saved to disk, until .Cm gpart commit is run to confirm changes. This behavior is also reported with diagnostic message: .Sy "GEOM_PART: (provider) was automatically resized." .Sy "Use `gpart commit (provider)` to save changes or `gpart undo (provider)`" .Sy "to revert them." .It Va kern.geom.part.check_integrity : No 1 This variable controls the behaviour of metadata integrity checks. When integrity checks are enabled, the .Nm PART GEOM class verifies all generic partition parameters obtained from the disk metadata. If some inconsistency is detected, the partition table will be rejected with a diagnostic message: .Sy "GEOM_PART: Integrity check failed (provider, scheme)" . .It Va kern.geom.part.ldm.debug : No 0 Debug level of the Logical Disk Manager (LDM) module. This can be set to a number between 0 and 2 inclusive. If set to 0 minimal debug information is printed, and if set to 2 the maximum amount of debug information is printed. .It Va kern.geom.part.ldm.show_mirrors : No 0 This variable controls how the Logical Disk Manager (LDM) module handles mirrored volumes. By default mirrored volumes are shown as partitions with type .Cm ms-ldm-data (see the .Sx "PARTITION TYPES" section). If this variable set to 1 each component of the mirrored volume will be present as independent partition. .Em NOTE : This may break a mirrored volume and lead to data damage. .It Va kern.geom.part.mbr.enforce_chs : No 0 Specify how the Master Boot Record (MBR) module does alignment. If this variable is set to a non-zero value, the module will automatically recalculate the user-specified offset and size for alignment with the CHS geometry. Otherwise the values will be left unchanged. .El .Sh EXIT STATUS Exit status is 0 on success, and 1 if the command fails. .Sh EXAMPLES The examples below assume that the disk's logical block size is 512 bytes, regardless of its physical block size. .Ss GPT In this example, we will format .Pa ada0 with the GPT scheme and create boot, swap and root partitions. First, we need to create the partition table: .Bd -literal -offset indent /sbin/gpart create -s GPT ada0 .Ed .Pp Next, we install a protective MBR with the first-stage bootstrap code. The protective MBR lists a single, bootable partition spanning the entire disk, thus allowing non-GPT-aware BIOSes to boot from the disk and preventing tools which do not understand the GPT scheme from considering the disk to be unformatted. .Bd -literal -offset indent /sbin/gpart bootcode -b /boot/pmbr ada0 .Ed .Pp We then create a dedicated .Cm freebsd-boot partition to hold the second-stage boot loader, which will load the .Fx kernel and modules from a UFS or ZFS filesystem. This partition must be larger than the bootstrap code .Po either .Pa /boot/gptboot for UFS or .Pa /boot/gptzfsboot for ZFS .Pc , but smaller than 545 kB since the first-stage loader will load the entire partition into memory during boot, regardless of how much data it actually contains. We create a 472-block (236 kB) boot partition at offset 40, which is the size of the partition table (34 blocks or 17 kB) rounded up to the nearest 4 kB boundary. .Bd -literal -offset indent /sbin/gpart add -b 40 -s 472 -t freebsd-boot ada0 /sbin/gpart bootcode -p /boot/gptboot -i 1 ada0 .Ed .Pp We now create a 4 GB swap partition at the first available offset, which is 40 + 472 = 512 blocks (256 kB). .Bd -literal -offset indent /sbin/gpart add -s 4G -t freebsd-swap ada0 .Ed .Pp Aligning the swap partition and all subsequent partitions on a 256 kB boundary ensures optimal performance on a wide range of media, from plain old disks with 512-byte blocks, through modern .Dq advanced format disks with 4096-byte physical blocks, to RAID volumes with stripe sizes of up to 256 kB. .Pp Finally, we create and format an 8 GB .Cm freebsd-ufs partition for the root filesystem, leaving the rest of the slice free for additional filesystems: .Bd -literal -offset indent /sbin/gpart add -s 8G -t freebsd-ufs ada0 /sbin/newfs -Uj /dev/ada0p3 .Ed .Ss MBR In this example, we will format .Pa ada0 with the MBR scheme and create a single partition which we subdivide using a traditional .Bx disklabel. .Pp First, we create the partition table and a single 64 GB partition, then we mark that partition active (bootable) and install the first-stage boot loader: .Bd -literal -offset indent /sbin/gpart create -s MBR ada0 /sbin/gpart add -t freebsd -s 64G ada0 /sbin/gpart set -a active -i 1 ada0 /sbin/gpart bootcode -b /boot/boot0 ada0 .Ed .Pp Next, we create a disklabel in that partition .Po .Dq slice in disklabel terminology .Pc with room for up to 20 partitions: .Bd -literal -offset indent /sbin/gpart create -s BSD -n 20 ada0s1 .Ed .Pp We then create an 8 GB root partition and a 4 GB swap partition: .Bd -literal -offset indent /sbin/gpart add -t freebsd-ufs -s 8G ada0s1 /sbin/gpart add -t freebsd-swap -s 4G ada0s1 .Ed .Pp Finally, we install the appropriate boot loader for the .Bx label: .Bd -literal -offset indent /sbin/gpart bootcode -b /boot/boot ada0s1 .Ed .Ss VTOC8 .Pp Create a VTOC8 scheme on .Pa da0 : .Bd -literal -offset indent /sbin/gpart create -s VTOC8 da0 .Ed .Pp Create a 512MB-sized .Cm freebsd-ufs partition to contain a UFS filesystem from which the system can boot. .Bd -literal -offset indent /sbin/gpart add -s 512M -t freebsd-ufs da0 .Ed .Pp Create a 15GB-sized .Cm freebsd-ufs partition to contain a UFS filesystem and aligned on 4KB boundaries: .Bd -literal -offset indent /sbin/gpart add -s 15G -t freebsd-ufs -a 4k da0 .Ed .Pp After creating all required partitions, embed bootstrap code into them: .Bd -literal -offset indent /sbin/gpart bootcode -p /boot/boot1 da0 .Ed .Ss Deleting Partitions and Destroying the Partitioning Scheme If a .Em "Device busy" error is shown when trying to destroy a partition table, remember that all of the partitions must be deleted first with the .Cm delete action. In this example, .Pa da0 has three partitions: .Bd -literal -offset indent /sbin/gpart delete -i 3 da0 /sbin/gpart delete -i 2 da0 /sbin/gpart delete -i 1 da0 /sbin/gpart destroy da0 .Ed .Pp Rather than deleting each partition and then destroying the partitioning scheme, the .Fl F option can be given with .Cm destroy to delete all of the partitions before destroying the partitioning scheme. This is equivalent to the previous example: .Bd -literal -offset indent /sbin/gpart destroy -F da0 .Ed .Ss Backup and Restore .Pp Create a backup of the partition table from .Pa da0 : .Bd -literal -offset indent /sbin/gpart backup da0 > da0.backup .Ed .Pp Restore the partition table from the backup to .Pa da0 : .Bd -literal -offset indent /sbin/gpart restore -l da0 < /mnt/da0.backup .Ed .Pp Clone the partition table from .Pa ada0 to .Pa ada1 and .Pa ada2 : .Bd -literal -offset indent /sbin/gpart backup ada0 | /sbin/gpart restore -F ada1 ada2 .Ed .Sh SEE ALSO .Xr geom 4 , .Xr boot0cfg 8 , .Xr geom 8 , .Xr gptboot 8 .Sh HISTORY The .Nm utility appeared in .Fx 7.0 . .Sh AUTHORS .An Marcel Moolenaar Aq Mt marcel@FreeBSD.org Index: head/sys/geom/part/g_part.c =================================================================== --- head/sys/geom/part/g_part.c (revision 341066) +++ head/sys/geom/part/g_part.c (revision 341067) @@ -1,2414 +1,2421 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2002, 2005-2009 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 AUTHOR ``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 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 "g_part_if.h" #ifndef _PATH_DEV #define _PATH_DEV "/dev/" #endif static kobj_method_t g_part_null_methods[] = { { 0, 0 } }; static struct g_part_scheme g_part_null_scheme = { "(none)", g_part_null_methods, sizeof(struct g_part_table), }; TAILQ_HEAD(, g_part_scheme) g_part_schemes = TAILQ_HEAD_INITIALIZER(g_part_schemes); struct g_part_alias_list { const char *lexeme; enum g_part_alias alias; } g_part_alias_list[G_PART_ALIAS_COUNT] = { { "apple-apfs", G_PART_ALIAS_APPLE_APFS }, { "apple-boot", G_PART_ALIAS_APPLE_BOOT }, { "apple-core-storage", G_PART_ALIAS_APPLE_CORE_STORAGE }, { "apple-hfs", G_PART_ALIAS_APPLE_HFS }, { "apple-label", G_PART_ALIAS_APPLE_LABEL }, { "apple-raid", G_PART_ALIAS_APPLE_RAID }, { "apple-raid-offline", G_PART_ALIAS_APPLE_RAID_OFFLINE }, { "apple-tv-recovery", G_PART_ALIAS_APPLE_TV_RECOVERY }, { "apple-ufs", G_PART_ALIAS_APPLE_UFS }, { "bios-boot", G_PART_ALIAS_BIOS_BOOT }, { "chromeos-firmware", G_PART_ALIAS_CHROMEOS_FIRMWARE }, { "chromeos-kernel", G_PART_ALIAS_CHROMEOS_KERNEL }, { "chromeos-reserved", G_PART_ALIAS_CHROMEOS_RESERVED }, { "chromeos-root", G_PART_ALIAS_CHROMEOS_ROOT }, { "dragonfly-ccd", G_PART_ALIAS_DFBSD_CCD }, { "dragonfly-hammer", G_PART_ALIAS_DFBSD_HAMMER }, { "dragonfly-hammer2", G_PART_ALIAS_DFBSD_HAMMER2 }, { "dragonfly-label32", G_PART_ALIAS_DFBSD }, { "dragonfly-label64", G_PART_ALIAS_DFBSD64 }, { "dragonfly-legacy", G_PART_ALIAS_DFBSD_LEGACY }, { "dragonfly-swap", G_PART_ALIAS_DFBSD_SWAP }, { "dragonfly-ufs", G_PART_ALIAS_DFBSD_UFS }, { "dragonfly-vinum", G_PART_ALIAS_DFBSD_VINUM }, { "ebr", G_PART_ALIAS_EBR }, { "efi", G_PART_ALIAS_EFI }, { "fat16", G_PART_ALIAS_MS_FAT16 }, { "fat32", G_PART_ALIAS_MS_FAT32 }, { "fat32lba", G_PART_ALIAS_MS_FAT32LBA }, { "freebsd", G_PART_ALIAS_FREEBSD }, { "freebsd-boot", G_PART_ALIAS_FREEBSD_BOOT }, { "freebsd-nandfs", G_PART_ALIAS_FREEBSD_NANDFS }, { "freebsd-swap", G_PART_ALIAS_FREEBSD_SWAP }, { "freebsd-ufs", G_PART_ALIAS_FREEBSD_UFS }, { "freebsd-vinum", G_PART_ALIAS_FREEBSD_VINUM }, { "freebsd-zfs", G_PART_ALIAS_FREEBSD_ZFS }, { "linux-data", G_PART_ALIAS_LINUX_DATA }, { "linux-lvm", G_PART_ALIAS_LINUX_LVM }, { "linux-raid", G_PART_ALIAS_LINUX_RAID }, { "linux-swap", G_PART_ALIAS_LINUX_SWAP }, { "mbr", G_PART_ALIAS_MBR }, { "ms-basic-data", G_PART_ALIAS_MS_BASIC_DATA }, { "ms-ldm-data", G_PART_ALIAS_MS_LDM_DATA }, { "ms-ldm-metadata", G_PART_ALIAS_MS_LDM_METADATA }, { "ms-recovery", G_PART_ALIAS_MS_RECOVERY }, { "ms-reserved", G_PART_ALIAS_MS_RESERVED }, { "ms-spaces", G_PART_ALIAS_MS_SPACES }, { "netbsd-ccd", G_PART_ALIAS_NETBSD_CCD }, { "netbsd-cgd", G_PART_ALIAS_NETBSD_CGD }, { "netbsd-ffs", G_PART_ALIAS_NETBSD_FFS }, { "netbsd-lfs", G_PART_ALIAS_NETBSD_LFS }, { "netbsd-raid", G_PART_ALIAS_NETBSD_RAID }, { "netbsd-swap", G_PART_ALIAS_NETBSD_SWAP }, { "ntfs", G_PART_ALIAS_MS_NTFS }, { "openbsd-data", G_PART_ALIAS_OPENBSD_DATA }, { "prep-boot", G_PART_ALIAS_PREP_BOOT }, { "vmware-reserved", G_PART_ALIAS_VMRESERVED }, { "vmware-vmfs", G_PART_ALIAS_VMFS }, { "vmware-vmkdiag", G_PART_ALIAS_VMKDIAG }, { "vmware-vsanhdr", G_PART_ALIAS_VMVSANHDR }, }; SYSCTL_DECL(_kern_geom); SYSCTL_NODE(_kern_geom, OID_AUTO, part, CTLFLAG_RW, 0, "GEOM_PART stuff"); static u_int check_integrity = 1; SYSCTL_UINT(_kern_geom_part, OID_AUTO, check_integrity, CTLFLAG_RWTUN, &check_integrity, 1, "Enable integrity checking"); static u_int auto_resize = 1; SYSCTL_UINT(_kern_geom_part, OID_AUTO, auto_resize, CTLFLAG_RWTUN, &auto_resize, 1, "Enable auto resize"); /* * The GEOM partitioning class. */ static g_ctl_req_t g_part_ctlreq; static g_ctl_destroy_geom_t g_part_destroy_geom; static g_fini_t g_part_fini; static g_init_t g_part_init; static g_taste_t g_part_taste; static g_access_t g_part_access; static g_dumpconf_t g_part_dumpconf; static g_orphan_t g_part_orphan; static g_spoiled_t g_part_spoiled; static g_start_t g_part_start; static g_resize_t g_part_resize; static g_ioctl_t g_part_ioctl; static struct g_class g_part_class = { .name = "PART", .version = G_VERSION, /* Class methods. */ .ctlreq = g_part_ctlreq, .destroy_geom = g_part_destroy_geom, .fini = g_part_fini, .init = g_part_init, .taste = g_part_taste, /* Geom methods. */ .access = g_part_access, .dumpconf = g_part_dumpconf, .orphan = g_part_orphan, .spoiled = g_part_spoiled, .start = g_part_start, .resize = g_part_resize, .ioctl = g_part_ioctl, }; DECLARE_GEOM_CLASS(g_part_class, g_part); MODULE_VERSION(g_part, 0); /* * Support functions. */ static void g_part_wither(struct g_geom *, int); const char * g_part_alias_name(enum g_part_alias alias) { int i; for (i = 0; i < G_PART_ALIAS_COUNT; i++) { if (g_part_alias_list[i].alias != alias) continue; return (g_part_alias_list[i].lexeme); } return (NULL); } void g_part_geometry_heads(off_t blocks, u_int sectors, off_t *bestchs, u_int *bestheads) { static u_int candidate_heads[] = { 1, 2, 16, 32, 64, 128, 255, 0 }; off_t chs, cylinders; u_int heads; int idx; *bestchs = 0; *bestheads = 0; for (idx = 0; candidate_heads[idx] != 0; idx++) { heads = candidate_heads[idx]; cylinders = blocks / heads / sectors; if (cylinders < heads || cylinders < sectors) break; if (cylinders > 1023) continue; chs = cylinders * heads * sectors; if (chs > *bestchs || (chs == *bestchs && *bestheads == 1)) { *bestchs = chs; *bestheads = heads; } } } static void g_part_geometry(struct g_part_table *table, struct g_consumer *cp, off_t blocks) { static u_int candidate_sectors[] = { 1, 9, 17, 33, 63, 0 }; off_t chs, bestchs; u_int heads, sectors; int idx; if (g_getattr("GEOM::fwsectors", cp, §ors) != 0 || sectors == 0 || g_getattr("GEOM::fwheads", cp, &heads) != 0 || heads == 0) { table->gpt_fixgeom = 0; table->gpt_heads = 0; table->gpt_sectors = 0; bestchs = 0; for (idx = 0; candidate_sectors[idx] != 0; idx++) { sectors = candidate_sectors[idx]; g_part_geometry_heads(blocks, sectors, &chs, &heads); if (chs == 0) continue; /* * Prefer a geometry with sectors > 1, but only if * it doesn't bump down the number of heads to 1. */ if (chs > bestchs || (chs == bestchs && heads > 1 && table->gpt_sectors == 1)) { bestchs = chs; table->gpt_heads = heads; table->gpt_sectors = sectors; } } /* * If we didn't find a geometry at all, then the disk is * too big. This means we can use the maximum number of * heads and sectors. */ if (bestchs == 0) { table->gpt_heads = 255; table->gpt_sectors = 63; } } else { table->gpt_fixgeom = 1; table->gpt_heads = heads; table->gpt_sectors = sectors; } } static void g_part_get_physpath_done(struct bio *bp) { struct g_geom *gp; struct g_part_entry *entry; struct g_part_table *table; struct g_provider *pp; struct bio *pbp; pbp = bp->bio_parent; pp = pbp->bio_to; gp = pp->geom; table = gp->softc; entry = pp->private; if (bp->bio_error == 0) { char *end; size_t len, remainder; len = strlcat(bp->bio_data, "/", bp->bio_length); if (len < bp->bio_length) { end = bp->bio_data + len; remainder = bp->bio_length - len; G_PART_NAME(table, entry, end, remainder); } } g_std_done(bp); } #define DPRINTF(...) if (bootverbose) { \ printf("GEOM_PART: " __VA_ARGS__); \ } static int g_part_check_integrity(struct g_part_table *table, struct g_consumer *cp) { struct g_part_entry *e1, *e2; struct g_provider *pp; off_t offset; int failed; failed = 0; pp = cp->provider; if (table->gpt_last < table->gpt_first) { DPRINTF("last LBA is below first LBA: %jd < %jd\n", (intmax_t)table->gpt_last, (intmax_t)table->gpt_first); failed++; } if (table->gpt_last > pp->mediasize / pp->sectorsize - 1) { DPRINTF("last LBA extends beyond mediasize: " "%jd > %jd\n", (intmax_t)table->gpt_last, (intmax_t)pp->mediasize / pp->sectorsize - 1); failed++; } LIST_FOREACH(e1, &table->gpt_entry, gpe_entry) { if (e1->gpe_deleted || e1->gpe_internal) continue; if (e1->gpe_start < table->gpt_first) { DPRINTF("partition %d has start offset below first " "LBA: %jd < %jd\n", e1->gpe_index, (intmax_t)e1->gpe_start, (intmax_t)table->gpt_first); failed++; } if (e1->gpe_start > table->gpt_last) { DPRINTF("partition %d has start offset beyond last " "LBA: %jd > %jd\n", e1->gpe_index, (intmax_t)e1->gpe_start, (intmax_t)table->gpt_last); failed++; } if (e1->gpe_end < e1->gpe_start) { DPRINTF("partition %d has end offset below start " "offset: %jd < %jd\n", e1->gpe_index, (intmax_t)e1->gpe_end, (intmax_t)e1->gpe_start); failed++; } if (e1->gpe_end > table->gpt_last) { DPRINTF("partition %d has end offset beyond last " "LBA: %jd > %jd\n", e1->gpe_index, (intmax_t)e1->gpe_end, (intmax_t)table->gpt_last); failed++; } if (pp->stripesize > 0) { offset = e1->gpe_start * pp->sectorsize; if (e1->gpe_offset > offset) offset = e1->gpe_offset; if ((offset + pp->stripeoffset) % pp->stripesize) { DPRINTF("partition %d on (%s, %s) is not " "aligned on %ju bytes\n", e1->gpe_index, pp->name, table->gpt_scheme->name, (uintmax_t)pp->stripesize); /* Don't treat this as a critical failure */ } } e2 = e1; while ((e2 = LIST_NEXT(e2, gpe_entry)) != NULL) { if (e2->gpe_deleted || e2->gpe_internal) continue; if (e1->gpe_start >= e2->gpe_start && e1->gpe_start <= e2->gpe_end) { DPRINTF("partition %d has start offset inside " "partition %d: start[%d] %jd >= start[%d] " "%jd <= end[%d] %jd\n", e1->gpe_index, e2->gpe_index, e2->gpe_index, (intmax_t)e2->gpe_start, e1->gpe_index, (intmax_t)e1->gpe_start, e2->gpe_index, (intmax_t)e2->gpe_end); failed++; } if (e1->gpe_end >= e2->gpe_start && e1->gpe_end <= e2->gpe_end) { DPRINTF("partition %d has end offset inside " "partition %d: start[%d] %jd >= end[%d] " "%jd <= end[%d] %jd\n", e1->gpe_index, e2->gpe_index, e2->gpe_index, (intmax_t)e2->gpe_start, e1->gpe_index, (intmax_t)e1->gpe_end, e2->gpe_index, (intmax_t)e2->gpe_end); failed++; } if (e1->gpe_start < e2->gpe_start && e1->gpe_end > e2->gpe_end) { DPRINTF("partition %d contains partition %d: " "start[%d] %jd > start[%d] %jd, end[%d] " "%jd < end[%d] %jd\n", e1->gpe_index, e2->gpe_index, e1->gpe_index, (intmax_t)e1->gpe_start, e2->gpe_index, (intmax_t)e2->gpe_start, e2->gpe_index, (intmax_t)e2->gpe_end, e1->gpe_index, (intmax_t)e1->gpe_end); failed++; } } } if (failed != 0) { printf("GEOM_PART: integrity check failed (%s, %s)\n", pp->name, table->gpt_scheme->name); if (check_integrity != 0) return (EINVAL); table->gpt_corrupt = 1; } return (0); } #undef DPRINTF struct g_part_entry * g_part_new_entry(struct g_part_table *table, int index, quad_t start, quad_t end) { struct g_part_entry *entry, *last; last = NULL; LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_index == index) break; if (entry->gpe_index > index) { entry = NULL; break; } last = entry; } if (entry == NULL) { entry = g_malloc(table->gpt_scheme->gps_entrysz, M_WAITOK | M_ZERO); entry->gpe_index = index; if (last == NULL) LIST_INSERT_HEAD(&table->gpt_entry, entry, gpe_entry); else LIST_INSERT_AFTER(last, entry, gpe_entry); } else entry->gpe_offset = 0; entry->gpe_start = start; entry->gpe_end = end; return (entry); } static void g_part_new_provider(struct g_geom *gp, struct g_part_table *table, struct g_part_entry *entry) { struct g_consumer *cp; struct g_provider *pp; struct sbuf *sb; struct g_geom_alias *gap; off_t offset; cp = LIST_FIRST(&gp->consumer); pp = cp->provider; offset = entry->gpe_start * pp->sectorsize; if (entry->gpe_offset < offset) entry->gpe_offset = offset; if (entry->gpe_pp == NULL) { /* * Add aliases to the geom before we create the provider so that * geom_dev can taste it with all the aliases in place so all * the aliased dev_t instances get created for each partition * (eg foo5p7 gets created for bar5p7 when foo is an alias of bar). */ LIST_FOREACH(gap, &table->gpt_gp->aliases, ga_next) { sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gap->ga_alias); sbuf_finish(sb); g_geom_add_alias(gp, sbuf_data(sb)); sbuf_delete(sb); } sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gp->name); sbuf_finish(sb); entry->gpe_pp = g_new_providerf(gp, "%s", sbuf_data(sb)); sbuf_delete(sb); entry->gpe_pp->flags |= G_PF_DIRECT_SEND | G_PF_DIRECT_RECEIVE; entry->gpe_pp->private = entry; /* Close the circle. */ } entry->gpe_pp->index = entry->gpe_index - 1; /* index is 1-based. */ entry->gpe_pp->mediasize = (entry->gpe_end - entry->gpe_start + 1) * pp->sectorsize; entry->gpe_pp->mediasize -= entry->gpe_offset - offset; entry->gpe_pp->sectorsize = pp->sectorsize; entry->gpe_pp->stripesize = pp->stripesize; entry->gpe_pp->stripeoffset = pp->stripeoffset + entry->gpe_offset; if (pp->stripesize > 0) entry->gpe_pp->stripeoffset %= pp->stripesize; entry->gpe_pp->flags |= pp->flags & G_PF_ACCEPT_UNMAPPED; g_error_provider(entry->gpe_pp, 0); } static struct g_geom* g_part_find_geom(const char *name) { struct g_geom *gp; LIST_FOREACH(gp, &g_part_class.geom, geom) { if ((gp->flags & G_GEOM_WITHER) == 0 && strcmp(name, gp->name) == 0) break; } return (gp); } static int g_part_parm_geom(struct gctl_req *req, const char *name, struct g_geom **v) { struct g_geom *gp; const char *gname; gname = gctl_get_asciiparam(req, name); if (gname == NULL) return (ENOATTR); if (strncmp(gname, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) gname += sizeof(_PATH_DEV) - 1; gp = g_part_find_geom(gname); if (gp == NULL) { gctl_error(req, "%d %s '%s'", EINVAL, name, gname); return (EINVAL); } *v = gp; return (0); } static int g_part_parm_provider(struct gctl_req *req, const char *name, struct g_provider **v) { struct g_provider *pp; const char *pname; pname = gctl_get_asciiparam(req, name); if (pname == NULL) return (ENOATTR); if (strncmp(pname, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0) pname += sizeof(_PATH_DEV) - 1; pp = g_provider_by_name(pname); if (pp == NULL) { gctl_error(req, "%d %s '%s'", EINVAL, name, pname); return (EINVAL); } *v = pp; return (0); } static int g_part_parm_quad(struct gctl_req *req, const char *name, quad_t *v) { const char *p; char *x; quad_t q; p = gctl_get_asciiparam(req, name); if (p == NULL) return (ENOATTR); q = strtoq(p, &x, 0); if (*x != '\0' || q < 0) { gctl_error(req, "%d %s '%s'", EINVAL, name, p); return (EINVAL); } *v = q; return (0); } static int g_part_parm_scheme(struct gctl_req *req, const char *name, struct g_part_scheme **v) { struct g_part_scheme *s; const char *p; p = gctl_get_asciiparam(req, name); if (p == NULL) return (ENOATTR); TAILQ_FOREACH(s, &g_part_schemes, scheme_list) { if (s == &g_part_null_scheme) continue; if (!strcasecmp(s->name, p)) break; } if (s == NULL) { gctl_error(req, "%d %s '%s'", EINVAL, name, p); return (EINVAL); } *v = s; return (0); } static int g_part_parm_str(struct gctl_req *req, const char *name, const char **v) { const char *p; p = gctl_get_asciiparam(req, name); if (p == NULL) return (ENOATTR); /* An empty label is always valid. */ if (strcmp(name, "label") != 0 && p[0] == '\0') { gctl_error(req, "%d %s '%s'", EINVAL, name, p); return (EINVAL); } *v = p; return (0); } static int g_part_parm_intmax(struct gctl_req *req, const char *name, u_int *v) { const intmax_t *p; int size; p = gctl_get_param(req, name, &size); if (p == NULL) return (ENOATTR); if (size != sizeof(*p) || *p < 0 || *p > INT_MAX) { gctl_error(req, "%d %s '%jd'", EINVAL, name, *p); return (EINVAL); } *v = (u_int)*p; return (0); } static int g_part_parm_uint32(struct gctl_req *req, const char *name, u_int *v) { const uint32_t *p; int size; p = gctl_get_param(req, name, &size); if (p == NULL) return (ENOATTR); if (size != sizeof(*p) || *p > INT_MAX) { gctl_error(req, "%d %s '%u'", EINVAL, name, (unsigned int)*p); return (EINVAL); } *v = (u_int)*p; return (0); } static int g_part_parm_bootcode(struct gctl_req *req, const char *name, const void **v, unsigned int *s) { const void *p; int size; p = gctl_get_param(req, name, &size); if (p == NULL) return (ENOATTR); *v = p; *s = size; return (0); } static int g_part_probe(struct g_geom *gp, struct g_consumer *cp, int depth) { struct g_part_scheme *iter, *scheme; struct g_part_table *table; int pri, probe; table = gp->softc; scheme = (table != NULL) ? table->gpt_scheme : NULL; pri = (scheme != NULL) ? G_PART_PROBE(table, cp) : INT_MIN; if (pri == 0) goto done; if (pri > 0) { /* error */ scheme = NULL; pri = INT_MIN; } TAILQ_FOREACH(iter, &g_part_schemes, scheme_list) { if (iter == &g_part_null_scheme) continue; table = (void *)kobj_create((kobj_class_t)iter, M_GEOM, M_WAITOK); table->gpt_gp = gp; table->gpt_scheme = iter; table->gpt_depth = depth; probe = G_PART_PROBE(table, cp); if (probe <= 0 && probe > pri) { pri = probe; scheme = iter; if (gp->softc != NULL) kobj_delete((kobj_t)gp->softc, M_GEOM); gp->softc = table; if (pri == 0) goto done; } else kobj_delete((kobj_t)table, M_GEOM); } done: return ((scheme == NULL) ? ENXIO : 0); } /* * Control request functions. */ static int g_part_ctl_add(struct gctl_req *req, struct g_part_parms *gpp) { struct g_geom *gp; struct g_provider *pp; struct g_part_entry *delent, *last, *entry; struct g_part_table *table; struct sbuf *sb; quad_t end; unsigned int index; int error; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); pp = LIST_FIRST(&gp->consumer)->provider; table = gp->softc; end = gpp->gpp_start + gpp->gpp_size - 1; if (gpp->gpp_start < table->gpt_first || gpp->gpp_start > table->gpt_last) { gctl_error(req, "%d start '%jd'", EINVAL, (intmax_t)gpp->gpp_start); return (EINVAL); } if (end < gpp->gpp_start || end > table->gpt_last) { gctl_error(req, "%d size '%jd'", EINVAL, (intmax_t)gpp->gpp_size); return (EINVAL); } if (gpp->gpp_index > table->gpt_entries) { gctl_error(req, "%d index '%d'", EINVAL, gpp->gpp_index); return (EINVAL); } delent = last = NULL; index = (gpp->gpp_index > 0) ? gpp->gpp_index : 1; LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted) { if (entry->gpe_index == index) delent = entry; continue; } if (entry->gpe_index == index) index = entry->gpe_index + 1; if (entry->gpe_index < index) last = entry; if (entry->gpe_internal) continue; if (gpp->gpp_start >= entry->gpe_start && gpp->gpp_start <= entry->gpe_end) { gctl_error(req, "%d start '%jd'", ENOSPC, (intmax_t)gpp->gpp_start); return (ENOSPC); } if (end >= entry->gpe_start && end <= entry->gpe_end) { gctl_error(req, "%d end '%jd'", ENOSPC, (intmax_t)end); return (ENOSPC); } if (gpp->gpp_start < entry->gpe_start && end > entry->gpe_end) { gctl_error(req, "%d size '%jd'", ENOSPC, (intmax_t)gpp->gpp_size); return (ENOSPC); } } if (gpp->gpp_index > 0 && index != gpp->gpp_index) { gctl_error(req, "%d index '%d'", EEXIST, gpp->gpp_index); return (EEXIST); } if (index > table->gpt_entries) { gctl_error(req, "%d index '%d'", ENOSPC, index); return (ENOSPC); } entry = (delent == NULL) ? g_malloc(table->gpt_scheme->gps_entrysz, M_WAITOK | M_ZERO) : delent; entry->gpe_index = index; entry->gpe_start = gpp->gpp_start; entry->gpe_end = end; error = G_PART_ADD(table, entry, gpp); if (error) { gctl_error(req, "%d", error); if (delent == NULL) g_free(entry); return (error); } if (delent == NULL) { if (last == NULL) LIST_INSERT_HEAD(&table->gpt_entry, entry, gpe_entry); else LIST_INSERT_AFTER(last, entry, gpe_entry); entry->gpe_created = 1; } else { entry->gpe_deleted = 0; entry->gpe_modified = 1; } g_part_new_provider(gp, table, entry); /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gp->name); if (pp->stripesize > 0 && entry->gpe_pp->stripeoffset != 0) sbuf_printf(sb, " added, but partition is not " "aligned on %ju bytes\n", (uintmax_t)pp->stripesize); else sbuf_cat(sb, " added\n"); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_bootcode(struct gctl_req *req, struct g_part_parms *gpp) { struct g_geom *gp; struct g_part_table *table; struct sbuf *sb; int error, sz; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; sz = table->gpt_scheme->gps_bootcodesz; if (sz == 0) { error = ENODEV; goto fail; } if (gpp->gpp_codesize > sz) { error = EFBIG; goto fail; } error = G_PART_BOOTCODE(table, gpp); if (error) goto fail; /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); sbuf_printf(sb, "bootcode written to %s\n", gp->name); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); fail: gctl_error(req, "%d", error); return (error); } static int g_part_ctl_commit(struct gctl_req *req, struct g_part_parms *gpp) { struct g_consumer *cp; struct g_geom *gp; struct g_provider *pp; struct g_part_entry *entry, *tmp; struct g_part_table *table; char *buf; int error, i; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; if (!table->gpt_opened) { gctl_error(req, "%d", EPERM); return (EPERM); } g_topology_unlock(); cp = LIST_FIRST(&gp->consumer); if ((table->gpt_smhead | table->gpt_smtail) != 0) { pp = cp->provider; buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO); while (table->gpt_smhead != 0) { i = ffs(table->gpt_smhead) - 1; error = g_write_data(cp, i * pp->sectorsize, buf, pp->sectorsize); if (error) { g_free(buf); goto fail; } table->gpt_smhead &= ~(1 << i); } while (table->gpt_smtail != 0) { i = ffs(table->gpt_smtail) - 1; error = g_write_data(cp, pp->mediasize - (i + 1) * pp->sectorsize, buf, pp->sectorsize); if (error) { g_free(buf); goto fail; } table->gpt_smtail &= ~(1 << i); } g_free(buf); } if (table->gpt_scheme == &g_part_null_scheme) { g_topology_lock(); g_access(cp, -1, -1, -1); g_part_wither(gp, ENXIO); return (0); } error = G_PART_WRITE(table, cp); if (error) goto fail; LIST_FOREACH_SAFE(entry, &table->gpt_entry, gpe_entry, tmp) { if (!entry->gpe_deleted) { /* Notify consumers that provider might be changed. */ if (entry->gpe_modified && ( entry->gpe_pp->acw + entry->gpe_pp->ace + entry->gpe_pp->acr) == 0) g_media_changed(entry->gpe_pp, M_NOWAIT); entry->gpe_created = 0; entry->gpe_modified = 0; continue; } LIST_REMOVE(entry, gpe_entry); g_free(entry); } table->gpt_created = 0; table->gpt_opened = 0; g_topology_lock(); g_access(cp, -1, -1, -1); return (0); fail: g_topology_lock(); gctl_error(req, "%d", error); return (error); } static int g_part_ctl_create(struct gctl_req *req, struct g_part_parms *gpp) { struct g_consumer *cp; struct g_geom *gp; struct g_provider *pp; struct g_part_scheme *scheme; struct g_part_table *null, *table; struct sbuf *sb; int attr, error; pp = gpp->gpp_provider; scheme = gpp->gpp_scheme; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, pp->name)); g_topology_assert(); /* Check that there isn't already a g_part geom on the provider. */ gp = g_part_find_geom(pp->name); if (gp != NULL) { null = gp->softc; if (null->gpt_scheme != &g_part_null_scheme) { gctl_error(req, "%d geom '%s'", EEXIST, pp->name); return (EEXIST); } } else null = NULL; if ((gpp->gpp_parms & G_PART_PARM_ENTRIES) && (gpp->gpp_entries < scheme->gps_minent || gpp->gpp_entries > scheme->gps_maxent)) { gctl_error(req, "%d entries '%d'", EINVAL, gpp->gpp_entries); return (EINVAL); } if (null == NULL) gp = g_new_geomf(&g_part_class, "%s", pp->name); gp->softc = kobj_create((kobj_class_t)gpp->gpp_scheme, M_GEOM, M_WAITOK); table = gp->softc; table->gpt_gp = gp; table->gpt_scheme = gpp->gpp_scheme; table->gpt_entries = (gpp->gpp_parms & G_PART_PARM_ENTRIES) ? gpp->gpp_entries : scheme->gps_minent; LIST_INIT(&table->gpt_entry); if (null == NULL) { cp = g_new_consumer(gp); cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE; error = g_attach(cp, pp); if (error == 0) error = g_access(cp, 1, 1, 1); if (error != 0) { g_part_wither(gp, error); gctl_error(req, "%d geom '%s'", error, pp->name); return (error); } table->gpt_opened = 1; } else { cp = LIST_FIRST(&gp->consumer); table->gpt_opened = null->gpt_opened; table->gpt_smhead = null->gpt_smhead; table->gpt_smtail = null->gpt_smtail; } g_topology_unlock(); /* Make sure the provider has media. */ if (pp->mediasize == 0 || pp->sectorsize == 0) { error = ENODEV; goto fail; } /* Make sure we can nest and if so, determine our depth. */ error = g_getattr("PART::isleaf", cp, &attr); if (!error && attr) { error = ENODEV; goto fail; } error = g_getattr("PART::depth", cp, &attr); table->gpt_depth = (!error) ? attr + 1 : 0; /* * Synthesize a disk geometry. Some partitioning schemes * depend on it and since some file systems need it even * when the partitition scheme doesn't, we do it here in * scheme-independent code. */ g_part_geometry(table, cp, pp->mediasize / pp->sectorsize); error = G_PART_CREATE(table, gpp); if (error) goto fail; g_topology_lock(); table->gpt_created = 1; if (null != NULL) kobj_delete((kobj_t)null, M_GEOM); /* * Support automatic commit by filling in the gpp_geom * parameter. */ gpp->gpp_parms |= G_PART_PARM_GEOM; gpp->gpp_geom = gp; /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); sbuf_printf(sb, "%s created\n", gp->name); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); fail: g_topology_lock(); if (null == NULL) { g_access(cp, -1, -1, -1); g_part_wither(gp, error); } else { kobj_delete((kobj_t)gp->softc, M_GEOM); gp->softc = null; } gctl_error(req, "%d provider", error); return (error); } static int g_part_ctl_delete(struct gctl_req *req, struct g_part_parms *gpp) { struct g_geom *gp; struct g_provider *pp; struct g_part_entry *entry; struct g_part_table *table; struct sbuf *sb; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted || entry->gpe_internal) continue; if (entry->gpe_index == gpp->gpp_index) break; } if (entry == NULL) { gctl_error(req, "%d index '%d'", ENOENT, gpp->gpp_index); return (ENOENT); } pp = entry->gpe_pp; if (pp != NULL) { if (pp->acr > 0 || pp->acw > 0 || pp->ace > 0) { gctl_error(req, "%d", EBUSY); return (EBUSY); } pp->private = NULL; entry->gpe_pp = NULL; } if (pp != NULL) g_wither_provider(pp, ENXIO); /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gp->name); sbuf_cat(sb, " deleted\n"); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } if (entry->gpe_created) { LIST_REMOVE(entry, gpe_entry); g_free(entry); } else { entry->gpe_modified = 0; entry->gpe_deleted = 1; } return (0); } static int g_part_ctl_destroy(struct gctl_req *req, struct g_part_parms *gpp) { struct g_consumer *cp; struct g_geom *gp; struct g_provider *pp; struct g_part_entry *entry, *tmp; struct g_part_table *null, *table; struct sbuf *sb; int error; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; /* Check for busy providers. */ LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted || entry->gpe_internal) continue; if (gpp->gpp_force) { pp = entry->gpe_pp; if (pp == NULL) continue; if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0) continue; } gctl_error(req, "%d", EBUSY); return (EBUSY); } if (gpp->gpp_force) { /* Destroy all providers. */ LIST_FOREACH_SAFE(entry, &table->gpt_entry, gpe_entry, tmp) { pp = entry->gpe_pp; if (pp != NULL) { pp->private = NULL; g_wither_provider(pp, ENXIO); } LIST_REMOVE(entry, gpe_entry); g_free(entry); } } error = G_PART_DESTROY(table, gpp); if (error) { gctl_error(req, "%d", error); return (error); } gp->softc = kobj_create((kobj_class_t)&g_part_null_scheme, M_GEOM, M_WAITOK); null = gp->softc; null->gpt_gp = gp; null->gpt_scheme = &g_part_null_scheme; LIST_INIT(&null->gpt_entry); cp = LIST_FIRST(&gp->consumer); pp = cp->provider; null->gpt_last = pp->mediasize / pp->sectorsize - 1; null->gpt_depth = table->gpt_depth; null->gpt_opened = table->gpt_opened; null->gpt_smhead = table->gpt_smhead; null->gpt_smtail = table->gpt_smtail; while ((entry = LIST_FIRST(&table->gpt_entry)) != NULL) { LIST_REMOVE(entry, gpe_entry); g_free(entry); } kobj_delete((kobj_t)table, M_GEOM); /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); sbuf_printf(sb, "%s destroyed\n", gp->name); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_modify(struct gctl_req *req, struct g_part_parms *gpp) { struct g_geom *gp; struct g_part_entry *entry; struct g_part_table *table; struct sbuf *sb; int error; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted || entry->gpe_internal) continue; if (entry->gpe_index == gpp->gpp_index) break; } if (entry == NULL) { gctl_error(req, "%d index '%d'", ENOENT, gpp->gpp_index); return (ENOENT); } error = G_PART_MODIFY(table, entry, gpp); if (error) { gctl_error(req, "%d", error); return (error); } if (!entry->gpe_created) entry->gpe_modified = 1; /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gp->name); sbuf_cat(sb, " modified\n"); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_move(struct gctl_req *req, struct g_part_parms *gpp) { gctl_error(req, "%d verb 'move'", ENOSYS); return (ENOSYS); } static int g_part_ctl_recover(struct gctl_req *req, struct g_part_parms *gpp) { struct g_part_table *table; struct g_geom *gp; struct sbuf *sb; int error, recovered; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; error = recovered = 0; if (table->gpt_corrupt) { error = G_PART_RECOVER(table); if (error == 0) error = g_part_check_integrity(table, LIST_FIRST(&gp->consumer)); if (error) { gctl_error(req, "%d recovering '%s' failed", error, gp->name); return (error); } recovered = 1; } /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); if (recovered) sbuf_printf(sb, "%s recovered\n", gp->name); else sbuf_printf(sb, "%s recovering is not needed\n", gp->name); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_resize(struct gctl_req *req, struct g_part_parms *gpp) { struct g_geom *gp; struct g_provider *pp; struct g_part_entry *pe, *entry; struct g_part_table *table; struct sbuf *sb; quad_t end; int error; off_t mediasize; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; /* check gpp_index */ LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted || entry->gpe_internal) continue; if (entry->gpe_index == gpp->gpp_index) break; } if (entry == NULL) { gctl_error(req, "%d index '%d'", ENOENT, gpp->gpp_index); return (ENOENT); } /* check gpp_size */ end = entry->gpe_start + gpp->gpp_size - 1; if (gpp->gpp_size < 1 || end > table->gpt_last) { gctl_error(req, "%d size '%jd'", EINVAL, (intmax_t)gpp->gpp_size); return (EINVAL); } LIST_FOREACH(pe, &table->gpt_entry, gpe_entry) { if (pe->gpe_deleted || pe->gpe_internal || pe == entry) continue; if (end >= pe->gpe_start && end <= pe->gpe_end) { gctl_error(req, "%d end '%jd'", ENOSPC, (intmax_t)end); return (ENOSPC); } if (entry->gpe_start < pe->gpe_start && end > pe->gpe_end) { gctl_error(req, "%d size '%jd'", ENOSPC, (intmax_t)gpp->gpp_size); return (ENOSPC); } } pp = entry->gpe_pp; if ((g_debugflags & 16) == 0 && (pp->acr > 0 || pp->acw > 0 || pp->ace > 0)) { if (entry->gpe_end - entry->gpe_start + 1 > gpp->gpp_size) { /* Deny shrinking of an opened partition. */ gctl_error(req, "%d", EBUSY); return (EBUSY); } } error = G_PART_RESIZE(table, entry, gpp); if (error) { gctl_error(req, "%d%s", error, error != EBUSY ? "": " resizing will lead to unexpected shrinking" " due to alignment"); return (error); } if (!entry->gpe_created) entry->gpe_modified = 1; /* update mediasize of changed provider */ mediasize = (entry->gpe_end - entry->gpe_start + 1) * pp->sectorsize; g_resize_provider(pp, mediasize); /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); G_PART_FULLNAME(table, entry, sb, gp->name); sbuf_cat(sb, " resized\n"); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_setunset(struct gctl_req *req, struct g_part_parms *gpp, unsigned int set) { struct g_geom *gp; struct g_part_entry *entry; struct g_part_table *table; struct sbuf *sb; int error; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; if (gpp->gpp_parms & G_PART_PARM_INDEX) { LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_deleted || entry->gpe_internal) continue; if (entry->gpe_index == gpp->gpp_index) break; } if (entry == NULL) { gctl_error(req, "%d index '%d'", ENOENT, gpp->gpp_index); return (ENOENT); } } else entry = NULL; error = G_PART_SETUNSET(table, entry, gpp->gpp_attrib, set); if (error) { gctl_error(req, "%d attrib '%s'", error, gpp->gpp_attrib); return (error); } /* Provide feedback if so requested. */ if (gpp->gpp_parms & G_PART_PARM_OUTPUT) { sb = sbuf_new_auto(); sbuf_printf(sb, "%s %sset on ", gpp->gpp_attrib, (set) ? "" : "un"); if (entry) G_PART_FULLNAME(table, entry, sb, gp->name); else sbuf_cat(sb, gp->name); sbuf_cat(sb, "\n"); sbuf_finish(sb); gctl_set_param(req, "output", sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); } return (0); } static int g_part_ctl_undo(struct gctl_req *req, struct g_part_parms *gpp) { struct g_consumer *cp; struct g_provider *pp; struct g_geom *gp; struct g_part_entry *entry, *tmp; struct g_part_table *table; int error, reprobe; gp = gpp->gpp_geom; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, gp->name)); g_topology_assert(); table = gp->softc; if (!table->gpt_opened) { gctl_error(req, "%d", EPERM); return (EPERM); } cp = LIST_FIRST(&gp->consumer); LIST_FOREACH_SAFE(entry, &table->gpt_entry, gpe_entry, tmp) { entry->gpe_modified = 0; if (entry->gpe_created) { pp = entry->gpe_pp; if (pp != NULL) { pp->private = NULL; entry->gpe_pp = NULL; g_wither_provider(pp, ENXIO); } entry->gpe_deleted = 1; } if (entry->gpe_deleted) { LIST_REMOVE(entry, gpe_entry); g_free(entry); } } g_topology_unlock(); reprobe = (table->gpt_scheme == &g_part_null_scheme || table->gpt_created) ? 1 : 0; if (reprobe) { LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (entry->gpe_internal) continue; error = EBUSY; goto fail; } while ((entry = LIST_FIRST(&table->gpt_entry)) != NULL) { LIST_REMOVE(entry, gpe_entry); g_free(entry); } error = g_part_probe(gp, cp, table->gpt_depth); if (error) { g_topology_lock(); g_access(cp, -1, -1, -1); g_part_wither(gp, error); return (0); } table = gp->softc; /* * Synthesize a disk geometry. Some partitioning schemes * depend on it and since some file systems need it even * when the partitition scheme doesn't, we do it here in * scheme-independent code. */ pp = cp->provider; g_part_geometry(table, cp, pp->mediasize / pp->sectorsize); } error = G_PART_READ(table, cp); if (error) goto fail; error = g_part_check_integrity(table, cp); if (error) goto fail; g_topology_lock(); LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (!entry->gpe_internal) g_part_new_provider(gp, table, entry); } table->gpt_opened = 0; g_access(cp, -1, -1, -1); return (0); fail: g_topology_lock(); gctl_error(req, "%d", error); return (error); } static void g_part_wither(struct g_geom *gp, int error) { struct g_part_entry *entry; struct g_part_table *table; struct g_provider *pp; table = gp->softc; if (table != NULL) { gp->softc = NULL; while ((entry = LIST_FIRST(&table->gpt_entry)) != NULL) { LIST_REMOVE(entry, gpe_entry); pp = entry->gpe_pp; entry->gpe_pp = NULL; if (pp != NULL) { pp->private = NULL; g_wither_provider(pp, error); } g_free(entry); } G_PART_DESTROY(table, NULL); kobj_delete((kobj_t)table, M_GEOM); } g_wither_geom(gp, error); } /* * Class methods. */ static void g_part_ctlreq(struct gctl_req *req, struct g_class *mp, const char *verb) { struct g_part_parms gpp; struct g_part_table *table; struct gctl_req_arg *ap; enum g_part_ctl ctlreq; unsigned int i, mparms, oparms, parm; int auto_commit, close_on_error; int error, modifies; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s,%s)", __func__, mp->name, verb)); g_topology_assert(); ctlreq = G_PART_CTL_NONE; modifies = 1; mparms = 0; oparms = G_PART_PARM_FLAGS | G_PART_PARM_OUTPUT | G_PART_PARM_VERSION; switch (*verb) { case 'a': if (!strcmp(verb, "add")) { ctlreq = G_PART_CTL_ADD; mparms |= G_PART_PARM_GEOM | G_PART_PARM_SIZE | G_PART_PARM_START | G_PART_PARM_TYPE; oparms |= G_PART_PARM_INDEX | G_PART_PARM_LABEL; } break; case 'b': if (!strcmp(verb, "bootcode")) { ctlreq = G_PART_CTL_BOOTCODE; mparms |= G_PART_PARM_GEOM | G_PART_PARM_BOOTCODE; + oparms |= G_PART_PARM_SKIP_DSN; } break; case 'c': if (!strcmp(verb, "commit")) { ctlreq = G_PART_CTL_COMMIT; mparms |= G_PART_PARM_GEOM; modifies = 0; } else if (!strcmp(verb, "create")) { ctlreq = G_PART_CTL_CREATE; mparms |= G_PART_PARM_PROVIDER | G_PART_PARM_SCHEME; oparms |= G_PART_PARM_ENTRIES; } break; case 'd': if (!strcmp(verb, "delete")) { ctlreq = G_PART_CTL_DELETE; mparms |= G_PART_PARM_GEOM | G_PART_PARM_INDEX; } else if (!strcmp(verb, "destroy")) { ctlreq = G_PART_CTL_DESTROY; mparms |= G_PART_PARM_GEOM; oparms |= G_PART_PARM_FORCE; } break; case 'm': if (!strcmp(verb, "modify")) { ctlreq = G_PART_CTL_MODIFY; mparms |= G_PART_PARM_GEOM | G_PART_PARM_INDEX; oparms |= G_PART_PARM_LABEL | G_PART_PARM_TYPE; } else if (!strcmp(verb, "move")) { ctlreq = G_PART_CTL_MOVE; mparms |= G_PART_PARM_GEOM | G_PART_PARM_INDEX; } break; case 'r': if (!strcmp(verb, "recover")) { ctlreq = G_PART_CTL_RECOVER; mparms |= G_PART_PARM_GEOM; } else if (!strcmp(verb, "resize")) { ctlreq = G_PART_CTL_RESIZE; mparms |= G_PART_PARM_GEOM | G_PART_PARM_INDEX | G_PART_PARM_SIZE; } break; case 's': if (!strcmp(verb, "set")) { ctlreq = G_PART_CTL_SET; mparms |= G_PART_PARM_ATTRIB | G_PART_PARM_GEOM; oparms |= G_PART_PARM_INDEX; } break; case 'u': if (!strcmp(verb, "undo")) { ctlreq = G_PART_CTL_UNDO; mparms |= G_PART_PARM_GEOM; modifies = 0; } else if (!strcmp(verb, "unset")) { ctlreq = G_PART_CTL_UNSET; mparms |= G_PART_PARM_ATTRIB | G_PART_PARM_GEOM; oparms |= G_PART_PARM_INDEX; } break; } if (ctlreq == G_PART_CTL_NONE) { gctl_error(req, "%d verb '%s'", EINVAL, verb); return; } bzero(&gpp, sizeof(gpp)); for (i = 0; i < req->narg; i++) { ap = &req->arg[i]; parm = 0; switch (ap->name[0]) { case 'a': if (!strcmp(ap->name, "arg0")) { parm = mparms & (G_PART_PARM_GEOM | G_PART_PARM_PROVIDER); } if (!strcmp(ap->name, "attrib")) parm = G_PART_PARM_ATTRIB; break; case 'b': if (!strcmp(ap->name, "bootcode")) parm = G_PART_PARM_BOOTCODE; break; case 'c': if (!strcmp(ap->name, "class")) continue; break; case 'e': if (!strcmp(ap->name, "entries")) parm = G_PART_PARM_ENTRIES; break; case 'f': if (!strcmp(ap->name, "flags")) parm = G_PART_PARM_FLAGS; else if (!strcmp(ap->name, "force")) parm = G_PART_PARM_FORCE; break; case 'i': if (!strcmp(ap->name, "index")) parm = G_PART_PARM_INDEX; break; case 'l': if (!strcmp(ap->name, "label")) parm = G_PART_PARM_LABEL; break; case 'o': if (!strcmp(ap->name, "output")) parm = G_PART_PARM_OUTPUT; break; case 's': if (!strcmp(ap->name, "scheme")) parm = G_PART_PARM_SCHEME; else if (!strcmp(ap->name, "size")) parm = G_PART_PARM_SIZE; else if (!strcmp(ap->name, "start")) parm = G_PART_PARM_START; + else if (!strcmp(ap->name, "skip_dsn")) + parm = G_PART_PARM_SKIP_DSN; break; case 't': if (!strcmp(ap->name, "type")) parm = G_PART_PARM_TYPE; break; case 'v': if (!strcmp(ap->name, "verb")) continue; else if (!strcmp(ap->name, "version")) parm = G_PART_PARM_VERSION; break; } if ((parm & (mparms | oparms)) == 0) { gctl_error(req, "%d param '%s'", EINVAL, ap->name); return; } switch (parm) { case G_PART_PARM_ATTRIB: error = g_part_parm_str(req, ap->name, &gpp.gpp_attrib); break; case G_PART_PARM_BOOTCODE: error = g_part_parm_bootcode(req, ap->name, &gpp.gpp_codeptr, &gpp.gpp_codesize); break; case G_PART_PARM_ENTRIES: error = g_part_parm_intmax(req, ap->name, &gpp.gpp_entries); break; case G_PART_PARM_FLAGS: error = g_part_parm_str(req, ap->name, &gpp.gpp_flags); break; case G_PART_PARM_FORCE: error = g_part_parm_uint32(req, ap->name, &gpp.gpp_force); break; case G_PART_PARM_GEOM: error = g_part_parm_geom(req, ap->name, &gpp.gpp_geom); break; case G_PART_PARM_INDEX: error = g_part_parm_intmax(req, ap->name, &gpp.gpp_index); break; case G_PART_PARM_LABEL: error = g_part_parm_str(req, ap->name, &gpp.gpp_label); break; case G_PART_PARM_OUTPUT: error = 0; /* Write-only parameter */ break; case G_PART_PARM_PROVIDER: error = g_part_parm_provider(req, ap->name, &gpp.gpp_provider); break; case G_PART_PARM_SCHEME: error = g_part_parm_scheme(req, ap->name, &gpp.gpp_scheme); break; case G_PART_PARM_SIZE: error = g_part_parm_quad(req, ap->name, &gpp.gpp_size); + break; + case G_PART_PARM_SKIP_DSN: + error = g_part_parm_uint32(req, ap->name, + &gpp.gpp_skip_dsn); break; case G_PART_PARM_START: error = g_part_parm_quad(req, ap->name, &gpp.gpp_start); break; case G_PART_PARM_TYPE: error = g_part_parm_str(req, ap->name, &gpp.gpp_type); break; case G_PART_PARM_VERSION: error = g_part_parm_uint32(req, ap->name, &gpp.gpp_version); break; default: error = EDOOFUS; gctl_error(req, "%d %s", error, ap->name); break; } if (error != 0) { if (error == ENOATTR) { gctl_error(req, "%d param '%s'", error, ap->name); } return; } gpp.gpp_parms |= parm; } if ((gpp.gpp_parms & mparms) != mparms) { parm = mparms - (gpp.gpp_parms & mparms); gctl_error(req, "%d param '%x'", ENOATTR, parm); return; } /* Obtain permissions if possible/necessary. */ close_on_error = 0; table = NULL; if (modifies && (gpp.gpp_parms & G_PART_PARM_GEOM)) { table = gpp.gpp_geom->softc; if (table != NULL && table->gpt_corrupt && ctlreq != G_PART_CTL_DESTROY && ctlreq != G_PART_CTL_RECOVER) { gctl_error(req, "%d table '%s' is corrupt", EPERM, gpp.gpp_geom->name); return; } if (table != NULL && !table->gpt_opened) { error = g_access(LIST_FIRST(&gpp.gpp_geom->consumer), 1, 1, 1); if (error) { gctl_error(req, "%d geom '%s'", error, gpp.gpp_geom->name); return; } table->gpt_opened = 1; close_on_error = 1; } } /* Allow the scheme to check or modify the parameters. */ if (table != NULL) { error = G_PART_PRECHECK(table, ctlreq, &gpp); if (error) { gctl_error(req, "%d pre-check failed", error); goto out; } } else error = EDOOFUS; /* Prevent bogus uninit. warning. */ switch (ctlreq) { case G_PART_CTL_NONE: panic("%s", __func__); case G_PART_CTL_ADD: error = g_part_ctl_add(req, &gpp); break; case G_PART_CTL_BOOTCODE: error = g_part_ctl_bootcode(req, &gpp); break; case G_PART_CTL_COMMIT: error = g_part_ctl_commit(req, &gpp); break; case G_PART_CTL_CREATE: error = g_part_ctl_create(req, &gpp); break; case G_PART_CTL_DELETE: error = g_part_ctl_delete(req, &gpp); break; case G_PART_CTL_DESTROY: error = g_part_ctl_destroy(req, &gpp); break; case G_PART_CTL_MODIFY: error = g_part_ctl_modify(req, &gpp); break; case G_PART_CTL_MOVE: error = g_part_ctl_move(req, &gpp); break; case G_PART_CTL_RECOVER: error = g_part_ctl_recover(req, &gpp); break; case G_PART_CTL_RESIZE: error = g_part_ctl_resize(req, &gpp); break; case G_PART_CTL_SET: error = g_part_ctl_setunset(req, &gpp, 1); break; case G_PART_CTL_UNDO: error = g_part_ctl_undo(req, &gpp); break; case G_PART_CTL_UNSET: error = g_part_ctl_setunset(req, &gpp, 0); break; } /* Implement automatic commit. */ if (!error) { auto_commit = (modifies && (gpp.gpp_parms & G_PART_PARM_FLAGS) && strchr(gpp.gpp_flags, 'C') != NULL) ? 1 : 0; if (auto_commit) { KASSERT(gpp.gpp_parms & G_PART_PARM_GEOM, ("%s", __func__)); error = g_part_ctl_commit(req, &gpp); } } out: if (error && close_on_error) { g_access(LIST_FIRST(&gpp.gpp_geom->consumer), -1, -1, -1); table->gpt_opened = 0; } } static int g_part_destroy_geom(struct gctl_req *req, struct g_class *mp, struct g_geom *gp) { G_PART_TRACE((G_T_TOPOLOGY, "%s(%s,%s)", __func__, mp->name, gp->name)); g_topology_assert(); g_part_wither(gp, EINVAL); return (0); } static struct g_geom * g_part_taste(struct g_class *mp, struct g_provider *pp, int flags __unused) { struct g_consumer *cp; struct g_geom *gp; struct g_part_entry *entry; struct g_part_table *table; struct root_hold_token *rht; struct g_geom_alias *gap; int attr, depth; int error; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s,%s)", __func__, mp->name, pp->name)); g_topology_assert(); /* Skip providers that are already open for writing. */ if (pp->acw > 0) return (NULL); /* * Create a GEOM with consumer and hook it up to the provider. * With that we become part of the topology. Obtain read access * to the provider. */ gp = g_new_geomf(mp, "%s", pp->name); LIST_FOREACH(gap, &pp->geom->aliases, ga_next) g_geom_add_alias(gp, gap->ga_alias); cp = g_new_consumer(gp); cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE; error = g_attach(cp, pp); if (error == 0) error = g_access(cp, 1, 0, 0); if (error != 0) { if (cp->provider) g_detach(cp); g_destroy_consumer(cp); g_destroy_geom(gp); return (NULL); } rht = root_mount_hold(mp->name); g_topology_unlock(); /* * Short-circuit the whole probing galore when there's no * media present. */ if (pp->mediasize == 0 || pp->sectorsize == 0) { error = ENODEV; goto fail; } /* Make sure we can nest and if so, determine our depth. */ error = g_getattr("PART::isleaf", cp, &attr); if (!error && attr) { error = ENODEV; goto fail; } error = g_getattr("PART::depth", cp, &attr); depth = (!error) ? attr + 1 : 0; error = g_part_probe(gp, cp, depth); if (error) goto fail; table = gp->softc; /* * Synthesize a disk geometry. Some partitioning schemes * depend on it and since some file systems need it even * when the partitition scheme doesn't, we do it here in * scheme-independent code. */ g_part_geometry(table, cp, pp->mediasize / pp->sectorsize); error = G_PART_READ(table, cp); if (error) goto fail; error = g_part_check_integrity(table, cp); if (error) goto fail; g_topology_lock(); LIST_FOREACH(entry, &table->gpt_entry, gpe_entry) { if (!entry->gpe_internal) g_part_new_provider(gp, table, entry); } root_mount_rel(rht); g_access(cp, -1, 0, 0); return (gp); fail: g_topology_lock(); root_mount_rel(rht); g_access(cp, -1, 0, 0); g_detach(cp); g_destroy_consumer(cp); g_destroy_geom(gp); return (NULL); } /* * Geom methods. */ static int g_part_access(struct g_provider *pp, int dr, int dw, int de) { struct g_consumer *cp; G_PART_TRACE((G_T_ACCESS, "%s(%s,%d,%d,%d)", __func__, pp->name, dr, dw, de)); cp = LIST_FIRST(&pp->geom->consumer); /* We always gain write-exclusive access. */ return (g_access(cp, dr, dw, dw + de)); } static void g_part_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp) { char buf[64]; struct g_part_entry *entry; struct g_part_table *table; KASSERT(sb != NULL && gp != NULL, ("%s", __func__)); table = gp->softc; if (indent == NULL) { KASSERT(cp == NULL && pp != NULL, ("%s", __func__)); entry = pp->private; if (entry == NULL) return; sbuf_printf(sb, " i %u o %ju ty %s", entry->gpe_index, (uintmax_t)entry->gpe_offset, G_PART_TYPE(table, entry, buf, sizeof(buf))); /* * libdisk compatibility quirk - the scheme dumps the * slicer name and partition type in a way that is * compatible with libdisk. When libdisk is not used * anymore, this should go away. */ G_PART_DUMPCONF(table, entry, sb, indent); } else if (cp != NULL) { /* Consumer configuration. */ KASSERT(pp == NULL, ("%s", __func__)); /* none */ } else if (pp != NULL) { /* Provider configuration. */ entry = pp->private; if (entry == NULL) return; sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)entry->gpe_start); sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)entry->gpe_end); sbuf_printf(sb, "%s%u\n", indent, entry->gpe_index); sbuf_printf(sb, "%s%s\n", indent, G_PART_TYPE(table, entry, buf, sizeof(buf))); sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)entry->gpe_offset); sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)pp->mediasize); G_PART_DUMPCONF(table, entry, sb, indent); } else { /* Geom configuration. */ sbuf_printf(sb, "%s%s\n", indent, table->gpt_scheme->name); sbuf_printf(sb, "%s%u\n", indent, table->gpt_entries); sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)table->gpt_first); sbuf_printf(sb, "%s%ju\n", indent, (uintmax_t)table->gpt_last); sbuf_printf(sb, "%s%u\n", indent, table->gpt_sectors); sbuf_printf(sb, "%s%u\n", indent, table->gpt_heads); sbuf_printf(sb, "%s%s\n", indent, table->gpt_corrupt ? "CORRUPT": "OK"); sbuf_printf(sb, "%s%s\n", indent, table->gpt_opened ? "true": "false"); G_PART_DUMPCONF(table, NULL, sb, indent); } } /*- * This start routine is only called for non-trivial requests, all the * trivial ones are handled autonomously by the slice code. * For requests we handle here, we must call the g_io_deliver() on the * bio, and return non-zero to indicate to the slice code that we did so. * This code executes in the "DOWN" I/O path, this means: * * No sleeping. * * Don't grab the topology lock. * * Don't call biowait, g_getattr(), g_setattr() or g_read_data() */ static int g_part_ioctl(struct g_provider *pp, u_long cmd, void *data, int fflag, struct thread *td) { struct g_part_table *table; table = pp->geom->softc; return G_PART_IOCTL(table, pp, cmd, data, fflag, td); } static void g_part_resize(struct g_consumer *cp) { struct g_part_table *table; G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, cp->provider->name)); g_topology_assert(); if (auto_resize == 0) return; table = cp->geom->softc; if (table->gpt_opened == 0) { if (g_access(cp, 1, 1, 1) != 0) return; table->gpt_opened = 1; } if (G_PART_RESIZE(table, NULL, NULL) == 0) printf("GEOM_PART: %s was automatically resized.\n" " Use `gpart commit %s` to save changes or " "`gpart undo %s` to revert them.\n", cp->geom->name, cp->geom->name, cp->geom->name); if (g_part_check_integrity(table, cp) != 0) { g_access(cp, -1, -1, -1); table->gpt_opened = 0; g_part_wither(table->gpt_gp, ENXIO); } } static void g_part_orphan(struct g_consumer *cp) { struct g_provider *pp; struct g_part_table *table; pp = cp->provider; KASSERT(pp != NULL, ("%s", __func__)); G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, pp->name)); g_topology_assert(); KASSERT(pp->error != 0, ("%s", __func__)); table = cp->geom->softc; if (table != NULL && table->gpt_opened) g_access(cp, -1, -1, -1); g_part_wither(cp->geom, pp->error); } static void g_part_spoiled(struct g_consumer *cp) { G_PART_TRACE((G_T_TOPOLOGY, "%s(%s)", __func__, cp->provider->name)); g_topology_assert(); cp->flags |= G_CF_ORPHAN; g_part_wither(cp->geom, ENXIO); } static void g_part_start(struct bio *bp) { struct bio *bp2; struct g_consumer *cp; struct g_geom *gp; struct g_part_entry *entry; struct g_part_table *table; struct g_kerneldump *gkd; struct g_provider *pp; void (*done_func)(struct bio *) = g_std_done; char buf[64]; biotrack(bp, __func__); pp = bp->bio_to; gp = pp->geom; table = gp->softc; cp = LIST_FIRST(&gp->consumer); G_PART_TRACE((G_T_BIO, "%s: cmd=%d, provider=%s", __func__, bp->bio_cmd, pp->name)); entry = pp->private; if (entry == NULL) { g_io_deliver(bp, ENXIO); return; } switch(bp->bio_cmd) { case BIO_DELETE: case BIO_READ: case BIO_WRITE: if (bp->bio_offset >= pp->mediasize) { g_io_deliver(bp, EIO); return; } bp2 = g_clone_bio(bp); if (bp2 == NULL) { g_io_deliver(bp, ENOMEM); return; } if (bp2->bio_offset + bp2->bio_length > pp->mediasize) bp2->bio_length = pp->mediasize - bp2->bio_offset; bp2->bio_done = g_std_done; bp2->bio_offset += entry->gpe_offset; g_io_request(bp2, cp); return; case BIO_FLUSH: break; case BIO_GETATTR: if (g_handleattr_int(bp, "GEOM::fwheads", table->gpt_heads)) return; if (g_handleattr_int(bp, "GEOM::fwsectors", table->gpt_sectors)) return; if (g_handleattr_int(bp, "PART::isleaf", table->gpt_isleaf)) return; if (g_handleattr_int(bp, "PART::depth", table->gpt_depth)) return; if (g_handleattr_str(bp, "PART::scheme", table->gpt_scheme->name)) return; if (g_handleattr_str(bp, "PART::type", G_PART_TYPE(table, entry, buf, sizeof(buf)))) return; if (!strcmp("GEOM::physpath", bp->bio_attribute)) { done_func = g_part_get_physpath_done; break; } if (!strcmp("GEOM::kerneldump", bp->bio_attribute)) { /* * Check that the partition is suitable for kernel * dumps. Typically only swap partitions should be * used. If the request comes from the nested scheme * we allow dumping there as well. */ if ((bp->bio_from == NULL || bp->bio_from->geom->class != &g_part_class) && G_PART_DUMPTO(table, entry) == 0) { g_io_deliver(bp, ENODEV); printf("GEOM_PART: Partition '%s' not suitable" " for kernel dumps (wrong type?)\n", pp->name); return; } gkd = (struct g_kerneldump *)bp->bio_data; if (gkd->offset >= pp->mediasize) { g_io_deliver(bp, EIO); return; } if (gkd->offset + gkd->length > pp->mediasize) gkd->length = pp->mediasize - gkd->offset; gkd->offset += entry->gpe_offset; } break; default: g_io_deliver(bp, EOPNOTSUPP); return; } bp2 = g_clone_bio(bp); if (bp2 == NULL) { g_io_deliver(bp, ENOMEM); return; } bp2->bio_done = done_func; g_io_request(bp2, cp); } static void g_part_init(struct g_class *mp) { TAILQ_INSERT_HEAD(&g_part_schemes, &g_part_null_scheme, scheme_list); } static void g_part_fini(struct g_class *mp) { TAILQ_REMOVE(&g_part_schemes, &g_part_null_scheme, scheme_list); } static void g_part_unload_event(void *arg, int flag) { struct g_consumer *cp; struct g_geom *gp; struct g_provider *pp; struct g_part_scheme *scheme; struct g_part_table *table; uintptr_t *xchg; int acc, error; if (flag == EV_CANCEL) return; xchg = arg; error = 0; scheme = (void *)(*xchg); g_topology_assert(); LIST_FOREACH(gp, &g_part_class.geom, geom) { table = gp->softc; if (table->gpt_scheme != scheme) continue; acc = 0; LIST_FOREACH(pp, &gp->provider, provider) acc += pp->acr + pp->acw + pp->ace; LIST_FOREACH(cp, &gp->consumer, consumer) acc += cp->acr + cp->acw + cp->ace; if (!acc) g_part_wither(gp, ENOSYS); else error = EBUSY; } if (!error) TAILQ_REMOVE(&g_part_schemes, scheme, scheme_list); *xchg = error; } int g_part_modevent(module_t mod, int type, struct g_part_scheme *scheme) { struct g_part_scheme *iter; uintptr_t arg; int error; error = 0; switch (type) { case MOD_LOAD: TAILQ_FOREACH(iter, &g_part_schemes, scheme_list) { if (scheme == iter) { printf("GEOM_PART: scheme %s is already " "registered!\n", scheme->name); break; } } if (iter == NULL) { TAILQ_INSERT_TAIL(&g_part_schemes, scheme, scheme_list); g_retaste(&g_part_class); } break; case MOD_UNLOAD: arg = (uintptr_t)scheme; error = g_waitfor_event(g_part_unload_event, &arg, M_WAITOK, NULL); if (error == 0) error = arg; break; default: error = EOPNOTSUPP; break; } return (error); } Index: head/sys/geom/part/g_part.h =================================================================== --- head/sys/geom/part/g_part.h (revision 341066) +++ head/sys/geom/part/g_part.h (revision 341067) @@ -1,242 +1,244 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2006-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 AUTHOR ``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 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 _GEOM_PART_H_ #define _GEOM_PART_H_ #define G_PART_TRACE(args) g_trace args #define G_PART_PROBE_PRI_LOW -10 #define G_PART_PROBE_PRI_NORM -5 #define G_PART_PROBE_PRI_HIGH 0 enum g_part_alias { G_PART_ALIAS_APPLE_APFS, /* An Apple APFS partition. */ G_PART_ALIAS_APPLE_BOOT, /* An Apple boot partition entry. */ G_PART_ALIAS_APPLE_CORE_STORAGE,/* An Apple Core Storage partition. */ G_PART_ALIAS_APPLE_HFS, /* An HFS+ file system entry. */ G_PART_ALIAS_APPLE_LABEL, /* An Apple label partition entry. */ G_PART_ALIAS_APPLE_RAID, /* An Apple RAID partition entry. */ G_PART_ALIAS_APPLE_RAID_OFFLINE,/* An Apple RAID (offline) part entry.*/ G_PART_ALIAS_APPLE_TV_RECOVERY, /* An Apple TV recovery part entry. */ G_PART_ALIAS_APPLE_UFS, /* An Apple UFS partition entry. */ G_PART_ALIAS_BIOS_BOOT, /* A GRUB 2 boot partition entry. */ G_PART_ALIAS_CHROMEOS_FIRMWARE, /* A ChromeOS firmware part. entry. */ G_PART_ALIAS_CHROMEOS_KERNEL, /* A ChromeOS Kernel part. entry. */ G_PART_ALIAS_CHROMEOS_RESERVED, /* ChromeOS. Reserved for future use. */ G_PART_ALIAS_CHROMEOS_ROOT, /* A ChromeOS root part. entry. */ G_PART_ALIAS_DFBSD, /* A DfBSD label32 partition entry */ G_PART_ALIAS_DFBSD64, /* A DfBSD label64 partition entry */ G_PART_ALIAS_DFBSD_CCD, /* A DfBSD CCD partition entry */ G_PART_ALIAS_DFBSD_HAMMER, /* A DfBSD HAMMER FS partition entry */ G_PART_ALIAS_DFBSD_HAMMER2, /* A DfBSD HAMMER2 FS partition entry */ G_PART_ALIAS_DFBSD_LEGACY, /* A DfBSD legacy partition entry */ G_PART_ALIAS_DFBSD_SWAP, /* A DfBSD swap partition entry */ G_PART_ALIAS_DFBSD_UFS, /* A DfBSD UFS partition entry */ G_PART_ALIAS_DFBSD_VINUM, /* A DfBSD Vinum partition entry */ G_PART_ALIAS_EBR, /* A EBR partition entry. */ G_PART_ALIAS_EFI, /* A EFI system partition entry. */ G_PART_ALIAS_FREEBSD, /* A BSD labeled partition entry. */ G_PART_ALIAS_FREEBSD_BOOT, /* A FreeBSD boot partition entry. */ G_PART_ALIAS_FREEBSD_NANDFS, /* A FreeBSD nandfs partition entry. */ G_PART_ALIAS_FREEBSD_SWAP, /* A swap partition entry. */ G_PART_ALIAS_FREEBSD_UFS, /* A UFS/UFS2 file system entry. */ G_PART_ALIAS_FREEBSD_VINUM, /* A Vinum partition entry. */ G_PART_ALIAS_FREEBSD_ZFS, /* A ZFS file system entry. */ G_PART_ALIAS_LINUX_DATA, /* A Linux data partition entry. */ G_PART_ALIAS_LINUX_LVM, /* A Linux LVM partition entry. */ G_PART_ALIAS_LINUX_RAID, /* A Linux RAID partition entry. */ G_PART_ALIAS_LINUX_SWAP, /* A Linux swap partition entry. */ G_PART_ALIAS_MBR, /* A MBR (extended) partition entry. */ G_PART_ALIAS_MS_BASIC_DATA, /* A Microsoft Data part. entry. */ G_PART_ALIAS_MS_FAT16, /* A Microsoft FAT16 partition entry. */ G_PART_ALIAS_MS_FAT32, /* A Microsoft FAT32 partition entry. */ G_PART_ALIAS_MS_FAT32LBA, /* A Microsoft FAT32 LBA partition entry */ G_PART_ALIAS_MS_LDM_DATA, /* A Microsoft LDM Data part. entry. */ G_PART_ALIAS_MS_LDM_METADATA, /* A Microsoft LDM Metadata entry. */ G_PART_ALIAS_MS_NTFS, /* A Microsoft NTFS partition entry */ G_PART_ALIAS_MS_RECOVERY, /* A Microsoft recovery part. entry. */ G_PART_ALIAS_MS_RESERVED, /* A Microsoft Reserved part. entry. */ G_PART_ALIAS_MS_SPACES, /* A Microsoft Spaces part. entry. */ G_PART_ALIAS_NETBSD_CCD, /* A NetBSD CCD partition entry. */ G_PART_ALIAS_NETBSD_CGD, /* A NetBSD CGD partition entry. */ G_PART_ALIAS_NETBSD_FFS, /* A NetBSD FFS partition entry. */ G_PART_ALIAS_NETBSD_LFS, /* A NetBSD LFS partition entry. */ G_PART_ALIAS_NETBSD_RAID, /* A NetBSD RAID partition entry. */ G_PART_ALIAS_NETBSD_SWAP, /* A NetBSD swap partition entry. */ G_PART_ALIAS_OPENBSD_DATA, /* An OpenBSD data partition entry. */ G_PART_ALIAS_PREP_BOOT, /* A PREP/CHRP boot partition entry. */ G_PART_ALIAS_VMFS, /* A VMware VMFS partition entry */ G_PART_ALIAS_VMKDIAG, /* A VMware vmkDiagnostic partition entry */ G_PART_ALIAS_VMRESERVED, /* A VMware reserved partition entry */ G_PART_ALIAS_VMVSANHDR, /* A VMware vSAN header partition entry */ /* Keep the following last */ G_PART_ALIAS_COUNT }; const char *g_part_alias_name(enum g_part_alias); /* G_PART scheme (KOBJ class). */ struct g_part_scheme { KOBJ_CLASS_FIELDS; size_t gps_entrysz; int gps_minent; int gps_maxent; int gps_bootcodesz; TAILQ_ENTRY(g_part_scheme) scheme_list; }; struct g_part_entry { LIST_ENTRY(g_part_entry) gpe_entry; struct g_provider *gpe_pp; /* Corresponding provider. */ off_t gpe_offset; /* Byte offset. */ quad_t gpe_start; /* First LBA of partition. */ quad_t gpe_end; /* Last LBA of partition. */ int gpe_index; int gpe_created:1; /* Entry is newly created. */ int gpe_deleted:1; /* Entry has been deleted. */ int gpe_modified:1; /* Entry has been modified. */ int gpe_internal:1; /* Entry is not a used entry. */ }; /* G_PART table (KOBJ instance). */ struct g_part_table { KOBJ_FIELDS; struct g_part_scheme *gpt_scheme; struct g_geom *gpt_gp; LIST_HEAD(, g_part_entry) gpt_entry; quad_t gpt_first; /* First allocatable LBA */ quad_t gpt_last; /* Last allocatable LBA */ int gpt_entries; /* * gpt_smhead and gpt_smtail are bitmaps representing the first * 32 sectors on the disk (gpt_smhead) and the last 32 sectors * on the disk (gpt_smtail). These maps are used by the commit * verb to clear sectors previously used by a scheme after the * partitioning scheme has been destroyed. */ uint32_t gpt_smhead; uint32_t gpt_smtail; /* * gpt_sectors and gpt_heads are the fixed or synchesized number * of sectors per track and heads (resp) that make up a disks * geometry. This is to support partitioning schemes as well as * file systems that work on a geometry. The MBR scheme and the * MS-DOS (FAT) file system come to mind. * We keep track of whether the geometry is fixed or synchesized * so that a partitioning scheme can correct the synthesized * geometry, based on the on-disk metadata. */ uint32_t gpt_sectors; uint32_t gpt_heads; int gpt_depth; /* Sub-partitioning level. */ int gpt_isleaf:1; /* Cannot be sub-partitioned. */ int gpt_created:1; /* Newly created. */ int gpt_modified:1; /* Table changes have been made. */ int gpt_opened:1; /* Permissions obtained. */ int gpt_fixgeom:1; /* Geometry is fixed. */ int gpt_corrupt:1; /* Table is corrupt. */ }; struct g_part_entry *g_part_new_entry(struct g_part_table *, int, quad_t, quad_t); enum g_part_ctl { G_PART_CTL_NONE, G_PART_CTL_ADD, G_PART_CTL_BOOTCODE, G_PART_CTL_COMMIT, G_PART_CTL_CREATE, G_PART_CTL_DELETE, G_PART_CTL_DESTROY, G_PART_CTL_MODIFY, G_PART_CTL_MOVE, G_PART_CTL_RECOVER, G_PART_CTL_RESIZE, G_PART_CTL_SET, G_PART_CTL_UNDO, G_PART_CTL_UNSET }; /* G_PART ctlreq parameters. */ #define G_PART_PARM_ENTRIES 0x0001 #define G_PART_PARM_FLAGS 0x0002 #define G_PART_PARM_GEOM 0x0004 #define G_PART_PARM_INDEX 0x0008 #define G_PART_PARM_LABEL 0x0010 #define G_PART_PARM_OUTPUT 0x0020 #define G_PART_PARM_PROVIDER 0x0040 #define G_PART_PARM_SCHEME 0x0080 #define G_PART_PARM_SIZE 0x0100 #define G_PART_PARM_START 0x0200 #define G_PART_PARM_TYPE 0x0400 #define G_PART_PARM_VERSION 0x0800 #define G_PART_PARM_BOOTCODE 0x1000 #define G_PART_PARM_ATTRIB 0x2000 #define G_PART_PARM_FORCE 0x4000 +#define G_PART_PARM_SKIP_DSN 0x8000 struct g_part_parms { unsigned int gpp_parms; unsigned int gpp_entries; const char *gpp_flags; struct g_geom *gpp_geom; unsigned int gpp_index; const char *gpp_label; struct g_provider *gpp_provider; struct g_part_scheme *gpp_scheme; quad_t gpp_size; quad_t gpp_start; const char *gpp_type; unsigned int gpp_version; const void *gpp_codeptr; unsigned int gpp_codesize; const char *gpp_attrib; unsigned int gpp_force; + unsigned int gpp_skip_dsn; }; void g_part_geometry_heads(off_t, u_int, off_t *, u_int *); int g_part_modevent(module_t, int, struct g_part_scheme *); #define G_PART_SCHEME_DECLARE(name) \ static int name##_modevent(module_t mod, int tp, void *d) \ { \ return (g_part_modevent(mod, tp, d)); \ } \ static moduledata_t name##_mod = { \ #name, \ name##_modevent, \ &name##_scheme \ }; \ DECLARE_MODULE(name, name##_mod, SI_SUB_DRIVERS, SI_ORDER_ANY); \ MODULE_DEPEND(name, g_part, 0, 0, 0) #endif /* !_GEOM_PART_H_ */ Index: head/sys/geom/part/g_part_mbr.c =================================================================== --- head/sys/geom/part/g_part_mbr.c (revision 341066) +++ head/sys/geom/part/g_part_mbr.c (revision 341067) @@ -1,618 +1,618 @@ /*- * 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 AUTHOR ``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 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 "g_part_if.h" FEATURE(geom_part_mbr, "GEOM partitioning class for MBR support"); SYSCTL_DECL(_kern_geom_part); static SYSCTL_NODE(_kern_geom_part, OID_AUTO, mbr, CTLFLAG_RW, 0, "GEOM_PART_MBR Master Boot Record"); static u_int enforce_chs = 0; SYSCTL_UINT(_kern_geom_part_mbr, OID_AUTO, enforce_chs, CTLFLAG_RWTUN, &enforce_chs, 0, "Enforce alignment to CHS addressing"); #define MBRSIZE 512 struct g_part_mbr_table { struct g_part_table base; u_char mbr[MBRSIZE]; }; struct g_part_mbr_entry { struct g_part_entry base; struct dos_partition ent; }; static int g_part_mbr_add(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static int g_part_mbr_bootcode(struct g_part_table *, struct g_part_parms *); static int g_part_mbr_create(struct g_part_table *, struct g_part_parms *); static int g_part_mbr_destroy(struct g_part_table *, struct g_part_parms *); static void g_part_mbr_dumpconf(struct g_part_table *, struct g_part_entry *, struct sbuf *, const char *); static int g_part_mbr_dumpto(struct g_part_table *, struct g_part_entry *); static int g_part_mbr_modify(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static const char *g_part_mbr_name(struct g_part_table *, struct g_part_entry *, char *, size_t); static int g_part_mbr_probe(struct g_part_table *, struct g_consumer *); static int g_part_mbr_read(struct g_part_table *, struct g_consumer *); static int g_part_mbr_setunset(struct g_part_table *, struct g_part_entry *, const char *, unsigned int); static const char *g_part_mbr_type(struct g_part_table *, struct g_part_entry *, char *, size_t); static int g_part_mbr_write(struct g_part_table *, struct g_consumer *); static int g_part_mbr_resize(struct g_part_table *, struct g_part_entry *, struct g_part_parms *); static kobj_method_t g_part_mbr_methods[] = { KOBJMETHOD(g_part_add, g_part_mbr_add), KOBJMETHOD(g_part_bootcode, g_part_mbr_bootcode), KOBJMETHOD(g_part_create, g_part_mbr_create), KOBJMETHOD(g_part_destroy, g_part_mbr_destroy), KOBJMETHOD(g_part_dumpconf, g_part_mbr_dumpconf), KOBJMETHOD(g_part_dumpto, g_part_mbr_dumpto), KOBJMETHOD(g_part_modify, g_part_mbr_modify), KOBJMETHOD(g_part_resize, g_part_mbr_resize), KOBJMETHOD(g_part_name, g_part_mbr_name), KOBJMETHOD(g_part_probe, g_part_mbr_probe), KOBJMETHOD(g_part_read, g_part_mbr_read), KOBJMETHOD(g_part_setunset, g_part_mbr_setunset), KOBJMETHOD(g_part_type, g_part_mbr_type), KOBJMETHOD(g_part_write, g_part_mbr_write), { 0, 0 } }; static struct g_part_scheme g_part_mbr_scheme = { "MBR", g_part_mbr_methods, sizeof(struct g_part_mbr_table), .gps_entrysz = sizeof(struct g_part_mbr_entry), .gps_minent = NDOSPART, .gps_maxent = NDOSPART, .gps_bootcodesz = MBRSIZE, }; G_PART_SCHEME_DECLARE(g_part_mbr); MODULE_VERSION(geom_part_mbr, 0); static struct g_part_mbr_alias { u_char typ; int alias; } mbr_alias_match[] = { { DOSPTYP_386BSD, G_PART_ALIAS_FREEBSD }, { DOSPTYP_APPLE_BOOT, G_PART_ALIAS_APPLE_BOOT }, { DOSPTYP_APPLE_UFS, G_PART_ALIAS_APPLE_UFS }, { DOSPTYP_EFI, G_PART_ALIAS_EFI }, { DOSPTYP_EXT, G_PART_ALIAS_EBR }, { DOSPTYP_EXTLBA, G_PART_ALIAS_EBR }, { DOSPTYP_FAT16, G_PART_ALIAS_MS_FAT16 }, { DOSPTYP_FAT32, G_PART_ALIAS_MS_FAT32 }, { DOSPTYP_FAT32LBA, G_PART_ALIAS_MS_FAT32LBA }, { DOSPTYP_HFS, G_PART_ALIAS_APPLE_HFS }, { DOSPTYP_LDM, G_PART_ALIAS_MS_LDM_DATA }, { DOSPTYP_LINLVM, G_PART_ALIAS_LINUX_LVM }, { DOSPTYP_LINRAID, G_PART_ALIAS_LINUX_RAID }, { DOSPTYP_LINSWP, G_PART_ALIAS_LINUX_SWAP }, { DOSPTYP_LINUX, G_PART_ALIAS_LINUX_DATA }, { DOSPTYP_NTFS, G_PART_ALIAS_MS_NTFS }, { DOSPTYP_PPCBOOT, G_PART_ALIAS_PREP_BOOT }, { DOSPTYP_VMFS, G_PART_ALIAS_VMFS }, { DOSPTYP_VMKDIAG, G_PART_ALIAS_VMKDIAG }, }; static int mbr_parse_type(const char *type, u_char *dp_typ) { const char *alias; char *endp; long lt; int i; if (type[0] == '!') { lt = strtol(type + 1, &endp, 0); if (type[1] == '\0' || *endp != '\0' || lt <= 0 || lt >= 256) return (EINVAL); *dp_typ = (u_char)lt; return (0); } for (i = 0; i < nitems(mbr_alias_match); i++) { alias = g_part_alias_name(mbr_alias_match[i].alias); if (strcasecmp(type, alias) == 0) { *dp_typ = mbr_alias_match[i].typ; return (0); } } return (EINVAL); } static int mbr_probe_bpb(u_char *bpb) { uint16_t secsz; uint8_t clstsz; #define PO2(x) ((x & (x - 1)) == 0) secsz = le16dec(bpb); if (secsz < 512 || secsz > 4096 || !PO2(secsz)) return (0); clstsz = bpb[2]; if (clstsz < 1 || clstsz > 128 || !PO2(clstsz)) return (0); #undef PO2 return (1); } static void mbr_set_chs(struct g_part_table *table, uint32_t lba, u_char *cylp, u_char *hdp, u_char *secp) { uint32_t cyl, hd, sec; sec = lba % table->gpt_sectors + 1; lba /= table->gpt_sectors; hd = lba % table->gpt_heads; lba /= table->gpt_heads; cyl = lba; if (cyl > 1023) sec = hd = cyl = ~0; *cylp = cyl & 0xff; *hdp = hd & 0xff; *secp = (sec & 0x3f) | ((cyl >> 2) & 0xc0); } static int mbr_align(struct g_part_table *basetable, uint32_t *start, uint32_t *size) { uint32_t sectors; if (enforce_chs == 0) return (0); sectors = basetable->gpt_sectors; if (*size < sectors) return (EINVAL); if (start != NULL && (*start % sectors)) { *size += (*start % sectors) - sectors; *start -= (*start % sectors) - sectors; } if (*size % sectors) *size -= (*size % sectors); if (*size < sectors) return (EINVAL); return (0); } static int g_part_mbr_add(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_mbr_entry *entry; uint32_t start, size; if (gpp->gpp_parms & G_PART_PARM_LABEL) return (EINVAL); entry = (struct g_part_mbr_entry *)baseentry; start = gpp->gpp_start; size = gpp->gpp_size; if (mbr_align(basetable, &start, &size) != 0) return (EINVAL); if (baseentry->gpe_deleted) bzero(&entry->ent, sizeof(entry->ent)); KASSERT(baseentry->gpe_start <= start, ("%s", __func__)); KASSERT(baseentry->gpe_end >= start + size - 1, ("%s", __func__)); baseentry->gpe_start = start; baseentry->gpe_end = start + size - 1; entry->ent.dp_start = start; entry->ent.dp_size = size; mbr_set_chs(basetable, baseentry->gpe_start, &entry->ent.dp_scyl, &entry->ent.dp_shd, &entry->ent.dp_ssect); mbr_set_chs(basetable, baseentry->gpe_end, &entry->ent.dp_ecyl, &entry->ent.dp_ehd, &entry->ent.dp_esect); return (mbr_parse_type(gpp->gpp_type, &entry->ent.dp_typ)); } static int g_part_mbr_bootcode(struct g_part_table *basetable, struct g_part_parms *gpp) { struct g_part_mbr_table *table; uint32_t dsn; if (gpp->gpp_codesize != MBRSIZE) return (ENODEV); table = (struct g_part_mbr_table *)basetable; dsn = *(uint32_t *)(table->mbr + DOSDSNOFF); bcopy(gpp->gpp_codeptr, table->mbr, DOSPARTOFF); - if (dsn != 0) + if (dsn != 0 && !gpp->gpp_skip_dsn) *(uint32_t *)(table->mbr + DOSDSNOFF) = dsn; return (0); } static int g_part_mbr_create(struct g_part_table *basetable, struct g_part_parms *gpp) { struct g_provider *pp; struct g_part_mbr_table *table; pp = gpp->gpp_provider; if (pp->sectorsize < MBRSIZE) return (ENOSPC); basetable->gpt_first = basetable->gpt_sectors; basetable->gpt_last = MIN(pp->mediasize / pp->sectorsize, UINT32_MAX) - 1; table = (struct g_part_mbr_table *)basetable; le16enc(table->mbr + DOSMAGICOFFSET, DOSMAGIC); return (0); } static int g_part_mbr_destroy(struct g_part_table *basetable, struct g_part_parms *gpp) { /* Wipe the first sector to clear the partitioning. */ basetable->gpt_smhead |= 1; return (0); } static void g_part_mbr_dumpconf(struct g_part_table *basetable, struct g_part_entry *baseentry, struct sbuf *sb, const char *indent) { struct g_part_mbr_entry *entry; struct g_part_mbr_table *table; uint32_t dsn; table = (struct g_part_mbr_table *)basetable; entry = (struct g_part_mbr_entry *)baseentry; if (indent == NULL) { /* conftxt: libdisk compatibility */ sbuf_printf(sb, " xs MBR xt %u", entry->ent.dp_typ); } else if (entry != NULL) { /* confxml: partition entry information */ sbuf_printf(sb, "%s%u\n", indent, entry->ent.dp_typ); if (entry->ent.dp_flag & 0x80) sbuf_printf(sb, "%sactive\n", indent); dsn = le32dec(table->mbr + DOSDSNOFF); sbuf_printf(sb, "%sHD(%d,MBR,%#08x,%#jx,%#jx)", indent, entry->base.gpe_index, dsn, (intmax_t)entry->base.gpe_start, (intmax_t)(entry->base.gpe_end - entry->base.gpe_start + 1)); sbuf_printf(sb, "\n"); } else { /* confxml: scheme information */ } } static int g_part_mbr_dumpto(struct g_part_table *table, struct g_part_entry *baseentry) { struct g_part_mbr_entry *entry; /* Allow dumping to a FreeBSD partition or Linux swap partition only. */ entry = (struct g_part_mbr_entry *)baseentry; return ((entry->ent.dp_typ == DOSPTYP_386BSD || entry->ent.dp_typ == DOSPTYP_LINSWP) ? 1 : 0); } static int g_part_mbr_modify(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_mbr_entry *entry; if (gpp->gpp_parms & G_PART_PARM_LABEL) return (EINVAL); entry = (struct g_part_mbr_entry *)baseentry; if (gpp->gpp_parms & G_PART_PARM_TYPE) return (mbr_parse_type(gpp->gpp_type, &entry->ent.dp_typ)); return (0); } static int g_part_mbr_resize(struct g_part_table *basetable, struct g_part_entry *baseentry, struct g_part_parms *gpp) { struct g_part_mbr_entry *entry; struct g_provider *pp; uint32_t size; if (baseentry == NULL) { pp = LIST_FIRST(&basetable->gpt_gp->consumer)->provider; basetable->gpt_last = MIN(pp->mediasize / pp->sectorsize, UINT32_MAX) - 1; return (0); } size = gpp->gpp_size; if (mbr_align(basetable, NULL, &size) != 0) return (EINVAL); /* XXX: prevent unexpected shrinking. */ pp = baseentry->gpe_pp; if ((g_debugflags & 0x10) == 0 && size < gpp->gpp_size && pp->mediasize / pp->sectorsize > size) return (EBUSY); entry = (struct g_part_mbr_entry *)baseentry; baseentry->gpe_end = baseentry->gpe_start + size - 1; entry->ent.dp_size = size; mbr_set_chs(basetable, baseentry->gpe_end, &entry->ent.dp_ecyl, &entry->ent.dp_ehd, &entry->ent.dp_esect); return (0); } static const char * g_part_mbr_name(struct g_part_table *table, struct g_part_entry *baseentry, char *buf, size_t bufsz) { snprintf(buf, bufsz, "s%d", baseentry->gpe_index); return (buf); } static int g_part_mbr_probe(struct g_part_table *table, struct g_consumer *cp) { char psn[8]; struct g_provider *pp; u_char *buf, *p; int error, index, res, sum; uint16_t magic; pp = cp->provider; /* Sanity-check the provider. */ if (pp->sectorsize < MBRSIZE || pp->mediasize < pp->sectorsize) return (ENOSPC); if (pp->sectorsize > 4096) return (ENXIO); /* We don't nest under an MBR (see EBR instead). */ error = g_getattr("PART::scheme", cp, &psn); if (error == 0 && strcmp(psn, g_part_mbr_scheme.name) == 0) return (ELOOP); /* Check that there's a MBR. */ buf = g_read_data(cp, 0L, pp->sectorsize, &error); if (buf == NULL) return (error); /* We goto out on mismatch. */ res = ENXIO; magic = le16dec(buf + DOSMAGICOFFSET); if (magic != DOSMAGIC) goto out; for (index = 0; index < NDOSPART; index++) { p = buf + DOSPARTOFF + index * DOSPARTSIZE; if (p[0] != 0 && p[0] != 0x80) goto out; } /* * If the partition table does not consist of all zeroes, * assume we have a MBR. If it's all zeroes, we could have * a boot sector. For example, a boot sector that doesn't * have boot code -- common on non-i386 hardware. In that * case we check if we have a possible BPB. If so, then we * assume we have a boot sector instead. */ sum = 0; for (index = 0; index < NDOSPART * DOSPARTSIZE; index++) sum += buf[DOSPARTOFF + index]; if (sum != 0 || !mbr_probe_bpb(buf + 0x0b)) res = G_PART_PROBE_PRI_NORM; out: g_free(buf); return (res); } static int g_part_mbr_read(struct g_part_table *basetable, struct g_consumer *cp) { struct dos_partition ent; struct g_provider *pp; struct g_part_mbr_table *table; struct g_part_mbr_entry *entry; u_char *buf, *p; off_t chs, msize, first; u_int sectors, heads; int error, index; pp = cp->provider; table = (struct g_part_mbr_table *)basetable; first = basetable->gpt_sectors; msize = MIN(pp->mediasize / pp->sectorsize, UINT32_MAX); buf = g_read_data(cp, 0L, pp->sectorsize, &error); if (buf == NULL) return (error); bcopy(buf, table->mbr, sizeof(table->mbr)); for (index = NDOSPART - 1; index >= 0; index--) { p = buf + DOSPARTOFF + index * DOSPARTSIZE; ent.dp_flag = p[0]; ent.dp_shd = p[1]; ent.dp_ssect = p[2]; ent.dp_scyl = p[3]; ent.dp_typ = p[4]; ent.dp_ehd = p[5]; ent.dp_esect = p[6]; ent.dp_ecyl = p[7]; ent.dp_start = le32dec(p + 8); ent.dp_size = le32dec(p + 12); if (ent.dp_typ == 0 || ent.dp_typ == DOSPTYP_PMBR) continue; if (ent.dp_start == 0 || ent.dp_size == 0) continue; sectors = ent.dp_esect & 0x3f; if (sectors > basetable->gpt_sectors && !basetable->gpt_fixgeom) { g_part_geometry_heads(msize, sectors, &chs, &heads); if (chs != 0) { basetable->gpt_sectors = sectors; basetable->gpt_heads = heads; } } if (ent.dp_start < first) first = ent.dp_start; entry = (struct g_part_mbr_entry *)g_part_new_entry(basetable, index + 1, ent.dp_start, ent.dp_start + ent.dp_size - 1); entry->ent = ent; } basetable->gpt_entries = NDOSPART; basetable->gpt_first = basetable->gpt_sectors; basetable->gpt_last = msize - 1; if (first < basetable->gpt_first) basetable->gpt_first = 1; g_free(buf); return (0); } static int g_part_mbr_setunset(struct g_part_table *table, struct g_part_entry *baseentry, const char *attrib, unsigned int set) { struct g_part_entry *iter; struct g_part_mbr_entry *entry; int changed; if (baseentry == NULL) return (ENODEV); if (strcasecmp(attrib, "active") != 0) return (EINVAL); /* Only one entry can have the active attribute. */ LIST_FOREACH(iter, &table->gpt_entry, gpe_entry) { if (iter->gpe_deleted) continue; changed = 0; entry = (struct g_part_mbr_entry *)iter; if (iter == baseentry) { if (set && (entry->ent.dp_flag & 0x80) == 0) { entry->ent.dp_flag |= 0x80; changed = 1; } else if (!set && (entry->ent.dp_flag & 0x80)) { entry->ent.dp_flag &= ~0x80; changed = 1; } } else { if (set && (entry->ent.dp_flag & 0x80)) { entry->ent.dp_flag &= ~0x80; changed = 1; } } if (changed && !iter->gpe_created) iter->gpe_modified = 1; } return (0); } static const char * g_part_mbr_type(struct g_part_table *basetable, struct g_part_entry *baseentry, char *buf, size_t bufsz) { struct g_part_mbr_entry *entry; int i; entry = (struct g_part_mbr_entry *)baseentry; for (i = 0; i < nitems(mbr_alias_match); i++) { if (mbr_alias_match[i].typ == entry->ent.dp_typ) return (g_part_alias_name(mbr_alias_match[i].alias)); } snprintf(buf, bufsz, "!%d", entry->ent.dp_typ); return (buf); } static int g_part_mbr_write(struct g_part_table *basetable, struct g_consumer *cp) { struct g_part_entry *baseentry; struct g_part_mbr_entry *entry; struct g_part_mbr_table *table; u_char *p; int error, index; table = (struct g_part_mbr_table *)basetable; baseentry = LIST_FIRST(&basetable->gpt_entry); for (index = 1; index <= basetable->gpt_entries; index++) { p = table->mbr + DOSPARTOFF + (index - 1) * DOSPARTSIZE; entry = (baseentry != NULL && index == baseentry->gpe_index) ? (struct g_part_mbr_entry *)baseentry : NULL; if (entry != NULL && !baseentry->gpe_deleted) { p[0] = entry->ent.dp_flag; p[1] = entry->ent.dp_shd; p[2] = entry->ent.dp_ssect; p[3] = entry->ent.dp_scyl; p[4] = entry->ent.dp_typ; p[5] = entry->ent.dp_ehd; p[6] = entry->ent.dp_esect; p[7] = entry->ent.dp_ecyl; le32enc(p + 8, entry->ent.dp_start); le32enc(p + 12, entry->ent.dp_size); } else bzero(p, DOSPARTSIZE); if (entry != NULL) baseentry = LIST_NEXT(baseentry, gpe_entry); } error = g_write_data(cp, 0, table->mbr, cp->provider->sectorsize); return (error); } Index: head/usr.sbin/boot0cfg/boot0cfg.c =================================================================== --- head/usr.sbin/boot0cfg/boot0cfg.c (revision 341066) +++ head/usr.sbin/boot0cfg/boot0cfg.c (revision 341067) @@ -1,608 +1,612 @@ /* * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2008 Luigi Rizzo * Copyright (c) 1999 Robert Nordier * 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. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #define MBRSIZE 512 /* master boot record size */ #define OFF_VERSION 0x1b0 /* offset: version number, only boot0version */ #define OFF_SERIAL 0x1b8 /* offset: volume serial number */ #define OFF_PTBL 0x1be /* offset: partition table */ #define OFF_MAGIC 0x1fe /* offset: magic number */ /* * Offsets to the parameters of the 512-byte boot block. * For historical reasons they are set as macros */ struct opt_offsets { int opt; int drive; int flags; int ticks; }; static struct opt_offsets b0_ofs[] = { { 0x0, 0x0, 0x0, 0x0 }, /* no boot block */ { 0x1b9, 0x1ba, 0x1bb, 0x1bc }, /* original block */ { 0x1b5, 0x1b6, 0x1b7, 0x1bc }, /* NT_SERIAL block */ }; static int b0_ver; /* boot block version set by boot0bs */ #define OFF_OPT (b0_ofs[b0_ver].opt) /* default boot option */ #define OFF_DRIVE (b0_ofs[b0_ver].drive) /* setdrv drive */ #define OFF_FLAGS (b0_ofs[b0_ver].flags) /* option flags */ #define OFF_TICKS (b0_ofs[b0_ver].ticks) /* clock ticks */ #define cv2(p) ((p)[0] | (p)[1] << 010) #define mk2(p, x) \ (p)[0] = (u_int8_t)(x), \ (p)[1] = (u_int8_t)((x) >> 010) static const struct { const char *tok; int def; } opttbl[] = { {"packet", 0}, {"update", 1}, {"setdrv", 0} }; static const int nopt = nitems(opttbl); static const char fmt0[] = "# flag start chs type" " end chs offset size\n"; static const char fmt1[] = "%d 0x%02x %4u:%3u:%2u 0x%02x" " %4u:%3u:%2u %10u %10u\n"; static int geom_class_available(const char *); static int read_mbr(const char *, u_int8_t **, int); -static void write_mbr(const char *, int, u_int8_t *, int); +static void write_mbr(const char *, int, u_int8_t *, int, int); static void display_mbr(u_int8_t *); static int boot0version(const u_int8_t *); static int boot0bs(const u_int8_t *); static void stropt(const char *, int *, int *); static int argtoi(const char *, int, int, int); static int set_bell(u_int8_t *, int, int); static void usage(void); static unsigned vol_id[5]; /* 4 plus 1 for flag */ static int v_flag; /* * Boot manager installation/configuration utility. */ int main(int argc, char *argv[]) { u_int8_t *mbr, *boot0; int boot0_size, mbr_size; const char *bpath, *fpath; char *disk; int B_flag, o_flag; int d_arg, m_arg, s_arg, t_arg; int o_and, o_or, o_e = -1; int up, c; bpath = "/boot/boot0"; fpath = NULL; B_flag = v_flag = o_flag = 0; d_arg = m_arg = s_arg = t_arg = -1; o_and = 0xff; o_or = 0; while ((c = getopt(argc, argv, "Bvb:d:e:f:i:m:o:s:t:")) != -1) switch (c) { case 'B': B_flag = 1; break; case 'v': v_flag = 1; break; case 'b': bpath = optarg; break; case 'd': d_arg = argtoi(optarg, 0, 0xff, 'd'); break; case 'e': if (optarg[0] == '0' && optarg[1] == 'x') sscanf(optarg, "0x%02x", &o_e); else o_e = optarg[0]; break; case 'f': fpath = optarg; break; case 'i': if (sscanf(optarg, "%02x%02x-%02x%02x", vol_id, vol_id+1, vol_id+2, vol_id+3) == 4) vol_id[4] = 1; else errx(1, "bad argument %s", optarg); break; case 'm': m_arg = argtoi(optarg, 0, 0xf, 'm'); break; case 'o': stropt(optarg, &o_and, &o_or); o_flag = 1; break; case 's': if (strcasecmp(optarg, "pxe") == 0) s_arg = 6; else s_arg = argtoi(optarg, 1, 6, 's'); break; case 't': t_arg = argtoi(optarg, 1, 0xffff, 't'); break; default: usage(); } argc -= optind; argv += optind; if (argc != 1) usage(); disk = g_device_path(*argv); if (disk == NULL) errx(1, "Unable to get providername for %s\n", *argv); up = B_flag || d_arg != -1 || m_arg != -1 || o_flag || s_arg != -1 || t_arg != -1; /* open the disk and read in the existing mbr. Either here or * when reading the block from disk, we do check for the version * and abort if a suitable block is not found. */ mbr_size = read_mbr(disk, &mbr, !B_flag); /* save the existing MBR if we are asked to do so */ if (fpath) - write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size); + write_mbr(fpath, O_CREAT | O_TRUNC, mbr, mbr_size, 0); /* * If we are installing the boot loader, read it from disk and copy the * slice table over from the existing MBR. If not, then point boot0 * back at the MBR we just read in. After this, boot0 is the data to * write back to disk if we are going to do a write. */ if (B_flag) { boot0_size = read_mbr(bpath, &boot0, 1); memcpy(boot0 + OFF_PTBL, mbr + OFF_PTBL, sizeof(struct dos_partition) * NDOSPART); if (b0_ver == 2) /* volume serial number support */ memcpy(boot0 + OFF_SERIAL, mbr + OFF_SERIAL, 4); } else { boot0 = mbr; boot0_size = mbr_size; } /* set the drive */ if (d_arg != -1) boot0[OFF_DRIVE] = d_arg; /* set various flags */ if (m_arg != -1) { boot0[OFF_FLAGS] &= 0xf0; boot0[OFF_FLAGS] |= m_arg; } if (o_flag) { boot0[OFF_FLAGS] &= o_and; boot0[OFF_FLAGS] |= o_or; } /* set the default boot selection */ if (s_arg != -1) boot0[OFF_OPT] = s_arg - 1; /* set the timeout */ if (t_arg != -1) mk2(boot0 + OFF_TICKS, t_arg); /* set the bell char */ if (o_e != -1 && set_bell(boot0, o_e, 0) != -1) up = 1; if (vol_id[4]) { if (b0_ver != 2) errx(1, "incompatible boot block, cannot set volume ID"); boot0[OFF_SERIAL] = vol_id[0]; boot0[OFF_SERIAL+1] = vol_id[1]; boot0[OFF_SERIAL+2] = vol_id[2]; boot0[OFF_SERIAL+3] = vol_id[3]; up = 1; /* force update */ } /* write the MBR back to disk */ if (up) - write_mbr(disk, 0, boot0, boot0_size); + write_mbr(disk, 0, boot0, boot0_size, vol_id[4] || b0_ver == 1); /* display the MBR */ if (v_flag) display_mbr(boot0); /* clean up */ if (mbr != boot0) free(boot0); free(mbr); free(disk); return 0; } /* get or set the 'bell' character to be used in case of errors. * Lookup for a certain code sequence, return -1 if not found. */ static int set_bell(u_int8_t *mbr, int new_bell, int report) { /* lookup sequence: 0x100 means skip, 0x200 means done */ static unsigned seq[] = { 0xb0, 0x100, 0xe8, 0x100, 0x100, 0x30, 0xe4, 0x200 }; int ofs, i, c; for (ofs = 0x60; ofs < 0x180; ofs++) { /* search range */ if (mbr[ofs] != seq[0]) /* search initial pattern */ continue; for (i=0;; i++) { if (seq[i] == 0x200) { /* found */ c = mbr[ofs+1]; if (!report) mbr[ofs+1] = c = new_bell; else printf(" bell=%c (0x%x)", (c >= ' ' && c < 0x7f) ? c : ' ', c); return c; } if (seq[i] != 0x100 && seq[i] != mbr[ofs+i]) break; } } warn("bell not found"); return -1; } /* * Read in the MBR of the disk. If it is boot0, then use the version to * read in all of it if necessary. Use pointers to return a malloc'd * buffer containing the MBR and then return its size. */ static int read_mbr(const char *disk, u_int8_t **mbr, int check_version) { u_int8_t buf[MBRSIZE]; int mbr_size, fd; int ver; ssize_t n; if ((fd = open(disk, O_RDONLY)) == -1) err(1, "open %s", disk); if ((n = read(fd, buf, MBRSIZE)) == -1) err(1, "read %s", disk); if (n != MBRSIZE) errx(1, "%s: short read", disk); if (cv2(buf + OFF_MAGIC) != 0xaa55) errx(1, "%s: bad magic", disk); if (! (ver = boot0bs(buf))) { if (check_version) errx(1, "%s: unknown or incompatible boot code", disk); } else if (boot0version(buf) == 0x101) { mbr_size = 1024; if ((*mbr = malloc(mbr_size)) == NULL) errx(1, "%s: unable to allocate read buffer", disk); if (lseek(fd, 0, SEEK_SET) == -1 || (n = read(fd, *mbr, mbr_size)) == -1) err(1, "%s", disk); if (n != mbr_size) errx(1, "%s: short read", disk); close(fd); return (mbr_size); } if ((*mbr = malloc(sizeof(buf))) == NULL) errx(1, "%s: unable to allocate MBR buffer", disk); memcpy(*mbr, buf, sizeof(buf)); close(fd); return sizeof(buf); } static int geom_class_available(const char *name) { struct gclass *class; struct gmesh mesh; int error; error = geom_gettree(&mesh); if (error != 0) errc(1, error, "Cannot get GEOM tree"); LIST_FOREACH(class, &mesh.lg_class, lg_class) { if (strcmp(class->lg_name, name) == 0) { geom_deletetree(&mesh); return (1); } } geom_deletetree(&mesh); return (0); } /* * Write out the mbr to the specified file. */ static void -write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size) +write_mbr(const char *fname, int flags, u_int8_t *mbr, int mbr_size, + int disable_dsn) { struct gctl_req *grq; const char *errmsg; char *pname; ssize_t n; int fd; fd = open(fname, O_WRONLY | flags, 0666); if (fd != -1) { n = write(fd, mbr, mbr_size); close(fd); if (n != mbr_size) errx(1, "%s: short write", fname); return; } /* * If we're called to write to a backup file, don't try to * write through GEOM. */ if (flags != 0) err(1, "can't open file %s to write backup", fname); /* Try open it read only. */ fd = open(fname, O_RDONLY); if (fd == -1) { warn("error opening %s", fname); return; } pname = g_providername(fd); if (pname == NULL) { warn("error getting providername for %s", fname); return; } /* First check that GEOM_PART is available */ if (geom_class_available("PART") != 0) { grq = gctl_get_handle(); gctl_ro_param(grq, "class", -1, "PART"); gctl_ro_param(grq, "arg0", -1, pname); gctl_ro_param(grq, "verb", -1, "bootcode"); gctl_ro_param(grq, "bootcode", mbr_size, mbr); gctl_ro_param(grq, "flags", -1, "C"); + if (disable_dsn) + gctl_ro_param(grq, "skip_dsn", sizeof(int), + &disable_dsn); errmsg = gctl_issue(grq); if (errmsg != NULL && errmsg[0] != '\0') errx(1, "GEOM_PART: write bootcode to %s failed: %s", fname, errmsg); gctl_free(grq); } else if (geom_class_available("MBR") != 0) { grq = gctl_get_handle(); gctl_ro_param(grq, "verb", -1, "write MBR"); gctl_ro_param(grq, "class", -1, "MBR"); gctl_ro_param(grq, "geom", -1, pname); gctl_ro_param(grq, "data", mbr_size, mbr); errmsg = gctl_issue(grq); if (errmsg != NULL) err(1, "GEOM_MBR: write MBR to %s failed", fname); gctl_free(grq); } else errx(1, "can't write MBR to %s", fname); free(pname); } /* * Outputs an informative dump of the data in the MBR to stdout. */ static void display_mbr(u_int8_t *mbr) { struct dos_partition *part; int i, version; part = (struct dos_partition *)(mbr + DOSPARTOFF); printf(fmt0); for (i = 0; i < NDOSPART; i++) if (part[i].dp_typ) printf(fmt1, 1 + i, part[i].dp_flag, part[i].dp_scyl + ((part[i].dp_ssect & 0xc0) << 2), part[i].dp_shd, part[i].dp_ssect & 0x3f, part[i].dp_typ, part[i].dp_ecyl + ((part[i].dp_esect & 0xc0) << 2), part[i].dp_ehd, part[i].dp_esect & 0x3f, part[i].dp_start, part[i].dp_size); printf("\n"); version = boot0version(mbr); printf("version=%d.%d drive=0x%x mask=0x%x ticks=%u", version >> 8, version & 0xff, mbr[OFF_DRIVE], mbr[OFF_FLAGS] & 0xf, cv2(mbr + OFF_TICKS)); set_bell(mbr, 0, 1); printf("\noptions="); for (i = 0; i < nopt; i++) { if (i) printf(","); if (!(mbr[OFF_FLAGS] & 1 << (7 - i)) ^ opttbl[i].def) printf("no"); printf("%s", opttbl[i].tok); } printf("\n"); if (b0_ver == 2) printf("volume serial ID %02x%02x-%02x%02x\n", mbr[OFF_SERIAL], mbr[OFF_SERIAL+1], mbr[OFF_SERIAL+2], mbr[OFF_SERIAL+3]); printf("default_selection=F%d (", mbr[OFF_OPT] + 1); if (mbr[OFF_OPT] < 4) printf("Slice %d", mbr[OFF_OPT] + 1); else if (mbr[OFF_OPT] == 4) printf("Drive 1"); else printf("PXE"); printf(")\n"); } /* * Return the boot0 version with the minor revision in the low byte, and * the major revision in the next higher byte. */ static int boot0version(const u_int8_t *bs) { /* Check for old version, and return 0x100 if found. */ int v = boot0bs(bs); if (v != 0) return v << 8; /* We have a newer boot0, so extract the version number and return it. */ return *(const int *)(bs + OFF_VERSION) & 0xffff; } /* descriptor of a pattern to match. * Start from the first entry trying to match the chunk of bytes, * if you hit an entry with len=0 terminate the search and report * off as the version. Otherwise skip to the next block after len=0 * An entry with len=0, off=0 is the end marker. */ struct byte_pattern { unsigned off; unsigned len; u_int8_t *key; }; /* * Decide if we have valid boot0 boot code by looking for * characteristic byte sequences at fixed offsets. */ static int boot0bs(const u_int8_t *bs) { /* the initial code sequence */ static u_int8_t id0[] = {0xfc, 0x31, 0xc0, 0x8e, 0xc0, 0x8e, 0xd8, 0x8e, 0xd0, 0xbc, 0x00, 0x7c }; /* the drive id */ static u_int8_t id1[] = {'D', 'r', 'i', 'v', 'e', ' '}; static struct byte_pattern patterns[] = { {0x0, sizeof(id0), id0}, {0x1b2, sizeof(id1), id1}, {1, 0, NULL}, {0x0, sizeof(id0), id0}, /* version with NT support */ {0x1ae, sizeof(id1), id1}, {2, 0, NULL}, {0, 0, NULL}, }; struct byte_pattern *p = patterns; for (; p->off || p->len; p++) { if (p->len == 0) break; if (!memcmp(bs + p->off, p->key, p->len)) /* match */ continue; while (p->len) /* skip to next block */ p++; } b0_ver = p->off; /* XXX ugly side effect */ return p->off; } /* * Adjust "and" and "or" masks for a -o option argument. */ static void stropt(const char *arg, int *xa, int *xo) { const char *q; char *s, *s1; int inv, i, x; if (!(s = strdup(arg))) err(1, NULL); for (s1 = s; (q = strtok(s1, ",")); s1 = NULL) { if ((inv = !strncmp(q, "no", 2))) q += 2; for (i = 0; i < nopt; i++) if (!strcmp(q, opttbl[i].tok)) break; if (i == nopt) errx(1, "%s: Unknown -o option", q); if (opttbl[i].def) inv ^= 1; x = 1 << (7 - i); if (inv) *xa &= ~x; else *xo |= x; } free(s); } /* * Convert and check an option argument. */ static int argtoi(const char *arg, int lo, int hi, int opt) { char *s; long x; errno = 0; x = strtol(arg, &s, 0); if (errno || !*arg || *s || x < lo || x > hi) errx(1, "%s: Bad argument to -%c option", arg, opt); return x; } /* * Display usage information. */ static void usage(void) { fprintf(stderr, "%s\n%s\n", "usage: boot0cfg [-Bv] [-b boot0] [-d drive] [-f file] [-m mask]", " [-o options] [-s slice] [-t ticks] disk"); exit(1); }