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