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