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