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