xref: /netbsd-src/sbin/disklabel/main.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /*	$NetBSD: main.c,v 1.17 2007/06/05 21:48:46 dyoung Exp $	*/
2 
3 /*
4  * Copyright (c) 2006 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Julio M. Merino Vidal.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Copyright (c) 1987, 1993
41  *	The Regents of the University of California.  All rights reserved.
42  *
43  * This code is derived from software contributed to Berkeley by
44  * Symmetric Computer Systems.
45  *
46  * Redistribution and use in source and binary forms, with or without
47  * modification, are permitted provided that the following conditions
48  * are met:
49  * 1. Redistributions of source code must retain the above copyright
50  *    notice, this list of conditions and the following disclaimer.
51  * 2. Redistributions in binary form must reproduce the above copyright
52  *    notice, this list of conditions and the following disclaimer in the
53  *    documentation and/or other materials provided with the distribution.
54  * 3. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #if HAVE_NBTOOL_CONFIG_H
72 #include "nbtool_config.h"
73 #endif
74 
75 #include <sys/cdefs.h>
76 #ifndef lint
77 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
78 	The Regents of the University of California.  All rights reserved.\n");
79 #endif	/* not lint */
80 
81 #ifndef lint
82 #if 0
83 static char sccsid[] = "@(#)disklabel.c	8.4 (Berkeley) 5/4/95";
84 /* from static char sccsid[] = "@(#)disklabel.c	1.2 (Symmetric) 11/28/85"; */
85 #else
86 __RCSID("$NetBSD: main.c,v 1.17 2007/06/05 21:48:46 dyoung Exp $");
87 #endif
88 #endif	/* not lint */
89 
90 #include <sys/param.h>
91 #include <sys/file.h>
92 #include <sys/stat.h>
93 #include <sys/wait.h>
94 #define DKTYPENAMES
95 #define FSTYPENAMES
96 
97 #include <ctype.h>
98 #include <err.h>
99 #include <errno.h>
100 #include <signal.h>
101 #include <string.h>
102 #include <stdio.h>
103 #include <stdlib.h>
104 #include <limits.h>
105 #include <unistd.h>
106 
107 #include <ufs/ufs/dinode.h>
108 #include <ufs/ffs/fs.h>
109 
110 #if HAVE_NBTOOL_CONFIG_H
111 #include <nbinclude/sys/disklabel.h>
112 #include <nbinclude/sys/disklabel_acorn.h>
113 #include <nbinclude/sys/bootblock.h>
114 #include "../../include/disktab.h"
115 #else
116 #include <sys/ioctl.h>
117 #include <sys/disklabel.h>
118 #include <sys/disklabel_acorn.h>
119 #include <sys/bootblock.h>
120 #include <util.h>
121 #include <disktab.h>
122 #endif /* HAVE_NBTOOL_CONFIG_H */
123 
124 #include "pathnames.h"
125 #include "extern.h"
126 #include "dkcksum.h"
127 
128 /*
129  * Disklabel: read and write disklabels.
130  * The label is usually placed on one of the first sectors of the disk.
131  * Many machines also place a bootstrap in the same area,
132  * in which case the label is embedded in the bootstrap.
133  * The bootstrap source must leave space at the proper offset
134  * for the label on such machines.
135  */
136 
137 #ifndef BBSIZE
138 #define	BBSIZE	8192			/* size of boot area, with label */
139 #endif
140 
141 #define DISKMAGIC_REV		bswap32(DISKMAGIC)
142 /* To delete a label, we just invert the magic numbers */
143 #define DISKMAGIC_DELETED	(~DISKMAGIC)
144 #define DISKMAGIC_DELETED_REV	bswap32(~DISKMAGIC)
145 
146 #define	DEFEDITOR	_PATH_VI
147 
148 char	specname[MAXPATHLEN];
149 
150 /* Some global data, all too hard to pass about */
151 char bootarea[BBSIZE];			/* Buffer matching part of disk */
152 int bootarea_len;			/* Number of bytes we actually read */
153 static struct	disklabel lab;		/* The label we have updated */
154 
155 static	int	Aflag;		/* Action all labels */
156 static	int	Fflag;		/* Read/write from file */
157 static	int	rflag;		/* Read/write direct from disk */
158 static	int	tflag;		/* Format output as disktab */
159 	int	Cflag;		/* CHS format output */
160 static	int	Dflag;		/* Delete old labels (use with write) */
161 static	int	Iflag;		/* Read/write direct, but default if absent */
162 static	int	lflag;		/* List all known file system types and exit */
163 static	int	mflag;		/* Expect disk to contain an MBR */
164 static int verbose;
165 static int read_all;		/* set if op = READ && Aflag */
166 
167 static int write_label(int);
168 static int readlabel_direct(int);
169 static void writelabel_direct(int);
170 static int update_label(int, u_int, u_int);
171 static struct disklabel *find_label(int, u_int);
172 
173 static void		 makedisktab(FILE *, struct disklabel *);
174 static void		 makelabel(const char *, const char *);
175 static void		 l_perror(const char *);
176 static void		 readlabel(int);
177 static int		 edit(int);
178 static int		 editit(const char *);
179 static char		*skip(char *);
180 static char		*word(char *);
181 static int		 getasciilabel(FILE *, struct disklabel *);
182 static void		 usage(void);
183 static int		 qsort_strcmp(const void *, const void *);
184 static int		 getulong(const char *, char, char **,
185     unsigned long *, unsigned long);
186 #define GETNUM32(a, v)	getulong(a, '\0', NULL, v, UINT32_MAX)
187 #define GETNUM16(a, v)	getulong(a, '\0', NULL, v, UINT16_MAX)
188 #define GETNUM8(a, v)	getulong(a, '\0', NULL, v, UINT8_MAX)
189 
190 static int set_writable_fd = -1;
191 
192 #if HAVE_NBTOOL_CONFIG_H
193 #define GETLABELOFFSET()	LABELOFFSET
194 #define GETLABELSECTOR()	LABELSECTOR
195 #else /* HAVE_NBTOOL_CONFIG_H */
196 #define GETLABELOFFSET()	getlabeloffset()
197 #define GETLABELSECTOR()	getlabelsector()
198 #endif
199 
200 /* Default location for label - only used if we don't find one to update */
201 #define LABEL_OFFSET (dklabel_getlabelsector() * DEV_BSIZE + dklabel_getlabeloffset())
202 
203 /*
204  * For portability it doesn't make sense to use any other value....
205  * Except, maybe, the size of a physical sector.
206  * This value is used if we have to write a label to the start of an mbr ptn.
207  */
208 #ifndef	LABELOFFSET_MBR
209 #define	LABELOFFSET_MBR	512
210 #endif
211 
212 #if HAVE_NBTOOL_CONFIG_H
213 static int
214 opendisk(const char *path, int flags, char *buf, int buflen, int cooked)
215 {
216 	int f;
217 	f = open(path, flags, 0);
218 	strlcpy(buf, path, buflen);
219 	return f;
220 }
221 
222 static int
223 dk_ioctl(int f, void *arg)
224 {
225 	errno = ENOTTY;
226 	return -1;
227 }
228 #define dk_ioctl(f, cmd, arg) dk_ioctl(f, arg)
229 #else
230 #define dk_ioctl(f, cmd, arg) ioctl(f, cmd, arg)
231 #endif /* HAVE_NBTOOL_CONFIG_H */
232 
233 static daddr_t
234 dklabel_getlabelsector(void)
235 {
236 	unsigned long int nval;
237 	char *end;
238 	const char *val;
239 
240 	if ((val = getenv("DISKLABELSECTOR")) == NULL)
241 		return GETLABELSECTOR();
242 	if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
243 		err(EXIT_FAILURE, "DISKLABELSECTOR in environment");
244 	return nval;
245 }
246 
247 static off_t
248 dklabel_getlabeloffset(void)
249 {
250 	unsigned long int nval;
251 	char *end;
252 	const char *val;
253 
254 	if ((val = getenv("DISKLABELOFFSET")) == NULL)
255 		return GETLABELOFFSET();
256 	if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
257 		err(EXIT_FAILURE, "DISKLABELOFFSET in environment");
258 	return nval;
259 }
260 
261 static void
262 clear_writable(void)
263 {
264 	static int zero = 0;
265 	dk_ioctl(set_writable_fd, DIOCWLABEL, &zero);
266 }
267 
268 int
269 main(int argc, char *argv[])
270 {
271 	FILE	*t;
272 	int	 ch, f, error;
273 	char	*dkname;
274 	struct stat sb;
275 	int	 writable;
276 	enum {
277 		UNSPEC, EDIT, READ, RESTORE, SETWRITABLE, SETREADONLY,
278 		WRITE, INTERACT, DELETE
279 	} op = UNSPEC, old_op;
280 
281 #ifdef USE_MBR
282 	mflag = 1;
283 #endif
284 #if HAVE_NBTOOL_CONFIG_H
285 	/* We must avoid doing any ioctl requests */
286 	Fflag = rflag = 1;
287 #endif
288 
289 	error = 0;
290 	while ((ch = getopt(argc, argv, "ACDFINRWb:ef:ilmrs:tvw")) != -1) {
291 		old_op = op;
292 		switch (ch) {
293 		case 'A':	/* Action all labels */
294 			Aflag = 1;
295 			rflag = 1;
296 			break;
297 		case 'C':	/* Display in CHS format */
298 			Cflag = 1;
299 			break;
300 		case 'D':	/* Delete all existing labels */
301 			Dflag = 1;
302 			rflag = 1;
303 			break;
304 		case 'F':	/* Treat 'disk' as a regular file */
305 			Fflag = 1;
306 			rflag = 1;	/* Force direct access */
307 			break;
308 		case 'I':	/* Use default label if none found */
309 			Iflag = 1;
310 			rflag = 1;	/* Implies direct access */
311 			break;
312 		case 'R':	/* Restore label from text file */
313 			op = RESTORE;
314 			break;
315 		case 'N':	/* Disallow writes to label sector */
316 			op = SETREADONLY;
317 			break;
318 		case 'W':	/* Allow writes to label sector */
319 			op = SETWRITABLE;
320 			break;
321 		case 'e':	/* Edit label with $EDITOR */
322 			op = EDIT;
323 			break;
324 		case 'f':	/* Name of disktab file */
325 			if (setdisktab(optarg) == -1)
326 				usage();
327 			break;
328 		case 'i':	/* Edit using built-in editor */
329 			op = INTERACT;
330 			break;
331 		case 'l':	/* List all known file system types and exit */
332 			lflag = 1;
333 			break;
334 		case 'm':	/* Expect disk to have an MBR */
335 			mflag ^= 1;
336 			break;
337 		case 'r':	/* Read/write label directly from disk */
338 			rflag = 1;
339 			break;
340 		case 't':	/* Format output as a disktab entry */
341 			tflag = 1;
342 			break;
343 		case 'v':	/* verbose/diag output */
344 			verbose++;
345 			break;
346 		case 'w':	/* Write label based on disktab entry */
347 			op = WRITE;
348 			break;
349 		case '?':
350 		default:
351 			usage();
352 		}
353 		if (old_op != UNSPEC && old_op != op)
354 			usage();
355 	}
356 	argc -= optind;
357 	argv += optind;
358 
359 	if (lflag)
360 		exit(list_fs_types() ? EXIT_SUCCESS : EXIT_FAILURE);
361 
362 	if (op == UNSPEC)
363 		op = Dflag ? DELETE : READ;
364 
365 	if (argc < 1)
366 		usage();
367 
368 	if (Iflag && op != EDIT && op != INTERACT)
369 		usage();
370 
371 	dkname = argv[0];
372 	f = opendisk(dkname, op == READ ? O_RDONLY : O_RDWR,
373 		    specname, sizeof specname, 0);
374 	if (f < 0)
375 		err(4, "%s", specname);
376 
377 	if (!Fflag && fstat(f, &sb) == 0 && S_ISREG(sb.st_mode))
378 		Fflag = rflag = 1;
379 
380 	switch (op) {
381 
382 	case DELETE:	/* Remove all existing labels */
383 		if (argc != 1)
384 			usage();
385 		Dflag = 2;
386 		writelabel_direct(f);
387 		break;
388 
389 	case EDIT:
390 		if (argc != 1)
391 			usage();
392 		readlabel(f);
393 		error = edit(f);
394 		break;
395 
396 	case INTERACT:
397 		if (argc != 1)
398 			usage();
399 		readlabel(f);
400 		/*
401 		 * XXX: Fill some default values so checklabel does not fail
402 		 */
403 		if (lab.d_bbsize == 0)
404 			lab.d_bbsize = BBSIZE;
405 		if (lab.d_sbsize == 0)
406 			lab.d_sbsize = SBLOCKSIZE;
407 		interact(&lab, f);
408 		break;
409 
410 	case READ:
411 		if (argc != 1)
412 			usage();
413 		read_all = Aflag;
414 		readlabel(f);
415 		if (read_all)
416 			/* Label got printed in the bowels of readlabel */
417 			break;
418 		if (tflag)
419 			makedisktab(stdout, &lab);
420 		else {
421 			showinfo(stdout, &lab, specname);
422 			showpartitions(stdout, &lab, Cflag);
423 		}
424 		error = checklabel(&lab);
425 		if (error)
426 			error += 100;
427 		break;
428 
429 	case RESTORE:
430 		if (argc != 2)
431 			usage();
432 		if (!(t = fopen(argv[1], "r")))
433 			err(4, "%s", argv[1]);
434 		if (getasciilabel(t, &lab))
435 			error = write_label(f);
436 		else
437 			error = 1;
438 		break;
439 
440 	case SETREADONLY:
441 		writable = 0;
442 		goto do_diocwlabel;
443 	case SETWRITABLE:
444 		writable = 1;
445 	    do_diocwlabel:
446 		if (argc != 1)
447 			usage();
448 		if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
449 			err(4, "ioctl DIOCWLABEL");
450 		break;
451 
452 	case WRITE:	/* Create label from /etc/disktab entry & write */
453 		if (argc < 2 || argc > 3)
454 			usage();
455 		makelabel(argv[1], argv[2]);
456 		if (checklabel(&lab) == 0)
457 			error = write_label(f);
458 		else
459 			error = 1;
460 		break;
461 
462 	case UNSPEC:
463 		usage();
464 
465 	}
466 	exit(error);
467 }
468 
469 /*
470  * Construct a prototype disklabel from /etc/disktab.
471  */
472 static void
473 makelabel(const char *type, const char *name)
474 {
475 	struct disklabel *dp;
476 
477 	dp = getdiskbyname(type);
478 	if (dp == NULL)
479 		errx(1, "unknown disk type: %s", type);
480 	lab = *dp;
481 
482 	/* d_packname is union d_boot[01], so zero */
483 	(void)memset(lab.d_packname, 0, sizeof(lab.d_packname));
484 	if (name)
485 		(void)strncpy(lab.d_packname, name, sizeof(lab.d_packname));
486 }
487 
488 static int
489 write_label(int f)
490 {
491 	int writable;
492 
493 	lab.d_magic = DISKMAGIC;
494 	lab.d_magic2 = DISKMAGIC;
495 	lab.d_checksum = 0;
496 	lab.d_checksum = dkcksum(&lab);
497 
498 	if (rflag) {
499 		/* Write the label directly to the disk */
500 
501 		/*
502 		 * First set the kernel disk label,
503 		 * then write a label to the raw disk.
504 		 * If the SDINFO ioctl fails because it is unimplemented,
505 		 * keep going; otherwise, the kernel consistency checks
506 		 * may prevent us from changing the current (in-core)
507 		 * label.
508 		 */
509 		if (!Fflag && dk_ioctl(f, DIOCSDINFO, &lab) < 0 &&
510 		    errno != ENODEV && errno != ENOTTY) {
511 			l_perror("ioctl DIOCSDINFO");
512 			return (1);
513 		}
514 		/*
515 		 * write enable label sector before write (if necessary),
516 		 * disable after writing.
517 		 */
518 		writable = 1;
519 		if (!Fflag) {
520 			if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
521 				perror("ioctl DIOCWLABEL");
522 			set_writable_fd = f;
523 			atexit(clear_writable);
524 		}
525 
526 		writelabel_direct(f);
527 
528 		/*
529 		 * Now issue a DIOCWDINFO. This will let the kernel convert the
530 		 * disklabel to some machdep format if needed.
531 		 */
532 		/* XXX: This is stupid! */
533 		if (!Fflag && dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
534 			l_perror("ioctl DIOCWDINFO");
535 			return (1);
536 		}
537 	} else {
538 		/* Get the kernel to write the label */
539 		if (dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
540 			l_perror("ioctl DIOCWDINFO");
541 			return (1);
542 		}
543 	}
544 
545 #ifdef __vax__
546 	if (lab.d_type == DTYPE_SMD && lab.d_flags & D_BADSECT &&
547 	    lab.d_secsize == 512) {
548 		/* Write the label to the odd sectors of the last track! */
549 		daddr_t	alt;
550 		int	i;
551 		uint8_t sec0[512];
552 
553 		if (pread(f, sec0, 512, 0) < 512) {
554 			warn("read master label to write alternates");
555 			return 0;
556 		}
557 
558 		alt = lab.d_ncylinders * lab.d_secpercyl - lab.d_nsectors;
559 		for (i = 1; i < 11 && i < lab.d_nsectors; i += 2) {
560 			if (pwrite(f, sec0, 512, (off_t)(alt + i) * 512) < 512)
561 				warn("alternate label %d write", i/2);
562 		}
563 	}
564 #endif	/* __vax__ */
565 
566 	return 0;
567 }
568 
569 int
570 writelabel(int f, struct disklabel *lp)
571 {
572 	if (lp != &lab)
573 		lab = *lp;
574 	return write_label(f);
575 }
576 
577 static void
578 l_perror(const char *s)
579 {
580 
581 	switch (errno) {
582 
583 	case ESRCH:
584 		warnx("%s: No disk label on disk;\n"
585 		    "use \"disklabel -I\" to install initial label", s);
586 		break;
587 
588 	case EINVAL:
589 		warnx("%s: Label magic number or checksum is wrong!\n"
590 		    "(disklabel or kernel is out of date?)", s);
591 		break;
592 
593 	case EBUSY:
594 		warnx("%s: Open partition would move or shrink", s);
595 		break;
596 
597 	case EXDEV:
598 		warnx("%s: Labeled partition or 'a' partition must start"
599 		      " at beginning of disk", s);
600 		break;
601 
602 	default:
603 		warn("%s", s);
604 		break;
605 	}
606 }
607 
608 #ifdef NO_MBR_SUPPORT
609 #define process_mbr(f, action) 1
610 #else
611 /*
612  * Scan DOS/MBR partition table and extended partition list for NetBSD ptns.
613  */
614 static int
615 process_mbr(int f, int (*action)(int, u_int))
616 {
617 	struct mbr_partition *dp;
618 	struct mbr_sector mbr;
619 	int rval = 1, res;
620 	int part;
621 	u_int ext_base, next_ext, this_ext, start;
622 
623 	ext_base = 0;
624 	next_ext = 0;
625 	for (;;) {
626 		this_ext = next_ext;
627 		next_ext = 0;
628 		if (verbose > 1)
629 			warnx("reading mbr sector %u", this_ext);
630 		if (pread(f, &mbr, sizeof mbr, this_ext * (off_t)DEV_BSIZE)
631 		    != sizeof(mbr)) {
632 			if (verbose)
633 				warn("Can't read master boot record %d",
634 				    this_ext);
635 			break;
636 		}
637 
638 		/* Check if table is valid. */
639 		if (mbr.mbr_magic != htole16(MBR_MAGIC)) {
640 			if (verbose)
641 				warnx("Invalid signature in mbr record %d",
642 				    this_ext);
643 			break;
644 		}
645 
646 		dp = &mbr.mbr_parts[0];
647 
648 		/* Find NetBSD partition(s). */
649 		for (part = 0; part < MBR_PART_COUNT; dp++, part++) {
650 			start = le32toh(dp->mbrp_start);
651 			switch (dp->mbrp_type) {
652 #ifdef COMPAT_386BSD_MBRPART
653 			case MBR_PTYPE_386BSD:
654 				if (ext_base != 0)
655 					break;
656 				/* FALLTHROUGH */
657 #endif
658 			case MBR_PTYPE_NETBSD:
659 				res = action(f, this_ext + start);
660 				if (res <= 0)
661 					/* Found or failure */
662 					return res;
663 				if (res > rval)
664 					/* Keep largest value */
665 					rval = res;
666 				break;
667 			case MBR_PTYPE_EXT:
668 			case MBR_PTYPE_EXT_LBA:
669 			case MBR_PTYPE_EXT_LNX:
670 				next_ext = start;
671 				break;
672 			default:
673 				break;
674 			}
675 		}
676 		if (next_ext == 0)
677 			/* No more extended partitions */
678 			break;
679 		next_ext += ext_base;
680 		if (ext_base == 0)
681 			ext_base = next_ext;
682 
683 		if (next_ext <= this_ext) {
684 			if (verbose)
685 				warnx("Invalid extended chain %x <= %x",
686 					next_ext, this_ext);
687 			break;
688 		}
689 		/* Maybe we should check against the disk size... */
690 	}
691 
692 	return rval;
693 }
694 
695 static int
696 readlabel_mbr(int f, u_int sector)
697 {
698 	struct disklabel *lp;
699 
700 	lp = find_label(f, sector);
701 	if (lp == NULL)
702 		return 1;
703 	lab = *lp;
704 	return 0;
705 }
706 
707 static int
708 writelabel_mbr(int f, u_int sector)
709 {
710 	return update_label(f, sector, mflag ? LABELOFFSET_MBR : ~0U) ? 2 : 0;
711 }
712 
713 #endif	/* !NO_MBR_SUPPORT */
714 
715 #ifndef USE_ACORN
716 #define get_filecore_partition(f) 0
717 #else
718 /*
719  * static int filecore_checksum(u_char *bootblock)
720  *
721  * Calculates the filecore boot block checksum. This is used to validate
722  * a filecore boot block on the disk.  If a boot block is validated then
723  * it is used to locate the partition table. If the boot block is not
724  * validated, it is assumed that the whole disk is NetBSD.
725  *
726  * The basic algorithm is:
727  *
728  *	for (each byte in block, excluding checksum) {
729  *		sum += byte;
730  *		if (sum > 255)
731  *			sum -= 255;
732  *	}
733  *
734  * That's equivalent to summing all of the bytes in the block
735  * (excluding the checksum byte, of course), then calculating the
736  * checksum as "cksum = sum - ((sum - 1) / 255) * 255)".  That
737  * expression may or may not yield a faster checksum function,
738  * but it's easier to reason about.
739  *
740  * Note that if you have a block filled with bytes of a single
741  * value "X" (regardless of that value!) and calculate the cksum
742  * of the block (excluding the checksum byte), you will _always_
743  * end up with a checksum of X.  (Do the math; that can be derived
744  * from the checksum calculation function!)  That means that
745  * blocks which contain bytes which all have the same value will
746  * always checksum properly.  That's a _very_ unlikely occurence
747  * (probably impossible, actually) for a valid filecore boot block,
748  * so we treat such blocks as invalid.
749  */
750 static int
751 filecore_checksum(u_char *bootblock)
752 {
753 	u_char	byte0, accum_diff;
754 	u_int	sum;
755 	int	i;
756 
757 	sum = 0;
758 	accum_diff = 0;
759 	byte0 = bootblock[0];
760 
761 	/*
762 	 * Sum the contents of the block, keeping track of whether
763 	 * or not all bytes are the same.  If 'accum_diff' ends up
764 	 * being zero, all of the bytes are, in fact, the same.
765 	 */
766 	for (i = 0; i < 511; ++i) {
767 		sum += bootblock[i];
768 		accum_diff |= bootblock[i] ^ byte0;
769 	}
770 
771 	/*
772 	 * Check to see if the checksum byte is the same as the
773 	 * rest of the bytes, too.  (Note that if all of the bytes
774 	 * are the same except the checksum, a checksum compare
775 	 * won't succeed, but that's not our problem.)
776 	 */
777 	accum_diff |= bootblock[i] ^ byte0;
778 
779 	/* All bytes in block are the same; call it invalid. */
780 	if (accum_diff == 0)
781 		return (-1);
782 
783 	return (sum - ((sum - 1) / 255) * 255);
784 }
785 
786 /*
787  * Check for the presence of a RiscOS filecore boot block
788  * indicating an ADFS file system on the disc.
789  * Return the offset to the NetBSD part of the disc if
790  * this can be determined.
791  * This routine will terminate disklabel if the disc
792  * is found to be ADFS only.
793  */
794 static u_int
795 get_filecore_partition(int f)
796 {
797 	struct filecore_bootblock	*fcbb;
798 	static u_char	bb[DEV_BSIZE];
799 	u_int		offset;
800 	struct riscix_partition_table	*riscix_part;
801 	int		loop;
802 
803 	if (pread(f, bb, sizeof(bb), (off_t)FILECORE_BOOT_SECTOR * DEV_BSIZE) != sizeof(bb))
804 		err(4, "can't read filecore boot block");
805 	fcbb = (struct filecore_bootblock *)bb;
806 
807 	/* Check if table is valid. */
808 	if (filecore_checksum(bb) != fcbb->checksum)
809 		return (0);
810 
811 	/*
812 	 * Check for NetBSD/arm32 (RiscBSD) partition marker.
813 	 * If found the NetBSD disklabel location is easy.
814 	 */
815 	offset = (fcbb->partition_cyl_low + (fcbb->partition_cyl_high << 8))
816 	    * fcbb->heads * fcbb->secspertrack;
817 
818 	switch (fcbb->partition_type) {
819 
820 	case PARTITION_FORMAT_RISCBSD:
821 		return (offset);
822 
823 	case PARTITION_FORMAT_RISCIX:
824 		/*
825 		 * Read the RISCiX partition table and search for the
826 		 * first partition named "RiscBSD", "NetBSD", or "Empty:"
827 		 *
828 		 * XXX is use of 'Empty:' really desirable?! -- cgd
829 		 */
830 
831 		if (pread(f, bb, sizeof(bb), (off_t)offset * DEV_BSIZE) != sizeof(bb))
832 			err(4, "can't read riscix partition table");
833 		riscix_part = (struct riscix_partition_table *)bb;
834 
835 		for (loop = 0; loop < NRISCIX_PARTITIONS; ++loop) {
836 			if (strcmp((char *)riscix_part->partitions[loop].rp_name,
837 				    "RiscBSD") == 0 ||
838 			    strcmp((char *)riscix_part->partitions[loop].rp_name,
839 				    "NetBSD") == 0 ||
840 			    strcmp((char *)riscix_part->partitions[loop].rp_name,
841 				    "Empty:") == 0) {
842 				return riscix_part->partitions[loop].rp_start;
843 				break;
844 			}
845 		}
846 		/*
847 		 * Valid filecore boot block, RISCiX partition table
848 		 * but no NetBSD partition. We should leave this
849 		 * disc alone.
850 		 */
851 		errx(4, "cannot label: no NetBSD partition found"
852 			" in RISCiX partition table");
853 
854 	default:
855 		/*
856 		 * Valid filecore boot block and no non-ADFS partition.
857 		 * This means that the whole disc is allocated for ADFS
858 		 * so do not trash ! If the user really wants to put a
859 		 * NetBSD disklabel on the disc then they should remove
860 		 * the filecore boot block first with dd.
861 		 */
862 		errx(4, "cannot label: filecore-only disk"
863 			" (no non-ADFS partition)");
864 	}
865 	return (0);
866 }
867 #endif	/* USE_ACORN */
868 
869 /*
870  * Fetch disklabel for disk to 'lab'.
871  * Use ioctl to get label unless -r flag is given.
872  */
873 static void
874 readlabel(int f)
875 {
876 	if (rflag) {
877 		/* Get label directly from disk */
878 		if (readlabel_direct(f) == 0)
879 			return;
880 		/*
881 		 * There was no label on the disk. Get the fictious one
882 		 * as a basis for initialisation.
883 		 */
884 		if (!Fflag && Iflag && (dk_ioctl(f, DIOCGDINFO, &lab) == 0 ||
885 		    dk_ioctl(f, DIOCGDEFLABEL, &lab) == 0))
886 			return;
887 	} else {
888 		/* Get label from kernel. */
889 		if (dk_ioctl(f, DIOCGDINFO, &lab) < 0)
890 			err(4, "ioctl DIOCGDINFO");
891 		return;
892 	}
893 
894 	if (read_all == 2)
895 		/* We actually found one, and printed it... */
896 		exit(0);
897 	errx(1, "could not read existing label");
898 }
899 
900 /*
901  * Reading the label from the disk is largely a case of 'hunt the label'.
902  * and since different architectures default to different places there
903  * could even be more than one label that contradict each other!
904  * For now we look in the expected place, then search through likely
905  * other locations.
906  */
907 static struct disklabel *
908 find_label(int f, u_int sector)
909 {
910 	struct disklabel *lp;
911 	int i, offset;
912 	const char *is_deleted;
913 
914 	bootarea_len = pread(f, bootarea, sizeof bootarea,
915 	    sector * (off_t)DEV_BSIZE);
916 	if (bootarea_len <= 0) {
917 		if (verbose)
918 			warn("failed to read bootarea from sector %u", sector);
919 		return NULL;
920 	}
921 
922 	if (verbose > 2)
923 		warnx("read sector %u len %u looking for label",
924 		    sector, bootarea_len);
925 
926 	/* Check expected offset first */
927 	for (offset = LABEL_OFFSET, i = -4;; offset = i += 4) {
928 		is_deleted = "";
929 		lp = (void *)(bootarea + offset);
930 		if (i == LABEL_OFFSET)
931 			continue;
932 		if ((char *)(lp + 1) > bootarea + bootarea_len)
933 			break;
934 		if (lp->d_magic2 != lp->d_magic)
935 			continue;
936 		if (read_all && (lp->d_magic == DISKMAGIC_DELETED ||
937 		    lp->d_magic == DISKMAGIC_DELETED_REV)) {
938 			lp->d_magic ^= ~0u;
939 			lp->d_magic2 ^= ~0u;
940 			is_deleted = "deleted ";
941 		}
942 		if (lp->d_magic != DISKMAGIC) {
943 			/* XXX: Do something about byte-swapped labels ? */
944 			if (lp->d_magic == DISKMAGIC_REV &&
945 			    lp->d_magic2 == DISKMAGIC_REV)
946 				warnx("ignoring %sbyteswapped label"
947 				    " at offset %u from sector %u",
948 				    is_deleted, offset, sector);
949 			continue;
950 		}
951 		if (lp->d_npartitions > MAXPARTITIONS || dkcksum(lp) != 0) {
952 			if (verbose > 0)
953 				warnx("corrupt label found at offset %u in "
954 				    "sector %u", offset, sector);
955 			continue;
956 		}
957 		if (verbose > 1)
958 			warnx("%slabel found at offset %u from sector %u",
959 			    is_deleted, offset, sector);
960 		if (!read_all)
961 			return lp;
962 
963 		/* To print all the labels we have to do it here */
964 		/* XXX: maybe we should compare them? */
965 		printf("# %ssector %u offset %u bytes\n",
966 		    is_deleted, sector, offset);
967 		if (tflag)
968 			makedisktab(stdout, lp);
969 		else {
970 			showinfo(stdout, lp, specname);
971 			showpartitions(stdout, lp, Cflag);
972 		}
973 		checklabel(lp);
974 		/* Remember we've found a label */
975 		read_all = 2;
976 	}
977 	return NULL;
978 }
979 
980 static void
981 write_bootarea(int f, u_int sector)
982 {
983 	int wlen;
984 
985 	if (bootarea_len <= 0)
986 		errx(1, "attempting to write after failed read");
987 
988 #ifdef __alpha__
989 	/*
990 	 * The Alpha requires that the boot block be checksummed.
991 	 * The NetBSD/alpha disklabel.h provides a macro to do it.
992 	 */
993 	if (sector == 0) {
994 		struct alpha_boot_block *bb;
995 
996 		bb = (struct alpha_boot_block *)(void *)bootarea;
997 		bb->bb_cksum = 0;
998 		ALPHA_BOOT_BLOCK_CKSUM(bb, &bb->bb_cksum);
999 	}
1000 #endif	/* __alpha__ */
1001 
1002 	wlen = pwrite(f, bootarea, bootarea_len, sector * (off_t)DEV_BSIZE);
1003 	if (wlen == bootarea_len)
1004 		return;
1005 	if (wlen == -1)
1006 		err(1, "disklabel write (sector %u) size %u failed",
1007 		    sector, bootarea_len);
1008 	errx(1, "disklabel write (sector %u) size %u truncated to %d",
1009 		    sector, bootarea_len, wlen);
1010 }
1011 
1012 static int
1013 update_label(int f, u_int label_sector, u_int label_offset)
1014 {
1015 	struct disklabel *disk_lp;
1016 
1017 	disk_lp = find_label(f, label_sector);
1018 
1019 	if (disk_lp && Dflag) {
1020 		/* Invalidate the existing label */
1021 		disk_lp->d_magic ^= ~0u;
1022 		disk_lp->d_magic2 ^= ~0u;
1023 		if (Dflag == 2)
1024 			write_bootarea(f, label_sector);
1025 		/* Force label to default location */
1026 		disk_lp = NULL;
1027 	}
1028 
1029 	if (Dflag == 2)
1030 		/* We are just deleting the label */
1031 		return 0;
1032 
1033 	if (disk_lp == NULL) {
1034 		if (label_offset == ~0u)
1035 			return 0;
1036 		/* Nothing on the disk - we need to add it */
1037 		disk_lp = (void *)(bootarea + label_offset);
1038 		if ((char *)(disk_lp + 1) > bootarea + bootarea_len)
1039 			errx(1, "no space in bootarea (sector %u) "
1040 			    "to create label", label_sector);
1041 	}
1042 
1043 	*disk_lp = lab;
1044 	write_bootarea(f, label_sector);
1045 	return 1;
1046 }
1047 
1048 static void
1049 writelabel_direct(int f)
1050 {
1051 	u_int label_sector;
1052 	int written = 0;
1053 	int rval;
1054 
1055 	label_sector = get_filecore_partition(f);
1056 	if (label_sector != 0)
1057 		/* The offset needs to be that from the acorn ports... */
1058 		written = update_label(f, label_sector, DEV_BSIZE);
1059 
1060 	rval = process_mbr(f, writelabel_mbr);
1061 
1062 	if (rval == 2 || written)
1063 		/* Don't add a label to sector 0, but update one if there */
1064 		update_label(f, 0, ~0u);
1065 	else
1066 		update_label(f, 0, LABEL_OFFSET);
1067 }
1068 
1069 static int
1070 readlabel_direct(int f)
1071 {
1072 	struct disklabel *disk_lp;
1073 	u_int filecore_partition_offset;
1074 
1075 	filecore_partition_offset = get_filecore_partition(f);
1076 	if (filecore_partition_offset != 0) {
1077 		disk_lp = find_label(f, filecore_partition_offset);
1078 		if (disk_lp != NULL) {
1079 			lab = *disk_lp;
1080 			return 0;
1081 		}
1082 	}
1083 
1084 	if (mflag && process_mbr(f, readlabel_mbr) == 0)
1085 		return 0;
1086 
1087 	disk_lp = find_label(f, 0);
1088 	if (disk_lp != NULL) {
1089 		lab = *disk_lp;
1090 		return 0;
1091 	}
1092 
1093 	if (!mflag && process_mbr(f, readlabel_mbr) == 0)
1094 		return 0;
1095 
1096 	return 1;
1097 }
1098 
1099 static void
1100 makedisktab(FILE *f, struct disklabel *lp)
1101 {
1102 	int	 i;
1103 	const char *did;
1104 	struct partition *pp;
1105 
1106 	did = "\\\n\t:";
1107 	(void) fprintf(f, "%.*s|Automatically generated label:\\\n\t:dt=",
1108 	    (int) sizeof(lp->d_typename), lp->d_typename);
1109 	if ((unsigned) lp->d_type < DKMAXTYPES)
1110 		(void) fprintf(f, "%s:", dktypenames[lp->d_type]);
1111 	else
1112 		(void) fprintf(f, "unknown%d:", lp->d_type);
1113 
1114 	(void) fprintf(f, "se#%d:", lp->d_secsize);
1115 	(void) fprintf(f, "ns#%d:", lp->d_nsectors);
1116 	(void) fprintf(f, "nt#%d:", lp->d_ntracks);
1117 	(void) fprintf(f, "sc#%d:", lp->d_secpercyl);
1118 	(void) fprintf(f, "nc#%d:", lp->d_ncylinders);
1119 
1120 	if ((lp->d_secpercyl * lp->d_ncylinders) != lp->d_secperunit) {
1121 		(void) fprintf(f, "%ssu#%d:", did, lp->d_secperunit);
1122 		did = "";
1123 	}
1124 	if (lp->d_rpm != 3600) {
1125 		(void) fprintf(f, "%srm#%d:", did, lp->d_rpm);
1126 		did = "";
1127 	}
1128 	if (lp->d_interleave != 1) {
1129 		(void) fprintf(f, "%sil#%d:", did, lp->d_interleave);
1130 		did = "";
1131 	}
1132 	if (lp->d_trackskew != 0) {
1133 		(void) fprintf(f, "%ssk#%d:", did, lp->d_trackskew);
1134 		did = "";
1135 	}
1136 	if (lp->d_cylskew != 0) {
1137 		(void) fprintf(f, "%scs#%d:", did, lp->d_cylskew);
1138 		did = "";
1139 	}
1140 	if (lp->d_headswitch != 0) {
1141 		(void) fprintf(f, "%shs#%d:", did, lp->d_headswitch);
1142 		did = "";
1143 	}
1144 	if (lp->d_trkseek != 0) {
1145 		(void) fprintf(f, "%sts#%d:", did, lp->d_trkseek);
1146 		did = "";
1147 	}
1148 #ifdef notyet
1149 	(void) fprintf(f, "drivedata: ");
1150 	for (i = NDDATA - 1; i >= 0; i--)
1151 		if (lp->d_drivedata[i])
1152 			break;
1153 	if (i < 0)
1154 		i = 0;
1155 	for (j = 0; j <= i; j++)
1156 		(void) fprintf(f, "%d ", lp->d_drivedata[j]);
1157 #endif	/* notyet */
1158 	pp = lp->d_partitions;
1159 	for (i = 0; i < lp->d_npartitions; i++, pp++) {
1160 		if (pp->p_size) {
1161 			char c = 'a' + i;
1162 			(void) fprintf(f, "\\\n\t:");
1163 			(void) fprintf(f, "p%c#%d:", c, pp->p_size);
1164 			(void) fprintf(f, "o%c#%d:", c, pp->p_offset);
1165 			if (pp->p_fstype != FS_UNUSED) {
1166 				if ((unsigned) pp->p_fstype < FSMAXTYPES)
1167 					(void) fprintf(f, "t%c=%s:", c,
1168 					    fstypenames[pp->p_fstype]);
1169 				else
1170 					(void) fprintf(f, "t%c=unknown%d:",
1171 					    c, pp->p_fstype);
1172 			}
1173 			switch (pp->p_fstype) {
1174 
1175 			case FS_UNUSED:
1176 				break;
1177 
1178 			case FS_BSDFFS:
1179 			case FS_BSDLFS:
1180 			case FS_EX2FS:
1181 			case FS_ADOS:
1182 			case FS_APPLEUFS:
1183 				(void) fprintf(f, "b%c#%d:", c,
1184 				    pp->p_fsize * pp->p_frag);
1185 				(void) fprintf(f, "f%c#%d:", c, pp->p_fsize);
1186 				break;
1187 			default:
1188 				break;
1189 			}
1190 		}
1191 	}
1192 	(void) fprintf(f, "\n");
1193 	(void) fflush(f);
1194 }
1195 
1196 static int
1197 edit(int f)
1198 {
1199 	const char *tmpdir;
1200 	char	tmpfil[MAXPATHLEN];
1201 	int	 first, ch, fd;
1202 	int	get_ok;
1203 	FILE	*fp;
1204 
1205 	if ((tmpdir = getenv("TMPDIR")) == NULL)
1206 		tmpdir = _PATH_TMP;
1207 	(void)snprintf(tmpfil, sizeof(tmpfil), "%s/%s", tmpdir, TMPFILE);
1208 	if ((fd = mkstemp(tmpfil)) == -1 || (fp = fdopen(fd, "w")) == NULL) {
1209 		warn("%s", tmpfil);
1210 		return (1);
1211 	}
1212 	(void)fchmod(fd, 0600);
1213 	showinfo(fp, &lab, specname);
1214 	showpartitions(fp, &lab, Cflag);
1215 	(void) fclose(fp);
1216 	for (;;) {
1217 		if (!editit(tmpfil))
1218 			break;
1219 		fp = fopen(tmpfil, "r");
1220 		if (fp == NULL) {
1221 			warn("%s", tmpfil);
1222 			break;
1223 		}
1224 		(void) memset(&lab, 0, sizeof(lab));
1225 		get_ok = getasciilabel(fp, &lab);
1226 		fclose(fp);
1227 		if (get_ok && write_label(f) == 0) {
1228 			(void) unlink(tmpfil);
1229 			return (0);
1230 		}
1231 		(void) printf("re-edit the label? [y]: ");
1232 		(void) fflush(stdout);
1233 		first = ch = getchar();
1234 		while (ch != '\n' && ch != EOF)
1235 			ch = getchar();
1236 		if (first == 'n' || first == 'N')
1237 			break;
1238 	}
1239 	(void)unlink(tmpfil);
1240 	return (1);
1241 }
1242 
1243 static int
1244 editit(const char *tmpfil)
1245 {
1246 	int pid, xpid;
1247 	int status;
1248 	sigset_t nsigset, osigset;
1249 
1250 	sigemptyset(&nsigset);
1251 	sigaddset(&nsigset, SIGINT);
1252 	sigaddset(&nsigset, SIGQUIT);
1253 	sigaddset(&nsigset, SIGHUP);
1254 	sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1255 	while ((pid = fork()) < 0) {
1256 		if (errno != EAGAIN) {
1257 			sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1258 			warn("fork");
1259 			return (0);
1260 		}
1261 		sleep(1);
1262 	}
1263 	if (pid == 0) {
1264 		const char *ed;
1265 		char *buf;
1266 		int retval;
1267 
1268 		sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1269 		setgid(getgid());
1270 		setuid(getuid());
1271 		if ((ed = getenv("EDITOR")) == (char *)0)
1272 			ed = DEFEDITOR;
1273 		/*
1274 		 * Jump through a few extra hoops in case someone's editor
1275 		 * is "editor arg1 arg2".
1276 		 */
1277 		asprintf(&buf, "%s %s", ed, tmpfil);
1278 		if (!buf)
1279 			err(1, "malloc");
1280 		retval = execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", buf, NULL);
1281 		if (retval == -1)
1282 			perror(ed);
1283 		exit(retval);
1284 	}
1285 	while ((xpid = wait(&status)) >= 0)
1286 		if (xpid == pid)
1287 			break;
1288 	sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1289 	return (!status);
1290 }
1291 
1292 static char *
1293 skip(char *cp)
1294 {
1295 
1296 	cp += strspn(cp, " \t");
1297 	if (*cp == '\0')
1298 		return (NULL);
1299 	return (cp);
1300 }
1301 
1302 static char *
1303 word(char *cp)
1304 {
1305 
1306 	if (cp == NULL || *cp == '\0')
1307 		return (NULL);
1308 
1309 	cp += strcspn(cp, " \t");
1310 	if (*cp == '\0')
1311 		return (NULL);
1312 	*cp++ = '\0';
1313 	cp += strspn(cp, " \t");
1314 	if (*cp == '\0')
1315 		return (NULL);
1316 	return (cp);
1317 }
1318 
1319 #define _CHECKLINE \
1320 	if (tp == NULL || *tp == '\0') {			\
1321 		warnx("line %d: too few fields", lineno);	\
1322 		errors++;					\
1323 		break;						\
1324 	}
1325 
1326 #define __CHECKLINE \
1327 	if (*tp == NULL || **tp == '\0') {			\
1328 		warnx("line %d: too few fields", lineno);	\
1329 		*tp = _error_;					\
1330 		return 0;					\
1331 	}
1332 
1333 static char _error_[] = "";
1334 #define NXTNUM(n)	if ((n = nxtnum(&tp, lineno),0) + tp != _error_) \
1335 			; else goto error
1336 #define NXTXNUM(n)	if ((n = nxtxnum(&tp, lp, lineno),0) + tp != _error_) \
1337 			; else goto error
1338 
1339 static unsigned long
1340 nxtnum(char **tp, int lineno)
1341 {
1342 	char *cp;
1343 	unsigned long v;
1344 
1345 	__CHECKLINE
1346 	if (getulong(*tp, '\0', &cp, &v, UINT32_MAX) != 0) {
1347 		warnx("line %d: syntax error", lineno);
1348 		*tp = _error_;
1349 		return 0;
1350 	}
1351 	*tp = cp;
1352 	return v;
1353 }
1354 
1355 static unsigned long
1356 nxtxnum(char **tp, struct disklabel *lp, int lineno)
1357 {
1358 	char	*cp, *ncp;
1359 	unsigned long n, v;
1360 
1361 	__CHECKLINE
1362 	cp = *tp;
1363 	if (getulong(cp, '/', &ncp, &n, UINT32_MAX) != 0)
1364 		goto bad;
1365 
1366 	if (*ncp == '/') {
1367 		n *= lp->d_secpercyl;
1368 		cp = ncp + 1;
1369 		if (getulong(cp, '/', &ncp, &v, UINT32_MAX) != 0)
1370 			goto bad;
1371 		n += v * lp->d_nsectors;
1372 		cp = ncp + 1;
1373 		if (getulong(cp, '\0', &ncp, &v, UINT32_MAX) != 0)
1374 			goto bad;
1375 		n += v;
1376 	}
1377 	*tp = ncp;
1378 	return n;
1379 bad:
1380 	warnx("line %d: invalid format", lineno);
1381 	*tp = _error_;
1382 	return 0;
1383 }
1384 
1385 /*
1386  * Read an ascii label in from fd f,
1387  * in the same format as that put out by showinfo() and showpartitions(),
1388  * and fill in lp.
1389  */
1390 static int
1391 getasciilabel(FILE *f, struct disklabel *lp)
1392 {
1393 	const char *const *cpp, *s;
1394 	struct partition *pp;
1395 	char	*cp, *tp, line[BUFSIZ], tbuf[15];
1396 	int	 lineno, errors;
1397 	unsigned long v;
1398 	unsigned int part;
1399 
1400 	lineno = 0;
1401 	errors = 0;
1402 	lp->d_bbsize = BBSIZE;				/* XXX */
1403 	lp->d_sbsize = SBLOCKSIZE;			/* XXX */
1404 	while (fgets(line, sizeof(line) - 1, f)) {
1405 		lineno++;
1406 		if ((cp = strpbrk(line, "#\r\n")) != NULL)
1407 			*cp = '\0';
1408 		cp = skip(line);
1409 		if (cp == NULL)     /* blank line or comment line */
1410 			continue;
1411 		tp = strchr(cp, ':'); /* everything has a colon in it */
1412 		if (tp == NULL) {
1413 			warnx("line %d: syntax error", lineno);
1414 			errors++;
1415 			continue;
1416 		}
1417 		*tp++ = '\0', tp = skip(tp);
1418 		if (!strcmp(cp, "type")) {
1419 			if (tp == NULL) {
1420 				strlcpy(tbuf, "unknown", sizeof(tbuf));
1421 				tp = tbuf;
1422 			}
1423 			cpp = dktypenames;
1424 			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
1425 				if ((s = *cpp) && !strcasecmp(s, tp)) {
1426 					lp->d_type = cpp - dktypenames;
1427 					goto next;
1428 				}
1429 			if (GETNUM16(tp, &v) != 0) {
1430 				warnx("line %d: syntax error", lineno);
1431 				errors++;
1432 				continue;
1433 			}
1434 			if (v >= DKMAXTYPES)
1435 				warnx("line %d: warning, unknown disk type: %s",
1436 				    lineno, tp);
1437 			lp->d_type = v;
1438 			continue;
1439 		}
1440 		if (!strcmp(cp, "flags")) {
1441 			for (v = 0; (cp = tp) && *cp != '\0';) {
1442 				tp = word(cp);
1443 				if (!strcasecmp(cp, "removable"))
1444 					v |= D_REMOVABLE;
1445 				else if (!strcasecmp(cp, "ecc"))
1446 					v |= D_ECC;
1447 				else if (!strcasecmp(cp, "badsect"))
1448 					v |= D_BADSECT;
1449 				else {
1450 					warnx("line %d: bad flag: %s",
1451 					    lineno, cp);
1452 					errors++;
1453 				}
1454 			}
1455 			lp->d_flags = v;
1456 			continue;
1457 		}
1458 		if (!strcmp(cp, "drivedata")) {
1459 			int i;
1460 
1461 			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
1462 				if (GETNUM32(cp, &v) != 0) {
1463 					warnx("line %d: bad drive data",
1464 					    lineno);
1465 					errors++;
1466 				} else
1467 					lp->d_drivedata[i] = v;
1468 				i++;
1469 				tp = word(cp);
1470 			}
1471 			continue;
1472 		}
1473 		if (sscanf(cp, "%lu partitions", &v) == 1) {
1474 			if (v == 0 || v > MAXPARTITIONS) {
1475 				warnx("line %d: bad # of partitions", lineno);
1476 				lp->d_npartitions = MAXPARTITIONS;
1477 				errors++;
1478 			} else
1479 				lp->d_npartitions = v;
1480 			continue;
1481 		}
1482 		if (tp == NULL) {
1483 			tbuf[0] = '\0';
1484 			tp = tbuf;
1485 		}
1486 		if (!strcmp(cp, "disk")) {
1487 			strncpy(lp->d_typename, tp, sizeof(lp->d_typename));
1488 			continue;
1489 		}
1490 		if (!strcmp(cp, "label")) {
1491 			strncpy(lp->d_packname, tp, sizeof(lp->d_packname));
1492 			continue;
1493 		}
1494 		if (!strcmp(cp, "bytes/sector")) {
1495 			if (GETNUM32(tp, &v) != 0 || v <= 0 || (v % 512) != 0) {
1496 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1497 				errors++;
1498 			} else
1499 				lp->d_secsize = v;
1500 			continue;
1501 		}
1502 		if (!strcmp(cp, "sectors/track")) {
1503 			if (GETNUM32(tp, &v) != 0) {
1504 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1505 				errors++;
1506 			} else
1507 				lp->d_nsectors = v;
1508 			continue;
1509 		}
1510 		if (!strcmp(cp, "sectors/cylinder")) {
1511 			if (GETNUM32(tp, &v) != 0) {
1512 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1513 				errors++;
1514 			} else
1515 				lp->d_secpercyl = v;
1516 			continue;
1517 		}
1518 		if (!strcmp(cp, "tracks/cylinder")) {
1519 			if (GETNUM32(tp, &v) != 0) {
1520 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1521 				errors++;
1522 			} else
1523 				lp->d_ntracks = v;
1524 			continue;
1525 		}
1526 		if (!strcmp(cp, "cylinders")) {
1527 			if (GETNUM32(tp, &v) != 0) {
1528 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1529 				errors++;
1530 			} else
1531 				lp->d_ncylinders = v;
1532 			continue;
1533 		}
1534 		if (!strcmp(cp, "total sectors") ||
1535 		    !strcmp(cp, "sectors/unit")) {
1536 			if (GETNUM32(tp, &v) != 0) {
1537 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1538 				errors++;
1539 			} else
1540 				lp->d_secperunit = v;
1541 			continue;
1542 		}
1543 		if (!strcmp(cp, "rpm")) {
1544 			if (GETNUM16(tp, &v) != 0) {
1545 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1546 				errors++;
1547 			} else
1548 				lp->d_rpm = v;
1549 			continue;
1550 		}
1551 		if (!strcmp(cp, "interleave")) {
1552 			if (GETNUM16(tp, &v) != 0) {
1553 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1554 				errors++;
1555 			} else
1556 				lp->d_interleave = v;
1557 			continue;
1558 		}
1559 		if (!strcmp(cp, "trackskew")) {
1560 			if (GETNUM16(tp, &v) != 0) {
1561 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1562 				errors++;
1563 			} else
1564 				lp->d_trackskew = v;
1565 			continue;
1566 		}
1567 		if (!strcmp(cp, "cylinderskew")) {
1568 			if (GETNUM16(tp, &v) != 0) {
1569 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1570 				errors++;
1571 			} else
1572 				lp->d_cylskew = v;
1573 			continue;
1574 		}
1575 		if (!strcmp(cp, "headswitch")) {
1576 			if (GETNUM32(tp, &v) != 0) {
1577 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1578 				errors++;
1579 			} else
1580 				lp->d_headswitch = v;
1581 			continue;
1582 		}
1583 		if (!strcmp(cp, "track-to-track seek")) {
1584 			if (GETNUM32(tp, &v) != 0) {
1585 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1586 				errors++;
1587 			} else
1588 				lp->d_trkseek = v;
1589 			continue;
1590 		}
1591 		if ('a' > *cp || *cp > 'z' || cp[1] != '\0') {
1592 			warnx("line %d: unknown field: %s", lineno, cp);
1593 			errors++;
1594 			continue;
1595 		}
1596 
1597 		/* We have a partition entry */
1598 		part = *cp - 'a';
1599 
1600 		if (part >= MAXPARTITIONS) {
1601 			warnx("line %d: bad partition name: %s", lineno, cp);
1602 			errors++;
1603 			continue;
1604 		}
1605 		pp = &lp->d_partitions[part];
1606 
1607 		NXTXNUM(pp->p_size);
1608 		NXTXNUM(pp->p_offset);
1609 		/* can't use word() here because of blanks in fstypenames[] */
1610 		tp += strspn(tp, " \t");
1611 		_CHECKLINE
1612 		cp = tp;
1613 		cpp = fstypenames;
1614 		for (; cpp < &fstypenames[FSMAXTYPES]; cpp++) {
1615 			s = *cpp;
1616 			if (s == NULL ||
1617 				(cp[strlen(s)] != ' ' &&
1618 				 cp[strlen(s)] != '\t' &&
1619 				 cp[strlen(s)] != '\0'))
1620 				continue;
1621 			if (!memcmp(s, cp, strlen(s))) {
1622 				pp->p_fstype = cpp - fstypenames;
1623 				tp += strlen(s);
1624 				if (*tp == '\0')
1625 					tp = NULL;
1626 				else {
1627 					tp += strspn(tp, " \t");
1628 					if (*tp == '\0')
1629 						tp = NULL;
1630 				}
1631 				goto gottype;
1632 			}
1633 		}
1634 		tp = word(cp);
1635 		if (isdigit(*cp & 0xff)) {
1636 			if (GETNUM8(cp, &v) != 0) {
1637 				warnx("line %d: syntax error", lineno);
1638 				errors++;
1639 			}
1640 		} else
1641 			v = FSMAXTYPES;
1642 		if ((unsigned)v >= FSMAXTYPES) {
1643 			warnx("line %d: warning, unknown file system type: %s",
1644 			    lineno, cp);
1645 			warnx("tip: use -l to see all valid file system "
1646 			    "types");
1647 			v = FS_UNUSED;
1648 		}
1649 		pp->p_fstype = v;
1650 gottype:
1651 		switch (pp->p_fstype) {
1652 
1653 		case FS_UNUSED:				/* XXX */
1654 			NXTNUM(pp->p_fsize);
1655 			if (pp->p_fsize == 0)
1656 				break;
1657 			NXTNUM(v);
1658 			pp->p_frag = v / pp->p_fsize;
1659 			break;
1660 
1661 		case FS_BSDFFS:
1662 		case FS_ADOS:
1663 		case FS_APPLEUFS:
1664 			NXTNUM(pp->p_fsize);
1665 			if (pp->p_fsize == 0)
1666 				break;
1667 			NXTNUM(v);
1668 			pp->p_frag = v / pp->p_fsize;
1669 			NXTNUM(pp->p_cpg);
1670 			break;
1671 		case FS_BSDLFS:
1672 			NXTNUM(pp->p_fsize);
1673 			if (pp->p_fsize == 0)
1674 				break;
1675 			NXTNUM(v);
1676 			pp->p_frag = v / pp->p_fsize;
1677 			NXTNUM(pp->p_sgs);
1678 			break;
1679 		case FS_EX2FS:
1680 			NXTNUM(pp->p_fsize);
1681 			if (pp->p_fsize == 0)
1682 				break;
1683 			NXTNUM(v);
1684 			pp->p_frag = v / pp->p_fsize;
1685 			break;
1686 		case FS_ISO9660:
1687 			NXTNUM(pp->p_cdsession);
1688 			break;
1689 		default:
1690 			break;
1691 		}
1692 		continue;
1693  error:
1694 		errors++;
1695  next:
1696 		;
1697 	}
1698 	errors += checklabel(lp);
1699 	return (errors == 0);
1700 }
1701 
1702 /*
1703  * Check disklabel for errors and fill in
1704  * derived fields according to supplied values.
1705  */
1706 int
1707 checklabel(struct disklabel *lp)
1708 {
1709 	struct partition *pp, *qp;
1710 	int	i, j, errors;
1711 	char	part;
1712 
1713 	errors = 0;
1714 	if (lp->d_secsize == 0) {
1715 		warnx("sector size %d", lp->d_secsize);
1716 		return (1);
1717 	}
1718 	if (lp->d_nsectors == 0) {
1719 		warnx("sectors/track %d", lp->d_nsectors);
1720 		return (1);
1721 	}
1722 	if (lp->d_ntracks == 0) {
1723 		warnx("tracks/cylinder %d", lp->d_ntracks);
1724 		return (1);
1725 	}
1726 	if  (lp->d_ncylinders == 0) {
1727 		warnx("cylinders/unit %d", lp->d_ncylinders);
1728 		errors++;
1729 	}
1730 	if (lp->d_rpm == 0)
1731 		warnx("warning, revolutions/minute %d", lp->d_rpm);
1732 	if (lp->d_secpercyl == 0)
1733 		lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1734 	if (lp->d_secperunit == 0)
1735 		lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1736 	if (lp->d_bbsize == 0) {
1737 		warnx("boot block size %d", lp->d_bbsize);
1738 		errors++;
1739 	} else if (lp->d_bbsize % lp->d_secsize)
1740 		warnx("warning, boot block size %% sector-size != 0");
1741 	if (lp->d_sbsize == 0) {
1742 		warnx("super block size %d", lp->d_sbsize);
1743 		errors++;
1744 	} else if (lp->d_sbsize % lp->d_secsize)
1745 		warnx("warning, super block size %% sector-size != 0");
1746 	if (lp->d_npartitions > MAXPARTITIONS)
1747 		warnx("warning, number of partitions (%d) > MAXPARTITIONS (%d)",
1748 		    lp->d_npartitions, MAXPARTITIONS);
1749 	else
1750 		for (i = MAXPARTITIONS - 1; i >= lp->d_npartitions; i--) {
1751 			part = 'a' + i;
1752 			pp = &lp->d_partitions[i];
1753 			if (pp->p_size || pp->p_offset) {
1754 				warnx("warning, partition %c increased "
1755 				    "number of partitions from %d to %d",
1756 				    part, lp->d_npartitions, i + 1);
1757 				lp->d_npartitions = i + 1;
1758 				break;
1759 			}
1760 		}
1761 	for (i = 0; i < lp->d_npartitions; i++) {
1762 		part = 'a' + i;
1763 		pp = &lp->d_partitions[i];
1764 		if (pp->p_size == 0 && pp->p_offset != 0)
1765 			warnx("warning, partition %c: size 0, but offset %d",
1766 			    part, pp->p_offset);
1767 #ifdef STRICT_CYLINDER_ALIGNMENT
1768 		if (pp->p_offset % lp->d_secpercyl) {
1769 			warnx("warning, partition %c:"
1770 			    " not starting on cylinder boundary",
1771 			    part);
1772 			errors++;
1773 		}
1774 #endif	/* STRICT_CYLINDER_ALIGNMENT */
1775 		if (pp->p_offset > lp->d_secperunit) {
1776 			warnx("partition %c: offset past end of unit", part);
1777 			errors++;
1778 		}
1779 		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1780 			warnx("partition %c: partition extends"
1781 			    " past end of unit",
1782 			    part);
1783 			errors++;
1784 		}
1785 		if (pp->p_fstype != FS_UNUSED)
1786 			for (j = i + 1; j < lp->d_npartitions; j++) {
1787 				qp = &lp->d_partitions[j];
1788 				if (qp->p_fstype == FS_UNUSED)
1789 					continue;
1790 				if (pp->p_offset < qp->p_offset + qp->p_size &&
1791 				    qp->p_offset < pp->p_offset + pp->p_size)
1792 					warnx("partitions %c and %c overlap",
1793 					    part, 'a' + j);
1794 			}
1795 	}
1796 	return (errors);
1797 }
1798 
1799 static void
1800 usage(void)
1801 {
1802 	static const struct {
1803 		const char *name;
1804 		const char *expn;
1805 	} usages[] = {
1806 	{ "[-ACFrtv] disk", "(to read label)" },
1807 	{ "-w [-DFrv] [-f disktab] disk disktype [packid]", "(to write label)" },
1808 	{ "-e [-CDFIrv] disk", "(to edit label)" },
1809 	{ "-i [-DFIrv] disk", "(to create a label interactively)" },
1810 	{ "-D [-v] disk", "(to delete existing label(s))" },
1811 	{ "-R [-DFrv] disk protofile", "(to restore label)" },
1812 	{ "[-NW] disk", "(to write disable/enable label)" },
1813 	{ "-l", "(to show all known file system types)" },
1814 	{ NULL, NULL }
1815 	};
1816 	int i;
1817 	const char *pn = getprogname();
1818 	const char *t = "usage:";
1819 
1820 	for (i = 0; usages[i].name != NULL; i++) {
1821 		(void)fprintf(stderr, "%s %s %s\n\t%s\n",
1822 		    t, pn, usages[i].name, usages[i].expn);
1823 		t = "or";
1824 	}
1825 	exit(1);
1826 }
1827 
1828 static int
1829 getulong(const char *str, char sep, char **epp, unsigned long *ul,
1830     unsigned long max)
1831 {
1832 	char *ep;
1833 
1834 	if (epp == NULL)
1835 		epp = &ep;
1836 
1837 	*ul = strtoul(str, epp, 10);
1838 
1839 	if ((*ul ==  ULONG_MAX && errno == ERANGE) || *ul > max)
1840 		return ERANGE;
1841 
1842 	if (*str == '\0' || (**epp != '\0' && **epp != sep &&
1843 	    !isspace((unsigned char)**epp)))
1844 		return EFTYPE;
1845 
1846 	return 0;
1847 }
1848 
1849 /*
1850  * This is a wrapper over the standard strcmp function to be used with
1851  * qsort on an array of pointers to strings.
1852  */
1853 static int
1854 qsort_strcmp(const void *v1, const void *v2)
1855 {
1856 	const char *const *sp1 = (const char *const *)v1;
1857 	const char *const *sp2 = (const char *const *)v2;
1858 
1859 	return strcmp(*sp1, *sp2);
1860 }
1861 
1862 /*
1863  * Prints all know file system types for a partition.
1864  * Returns 1 on success, 0 on failure.
1865  */
1866 int
1867 list_fs_types(void)
1868 {
1869 	int ret;
1870 	size_t nelems;
1871 
1872 	nelems = 0;
1873 	{
1874 		const char *const *namep;
1875 
1876 		namep = fstypenames;
1877 		while (*namep++ != NULL)
1878 			nelems++;
1879 	}
1880 
1881 	ret = 1;
1882 	if (nelems > 0) {
1883 		const char **list;
1884 		size_t i;
1885 
1886 		list = (const char **)malloc(sizeof(char *) * nelems);
1887 		if (list == NULL) {
1888 			warnx("sorry, could not allocate memory for list");
1889 			ret = 0;
1890 		} else {
1891 			for (i = 0; i < nelems; i++)
1892 				list[i] = fstypenames[i];
1893 
1894 			qsort(list, nelems, sizeof(char *), qsort_strcmp);
1895 
1896 			for (i = 0; i < nelems; i++)
1897 				(void)printf("%s\n", list[i]);
1898 
1899 			free(list);
1900 		}
1901 	}
1902 
1903 	return ret;
1904 }
1905