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