geom_part.c revision 219416
1/*-
2 * Copyright (c) 2007, 2008 Marcel Moolenaar
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sbin/geom/class/part/geom_part.c 219416 2011-03-08 22:01:47Z ae $");
29
30#include <sys/stat.h>
31#include <sys/vtoc.h>
32
33#include <assert.h>
34#include <ctype.h>
35#include <err.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <libgeom.h>
39#include <libutil.h>
40#include <paths.h>
41#include <signal.h>
42#include <stdint.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <limits.h>
46#include <inttypes.h>
47#include <string.h>
48#include <strings.h>
49#include <unistd.h>
50
51#include "core/geom.h"
52#include "misc/subr.h"
53
54#ifdef STATIC_GEOM_CLASSES
55#define	PUBSYM(x)	gpart_##x
56#else
57#define	PUBSYM(x)	x
58#endif
59
60uint32_t PUBSYM(lib_version) = G_LIB_VERSION;
61uint32_t PUBSYM(version) = 0;
62
63static char sstart[32];
64static char ssize[32];
65volatile sig_atomic_t undo_restore;
66
67#define	GPART_AUTOFILL	"*"
68#define	GPART_FLAGS	"C"
69
70#define	GPART_PARAM_BOOTCODE	"bootcode"
71#define	GPART_PARAM_INDEX	"index"
72#define	GPART_PARAM_PARTCODE	"partcode"
73
74static struct gclass *find_class(struct gmesh *, const char *);
75static struct ggeom * find_geom(struct gclass *, const char *);
76static const char *find_geomcfg(struct ggeom *, const char *);
77static const char *find_provcfg(struct gprovider *, const char *);
78static struct gprovider *find_provider(struct ggeom *, off_t);
79static const char *fmtsize(int64_t);
80static int gpart_autofill(struct gctl_req *);
81static int gpart_autofill_resize(struct gctl_req *);
82static void gpart_bootcode(struct gctl_req *, unsigned int);
83static void *gpart_bootfile_read(const char *, ssize_t *);
84static void gpart_issue(struct gctl_req *, unsigned int);
85static void gpart_show(struct gctl_req *, unsigned int);
86static void gpart_show_geom(struct ggeom *, const char *, int);
87static int gpart_show_hasopt(struct gctl_req *, const char *, const char *);
88static void gpart_write_partcode(struct ggeom *, int, void *, ssize_t);
89static void gpart_write_partcode_vtoc8(struct ggeom *, int, void *);
90static void gpart_print_error(const char *);
91static void gpart_backup(struct gctl_req *, unsigned int);
92static void gpart_restore(struct gctl_req *, unsigned int);
93
94struct g_command PUBSYM(class_commands)[] = {
95	{ "add", 0, gpart_issue, {
96		{ 'b', "start", GPART_AUTOFILL, G_TYPE_STRING },
97		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
98		{ 't', "type", NULL, G_TYPE_STRING },
99		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER },
100		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
101		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
102		G_OPT_SENTINEL },
103	    "[-b start] [-s size] -t type [-i index] [-l label] [-f flags] geom"
104	},
105	{ "backup", 0, gpart_backup, G_NULL_OPTS,
106	    "geom"
107	},
108	{ "bootcode", 0, gpart_bootcode, {
109		{ 'b', GPART_PARAM_BOOTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
110		{ 'p', GPART_PARAM_PARTCODE, G_VAL_OPTIONAL, G_TYPE_STRING },
111		{ 'i', GPART_PARAM_INDEX, G_VAL_OPTIONAL, G_TYPE_NUMBER },
112		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
113		G_OPT_SENTINEL },
114	    "[-b bootcode] [-p partcode] [-i index] [-f flags] geom"
115	},
116	{ "commit", 0, gpart_issue, G_NULL_OPTS,
117	    "geom"
118	},
119	{ "create", 0, gpart_issue, {
120		{ 's', "scheme", NULL, G_TYPE_STRING },
121		{ 'n', "entries", G_VAL_OPTIONAL, G_TYPE_NUMBER },
122		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
123		G_OPT_SENTINEL },
124	    "-s scheme [-n entries] [-f flags] provider"
125	},
126	{ "delete", 0, gpart_issue, {
127		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
128		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
129		G_OPT_SENTINEL },
130	    "-i index [-f flags] geom"
131	},
132	{ "destroy", 0, gpart_issue, {
133		{ 'F', "force", NULL, G_TYPE_BOOL },
134		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
135		G_OPT_SENTINEL },
136	    "[-F] [-f flags] geom"
137	},
138	{ "modify", 0, gpart_issue, {
139		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
140		{ 'l', "label", G_VAL_OPTIONAL, G_TYPE_STRING },
141		{ 't', "type", G_VAL_OPTIONAL, G_TYPE_STRING },
142		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
143		G_OPT_SENTINEL },
144	    "-i index [-l label] [-t type] [-f flags] geom"
145	},
146	{ "set", 0, gpart_issue, {
147		{ 'a', "attrib", NULL, G_TYPE_STRING },
148		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
149		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
150		G_OPT_SENTINEL },
151	    "-a attrib -i index [-f flags] geom"
152	},
153	{ "show", 0, gpart_show, {
154		{ 'l', "show_label", NULL, G_TYPE_BOOL },
155		{ 'r', "show_rawtype", NULL, G_TYPE_BOOL },
156		{ 'p', "show_providers", NULL, G_TYPE_BOOL },
157		G_OPT_SENTINEL },
158	    "[-lrp] [geom ...]"
159	},
160	{ "undo", 0, gpart_issue, G_NULL_OPTS,
161	    "geom"
162	},
163	{ "unset", 0, gpart_issue, {
164		{ 'a', "attrib", NULL, G_TYPE_STRING },
165		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
166		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
167		G_OPT_SENTINEL },
168	    "-a attrib -i index [-f flags] geom"
169	},
170	{ "resize", 0, gpart_issue, {
171		{ 's', "size", GPART_AUTOFILL, G_TYPE_STRING },
172		{ 'i', GPART_PARAM_INDEX, NULL, G_TYPE_NUMBER },
173		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
174		G_OPT_SENTINEL },
175	    "[-s size] -i index [-f flags] geom"
176	},
177	{ "restore", 0, gpart_restore, {
178		{ 'F', "force", NULL, G_TYPE_BOOL },
179		{ 'l', "restore_labels", NULL, G_TYPE_BOOL },
180		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
181		G_OPT_SENTINEL },
182	    "[-lF] [-f flags] provider [...]"
183	},
184	{ "recover", 0, gpart_issue, {
185		{ 'f', "flags", GPART_FLAGS, G_TYPE_STRING },
186		G_OPT_SENTINEL },
187	    "[-f flags] geom"
188	},
189	G_CMD_SENTINEL
190};
191
192static struct gclass *
193find_class(struct gmesh *mesh, const char *name)
194{
195	struct gclass *classp;
196
197	LIST_FOREACH(classp, &mesh->lg_class, lg_class) {
198		if (strcmp(classp->lg_name, name) == 0)
199			return (classp);
200	}
201	return (NULL);
202}
203
204static struct ggeom *
205find_geom(struct gclass *classp, const char *name)
206{
207	struct ggeom *gp;
208
209	if (strncmp(name, _PATH_DEV, sizeof(_PATH_DEV) - 1) == 0)
210		name += sizeof(_PATH_DEV) - 1;
211	LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
212		if (strcmp(gp->lg_name, name) == 0)
213			return (gp);
214	}
215	return (NULL);
216}
217
218static const char *
219find_geomcfg(struct ggeom *gp, const char *cfg)
220{
221	struct gconfig *gc;
222
223	LIST_FOREACH(gc, &gp->lg_config, lg_config) {
224		if (!strcmp(gc->lg_name, cfg))
225			return (gc->lg_val);
226	}
227	return (NULL);
228}
229
230static const char *
231find_provcfg(struct gprovider *pp, const char *cfg)
232{
233	struct gconfig *gc;
234
235	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
236		if (!strcmp(gc->lg_name, cfg))
237			return (gc->lg_val);
238	}
239	return (NULL);
240}
241
242static struct gprovider *
243find_provider(struct ggeom *gp, off_t minsector)
244{
245	struct gprovider *pp, *bestpp;
246	const char *s;
247	off_t sector, bestsector;
248
249	bestpp = NULL;
250	bestsector = 0;
251	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
252		s = find_provcfg(pp, "start");
253		if (s == NULL) {
254			s = find_provcfg(pp, "offset");
255			sector =
256			    (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
257		} else
258			sector = (off_t)strtoimax(s, NULL, 0);
259
260		if (sector < minsector)
261			continue;
262		if (bestpp != NULL && sector >= bestsector)
263			continue;
264
265		bestpp = pp;
266		bestsector = sector;
267	}
268	return (bestpp);
269}
270
271static const char *
272fmtsize(int64_t rawsz)
273{
274	static char buf[5];
275
276	humanize_number(buf, sizeof(buf), rawsz, "", HN_AUTOSCALE,
277	    HN_B | HN_NOSPACE | HN_DECIMAL);
278	return (buf);
279}
280
281static const char *
282fmtattrib(struct gprovider *pp)
283{
284	static char buf[128];
285	struct gconfig *gc;
286	u_int idx;
287
288	buf[0] = '\0';
289	idx = 0;
290	LIST_FOREACH(gc, &pp->lg_config, lg_config) {
291		if (strcmp(gc->lg_name, "attrib") != 0)
292			continue;
293		idx += snprintf(buf + idx, sizeof(buf) - idx, "%s%s",
294		    (idx == 0) ? " [" : ",", gc->lg_val);
295	}
296	if (idx > 0)
297		snprintf(buf + idx, sizeof(buf) - idx, "] ");
298	return (buf);
299}
300
301static int
302gpart_autofill_resize(struct gctl_req *req)
303{
304	struct gmesh mesh;
305	struct gclass *cp;
306	struct ggeom *gp;
307	struct gprovider *pp;
308	off_t last, size, start, new_size;
309	off_t lba, new_lba;
310	const char *s;
311	int error, idx;
312
313	idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX);
314	if (idx < 1)
315		errx(EXIT_FAILURE, "invalid partition index");
316
317	error = geom_gettree(&mesh);
318	if (error)
319		return (error);
320	s = gctl_get_ascii(req, "class");
321	if (s == NULL)
322		abort();
323	cp = find_class(&mesh, s);
324	if (cp == NULL)
325		errx(EXIT_FAILURE, "Class %s not found.", s);
326	s = gctl_get_ascii(req, "arg0");
327	if (s == NULL)
328		abort();
329	gp = find_geom(cp, s);
330	if (gp == NULL)
331		errx(EXIT_FAILURE, "No such geom: %s.", s);
332	pp = LIST_FIRST(&gp->lg_consumer)->lg_provider;
333	if (pp == NULL)
334		errx(EXIT_FAILURE, "Provider for geom %s not found.", s);
335
336	s = gctl_get_ascii(req, "size");
337	if (*s == '*')
338		new_size = 0;
339	else {
340		error = g_parse_lba(s, pp->lg_sectorsize, &new_size);
341		if (error)
342			errc(EXIT_FAILURE, error, "Invalid size param");
343		/* no autofill necessary. */
344		goto done;
345	}
346
347	last = (off_t)strtoimax(find_geomcfg(gp, "last"), NULL, 0);
348	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
349		s = find_provcfg(pp, "index");
350		if (s == NULL)
351			continue;
352		if (atoi(s) == idx)
353			break;
354	}
355	if (pp == NULL)
356		errx(EXIT_FAILURE, "invalid partition index");
357
358	s = find_provcfg(pp, "start");
359	if (s == NULL) {
360		s = find_provcfg(pp, "offset");
361		start = (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
362	} else
363		start = (off_t)strtoimax(s, NULL, 0);
364	s = find_provcfg(pp, "end");
365	if (s == NULL) {
366		s = find_provcfg(pp, "length");
367		lba = start +
368		    (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
369	} else
370		lba = (off_t)strtoimax(s, NULL, 0) + 1;
371
372	if (lba > last) {
373		geom_deletetree(&mesh);
374		return (ENOSPC);
375	}
376	size = lba - start;
377	pp = find_provider(gp, lba);
378	if (pp == NULL)
379		new_size = last - start + 1;
380	else {
381		s = find_provcfg(pp, "start");
382		if (s == NULL) {
383			s = find_provcfg(pp, "offset");
384			new_lba =
385			    (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
386		} else
387			new_lba = (off_t)strtoimax(s, NULL, 0);
388		/*
389		 * Is there any free space between current and
390		 * next providers?
391		 */
392		if (new_lba > lba)
393			new_size = new_lba - start;
394		else {
395			geom_deletetree(&mesh);
396			return (ENOSPC);
397		}
398	}
399done:
400	snprintf(ssize, sizeof(ssize), "%jd", (intmax_t)new_size);
401	gctl_change_param(req, "size", -1, ssize);
402	geom_deletetree(&mesh);
403	return (0);
404}
405
406static int
407gpart_autofill(struct gctl_req *req)
408{
409	struct gmesh mesh;
410	struct gclass *cp;
411	struct ggeom *gp;
412	struct gprovider *pp;
413	off_t first, last;
414	off_t size, start;
415	off_t lba, len;
416	uintmax_t grade;
417	const char *s;
418	int error, has_size, has_start;
419
420	s = gctl_get_ascii(req, "verb");
421	if (strcmp(s, "resize") == 0)
422		return gpart_autofill_resize(req);
423	if (strcmp(s, "add") != 0)
424		return (0);
425
426	error = geom_gettree(&mesh);
427	if (error)
428		return (error);
429	s = gctl_get_ascii(req, "class");
430	if (s == NULL)
431		abort();
432	cp = find_class(&mesh, s);
433	if (cp == NULL)
434		errx(EXIT_FAILURE, "Class %s not found.", s);
435	s = gctl_get_ascii(req, "arg0");
436	if (s == NULL)
437		abort();
438	gp = find_geom(cp, s);
439	if (gp == NULL)
440		errx(EXIT_FAILURE, "No such geom: %s.", s);
441	pp = LIST_FIRST(&gp->lg_consumer)->lg_provider;
442	if (pp == NULL)
443		errx(EXIT_FAILURE, "Provider for geom %s not found.", s);
444
445	s = gctl_get_ascii(req, "size");
446	has_size = (*s == '*') ? 0 : 1;
447	size = 0;
448	if (has_size) {
449		error = g_parse_lba(s, pp->lg_sectorsize, &size);
450		if (error)
451			errc(EXIT_FAILURE, error, "Invalid size param");
452	}
453
454	s = gctl_get_ascii(req, "start");
455	has_start = (*s == '*') ? 0 : 1;
456	start = 0ULL;
457	if (has_start) {
458		error = g_parse_lba(s, pp->lg_sectorsize, &start);
459		if (error)
460			errc(EXIT_FAILURE, error, "Invalid start param");
461	}
462
463	/* No autofill necessary. */
464	if (has_size && has_start)
465		goto done;
466
467	first = (off_t)strtoimax(find_geomcfg(gp, "first"), NULL, 0);
468	last = (off_t)strtoimax(find_geomcfg(gp, "last"), NULL, 0);
469	grade = ~0ULL;
470	while ((pp = find_provider(gp, first)) != NULL) {
471		s = find_provcfg(pp, "start");
472		if (s == NULL) {
473			s = find_provcfg(pp, "offset");
474			lba = (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
475		} else
476			lba = (off_t)strtoimax(s, NULL, 0);
477
478		if (first < lba) {
479			/* Free space [first, lba> */
480			len = lba - first;
481			if (has_size) {
482				if (len >= size &&
483				    (uintmax_t)(len - size) < grade) {
484					start = first;
485					grade = len - size;
486				}
487			} else if (has_start) {
488				if (start >= first && start < lba) {
489					size = lba - start;
490					grade = start - first;
491				}
492			} else {
493				if (grade == ~0ULL || len > size) {
494					start = first;
495					size = len;
496					grade = 0;
497				}
498			}
499		}
500
501		s = find_provcfg(pp, "end");
502		if (s == NULL) {
503			s = find_provcfg(pp, "length");
504			first = lba +
505			    (off_t)strtoimax(s, NULL, 0) / pp->lg_sectorsize;
506		} else
507			first = (off_t)strtoimax(s, NULL, 0) + 1;
508	}
509	if (first <= last) {
510		/* Free space [first-last] */
511		len = last - first + 1;
512		if (has_size) {
513			if (len >= size &&
514			    (uintmax_t)(len - size) < grade) {
515				start = first;
516				grade = len - size;
517			}
518		} else if (has_start) {
519			if (start >= first && start <= last) {
520				size = last - start + 1;
521				grade = start - first;
522			}
523		} else {
524			if (grade == ~0ULL || len > size) {
525				start = first;
526				size = len;
527				grade = 0;
528			}
529		}
530	}
531
532	if (grade == ~0ULL) {
533		geom_deletetree(&mesh);
534		return (ENOSPC);
535	}
536
537done:
538	snprintf(ssize, sizeof(ssize), "%jd", (intmax_t)size);
539	gctl_change_param(req, "size", -1, ssize);
540	snprintf(sstart, sizeof(sstart), "%jd", (intmax_t)start);
541	gctl_change_param(req, "start", -1, sstart);
542	geom_deletetree(&mesh);
543	return (0);
544}
545
546static void
547gpart_show_geom(struct ggeom *gp, const char *element, int show_providers)
548{
549	struct gprovider *pp;
550	const char *s, *scheme;
551	off_t first, last, sector, end;
552	off_t length, secsz;
553	int idx, wblocks, wname, wmax;
554
555	scheme = find_geomcfg(gp, "scheme");
556	s = find_geomcfg(gp, "first");
557	first = (off_t)strtoimax(s, NULL, 0);
558	s = find_geomcfg(gp, "last");
559	last = (off_t)strtoimax(s, NULL, 0);
560	wblocks = strlen(s);
561	s = find_geomcfg(gp, "state");
562	if (s != NULL && *s != 'C')
563		s = NULL;
564	wmax = strlen(gp->lg_name);
565	if (show_providers) {
566		LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
567			wname = strlen(pp->lg_name);
568			if (wname > wmax)
569				wmax = wname;
570		}
571	}
572	wname = wmax;
573	pp = LIST_FIRST(&gp->lg_consumer)->lg_provider;
574	secsz = pp->lg_sectorsize;
575	printf("=>%*jd  %*jd  %*s  %s  (%s)%s\n",
576	    wblocks, (intmax_t)first, wblocks, (intmax_t)(last - first + 1),
577	    wname, gp->lg_name,
578	    scheme, fmtsize(pp->lg_mediasize),
579	    s ? " [CORRUPT]": "");
580
581	while ((pp = find_provider(gp, first)) != NULL) {
582		s = find_provcfg(pp, "start");
583		if (s == NULL) {
584			s = find_provcfg(pp, "offset");
585			sector = (off_t)strtoimax(s, NULL, 0) / secsz;
586		} else
587			sector = (off_t)strtoimax(s, NULL, 0);
588
589		s = find_provcfg(pp, "end");
590		if (s == NULL) {
591			s = find_provcfg(pp, "length");
592			length = (off_t)strtoimax(s, NULL, 0) / secsz;
593			end = sector + length - 1;
594		} else {
595			end = (off_t)strtoimax(s, NULL, 0);
596			length = end - sector + 1;
597		}
598		s = find_provcfg(pp, "index");
599		idx = atoi(s);
600		if (first < sector) {
601			printf("  %*jd  %*jd  %*s  - free -  (%s)\n",
602			    wblocks, (intmax_t)first, wblocks,
603			    (intmax_t)(sector - first), wname, "",
604			    fmtsize((sector - first) * secsz));
605		}
606		if (show_providers) {
607			printf("  %*jd  %*jd  %*s  %s %s (%s)\n",
608			    wblocks, (intmax_t)sector, wblocks,
609			    (intmax_t)length, wname, pp->lg_name,
610			    find_provcfg(pp, element), fmtattrib(pp),
611			    fmtsize(pp->lg_mediasize));
612		} else
613			printf("  %*jd  %*jd  %*d  %s %s (%s)\n",
614			    wblocks, (intmax_t)sector, wblocks,
615			    (intmax_t)length, wname, idx,
616			    find_provcfg(pp, element), fmtattrib(pp),
617			    fmtsize(pp->lg_mediasize));
618		first = end + 1;
619	}
620	if (first <= last) {
621		length = last - first + 1;
622		printf("  %*jd  %*jd  %*s  - free -  (%s)\n",
623		    wblocks, (intmax_t)first, wblocks, (intmax_t)length,
624		    wname, "",
625		    fmtsize(length * secsz));
626	}
627	printf("\n");
628}
629
630static int
631gpart_show_hasopt(struct gctl_req *req, const char *opt, const char *elt)
632{
633
634	if (!gctl_get_int(req, "%s", opt))
635		return (0);
636
637	if (elt != NULL)
638		errx(EXIT_FAILURE, "-l and -r are mutually exclusive");
639
640	return (1);
641}
642
643static void
644gpart_show(struct gctl_req *req, unsigned int fl __unused)
645{
646	struct gmesh mesh;
647	struct gclass *classp;
648	struct ggeom *gp;
649	const char *element, *name;
650	int error, i, nargs, show_providers;
651
652	element = NULL;
653	if (gpart_show_hasopt(req, "show_label", element))
654		element = "label";
655	if (gpart_show_hasopt(req, "show_rawtype", element))
656		element = "rawtype";
657	if (element == NULL)
658		element = "type";
659
660	name = gctl_get_ascii(req, "class");
661	if (name == NULL)
662		abort();
663	error = geom_gettree(&mesh);
664	if (error != 0)
665		errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
666	classp = find_class(&mesh, name);
667	if (classp == NULL) {
668		geom_deletetree(&mesh);
669		errx(EXIT_FAILURE, "Class %s not found.", name);
670	}
671	show_providers = gctl_get_int(req, "show_providers");
672	nargs = gctl_get_int(req, "nargs");
673	if (nargs > 0) {
674		for (i = 0; i < nargs; i++) {
675			name = gctl_get_ascii(req, "arg%d", i);
676			gp = find_geom(classp, name);
677			if (gp != NULL)
678				gpart_show_geom(gp, element, show_providers);
679			else
680				errx(EXIT_FAILURE, "No such geom: %s.", name);
681		}
682	} else {
683		LIST_FOREACH(gp, &classp->lg_geom, lg_geom) {
684			gpart_show_geom(gp, element, show_providers);
685		}
686	}
687	geom_deletetree(&mesh);
688}
689
690static void
691gpart_backup(struct gctl_req *req, unsigned int fl __unused)
692{
693	struct gmesh mesh;
694	struct gclass *classp;
695	struct gprovider *pp;
696	struct ggeom *gp;
697	const char *s, *scheme;
698	off_t sector, end;
699	off_t length, secsz;
700	int error, i, windex, wblocks, wtype;
701
702	if (gctl_get_int(req, "nargs") != 1)
703		errx(EXIT_FAILURE, "Invalid number of arguments.");
704	error = geom_gettree(&mesh);
705	if (error != 0)
706		errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
707	s = gctl_get_ascii(req, "class");
708	if (s == NULL)
709		abort();
710	classp = find_class(&mesh, s);
711	if (classp == NULL) {
712		geom_deletetree(&mesh);
713		errx(EXIT_FAILURE, "Class %s not found.", s);
714	}
715	s = gctl_get_ascii(req, "arg0");
716	if (s == NULL)
717		abort();
718	gp = find_geom(classp, s);
719	if (gp == NULL)
720		errx(EXIT_FAILURE, "No such geom: %s.", s);
721	scheme = find_geomcfg(gp, "scheme");
722	if (scheme == NULL)
723		abort();
724	pp = LIST_FIRST(&gp->lg_consumer)->lg_provider;
725	secsz = pp->lg_sectorsize;
726	s = find_geomcfg(gp, "last");
727	wblocks = strlen(s);
728	wtype = 0;
729	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
730		s = find_provcfg(pp, "type");
731		i = strlen(s);
732		if (i > wtype)
733			wtype = i;
734	}
735	s = find_geomcfg(gp, "entries");
736	windex = strlen(s);
737	printf("%s %s\n", scheme, s);
738	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
739		s = find_provcfg(pp, "start");
740		if (s == NULL) {
741			s = find_provcfg(pp, "offset");
742			sector = (off_t)strtoimax(s, NULL, 0) / secsz;
743		} else
744			sector = (off_t)strtoimax(s, NULL, 0);
745
746		s = find_provcfg(pp, "end");
747		if (s == NULL) {
748			s = find_provcfg(pp, "length");
749			length = (off_t)strtoimax(s, NULL, 0) / secsz;
750		} else {
751			end = (off_t)strtoimax(s, NULL, 0);
752			length = end - sector + 1;
753		}
754		s = find_provcfg(pp, "label");
755		printf("%-*s %*s %*jd %*jd %s %s\n",
756		    windex, find_provcfg(pp, "index"),
757		    wtype, find_provcfg(pp, "type"),
758		    wblocks, (intmax_t)sector,
759		    wblocks, (intmax_t)length,
760		    (s != NULL) ? s: "", fmtattrib(pp));
761	}
762	geom_deletetree(&mesh);
763}
764
765static int
766skip_line(const char *p)
767{
768
769	while (*p != '\0') {
770		if (*p == '#')
771			return (1);
772		if (isspace(*p) == 0)
773			return (0);
774		p++;
775	}
776	return (1);
777}
778
779static void
780gpart_sighndl(int sig __unused)
781{
782	undo_restore = 1;
783}
784
785static void
786gpart_restore(struct gctl_req *req, unsigned int fl __unused)
787{
788	struct gmesh mesh;
789	struct gclass *classp;
790	struct gctl_req *r;
791	struct ggeom *gp;
792	struct sigaction si_sa;
793	const char *s, *flags, *errstr, *label;
794	char **ap, *argv[6], line[BUFSIZ], *pline;
795	int error, forced, i, l, nargs, created, rl;
796	intmax_t n;
797
798	nargs = gctl_get_int(req, "nargs");
799	if (nargs < 1)
800		errx(EXIT_FAILURE, "Invalid number of arguments.");
801
802	forced = gctl_get_int(req, "force");
803	flags = gctl_get_ascii(req, "flags");
804	rl = gctl_get_int(req, "restore_labels");
805	s = gctl_get_ascii(req, "class");
806	if (s == NULL)
807		abort();
808	error = geom_gettree(&mesh);
809	if (error != 0)
810		errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
811	classp = find_class(&mesh, s);
812	if (classp == NULL) {
813		geom_deletetree(&mesh);
814		errx(EXIT_FAILURE, "Class %s not found.", s);
815	}
816
817	sigemptyset(&si_sa.sa_mask);
818	si_sa.sa_flags = 0;
819	si_sa.sa_handler = gpart_sighndl;
820	if (sigaction(SIGINT, &si_sa, 0) == -1)
821		err(EXIT_FAILURE, "sigaction SIGINT");
822
823	if (forced) {
824		/* destroy existent partition table before restore */
825		for (i = 0; i < nargs; i++) {
826			s = gctl_get_ascii(req, "arg%d", i);
827			gp = find_geom(classp, s);
828			if (gp != NULL) {
829				r = gctl_get_handle();
830				gctl_ro_param(r, "class", -1,
831				    classp->lg_name);
832				gctl_ro_param(r, "verb", -1, "destroy");
833				gctl_ro_param(r, "flags", -1, "restore");
834				gctl_ro_param(r, "force", sizeof(forced),
835				    &forced);
836				gctl_ro_param(r, "arg0", -1, s);
837				errstr = gctl_issue(r);
838				if (errstr != NULL && errstr[0] != '\0') {
839					gpart_print_error(errstr);
840					gctl_free(r);
841					goto backout;
842				}
843				gctl_free(r);
844			}
845		}
846	}
847	created = 0;
848	while (undo_restore == 0 &&
849	    fgets(line, sizeof(line) - 1, stdin) != NULL) {
850		/* Format of backup entries:
851		 * <scheme name> <number of entries>
852		 * <index> <type> <start> <size> [label] ['['attrib[,attrib]']']
853		 */
854		pline = (char *)line;
855		pline[strlen(line) - 1] = 0;
856		if (skip_line(pline))
857			continue;
858		for (ap = argv;
859		    (*ap = strsep(&pline, " \t")) != NULL;)
860			if (**ap != '\0' && ++ap >= &argv[6])
861				break;
862		l = ap - &argv[0];
863		label = pline = NULL;
864		if (l == 1 || l == 2) { /* create table */
865			if (created)
866				errx(EXIT_FAILURE, "Incorrect backup format.");
867			if (l == 2)
868				n = strtoimax(argv[1], NULL, 0);
869			for (i = 0; i < nargs; i++) {
870				s = gctl_get_ascii(req, "arg%d", i);
871				r = gctl_get_handle();
872				gctl_ro_param(r, "class", -1,
873				    classp->lg_name);
874				gctl_ro_param(r, "verb", -1, "create");
875				gctl_ro_param(r, "scheme", -1, argv[0]);
876				if (l == 2)
877					gctl_ro_param(r, "entries",
878					    sizeof(n), &n);
879				gctl_ro_param(r, "flags", -1, "restore");
880				gctl_ro_param(r, "arg0", -1, s);
881				errstr = gctl_issue(r);
882				if (errstr != NULL && errstr[0] != '\0') {
883					gpart_print_error(errstr);
884					gctl_free(r);
885					goto backout;
886				}
887				gctl_free(r);
888			}
889			created = 1;
890			continue;
891		} else if (l < 4 || created == 0)
892			errx(EXIT_FAILURE, "Incorrect backup format.");
893		else if (l == 5) {
894			if (strchr(argv[4], '[') == NULL)
895				label = argv[4];
896			else
897				pline = argv[4];
898		} else if (l == 6) {
899			label = argv[4];
900			pline = argv[5];
901		}
902		/* Add partitions to each table */
903		for (i = 0; i < nargs; i++) {
904			s = gctl_get_ascii(req, "arg%d", i);
905			r = gctl_get_handle();
906			n = strtoimax(argv[0], NULL, 0);
907			gctl_ro_param(r, "class", -1, classp->lg_name);
908			gctl_ro_param(r, "verb", -1, "add");
909			gctl_ro_param(r, "flags", -1, "restore");
910			gctl_ro_param(r, GPART_PARAM_INDEX, sizeof(n), &n);
911			gctl_ro_param(r, "type", -1, argv[1]);
912			gctl_ro_param(r, "start", -1, argv[2]);
913			gctl_ro_param(r, "size", -1, argv[3]);
914			if (rl != 0 && label != NULL)
915				gctl_ro_param(r, "label", -1, argv[4]);
916			gctl_ro_param(r, "arg0", -1, s);
917			error = gpart_autofill(r);
918			if (error != 0)
919				errc(EXIT_FAILURE, error, "autofill");
920			errstr = gctl_issue(r);
921			if (errstr != NULL && errstr[0] != '\0') {
922				gpart_print_error(errstr);
923				gctl_free(r);
924				goto backout;
925			}
926			gctl_free(r);
927		}
928		if (pline == NULL || *pline != '[')
929			continue;
930		/* set attributes */
931		pline++;
932		for (ap = argv;
933		    (*ap = strsep(&pline, ",]")) != NULL;)
934			if (**ap != '\0' && ++ap >= &argv[6])
935				break;
936		for (i = 0; i < nargs; i++) {
937			l = ap - &argv[0];
938			s = gctl_get_ascii(req, "arg%d", i);
939			while (l > 0) {
940				r = gctl_get_handle();
941				gctl_ro_param(r, "class", -1, classp->lg_name);
942				gctl_ro_param(r, "verb", -1, "set");
943				gctl_ro_param(r, "flags", -1, "restore");
944				gctl_ro_param(r, GPART_PARAM_INDEX,
945				    sizeof(n), &n);
946				gctl_ro_param(r, "attrib", -1, argv[--l]);
947				gctl_ro_param(r, "arg0", -1, s);
948				errstr = gctl_issue(r);
949				if (errstr != NULL && errstr[0] != '\0') {
950					gpart_print_error(errstr);
951					gctl_free(r);
952					goto backout;
953				}
954				gctl_free(r);
955			}
956		}
957	}
958	if (undo_restore)
959		goto backout;
960	/* commit changes if needed */
961	if (strchr(flags, 'C') != NULL) {
962		for (i = 0; i < nargs; i++) {
963			s = gctl_get_ascii(req, "arg%d", i);
964			r = gctl_get_handle();
965			gctl_ro_param(r, "class", -1, classp->lg_name);
966			gctl_ro_param(r, "verb", -1, "commit");
967			gctl_ro_param(r, "arg0", -1, s);
968			errstr = gctl_issue(r);
969			if (errstr != NULL && errstr[0] != '\0') {
970				gpart_print_error(errstr);
971				gctl_free(r);
972				goto backout;
973			}
974			gctl_free(r);
975		}
976	}
977	gctl_free(req);
978	geom_deletetree(&mesh);
979	exit(EXIT_SUCCESS);
980
981backout:
982	for (i = 0; i < nargs; i++) {
983		s = gctl_get_ascii(req, "arg%d", i);
984		r = gctl_get_handle();
985		gctl_ro_param(r, "class", -1, classp->lg_name);
986		gctl_ro_param(r, "verb", -1, "undo");
987		gctl_ro_param(r, "arg0", -1, s);
988		gctl_issue(r);
989		gctl_free(r);
990	}
991	gctl_free(req);
992	geom_deletetree(&mesh);
993	exit(EXIT_FAILURE);
994}
995
996static void *
997gpart_bootfile_read(const char *bootfile, ssize_t *size)
998{
999	struct stat sb;
1000	void *code;
1001	int fd;
1002
1003	if (stat(bootfile, &sb) == -1)
1004		err(EXIT_FAILURE, "%s", bootfile);
1005	if (!S_ISREG(sb.st_mode))
1006		errx(EXIT_FAILURE, "%s: not a regular file", bootfile);
1007	if (sb.st_size == 0)
1008		errx(EXIT_FAILURE, "%s: empty file", bootfile);
1009	if (*size > 0 && sb.st_size > *size)
1010		errx(EXIT_FAILURE, "%s: file too big (%zu limit)", bootfile,
1011		    *size);
1012
1013	*size = sb.st_size;
1014
1015	fd = open(bootfile, O_RDONLY);
1016	if (fd == -1)
1017		err(EXIT_FAILURE, "%s", bootfile);
1018	code = malloc(*size);
1019	if (code == NULL)
1020		err(EXIT_FAILURE, NULL);
1021	if (read(fd, code, *size) != *size)
1022		err(EXIT_FAILURE, "%s", bootfile);
1023	close(fd);
1024
1025	return (code);
1026}
1027
1028static void
1029gpart_write_partcode(struct ggeom *gp, int idx, void *code, ssize_t size)
1030{
1031	char dsf[128];
1032	struct gprovider *pp;
1033	const char *s;
1034	char *buf;
1035	off_t bsize;
1036	int fd;
1037
1038	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
1039		s = find_provcfg(pp, "index");
1040		if (s == NULL)
1041			continue;
1042		if (atoi(s) == idx)
1043			break;
1044	}
1045
1046	if (pp != NULL) {
1047		snprintf(dsf, sizeof(dsf), "/dev/%s", pp->lg_name);
1048		fd = open(dsf, O_WRONLY);
1049		if (fd == -1)
1050			err(EXIT_FAILURE, "%s", dsf);
1051		if (lseek(fd, size, SEEK_SET) != size)
1052			errx(EXIT_FAILURE, "%s: not enough space", dsf);
1053		if (lseek(fd, 0, SEEK_SET) != 0)
1054			err(EXIT_FAILURE, "%s", dsf);
1055
1056		/*
1057		 * When writing to a disk device, the write must be
1058		 * sector aligned and not write to any partial sectors,
1059		 * so round up the buffer size to the next sector and zero it.
1060		 */
1061		bsize = (size + pp->lg_sectorsize - 1) /
1062		    pp->lg_sectorsize * pp->lg_sectorsize;
1063		buf = calloc(1, bsize);
1064		if (buf == NULL)
1065			err(EXIT_FAILURE, "%s", dsf);
1066		bcopy(code, buf, size);
1067		if (write(fd, buf, bsize) != bsize)
1068			err(EXIT_FAILURE, "%s", dsf);
1069		free(buf);
1070		close(fd);
1071	} else
1072		errx(EXIT_FAILURE, "invalid partition index");
1073}
1074
1075static void
1076gpart_write_partcode_vtoc8(struct ggeom *gp, int idx, void *code)
1077{
1078	char dsf[128];
1079	struct gprovider *pp;
1080	const char *s;
1081	int installed, fd;
1082
1083	installed = 0;
1084	LIST_FOREACH(pp, &gp->lg_provider, lg_provider) {
1085		s = find_provcfg(pp, "index");
1086		if (s == NULL)
1087			continue;
1088		if (idx != 0 && atoi(s) != idx)
1089			continue;
1090		snprintf(dsf, sizeof(dsf), "/dev/%s", pp->lg_name);
1091		if (pp->lg_sectorsize != sizeof(struct vtoc8))
1092			errx(EXIT_FAILURE, "%s: unexpected sector "
1093			    "size (%d)\n", dsf, pp->lg_sectorsize);
1094		fd = open(dsf, O_WRONLY);
1095		if (fd == -1)
1096			err(EXIT_FAILURE, "%s", dsf);
1097		if (lseek(fd, VTOC_BOOTSIZE, SEEK_SET) != VTOC_BOOTSIZE)
1098			continue;
1099		/*
1100		 * We ignore the first VTOC_BOOTSIZE bytes of boot code in
1101		 * order to avoid overwriting the label.
1102		 */
1103		if (lseek(fd, sizeof(struct vtoc8), SEEK_SET) !=
1104		    sizeof(struct vtoc8))
1105			err(EXIT_FAILURE, "%s", dsf);
1106		if (write(fd, (caddr_t)code + sizeof(struct vtoc8),
1107		    VTOC_BOOTSIZE - sizeof(struct vtoc8)) != VTOC_BOOTSIZE -
1108		    sizeof(struct vtoc8))
1109			err(EXIT_FAILURE, "%s", dsf);
1110		installed++;
1111		close(fd);
1112		if (idx != 0 && atoi(s) == idx)
1113			break;
1114	}
1115	if (installed == 0)
1116		errx(EXIT_FAILURE, "%s: no partitions", gp->lg_name);
1117}
1118
1119static void
1120gpart_bootcode(struct gctl_req *req, unsigned int fl)
1121{
1122	struct gmesh mesh;
1123	struct gclass *classp;
1124	struct ggeom *gp;
1125	const char *s;
1126	void *bootcode, *partcode;
1127	size_t bootsize, partsize;
1128	int error, idx, vtoc8;
1129
1130	if (gctl_has_param(req, GPART_PARAM_BOOTCODE)) {
1131		s = gctl_get_ascii(req, GPART_PARAM_BOOTCODE);
1132		bootsize = 800 * 1024;		/* Arbitrary limit. */
1133		bootcode = gpart_bootfile_read(s, &bootsize);
1134		error = gctl_change_param(req, GPART_PARAM_BOOTCODE, bootsize,
1135		    bootcode);
1136		if (error)
1137			errc(EXIT_FAILURE, error, "internal error");
1138	} else {
1139		bootcode = NULL;
1140		bootsize = 0;
1141	}
1142
1143	s = gctl_get_ascii(req, "class");
1144	if (s == NULL)
1145		abort();
1146	error = geom_gettree(&mesh);
1147	if (error != 0)
1148		errc(EXIT_FAILURE, error, "Cannot get GEOM tree");
1149	classp = find_class(&mesh, s);
1150	if (classp == NULL) {
1151		geom_deletetree(&mesh);
1152		errx(EXIT_FAILURE, "Class %s not found.", s);
1153	}
1154	if (gctl_get_int(req, "nargs") != 1)
1155		errx(EXIT_FAILURE, "Invalid number of arguments.");
1156	s = gctl_get_ascii(req, "arg0");
1157	if (s == NULL)
1158		abort();
1159	gp = find_geom(classp, s);
1160	if (gp == NULL)
1161		errx(EXIT_FAILURE, "No such geom: %s.", s);
1162	s = find_geomcfg(gp, "scheme");
1163	vtoc8 = 0;
1164	if (strcmp(s, "VTOC8") == 0)
1165		vtoc8 = 1;
1166
1167	if (gctl_has_param(req, GPART_PARAM_PARTCODE)) {
1168		s = gctl_get_ascii(req, GPART_PARAM_PARTCODE);
1169		partsize = vtoc8 != 0 ? VTOC_BOOTSIZE : bootsize * 1024;
1170		partcode = gpart_bootfile_read(s, &partsize);
1171		error = gctl_delete_param(req, GPART_PARAM_PARTCODE);
1172		if (error)
1173			errc(EXIT_FAILURE, error, "internal error");
1174	} else {
1175		partcode = NULL;
1176		partsize = 0;
1177	}
1178
1179	if (gctl_has_param(req, GPART_PARAM_INDEX)) {
1180		if (partcode == NULL)
1181			errx(EXIT_FAILURE, "-i is only valid with -p");
1182		idx = (int)gctl_get_intmax(req, GPART_PARAM_INDEX);
1183		if (idx < 1)
1184			errx(EXIT_FAILURE, "invalid partition index");
1185		error = gctl_delete_param(req, GPART_PARAM_INDEX);
1186		if (error)
1187			errc(EXIT_FAILURE, error, "internal error");
1188	} else
1189		idx = 0;
1190
1191	if (partcode != NULL) {
1192		if (vtoc8 == 0) {
1193			if (idx == 0)
1194				errx(EXIT_FAILURE, "missing -i option");
1195			gpart_write_partcode(gp, idx, partcode, partsize);
1196		} else
1197			gpart_write_partcode_vtoc8(gp, idx, partcode);
1198	} else
1199		if (bootcode == NULL)
1200			errx(EXIT_FAILURE, "no -b nor -p");
1201
1202	if (bootcode != NULL)
1203		gpart_issue(req, fl);
1204
1205	geom_deletetree(&mesh);
1206}
1207
1208static void
1209gpart_print_error(const char *errstr)
1210{
1211	char *errmsg;
1212	int error;
1213
1214	error = strtol(errstr, &errmsg, 0);
1215	if (errmsg != errstr) {
1216		while (errmsg[0] == ' ')
1217			errmsg++;
1218		if (errmsg[0] != '\0')
1219			warnc(error, "%s", errmsg);
1220		else
1221			warnc(error, NULL);
1222	} else
1223		warnx("%s", errmsg);
1224}
1225
1226static void
1227gpart_issue(struct gctl_req *req, unsigned int fl __unused)
1228{
1229	char buf[4096];
1230	const char *errstr;
1231	int error, status;
1232
1233	if (gctl_get_int(req, "nargs") != 1)
1234		errx(EXIT_FAILURE, "Invalid number of arguments.");
1235	(void)gctl_delete_param(req, "nargs");
1236
1237	/* autofill parameters (if applicable). */
1238	error = gpart_autofill(req);
1239	if (error) {
1240		warnc(error, "autofill");
1241		status = EXIT_FAILURE;
1242		goto done;
1243	}
1244
1245	bzero(buf, sizeof(buf));
1246	gctl_rw_param(req, "output", sizeof(buf), buf);
1247	errstr = gctl_issue(req);
1248	if (errstr == NULL || errstr[0] == '\0') {
1249		if (buf[0] != '\0')
1250			printf("%s", buf);
1251		status = EXIT_SUCCESS;
1252		goto done;
1253	}
1254
1255	gpart_print_error(errstr);
1256	status = EXIT_FAILURE;
1257
1258 done:
1259	gctl_free(req);
1260	exit(status);
1261}
1262