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