bsdlabel.c revision 115948
1/*
2 * Copyright (c) 1994, 1995 Gordon W. Ross
3 * Copyright (c) 1994 Theo de Raadt
4 * All rights reserved.
5 * Copyright (c) 1987, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Symmetric Computer Systems.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 *    must display the following acknowledgement:
21 *	This product includes software developed by the University of
22 *	California, Berkeley and its contributors.
23 *      This product includes software developed by Theo de Raadt.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 *	from: $NetBSD: disksubr.c,v 1.13 2000/12/17 22:39:18 pk $
41 */
42
43#if 0
44#ifndef lint
45static const char copyright[] =
46"@(#) Copyright (c) 1987, 1993\n\
47	The Regents of the University of California.  All rights reserved.\n";
48#endif /* not lint */
49
50#ifndef lint
51static char sccsid[] = "@(#)disklabel.c	8.2 (Berkeley) 1/7/94";
52/* from static char sccsid[] = "@(#)disklabel.c	1.2 (Symmetric) 11/28/85"; */
53#endif /* not lint */
54#endif
55#include <sys/cdefs.h>
56__FBSDID("$FreeBSD: head/sbin/bsdlabel/bsdlabel.c 115948 2003-06-07 09:09:39Z phk $");
57
58#include <sys/param.h>
59#include <stdint.h>
60#include <sys/file.h>
61#include <sys/stat.h>
62#include <sys/wait.h>
63#include <sys/disk.h>
64#define DKTYPENAMES
65#define FSTYPENAMES
66#include <sys/disklabel.h>
67
68#include <unistd.h>
69#include <string.h>
70#include <stdio.h>
71#include <libgeom.h>
72#include <stdlib.h>
73#include <signal.h>
74#include <stdarg.h>
75#include <ctype.h>
76#include <err.h>
77#include <errno.h>
78
79#include "pathnames.h"
80
81/* FIX!  These are too low, but are traditional */
82#define DEFAULT_NEWFS_BLOCK  8192U
83#define DEFAULT_NEWFS_FRAG   1024U
84#define DEFAULT_NEWFS_CPG    16U
85
86#define BIG_NEWFS_BLOCK  16384U
87#define BIG_NEWFS_FRAG   2048U
88#define BIG_NEWFS_CPG    64U
89
90static void	makelabel(const char *, struct disklabel *);
91static int	writelabel(void);
92static int readlabel(int flag);
93static void	display(FILE *, const struct disklabel *);
94static int edit(void);
95static int	editit(void);
96static char	*skip(char *);
97static char	*word(char *);
98static int	getasciilabel(FILE *, struct disklabel *);
99static int	getasciipartspec(char *, struct disklabel *, int, int);
100static int	checklabel(struct disklabel *);
101static void	usage(void);
102static struct disklabel *getvirginlabel(void);
103
104#define	DEFEDITOR	_PATH_VI
105
106static char	*dkname;
107static char	*specname;
108static char	tmpfil[] = PATH_TMPFILE;
109
110static struct	disklabel lab;
111static u_char	bootarea[BBSIZE];
112static off_t	mediasize;
113static u_int	secsize;
114static char	blank[] = "";
115static char	unknown[] = "unknown";
116
117#define MAX_PART ('z')
118#define MAX_NUM_PARTS (1 + MAX_PART - 'a')
119static char    part_size_type[MAX_NUM_PARTS];
120static char    part_offset_type[MAX_NUM_PARTS];
121static int     part_set[MAX_NUM_PARTS];
122
123static int	installboot;	/* non-zero if we should install a boot program */
124static int	allfields;	/* present all fields in edit */
125static char const *xxboot;	/* primary boot */
126
127static off_t mbroffset;
128static int labelsoffset = LABELSECTOR;
129static int labeloffset = LABELOFFSET;
130static int bbsize = BBSIZE;
131static int alphacksum =
132#if defined(__alpha__)
133	1;
134#else
135	0;
136#endif
137
138enum	{
139	UNSPEC, EDIT, READ, RESTORE, WRITE, WRITEBOOT
140} op = UNSPEC;
141
142
143static int	disable_write;   /* set to disable writing to disk label */
144
145int
146main(int argc, char *argv[])
147{
148	FILE *t;
149	int ch, error = 0;
150	char const *name = 0;
151
152	while ((ch = getopt(argc, argv, "ABb:em:nRrs:w")) != -1)
153		switch (ch) {
154			case 'A':
155				allfields = 1;
156				break;
157			case 'B':
158				++installboot;
159				break;
160			case 'b':
161				xxboot = optarg;
162				break;
163			case 'm':
164				if (!strcmp(optarg, "i386") ||
165				    !strcmp(optarg, "amd64") ||
166				    !strcmp(optarg, "ia64") ||
167				    !strcmp(optarg, "pc98")) {
168					labelsoffset = 1;
169					labeloffset = 0;
170					bbsize = 8192;
171					alphacksum = 0;
172				} else if (!strcmp(optarg, "alpha")) {
173					labelsoffset = 0;
174					labeloffset = 64;
175					bbsize = 8192;
176					alphacksum = 1;
177				} else {
178					errx(1, "Unsupported architecture");
179				}
180				break;
181			case 'n':
182				disable_write = 1;
183				break;
184			case 'R':
185				if (op != UNSPEC)
186					usage();
187				op = RESTORE;
188				break;
189			case 'e':
190				if (op != UNSPEC)
191					usage();
192				op = EDIT;
193				break;
194			case 'r':
195				/*
196				 * We accept and ignode -r for compatibility with
197				 * historically disklabel usage.
198				 */
199				break;
200			case 'w':
201				if (op != UNSPEC)
202					usage();
203				op = WRITE;
204				break;
205			case '?':
206			default:
207				usage();
208		}
209	argc -= optind;
210	argv += optind;
211
212	if (argc < 1)
213		usage();
214
215	/* Figure out the names of the thing we're working on */
216	if (argv[0][0] != '/') {
217		dkname = argv[0];
218		asprintf(&specname, "%s%s", _PATH_DEV, argv[0]);
219	} else {
220		dkname = strrchr(argv[0], '/');
221		dkname++;
222		specname = argv[0];
223	}
224
225	if (installboot && op == UNSPEC)
226		op = WRITEBOOT;
227	else if (op == UNSPEC)
228		op = READ;
229
230	switch(op) {
231
232	case UNSPEC:
233		break;
234
235	case EDIT:
236		if (argc != 1)
237			usage();
238		readlabel(1);
239		error = edit();
240		break;
241
242	case READ:
243		if (argc != 1)
244			usage();
245		readlabel(1);
246		display(stdout, NULL);
247		error = checklabel(NULL);
248		break;
249
250	case RESTORE:
251		if (argc != 2)
252			usage();
253		if (!(t = fopen(argv[1], "r")))
254			err(4, "fopen %s", argv[1]);
255		readlabel(0);
256		if (!getasciilabel(t, &lab))
257			exit(1);
258		error = writelabel();
259		break;
260
261	case WRITE:
262		if (argc == 2)
263			name = argv[1];
264		else if (argc == 1)
265			name = "auto";
266		else
267			usage();
268		readlabel(0);
269		makelabel(name, &lab);
270		if (checklabel(NULL) == 0)
271			error = writelabel();
272		break;
273
274	case WRITEBOOT:
275
276		readlabel(1);
277		if (argc == 2)
278			makelabel(argv[1], &lab);
279		if (checklabel(NULL) == 0)
280			error = writelabel();
281		break;
282	}
283	exit(error);
284}
285
286/*
287 * Construct a prototype disklabel from /etc/disktab.
288 */
289static void
290makelabel(const char *type, struct disklabel *lp)
291{
292	struct disklabel *dp;
293
294	if (strcmp(type, "auto") == 0)
295		dp = getvirginlabel();
296	else
297		dp = getdiskbyname(type);
298	if (dp == NULL)
299		errx(1, "%s: unknown disk type", type);
300	*lp = *dp;
301	bzero(lp->d_packname, sizeof(lp->d_packname));
302}
303
304static void
305readboot(void)
306{
307	int fd, i;
308	struct stat st;
309
310	if (xxboot == NULL)
311		xxboot = "/boot/boot";
312	fd = open(xxboot, O_RDONLY);
313	if (fd < 0)
314		err(1, "cannot open %s", xxboot);
315	fstat(fd, &st);
316	if (alphacksum && st.st_size <= BBSIZE - 512) {
317		i = read(fd, bootarea + 512, st.st_size);
318		if (i != st.st_size)
319			err(1, "read error %s", xxboot);
320		return;
321	} else if ((!alphacksum) && st.st_size <= BBSIZE) {
322		i = read(fd, bootarea, st.st_size);
323		if (i != st.st_size)
324			err(1, "read error %s", xxboot);
325		return;
326	}
327	errx(1, "boot code %s is wrong size", xxboot);
328}
329
330static int
331writelabel(void)
332{
333	uint64_t *p, sum;
334	int i, fd;
335	struct gctl_req *grq;
336	char const *errstr;
337	struct disklabel *lp = &lab;
338
339	if (disable_write) {
340		warnx("write to disk label supressed - label was as follows:");
341		display(stdout, NULL);
342		return (0);
343	}
344
345	lp->d_magic = DISKMAGIC;
346	lp->d_magic2 = DISKMAGIC;
347	lp->d_checksum = 0;
348	lp->d_checksum = dkcksum(lp);
349	if (installboot)
350		readboot();
351	for (i = 0; i < lab.d_npartitions; i++)
352		if (lab.d_partitions[i].p_size)
353			lab.d_partitions[i].p_offset += mbroffset;
354	bsd_disklabel_le_enc(bootarea + labeloffset + labelsoffset * secsize,
355	    lp);
356	if (alphacksum) {
357		/* Generate the bootblock checksum for the SRM console.  */
358		for (p = (uint64_t *)bootarea, i = 0, sum = 0; i < 63; i++)
359			sum += p[i];
360		p[63] = sum;
361	}
362
363	fd = open(specname, O_RDWR);
364	if (fd < 0) {
365		grq = gctl_get_handle();
366		gctl_ro_param(grq, "verb", -1, "write label");
367		gctl_ro_param(grq, "class", -1, "BSD");
368		gctl_ro_param(grq, "geom", -1, dkname);
369		gctl_ro_param(grq, "label", 148+16*8,
370			bootarea + labeloffset + labelsoffset * secsize);
371		errstr = gctl_issue(grq);
372		if (errstr != NULL) {
373			warnx("%s", errstr);
374			gctl_free(grq);
375			return(1);
376		}
377		gctl_free(grq);
378		if (installboot) {
379			grq = gctl_get_handle();
380			gctl_ro_param(grq, "verb", -1, "write bootcode");
381			gctl_ro_param(grq, "class", -1, "BSD");
382			gctl_ro_param(grq, "geom", -1, dkname);
383			gctl_ro_param(grq, "bootcode", BBSIZE, bootarea);
384			errstr = gctl_issue(grq);
385			if (errstr != NULL) {
386				warnx("%s", errstr);
387				gctl_free(grq);
388				return (1);
389			}
390			gctl_free(grq);
391		}
392	} else {
393		if (write(fd, bootarea, bbsize) != bbsize) {
394			warn("write %s", specname);
395			close (fd);
396			return (1);
397		}
398		close (fd);
399	}
400	return (0);
401}
402
403/*
404 * Fetch disklabel for disk.
405 * Use ioctl to get label unless -r flag is given.
406 */
407static int
408readlabel(int flag)
409{
410	int f, i;
411	int error;
412	struct gctl_req *grq;
413	char const *errstr;
414
415	f = open(specname, O_RDONLY);
416	if (f < 0)
417		err(1, specname);
418	/* New world order */
419	if ((ioctl(f, DIOCGMEDIASIZE, &mediasize) != 0) ||
420	    (ioctl(f, DIOCGSECTORSIZE, &secsize) != 0)) {
421		err(4, "cannot get disk geometry");
422	}
423	(void)lseek(f, (off_t)0, SEEK_SET);
424	if (read(f, bootarea, BBSIZE) != BBSIZE)
425		err(4, "%s read", specname);
426	close (f);
427	error = bsd_disklabel_le_dec(
428	    bootarea + (labeloffset + labelsoffset * secsize),
429	    &lab, MAXPARTITIONS);
430	if (flag && error)
431		errx(1, "%s: no valid label found", specname);
432
433	grq = gctl_get_handle();
434	gctl_ro_param(grq, "verb", -1, "read mbroffset");
435	gctl_ro_param(grq, "class", -1, "BSD");
436	gctl_ro_param(grq, "geom", -1, dkname);
437	gctl_rw_param(grq, "mbroffset", sizeof(mbroffset), &mbroffset);
438	errstr = gctl_issue(grq);
439	if (errstr != NULL) {
440		mbroffset = 0;
441		gctl_free(grq);
442		return (error);
443	}
444	mbroffset /= lab.d_secsize;
445	if (lab.d_partitions[RAW_PART].p_offset == mbroffset)
446		for (i = 0; i < lab.d_npartitions; i++)
447			if (lab.d_partitions[i].p_size)
448				lab.d_partitions[i].p_offset -= mbroffset;
449	return (error);
450}
451
452
453static void
454display(FILE *f, const struct disklabel *lp)
455{
456	int i, j;
457	const struct partition *pp;
458
459	if (lp == NULL)
460		lp = &lab;
461
462	fprintf(f, "# %s:\n", specname);
463	if (allfields) {
464		if (lp->d_type < DKMAXTYPES)
465			fprintf(f, "type: %s\n", dktypenames[lp->d_type]);
466		else
467			fprintf(f, "type: %u\n", lp->d_type);
468		fprintf(f, "disk: %.*s\n", (int)sizeof(lp->d_typename),
469			lp->d_typename);
470		fprintf(f, "label: %.*s\n", (int)sizeof(lp->d_packname),
471			lp->d_packname);
472		fprintf(f, "flags:");
473		if (lp->d_flags & D_REMOVABLE)
474			fprintf(f, " removeable");
475		if (lp->d_flags & D_ECC)
476			fprintf(f, " ecc");
477		if (lp->d_flags & D_BADSECT)
478			fprintf(f, " badsect");
479		fprintf(f, "\n");
480		fprintf(f, "bytes/sector: %lu\n", (u_long)lp->d_secsize);
481		fprintf(f, "sectors/track: %lu\n", (u_long)lp->d_nsectors);
482		fprintf(f, "tracks/cylinder: %lu\n", (u_long)lp->d_ntracks);
483		fprintf(f, "sectors/cylinder: %lu\n", (u_long)lp->d_secpercyl);
484		fprintf(f, "cylinders: %lu\n", (u_long)lp->d_ncylinders);
485		fprintf(f, "sectors/unit: %lu\n", (u_long)lp->d_secperunit);
486		fprintf(f, "rpm: %u\n", lp->d_rpm);
487		fprintf(f, "interleave: %u\n", lp->d_interleave);
488		fprintf(f, "trackskew: %u\n", lp->d_trackskew);
489		fprintf(f, "cylinderskew: %u\n", lp->d_cylskew);
490		fprintf(f, "headswitch: %lu\t\t# milliseconds\n",
491		    (u_long)lp->d_headswitch);
492		fprintf(f, "track-to-track seek: %ld\t# milliseconds\n",
493		    (u_long)lp->d_trkseek);
494		fprintf(f, "drivedata: ");
495		for (i = NDDATA - 1; i >= 0; i--)
496			if (lp->d_drivedata[i])
497				break;
498		if (i < 0)
499			i = 0;
500		for (j = 0; j <= i; j++)
501			fprintf(f, "%lu ", (u_long)lp->d_drivedata[j]);
502		fprintf(f, "\n\n");
503	}
504	fprintf(f, "%u partitions:\n", lp->d_npartitions);
505	fprintf(f,
506	    "#        size   offset    fstype   [fsize bsize bps/cpg]\n");
507	pp = lp->d_partitions;
508	for (i = 0; i < lp->d_npartitions; i++, pp++) {
509		if (pp->p_size) {
510			fprintf(f, "  %c: %8lu %8lu  ", 'a' + i,
511			   (u_long)pp->p_size, (u_long)pp->p_offset);
512			if (pp->p_fstype < FSMAXTYPES)
513				fprintf(f, "%8.8s", fstypenames[pp->p_fstype]);
514			else
515				fprintf(f, "%8d", pp->p_fstype);
516			switch (pp->p_fstype) {
517
518			case FS_UNUSED:				/* XXX */
519				fprintf(f, "    %5lu %5lu %5.5s ",
520				    (u_long)pp->p_fsize,
521				    (u_long)(pp->p_fsize * pp->p_frag), "");
522				break;
523
524			case FS_BSDFFS:
525				fprintf(f, "    %5lu %5lu %5u ",
526				    (u_long)pp->p_fsize,
527				    (u_long)(pp->p_fsize * pp->p_frag),
528				    pp->p_cpg);
529				break;
530
531			case FS_BSDLFS:
532				fprintf(f, "    %5lu %5lu %5d",
533				    (u_long)pp->p_fsize,
534				    (u_long)(pp->p_fsize * pp->p_frag),
535				    pp->p_cpg);
536				break;
537
538			default:
539				fprintf(f, "%20.20s", "");
540				break;
541			}
542			if (i == RAW_PART) {
543				fprintf(f, "  # \"raw\" part, don't edit");
544			}
545			fprintf(f, "\n");
546		}
547	}
548	fflush(f);
549}
550
551static int
552edit(void)
553{
554	int c, fd;
555	struct disklabel label;
556	FILE *fp;
557
558	if ((fd = mkstemp(tmpfil)) == -1 ||
559	    (fp = fdopen(fd, "w")) == NULL) {
560		warnx("can't create %s", tmpfil);
561		return (1);
562	}
563	display(fp, NULL);
564	fclose(fp);
565	for (;;) {
566		if (!editit())
567			break;
568		fp = fopen(tmpfil, "r");
569		if (fp == NULL) {
570			warnx("can't reopen %s for reading", tmpfil);
571			break;
572		}
573		bzero((char *)&label, sizeof(label));
574		c = getasciilabel(fp, &label);
575		fclose(fp);
576		if (c) {
577			lab = label;
578			if (writelabel() == 0) {
579				(void) unlink(tmpfil);
580				return (0);
581			}
582		}
583		printf("re-edit the label? [y]: ");
584		fflush(stdout);
585		c = getchar();
586		if (c != EOF && c != (int)'\n')
587			while (getchar() != (int)'\n')
588				;
589		if  (c == (int)'n')
590			break;
591	}
592	(void) unlink(tmpfil);
593	return (1);
594}
595
596static int
597editit(void)
598{
599	int pid, xpid;
600	int locstat, omask;
601	const char *ed;
602
603	omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
604	while ((pid = fork()) < 0) {
605		if (errno == EPROCLIM) {
606			warnx("you have too many processes");
607			return(0);
608		}
609		if (errno != EAGAIN) {
610			warn("fork");
611			return(0);
612		}
613		sleep(1);
614	}
615	if (pid == 0) {
616		sigsetmask(omask);
617		setgid(getgid());
618		setuid(getuid());
619		if ((ed = getenv("EDITOR")) == (char *)0)
620			ed = DEFEDITOR;
621		execlp(ed, ed, tmpfil, (char *)0);
622		err(1, "%s", ed);
623	}
624	while ((xpid = wait(&locstat)) >= 0)
625		if (xpid == pid)
626			break;
627	sigsetmask(omask);
628	return(!locstat);
629}
630
631static char *
632skip(char *cp)
633{
634
635	while (*cp != '\0' && isspace(*cp))
636		cp++;
637	if (*cp == '\0' || *cp == '#')
638		return (NULL);
639	return (cp);
640}
641
642static char *
643word(char *cp)
644{
645	char c;
646
647	while (*cp != '\0' && !isspace(*cp) && *cp != '#')
648		cp++;
649	if ((c = *cp) != '\0') {
650		*cp++ = '\0';
651		if (c != '#')
652			return (skip(cp));
653	}
654	return (NULL);
655}
656
657/*
658 * Read an ascii label in from fd f,
659 * in the same format as that put out by display(),
660 * and fill in lp.
661 */
662static int
663getasciilabel(FILE *f, struct disklabel *lp)
664{
665	char *cp;
666	const char **cpp;
667	u_int part;
668	char *tp, line[BUFSIZ];
669	u_long v;
670	int lineno = 0, errors = 0;
671	int i;
672
673	makelabel("auto", lp);
674	bzero(&part_set, sizeof(part_set));
675	bzero(&part_size_type, sizeof(part_size_type));
676	bzero(&part_offset_type, sizeof(part_offset_type));
677	lp->d_bbsize = BBSIZE;				/* XXX */
678	lp->d_sbsize = 0;				/* XXX */
679	while (fgets(line, sizeof(line) - 1, f)) {
680		lineno++;
681		if ((cp = index(line,'\n')) != 0)
682			*cp = '\0';
683		cp = skip(line);
684		if (cp == NULL)
685			continue;
686		tp = index(cp, ':');
687		if (tp == NULL) {
688			fprintf(stderr, "line %d: syntax error\n", lineno);
689			errors++;
690			continue;
691		}
692		*tp++ = '\0', tp = skip(tp);
693		if (!strcmp(cp, "type")) {
694			if (tp == NULL)
695				tp = unknown;
696			cpp = dktypenames;
697			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
698				if (*cpp && !strcmp(*cpp, tp)) {
699					lp->d_type = cpp - dktypenames;
700					break;
701				}
702			if (cpp < &dktypenames[DKMAXTYPES])
703				continue;
704			v = strtoul(tp, NULL, 10);
705			if (v >= DKMAXTYPES)
706				fprintf(stderr, "line %d:%s %lu\n", lineno,
707				    "Warning, unknown disk type", v);
708			lp->d_type = v;
709			continue;
710		}
711		if (!strcmp(cp, "flags")) {
712			for (v = 0; (cp = tp) && *cp != '\0';) {
713				tp = word(cp);
714				if (!strcmp(cp, "removeable"))
715					v |= D_REMOVABLE;
716				else if (!strcmp(cp, "ecc"))
717					v |= D_ECC;
718				else if (!strcmp(cp, "badsect"))
719					v |= D_BADSECT;
720				else {
721					fprintf(stderr,
722					    "line %d: %s: bad flag\n",
723					    lineno, cp);
724					errors++;
725				}
726			}
727			lp->d_flags = v;
728			continue;
729		}
730		if (!strcmp(cp, "drivedata")) {
731			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
732				lp->d_drivedata[i++] = strtoul(cp, NULL, 10);
733				tp = word(cp);
734			}
735			continue;
736		}
737		if (sscanf(cp, "%lu partitions", &v) == 1) {
738			if (v == 0 || v > MAXPARTITIONS) {
739				fprintf(stderr,
740				    "line %d: bad # of partitions\n", lineno);
741				lp->d_npartitions = MAXPARTITIONS;
742				errors++;
743			} else
744				lp->d_npartitions = v;
745			continue;
746		}
747		if (tp == NULL)
748			tp = blank;
749		if (!strcmp(cp, "disk")) {
750			strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
751			continue;
752		}
753		if (!strcmp(cp, "label")) {
754			strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
755			continue;
756		}
757		if (!strcmp(cp, "bytes/sector")) {
758			v = strtoul(tp, NULL, 10);
759			if (v == 0 || (v % DEV_BSIZE) != 0) {
760				fprintf(stderr,
761				    "line %d: %s: bad sector size\n",
762				    lineno, tp);
763				errors++;
764			} else
765				lp->d_secsize = v;
766			continue;
767		}
768		if (!strcmp(cp, "sectors/track")) {
769			v = strtoul(tp, NULL, 10);
770#if (ULONG_MAX != 0xffffffffUL)
771			if (v == 0 || v > 0xffffffff) {
772#else
773			if (v == 0) {
774#endif
775				fprintf(stderr, "line %d: %s: bad %s\n",
776				    lineno, tp, cp);
777				errors++;
778			} else
779				lp->d_nsectors = v;
780			continue;
781		}
782		if (!strcmp(cp, "sectors/cylinder")) {
783			v = strtoul(tp, NULL, 10);
784			if (v == 0) {
785				fprintf(stderr, "line %d: %s: bad %s\n",
786				    lineno, tp, cp);
787				errors++;
788			} else
789				lp->d_secpercyl = v;
790			continue;
791		}
792		if (!strcmp(cp, "tracks/cylinder")) {
793			v = strtoul(tp, NULL, 10);
794			if (v == 0) {
795				fprintf(stderr, "line %d: %s: bad %s\n",
796				    lineno, tp, cp);
797				errors++;
798			} else
799				lp->d_ntracks = v;
800			continue;
801		}
802		if (!strcmp(cp, "cylinders")) {
803			v = strtoul(tp, NULL, 10);
804			if (v == 0) {
805				fprintf(stderr, "line %d: %s: bad %s\n",
806				    lineno, tp, cp);
807				errors++;
808			} else
809				lp->d_ncylinders = v;
810			continue;
811		}
812		if (!strcmp(cp, "sectors/unit")) {
813			v = strtoul(tp, NULL, 10);
814			if (v == 0) {
815				fprintf(stderr, "line %d: %s: bad %s\n",
816				    lineno, tp, cp);
817				errors++;
818			} else
819				lp->d_secperunit = v;
820			continue;
821		}
822		if (!strcmp(cp, "rpm")) {
823			v = strtoul(tp, NULL, 10);
824			if (v == 0 || v > USHRT_MAX) {
825				fprintf(stderr, "line %d: %s: bad %s\n",
826				    lineno, tp, cp);
827				errors++;
828			} else
829				lp->d_rpm = v;
830			continue;
831		}
832		if (!strcmp(cp, "interleave")) {
833			v = strtoul(tp, NULL, 10);
834			if (v == 0 || v > USHRT_MAX) {
835				fprintf(stderr, "line %d: %s: bad %s\n",
836				    lineno, tp, cp);
837				errors++;
838			} else
839				lp->d_interleave = v;
840			continue;
841		}
842		if (!strcmp(cp, "trackskew")) {
843			v = strtoul(tp, NULL, 10);
844			if (v > USHRT_MAX) {
845				fprintf(stderr, "line %d: %s: bad %s\n",
846				    lineno, tp, cp);
847				errors++;
848			} else
849				lp->d_trackskew = v;
850			continue;
851		}
852		if (!strcmp(cp, "cylinderskew")) {
853			v = strtoul(tp, NULL, 10);
854			if (v > USHRT_MAX) {
855				fprintf(stderr, "line %d: %s: bad %s\n",
856				    lineno, tp, cp);
857				errors++;
858			} else
859				lp->d_cylskew = v;
860			continue;
861		}
862		if (!strcmp(cp, "headswitch")) {
863			v = strtoul(tp, NULL, 10);
864			lp->d_headswitch = v;
865			continue;
866		}
867		if (!strcmp(cp, "track-to-track seek")) {
868			v = strtoul(tp, NULL, 10);
869			lp->d_trkseek = v;
870			continue;
871		}
872		/* the ':' was removed above */
873		if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') {
874			fprintf(stderr,
875			    "line %d: %s: Unknown disklabel field\n", lineno,
876			    cp);
877			errors++;
878			continue;
879		}
880
881		/* Process a partition specification line. */
882		part = *cp - 'a';
883		if (part >= lp->d_npartitions) {
884			fprintf(stderr,
885			    "line %d: partition name out of range a-%c: %s\n",
886			    lineno, 'a' + lp->d_npartitions - 1, cp);
887			errors++;
888			continue;
889		}
890		part_set[part] = 1;
891
892		if (getasciipartspec(tp, lp, part, lineno) != 0) {
893			errors++;
894			break;
895		}
896	}
897	errors += checklabel(lp);
898	return (errors == 0);
899}
900
901#define NXTNUM(n) do { \
902	if (tp == NULL) { \
903		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
904		return (1); \
905	} else { \
906		cp = tp, tp = word(cp); \
907		(n) = strtoul(cp, NULL, 10); \
908	} \
909} while (0)
910
911/* retain 1 character following number */
912#define NXTWORD(w,n) do { \
913	if (tp == NULL) { \
914		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
915		return (1); \
916	} else { \
917	        char *tmp; \
918		cp = tp, tp = word(cp); \
919	        (n) = strtoul(cp, &tmp, 10); \
920		if (tmp) (w) = *tmp; \
921	} \
922} while (0)
923
924/*
925 * Read a partition line into partition `part' in the specified disklabel.
926 * Return 0 on success, 1 on failure.
927 */
928static int
929getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno)
930{
931	struct partition *pp;
932	char *cp;
933	const char **cpp;
934	u_long v;
935
936	pp = &lp->d_partitions[part];
937	cp = NULL;
938
939	v = 0;
940	NXTWORD(part_size_type[part],v);
941	if (v == 0 && part_size_type[part] != '*') {
942		fprintf(stderr,
943		    "line %d: %s: bad partition size\n", lineno, cp);
944		return (1);
945	}
946	pp->p_size = v;
947
948	v = 0;
949	NXTWORD(part_offset_type[part],v);
950	if (v == 0 && part_offset_type[part] != '*' &&
951	    part_offset_type[part] != '\0') {
952		fprintf(stderr,
953		    "line %d: %s: bad partition offset\n", lineno, cp);
954		return (1);
955	}
956	pp->p_offset = v;
957	if (tp == NULL) {
958		fprintf(stderr, "line %d: missing file system type\n", lineno);
959		return (1);
960	}
961	cp = tp, tp = word(cp);
962	for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++)
963		if (*cpp && !strcmp(*cpp, cp))
964			break;
965	if (*cpp != NULL) {
966		pp->p_fstype = cpp - fstypenames;
967	} else {
968		if (isdigit(*cp))
969			v = strtoul(cp, NULL, 10);
970		else
971			v = FSMAXTYPES;
972		if (v >= FSMAXTYPES) {
973			fprintf(stderr,
974			    "line %d: Warning, unknown file system type %s\n",
975			    lineno, cp);
976			v = FS_UNUSED;
977		}
978		pp->p_fstype = v;
979	}
980
981	switch (pp->p_fstype) {
982	case FS_UNUSED:
983		/*
984		 * allow us to accept defaults for
985		 * fsize/frag/cpg
986		 */
987		if (tp) {
988			NXTNUM(pp->p_fsize);
989			if (pp->p_fsize == 0)
990				break;
991			NXTNUM(v);
992			pp->p_frag = v / pp->p_fsize;
993		}
994		/* else default to 0's */
995		break;
996
997	/* These happen to be the same */
998	case FS_BSDFFS:
999	case FS_BSDLFS:
1000		if (tp) {
1001			NXTNUM(pp->p_fsize);
1002			if (pp->p_fsize == 0)
1003				break;
1004			NXTNUM(v);
1005			pp->p_frag = v / pp->p_fsize;
1006			NXTNUM(pp->p_cpg);
1007		} else {
1008			/*
1009			 * FIX! poor attempt at adaptive
1010			 */
1011			/* 1 GB */
1012			if (pp->p_size < 1024*1024*1024 / lp->d_secsize) {
1013				/*
1014				 * FIX! These are too low, but are traditional
1015				 */
1016				pp->p_fsize = DEFAULT_NEWFS_FRAG;
1017				pp->p_frag = DEFAULT_NEWFS_BLOCK /
1018				    DEFAULT_NEWFS_FRAG;
1019				pp->p_cpg = DEFAULT_NEWFS_CPG;
1020			} else {
1021				pp->p_fsize = BIG_NEWFS_FRAG;
1022				pp->p_frag = BIG_NEWFS_BLOCK /
1023				    BIG_NEWFS_FRAG;
1024				pp->p_cpg = BIG_NEWFS_CPG;
1025			}
1026		}
1027	default:
1028		break;
1029	}
1030	return (0);
1031}
1032
1033/*
1034 * Check disklabel for errors and fill in
1035 * derived fields according to supplied values.
1036 */
1037static int
1038checklabel(struct disklabel *lp)
1039{
1040	struct partition *pp;
1041	int i, errors = 0;
1042	char part;
1043	u_long total_size, total_percent, current_offset;
1044	int seen_default_offset;
1045	int hog_part;
1046	int j;
1047	struct partition *pp2;
1048
1049	if (lp == NULL)
1050		lp = &lab;
1051
1052	if (allfields) {
1053
1054		if (lp->d_secsize == 0) {
1055			fprintf(stderr, "sector size 0\n");
1056			return (1);
1057		}
1058		if (lp->d_nsectors == 0) {
1059			fprintf(stderr, "sectors/track 0\n");
1060			return (1);
1061		}
1062		if (lp->d_ntracks == 0) {
1063			fprintf(stderr, "tracks/cylinder 0\n");
1064			return (1);
1065		}
1066		if  (lp->d_ncylinders == 0) {
1067			fprintf(stderr, "cylinders/unit 0\n");
1068			errors++;
1069		}
1070		if (lp->d_rpm == 0)
1071			warnx("revolutions/minute 0");
1072		if (lp->d_secpercyl == 0)
1073			lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1074		if (lp->d_secperunit == 0)
1075			lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1076		if (lp->d_bbsize == 0) {
1077			fprintf(stderr, "boot block size 0\n");
1078			errors++;
1079		} else if (lp->d_bbsize % lp->d_secsize)
1080			warnx("boot block size %% sector-size != 0");
1081		if (lp->d_npartitions > MAXPARTITIONS)
1082			warnx("number of partitions (%lu) > MAXPARTITIONS (%d)",
1083			    (u_long)lp->d_npartitions, MAXPARTITIONS);
1084	} else {
1085		struct disklabel *vl;
1086
1087		vl = getvirginlabel();
1088		lp->d_secsize = vl->d_secsize;
1089		lp->d_nsectors = vl->d_nsectors;
1090		lp->d_ntracks = vl->d_ntracks;
1091		lp->d_ncylinders = vl->d_ncylinders;
1092		lp->d_rpm = vl->d_rpm;
1093		lp->d_interleave = vl->d_interleave;
1094		lp->d_secpercyl = vl->d_secpercyl;
1095		lp->d_secperunit = vl->d_secperunit;
1096		lp->d_bbsize = vl->d_bbsize;
1097		lp->d_npartitions = vl->d_npartitions;
1098	}
1099
1100
1101	/* first allocate space to the partitions, then offsets */
1102	total_size = 0; /* in sectors */
1103	total_percent = 0; /* in percent */
1104	hog_part = -1;
1105	/* find all fixed partitions */
1106	for (i = 0; i < lp->d_npartitions; i++) {
1107		pp = &lp->d_partitions[i];
1108		if (part_set[i]) {
1109			if (part_size_type[i] == '*') {
1110				if (i == RAW_PART) {
1111					pp->p_size = lp->d_secperunit;
1112				} else {
1113					if (hog_part != -1)
1114						warnx("Too many '*' partitions (%c and %c)",
1115						    hog_part + 'a',i + 'a');
1116					else
1117						hog_part = i;
1118				}
1119			} else {
1120				off_t size;
1121
1122				size = pp->p_size;
1123				switch (part_size_type[i]) {
1124				case '%':
1125					total_percent += size;
1126					break;
1127				case 'k':
1128				case 'K':
1129					size *= 1024ULL;
1130					break;
1131				case 'm':
1132				case 'M':
1133					size *= 1024ULL * 1024ULL;
1134					break;
1135				case 'g':
1136				case 'G':
1137					size *= 1024ULL * 1024ULL * 1024ULL;
1138					break;
1139				case '\0':
1140					break;
1141				default:
1142					warnx("unknown size specifier '%c' (K/M/G are valid)",part_size_type[i]);
1143					break;
1144				}
1145				/* don't count %'s yet */
1146				if (part_size_type[i] != '%') {
1147					/*
1148					 * for all not in sectors, convert to
1149					 * sectors
1150					 */
1151					if (part_size_type[i] != '\0') {
1152						if (size % lp->d_secsize != 0)
1153							warnx("partition %c not an integer number of sectors",
1154							    i + 'a');
1155						size /= lp->d_secsize;
1156						pp->p_size = size;
1157					}
1158					/* else already in sectors */
1159					if (i != RAW_PART)
1160						total_size += size;
1161				}
1162			}
1163		}
1164	}
1165	/* handle % partitions - note %'s don't need to add up to 100! */
1166	if (total_percent != 0) {
1167		long free_space = lp->d_secperunit - total_size;
1168		if (total_percent > 100) {
1169			fprintf(stderr,"total percentage %lu is greater than 100\n",
1170			    total_percent);
1171			errors++;
1172		}
1173
1174		if (free_space > 0) {
1175			for (i = 0; i < lp->d_npartitions; i++) {
1176				pp = &lp->d_partitions[i];
1177				if (part_set[i] && part_size_type[i] == '%') {
1178					/* careful of overflows! and integer roundoff */
1179					pp->p_size = ((double)pp->p_size/100) * free_space;
1180					total_size += pp->p_size;
1181
1182					/* FIX we can lose a sector or so due to roundoff per
1183					   partition.  A more complex algorithm could avoid that */
1184				}
1185			}
1186		} else {
1187			fprintf(stderr,
1188			    "%ld sectors available to give to '*' and '%%' partitions\n",
1189			    free_space);
1190			errors++;
1191			/* fix?  set all % partitions to size 0? */
1192		}
1193	}
1194	/* give anything remaining to the hog partition */
1195	if (hog_part != -1) {
1196		lp->d_partitions[hog_part].p_size = lp->d_secperunit - total_size;
1197		total_size = lp->d_secperunit;
1198	}
1199
1200	/* Now set the offsets for each partition */
1201	current_offset = 0; /* in sectors */
1202	seen_default_offset = 0;
1203	for (i = 0; i < lp->d_npartitions; i++) {
1204		part = 'a' + i;
1205		pp = &lp->d_partitions[i];
1206		if (part_set[i]) {
1207			if (part_offset_type[i] == '*') {
1208				if (i == RAW_PART) {
1209					pp->p_offset = 0;
1210				} else {
1211					pp->p_offset = current_offset;
1212					seen_default_offset = 1;
1213				}
1214			} else {
1215				/* allow them to be out of order for old-style tables */
1216				if (pp->p_offset < current_offset &&
1217				    seen_default_offset && i != RAW_PART &&
1218				    pp->p_fstype != FS_VINUM) {
1219					fprintf(stderr,
1220"Offset %ld for partition %c overlaps previous partition which ends at %lu\n",
1221					    (long)pp->p_offset,i+'a',current_offset);
1222					fprintf(stderr,
1223"Labels with any *'s for offset must be in ascending order by sector\n");
1224					errors++;
1225				} else if (pp->p_offset != current_offset &&
1226				    i != RAW_PART && seen_default_offset) {
1227					/*
1228					 * this may give unneeded warnings if
1229					 * partitions are out-of-order
1230					 */
1231					warnx(
1232"Offset %ld for partition %c doesn't match expected value %ld",
1233					    (long)pp->p_offset, i + 'a', current_offset);
1234				}
1235			}
1236			if (i != RAW_PART)
1237				current_offset = pp->p_offset + pp->p_size;
1238		}
1239	}
1240
1241	for (i = 0; i < lp->d_npartitions; i++) {
1242		part = 'a' + i;
1243		pp = &lp->d_partitions[i];
1244		if (pp->p_size == 0 && pp->p_offset != 0)
1245			warnx("partition %c: size 0, but offset %lu",
1246			    part, (u_long)pp->p_offset);
1247#ifdef notdef
1248		if (pp->p_size % lp->d_secpercyl)
1249			warnx("partition %c: size %% cylinder-size != 0",
1250			    part);
1251		if (pp->p_offset % lp->d_secpercyl)
1252			warnx("partition %c: offset %% cylinder-size != 0",
1253			    part);
1254#endif
1255		if (pp->p_offset > lp->d_secperunit) {
1256			fprintf(stderr,
1257			    "partition %c: offset past end of unit\n", part);
1258			errors++;
1259		}
1260		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1261			fprintf(stderr,
1262			"partition %c: partition extends past end of unit\n",
1263			    part);
1264			errors++;
1265		}
1266		if (i == RAW_PART) {
1267			if (pp->p_fstype != FS_UNUSED)
1268				warnx("partition %c is not marked as unused!",part);
1269			if (pp->p_offset != 0)
1270				warnx("partition %c doesn't start at 0!",part);
1271			if (pp->p_size != lp->d_secperunit)
1272				warnx("partition %c doesn't cover the whole unit!",part);
1273
1274			if ((pp->p_fstype != FS_UNUSED) || (pp->p_offset != 0) ||
1275			    (pp->p_size != lp->d_secperunit)) {
1276				warnx("An incorrect partition %c may cause problems for "
1277				    "standard system utilities",part);
1278			}
1279		}
1280
1281		/* check for overlaps */
1282		/* this will check for all possible overlaps once and only once */
1283		for (j = 0; j < i; j++) {
1284			pp2 = &lp->d_partitions[j];
1285			if (j != RAW_PART && i != RAW_PART &&
1286			    pp->p_fstype != FS_VINUM &&
1287			    pp2->p_fstype != FS_VINUM &&
1288			    part_set[i] && part_set[j]) {
1289				if (pp2->p_offset < pp->p_offset + pp->p_size &&
1290				    (pp2->p_offset + pp2->p_size > pp->p_offset ||
1291					pp2->p_offset >= pp->p_offset)) {
1292					fprintf(stderr,"partitions %c and %c overlap!\n",
1293					    j + 'a', i + 'a');
1294					errors++;
1295				}
1296			}
1297		}
1298	}
1299	for (; i < MAXPARTITIONS; i++) {
1300		part = 'a' + i;
1301		pp = &lp->d_partitions[i];
1302		if (pp->p_size || pp->p_offset)
1303			warnx("unused partition %c: size %d offset %lu",
1304			    'a' + i, pp->p_size, (u_long)pp->p_offset);
1305	}
1306	return (errors);
1307}
1308
1309/*
1310 * When operating on a "virgin" disk, try getting an initial label
1311 * from the associated device driver.  This might work for all device
1312 * drivers that are able to fetch some initial device parameters
1313 * without even having access to a (BSD) disklabel, like SCSI disks,
1314 * most IDE drives, or vn devices.
1315 *
1316 * The device name must be given in its "canonical" form.
1317 */
1318static struct disklabel *
1319getvirginlabel(void)
1320{
1321	static struct disklabel loclab;
1322	struct partition *dp;
1323	int f;
1324	u_int u;
1325
1326	if ((f = open(specname, O_RDONLY)) == -1) {
1327		warn("cannot open %s", specname);
1328		return (NULL);
1329	}
1330
1331	/* New world order */
1332	if ((ioctl(f, DIOCGMEDIASIZE, &mediasize) != 0) ||
1333	    (ioctl(f, DIOCGSECTORSIZE, &secsize) != 0)) {
1334		close (f);
1335		return (NULL);
1336	}
1337	memset(&loclab, 0, sizeof loclab);
1338	loclab.d_magic = DISKMAGIC;
1339	loclab.d_magic2 = DISKMAGIC;
1340	loclab.d_secsize = secsize;
1341	loclab.d_secperunit = mediasize / secsize;
1342
1343	/*
1344	 * Nobody in these enligthened days uses the CHS geometry for
1345	 * anything, but nontheless try to get it right.  If we fail
1346	 * to get any good ideas from the device, construct something
1347	 * which is IBM-PC friendly.
1348	 */
1349	if (ioctl(f, DIOCGFWSECTORS, &u) == 0)
1350		loclab.d_nsectors = u;
1351	else
1352		loclab.d_nsectors = 63;
1353	if (ioctl(f, DIOCGFWHEADS, &u) == 0)
1354		loclab.d_ntracks = u;
1355	else if (loclab.d_secperunit <= 63*1*1024)
1356		loclab.d_ntracks = 1;
1357	else if (loclab.d_secperunit <= 63*16*1024)
1358		loclab.d_ntracks = 16;
1359	else
1360		loclab.d_ntracks = 255;
1361	loclab.d_secpercyl = loclab.d_ntracks * loclab.d_nsectors;
1362	loclab.d_ncylinders = loclab.d_secperunit / loclab.d_secpercyl;
1363	loclab.d_npartitions = MAXPARTITIONS;
1364
1365	/* Various (unneeded) compat stuff */
1366	loclab.d_rpm = 3600;
1367	loclab.d_bbsize = BBSIZE;
1368	loclab.d_interleave = 1;
1369	strncpy(loclab.d_typename, "amnesiac",
1370	    sizeof(loclab.d_typename));
1371
1372	dp = &loclab.d_partitions[RAW_PART];
1373	dp->p_size = loclab.d_secperunit;
1374	loclab.d_checksum = dkcksum(&loclab);
1375	close (f);
1376	return (&loclab);
1377}
1378
1379static void
1380usage(void)
1381{
1382
1383	fprintf(stderr,
1384	"%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1385	"usage: bsdlabel disk",
1386	"\t\t(to read label)",
1387	"	bsdlabel -w [-n] [-m machine] disk [type]",
1388	"\t\t(to write label with existing boot program)",
1389	"	bsdlabel -e [-n] [-m machine] disk",
1390	"\t\t(to edit label)",
1391	"	bsdlabel -R [-n] [-m machine] disk protofile",
1392	"\t\t(to restore label with existing boot program)",
1393	"	bsdlabel -B [-b boot] [-m machine] disk",
1394	"\t\t(to install boot program with existing on-disk label)",
1395	"	bsdlabel -w -B [-n] [-b boot] [-m machine] disk [type]",
1396	"\t\t(to write label and install boot program)",
1397	"	bsdlabel -R -B [-n] [-b boot] [-m machine] disk protofile",
1398		"\t\t(to restore label and install boot program)"
1399	);
1400	exit(1);
1401}
1402