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