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