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