xref: /freebsd/sbin/bsdlabel/bsdlabel.c (revision 729362425c09cf6b362366aabc6fb547eee8035a)
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
44 static 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
51 static 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$");
58 
59 #include <sys/param.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 <sys/diskmbr.h>
69 #if (DOSPARTOFF != 446 || NDOSPART != 4 || DOSPTYP_386BSD != 0xa5)
70 #error	<sys/diskmbr.h> has changed
71 #else
72 #define	I386_DOSPARTOFF		446
73 #define	I386_NDOSPART		4
74 #define	I386_DOSPTYP_386BSD	0xa5
75 #endif
76 #undef DOSPARTOFF
77 #undef NDOSPART
78 #undef DOSPTYP_386BSD
79 
80 #include <sys/diskpc98.h>
81 #if (DOSPARTOFF != 0 || NDOSPART != 16 || DOSPTYP_386BSD != 0x94)
82 #error	<sys/diskpc98.h> has changed
83 #else
84 #define	PC98_DOSPARTOFF		0
85 #define	PC98_NDOSPART		16
86 #define	PC98_DOSPTYP_386BSD	0x94
87 #endif
88 #undef DOSPARTOFF
89 #undef NDOSPART
90 #undef DOSPTYP_386BSD
91 
92 #define	IS_PC98	(arch->mach == MACH_PC98)
93 #define	DOSPARTOFF	(IS_PC98 ? PC98_DOSPARTOFF : I386_DOSPARTOFF)
94 #define	NDOSPART	(IS_PC98 ? PC98_NDOSPART : I386_NDOSPART)
95 #define	DOSPTYP_386BSD	(IS_PC98 ? PC98_DOSPTYP_386BSD : I386_DOSPTYP_386BSD)
96 
97 #include <unistd.h>
98 #include <string.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <signal.h>
102 #include <stdarg.h>
103 #include <ctype.h>
104 #include <err.h>
105 #include <errno.h>
106 
107 #include "pathnames.h"
108 
109 /*
110  * Disklabel: read and write disklabels.
111  * The label is usually placed on one of the first sectors of the disk.
112  * Many machines also place a bootstrap in the same area,
113  * in which case the label is embedded in the bootstrap.
114  * The bootstrap source must leave space at the proper offset
115  * for the label on such machines.
116  */
117 
118 #ifndef BBSIZE
119 #define	BBSIZE	8192			/* size of boot area, with label */
120 #endif
121 
122 /* FIX!  These are too low, but are traditional */
123 #define DEFAULT_NEWFS_BLOCK  8192U
124 #define DEFAULT_NEWFS_FRAG   1024U
125 #define DEFAULT_NEWFS_CPG    16U
126 
127 #define BIG_NEWFS_BLOCK  16384U
128 #define BIG_NEWFS_FRAG   2048U
129 #define BIG_NEWFS_CPG    64U
130 
131 void	makelabel(const char *, const char *, struct disklabel *);
132 int	writelabel(int, void *, struct disklabel *);
133 void	l_perror(const char *);
134 struct disklabel *readlabel(int);
135 struct disklabel *makebootarea(void *, struct disklabel *, int);
136 void	display(FILE *, const struct disklabel *);
137 int	edit(struct disklabel *, int);
138 int	editit(void);
139 char	*skip(char *);
140 char	*word(char *);
141 int	getasciilabel(FILE *, struct disklabel *);
142 int	getasciipartspec(char *, struct disklabel *, int, int);
143 int	checklabel(struct disklabel *);
144 void	Warning(const char *, ...) __printflike(1, 2);
145 void	usage(void);
146 struct disklabel *getvirginlabel(void);
147 
148 #define	DEFEDITOR	_PATH_VI
149 #define	streq(a,b)	(strcmp(a,b) == 0)
150 
151 char	*dkname;
152 char	*specname;
153 char	tmpfil[] = PATH_TMPFILE;
154 
155 char	namebuf[BBSIZE], *np = namebuf;
156 struct	disklabel lab;
157 int64_t	bootarea[BBSIZE / 8];
158 char	blank[] = "";
159 char	unknown[] = "unknown";
160 
161 #define MAX_PART ('z')
162 #define MAX_NUM_PARTS (1 + MAX_PART - 'a')
163 char    part_size_type[MAX_NUM_PARTS];
164 char    part_offset_type[MAX_NUM_PARTS];
165 int     part_set[MAX_NUM_PARTS];
166 
167 int	installboot;	/* non-zero if we should install a boot program */
168 char	*xxboot;	/* primary boot */
169 char	boot0[MAXPATHLEN];
170 
171 enum	{
172 	UNSPEC, EDIT, READ, RESTORE, WRITE, WRITEBOOT
173 } op = UNSPEC;
174 
175 enum { ARCH_I386, ARCH_ALPHA, ARCH_IA64 };
176 
177 enum { MACH_I386, MACH_PC98 };
178 
179 struct {
180 	const char	*name;
181 	int		arch;
182 	int		mach;
183 	off_t		label_sector;
184 	off_t		label_offset;
185 } arches[] = {
186 	{ "i386", ARCH_I386, MACH_I386, 1, 0 },
187 	{ "pc98", ARCH_I386, MACH_PC98, 1, 0 },
188 	{ "alpha", ARCH_ALPHA, ARCH_ALPHA, 0, 64 },
189 	{ "ia64", ARCH_IA64, ARCH_IA64, 1, 0 },
190 }, *arch;
191 #define	NARCHES	(int)(sizeof(arches) / sizeof(*arches))
192 
193 int	rflag;
194 int	disable_write;   /* set to disable writing to disk label */
195 
196 int
197 main(int argc, char *argv[])
198 {
199 	struct disklabel *lp;
200 	FILE *t;
201 	int ch, f = 0, error = 0, i;
202 	char *name = 0;
203 
204 	while ((ch = getopt(argc, argv, "Bb:em:nRrs:w")) != -1)
205 		switch (ch) {
206 			case 'B':
207 				++installboot;
208 				break;
209 			case 'b':
210 				xxboot = optarg;
211 				break;
212 			case 'm':
213 				for (i = 0; i < NARCHES &&
214 				    strcmp(arches[i].name, optarg) != 0;
215 				    i++);
216 				if (i == NARCHES)
217 					errx(1, "%s: unknown architecture",
218 					    optarg);
219 				arch = &arches[i];
220 				break;
221 			case 'n':
222 				disable_write = 1;
223 				break;
224 			case 'R':
225 				if (op != UNSPEC)
226 					usage();
227 				op = RESTORE;
228 				break;
229 			case 'e':
230 				if (op != UNSPEC)
231 					usage();
232 				op = EDIT;
233 				break;
234 			case 'r':
235 				++rflag;
236 				break;
237 			case 'w':
238 				if (op != UNSPEC)
239 					usage();
240 				op = WRITE;
241 				break;
242 			case '?':
243 			default:
244 				usage();
245 		}
246 	argc -= optind;
247 	argv += optind;
248 	if (installboot) {
249 		rflag++;
250 		if (op == UNSPEC)
251 			op = WRITEBOOT;
252 	} else {
253 		if (op == UNSPEC)
254 			op = READ;
255 		xxboot = 0;
256 	}
257 	if (argc < 1)
258 		usage();
259 
260 	if (arch == NULL) {
261 		for (i = 0; i < NARCHES; i++)
262 			if (strcmp(arches[i].name,
263 #if defined(__i386__)
264 #ifdef PC98
265 			    "pc98"
266 #else
267 			    "i386"
268 #endif
269 #elif defined(__alpha__)
270 			    "alpha"
271 #elif defined(__ia64__)
272 			    "ia64"
273 #else
274 			    "unknown"
275 #endif
276 			    ) == 0) {
277 				arch = &arches[i];
278 				break;
279 			}
280 		if (i == NARCHES)
281 			errx(1, "unsupported architecture");
282 	}
283 
284 	dkname = argv[0];
285 	if (dkname[0] != '/') {
286 		(void)sprintf(np, "%s%s%c", _PATH_DEV, dkname, 'a' + RAW_PART);
287 		specname = np;
288 		np += strlen(specname) + 1;
289 	} else
290 		specname = dkname;
291 	f = open(specname, op == READ ? O_RDONLY : O_RDWR);
292 	if (f < 0 && errno == ENOENT && dkname[0] != '/') {
293 		(void)sprintf(specname, "%s%s", _PATH_DEV, dkname);
294 		np = namebuf + strlen(specname) + 1;
295 		f = open(specname, op == READ ? O_RDONLY : O_RDWR);
296 	}
297 	if (f < 0 && errno == EBUSY) {
298 		/* lets try to get by with ioctls */
299 		f = open(specname, O_RDONLY);
300 	}
301 	if (f < 0)
302 		err(4, "%s", specname);
303 
304 	switch(op) {
305 
306 	case UNSPEC:
307 		break;
308 
309 	case EDIT:
310 		if (argc != 1)
311 			usage();
312 		lp = readlabel(f);
313 		error = edit(lp, f);
314 		break;
315 
316 	case READ:
317 		if (argc != 1)
318 			usage();
319 		lp = readlabel(f);
320 		display(stdout, lp);
321 		error = checklabel(lp);
322 		break;
323 
324 	case RESTORE:
325 		if (argc != 2)
326 			usage();
327 		if (!(t = fopen(argv[1], "r")))
328 			err(4, "%s", argv[1]);
329 		if (!getasciilabel(t, &lab))
330 			exit(1);
331 		lp = makebootarea(bootarea, &lab, f);
332 		*lp = lab;
333 		error = writelabel(f, bootarea, lp);
334 		break;
335 
336 	case WRITE:
337 		if (argc == 3) {
338 			name = argv[2];
339 			argc--;
340 		}
341 		if (argc != 2)
342 			usage();
343 		makelabel(argv[1], name, &lab);
344 		lp = makebootarea(bootarea, &lab, f);
345 		*lp = lab;
346 		if (checklabel(lp) == 0)
347 			error = writelabel(f, bootarea, lp);
348 		break;
349 
350 	case WRITEBOOT:
351 	{
352 		struct disklabel tlab;
353 
354 		lp = readlabel(f);
355 		tlab = *lp;
356 		if (argc == 2)
357 			makelabel(argv[1], 0, &lab);
358 		lp = makebootarea(bootarea, &lab, f);
359 		*lp = tlab;
360 		if (checklabel(lp) == 0)
361 			error = writelabel(f, bootarea, lp);
362 		break;
363 	}
364 	}
365 	exit(error);
366 }
367 
368 /*
369  * Construct a prototype disklabel from /etc/disktab.
370  */
371 void
372 makelabel(const char *type, const char *name, struct disklabel *lp)
373 {
374 	struct disklabel *dp;
375 
376 	if (strcmp(type, "auto") == 0)
377 		dp = getvirginlabel();
378 	else
379 		dp = getdiskbyname(type);
380 	if (dp == NULL)
381 		errx(1, "%s: unknown disk type", type);
382 	*lp = *dp;
383 	bzero(lp->d_packname, sizeof(lp->d_packname));
384 	if (name)
385 		(void)strncpy(lp->d_packname, name, sizeof(lp->d_packname));
386 }
387 
388 int
389 writelabel(int f, void *boot, struct disklabel *lp)
390 {
391 	uint64_t *p, sum;
392 	int i;
393 
394 	if (disable_write) {
395 		Warning("write to disk label supressed - label was as follows:");
396 		display(stdout, lp);
397 		return (0);
398 	}
399 
400 	lp->d_magic = DISKMAGIC;
401 	lp->d_magic2 = DISKMAGIC;
402 	lp->d_checksum = 0;
403 	lp->d_checksum = dkcksum(lp);
404 	if (!rflag) {
405 		if (ioctl(f, DIOCWDINFO, lp) < 0) {
406 			l_perror("ioctl DIOCWDINFO");
407 			return (1);
408 		}
409 		return (0);
410 	}
411 
412 	/*
413 	 * First set the kernel disk label,
414 	 * then write a label to the raw disk.
415 	 * If the SDINFO ioctl fails because it is unimplemented,
416 	 * keep going; otherwise, the kernel consistency checks
417 	 * may prevent us from changing the current (in-core)
418 	 * label.
419 	 */
420 	if (ioctl(f, DIOCSDINFO, lp) < 0 &&
421 		errno != ENODEV && errno != ENOTTY) {
422 		l_perror("ioctl DIOCSDINFO");
423 		return (1);
424 	}
425 	(void)lseek(f, (off_t)0, SEEK_SET);
426 
427 	if (arch->arch == ARCH_ALPHA) {
428 		/*
429 		 * Generate the bootblock checksum for the SRM console.
430 		 */
431 		for (p = (uint64_t *)boot, i = 0, sum = 0; i < 63; i++)
432 			sum += p[i];
433 		p[63] = sum;
434 	}
435 	if (ioctl(f, DIOCBSDBB, &boot) == 0)
436 		return (0);
437 	if (write(f, boot, lp->d_bbsize) != (int)lp->d_bbsize) {
438 		warn("write");
439 		return (1);
440 	}
441 	return (0);
442 }
443 
444 void
445 l_perror(const char *s)
446 {
447 	switch (errno) {
448 
449 	case ESRCH:
450 		warnx("%s: no disk label on disk;", s);
451 		fprintf(stderr, "add \"-r\" to install initial label\n");
452 		break;
453 
454 	case EINVAL:
455 		warnx("%s: label magic number or checksum is wrong!", s);
456 		fprintf(stderr, "(disklabel or kernel is out of date?)\n");
457 		break;
458 
459 	case EBUSY:
460 		warnx("%s: open partition would move or shrink", s);
461 		break;
462 
463 	case EXDEV:
464 		warnx("%s: '%c' partition must start at beginning of disk",
465 		    s, 'a' + RAW_PART);
466 		break;
467 
468 	default:
469 		warn((char *)NULL);
470 		break;
471 	}
472 }
473 
474 /*
475  * Fetch disklabel for disk.
476  * Use ioctl to get label unless -r flag is given.
477  */
478 struct disklabel *
479 readlabel(int f)
480 {
481 	struct disklabel *lp;
482 
483 	if (rflag) {
484 		if (read(f, bootarea, BBSIZE) < BBSIZE)
485 			err(4, "%s", specname);
486 		for (lp = (struct disklabel *)bootarea;
487 		    lp <= (struct disklabel *)
488 			((char *)bootarea + BBSIZE - sizeof(*lp));
489 		    lp = (struct disklabel *)((char *)lp + 16))
490 			if (lp->d_magic == DISKMAGIC &&
491 			    lp->d_magic2 == DISKMAGIC)
492 				break;
493 		if (lp > (struct disklabel *)
494 		    ((char *)bootarea + BBSIZE - sizeof(*lp)) ||
495 		    lp->d_magic != DISKMAGIC || lp->d_magic2 != DISKMAGIC ||
496 		    dkcksum(lp) != 0)
497 			errx(1,
498 	    "bad pack magic number (label is damaged, or pack is unlabeled)");
499 	} else {
500 		lp = &lab;
501 		if (ioctl(f, DIOCGDINFO, lp) < 0)
502 			err(4, "ioctl DIOCGDINFO");
503 	}
504 	return (lp);
505 }
506 
507 /*
508  * Construct a bootarea (d_bbsize bytes) in the specified buffer ``boot''
509  * Returns a pointer to the disklabel portion of the bootarea.
510  */
511 struct disklabel *
512 makebootarea(void *boot, struct disklabel *dp, int f)
513 {
514 	struct disklabel *lp;
515 	char *p;
516 	int b;
517 	char *dkbasename;
518 	struct stat sb;
519 	uint64_t *bootinfo;
520 	int n;
521 	char *tmpbuf;
522 	int i, found, dps;
523 
524 	/* XXX */
525 	if (dp->d_secsize == 0) {
526 		dp->d_secsize = DEV_BSIZE;
527 		dp->d_bbsize = BBSIZE;
528 	}
529 	lp = (struct disklabel *)
530 	    ((char *)boot + (arch->label_sector * dp->d_secsize) +
531 	    arch->label_offset);
532 	bzero((char *)lp, sizeof *lp);
533 	/*
534 	 * If we are not installing a boot program but we are installing a
535 	 * label on disk then we must read the current bootarea so we don't
536 	 * clobber the existing boot.
537 	 */
538 	if (!installboot) {
539 		if (rflag) {
540 			if (read(f, boot, BBSIZE) < BBSIZE)
541 				err(4, "%s", specname);
542 			bzero((char *)lp, sizeof *lp);
543 		}
544 		return (lp);
545 	}
546 	/*
547 	 * We are installing a boot program.  Determine the name(s) and
548 	 * read them into the appropriate places in the boot area.
549 	 */
550 	if (!xxboot) {
551 		dkbasename = np;
552 		if ((p = rindex(dkname, '/')) == NULL)
553 			p = dkname;
554 		else
555 			p++;
556 		while (*p && !isdigit(*p))
557 			*np++ = *p++;
558 		*np++ = '\0';
559 
560 		if (!xxboot) {
561 			(void)sprintf(boot0, "%s/boot", _PATH_BOOTDIR);
562 			xxboot = boot0;
563 		}
564 	}
565 
566 	b = open(xxboot, O_RDONLY);
567 	if (b < 0)
568 		err(4, "%s", xxboot);
569 	if (fstat(b, &sb) != 0)
570 		err(4, "%s", xxboot);
571 	if (arch->arch == ARCH_I386) {
572 		if (sb.st_size > BBSIZE)
573 			errx(4, "%s too large", xxboot);
574 		/*
575 		 * XXX Botch alert.
576 		 * The i386/PC98 has the so-called fdisk table embedded into the
577 		 * primary bootstrap.  We take care to not clobber it, but
578 		 * only if it does already contain some data.  (Otherwise,
579 		 * the xxboot provides a template.)
580 		 */
581 		if ((tmpbuf = (char *)malloc((int)dp->d_secsize)) == 0)
582 			err(4, "%s", xxboot);
583 		memcpy((void *)tmpbuf, (void *)boot, (int)dp->d_secsize);
584 
585 		if (read(b, boot, BBSIZE) < 0)
586 			err(4, "%s", xxboot);
587 
588 		/* XXX: rely on some very precise overlaps in definitions */
589 		dps = IS_PC98 ? sizeof(struct pc98_partition) :
590 		    sizeof(struct dos_partition);
591 		for (i = DOSPARTOFF, found = 0;
592 		     !found && i < (int)(DOSPARTOFF + NDOSPART * dps);
593 		     i++)
594 			found = tmpbuf[i] != 0;
595 		if (found)
596 			memcpy((void *)&((char *)boot)[DOSPARTOFF],
597 			       (void *)&tmpbuf[DOSPARTOFF],
598 			       NDOSPART * dps);
599 		free(tmpbuf);
600 	}
601 
602 	if (arch->arch == ARCH_ALPHA) {
603 		if (sb.st_size > BBSIZE - dp->d_secsize)
604 			errx(4, "%s too large", xxboot);
605 		/*
606 		 * On the alpha, the primary bootstrap starts at the
607 		 * second sector of the boot area.  The first sector
608 		 * contains the label and must be edited to contain the
609 		 * size and location of the primary bootstrap.
610 		 */
611 		n = read(b, (char *)boot + dp->d_secsize,
612 		    BBSIZE - dp->d_secsize);
613 		if (n < 0)
614 			err(4, "%s", xxboot);
615 		bootinfo = (uint64_t *)((char *)boot + 480);
616 		bootinfo[0] = (n + dp->d_secsize - 1) / dp->d_secsize;
617 		bootinfo[1] = 1;	/* start at sector 1 */
618 		bootinfo[2] = 0;	/* flags (must be zero) */
619 	}
620 
621 	(void)close(b);
622 	/*
623 	 * Make sure no part of the bootstrap is written in the area
624 	 * reserved for the label.
625 	 */
626 	for (p = (char *)lp; p < (char *)lp + sizeof(struct disklabel); p++)
627 		if (*p)
628 			errx(2, "bootstrap doesn't leave room for disk label");
629 	return (lp);
630 }
631 
632 void
633 display(FILE *f, const struct disklabel *lp)
634 {
635 	int i, j;
636 	const struct partition *pp;
637 
638 	fprintf(f, "# %s:\n", specname);
639 	if (lp->d_type < DKMAXTYPES)
640 		fprintf(f, "type: %s\n", dktypenames[lp->d_type]);
641 	else
642 		fprintf(f, "type: %u\n", lp->d_type);
643 	fprintf(f, "disk: %.*s\n", (int)sizeof(lp->d_typename),
644 		lp->d_typename);
645 	fprintf(f, "label: %.*s\n", (int)sizeof(lp->d_packname),
646 		lp->d_packname);
647 	fprintf(f, "flags:");
648 	if (lp->d_flags & D_REMOVABLE)
649 		fprintf(f, " removeable");
650 	if (lp->d_flags & D_ECC)
651 		fprintf(f, " ecc");
652 	if (lp->d_flags & D_BADSECT)
653 		fprintf(f, " badsect");
654 	fprintf(f, "\n");
655 	fprintf(f, "bytes/sector: %lu\n", (u_long)lp->d_secsize);
656 	fprintf(f, "sectors/track: %lu\n", (u_long)lp->d_nsectors);
657 	fprintf(f, "tracks/cylinder: %lu\n", (u_long)lp->d_ntracks);
658 	fprintf(f, "sectors/cylinder: %lu\n", (u_long)lp->d_secpercyl);
659 	fprintf(f, "cylinders: %lu\n", (u_long)lp->d_ncylinders);
660 	fprintf(f, "sectors/unit: %lu\n", (u_long)lp->d_secperunit);
661 	fprintf(f, "rpm: %u\n", lp->d_rpm);
662 	fprintf(f, "interleave: %u\n", lp->d_interleave);
663 	fprintf(f, "trackskew: %u\n", lp->d_trackskew);
664 	fprintf(f, "cylinderskew: %u\n", lp->d_cylskew);
665 	fprintf(f, "headswitch: %lu\t\t# milliseconds\n",
666 	    (u_long)lp->d_headswitch);
667 	fprintf(f, "track-to-track seek: %ld\t# milliseconds\n",
668 	    (u_long)lp->d_trkseek);
669 	fprintf(f, "drivedata: ");
670 	for (i = NDDATA - 1; i >= 0; i--)
671 		if (lp->d_drivedata[i])
672 			break;
673 	if (i < 0)
674 		i = 0;
675 	for (j = 0; j <= i; j++)
676 		fprintf(f, "%lu ", (u_long)lp->d_drivedata[j]);
677 	fprintf(f, "\n\n%u partitions:\n", lp->d_npartitions);
678 	fprintf(f,
679 	    "#        size   offset    fstype   [fsize bsize bps/cpg]\n");
680 	pp = lp->d_partitions;
681 	for (i = 0; i < lp->d_npartitions; i++, pp++) {
682 		if (pp->p_size) {
683 			fprintf(f, "  %c: %8lu %8lu  ", 'a' + i,
684 			   (u_long)pp->p_size, (u_long)pp->p_offset);
685 			if (pp->p_fstype < FSMAXTYPES)
686 				fprintf(f, "%8.8s", fstypenames[pp->p_fstype]);
687 			else
688 				fprintf(f, "%8d", pp->p_fstype);
689 			switch (pp->p_fstype) {
690 
691 			case FS_UNUSED:				/* XXX */
692 				fprintf(f, "    %5lu %5lu %5.5s ",
693 				    (u_long)pp->p_fsize,
694 				    (u_long)(pp->p_fsize * pp->p_frag), "");
695 				break;
696 
697 			case FS_BSDFFS:
698 				fprintf(f, "    %5lu %5lu %5u ",
699 				    (u_long)pp->p_fsize,
700 				    (u_long)(pp->p_fsize * pp->p_frag),
701 				    pp->p_cpg);
702 				break;
703 
704 			case FS_BSDLFS:
705 				fprintf(f, "    %5lu %5lu %5d",
706 				    (u_long)pp->p_fsize,
707 				    (u_long)(pp->p_fsize * pp->p_frag),
708 				    pp->p_cpg);
709 				break;
710 
711 			default:
712 				fprintf(f, "%20.20s", "");
713 				break;
714 			}
715 			fprintf(f, "\t# (Cyl. %4lu",
716 			    (u_long)(pp->p_offset / lp->d_secpercyl));
717 			if (pp->p_offset % lp->d_secpercyl)
718 			    putc('*', f);
719 			else
720 			    putc(' ', f);
721 			fprintf(f, "- %lu",
722 			    (u_long)((pp->p_offset + pp->p_size +
723 			    lp->d_secpercyl - 1) /
724 			    lp->d_secpercyl - 1));
725 			if (pp->p_size % lp->d_secpercyl)
726 			    putc('*', f);
727 			fprintf(f, ")\n");
728 		}
729 	}
730 	fflush(f);
731 }
732 
733 int
734 edit(struct disklabel *lp, int f)
735 {
736 	int c, fd;
737 	struct disklabel label;
738 	FILE *fp;
739 
740 	if ((fd = mkstemp(tmpfil)) == -1 ||
741 	    (fp = fdopen(fd, "w")) == NULL) {
742 		warnx("can't create %s", tmpfil);
743 		return (1);
744 	}
745 	display(fp, lp);
746 	fclose(fp);
747 	for (;;) {
748 		if (!editit())
749 			break;
750 		fp = fopen(tmpfil, "r");
751 		if (fp == NULL) {
752 			warnx("can't reopen %s for reading", tmpfil);
753 			break;
754 		}
755 		bzero((char *)&label, sizeof(label));
756 		if (getasciilabel(fp, &label)) {
757 			*lp = label;
758 			if (writelabel(f, bootarea, lp) == 0) {
759 				fclose(fp);
760 				(void) unlink(tmpfil);
761 				return (0);
762 			}
763 		}
764 		fclose(fp);
765 		printf("re-edit the label? [y]: "); fflush(stdout);
766 		c = getchar();
767 		if (c != EOF && c != (int)'\n')
768 			while (getchar() != (int)'\n')
769 				;
770 		if  (c == (int)'n')
771 			break;
772 	}
773 	(void) unlink(tmpfil);
774 	return (1);
775 }
776 
777 int
778 editit(void)
779 {
780 	int pid, xpid;
781 	int locstat, omask;
782 	const char *ed;
783 
784 	omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
785 	while ((pid = fork()) < 0) {
786 		if (errno == EPROCLIM) {
787 			warnx("you have too many processes");
788 			return(0);
789 		}
790 		if (errno != EAGAIN) {
791 			warn("fork");
792 			return(0);
793 		}
794 		sleep(1);
795 	}
796 	if (pid == 0) {
797 		sigsetmask(omask);
798 		setgid(getgid());
799 		setuid(getuid());
800 		if ((ed = getenv("EDITOR")) == (char *)0)
801 			ed = DEFEDITOR;
802 		execlp(ed, ed, tmpfil, (char *)0);
803 		err(1, "%s", ed);
804 	}
805 	while ((xpid = wait(&locstat)) >= 0)
806 		if (xpid == pid)
807 			break;
808 	sigsetmask(omask);
809 	return(!locstat);
810 }
811 
812 char *
813 skip(char *cp)
814 {
815 
816 	while (*cp != '\0' && isspace(*cp))
817 		cp++;
818 	if (*cp == '\0' || *cp == '#')
819 		return (NULL);
820 	return (cp);
821 }
822 
823 char *
824 word(char *cp)
825 {
826 	char c;
827 
828 	while (*cp != '\0' && !isspace(*cp) && *cp != '#')
829 		cp++;
830 	if ((c = *cp) != '\0') {
831 		*cp++ = '\0';
832 		if (c != '#')
833 			return (skip(cp));
834 	}
835 	return (NULL);
836 }
837 
838 /*
839  * Read an ascii label in from fd f,
840  * in the same format as that put out by display(),
841  * and fill in lp.
842  */
843 int
844 getasciilabel(FILE *f, struct disklabel *lp)
845 {
846 	char *cp;
847 	const char **cpp;
848 	u_int part;
849 	char *tp, line[BUFSIZ];
850 	u_long v;
851 	int lineno = 0, errors = 0;
852 	int i;
853 
854 	bzero(&part_set, sizeof(part_set));
855 	bzero(&part_size_type, sizeof(part_size_type));
856 	bzero(&part_offset_type, sizeof(part_offset_type));
857 	lp->d_bbsize = BBSIZE;				/* XXX */
858 	lp->d_sbsize = 0;				/* XXX */
859 	while (fgets(line, sizeof(line) - 1, f)) {
860 		lineno++;
861 		if ((cp = index(line,'\n')) != 0)
862 			*cp = '\0';
863 		cp = skip(line);
864 		if (cp == NULL)
865 			continue;
866 		tp = index(cp, ':');
867 		if (tp == NULL) {
868 			fprintf(stderr, "line %d: syntax error\n", lineno);
869 			errors++;
870 			continue;
871 		}
872 		*tp++ = '\0', tp = skip(tp);
873 		if (streq(cp, "type")) {
874 			if (tp == NULL)
875 				tp = unknown;
876 			cpp = dktypenames;
877 			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
878 				if (*cpp && streq(*cpp, tp)) {
879 					lp->d_type = cpp - dktypenames;
880 					break;
881 				}
882 			if (cpp < &dktypenames[DKMAXTYPES])
883 				continue;
884 			v = strtoul(tp, NULL, 10);
885 			if (v >= DKMAXTYPES)
886 				fprintf(stderr, "line %d:%s %lu\n", lineno,
887 				    "Warning, unknown disk type", v);
888 			lp->d_type = v;
889 			continue;
890 		}
891 		if (streq(cp, "flags")) {
892 			for (v = 0; (cp = tp) && *cp != '\0';) {
893 				tp = word(cp);
894 				if (streq(cp, "removeable"))
895 					v |= D_REMOVABLE;
896 				else if (streq(cp, "ecc"))
897 					v |= D_ECC;
898 				else if (streq(cp, "badsect"))
899 					v |= D_BADSECT;
900 				else {
901 					fprintf(stderr,
902 					    "line %d: %s: bad flag\n",
903 					    lineno, cp);
904 					errors++;
905 				}
906 			}
907 			lp->d_flags = v;
908 			continue;
909 		}
910 		if (streq(cp, "drivedata")) {
911 			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
912 				lp->d_drivedata[i++] = strtoul(cp, NULL, 10);
913 				tp = word(cp);
914 			}
915 			continue;
916 		}
917 		if (sscanf(cp, "%lu partitions", &v) == 1) {
918 			if (v == 0 || v > MAXPARTITIONS) {
919 				fprintf(stderr,
920 				    "line %d: bad # of partitions\n", lineno);
921 				lp->d_npartitions = MAXPARTITIONS;
922 				errors++;
923 			} else
924 				lp->d_npartitions = v;
925 			continue;
926 		}
927 		if (tp == NULL)
928 			tp = blank;
929 		if (streq(cp, "disk")) {
930 			strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
931 			continue;
932 		}
933 		if (streq(cp, "label")) {
934 			strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
935 			continue;
936 		}
937 		if (streq(cp, "bytes/sector")) {
938 			v = strtoul(tp, NULL, 10);
939 			if (v == 0 || (v % DEV_BSIZE) != 0) {
940 				fprintf(stderr,
941 				    "line %d: %s: bad sector size\n",
942 				    lineno, tp);
943 				errors++;
944 			} else
945 				lp->d_secsize = v;
946 			continue;
947 		}
948 		if (streq(cp, "sectors/track")) {
949 			v = strtoul(tp, NULL, 10);
950 #if (ULONG_MAX != 0xffffffffUL)
951 			if (v == 0 || v > 0xffffffff) {
952 #else
953 			if (v == 0) {
954 #endif
955 				fprintf(stderr, "line %d: %s: bad %s\n",
956 				    lineno, tp, cp);
957 				errors++;
958 			} else
959 				lp->d_nsectors = v;
960 			continue;
961 		}
962 		if (streq(cp, "sectors/cylinder")) {
963 			v = strtoul(tp, NULL, 10);
964 			if (v == 0) {
965 				fprintf(stderr, "line %d: %s: bad %s\n",
966 				    lineno, tp, cp);
967 				errors++;
968 			} else
969 				lp->d_secpercyl = v;
970 			continue;
971 		}
972 		if (streq(cp, "tracks/cylinder")) {
973 			v = strtoul(tp, NULL, 10);
974 			if (v == 0) {
975 				fprintf(stderr, "line %d: %s: bad %s\n",
976 				    lineno, tp, cp);
977 				errors++;
978 			} else
979 				lp->d_ntracks = v;
980 			continue;
981 		}
982 		if (streq(cp, "cylinders")) {
983 			v = strtoul(tp, NULL, 10);
984 			if (v == 0) {
985 				fprintf(stderr, "line %d: %s: bad %s\n",
986 				    lineno, tp, cp);
987 				errors++;
988 			} else
989 				lp->d_ncylinders = v;
990 			continue;
991 		}
992 		if (streq(cp, "sectors/unit")) {
993 			v = strtoul(tp, NULL, 10);
994 			if (v == 0) {
995 				fprintf(stderr, "line %d: %s: bad %s\n",
996 				    lineno, tp, cp);
997 				errors++;
998 			} else
999 				lp->d_secperunit = v;
1000 			continue;
1001 		}
1002 		if (streq(cp, "rpm")) {
1003 			v = strtoul(tp, NULL, 10);
1004 			if (v == 0 || v > USHRT_MAX) {
1005 				fprintf(stderr, "line %d: %s: bad %s\n",
1006 				    lineno, tp, cp);
1007 				errors++;
1008 			} else
1009 				lp->d_rpm = v;
1010 			continue;
1011 		}
1012 		if (streq(cp, "interleave")) {
1013 			v = strtoul(tp, NULL, 10);
1014 			if (v == 0 || v > USHRT_MAX) {
1015 				fprintf(stderr, "line %d: %s: bad %s\n",
1016 				    lineno, tp, cp);
1017 				errors++;
1018 			} else
1019 				lp->d_interleave = v;
1020 			continue;
1021 		}
1022 		if (streq(cp, "trackskew")) {
1023 			v = strtoul(tp, NULL, 10);
1024 			if (v > USHRT_MAX) {
1025 				fprintf(stderr, "line %d: %s: bad %s\n",
1026 				    lineno, tp, cp);
1027 				errors++;
1028 			} else
1029 				lp->d_trackskew = v;
1030 			continue;
1031 		}
1032 		if (streq(cp, "cylinderskew")) {
1033 			v = strtoul(tp, NULL, 10);
1034 			if (v > USHRT_MAX) {
1035 				fprintf(stderr, "line %d: %s: bad %s\n",
1036 				    lineno, tp, cp);
1037 				errors++;
1038 			} else
1039 				lp->d_cylskew = v;
1040 			continue;
1041 		}
1042 		if (streq(cp, "headswitch")) {
1043 			v = strtoul(tp, NULL, 10);
1044 			lp->d_headswitch = v;
1045 			continue;
1046 		}
1047 		if (streq(cp, "track-to-track seek")) {
1048 			v = strtoul(tp, NULL, 10);
1049 			lp->d_trkseek = v;
1050 			continue;
1051 		}
1052 		/* the ':' was removed above */
1053 		if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') {
1054 			fprintf(stderr,
1055 			    "line %d: %s: Unknown disklabel field\n", lineno,
1056 			    cp);
1057 			errors++;
1058 			continue;
1059 		}
1060 
1061 		/* Process a partition specification line. */
1062 		part = *cp - 'a';
1063 		if (part >= lp->d_npartitions) {
1064 			fprintf(stderr,
1065 			    "line %d: partition name out of range a-%c: %s\n",
1066 			    lineno, 'a' + lp->d_npartitions - 1, cp);
1067 			errors++;
1068 			continue;
1069 		}
1070 		part_set[part] = 1;
1071 
1072 		if (getasciipartspec(tp, lp, part, lineno) != 0) {
1073 			errors++;
1074 			break;
1075 		}
1076 	}
1077 	errors += checklabel(lp);
1078 	return (errors == 0);
1079 }
1080 
1081 #define NXTNUM(n) do { \
1082 	if (tp == NULL) { \
1083 		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1084 		return (1); \
1085 	} else { \
1086 		cp = tp, tp = word(cp); \
1087 		(n) = strtoul(cp, NULL, 10); \
1088 	} \
1089 } while (0)
1090 
1091 /* retain 1 character following number */
1092 #define NXTWORD(w,n) do { \
1093 	if (tp == NULL) { \
1094 		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1095 		return (1); \
1096 	} else { \
1097 	        char *tmp; \
1098 		cp = tp, tp = word(cp); \
1099 	        (n) = strtoul(cp, &tmp, 10); \
1100 		if (tmp) (w) = *tmp; \
1101 	} \
1102 } while (0)
1103 
1104 /*
1105  * Read a partition line into partition `part' in the specified disklabel.
1106  * Return 0 on success, 1 on failure.
1107  */
1108 int
1109 getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno)
1110 {
1111 	struct partition *pp;
1112 	char *cp;
1113 	const char **cpp;
1114 	u_long v;
1115 
1116 	pp = &lp->d_partitions[part];
1117 	cp = NULL;
1118 
1119 	v = 0;
1120 	NXTWORD(part_size_type[part],v);
1121 	if (v == 0 && part_size_type[part] != '*') {
1122 		fprintf(stderr,
1123 		    "line %d: %s: bad partition size\n", lineno, cp);
1124 		return (1);
1125 	}
1126 	pp->p_size = v;
1127 
1128 	v = 0;
1129 	NXTWORD(part_offset_type[part],v);
1130 	if (v == 0 && part_offset_type[part] != '*' &&
1131 	    part_offset_type[part] != '\0') {
1132 		fprintf(stderr,
1133 		    "line %d: %s: bad partition offset\n", lineno, cp);
1134 		return (1);
1135 	}
1136 	pp->p_offset = v;
1137 	cp = tp, tp = word(cp);
1138 	for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++)
1139 		if (*cpp && streq(*cpp, cp))
1140 			break;
1141 	if (*cpp != NULL) {
1142 		pp->p_fstype = cpp - fstypenames;
1143 	} else {
1144 		if (isdigit(*cp))
1145 			v = strtoul(cp, NULL, 10);
1146 		else
1147 			v = FSMAXTYPES;
1148 		if (v >= FSMAXTYPES) {
1149 			fprintf(stderr,
1150 			    "line %d: Warning, unknown file system type %s\n",
1151 			    lineno, cp);
1152 			v = FS_UNUSED;
1153 		}
1154 		pp->p_fstype = v;
1155 	}
1156 
1157 	switch (pp->p_fstype) {
1158 	case FS_UNUSED:
1159 		/*
1160 		 * allow us to accept defaults for
1161 		 * fsize/frag/cpg
1162 		 */
1163 		if (tp) {
1164 			NXTNUM(pp->p_fsize);
1165 			if (pp->p_fsize == 0)
1166 				break;
1167 			NXTNUM(v);
1168 			pp->p_frag = v / pp->p_fsize;
1169 		}
1170 		/* else default to 0's */
1171 		break;
1172 
1173 	/* These happen to be the same */
1174 	case FS_BSDFFS:
1175 	case FS_BSDLFS:
1176 		if (tp) {
1177 			NXTNUM(pp->p_fsize);
1178 			if (pp->p_fsize == 0)
1179 				break;
1180 			NXTNUM(v);
1181 			pp->p_frag = v / pp->p_fsize;
1182 			NXTNUM(pp->p_cpg);
1183 		} else {
1184 			/*
1185 			 * FIX! poor attempt at adaptive
1186 			 */
1187 			/* 1 GB */
1188 			if (pp->p_size < 1024*1024*1024 / lp->d_secsize) {
1189 				/*
1190 				 * FIX! These are too low, but are traditional
1191 				 */
1192 				pp->p_fsize = DEFAULT_NEWFS_FRAG;
1193 				pp->p_frag = DEFAULT_NEWFS_BLOCK /
1194 				    DEFAULT_NEWFS_FRAG;
1195 				pp->p_cpg = DEFAULT_NEWFS_CPG;
1196 			} else {
1197 				pp->p_fsize = BIG_NEWFS_FRAG;
1198 				pp->p_frag = BIG_NEWFS_BLOCK /
1199 				    BIG_NEWFS_FRAG;
1200 				pp->p_cpg = BIG_NEWFS_CPG;
1201 			}
1202 		}
1203 	default:
1204 		break;
1205 	}
1206 	return (0);
1207 }
1208 
1209 /*
1210  * Check disklabel for errors and fill in
1211  * derived fields according to supplied values.
1212  */
1213 int
1214 checklabel(struct disklabel *lp)
1215 {
1216 	struct partition *pp;
1217 	int i, errors = 0;
1218 	char part;
1219 	u_long total_size, total_percent, current_offset;
1220 	int seen_default_offset;
1221 	int hog_part;
1222 	int j;
1223 	struct partition *pp2;
1224 
1225 	if (lp->d_secsize == 0) {
1226 		fprintf(stderr, "sector size 0\n");
1227 		return (1);
1228 	}
1229 	if (lp->d_nsectors == 0) {
1230 		fprintf(stderr, "sectors/track 0\n");
1231 		return (1);
1232 	}
1233 	if (lp->d_ntracks == 0) {
1234 		fprintf(stderr, "tracks/cylinder 0\n");
1235 		return (1);
1236 	}
1237 	if  (lp->d_ncylinders == 0) {
1238 		fprintf(stderr, "cylinders/unit 0\n");
1239 		errors++;
1240 	}
1241 	if (lp->d_rpm == 0)
1242 		Warning("revolutions/minute 0");
1243 	if (lp->d_secpercyl == 0)
1244 		lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1245 	if (lp->d_secperunit == 0)
1246 		lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1247 	if (lp->d_bbsize == 0) {
1248 		fprintf(stderr, "boot block size 0\n");
1249 		errors++;
1250 	} else if (lp->d_bbsize % lp->d_secsize)
1251 		Warning("boot block size %% sector-size != 0");
1252 	if (lp->d_npartitions > MAXPARTITIONS)
1253 		Warning("number of partitions (%lu) > MAXPARTITIONS (%d)",
1254 		    (u_long)lp->d_npartitions, MAXPARTITIONS);
1255 
1256 	/* first allocate space to the partitions, then offsets */
1257 	total_size = 0; /* in sectors */
1258 	total_percent = 0; /* in percent */
1259 	hog_part = -1;
1260 	/* find all fixed partitions */
1261 	for (i = 0; i < lp->d_npartitions; i++) {
1262 		pp = &lp->d_partitions[i];
1263 		if (part_set[i]) {
1264 			if (part_size_type[i] == '*') {
1265 				if (i == RAW_PART) {
1266 					pp->p_size = lp->d_secperunit;
1267 				} else {
1268 					if (hog_part != -1)
1269 						Warning("Too many '*' partitions (%c and %c)",
1270 						    hog_part + 'a',i + 'a');
1271 					else
1272 						hog_part = i;
1273 				}
1274 			} else {
1275 				off_t size;
1276 
1277 				size = pp->p_size;
1278 				switch (part_size_type[i]) {
1279 				case '%':
1280 					total_percent += size;
1281 					break;
1282 				case 'k':
1283 				case 'K':
1284 					size *= 1024ULL;
1285 					break;
1286 				case 'm':
1287 				case 'M':
1288 					size *= 1024ULL * 1024ULL;
1289 					break;
1290 				case 'g':
1291 				case 'G':
1292 					size *= 1024ULL * 1024ULL * 1024ULL;
1293 					break;
1294 				case '\0':
1295 					break;
1296 				default:
1297 					Warning("unknown size specifier '%c' (K/M/G are valid)",part_size_type[i]);
1298 					break;
1299 				}
1300 				/* don't count %'s yet */
1301 				if (part_size_type[i] != '%') {
1302 					/*
1303 					 * for all not in sectors, convert to
1304 					 * sectors
1305 					 */
1306 					if (part_size_type[i] != '\0') {
1307 						if (size % lp->d_secsize != 0)
1308 							Warning("partition %c not an integer number of sectors",
1309 							    i + 'a');
1310 						size /= lp->d_secsize;
1311 						pp->p_size = size;
1312 					}
1313 					/* else already in sectors */
1314 					if (i != RAW_PART)
1315 						total_size += size;
1316 				}
1317 			}
1318 		}
1319 	}
1320 	/* handle % partitions - note %'s don't need to add up to 100! */
1321 	if (total_percent != 0) {
1322 		long free_space = lp->d_secperunit - total_size;
1323 		if (total_percent > 100) {
1324 			fprintf(stderr,"total percentage %lu is greater than 100\n",
1325 			    total_percent);
1326 			errors++;
1327 		}
1328 
1329 		if (free_space > 0) {
1330 			for (i = 0; i < lp->d_npartitions; i++) {
1331 				pp = &lp->d_partitions[i];
1332 				if (part_set[i] && part_size_type[i] == '%') {
1333 					/* careful of overflows! and integer roundoff */
1334 					pp->p_size = ((double)pp->p_size/100) * free_space;
1335 					total_size += pp->p_size;
1336 
1337 					/* FIX we can lose a sector or so due to roundoff per
1338 					   partition.  A more complex algorithm could avoid that */
1339 				}
1340 			}
1341 		} else {
1342 			fprintf(stderr,
1343 			    "%ld sectors available to give to '*' and '%%' partitions\n",
1344 			    free_space);
1345 			errors++;
1346 			/* fix?  set all % partitions to size 0? */
1347 		}
1348 	}
1349 	/* give anything remaining to the hog partition */
1350 	if (hog_part != -1) {
1351 		lp->d_partitions[hog_part].p_size = lp->d_secperunit - total_size;
1352 		total_size = lp->d_secperunit;
1353 	}
1354 
1355 	/* Now set the offsets for each partition */
1356 	current_offset = 0; /* in sectors */
1357 	seen_default_offset = 0;
1358 	for (i = 0; i < lp->d_npartitions; i++) {
1359 		part = 'a' + i;
1360 		pp = &lp->d_partitions[i];
1361 		if (part_set[i]) {
1362 			if (part_offset_type[i] == '*') {
1363 				if (i == RAW_PART) {
1364 					pp->p_offset = 0;
1365 				} else {
1366 					pp->p_offset = current_offset;
1367 					seen_default_offset = 1;
1368 				}
1369 			} else {
1370 				/* allow them to be out of order for old-style tables */
1371 				if (pp->p_offset < current_offset &&
1372 				    seen_default_offset && i != RAW_PART &&
1373 				    pp->p_fstype != FS_VINUM) {
1374 					fprintf(stderr,
1375 "Offset %ld for partition %c overlaps previous partition which ends at %lu\n",
1376 					    (long)pp->p_offset,i+'a',current_offset);
1377 					fprintf(stderr,
1378 "Labels with any *'s for offset must be in ascending order by sector\n");
1379 					errors++;
1380 				} else if (pp->p_offset != current_offset &&
1381 				    i != RAW_PART && seen_default_offset) {
1382 					/*
1383 					 * this may give unneeded warnings if
1384 					 * partitions are out-of-order
1385 					 */
1386 					Warning(
1387 "Offset %ld for partition %c doesn't match expected value %ld",
1388 					    (long)pp->p_offset, i + 'a', current_offset);
1389 				}
1390 			}
1391 			if (i != RAW_PART)
1392 				current_offset = pp->p_offset + pp->p_size;
1393 		}
1394 	}
1395 
1396 	for (i = 0; i < lp->d_npartitions; i++) {
1397 		part = 'a' + i;
1398 		pp = &lp->d_partitions[i];
1399 		if (pp->p_size == 0 && pp->p_offset != 0)
1400 			Warning("partition %c: size 0, but offset %lu",
1401 			    part, (u_long)pp->p_offset);
1402 #ifdef notdef
1403 		if (pp->p_size % lp->d_secpercyl)
1404 			Warning("partition %c: size %% cylinder-size != 0",
1405 			    part);
1406 		if (pp->p_offset % lp->d_secpercyl)
1407 			Warning("partition %c: offset %% cylinder-size != 0",
1408 			    part);
1409 #endif
1410 		if (pp->p_offset > lp->d_secperunit) {
1411 			fprintf(stderr,
1412 			    "partition %c: offset past end of unit\n", part);
1413 			errors++;
1414 		}
1415 		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1416 			fprintf(stderr,
1417 			"partition %c: partition extends past end of unit\n",
1418 			    part);
1419 			errors++;
1420 		}
1421 		if (i == RAW_PART)
1422 		{
1423 			if (pp->p_fstype != FS_UNUSED)
1424 				Warning("partition %c is not marked as unused!",part);
1425 			if (pp->p_offset != 0)
1426 				Warning("partition %c doesn't start at 0!",part);
1427 			if (pp->p_size != lp->d_secperunit)
1428 				Warning("partition %c doesn't cover the whole unit!",part);
1429 
1430 			if ((pp->p_fstype != FS_UNUSED) || (pp->p_offset != 0) ||
1431 			    (pp->p_size != lp->d_secperunit)) {
1432 				Warning("An incorrect partition %c may cause problems for "
1433 				    "standard system utilities",part);
1434 			}
1435 		}
1436 
1437 		/* check for overlaps */
1438 		/* this will check for all possible overlaps once and only once */
1439 		for (j = 0; j < i; j++) {
1440 			pp2 = &lp->d_partitions[j];
1441 			if (j != RAW_PART && i != RAW_PART &&
1442 			    pp->p_fstype != FS_VINUM &&
1443 			    pp2->p_fstype != FS_VINUM &&
1444 			    part_set[i] && part_set[j]) {
1445 				if (pp2->p_offset < pp->p_offset + pp->p_size &&
1446 				    (pp2->p_offset + pp2->p_size > pp->p_offset ||
1447 					pp2->p_offset >= pp->p_offset)) {
1448 					fprintf(stderr,"partitions %c and %c overlap!\n",
1449 					    j + 'a', i + 'a');
1450 					errors++;
1451 				}
1452 			}
1453 		}
1454 	}
1455 	for (; i < MAXPARTITIONS; i++) {
1456 		part = 'a' + i;
1457 		pp = &lp->d_partitions[i];
1458 		if (pp->p_size || pp->p_offset)
1459 			Warning("unused partition %c: size %d offset %lu",
1460 			    'a' + i, pp->p_size, (u_long)pp->p_offset);
1461 	}
1462 	return (errors);
1463 }
1464 
1465 /*
1466  * When operating on a "virgin" disk, try getting an initial label
1467  * from the associated device driver.  This might work for all device
1468  * drivers that are able to fetch some initial device parameters
1469  * without even having access to a (BSD) disklabel, like SCSI disks,
1470  * most IDE drives, or vn devices.
1471  *
1472  * The device name must be given in its "canonical" form.
1473  */
1474 struct disklabel *
1475 getvirginlabel(void)
1476 {
1477 	static struct disklabel loclab;
1478 	struct partition *dp;
1479 	char lnamebuf[BBSIZE];
1480 	int f;
1481 	u_int secsize, u;
1482 	off_t mediasize;
1483 
1484 	if (dkname[0] == '/') {
1485 		warnx("\"auto\" requires the usage of a canonical disk name");
1486 		return (NULL);
1487 	}
1488 	(void)snprintf(lnamebuf, BBSIZE, "%s%s", _PATH_DEV, dkname);
1489 	if ((f = open(lnamebuf, O_RDONLY)) == -1) {
1490 		warn("cannot open %s", lnamebuf);
1491 		return (NULL);
1492 	}
1493 
1494 	/* New world order */
1495 	if ((ioctl(f, DIOCGMEDIASIZE, &mediasize) != 0) ||
1496 	    (ioctl(f, DIOCGSECTORSIZE, &secsize) != 0)) {
1497 		close (f);
1498 		return (NULL);
1499 	}
1500 	memset(&loclab, 0, sizeof loclab);
1501 	loclab.d_magic = DISKMAGIC;
1502 	loclab.d_magic2 = DISKMAGIC;
1503 	loclab.d_secsize = secsize;
1504 	loclab.d_secperunit = mediasize / secsize;
1505 
1506 	/*
1507 	 * Nobody in these enligthened days uses the CHS geometry for
1508 	 * anything, but nontheless try to get it right.  If we fail
1509 	 * to get any good ideas from the device, construct something
1510 	 * which is IBM-PC friendly.
1511 	 */
1512 	if (ioctl(f, DIOCGFWSECTORS, &u) == 0)
1513 		loclab.d_nsectors = u;
1514 	else
1515 		loclab.d_nsectors = 63;
1516 	if (ioctl(f, DIOCGFWHEADS, &u) == 0)
1517 		loclab.d_ntracks = u;
1518 	else if (loclab.d_secperunit <= 63*1*1024)
1519 		loclab.d_ntracks = 1;
1520 	else if (loclab.d_secperunit <= 63*16*1024)
1521 		loclab.d_ntracks = 16;
1522 	else
1523 		loclab.d_ntracks = 255;
1524 	loclab.d_secpercyl = loclab.d_ntracks * loclab.d_nsectors;
1525 	loclab.d_ncylinders = loclab.d_secperunit / loclab.d_secpercyl;
1526 	loclab.d_npartitions = MAXPARTITIONS;
1527 
1528 	/* Various (unneeded) compat stuff */
1529 	loclab.d_rpm = 3600;
1530 	loclab.d_bbsize = BBSIZE;
1531 	loclab.d_interleave = 1;;
1532 	strncpy(loclab.d_typename, "amnesiac",
1533 	    sizeof(loclab.d_typename));
1534 
1535 	dp = &loclab.d_partitions[RAW_PART];
1536 	dp->p_size = loclab.d_secperunit;
1537 	loclab.d_checksum = dkcksum(&loclab);
1538 	close (f);
1539 	return (&loclab);
1540 }
1541 
1542 
1543 /*VARARGS1*/
1544 void
1545 Warning(const char *fmt, ...)
1546 {
1547 	va_list ap;
1548 
1549 	fprintf(stderr, "Warning, ");
1550 	va_start(ap, fmt);
1551 	vfprintf(stderr, fmt, ap);
1552 	fprintf(stderr, "\n");
1553 	va_end(ap);
1554 }
1555 
1556 void
1557 usage(void)
1558 {
1559 
1560 	fprintf(stderr,
1561 	"%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",
1562 	"usage: disklabel [-r] disk",
1563 	"\t\t(to read label)",
1564 	"	disklabel -w [-nr] [-m machine] disk type [packid]",
1565 	"\t\t(to write label with existing boot program)",
1566 	"	disklabel -e [-nr] [-m machine] disk",
1567 	"\t\t(to edit label)",
1568 	"	disklabel -R [-nr] [-m machine] disk protofile",
1569 	"\t\t(to restore label with existing boot program)",
1570 	"	disklabel -B [-b boot] [-m machine] disk",
1571 	"\t\t(to install boot program with existing on-disk label)",
1572 	"	disklabel -w -B [-n] [-b boot] [-m machine] disk type [packid]",
1573 	"\t\t(to write label and install boot program)",
1574 	"	disklabel -R -B [-n] [-b boot] [-m machine] disk protofile",
1575 		"\t\t(to restore label and install boot program)"
1576 	);
1577 	exit(1);
1578 }
1579