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