xref: /freebsd/sbin/bsdlabel/bsdlabel.c (revision 7aa383846770374466b1dcb2cefd71bde9acf463)
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;
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 			v = strtoul(tp, NULL, 10);
798 			if (v >= DKMAXTYPES)
799 				fprintf(stderr, "line %d:%s %lu\n", lineno,
800 				    "Warning, unknown disk type", v);
801 			lp->d_type = v;
802 			continue;
803 		}
804 		if (!strcmp(cp, "flags")) {
805 			for (v = 0; (cp = tp) && *cp != '\0';) {
806 				tp = word(cp);
807 				if (!strcmp(cp, "removeable"))
808 					v |= D_REMOVABLE;
809 				else if (!strcmp(cp, "ecc"))
810 					v |= D_ECC;
811 				else if (!strcmp(cp, "badsect"))
812 					v |= D_BADSECT;
813 				else {
814 					fprintf(stderr,
815 					    "line %d: %s: bad flag\n",
816 					    lineno, cp);
817 					errors++;
818 				}
819 			}
820 			lp->d_flags = v;
821 			continue;
822 		}
823 		if (!strcmp(cp, "drivedata")) {
824 			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
825 				lp->d_drivedata[i++] = strtoul(cp, NULL, 10);
826 				tp = word(cp);
827 			}
828 			continue;
829 		}
830 		if (sscanf(cp, "%lu partitions", &v) == 1) {
831 			if (v == 0 || v > MAXPARTITIONS) {
832 				fprintf(stderr,
833 				    "line %d: bad # of partitions\n", lineno);
834 				lp->d_npartitions = MAXPARTITIONS;
835 				errors++;
836 			} else
837 				lp->d_npartitions = v;
838 			continue;
839 		}
840 		if (tp == NULL)
841 			tp = blank;
842 		if (!strcmp(cp, "disk")) {
843 			strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
844 			continue;
845 		}
846 		if (!strcmp(cp, "label")) {
847 			strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
848 			continue;
849 		}
850 		if (!strcmp(cp, "bytes/sector")) {
851 			v = strtoul(tp, NULL, 10);
852 			if (v == 0 || (v % DEV_BSIZE) != 0) {
853 				fprintf(stderr,
854 				    "line %d: %s: bad sector size\n",
855 				    lineno, tp);
856 				errors++;
857 			} else
858 				lp->d_secsize = v;
859 			continue;
860 		}
861 		if (!strcmp(cp, "sectors/track")) {
862 			v = strtoul(tp, NULL, 10);
863 #if (ULONG_MAX != 0xffffffffUL)
864 			if (v == 0 || v > 0xffffffff)
865 #else
866 			if (v == 0)
867 #endif
868 			{
869 				fprintf(stderr, "line %d: %s: bad %s\n",
870 				    lineno, tp, cp);
871 				errors++;
872 			} else
873 				lp->d_nsectors = v;
874 			continue;
875 		}
876 		if (!strcmp(cp, "sectors/cylinder")) {
877 			v = strtoul(tp, NULL, 10);
878 			if (v == 0) {
879 				fprintf(stderr, "line %d: %s: bad %s\n",
880 				    lineno, tp, cp);
881 				errors++;
882 			} else
883 				lp->d_secpercyl = v;
884 			continue;
885 		}
886 		if (!strcmp(cp, "tracks/cylinder")) {
887 			v = strtoul(tp, NULL, 10);
888 			if (v == 0) {
889 				fprintf(stderr, "line %d: %s: bad %s\n",
890 				    lineno, tp, cp);
891 				errors++;
892 			} else
893 				lp->d_ntracks = v;
894 			continue;
895 		}
896 		if (!strcmp(cp, "cylinders")) {
897 			v = strtoul(tp, NULL, 10);
898 			if (v == 0) {
899 				fprintf(stderr, "line %d: %s: bad %s\n",
900 				    lineno, tp, cp);
901 				errors++;
902 			} else
903 				lp->d_ncylinders = v;
904 			continue;
905 		}
906 		if (!strcmp(cp, "sectors/unit")) {
907 			v = strtoul(tp, NULL, 10);
908 			if (v == 0) {
909 				fprintf(stderr, "line %d: %s: bad %s\n",
910 				    lineno, tp, cp);
911 				errors++;
912 			} else
913 				lp->d_secperunit = v;
914 			continue;
915 		}
916 		if (!strcmp(cp, "rpm")) {
917 			v = strtoul(tp, NULL, 10);
918 			if (v == 0 || v > USHRT_MAX) {
919 				fprintf(stderr, "line %d: %s: bad %s\n",
920 				    lineno, tp, cp);
921 				errors++;
922 			} else
923 				lp->d_rpm = v;
924 			continue;
925 		}
926 		if (!strcmp(cp, "interleave")) {
927 			v = strtoul(tp, NULL, 10);
928 			if (v == 0 || v > USHRT_MAX) {
929 				fprintf(stderr, "line %d: %s: bad %s\n",
930 				    lineno, tp, cp);
931 				errors++;
932 			} else
933 				lp->d_interleave = v;
934 			continue;
935 		}
936 		if (!strcmp(cp, "trackskew")) {
937 			v = strtoul(tp, NULL, 10);
938 			if (v > USHRT_MAX) {
939 				fprintf(stderr, "line %d: %s: bad %s\n",
940 				    lineno, tp, cp);
941 				errors++;
942 			} else
943 				lp->d_trackskew = v;
944 			continue;
945 		}
946 		if (!strcmp(cp, "cylinderskew")) {
947 			v = strtoul(tp, NULL, 10);
948 			if (v > USHRT_MAX) {
949 				fprintf(stderr, "line %d: %s: bad %s\n",
950 				    lineno, tp, cp);
951 				errors++;
952 			} else
953 				lp->d_cylskew = v;
954 			continue;
955 		}
956 		if (!strcmp(cp, "headswitch")) {
957 			v = strtoul(tp, NULL, 10);
958 			lp->d_headswitch = v;
959 			continue;
960 		}
961 		if (!strcmp(cp, "track-to-track seek")) {
962 			v = strtoul(tp, NULL, 10);
963 			lp->d_trkseek = v;
964 			continue;
965 		}
966 		/* the ':' was removed above */
967 		if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') {
968 			fprintf(stderr,
969 			    "line %d: %s: Unknown disklabel field\n", lineno,
970 			    cp);
971 			errors++;
972 			continue;
973 		}
974 
975 		/* Process a partition specification line. */
976 		part = *cp - 'a';
977 		if (part >= lp->d_npartitions) {
978 			fprintf(stderr,
979 			    "line %d: partition name out of range a-%c: %s\n",
980 			    lineno, 'a' + lp->d_npartitions - 1, cp);
981 			errors++;
982 			continue;
983 		}
984 		part_set[part] = 1;
985 
986 		if (getasciipartspec(tp, lp, part, lineno) != 0) {
987 			errors++;
988 			break;
989 		}
990 	}
991 	errors += checklabel(lp);
992 	return (errors == 0);
993 }
994 
995 #define NXTNUM(n) do { \
996 	if (tp == NULL) { \
997 		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
998 		return (1); \
999 	} else { \
1000 		cp = tp, tp = word(cp); \
1001 		(n) = strtoul(cp, NULL, 10); \
1002 	} \
1003 } while (0)
1004 
1005 /* retain 1 character following number */
1006 #define NXTWORD(w,n) do { \
1007 	if (tp == NULL) { \
1008 		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1009 		return (1); \
1010 	} else { \
1011 		char *tmp; \
1012 		cp = tp, tp = word(cp); \
1013 		(n) = strtoul(cp, &tmp, 10); \
1014 		if (tmp) (w) = *tmp; \
1015 	} \
1016 } while (0)
1017 
1018 /*
1019  * Read a partition line into partition `part' in the specified disklabel.
1020  * Return 0 on success, 1 on failure.
1021  */
1022 static int
1023 getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno)
1024 {
1025 	struct partition *pp;
1026 	char *cp;
1027 	const char **cpp;
1028 	u_long v;
1029 
1030 	pp = &lp->d_partitions[part];
1031 	cp = NULL;
1032 
1033 	v = 0;
1034 	NXTWORD(part_size_type[part],v);
1035 	if (v == 0 && part_size_type[part] != '*') {
1036 		fprintf(stderr,
1037 		    "line %d: %s: bad partition size\n", lineno, cp);
1038 		return (1);
1039 	}
1040 	pp->p_size = v;
1041 
1042 	v = 0;
1043 	NXTWORD(part_offset_type[part],v);
1044 	if (v == 0 && part_offset_type[part] != '*' &&
1045 	    part_offset_type[part] != '\0') {
1046 		fprintf(stderr,
1047 		    "line %d: %s: bad partition offset\n", lineno, cp);
1048 		return (1);
1049 	}
1050 	pp->p_offset = v;
1051 	if (tp == NULL) {
1052 		fprintf(stderr, "line %d: missing file system type\n", lineno);
1053 		return (1);
1054 	}
1055 	cp = tp, tp = word(cp);
1056 	for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++)
1057 		if (*cpp && !strcmp(*cpp, cp))
1058 			break;
1059 	if (*cpp != NULL) {
1060 		pp->p_fstype = cpp - fstypenames;
1061 	} else {
1062 		if (isdigit(*cp))
1063 			v = strtoul(cp, NULL, 10);
1064 		else
1065 			v = FSMAXTYPES;
1066 		if (v >= FSMAXTYPES) {
1067 			fprintf(stderr,
1068 			    "line %d: Warning, unknown file system type %s\n",
1069 			    lineno, cp);
1070 			v = FS_UNUSED;
1071 		}
1072 		pp->p_fstype = v;
1073 	}
1074 
1075 	switch (pp->p_fstype) {
1076 	case FS_UNUSED:
1077 	case FS_BSDFFS:
1078 	case FS_BSDLFS:
1079 		/* accept defaults for fsize/frag/cpg */
1080 		if (tp) {
1081 			NXTNUM(pp->p_fsize);
1082 			if (pp->p_fsize == 0)
1083 				break;
1084 			NXTNUM(v);
1085 			pp->p_frag = v / pp->p_fsize;
1086 			if (tp != NULL)
1087 				NXTNUM(pp->p_cpg);
1088 		}
1089 		/* else default to 0's */
1090 		break;
1091 	default:
1092 		break;
1093 	}
1094 	return (0);
1095 }
1096 
1097 /*
1098  * Check disklabel for errors and fill in
1099  * derived fields according to supplied values.
1100  */
1101 static int
1102 checklabel(struct disklabel *lp)
1103 {
1104 	struct partition *pp;
1105 	int i, errors = 0;
1106 	char part;
1107 	u_long base_offset, needed, total_size, total_percent, current_offset;
1108 	long free_space;
1109 	int seen_default_offset;
1110 	int hog_part;
1111 	int j;
1112 	struct partition *pp2;
1113 
1114 	if (lp == NULL)
1115 		lp = &lab;
1116 
1117 	if (allfields) {
1118 
1119 		if (lp->d_secsize == 0) {
1120 			fprintf(stderr, "sector size 0\n");
1121 			return (1);
1122 		}
1123 		if (lp->d_nsectors == 0) {
1124 			fprintf(stderr, "sectors/track 0\n");
1125 			return (1);
1126 		}
1127 		if (lp->d_ntracks == 0) {
1128 			fprintf(stderr, "tracks/cylinder 0\n");
1129 			return (1);
1130 		}
1131 		if  (lp->d_ncylinders == 0) {
1132 			fprintf(stderr, "cylinders/unit 0\n");
1133 			errors++;
1134 		}
1135 		if (lp->d_rpm == 0)
1136 			warnx("revolutions/minute 0");
1137 		if (lp->d_secpercyl == 0)
1138 			lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1139 		if (lp->d_secperunit == 0)
1140 			lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1141 		if (lp->d_bbsize == 0) {
1142 			fprintf(stderr, "boot block size 0\n");
1143 			errors++;
1144 		} else if (lp->d_bbsize % lp->d_secsize)
1145 			warnx("boot block size %% sector-size != 0");
1146 		if (lp->d_npartitions > MAXPARTITIONS)
1147 			warnx("number of partitions (%lu) > MAXPARTITIONS (%d)",
1148 			    (u_long)lp->d_npartitions, MAXPARTITIONS);
1149 	} else {
1150 		struct disklabel *vl;
1151 
1152 		vl = getvirginlabel();
1153 		lp->d_secsize = vl->d_secsize;
1154 		lp->d_nsectors = vl->d_nsectors;
1155 		lp->d_ntracks = vl->d_ntracks;
1156 		lp->d_ncylinders = vl->d_ncylinders;
1157 		lp->d_rpm = vl->d_rpm;
1158 		lp->d_interleave = vl->d_interleave;
1159 		lp->d_secpercyl = vl->d_secpercyl;
1160 		lp->d_secperunit = vl->d_secperunit;
1161 		lp->d_bbsize = vl->d_bbsize;
1162 		lp->d_npartitions = vl->d_npartitions;
1163 	}
1164 
1165 
1166 	/* first allocate space to the partitions, then offsets */
1167 	total_size = 0; /* in sectors */
1168 	total_percent = 0; /* in percent */
1169 	hog_part = -1;
1170 	/* find all fixed partitions */
1171 	for (i = 0; i < lp->d_npartitions; i++) {
1172 		pp = &lp->d_partitions[i];
1173 		if (part_set[i]) {
1174 			if (part_size_type[i] == '*') {
1175 				if (i == RAW_PART) {
1176 					pp->p_size = lp->d_secperunit;
1177 				} else {
1178 					if (hog_part != -1)
1179 						warnx("Too many '*' partitions (%c and %c)",
1180 						    hog_part + 'a',i + 'a');
1181 					else
1182 						hog_part = i;
1183 				}
1184 			} else {
1185 				off_t size;
1186 
1187 				size = pp->p_size;
1188 				switch (part_size_type[i]) {
1189 				case '%':
1190 					total_percent += size;
1191 					break;
1192 				case 't':
1193 				case 'T':
1194 					size *= 1024ULL;
1195 					/* FALLTHROUGH */
1196 				case 'g':
1197 				case 'G':
1198 					size *= 1024ULL;
1199 					/* FALLTHROUGH */
1200 				case 'm':
1201 				case 'M':
1202 					size *= 1024ULL;
1203 					/* FALLTHROUGH */
1204 				case 'k':
1205 				case 'K':
1206 					size *= 1024ULL;
1207 					break;
1208 				case '\0':
1209 					break;
1210 				default:
1211 					warnx("unknown multiplier suffix '%c' for partition %c (should be K, M, G or T)",
1212 					    part_size_type[i], i + 'a');
1213 					break;
1214 				}
1215 				/* don't count %'s yet */
1216 				if (part_size_type[i] != '%') {
1217 					/*
1218 					 * for all not in sectors, convert to
1219 					 * sectors
1220 					 */
1221 					if (part_size_type[i] != '\0') {
1222 						if (size % lp->d_secsize != 0)
1223 							warnx("partition %c not an integer number of sectors",
1224 							    i + 'a');
1225 						size /= lp->d_secsize;
1226 						pp->p_size = size;
1227 					}
1228 					/* else already in sectors */
1229 					if (i != RAW_PART)
1230 						total_size += size;
1231 				}
1232 			}
1233 		}
1234 	}
1235 
1236 	/* Find out the total free space, excluding the boot block area. */
1237 	base_offset = BBSIZE / secsize;
1238 	free_space = 0;
1239 	for (i = 0; i < lp->d_npartitions; i++) {
1240 		pp = &lp->d_partitions[i];
1241 		if (!part_set[i] || i == RAW_PART ||
1242 		    part_size_type[i] == '%' || part_size_type[i] == '*')
1243 			continue;
1244 		if (pp->p_offset > base_offset)
1245 			free_space += pp->p_offset - base_offset;
1246 		if (pp->p_offset + pp->p_size > base_offset)
1247 			base_offset = pp->p_offset + pp->p_size;
1248 	}
1249 	if (base_offset < lp->d_secperunit)
1250 		free_space += lp->d_secperunit - base_offset;
1251 
1252 	/* handle % partitions - note %'s don't need to add up to 100! */
1253 	if (total_percent != 0) {
1254 		if (total_percent > 100) {
1255 			fprintf(stderr,"total percentage %lu is greater than 100\n",
1256 			    total_percent);
1257 			errors++;
1258 		}
1259 
1260 		if (free_space > 0) {
1261 			for (i = 0; i < lp->d_npartitions; i++) {
1262 				pp = &lp->d_partitions[i];
1263 				if (part_set[i] && part_size_type[i] == '%') {
1264 					/* careful of overflows! and integer roundoff */
1265 					pp->p_size = ((double)pp->p_size/100) * free_space;
1266 					total_size += pp->p_size;
1267 
1268 					/* FIX we can lose a sector or so due to roundoff per
1269 					   partition.  A more complex algorithm could avoid that */
1270 				}
1271 			}
1272 		} else {
1273 			fprintf(stderr,
1274 			    "%ld sectors available to give to '*' and '%%' partitions\n",
1275 			    free_space);
1276 			errors++;
1277 			/* fix?  set all % partitions to size 0? */
1278 		}
1279 	}
1280 	/* give anything remaining to the hog partition */
1281 	if (hog_part != -1) {
1282 		/*
1283 		 * Find the range of offsets usable by '*' partitions around
1284 		 * the hog partition and how much space they need.
1285 		 */
1286 		needed = 0;
1287 		base_offset = BBSIZE / secsize;
1288 		for (i = hog_part - 1; i >= 0; i--) {
1289 			pp = &lp->d_partitions[i];
1290 			if (!part_set[i] || i == RAW_PART)
1291 				continue;
1292 			if (part_offset_type[i] == '*') {
1293 				needed += pp->p_size;
1294 				continue;
1295 			}
1296 			base_offset = pp->p_offset + pp->p_size;
1297 			break;
1298 		}
1299 		current_offset = lp->d_secperunit;
1300 		for (i = lp->d_npartitions - 1; i > hog_part; i--) {
1301 			pp = &lp->d_partitions[i];
1302 			if (!part_set[i] || i == RAW_PART)
1303 				continue;
1304 			if (part_offset_type[i] == '*') {
1305 				needed += pp->p_size;
1306 				continue;
1307 			}
1308 			current_offset = pp->p_offset;
1309 		}
1310 
1311 		if (current_offset - base_offset <= needed) {
1312 			fprintf(stderr, "Cannot find space for partition %c\n",
1313 			    hog_part + 'a');
1314 			fprintf(stderr,
1315 			    "Need more than %lu sectors between %lu and %lu\n",
1316 			    needed, base_offset, current_offset);
1317 			errors++;
1318 			lp->d_partitions[hog_part].p_size = 0;
1319 		} else {
1320 			lp->d_partitions[hog_part].p_size = current_offset -
1321 			    base_offset - needed;
1322 			total_size += lp->d_partitions[hog_part].p_size;
1323 		}
1324 	}
1325 
1326 	/* Now set the offsets for each partition */
1327 	current_offset = BBSIZE / secsize; /* in sectors */
1328 	seen_default_offset = 0;
1329 	for (i = 0; i < lp->d_npartitions; i++) {
1330 		part = 'a' + i;
1331 		pp = &lp->d_partitions[i];
1332 		if (part_set[i]) {
1333 			if (part_offset_type[i] == '*') {
1334 				if (i == RAW_PART) {
1335 					pp->p_offset = 0;
1336 				} else {
1337 					pp->p_offset = current_offset;
1338 					seen_default_offset = 1;
1339 				}
1340 			} else {
1341 				/* allow them to be out of order for old-style tables */
1342 				if (pp->p_offset < current_offset &&
1343 				    seen_default_offset && i != RAW_PART &&
1344 				    pp->p_fstype != FS_VINUM) {
1345 					fprintf(stderr,
1346 "Offset %ld for partition %c overlaps previous partition which ends at %lu\n",
1347 					    (long)pp->p_offset,i+'a',current_offset);
1348 					fprintf(stderr,
1349 "Labels with any *'s for offset must be in ascending order by sector\n");
1350 					errors++;
1351 				} else if (pp->p_offset != current_offset &&
1352 				    i != RAW_PART && seen_default_offset) {
1353 					/*
1354 					 * this may give unneeded warnings if
1355 					 * partitions are out-of-order
1356 					 */
1357 					warnx(
1358 "Offset %ld for partition %c doesn't match expected value %ld",
1359 					    (long)pp->p_offset, i + 'a', current_offset);
1360 				}
1361 			}
1362 			if (i != RAW_PART)
1363 				current_offset = pp->p_offset + pp->p_size;
1364 		}
1365 	}
1366 
1367 	for (i = 0; i < lp->d_npartitions; i++) {
1368 		part = 'a' + i;
1369 		pp = &lp->d_partitions[i];
1370 		if (pp->p_size == 0 && pp->p_offset != 0)
1371 			warnx("partition %c: size 0, but offset %lu",
1372 			    part, (u_long)pp->p_offset);
1373 #ifdef notdef
1374 		if (pp->p_size % lp->d_secpercyl)
1375 			warnx("partition %c: size %% cylinder-size != 0",
1376 			    part);
1377 		if (pp->p_offset % lp->d_secpercyl)
1378 			warnx("partition %c: offset %% cylinder-size != 0",
1379 			    part);
1380 #endif
1381 		if (pp->p_offset > lp->d_secperunit) {
1382 			fprintf(stderr,
1383 			    "partition %c: offset past end of unit\n", part);
1384 			errors++;
1385 		}
1386 		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1387 			fprintf(stderr,
1388 			"partition %c: partition extends past end of unit\n",
1389 			    part);
1390 			errors++;
1391 		}
1392 		if (i == RAW_PART) {
1393 			if (pp->p_fstype != FS_UNUSED)
1394 				warnx("partition %c is not marked as unused!",part);
1395 			if (pp->p_offset != 0)
1396 				warnx("partition %c doesn't start at 0!",part);
1397 			if (pp->p_size != lp->d_secperunit)
1398 				warnx("partition %c doesn't cover the whole unit!",part);
1399 
1400 			if ((pp->p_fstype != FS_UNUSED) || (pp->p_offset != 0) ||
1401 			    (pp->p_size != lp->d_secperunit)) {
1402 				warnx("An incorrect partition %c may cause problems for "
1403 				    "standard system utilities",part);
1404 			}
1405 		}
1406 
1407 		/* check for overlaps */
1408 		/* this will check for all possible overlaps once and only once */
1409 		for (j = 0; j < i; j++) {
1410 			pp2 = &lp->d_partitions[j];
1411 			if (j != RAW_PART && i != RAW_PART &&
1412 			    pp->p_fstype != FS_VINUM &&
1413 			    pp2->p_fstype != FS_VINUM &&
1414 			    part_set[i] && part_set[j]) {
1415 				if (pp2->p_offset < pp->p_offset + pp->p_size &&
1416 				    (pp2->p_offset + pp2->p_size > pp->p_offset ||
1417 					pp2->p_offset >= pp->p_offset)) {
1418 					fprintf(stderr,"partitions %c and %c overlap!\n",
1419 					    j + 'a', i + 'a');
1420 					errors++;
1421 				}
1422 			}
1423 		}
1424 	}
1425 	for (; i < lp->d_npartitions; i++) {
1426 		part = 'a' + i;
1427 		pp = &lp->d_partitions[i];
1428 		if (pp->p_size || pp->p_offset)
1429 			warnx("unused partition %c: size %d offset %lu",
1430 			    'a' + i, pp->p_size, (u_long)pp->p_offset);
1431 	}
1432 	return (errors);
1433 }
1434 
1435 /*
1436  * When operating on a "virgin" disk, try getting an initial label
1437  * from the associated device driver.  This might work for all device
1438  * drivers that are able to fetch some initial device parameters
1439  * without even having access to a (BSD) disklabel, like SCSI disks,
1440  * most IDE drives, or vn devices.
1441  *
1442  * The device name must be given in its "canonical" form.
1443  */
1444 static struct disklabel *
1445 getvirginlabel(void)
1446 {
1447 	static struct disklabel loclab;
1448 	struct partition *dp;
1449 	int f;
1450 	u_int u;
1451 
1452 	if ((f = open(specname, O_RDONLY)) == -1) {
1453 		warn("cannot open %s", specname);
1454 		return (NULL);
1455 	}
1456 
1457 	if (is_file)
1458 		get_file_parms(f);
1459 	else {
1460 		mediasize = g_mediasize(f);
1461 		secsize = g_sectorsize(f);
1462 		if (secsize < 0 || mediasize < 0) {
1463 			close (f);
1464 			return (NULL);
1465 		}
1466 	}
1467 	memset(&loclab, 0, sizeof loclab);
1468 	loclab.d_magic = DISKMAGIC;
1469 	loclab.d_magic2 = DISKMAGIC;
1470 	loclab.d_secsize = secsize;
1471 	loclab.d_secperunit = mediasize / secsize;
1472 
1473 	/*
1474 	 * Nobody in these enligthened days uses the CHS geometry for
1475 	 * anything, but nontheless try to get it right.  If we fail
1476 	 * to get any good ideas from the device, construct something
1477 	 * which is IBM-PC friendly.
1478 	 */
1479 	if (ioctl(f, DIOCGFWSECTORS, &u) == 0)
1480 		loclab.d_nsectors = u;
1481 	else
1482 		loclab.d_nsectors = 63;
1483 	if (ioctl(f, DIOCGFWHEADS, &u) == 0)
1484 		loclab.d_ntracks = u;
1485 	else if (loclab.d_secperunit <= 63*1*1024)
1486 		loclab.d_ntracks = 1;
1487 	else if (loclab.d_secperunit <= 63*16*1024)
1488 		loclab.d_ntracks = 16;
1489 	else
1490 		loclab.d_ntracks = 255;
1491 	loclab.d_secpercyl = loclab.d_ntracks * loclab.d_nsectors;
1492 	loclab.d_ncylinders = loclab.d_secperunit / loclab.d_secpercyl;
1493 	loclab.d_npartitions = DEFPARTITIONS;
1494 
1495 	/* Various (unneeded) compat stuff */
1496 	loclab.d_rpm = 3600;
1497 	loclab.d_bbsize = BBSIZE;
1498 	loclab.d_interleave = 1;
1499 	strncpy(loclab.d_typename, "amnesiac",
1500 	    sizeof(loclab.d_typename));
1501 
1502 	dp = &loclab.d_partitions[RAW_PART];
1503 	dp->p_size = loclab.d_secperunit;
1504 	loclab.d_checksum = dkcksum(&loclab);
1505 	close (f);
1506 	return (&loclab);
1507 }
1508 
1509 static void
1510 usage(void)
1511 {
1512 
1513 	fprintf(stderr,
1514 	"%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",
1515 	"usage: bsdlabel disk",
1516 	"\t\t(to read label)",
1517 	"	bsdlabel -w [-n] [-m machine] disk [type]",
1518 	"\t\t(to write label with existing boot program)",
1519 	"	bsdlabel -e [-n] [-m machine] disk",
1520 	"\t\t(to edit label)",
1521 	"	bsdlabel -R [-n] [-m machine] disk protofile",
1522 	"\t\t(to restore label with existing boot program)",
1523 	"	bsdlabel -B [-b boot] [-m machine] disk",
1524 	"\t\t(to install boot program with existing on-disk label)",
1525 	"	bsdlabel -w -B [-n] [-b boot] [-m machine] disk [type]",
1526 	"\t\t(to write label and install boot program)",
1527 	"	bsdlabel -R -B [-n] [-b boot] [-m machine] disk protofile",
1528 		"\t\t(to restore label and install boot program)"
1529 	);
1530 	exit(1);
1531 }
1532