Home | History | Annotate | Line # | Download | only in fdisk
fdisk.c revision 1.155
      1 /*	$NetBSD: fdisk.c,v 1.155 2018/08/27 14:55:46 sevan Exp $ */
      2 
      3 /*
      4  * Mach Operating System
      5  * Copyright (c) 1992 Carnegie Mellon University
      6  * All Rights Reserved.
      7  *
      8  * Permission to use, copy, modify and distribute this software and its
      9  * documentation is hereby granted, provided that both the copyright
     10  * notice and this permission notice appear in all copies of the
     11  * software, derivative works or modified versions, and any portions
     12  * thereof, and that both notices appear in supporting documentation.
     13  *
     14  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     15  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
     16  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     17  *
     18  * Carnegie Mellon requests users of this software to return to
     19  *
     20  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     21  *  School of Computer Science
     22  *  Carnegie Mellon University
     23  *  Pittsburgh PA 15213-3890
     24  *
     25  * any improvements or extensions that they make and grant Carnegie Mellon
     26  * the rights to redistribute these changes.
     27  */
     28 
     29 /*
     30  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
     31  *	Copyright (c) 1989	Robert. V. Baron
     32  *	Created.
     33  */
     34 
     35 #if HAVE_NBTOOL_CONFIG_H
     36 #include "nbtool_config.h"
     37 #endif
     38 
     39 #include <sys/cdefs.h>
     40 
     41 #ifndef lint
     42 __RCSID("$NetBSD: fdisk.c,v 1.155 2018/08/27 14:55:46 sevan Exp $");
     43 #endif /* not lint */
     44 
     45 #define MBRPTYPENAMES
     46 #include <sys/types.h>
     47 #include <sys/param.h>
     48 #include <sys/stat.h>
     49 #include <ctype.h>
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <paths.h>
     54 #include <stdarg.h>
     55 #include <stddef.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <unistd.h>
     60 #include <vis.h>
     61 #include <zlib.h>
     62 
     63 #if !HAVE_NBTOOL_CONFIG_H
     64 #include <sys/disklabel.h>
     65 #include <sys/disklabel_gpt.h>
     66 #include <sys/bootblock.h>
     67 #include <sys/ioctl.h>
     68 #include <sys/sysctl.h>
     69 #include <disktab.h>
     70 #include <util.h>
     71 #else
     72 #include <nbinclude/sys/disklabel.h>
     73 #include <nbinclude/sys/disklabel_gpt.h>
     74 #include <nbinclude/sys/bootblock.h>
     75 #include "../../include/disktab.h"
     76 /* We enforce -F, so none of these possibly undefined items can be needed */
     77 #define opendisk(path, fl, buf, buflen, cooked) (-1)
     78 #endif /* HAVE_NBTOOL_CONFIG_H */
     79 
     80 #ifndef	DEFAULT_BOOTDIR
     81 #define	DEFAULT_BOOTDIR		"/usr/mdec"
     82 #endif
     83 
     84 #define	LE_MBR_MAGIC		htole16(MBR_MAGIC)
     85 #define	LE_MBR_BS_MAGIC		htole16(MBR_BS_MAGIC)
     86 
     87 #ifdef BOOTSEL
     88 
     89 #define	DEFAULT_BOOTCODE	"mbr"
     90 #define	DEFAULT_BOOTSELCODE	"mbr_bootsel"
     91 #define	DEFAULT_BOOTEXTCODE	"mbr_ext"
     92 
     93 /* Scan values for the various keys we use, as returned by the BIOS */
     94 #define	SCAN_ENTER	0x1c
     95 #define	SCAN_F1		0x3b
     96 #define	SCAN_1		0x2
     97 
     98 
     99 #define	MAX_BIOS_DISKS	16	/* Going beyond F12 is hard though! */
    100 
    101 /* We same the dflt 'boot partition' as a disk block, with some magic values. */
    102 #define DEFAULT_ACTIVE	(~(daddr_t)0)
    103 #define	DEFAULT_DISK(n)	(DEFAULT_ACTIVE - MAX_BIOS_DISKS + (n))
    104 
    105 #endif
    106 
    107 #define GPT_TYPE(offs) ((offs) == GPT_HDR_BLKNO ?  "primary" : "secondary")
    108 
    109 #ifndef PRIdaddr
    110 #define PRIdaddr PRId64
    111 #endif
    112 
    113 #ifndef _PATH_DEFDISK
    114 #define _PATH_DEFDISK	"/dev/rwd0d"
    115 #endif
    116 
    117 struct {
    118 	struct mbr_sector *ptn;		/* array of pbrs */
    119 	daddr_t		base;		/* first sector of ext. ptn */
    120 	daddr_t		limit;		/* last sector of ext. ptn */
    121 	int		num_ptn;	/* number of contained partitions */
    122 	int		ptn_id;		/* entry in mbr */
    123 	int		is_corrupt;	/* 1 if extended chain illegal */
    124 } ext;
    125 
    126 #define LBUF 100
    127 static char lbuf[LBUF];
    128 
    129 static const char *disk = _PATH_DEFDISK;
    130 
    131 static struct disklabel disklabel;		/* disk parameters */
    132 
    133 static struct mbr_sector mboot;
    134 
    135 static const char *boot_dir = DEFAULT_BOOTDIR;
    136 static char *boot_path = NULL;			/* name of file we actually opened */
    137 
    138 #ifdef BOOTSEL
    139 #define BOOTSEL_OPTIONS	"B"
    140 #else
    141 #define BOOTSEL_OPTIONS
    142 #define change_part(e, p, id, st, sz, bm) change__part(e, p, id, st, sz)
    143 #endif
    144 #define OPTIONS	BOOTSEL_OPTIONS "0123FSafiIluvA:b:c:E:r:s:w:z:"
    145 
    146 /*
    147  * Disk geometry and partition alignment.
    148  *
    149  * Modern disks do not have a fixed geomery and will always give a 'faked'
    150  * geometry that matches the ATA standard - max 16 heads and 256 sec/track.
    151  * The ATA geometry allows access to 2^28 sectors (as does LBA mode).
    152  *
    153  * The BIOS calls originally used an 8bit register for cylinder, head and
    154  * sector. Later 2 bits were stolen from the sector number and added to
    155  * cylinder number. The BIOS will translate this faked geometry either to
    156  * the geometry reported by the disk, or do LBA reads (possibly LBA48).
    157  * BIOS CHS reads have all sorts of limits, but 2^24 is absolute.
    158  * For historic reasons the BIOS geometry is the called the dos geometry!
    159  *
    160  * If you know the disks real geometry it is usually worth aligning
    161  * disk partitions to cylinder boundaries (certainly traditional!).
    162  * For 'mbr' disks this has always been done with the BIOS geometry.
    163  * The first track (typically 63 sectors) is reserved because the first
    164  * sector is used for boot code. Similarly the data partition in an
    165  * extended partition will start one track in. If an extended partition
    166  * starts at the beginning of the disk you lose 2 tracks.
    167  *
    168  * However non-magnetic media in particular has physical sectors that are
    169  * not the same size as those reported, so has to do read modify write
    170  * sequences for misaligned transfers. The alignment of partitions to
    171  * cylinder boundaries makes this happen all the time.
    172  *
    173  * It is thus sensible to align partitions on a sensible sector boundary.
    174  * For instance 1MB (2048 sectors).
    175  * Common code can do this by using a geometry with 1 head and 2048
    176  * sectors per track.
    177  */
    178 
    179 /* Disks reported geometry and overall size from device driver */
    180 static unsigned int cylinders, sectors, heads;
    181 static daddr_t disksectors;
    182 #define cylindersectors (heads * sectors)
    183 
    184 /* Geometry from the BIOS */
    185 static unsigned int dos_cylinders;
    186 static unsigned int dos_heads;
    187 static unsigned int dos_sectors;
    188 static daddr_t dos_disksectors;
    189 #define dos_cylindersectors (dos_heads * dos_sectors)
    190 #define dos_totalsectors (dos_heads * dos_sectors * dos_cylinders)
    191 
    192 #define DOSSECT(s,c)	(((s) & 0x3f) | (((c) >> 2) & 0xc0))
    193 #define DOSCYL(c)	((c) & 0xff)
    194 #define SEC_IN_1M (1024 * 1024 / secsize)
    195 #define SEC_TO_MB(sec) ((unsigned int)(((sec) + SEC_IN_1M / 2) / SEC_IN_1M))
    196 #define SEC_TO_CYL(sec) (((sec) + dos_cylindersectors/2) / dos_cylindersectors)
    197 
    198 #define MAXCYL		1024	/* Usual limit is 1023 */
    199 #define	MAXHEAD		256	/* Usual limit is 255 */
    200 #define	MAXSECTOR	63
    201 static int partition = -1;
    202 
    203 /* Alignment of partition, and offset if first sector unusable */
    204 static unsigned int ptn_alignment;	/* default dos_cylindersectors */
    205 static unsigned int ptn_0_offset;	/* default dos_sectors */
    206 
    207 static int fd = -1, wfd = -1, *rfd = &fd;
    208 static char *disk_file = NULL;
    209 static char *disk_type = NULL;
    210 
    211 static int a_flag;		/* set active partition */
    212 static int i_flag;		/* init bootcode */
    213 static int I_flag;		/* ignore errors */
    214 static int u_flag;		/* update partition data */
    215 static int v_flag;		/* more verbose */
    216 static int sh_flag;		/* Output data as shell defines */
    217 static int f_flag;		/* force --not interactive */
    218 static int s_flag;		/* set id,offset,size */
    219 static int b_flag;		/* Set cyl, heads, secs (as c/h/s) */
    220 static int B_flag;		/* Edit/install bootselect code */
    221 static int E_flag;		/* extended partition number */
    222 static int b_cyl, b_head, b_sec;  /* b_flag values. */
    223 
    224 #if !HAVE_NBTOOL_CONFIG_H
    225 static int F_flag = 0;
    226 #else
    227 /* Tool - force 'file' mode to avoid unsupported functions and ioctls */
    228 static int F_flag = 1;
    229 #endif
    230 
    231 static struct gpt_hdr gpt1, gpt2;	/* GUID partition tables */
    232 
    233 static struct mbr_sector bootcode[8192 / sizeof (struct mbr_sector)];
    234 static ssize_t secsize = 512;	/* sector size */
    235 static char *iobuf;		/* buffer for non 512 sector I/O */
    236 static int bootsize;		/* actual size of bootcode */
    237 static int boot_installed;	/* 1 if we've copied code into the mbr */
    238 
    239 #if defined(USE_DISKLIST)
    240 #include <machine/cpu.h>
    241 static struct disklist *dl;
    242 #endif
    243 
    244 
    245 #define KNOWN_SYSIDS	(sizeof(mbr_ptypes)/sizeof(mbr_ptypes[0]))
    246 
    247 __dead static void	usage(void);
    248 static void	print_s0(int);
    249 static void	print_part(struct mbr_sector *, int, daddr_t);
    250 static void	print_mbr_partition(struct mbr_sector *, int, daddr_t, daddr_t, int);
    251 static void	print_pbr(daddr_t, int, uint8_t);
    252 static int	is_all_zero(const unsigned char *, size_t);
    253 static void	printvis(int, const char *, const char *, size_t);
    254 static int	read_boot(const char *, void *, size_t, int);
    255 static void	init_sector0(int);
    256 static void	intuit_translated_geometry(void);
    257 static void	get_bios_geometry(void);
    258 static void	get_extended_ptn(void);
    259 static void	get_ptn_alignmemt(void);
    260 #if defined(USE_DISKLIST)
    261 static void	get_diskname(const char *, char *, size_t);
    262 #endif
    263 static int	change_part(int, int, int, daddr_t, daddr_t, char *);
    264 static void	print_geometry(void);
    265 static int	first_active(void);
    266 static void	change_active(int);
    267 static void	change_bios_geometry(void);
    268 static void	dos(int, unsigned char *, unsigned char *, unsigned char *);
    269 static int	open_disk(int);
    270 static ssize_t	read_disk(daddr_t, void *);
    271 static ssize_t	write_disk(daddr_t, void *);
    272 static int	get_params(void);
    273 static int	read_s0(daddr_t, struct mbr_sector *);
    274 static int	write_mbr(void);
    275 static int	read_gpt(daddr_t, struct gpt_hdr *);
    276 static int	delete_gpt(struct gpt_hdr *);
    277 static int	yesno(const char *, ...) __printflike(1, 2);
    278 static int64_t	decimal(const char *, int64_t, int, int64_t, int64_t);
    279 #define DEC_SEC		1		/* asking for a sector number */
    280 #define	DEC_RND		2		/* round to end of first track */
    281 #define	DEC_RND_0	4		/* convert 0 to size of a track */
    282 #define DEC_RND_DOWN	8		/* subtract 1 track */
    283 #define DEC_RND_DOWN_2	16		/* subtract 2 tracks */
    284 static int	ptn_id(const char *, int *);
    285 static int	type_match(const void *, const void *);
    286 static const char *get_type(int);
    287 static int	get_mapping(int, unsigned int *, unsigned int *, unsigned int *, unsigned long *);
    288 #ifdef BOOTSEL
    289 static daddr_t	configure_bootsel(daddr_t);
    290 static void	install_bootsel(int);
    291 static daddr_t	get_default_boot(void);
    292 static void	set_default_boot(daddr_t);
    293 static void	string(const char *, int, char *);
    294 #endif
    295 
    296 static void
    297 initvar_disk(const char **diskp)
    298 {
    299 #if !HAVE_NBTOOL_CONFIG_H
    300 	int mib[2];
    301 	size_t len;
    302 	char *root_device;
    303 
    304 	mib[0] = CTL_KERN;
    305 	mib[1] = KERN_ROOT_DEVICE;
    306 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1 ||
    307 	    (root_device = malloc(len)) == NULL ||
    308 	    sysctl(mib, 2, root_device, &len, NULL, 0) == -1)
    309 		return;
    310 
    311 	*diskp = root_device;
    312 #endif /* HAVE_NBTOOL_CONFIG_H */
    313 }
    314 
    315 static int
    316 getnum(const char *str, int *num)
    317 {
    318 	char *e;
    319 	long l;
    320 
    321 	errno = 0;
    322 	l = strtol(str, &e, 0);
    323 	if (str[0] == '\0' || *e != '\0')
    324 		return -1;
    325 	if (errno == ERANGE && (l == LONG_MAX || l == LONG_MIN))
    326 		return -1;
    327 	/* XXX: truncation */
    328 	*num = (int)l;
    329 	return 0;
    330 }
    331 
    332 /* [<sysid>][/[<start>][/[<size>][/[<bootmenu>]]]] */
    333 static int
    334 parse_s(char *arg, int *csysid, unsigned *cstart, unsigned *csize,
    335     char **cbootmenu)
    336 {
    337 	char *ptr;
    338 	int num;
    339 
    340 	if ((ptr = strchr(arg, '/')) != NULL)
    341 		*ptr++ = '\0';
    342 
    343 	if (*arg) {
    344 		if (getnum(arg, &num) == -1)
    345 			return -1;
    346 		*csysid = num;
    347 	}
    348 	if (ptr == NULL)
    349 		return 0;
    350 
    351 	arg = ptr;
    352 	if ((ptr = strchr(arg, '/')) != NULL)
    353 		*ptr++ = '\0';
    354 	if (*arg) {
    355 		if (getnum(arg, &num) == -1)
    356 			return -1;
    357 		*cstart = num;
    358 	}
    359 	if (ptr == NULL)
    360 		return 0;
    361 
    362 	arg = ptr;
    363 	if ((ptr = strchr(arg, '/')) != NULL)
    364 		*ptr++ = '\0';
    365 	if (*arg) {
    366 		if (getnum(arg, &num) == -1)
    367 			return -1;
    368 		*csize = num;
    369 	}
    370 	if (ptr != NULL && *ptr)
    371 		*cbootmenu = ptr;
    372 	return 0;
    373 }
    374 
    375 int
    376 main(int argc, char *argv[])
    377 {
    378 	struct stat sb;
    379 	int ch;
    380 	size_t len;
    381 	char *cp;
    382 	int n;
    383 #ifdef BOOTSEL
    384 	daddr_t default_ptn;		/* start sector of default ptn */
    385 #endif
    386 	char *cbootmenu = 0;
    387 
    388 	int csysid;	/* For the s_flag. */
    389 	unsigned int cstart, csize;
    390 	a_flag = u_flag = sh_flag = f_flag = s_flag = b_flag = 0;
    391 	i_flag = B_flag = 0;
    392 	v_flag = 0;
    393 	E_flag = 0;
    394 	csysid = -1;
    395 	cstart = csize = ~0;
    396 	while ((ch = getopt(argc, argv, OPTIONS)) != -1) {
    397 		switch (ch) {
    398 		case '0':
    399 			partition = 0;
    400 			break;
    401 		case '1':
    402 			partition = 1;
    403 			break;
    404 		case '2':
    405 			partition = 2;
    406 			break;
    407 		case '3':
    408 			partition = 3;
    409 			break;
    410 		case 'E':	/* Extended partition number */
    411 			E_flag = 1;
    412 			partition = strtoul(optarg, &cp, 0);
    413 			if (*cp || partition < 0)
    414 				errx(1, "Bad partition number -E %s.", optarg);
    415 			break;
    416 #ifdef BOOTSEL
    417 		case 'B':	/* Bootselect parameters */
    418 			B_flag = 1;
    419 			break;
    420 #endif
    421 		case 'F':	/* device argument is really a file */
    422 			F_flag = 1;
    423 			break;
    424 		case 'S':	/* Output as shell variables */
    425 			sh_flag = 1;
    426 			break;
    427 		case 'a':	/* Set active partition */
    428 			a_flag = 1;
    429 			break;
    430 		case 'f':	/* Non interactive */
    431 			f_flag = 1;
    432 			break;
    433 		case 'i':	/* Always update bootcode */
    434 			i_flag = 1;
    435 			break;
    436 		case 'I':	/* Ignore errors */
    437 			I_flag = 1;
    438 			break;
    439 		case 'l':	/* List known partition types */
    440 			for (len = 0; len < KNOWN_SYSIDS; len++)
    441 				printf("%03d %s\n", mbr_ptypes[len].id,
    442 				    mbr_ptypes[len].name);
    443 			return 0;
    444 		case 'u':	/* Update partition details */
    445 			u_flag = 1;
    446 			break;
    447 		case 'v':	/* Be verbose */
    448 			v_flag++;
    449 			break;
    450 		case 's':	/* Partition details */
    451 			s_flag = 1;
    452 
    453 			if (parse_s(optarg, &csysid, &cstart, &csize,
    454 			    &cbootmenu) == -1)
    455 				errx(1, "Bad argument to the -s flag.");
    456 			break;
    457 		case 'b':	/* BIOS geometry */
    458 			b_flag = 1;
    459 			if (sscanf(optarg, "%d/%d/%d%n", &b_cyl, &b_head,
    460 			    &b_sec, &n) != 3 || optarg[n] != 0)
    461 				errx(1, "Bad argument to the -b flag.");
    462 			if (b_cyl > MAXCYL)
    463 				b_cyl = MAXCYL;
    464 			break;
    465 		case 'A':	/* Partition alignment[/offset] */
    466 			if (sscanf(optarg, "%u%n/%u%n", &ptn_alignment,
    467 				    &n, &ptn_0_offset, &n) < 1
    468 			    || optarg[n] != 0
    469 			    || ptn_0_offset > ptn_alignment)
    470 				errx(1, "Bad argument to the -A flag.");
    471 			if (ptn_0_offset == 0)
    472 				ptn_0_offset = ptn_alignment;
    473 			break;
    474 		case 'c':	/* file/directory containing boot code */
    475 			if (strchr(optarg, '/') != NULL &&
    476 			    stat(optarg, &sb) == 0 &&
    477 			    (sb.st_mode & S_IFMT) == S_IFDIR) {
    478 				boot_dir = optarg;
    479 				break;
    480 			}
    481 			bootsize = read_boot(optarg, bootcode,
    482 						sizeof bootcode, 1);
    483 			i_flag = 1;
    484 			break;
    485 		case 'r':	/* read data from disk_file (not raw disk) */
    486 			rfd = &wfd;
    487 			/* FALLTHROUGH */
    488 		case 'w':	/* write data to disk_file */
    489 			disk_file = optarg;
    490 			break;
    491 		case 't':
    492 			if (setdisktab(optarg) == -1)
    493 				errx(EXIT_FAILURE, "bad disktab");
    494 			break;
    495 		case 'T':
    496 			disk_type = optarg;
    497 			break;
    498 		case 'z':
    499 			secsize = atoi(optarg);
    500 			if (secsize <= 512)
    501 out:				 errx(EXIT_FAILURE, "Invalid sector size %zd",
    502 				    secsize);
    503 			for (ch = secsize; (ch & 1) == 0; ch >>= 1)
    504 				continue;
    505 			if (ch != 1)
    506 				goto out;
    507 			break;
    508 		default:
    509 			usage();
    510 		}
    511 	}
    512 	argc -= optind;
    513 	argv += optind;
    514 
    515 	if (disk_type != NULL && getdiskbyname(disk_type) == NULL)
    516 		errx(EXIT_FAILURE, "bad disktype");
    517 
    518 	if (sh_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
    519 		usage();
    520 
    521 	if (B_flag && f_flag) {
    522 		warnx("Bootselector may only be configured interactively");
    523 		usage();
    524 	}
    525 
    526 	if (f_flag && u_flag && !s_flag) {
    527 		warnx("Partition data not specified");
    528 		usage();
    529 	}
    530 
    531 	if (s_flag && partition == -1) {
    532 		warnx("-s flag requires a partition selected.");
    533 		usage();
    534 	}
    535 
    536 	if (argc > 1)
    537 		usage();
    538 
    539 	if (argc > 0)
    540 		disk = argv[0];
    541 	else if (!F_flag) {
    542 		/* Default to boot device */
    543 		initvar_disk(&disk);
    544 	}
    545 
    546 	if (!F_flag && stat(disk, &sb) == 0 && S_ISREG(sb.st_mode))
    547 		F_flag = 1;
    548 
    549 	if (open_disk(B_flag || a_flag || i_flag || u_flag) < 0)
    550 		exit(1);
    551 
    552 	if (secsize > 512) {
    553 		if ((iobuf = malloc(secsize)) == NULL)
    554 			err(EXIT_FAILURE, "Cannot allocate %zd buffer",
    555 			    secsize);
    556 	}
    557 
    558 	if (read_s0(0, &mboot))
    559 		/* must have been a blank disk */
    560 		init_sector0(1);
    561 
    562 	read_gpt(GPT_HDR_BLKNO, &gpt1);
    563 	read_gpt(disksectors - 1, &gpt2);
    564 
    565 	if (b_flag) {
    566 		dos_cylinders = b_cyl;
    567 		dos_heads = b_head;
    568 		dos_sectors = b_sec;
    569 	} else {
    570 		get_bios_geometry();
    571 	}
    572 
    573 	if (ptn_alignment == 0)
    574 		get_ptn_alignmemt();
    575 
    576 	get_extended_ptn();
    577 
    578 #ifdef BOOTSEL
    579 	default_ptn = get_default_boot();
    580 #endif
    581 
    582 	if (E_flag && !u_flag && partition >= ext.num_ptn)
    583 		errx(1, "Extended partition %d is not defined.", partition);
    584 
    585 	/* Do the update stuff! */
    586 	if (u_flag) {
    587 		if (!f_flag && !b_flag)
    588 			change_bios_geometry();
    589 
    590 		if (s_flag)
    591 			change_part(E_flag, partition, csysid, cstart, csize,
    592 				cbootmenu);
    593 		else {
    594 			int part = partition, chg_ext = E_flag, prompt = 1;
    595 			do {
    596 				if (prompt) {
    597 					printf("\n");
    598 					print_s0(partition);
    599 				}
    600 				if (partition == -1)
    601 					part = ptn_id(
    602 				    "Which partition do you want to change?",
    603 							&chg_ext);
    604 				if (part < 0)
    605 					break;
    606 				prompt = change_part(chg_ext, part, 0, 0, 0, 0);
    607 			} while (partition == -1);
    608 		}
    609 	} else {
    610 		if (!i_flag && !B_flag) {
    611 			print_geometry();
    612 			print_s0(partition);
    613 		}
    614 	}
    615 
    616 	if (a_flag && !E_flag)
    617 		change_active(partition);
    618 
    619 #ifdef BOOTSEL
    620 	if (B_flag || u_flag || i_flag)
    621 		/* Ensure the mbr code supports this configuration */
    622 		install_bootsel(0);
    623 	if (B_flag)
    624 		default_ptn = configure_bootsel(default_ptn);
    625 	set_default_boot(default_ptn);
    626 #else
    627 	if (i_flag)
    628 		init_sector0(0);
    629 #endif
    630 
    631 	if (u_flag || a_flag || i_flag || B_flag) {
    632 		if (!f_flag) {
    633 			printf("\nWe haven't written the MBR back to disk "
    634 			       "yet.  This is your last chance.\n");
    635 			if (u_flag)
    636 				print_s0(-1);
    637 			if (gpt1.hdr_size != 0 || gpt2.hdr_size != 0)
    638 				printf("\nWARNING: The disk is carrying "
    639 				       "GUID Partition Tables.\n"
    640 				       "         If you continue, "
    641 				       "GPT headers will be deleted.\n\n");
    642 			if (yesno("Should we write new partition table?")) {
    643 				delete_gpt(&gpt1);
    644 				delete_gpt(&gpt2);
    645 				write_mbr();
    646 			}
    647 		} else {
    648 			if (delete_gpt(&gpt1) > 0)
    649 				warnx("Primary GPT header was deleted");
    650 			if (delete_gpt(&gpt2) > 0)
    651 				warnx("Secondary GPT header was deleted");
    652 			write_mbr();
    653 		}
    654 	}
    655 
    656 	exit(0);
    657 }
    658 
    659 static void
    660 usage(void)
    661 {
    662 	int indent = 7 + (int)strlen(getprogname()) + 1;
    663 
    664 	(void)fprintf(stderr, "usage: %s [-aBFfIilSuv] "
    665 		"[-A ptn_alignment[/ptn_0_offset]] \\\n"
    666 		"%*s[-b cylinders/heads/sectors] \\\n"
    667 		"%*s[-0123 | -E num "
    668 		"[-s [id][/[start][/[size][/bootmenu]]]] \\\n"
    669 		"%*s[-t disktab] [-T disktype] \\\n"
    670 		"%*s[-c bootcode] "
    671 		"[-r|-w file] [-z sectorsize] [device]\n"
    672 		"\t-a change active partition\n"
    673 		"\t-f force - not interactive\n"
    674 		"\t-i initialise MBR code\n"
    675 		"\t-I ignore errors about no space or overlapping partitions\n"
    676 		"\t-l list partition types\n"
    677 		"\t-u update partition data\n"
    678 		"\t-v verbose output, -v -v more verbose still\n"
    679 		"\t-B update bootselect options\n"
    680 		"\t-F treat device as a regular file\n"
    681 		"\t-S output as shell defines\n"
    682 		"\t-r and -w access 'file' for non-destructive testing\n",
    683 		getprogname(), indent, "", indent, "", indent, "", indent, "");
    684 	exit(1);
    685 }
    686 
    687 static daddr_t
    688 ext_offset(int part)
    689 {
    690 	daddr_t offset = ext.base;
    691 
    692 	if (part != 0)
    693 		offset += le32toh(ext.ptn[part - 1].mbr_parts[1].mbrp_start);
    694 	return offset;
    695 }
    696 
    697 static void
    698 print_s0(int which)
    699 {
    700 	int part;
    701 
    702 	if (which == -1) {
    703 		if (!sh_flag)
    704 			printf("Partition table:\n");
    705 		for (part = 0; part < MBR_PART_COUNT; part++) {
    706 			if (!sh_flag)
    707 				printf("%d: ", part);
    708 			print_part(&mboot, part, 0);
    709 		}
    710 		if (!sh_flag) {
    711 			if (ext.is_corrupt)
    712 				printf("Extended partition table is corrupt\n");
    713 			else
    714 				if (ext.num_ptn != 0)
    715 					printf("Extended partition table:\n");
    716 		}
    717 		for (part = 0; part < ext.num_ptn; part++) {
    718 			if (!sh_flag)
    719 				printf("E%d: ", part);
    720 			print_part(&ext.ptn[part], 0, ext_offset(part));
    721 			if (!sh_flag && v_flag >= 2) {
    722 				printf("link: ");
    723 				print_mbr_partition(&ext.ptn[part], 1,
    724 						ext_offset(part), ext.base, 0);
    725 			}
    726 		}
    727 #ifdef BOOTSEL
    728 		if (!sh_flag && mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
    729 			int tmo;
    730 
    731 			printf("Bootselector ");
    732 			if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ACTIVE) {
    733 				printf("enabled");
    734 				tmo = le16toh(mboot.mbr_bootsel.mbrbs_timeo);
    735 				if (tmo == 0xffff)
    736 					printf(", infinite timeout");
    737 				else
    738 					printf(", timeout %d seconds",
    739 						    (10 * tmo + 9) / 182);
    740 			} else
    741 				printf("disabled");
    742 			printf(".\n");
    743 		}
    744 #endif
    745 		if (!sh_flag) {
    746 			int active = first_active();
    747 			if (active == MBR_PART_COUNT)
    748 				printf("No active partition.\n");
    749 			else
    750 				printf("First active partition: %d\n", active);
    751 		}
    752 		if (!sh_flag)
    753 			printf("Drive serial number: %"PRIu32" (0x%08x)\n",
    754 			    le32toh(mboot.mbr_dsn),
    755 			    le32toh(mboot.mbr_dsn));
    756 		return;
    757 	}
    758 
    759 	if (E_flag) {
    760 		if (!sh_flag)
    761 			printf("Extended partition E%d:\n", which);
    762 		if (which > ext.num_ptn)
    763 			printf("Undefined\n");
    764 		else
    765 			print_part(&ext.ptn[which], 0, ext_offset(which));
    766 	} else {
    767 		if (!sh_flag)
    768 			printf("Partition %d:\n", which);
    769 		print_part(&mboot, which, 0);
    770 	}
    771 }
    772 
    773 static void
    774 print_part(struct mbr_sector *boot, int part, daddr_t offset)
    775 {
    776 	struct mbr_partition *partp;
    777 	const char *e;
    778 
    779 	if (!sh_flag) {
    780 		print_mbr_partition(boot, part, offset, 0, 0);
    781 		return;
    782 	}
    783 
    784 	partp = &boot->mbr_parts[part];
    785 	if (boot != &mboot) {
    786 		part = boot - ext.ptn;
    787 		e = "E";
    788 	} else
    789 		e = "";
    790 
    791 	if (partp->mbrp_type == 0) {
    792 		printf("PART%s%dSIZE=0\n", e, part);
    793 		return;
    794 	}
    795 
    796 	printf("PART%s%dID=%d\n", e, part, partp->mbrp_type);
    797 	printf("PART%s%dSIZE=%u\n", e, part, le32toh(partp->mbrp_size));
    798 	printf("PART%s%dSTART=%"PRIdaddr"\n", e, part,
    799 	    offset + le32toh(partp->mbrp_start));
    800 	printf("PART%s%dFLAG=0x%x\n", e, part, partp->mbrp_flag);
    801 	printf("PART%s%dBCYL=%d\n", e, part,
    802 	    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect));
    803 	printf("PART%s%dBHEAD=%d\n", e, part, partp->mbrp_shd);
    804 	printf("PART%s%dBSEC=%d\n", e, part, MBR_PSECT(partp->mbrp_ssect));
    805 	printf("PART%s%dECYL=%d\n", e, part,
    806 	    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect));
    807 	printf("PART%s%dEHEAD=%d\n", e, part, partp->mbrp_ehd);
    808 	printf("PART%s%dESEC=%d\n", e, part, MBR_PSECT(partp->mbrp_esect));
    809 }
    810 
    811 static void
    812 pr_cyls(daddr_t sector, int is_end)
    813 {
    814 	unsigned long cyl, head, sect;
    815 	cyl = sector / dos_cylindersectors;
    816 	sect = sector - cyl * dos_cylindersectors;
    817 	head = sect / dos_sectors;
    818 	sect -= head * dos_sectors;
    819 
    820 	printf("%lu", cyl);
    821 
    822 	if (is_end) {
    823 		if (head == dos_heads - 1 && sect == dos_sectors - 1)
    824 			return;
    825 	} else {
    826 		if (head == 0 && sect == 0)
    827 			return;
    828 	}
    829 
    830 	printf("/%lu/%lu", head, sect + 1);
    831 }
    832 
    833 static void
    834 print_mbr_partition(struct mbr_sector *boot, int part,
    835     daddr_t offset, daddr_t exoffset, int indent)
    836 {
    837 	daddr_t	start;
    838 	daddr_t	size;
    839 	struct mbr_partition *partp = &boot->mbr_parts[part];
    840 	struct mbr_sector eboot;
    841 	int p;
    842 	static int dumped = 0;
    843 
    844 	if (partp->mbrp_type == 0 && v_flag < 2) {
    845 		printf("<UNUSED>\n");
    846 		return;
    847 	}
    848 
    849 	start = le32toh(partp->mbrp_start);
    850 	size = le32toh(partp->mbrp_size);
    851 	if (MBR_IS_EXTENDED(partp->mbrp_type))
    852 		start += exoffset;
    853 	else
    854 		start += offset;
    855 
    856 	printf("%s (sysid %d)\n", get_type(partp->mbrp_type), partp->mbrp_type);
    857 #ifdef BOOTSEL
    858 	if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC &&
    859 	    boot->mbr_bootsel.mbrbs_nametab[part][0])
    860 		printf("%*s    bootmenu: %s\n", indent, "",
    861 		    boot->mbr_bootsel.mbrbs_nametab[part]);
    862 #endif
    863 
    864 	printf("%*s    start %"PRIdaddr", size %"PRIdaddr,
    865 	    indent, "", start, size);
    866 	if (size != 0) {
    867 		printf(" (%u MB, Cyls ", SEC_TO_MB(size));
    868 		if (v_flag == 0 && le32toh(partp->mbrp_start) == ptn_0_offset)
    869 			pr_cyls(start - ptn_0_offset, 0);
    870 		else
    871 			pr_cyls(start, 0);
    872 		printf("-");
    873 		pr_cyls(start + size - 1, 1);
    874 		printf(")");
    875 	}
    876 
    877 	switch (partp->mbrp_flag) {
    878 	case 0:
    879 		break;
    880 	case MBR_PFLAG_ACTIVE:
    881 		printf(", Active");
    882 		break;
    883 	default:
    884 		printf(", flag 0x%x", partp->mbrp_flag);
    885 		break;
    886 	}
    887 	printf("\n");
    888 
    889 	if (v_flag) {
    890 		printf("%*s        beg: cylinder %4d, head %3d, sector %2d\n",
    891 		    indent, "",
    892 		    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
    893 		    partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
    894 		printf("%*s        end: cylinder %4d, head %3d, sector %2d\n",
    895 		    indent, "",
    896 		    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
    897 		    partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
    898 	}
    899 
    900 	if (partp->mbrp_type == 0 && start == 0 && v_flag < 3)
    901 		return;
    902 
    903 	if (! MBR_IS_EXTENDED(partp->mbrp_type))
    904 		print_pbr(start, indent + 8, partp->mbrp_type);
    905 
    906 	if (!MBR_IS_EXTENDED(partp->mbrp_type) ||
    907 	    (v_flag <= 2 && !ext.is_corrupt))
    908 		return;
    909 
    910 	/*
    911 	 * Recursive dump extended table,
    912 	 * This is read from the disk - so is wrong during editing.
    913 	 * Just ensure we only show it once.
    914 	 */
    915 	if (dumped)
    916 		return;
    917 
    918 	printf("%*s    Extended partition table:\n", indent, "");
    919 	indent += 4;
    920 	if (read_s0(start, &eboot) == -1)
    921 		return;
    922 	for (p = 0; p < MBR_PART_COUNT; p++) {
    923 		printf("%*s%d: ", indent, "", p);
    924 		print_mbr_partition(&eboot, p, start,
    925 				    exoffset ? exoffset : start, indent);
    926 	}
    927 
    928 	if (exoffset == 0)
    929 		dumped = 1;
    930 }
    931 
    932 /* Print a line with a label and a vis-encoded string */
    933 static void
    934 printvis(int indent, const char *label, const char *buf, size_t size)
    935 {
    936 	char *visbuf;
    937 
    938 	if ((visbuf = malloc(size * 4 + 1)) == NULL)
    939 		err(1, "Malloc failed");
    940 	strsvisx(visbuf, buf, size, VIS_TAB|VIS_NL|VIS_OCTAL, "\"");
    941 	printf("%*s%s: \"%s\"\n",
    942 	    indent, "",
    943 	    label, visbuf);
    944 	free(visbuf);
    945 }
    946 
    947 /* Check whether a buffer contains all bytes zero */
    948 static int
    949 is_all_zero(const unsigned char *p, size_t size)
    950 {
    951 
    952 	while (size-- > 0) {
    953 		if (*p++ != 0)
    954 			return 0;
    955 	}
    956 	return 1;
    957 }
    958 
    959 /*
    960  * Report on the contents of a PBR sector.
    961  *
    962  * We first perform several sanity checks.  If vflag >= 2, we report all
    963  * failing tests, but for smaller values of v_flag we stop after the
    964  * first failing test.  Tests are ordered in an attempt to get the most
    965  * useful error message from the first failing test.
    966  *
    967  * If v_flag >= 2, we also report some decoded values from the PBR.
    968  * These results may be meaningless, if the PBR doesn't follow common
    969  * conventions.
    970  *
    971  * Trying to decode anything more than the magic number in the last
    972  * two bytes is a layering violation, but it can be very useful in
    973  * diagnosing boot failures.
    974  */
    975 static void
    976 print_pbr(daddr_t sector, int indent, uint8_t part_type)
    977 {
    978 	struct mbr_sector pboot;
    979 	unsigned char *p, *endp;
    980 	unsigned char val;
    981 	int ok;
    982 	int errcount = 0;
    983 
    984 #define PBR_ERROR(...)							\
    985 	do {								\
    986 		++errcount;						\
    987 		printf("%*s%s: ", indent, "",				\
    988 		    (v_flag < 2 ? "PBR is not bootable" : "Not bootable")); \
    989 		printf(__VA_ARGS__);					\
    990 		if (v_flag < 2)						\
    991 			return;						\
    992 	} while (/*CONSTCOND*/ 0)
    993 
    994 	if (v_flag >= 2) {
    995 		printf("%*sInformation from PBR:\n",
    996 		    indent, "");
    997 		indent += 4;
    998 	}
    999 
   1000 	if (read_disk(sector, &pboot) == -1) {
   1001 		PBR_ERROR("Sector %"PRIdaddr" is unreadable (%s)\n",
   1002 		    sector, strerror(errno));
   1003 		return;
   1004 	}
   1005 
   1006 	/* all bytes identical? */
   1007 	p = (unsigned char *)&pboot;
   1008 	endp = p + sizeof(pboot);
   1009 	val = *p;
   1010 	ok = 0;
   1011 	for (; p < endp; p++) {
   1012 		if (*p != val) {
   1013 			ok = 1;
   1014 			break;
   1015 		}
   1016 	}
   1017 	if (! ok)
   1018 		PBR_ERROR("All bytes are identical (0x%02x)\n", val);
   1019 
   1020 	if (pboot.mbr_magic != LE_MBR_MAGIC)
   1021 		PBR_ERROR("Bad magic number (0x%04x)\n",
   1022 			le16toh(pboot.mbr_magic));
   1023 
   1024 #if 0
   1025 	/* Some i386 OS might fail this test.  All non-i386 will fail. */
   1026 	if (pboot.mbr_jmpboot[0] != 0xE9
   1027 	    && pboot.mbr_jmpboot[0] != 0xEB) {
   1028 		PBR_ERROR("Does not begin with i386 JMP instruction"
   1029 			" (0x%02x 0x%02x0 0x%02x)\n",
   1030 		    pboot.mbr_jmpboot[0], pboot.mbr_jmpboot[1],
   1031 		    pboot.mbr_jmpboot[2]);
   1032 	}
   1033 #endif
   1034 
   1035 	if (v_flag > 0 && errcount == 0)
   1036 		printf("%*sPBR appears to be bootable\n",
   1037 		    indent, "");
   1038 	if (v_flag < 2)
   1039 		return;
   1040 
   1041 	if (! is_all_zero(pboot.mbr_oemname, sizeof(pboot.mbr_oemname))) {
   1042 		printvis(indent, "OEM name", (char *)pboot.mbr_oemname,
   1043 			sizeof(pboot.mbr_oemname));
   1044 	}
   1045 
   1046 	if (pboot.mbr_bpb.bpb16.bsBootSig == 0x29)
   1047 		printf("%*sBPB FAT16 boot signature found\n",
   1048 		    indent, "");
   1049 	if (pboot.mbr_bpb.bpb32.bsBootSig == 0x29)
   1050 		printf("%*sBPB FAT32 boot signature found\n",
   1051 		    indent, "");
   1052 
   1053 #undef PBR_ERROR
   1054 }
   1055 
   1056 static int
   1057 read_boot(const char *name, void *buf, size_t len, int err_exit)
   1058 {
   1059 	int bfd, ret;
   1060 	struct stat st;
   1061 
   1062 	if (boot_path != NULL)
   1063 		free(boot_path);
   1064 	if (strchr(name, '/') == 0)
   1065 		asprintf(&boot_path, "%s/%s", boot_dir, name);
   1066 	else
   1067 		boot_path = strdup(name);
   1068 	if (boot_path == NULL)
   1069 		err(1, "Malloc failed");
   1070 
   1071 	if ((bfd = open(boot_path, O_RDONLY)) < 0 || fstat(bfd, &st) == -1) {
   1072 		warn("%s", boot_path);
   1073 		goto fail;
   1074 	}
   1075 
   1076 	if (st.st_size > (off_t)len) {
   1077 		warnx("%s: bootcode too large", boot_path);
   1078 		goto fail;
   1079 	}
   1080 	ret = st.st_size;
   1081 	if (ret < 0x200) {
   1082 		warnx("%s: bootcode too small", boot_path);
   1083 		goto fail;
   1084 	}
   1085 	if (read(bfd, buf, len) != ret) {
   1086 		warn("%s", boot_path);
   1087 		goto fail;
   1088 	}
   1089 
   1090 	/*
   1091 	 * Do some sanity checking here
   1092 	 */
   1093 	if (((struct mbr_sector *)buf)->mbr_magic != LE_MBR_MAGIC) {
   1094 		warnx("%s: invalid magic", boot_path);
   1095 		goto fail;
   1096 	}
   1097 
   1098 	close(bfd);
   1099 	ret = (ret + 0x1ff) & ~0x1ff;
   1100 	return ret;
   1101 
   1102     fail:
   1103 	if (bfd >= 0)
   1104 		close(bfd);
   1105 	if (err_exit)
   1106 		exit(1);
   1107 	return 0;
   1108 }
   1109 
   1110 static void
   1111 init_sector0(int zappart)
   1112 {
   1113 	int i;
   1114 	int copy_size = offsetof(struct mbr_sector, mbr_dsn);
   1115 
   1116 #ifdef DEFAULT_BOOTCODE
   1117 	if (bootsize == 0)
   1118 		bootsize = read_boot(DEFAULT_BOOTCODE, bootcode,
   1119 			sizeof bootcode, 0);
   1120 #endif
   1121 #ifdef BOOTSEL
   1122 	if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
   1123 	    && bootcode[0].mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   1124 		copy_size = MBR_BS_OFFSET;
   1125 #endif
   1126 
   1127 	if (bootsize != 0) {
   1128 		boot_installed = 1;
   1129 		memcpy(&mboot, bootcode, copy_size);
   1130 		mboot.mbr_bootsel_magic = bootcode[0].mbr_bootsel_magic;
   1131 	}
   1132 	mboot.mbr_magic = LE_MBR_MAGIC;
   1133 
   1134 	if (!zappart)
   1135 		return;
   1136 	for (i = 0; i < MBR_PART_COUNT; i++)
   1137 		memset(&mboot.mbr_parts[i], 0, sizeof(mboot.mbr_parts[i]));
   1138 }
   1139 
   1140 static void
   1141 get_extended_ptn(void)
   1142 {
   1143 	struct mbr_partition *mp;
   1144 	struct mbr_sector *boot;
   1145 	daddr_t offset;
   1146 	struct mbr_sector *nptn;
   1147 
   1148 	/* find first (there should only be one) extended partition */
   1149 	for (mp = mboot.mbr_parts; !MBR_IS_EXTENDED(mp->mbrp_type); mp++)
   1150 		if (mp >= &mboot.mbr_parts[MBR_PART_COUNT])
   1151 			return;
   1152 
   1153 	/*
   1154 	 * The extended partition should be structured as a linked list
   1155 	 * (even though it appears, at first glance, to be a tree).
   1156 	 */
   1157 	ext.base = le32toh(mp->mbrp_start);
   1158 	ext.limit = ext.base + le32toh(mp->mbrp_size);
   1159 	ext.ptn_id = mp - mboot.mbr_parts;
   1160 	for (offset = 0;; offset = le32toh(boot->mbr_parts[1].mbrp_start)) {
   1161 		nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
   1162 		if (nptn == NULL)
   1163 			err(1, "Malloc failed");
   1164 		ext.ptn = nptn;
   1165 		boot = ext.ptn + ext.num_ptn;
   1166 		if (read_s0(offset + ext.base, boot) == -1)
   1167 			break;
   1168 		/* expect p0 to be valid and p1 to be another extended ptn */
   1169 		if (MBR_IS_EXTENDED(boot->mbr_parts[0].mbrp_type))
   1170 			break;
   1171 		if (boot->mbr_parts[1].mbrp_type != 0 &&
   1172 		    !MBR_IS_EXTENDED(boot->mbr_parts[1].mbrp_type))
   1173 			break;
   1174 		/* p2 and p3 should be unallocated */
   1175 		if (boot->mbr_parts[2].mbrp_type != 0 ||
   1176 		    boot->mbr_parts[3].mbrp_type != 0)
   1177 			break;
   1178 		/* data ptn inside extended one */
   1179 		if (boot->mbr_parts[0].mbrp_type != 0 &&
   1180 		    offset + le32toh(boot->mbr_parts[0].mbrp_start)
   1181 		    + le32toh(boot->mbr_parts[0].mbrp_size) > ext.limit)
   1182 			break;
   1183 
   1184 		ext.num_ptn++;
   1185 
   1186 		if (boot->mbr_parts[1].mbrp_type == 0)
   1187 			/* end of extended partition chain */
   1188 			return;
   1189 		/* must be in sector order */
   1190 		if (offset >= le32toh(boot->mbr_parts[1].mbrp_start))
   1191 			break;
   1192 	}
   1193 
   1194 	warnx("Extended partition table is corrupt");
   1195 	ext.is_corrupt = 1;
   1196 	ext.num_ptn = 0;
   1197 }
   1198 
   1199 #if defined(USE_DISKLIST)
   1200 static void
   1201 get_diskname(const char *fullname, char *diskname, size_t size)
   1202 {
   1203 	const char *p, *p2;
   1204 	size_t len;
   1205 
   1206 	p = strrchr(fullname, '/');
   1207 	if (p == NULL)
   1208 		p = fullname;
   1209 	else
   1210 		p++;
   1211 
   1212 	if (*p == 0) {
   1213 		strlcpy(diskname, fullname, size);
   1214 		return;
   1215 	}
   1216 
   1217 	if (*p == 'r')
   1218 		p++;
   1219 
   1220 	for (p2 = p; *p2 != 0; p2++)
   1221 		if (isdigit((unsigned char)*p2))
   1222 			break;
   1223 	if (*p2 == 0) {
   1224 		/* XXX invalid diskname? */
   1225 		strlcpy(diskname, fullname, size);
   1226 		return;
   1227 	}
   1228 	while (isdigit((unsigned char)*p2))
   1229 		p2++;
   1230 
   1231 	len = p2 - p;
   1232 	if (len > size) {
   1233 		/* XXX */
   1234 		strlcpy(diskname, fullname, size);
   1235 		return;
   1236 	}
   1237 
   1238 	memcpy(diskname, p, len);
   1239 	diskname[len] = 0;
   1240 }
   1241 #endif
   1242 
   1243 static void
   1244 get_ptn_alignmemt(void)
   1245 {
   1246 	struct mbr_partition *partp = &mboot.mbr_parts[0];
   1247 	uint32_t ptn_0_base, ptn_0_limit;
   1248 
   1249 	/* Default to using 'traditional' cylinder alignment */
   1250 	ptn_alignment = dos_cylindersectors;
   1251 	ptn_0_offset = dos_sectors;
   1252 
   1253 	if (partp->mbrp_type != 0) {
   1254 		/* Try to copy alignment of first partition */
   1255 		ptn_0_base = le32toh(partp->mbrp_start);
   1256 		ptn_0_limit = ptn_0_base + le32toh(partp->mbrp_size);
   1257 		if (!(ptn_0_limit & 2047)) {
   1258 			/* Partition ends on a 1MB boundary, align to 1MB */
   1259 			ptn_alignment = 2048;
   1260 			if (ptn_0_base <= 2048
   1261 			    && !(ptn_0_base & (ptn_0_base - 1))) {
   1262 				/* ptn_base is a power of 2, use it */
   1263 				ptn_0_offset = ptn_0_base;
   1264 			}
   1265 		}
   1266 	} else {
   1267 		/* Use 1MB alignment for large disks */
   1268 		if (disksectors > 2048 * 1024 * 128) {
   1269 			ptn_alignment = 2048;
   1270 			ptn_0_offset = 2048;
   1271 		}
   1272 	}
   1273 }
   1274 
   1275 static void
   1276 get_bios_geometry(void)
   1277 {
   1278 #if defined(USE_DISKLIST)
   1279 	int mib[2], i;
   1280 	size_t len;
   1281 	struct biosdisk_info *bip;
   1282 	struct nativedisk_info *nip;
   1283 	char diskname[8];
   1284 
   1285 	mib[0] = CTL_MACHDEP;
   1286 	mib[1] = CPU_DISKINFO;
   1287 	if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
   1288 		goto out;
   1289 	}
   1290 	dl = (struct disklist *) malloc(len);
   1291 	if (dl == NULL)
   1292 		err(1, "Malloc failed");
   1293 	if (sysctl(mib, 2, dl, &len, NULL, 0) < 0) {
   1294 		free(dl);
   1295 		dl = 0;
   1296 		goto out;
   1297 	}
   1298 
   1299 	get_diskname(disk, diskname, sizeof diskname);
   1300 
   1301 	for (i = 0; i < dl->dl_nnativedisks; i++) {
   1302 		nip = &dl->dl_nativedisks[i];
   1303 		if (strcmp(diskname, nip->ni_devname))
   1304 			continue;
   1305 		/*
   1306 		 * XXX listing possible matches is better. This is ok for
   1307 		 * now because the user has a chance to change it later.
   1308 		 * Also, if all the disks have the same parameters then we can
   1309 		 * just use them, we don't need to know which disk is which.
   1310 		 */
   1311 		if (nip->ni_nmatches != 0) {
   1312 			bip = &dl->dl_biosdisks[nip->ni_biosmatches[0]];
   1313 			dos_cylinders = bip->bi_cyl;
   1314 			dos_heads = bip->bi_head;
   1315 			dos_sectors = bip->bi_sec;
   1316 			if (bip->bi_lbasecs)
   1317 				dos_disksectors = bip->bi_lbasecs;
   1318 			return;
   1319 		}
   1320 	}
   1321  out:
   1322 #endif
   1323 	/* Allright, allright, make a stupid guess.. */
   1324 	intuit_translated_geometry();
   1325 }
   1326 
   1327 #ifdef BOOTSEL
   1328 static daddr_t
   1329 get_default_boot(void)
   1330 {
   1331 	unsigned int id;
   1332 	int p;
   1333 
   1334 	if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1335 		/* default to first active partition */
   1336 		return DEFAULT_ACTIVE;
   1337 
   1338 	id = mboot.mbr_bootsel.mbrbs_defkey;
   1339 
   1340 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII) {
   1341 		/* Keycode is ascii */
   1342 		if (id == '\r')
   1343 		    return DEFAULT_ACTIVE;
   1344 		/* '1'+ => allocated partition id, 'a'+ => disk 0+ */
   1345 		if (id >= 'a' && id < 'a' + MAX_BIOS_DISKS)
   1346 			return DEFAULT_DISK(id - 'a');
   1347 		id -= '1';
   1348 	} else {
   1349 		/* keycode is PS/2 keycode */
   1350 		if (id == SCAN_ENTER)
   1351 			return DEFAULT_ACTIVE;
   1352 		/* 1+ => allocated partition id, F1+ => disk 0+ */
   1353 		if (id >= SCAN_F1 && id < SCAN_F1 + MAX_BIOS_DISKS)
   1354 			return DEFAULT_DISK(id - SCAN_F1);
   1355 		id -= SCAN_1;
   1356 	}
   1357 
   1358 	/* Convert partition index to the invariant start sector number */
   1359 
   1360 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1361 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1362 			continue;
   1363 		if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1364 			continue;
   1365 		if (id-- == 0)
   1366 			return le32toh(mboot.mbr_parts[p].mbrp_start);
   1367 	}
   1368 
   1369 	for (p = 0; p < ext.num_ptn; p++) {
   1370 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1371 			continue;
   1372 		if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1373 			continue;
   1374 		if (id-- == 0)
   1375 			return ext_offset(p)
   1376 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start);
   1377 	}
   1378 
   1379 	return DEFAULT_ACTIVE;
   1380 }
   1381 
   1382 static void
   1383 set_default_boot(daddr_t default_ptn)
   1384 {
   1385 	int p;
   1386 	static const unsigned char key_list[] = { SCAN_ENTER, SCAN_F1, SCAN_1,
   1387 						'\r', 'a', '1' };
   1388 	const unsigned char *key = key_list;
   1389 
   1390 	if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1391 		/* sanity */
   1392 		return;
   1393 
   1394 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII)
   1395 		/* Use ascii values */
   1396 		key += 3;
   1397 
   1398 	if (default_ptn == DEFAULT_ACTIVE) {
   1399 		mboot.mbr_bootsel.mbrbs_defkey = key[0];
   1400 		return;
   1401 	}
   1402 
   1403 	if (default_ptn >= DEFAULT_DISK(0)
   1404 	    && default_ptn < DEFAULT_DISK(MAX_BIOS_DISKS)) {
   1405 		mboot.mbr_bootsel.mbrbs_defkey = key[1]
   1406 		    + default_ptn - DEFAULT_DISK(0);
   1407 		return;
   1408 	}
   1409 
   1410 	mboot.mbr_bootsel.mbrbs_defkey = key[2];
   1411 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1412 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1413 			continue;
   1414 		if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1415 			continue;
   1416 		if (le32toh(mboot.mbr_parts[p].mbrp_start) == default_ptn)
   1417 			return;
   1418 		mboot.mbr_bootsel.mbrbs_defkey++;
   1419 	}
   1420 
   1421 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_EXTLBA) {
   1422 		for (p = 0; p < ext.num_ptn; p++) {
   1423 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1424 				continue;
   1425 			if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1426 				continue;
   1427 			if (le32toh(ext.ptn[p].mbr_parts[0].mbrp_start) +
   1428 			    ext_offset(p) == default_ptn)
   1429 				return;
   1430 			mboot.mbr_bootsel.mbrbs_defkey++;
   1431 		}
   1432 	}
   1433 
   1434 	/* Default to first active partition */
   1435 	mboot.mbr_bootsel.mbrbs_defkey = key[0];
   1436 }
   1437 
   1438 static void
   1439 install_bootsel(int needed)
   1440 {
   1441 	struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
   1442 	int p;
   1443 	int ext13 = 0;
   1444 	const char *code;
   1445 
   1446 	needed |= MBR_BS_NEWMBR;	/* need new bootsel code */
   1447 
   1448 	/* Work out which boot code we need for this configuration */
   1449 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1450 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1451 			continue;
   1452 		if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1453 			break;
   1454 		if (mbs->mbrbs_nametab[p][0] == 0)
   1455 			continue;
   1456 		needed |= MBR_BS_ACTIVE;
   1457 		if (le32toh(mboot.mbr_parts[p].mbrp_start) >= dos_totalsectors)
   1458 			ext13 = MBR_BS_EXTINT13;
   1459 	}
   1460 
   1461 	for (p = 0; p < ext.num_ptn; p++) {
   1462 		if (ext.ptn[p].mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1463 			continue;
   1464 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1465 			continue;
   1466 		if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1467 			continue;
   1468 		needed |= MBR_BS_EXTLBA | MBR_BS_ACTIVE;
   1469 	}
   1470 
   1471 	if (B_flag)
   1472 		needed |= MBR_BS_ACTIVE;
   1473 
   1474 	/* Is the installed code good enough ? */
   1475 	if (!i_flag && (needed == 0 ||
   1476 	    (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
   1477 	    && (mbs->mbrbs_flags & needed) == needed))) {
   1478 		/* yes - just set flags */
   1479 		mbs->mbrbs_flags |= ext13;
   1480 		return;
   1481 	}
   1482 
   1483 	/* ok - we need to replace the bootcode */
   1484 
   1485 	if (f_flag && !(i_flag || B_flag)) {
   1486 		warnx("Installed bootfile doesn't support required options.");
   1487 		return;
   1488 	}
   1489 
   1490 	if (!f_flag && bootsize == 0 && !i_flag)
   1491 		/* Output an explanation for the 'update bootcode' prompt. */
   1492 		printf("\n%s\n",
   1493 		    "Installed bootfile doesn't support required options.");
   1494 
   1495 	/* Were we told a specific file ? (which we have already read) */
   1496 	/* If so check that it supports what we need. */
   1497 	if (bootsize != 0 && needed != 0
   1498 	    && (bootcode[0].mbr_bootsel_magic != LE_MBR_BS_MAGIC
   1499 	    || ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed))) {
   1500 		/* No it doesn't... */
   1501 		if (f_flag)
   1502 			warnx("Bootfile %s doesn't support "
   1503 				    "required bootsel options", boot_path );
   1504 			/* But install it anyway */
   1505 		else
   1506 			if (yesno("Bootfile %s doesn't support the required "
   1507 			    "options,\ninstall default bootfile instead?",
   1508 			    boot_path))
   1509 				bootsize = 0;
   1510 	}
   1511 
   1512 	if (bootsize == 0) {
   1513 		/* Get name of bootfile that supports the required facilities */
   1514 		code = DEFAULT_BOOTCODE;
   1515 		if (needed & MBR_BS_ACTIVE)
   1516 			code = DEFAULT_BOOTSELCODE;
   1517 #ifdef DEFAULT_BOOTEXTCODE
   1518 		if (needed & MBR_BS_EXTLBA)
   1519 			code = DEFAULT_BOOTEXTCODE;
   1520 #endif
   1521 
   1522 		bootsize = read_boot(code, bootcode, sizeof bootcode, 0);
   1523 		if (bootsize == 0)
   1524 			/* The old bootcode is better than no bootcode at all */
   1525 			return;
   1526 		if ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed)
   1527 			warnx("Default bootfile %s doesn't support required "
   1528 				"options.  Got flags 0x%x, wanted 0x%x\n",
   1529 				boot_path, bootcode[0].mbr_bootsel.mbrbs_flags,
   1530 				needed);
   1531 	}
   1532 
   1533 	if (!f_flag && !yesno("Update the bootcode from %s?", boot_path))
   1534 		return;
   1535 
   1536 	init_sector0(0);
   1537 
   1538 	if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   1539 		mbs->mbrbs_flags = bootcode[0].mbr_bootsel.mbrbs_flags | ext13;
   1540 }
   1541 
   1542 static daddr_t
   1543 configure_bootsel(daddr_t default_ptn)
   1544 {
   1545 	struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
   1546 	int i, item, opt;
   1547 	int tmo;
   1548 	daddr_t *off;
   1549 	int num_bios_disks;
   1550 
   1551 #if defined(USE_DISKLIST)
   1552 	if (dl != NULL) {
   1553 		num_bios_disks = dl->dl_nbiosdisks;
   1554 		if (num_bios_disks > MAX_BIOS_DISKS)
   1555 			num_bios_disks = MAX_BIOS_DISKS;
   1556 	} else
   1557 #endif
   1558 		num_bios_disks = MAX_BIOS_DISKS;
   1559 
   1560 	printf("\nBoot selector configuration:\n");
   1561 
   1562 	/* The timeout value is in ticks, ~18.2 Hz. Avoid using floats.
   1563 	 * Ticks are nearly 64k/3600 - so our long timers are sligtly out!
   1564 	 * Newer bootcode always waits for 1 tick, so treats 0xffff
   1565 	 * as wait forever.
   1566 	 */
   1567 	tmo = le16toh(mbs->mbrbs_timeo);
   1568 	tmo = tmo == 0xffff ? -1 : (10 * tmo + 9) / 182;
   1569 	tmo = decimal("Timeout value (0 to 3600 seconds, -1 => never)",
   1570 			tmo, 0, -1, 3600);
   1571 	mbs->mbrbs_timeo = htole16(tmo == -1 ? 0xffff : (tmo * 182) / 10);
   1572 
   1573 	off = calloc(1 + MBR_PART_COUNT + ext.num_ptn + num_bios_disks, sizeof *off);
   1574 	if (off == NULL)
   1575 		err(1, "Malloc failed");
   1576 
   1577 	printf("Select the default boot option. Options are:\n\n");
   1578 	item = 0;
   1579 	opt = 0;
   1580 	off[opt] = DEFAULT_ACTIVE;
   1581 	printf("%d: The first active partition\n", opt);
   1582 	for (i = 0; i < MBR_PART_COUNT; i++) {
   1583 		if (mboot.mbr_parts[i].mbrp_type == 0)
   1584 			continue;
   1585 		if (mbs->mbrbs_nametab[i][0] == 0)
   1586 			continue;
   1587 		printf("%d: %s\n", ++opt, &mbs->mbrbs_nametab[i][0]);
   1588 		off[opt] = le32toh(mboot.mbr_parts[i].mbrp_start);
   1589 		if (off[opt] == default_ptn)
   1590 			item = opt;
   1591 	}
   1592 	if (mbs->mbrbs_flags & MBR_BS_EXTLBA) {
   1593 		for (i = 0; i < ext.num_ptn; i++) {
   1594 			if (ext.ptn[i].mbr_parts[0].mbrp_type == 0)
   1595 				continue;
   1596 			if (ext.ptn[i].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1597 				continue;
   1598 			printf("%d: %s\n",
   1599 			    ++opt, ext.ptn[i].mbr_bootsel.mbrbs_nametab[0]);
   1600 			off[opt] = ext_offset(i) +
   1601 			    le32toh(ext.ptn[i].mbr_parts[0].mbrp_start);
   1602 			if (off[opt] == default_ptn)
   1603 				item = opt;
   1604 		}
   1605 	}
   1606 	for (i = 0; i < num_bios_disks; i++) {
   1607 		printf("%d: Harddisk %d\n", ++opt, i);
   1608 		off[opt] = DEFAULT_DISK(i);
   1609 		if (DEFAULT_DISK(i) == default_ptn)
   1610 			item = opt;
   1611 	}
   1612 
   1613 	item = decimal("Default boot option", item, 0, 0, opt);
   1614 
   1615 	default_ptn = off[item];
   1616 	free(off);
   1617 	return default_ptn;
   1618 }
   1619 #endif /* BOOTSEL */
   1620 
   1621 
   1622 /* Prerequisite: the disklabel parameters and master boot record must
   1623  *		 have been read (i.e. dos_* and mboot are meaningful).
   1624  * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
   1625  *		  dos_cylindersectors to be consistent with what the
   1626  *		  partition table is using, if we can find a geometry
   1627  *		  which is consistent with all partition table entries.
   1628  *		  We may get the number of cylinders slightly wrong (in
   1629  *		  the conservative direction).  The idea is to be able
   1630  *		  to create a NetBSD partition on a disk we don't know
   1631  *		  the translated geometry of.
   1632  * This routine is only used for non-x86 systems or when we fail to
   1633  * get the BIOS geometry from the kernel.
   1634  */
   1635 static void
   1636 intuit_translated_geometry(void)
   1637 {
   1638 	uint32_t xcylinders;
   1639 	int xheads = -1, xsectors = -1, i, j;
   1640 	unsigned int c1, h1, s1, c2, h2, s2;
   1641 	unsigned long a1, a2;
   1642 	uint64_t num, denom;
   1643 
   1644 	/*
   1645 	 * The physical parameters may be invalid as bios geometry.
   1646 	 * If we cannot determine the actual bios geometry, we are
   1647 	 * better off picking a likely 'faked' geometry than leaving
   1648 	 * the invalid physical one.
   1649 	 */
   1650 
   1651 	if (dos_cylinders > MAXCYL || dos_heads > MAXHEAD ||
   1652 	    dos_sectors > MAXSECTOR) {
   1653 		h1 = MAXHEAD - 1;
   1654 		c1 = MAXCYL - 1;
   1655 #if defined(USE_DISKLIST)
   1656 		if (dl != NULL) {
   1657 			/* BIOS may use 256 heads or 1024 cylinders */
   1658 			for (i = 0; i < dl->dl_nbiosdisks; i++) {
   1659 				if (h1 < (unsigned int)dl->dl_biosdisks[i].bi_head)
   1660 					h1 = dl->dl_biosdisks[i].bi_head;
   1661 				if (c1 < (unsigned int)dl->dl_biosdisks[i].bi_cyl)
   1662 					c1 = dl->dl_biosdisks[i].bi_cyl;
   1663 			}
   1664 		}
   1665 #endif
   1666 		dos_sectors = MAXSECTOR;
   1667 		dos_heads = h1;
   1668 		dos_cylinders = disklabel.d_secperunit / (MAXSECTOR * h1);
   1669 		if (dos_cylinders > c1)
   1670 			dos_cylinders = c1;
   1671 	}
   1672 
   1673 	/* Try to deduce the number of heads from two different mappings. */
   1674 	for (i = 0; i < MBR_PART_COUNT * 2 - 1; i++) {
   1675 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
   1676 			continue;
   1677 		a1 -= s1;
   1678 		for (j = i + 1; j < MBR_PART_COUNT * 2; j++) {
   1679 			if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
   1680 				continue;
   1681 			a2 -= s2;
   1682 			num = (uint64_t)h1 * a2 - (uint64_t)h2 * a1;
   1683 			denom = (uint64_t)c2 * a1 - (uint64_t)c1 * a2;
   1684 			if (denom != 0 && num != 0 && num % denom == 0) {
   1685 				xheads = num / denom;
   1686 				xsectors = a1 / (c1 * xheads + h1);
   1687 				break;
   1688 			}
   1689 		}
   1690 		if (xheads != -1)
   1691 			break;
   1692 	}
   1693 
   1694 	if (xheads == -1) {
   1695 		if (F_flag)
   1696 			return;
   1697 		warnx("Cannot determine the number of heads");
   1698 		return;
   1699 	}
   1700 
   1701 	if (xsectors == -1) {
   1702 		warnx("Cannot determine the number of sectors");
   1703 		return;
   1704 	}
   1705 
   1706 	/* Estimate the number of cylinders. */
   1707 	xcylinders = disklabel.d_secperunit / xheads / xsectors;
   1708 	if (disklabel.d_secperunit > xcylinders * xheads * xsectors)
   1709 		xcylinders++;
   1710 
   1711 	/*
   1712 	 * Now verify consistency with each of the partition table entries.
   1713 	 * Be willing to shove cylinders up a little bit to make things work,
   1714 	 * but translation mismatches are fatal.
   1715 	 */
   1716 	for (i = 0; i < MBR_PART_COUNT * 2; i++) {
   1717 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
   1718 			continue;
   1719 		if (c1 >= MAXCYL - 2)
   1720 			continue;
   1721 		if (xsectors * (c1 * xheads + h1) + s1 != a1)
   1722 			return;
   1723 	}
   1724 
   1725 
   1726 	/* Everything checks out.
   1727 	 * Reset the geometry to use for further calculations.
   1728 	 * But cylinders cannot be > 1024.
   1729 	 */
   1730 	if (xcylinders > MAXCYL)
   1731 		dos_cylinders = MAXCYL;
   1732 	else
   1733 		dos_cylinders = xcylinders;
   1734 	dos_heads = xheads;
   1735 	dos_sectors = xsectors;
   1736 }
   1737 
   1738 /*
   1739  * For the purposes of intuit_translated_geometry(), treat the partition
   1740  * table as a list of eight mapping between (cylinder, head, sector)
   1741  * triplets and absolute sectors.  Get the relevant geometry triplet and
   1742  * absolute sectors for a given entry, or return -1 if it isn't present.
   1743  * Note: for simplicity, the returned sector is 0-based.
   1744  */
   1745 static int
   1746 get_mapping(int i, unsigned int *cylinder, unsigned int *head, unsigned int *sector,
   1747     unsigned long *absolute)
   1748 {
   1749 	struct mbr_partition *part = &mboot.mbr_parts[i / 2];
   1750 
   1751 	if (part->mbrp_type == 0)
   1752 		return -1;
   1753 	if (i % 2 == 0) {
   1754 		*cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
   1755 		*head = part->mbrp_shd;
   1756 		*sector = MBR_PSECT(part->mbrp_ssect);
   1757 		*absolute = le32toh(part->mbrp_start);
   1758 	} else {
   1759 		*cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
   1760 		*head = part->mbrp_ehd;
   1761 		*sector = MBR_PSECT(part->mbrp_esect);
   1762 		*absolute = le32toh(part->mbrp_start)
   1763 		    + le32toh(part->mbrp_size) - 1;
   1764 	}
   1765 	/* Sanity check the data against all zeroes */
   1766 	if ((*cylinder == 0) && (*sector == 0) && (*head == 0))
   1767 		return -1;
   1768 	/* sector numbers in the MBR partition table start at 1 */
   1769 	*sector = *sector - 1;
   1770 	/* Sanity check the data against max values */
   1771 	if ((((*cylinder * MAXHEAD) + *head) * MAXSECTOR + *sector) < *absolute)
   1772 		/* cannot be a CHS mapping */
   1773 		return -1;
   1774 	return 0;
   1775 }
   1776 
   1777 static void
   1778 delete_ptn(int part)
   1779 {
   1780 	if (part == ext.ptn_id) {
   1781 		/* forget all about the extended partition */
   1782 		free(ext.ptn);
   1783 		memset(&ext, 0, sizeof ext);
   1784 	}
   1785 
   1786 	mboot.mbr_parts[part].mbrp_type = 0;
   1787 }
   1788 
   1789 static void
   1790 delete_ext_ptn(int part)
   1791 {
   1792 
   1793 	if (part == 0) {
   1794 		ext.ptn[0].mbr_parts[0].mbrp_type = 0;
   1795 		return;
   1796 	}
   1797 	ext.ptn[part - 1].mbr_parts[1] = ext.ptn[part].mbr_parts[1];
   1798 	memmove(&ext.ptn[part], &ext.ptn[part + 1],
   1799 		(ext.num_ptn - part - 1) * sizeof ext.ptn[0]);
   1800 	ext.num_ptn--;
   1801 }
   1802 
   1803 static int
   1804 add_ext_ptn(daddr_t start, daddr_t size)
   1805 {
   1806 	int part;
   1807 	struct mbr_partition *partp;
   1808 	struct mbr_sector *nptn;
   1809 
   1810 	nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
   1811 	if (!nptn)
   1812 		err(1, "realloc");
   1813 	ext.ptn = nptn;
   1814 	for (part = 0; part < ext.num_ptn; part++)
   1815 		if (ext_offset(part) > start)
   1816 			break;
   1817 	/* insert before 'part' - make space... */
   1818 	memmove(&ext.ptn[part + 1], &ext.ptn[part],
   1819 		(ext.num_ptn - part) * sizeof ext.ptn[0]);
   1820 	memset(&ext.ptn[part], 0, sizeof ext.ptn[0]);
   1821 	ext.ptn[part].mbr_magic = LE_MBR_MAGIC;
   1822 	/* we will be 'part' */
   1823 	if (part == 0) {
   1824 		/* link us to 'next' */
   1825 		partp = &ext.ptn[0].mbr_parts[1];
   1826 		/* offset will be fixed by caller */
   1827 		partp->mbrp_size = htole32(
   1828 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_start) +
   1829 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_size));
   1830 	} else {
   1831 		/* link us to prev's next */
   1832 		partp = &ext.ptn[part - 1].mbr_parts[1];
   1833 		ext.ptn[part].mbr_parts[1] = *partp;
   1834 		/* and prev onto us */
   1835 		partp->mbrp_start = htole32(start - ptn_0_offset - ext.base);
   1836 		partp->mbrp_size = htole32(size + ptn_0_offset);
   1837 	}
   1838 	partp->mbrp_type = 5;	/* as used by win98 */
   1839 	partp->mbrp_flag = 0;
   1840 	/* wallop in some CHS values - win98 doesn't saturate them */
   1841 	dos(le32toh(partp->mbrp_start),
   1842 	    &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
   1843 	dos(le32toh(partp->mbrp_start) + le32toh(partp->mbrp_size) - 1,
   1844 	    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
   1845 	ext.num_ptn++;
   1846 
   1847 	return part;
   1848 }
   1849 
   1850 static const char *
   1851 check_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
   1852 {
   1853 	int p;
   1854 	unsigned int p_s, p_e;
   1855 
   1856 	if (sysid != 0) {
   1857 		if (start == 0)
   1858 			return "Sector zero is reserved for the MBR";
   1859 #if 0
   1860 		if (start < ptn_0_offset)
   1861 			/* This is just a convention, not a requirement */
   1862 			return "Track zero is reserved for the BIOS";
   1863 #endif
   1864 		if (start + size > disksectors)
   1865 			return "Partition exceeds size of disk";
   1866 		for (p = 0; p < MBR_PART_COUNT; p++) {
   1867 			if (p == part || mboot.mbr_parts[p].mbrp_type == 0)
   1868 				continue;
   1869 			p_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   1870 			p_e = p_s + le32toh(mboot.mbr_parts[p].mbrp_size);
   1871 			if (start + size <= p_s || start >= p_e)
   1872 				continue;
   1873 			if (f_flag) {
   1874 				if (fix)
   1875 					delete_ptn(p);
   1876 				return 0;
   1877 			}
   1878 			return "Overlaps another partition";
   1879 		}
   1880 	}
   1881 
   1882 	/* Are we trying to create an extended partition */
   1883 	if (!MBR_IS_EXTENDED(mboot.mbr_parts[part].mbrp_type)) {
   1884 		/* this wasn't the extended partition */
   1885 		if (!MBR_IS_EXTENDED(sysid))
   1886 			return 0;
   1887 		/* making an extended partition */
   1888 		if (ext.base != 0) {
   1889 			if (!f_flag)
   1890 				return "There cannot be 2 extended partitions";
   1891 			if (fix)
   1892 				delete_ptn(ext.ptn_id);
   1893 		}
   1894 		if (fix) {
   1895 			/* allocate a new extended partition */
   1896 			ext.ptn = calloc(1, sizeof ext.ptn[0]);
   1897 			if (ext.ptn == NULL)
   1898 				err(1, "Malloc failed");
   1899 			ext.ptn[0].mbr_magic = LE_MBR_MAGIC;
   1900 			ext.ptn_id = part;
   1901 			ext.base = start;
   1902 			ext.limit = start + size;
   1903 			ext.num_ptn = 1;
   1904 		}
   1905 		return 0;
   1906 	}
   1907 
   1908 	/* Check we haven't cut space allocated to an extended ptn */
   1909 
   1910 	if (!MBR_IS_EXTENDED(sysid)) {
   1911 		/* no longer an extended partition */
   1912 		if (fix) {
   1913 			/* Kill all memory of the extended partitions */
   1914 			delete_ptn(part);
   1915 			return 0;
   1916 		}
   1917 		if (ext.num_ptn == 0 ||
   1918 		    (ext.num_ptn == 1 && ext.ptn[0].mbr_parts[0].mbrp_type == 0))
   1919 			/* nothing in extended partition */
   1920 			return 0;
   1921 		if (f_flag)
   1922 			return 0;
   1923 		if (yesno("Do you really want to delete all the extended partitions?"))
   1924 			return 0;
   1925 		return "Extended partition busy";
   1926 	}
   1927 
   1928 	if (le32toh(mboot.mbr_parts[part].mbrp_start) != ext.base)
   1929 		/* maybe impossible, but an extra sanity check */
   1930 		return 0;
   1931 
   1932 	for (p = ext.num_ptn; --p >= 0;) {
   1933 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1934 			continue;
   1935 		p_s = ext_offset(p);
   1936 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   1937 			  + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   1938 		if (p_s >= start && p_e <= start + size)
   1939 			continue;
   1940 		if (!f_flag)
   1941 			return "Extended partition outside main partition";
   1942 		if (fix)
   1943 			delete_ext_ptn(p);
   1944 	}
   1945 
   1946 	if (fix && start != ext.base) {
   1947 		/* The internal offsets need to be fixed up */
   1948 		for (p = 0; p < ext.num_ptn - 1; p++)
   1949 			ext.ptn[p].mbr_parts[1].mbrp_start = htole32(
   1950 			    le32toh(ext.ptn[p].mbr_parts[1].mbrp_start)
   1951 				    + ext.base - start);
   1952 		/* and maybe an empty partition at the start */
   1953 		if (ext.ptn[0].mbr_parts[0].mbrp_type == 0) {
   1954 			if (le32toh(ext.ptn[0].mbr_parts[1].mbrp_start) == 0) {
   1955 				/* don't need the empty slot */
   1956 				memmove(&ext.ptn[0], &ext.ptn[1],
   1957 					(ext.num_ptn - 1) * sizeof ext.ptn[0]);
   1958 				ext.num_ptn--;
   1959 			}
   1960 		} else {
   1961 			/* must create an empty slot */
   1962 			add_ext_ptn(start, ptn_0_offset);
   1963 			ext.ptn[0].mbr_parts[1].mbrp_start = htole32(ext.base
   1964 								- start);
   1965 		}
   1966 	}
   1967 	if (fix) {
   1968 		ext.base = start;
   1969 		ext.limit = start + size;
   1970 	}
   1971 	return 0;
   1972 }
   1973 
   1974 static const char *
   1975 check_ext_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
   1976 {
   1977 	int p;
   1978 	unsigned int p_s, p_e;
   1979 
   1980 	if (sysid == 0)
   1981 		return 0;
   1982 
   1983 	if (MBR_IS_EXTENDED(sysid))
   1984 		return "Nested extended partitions are not allowed";
   1985 
   1986 	/* allow one track at start for extended partition header */
   1987 	start -= ptn_0_offset;
   1988 	size += ptn_0_offset;
   1989 	if (start < ext.base || start + size > ext.limit)
   1990 		return "Outside bounds of extended partition";
   1991 
   1992 	if (f_flag && !fix)
   1993 		return 0;
   1994 
   1995 	for (p = ext.num_ptn; --p >= 0;) {
   1996 		if (p == part || ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1997 			continue;
   1998 		p_s = ext_offset(p);
   1999 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2000 			+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   2001 		if (p == 0)
   2002 			p_s += le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2003 							- ptn_0_offset;
   2004 		if (start < p_e && start + size > p_s) {
   2005 			if (!f_flag)
   2006 				return "Overlaps another extended partition";
   2007 			if (fix) {
   2008 				if (part == -1)
   2009 					delete_ext_ptn(p);
   2010 				else
   2011 					/* must not change numbering yet */
   2012 					ext.ptn[p].mbr_parts[0].mbrp_type = 0;
   2013 			}
   2014 		}
   2015 	}
   2016 	return 0;
   2017 }
   2018 
   2019 static int
   2020 change_part(int extended, int part, int sysid, daddr_t start, daddr_t size,
   2021 	char *bootmenu)
   2022 {
   2023 	struct mbr_partition *partp;
   2024 	struct mbr_sector *boot;
   2025 	daddr_t offset;
   2026 	const char *e;
   2027 	int upart = part;
   2028 	int p;
   2029 	int fl;
   2030 	daddr_t n_s, n_e;
   2031 	const char *errtext;
   2032 #ifdef BOOTSEL
   2033 	char tmp_bootmenu[MBR_PART_COUNT * (MBR_BS_PARTNAMESIZE + 1)];
   2034 	int bootmenu_len = (extended ? MBR_PART_COUNT : 1) * (MBR_BS_PARTNAMESIZE + 1);
   2035 #endif
   2036 
   2037 	if (extended) {
   2038 		if (part != -1 && part < ext.num_ptn) {
   2039 			boot = &ext.ptn[part];
   2040 			partp = &boot->mbr_parts[0];
   2041 			offset = ext_offset(part);
   2042 		} else {
   2043 			part = -1;
   2044 			boot = 0;
   2045 			partp = 0;
   2046 			offset = 0;
   2047 		}
   2048 		upart = 0;
   2049 		e = "E";
   2050 	} else {
   2051 		boot = &mboot;
   2052 		partp = &boot->mbr_parts[part];
   2053 		offset = 0;
   2054 		e = "";
   2055 	}
   2056 
   2057 	if (!f_flag && part != -1) {
   2058 		printf("The data for partition %s%d is:\n", e, part);
   2059 		print_part(boot, upart, offset);
   2060 	}
   2061 
   2062 #ifdef BOOTSEL
   2063 	if (bootmenu != NULL)
   2064 		strlcpy(tmp_bootmenu, bootmenu, bootmenu_len);
   2065 	else
   2066 		if (boot != NULL && boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   2067 			strlcpy(tmp_bootmenu,
   2068 				boot->mbr_bootsel.mbrbs_nametab[upart],
   2069 				bootmenu_len);
   2070 		else
   2071 			tmp_bootmenu[0] = 0;
   2072 #endif
   2073 
   2074 	if (partp != NULL) {
   2075 		if (!s_flag) {
   2076 			/* values not specified, default to current ones */
   2077 			sysid = partp->mbrp_type;
   2078 			start = offset + le32toh(partp->mbrp_start);
   2079 			size = le32toh(partp->mbrp_size);
   2080 		} else {
   2081 			if (sysid == -1)
   2082 				sysid = partp->mbrp_type;
   2083 			if (start == (daddr_t)0xffffffff) {
   2084 				start = offset + le32toh(partp->mbrp_start);
   2085 				if (start == 0)
   2086 					start = offset = ptn_0_offset;
   2087 			}
   2088 			if (size == (daddr_t)0xffffffff) {
   2089 				size = le32toh(partp->mbrp_size);
   2090 				if (size == 0)
   2091 					size = disksectors - start;
   2092 			}
   2093 		}
   2094 	}
   2095 
   2096 	/* creating a new partition, default to free space */
   2097 	if (!s_flag && sysid == 0 && extended) {
   2098 		/* non-extended partition */
   2099 		start = ext.base;
   2100 		for (p = 0; p < ext.num_ptn; p++) {
   2101 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2102 				continue;
   2103 			n_s = ext_offset(p);
   2104 			if (n_s > start + ptn_0_offset)
   2105 				break;
   2106 			start = ext_offset(p)
   2107 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2108 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   2109 		}
   2110 		if (ext.limit - start <= ptn_0_offset) {
   2111 			printf("No space in extended partition\n");
   2112 			return 0;
   2113 		}
   2114 		start += ptn_0_offset;
   2115 	}
   2116 
   2117 	if (!s_flag && sysid == 0 && !extended) {
   2118 		/* same for non-extended partition */
   2119 		/* first see if old start is free */
   2120 		if (start < ptn_0_offset)
   2121 			start = 0;
   2122 		for (p = 0; start != 0 && p < MBR_PART_COUNT; p++) {
   2123 			if (mboot.mbr_parts[p].mbrp_type == 0)
   2124 				continue;
   2125 			n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2126 			if (start >= n_s &&
   2127 			    start < n_s + le32toh(mboot.mbr_parts[p].mbrp_size))
   2128 				start = 0;
   2129 		}
   2130 		if (start == 0) {
   2131 			/* Look for first gap */
   2132 			start = ptn_0_offset;
   2133 			for (p = 0; p < MBR_PART_COUNT; p++) {
   2134 				if (mboot.mbr_parts[p].mbrp_type == 0)
   2135 					continue;
   2136 				n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2137 				n_e = n_s + le32toh(mboot.mbr_parts[p].mbrp_size);
   2138 				if (start >= n_s && start < n_e) {
   2139 					start = n_e;
   2140 					p = -1;
   2141 				}
   2142 			}
   2143 			if (start >= disksectors && !I_flag) {
   2144 				printf("No free space\n");
   2145 				return 0;
   2146 			}
   2147 		}
   2148 	}
   2149 
   2150 	if (!f_flag) {
   2151 		/* request new values from user */
   2152 		if (sysid == 0)
   2153 			sysid = 169;
   2154 		sysid = decimal("sysid", sysid, 0, 0, 255);
   2155 		if (sysid == 0 && !v_flag) {
   2156 			start = 0;
   2157 			size = 0;
   2158 #ifdef BOOTSEL
   2159 			tmp_bootmenu[0] = 0;
   2160 #endif
   2161 		} else {
   2162 			daddr_t old = start;
   2163 			daddr_t lim = extended ? ext.limit : disksectors;
   2164 			start = decimal("start", start,
   2165 				DEC_SEC | DEC_RND_0 | (extended ? DEC_RND : 0),
   2166 				extended ? ext.base : 0, lim);
   2167 			/* Adjust 'size' so that end doesn't move when 'start'
   2168 			 * is only changed slightly.
   2169 			 */
   2170 			if (size > start - old)
   2171 				size -= start - old;
   2172 			else
   2173 				size = 0;
   2174 			/* Find end of available space from this start point */
   2175 			if (extended) {
   2176 				for (p = 0; p < ext.num_ptn; p++) {
   2177 					if (p == part)
   2178 						continue;
   2179 					if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2180 						continue;
   2181 					n_s = ext_offset(p);
   2182 					if (n_s > start && n_s < lim)
   2183 						lim = n_s;
   2184 					if (start >= n_s && start < n_s
   2185 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2186 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size)) {
   2187 						lim = start;
   2188 						break;
   2189 					}
   2190 				}
   2191 			} else {
   2192 				for (p = 0; p < MBR_PART_COUNT; p++) {
   2193 					if (p == part)
   2194 						continue;
   2195 					if (mboot.mbr_parts[p].mbrp_type == 0)
   2196 						continue;
   2197 					n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2198 					if (n_s > start && n_s < lim)
   2199 						lim = n_s;
   2200 					if (start >= n_s && start < n_s
   2201 				    + le32toh(mboot.mbr_parts[p].mbrp_size)) {
   2202 						lim = start;
   2203 						break;
   2204 					}
   2205 				}
   2206 			}
   2207 			lim -= start;
   2208 			if (lim == 0) {
   2209 				printf("Start sector already allocated\n");
   2210 				return 0;
   2211 			}
   2212 			if (size == 0 || size > lim)
   2213 				size = lim;
   2214 			fl = DEC_SEC;
   2215 			if (start % ptn_alignment == ptn_0_offset)
   2216 				fl |= DEC_RND_DOWN;
   2217 			if (start == 2 * ptn_0_offset)
   2218 				fl |= DEC_RND_DOWN | DEC_RND_DOWN_2;
   2219 			size = decimal("size", size, fl, 0, lim);
   2220 #ifdef BOOTSEL
   2221 #ifndef DEFAULT_BOOTEXTCODE
   2222 			if (!extended)
   2223 #endif
   2224 				string("bootmenu", bootmenu_len, tmp_bootmenu);
   2225 #endif
   2226 		}
   2227 	}
   2228 
   2229 	/*
   2230 	 * Before we write these away, we must verify that nothing
   2231 	 * untoward has been requested.
   2232 	 */
   2233 
   2234 	if (extended)
   2235 		errtext = check_ext_overlap(part, sysid, start, size, 0);
   2236 	else
   2237 		errtext = check_overlap(part, sysid, start, size, 0);
   2238 	if (errtext != NULL && !I_flag) {
   2239 		if (f_flag)
   2240 			errx(2, "%s", errtext);
   2241 		printf("%s\n", errtext);
   2242 		return 0;
   2243 	}
   2244 
   2245 	/*
   2246 	 * Before proceeding, delete any overlapped partitions.
   2247 	 * This can only happen if '-f' was supplied on the command line.
   2248 	 * Just hope the caller knows what they are doing.
   2249 	 * This also fixes the base of each extended partition if the
   2250 	 * partition itself has moved.
   2251 	 */
   2252 	if (!I_flag) {
   2253 		if (extended)
   2254 			errtext = check_ext_overlap(part, sysid, start, size, 1);
   2255 		else
   2256 			errtext = check_overlap(part, sysid, start, size, 1);
   2257 		if (errtext)
   2258 			errx(1, "%s", errtext);
   2259 	}
   2260 
   2261 
   2262 	if (sysid == 0) {
   2263 		/* delete this partition - save info though */
   2264 		if (partp == NULL)
   2265 			/* must have been trying to create an extended ptn */
   2266 			return 0;
   2267 		if (start == 0 && size == 0)
   2268 			memset(partp, 0, sizeof *partp);
   2269 #ifdef BOOTSEL
   2270 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   2271 			memset(boot->mbr_bootsel.mbrbs_nametab[upart], 0,
   2272 				sizeof boot->mbr_bootsel.mbrbs_nametab[0]);
   2273 #endif
   2274 		if (extended)
   2275 			delete_ext_ptn(part);
   2276 		else
   2277 			delete_ptn(part);
   2278 		return 1;
   2279 	}
   2280 
   2281 
   2282 	if (extended) {
   2283 		if (part != -1)
   2284 			delete_ext_ptn(part);
   2285 		if (start == ext.base + ptn_0_offset)
   2286 			/* First one must have been free */
   2287 			part = 0;
   2288 		else
   2289 			part = add_ext_ptn(start, size);
   2290 
   2291 		/* These must be re-calculated because of the realloc */
   2292 		boot = &ext.ptn[part];
   2293 		partp = &boot->mbr_parts[0];
   2294 		offset = ext_offset(part);
   2295 	}
   2296 
   2297 	partp->mbrp_type = sysid;
   2298 	partp->mbrp_start = htole32( start - offset);
   2299 	partp->mbrp_size = htole32( size);
   2300 	dos(start, &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
   2301 	dos(start + size - 1,
   2302 		    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
   2303 #ifdef BOOTSEL
   2304 	if (extended) {
   2305 		boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
   2306 		strncpy(boot->mbr_bootsel.mbrbs_nametab[upart], tmp_bootmenu,
   2307 			bootmenu_len);
   2308 	} else {
   2309 		/* We need to bootselect code installed in order to have
   2310 		 * somewhere to safely write the menu tag.
   2311 		 */
   2312 		if (boot->mbr_bootsel_magic != LE_MBR_BS_MAGIC) {
   2313 			if (f_flag ||
   2314 			    yesno("The bootselect code is not installed, "
   2315 				"do you want to install it now?"))
   2316 				install_bootsel(MBR_BS_ACTIVE);
   2317 		}
   2318 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
   2319 			strncpy(boot->mbr_bootsel.mbrbs_nametab[upart],
   2320 				tmp_bootmenu, bootmenu_len);
   2321 		}
   2322 	}
   2323 #endif
   2324 
   2325 	if (v_flag && !f_flag && yesno("Explicitly specify beg/end address?")) {
   2326 		/* this really isn't a good idea.... */
   2327 		int tsector, tcylinder, thead;
   2328 
   2329 		tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
   2330 		thead = partp->mbrp_shd;
   2331 		tsector = MBR_PSECT(partp->mbrp_ssect);
   2332 		tcylinder = decimal("beginning cylinder",
   2333 				tcylinder, 0, 0, dos_cylinders - 1);
   2334 		thead = decimal("beginning head",
   2335 				thead, 0, 0, dos_heads - 1);
   2336 		tsector = decimal("beginning sector",
   2337 				tsector, 0, 1, dos_sectors);
   2338 		partp->mbrp_scyl = DOSCYL(tcylinder);
   2339 		partp->mbrp_shd = thead;
   2340 		partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
   2341 
   2342 		tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
   2343 		thead = partp->mbrp_ehd;
   2344 		tsector = MBR_PSECT(partp->mbrp_esect);
   2345 		tcylinder = decimal("ending cylinder",
   2346 				tcylinder, 0, 0, dos_cylinders - 1);
   2347 		thead = decimal("ending head",
   2348 				thead, 0, 0, dos_heads - 1);
   2349 		tsector = decimal("ending sector",
   2350 				tsector, 0, 1, dos_sectors);
   2351 		partp->mbrp_ecyl = DOSCYL(tcylinder);
   2352 		partp->mbrp_ehd = thead;
   2353 		partp->mbrp_esect = DOSSECT(tsector, tcylinder);
   2354 	}
   2355 
   2356 	/* If we had to mark an extended partition as deleted because
   2357 	 * another request would have overlapped it, now is the time
   2358 	 * to do the actual delete.
   2359 	 */
   2360 	if (extended && f_flag) {
   2361 		for (p = ext.num_ptn; --p >= 0;)
   2362 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2363 				delete_ext_ptn(p);
   2364 	}
   2365 	return 1;
   2366 }
   2367 
   2368 static void
   2369 print_geometry(void)
   2370 {
   2371 
   2372 	if (sh_flag) {
   2373 		printf("DISK=%s\n", disk);
   2374 		printf("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%"PRIdaddr"\n",
   2375 			cylinders, heads, sectors, disksectors);
   2376 		printf("BCYL=%d\nBHEAD=%d\nBSEC=%d\nBDLSIZE=%"PRIdaddr"\n",
   2377 			dos_cylinders, dos_heads, dos_sectors, dos_disksectors);
   2378 		printf("NUMEXTPTN=%d\n", ext.num_ptn);
   2379 		return;
   2380 	}
   2381 
   2382 	/* Not sh_flag */
   2383 	printf("Disk: %s\n", disk);
   2384 	printf("NetBSD disklabel disk geometry:\n");
   2385 	printf("cylinders: %d, heads: %d, sectors/track: %d "
   2386 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr", "
   2387 	    "bytes/sector: %zd\n\n", cylinders, heads, sectors,
   2388 	    cylindersectors, disksectors, secsize);
   2389 	printf("BIOS disk geometry:\n");
   2390 	printf("cylinders: %d, heads: %d, sectors/track: %d "
   2391 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
   2392 	    dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors,
   2393 	    dos_disksectors);
   2394 	printf("Partitions aligned to %d sector boundaries, offset %d\n\n",
   2395 	    ptn_alignment, ptn_0_offset);
   2396 }
   2397 
   2398 /* Find the first active partition, else return MBR_PART_COUNT */
   2399 static int
   2400 first_active(void)
   2401 {
   2402 	struct mbr_partition *partp = &mboot.mbr_parts[0];
   2403 	int part;
   2404 
   2405 	for (part = 0; part < MBR_PART_COUNT; part++)
   2406 		if (partp[part].mbrp_flag & MBR_PFLAG_ACTIVE)
   2407 			return part;
   2408 	return MBR_PART_COUNT;
   2409 }
   2410 
   2411 static void
   2412 change_active(int which)
   2413 {
   2414 	struct mbr_partition *partp;
   2415 	int part;
   2416 	int active = MBR_PART_COUNT;
   2417 
   2418 	partp = &mboot.mbr_parts[0];
   2419 
   2420 	if (a_flag && which != -1)
   2421 		active = which;
   2422 	else
   2423 		active = first_active();
   2424 	if (!f_flag) {
   2425 		if (yesno("Do you want to change the active partition?")) {
   2426 			printf ("Choosing %d will make no partition active.\n",
   2427 			    MBR_PART_COUNT);
   2428 			do {
   2429 				active = decimal("active partition",
   2430 						active, 0, 0, MBR_PART_COUNT);
   2431 			} while (!yesno("Are you happy with this choice?"));
   2432 		} else
   2433 			return;
   2434 	} else
   2435 		if (active != MBR_PART_COUNT)
   2436 			printf ("Making partition %d active.\n", active);
   2437 
   2438 	for (part = 0; part < MBR_PART_COUNT; part++)
   2439 		partp[part].mbrp_flag &= ~MBR_PFLAG_ACTIVE;
   2440 	if (active < MBR_PART_COUNT)
   2441 		partp[active].mbrp_flag |= MBR_PFLAG_ACTIVE;
   2442 }
   2443 
   2444 static void
   2445 change_bios_geometry(void)
   2446 {
   2447 	print_geometry();
   2448 	if (!yesno("Do you want to change our idea of what BIOS thinks?"))
   2449 		return;
   2450 
   2451 #if defined(USE_DISKLIST)
   2452 	if (dl != NULL) {
   2453 		struct biosdisk_info *bip;
   2454 		int i;
   2455 
   2456 		for (i = 0; i < dl->dl_nbiosdisks; i++) {
   2457 			if (i == 0)
   2458 				printf("\nGeometries of known disks:\n");
   2459 			bip = &dl->dl_biosdisks[i];
   2460 			printf("Disk %d: cylinders %u, heads %u, sectors %u"
   2461 				" (%"PRIdaddr" sectors, %dMB)\n",
   2462 			    i, bip->bi_cyl, bip->bi_head, bip->bi_sec,
   2463 			    bip->bi_lbasecs, SEC_TO_MB(bip->bi_lbasecs));
   2464 
   2465 		}
   2466 		printf("\n");
   2467 	}
   2468 #endif
   2469 	do {
   2470 		dos_cylinders = decimal("BIOS's idea of #cylinders",
   2471 					dos_cylinders, 0, 0, MAXCYL);
   2472 		dos_heads = decimal("BIOS's idea of #heads",
   2473 					dos_heads, 0, 0, MAXHEAD);
   2474 		dos_sectors = decimal("BIOS's idea of #sectors",
   2475 					dos_sectors, 0, 1, MAXSECTOR);
   2476 		print_geometry();
   2477 	} while (!yesno("Are you happy with this choice?"));
   2478 }
   2479 
   2480 
   2481 /***********************************************\
   2482 * Change real numbers into strange dos numbers	*
   2483 \***********************************************/
   2484 static void
   2485 dos(int sector, unsigned char *cylinderp, unsigned char *headp,
   2486     unsigned char *sectorp)
   2487 {
   2488 	int cylinder, head;
   2489 
   2490 	cylinder = sector / dos_cylindersectors;
   2491 	sector -= cylinder * dos_cylindersectors;
   2492 
   2493 	head = sector / dos_sectors;
   2494 	sector -= head * dos_sectors;
   2495 	if (cylinder > 1023)
   2496 		cylinder = 1023;
   2497 
   2498 	*cylinderp = DOSCYL(cylinder);
   2499 	*headp = head;
   2500 	*sectorp = DOSSECT(sector + 1, cylinder);
   2501 }
   2502 
   2503 static int
   2504 open_disk(int update)
   2505 {
   2506 	static char namebuf[MAXPATHLEN + 1];
   2507 	int flags = update && disk_file == NULL ? O_RDWR : O_RDONLY;
   2508 
   2509 	if (!F_flag) {
   2510 		fd = opendisk(disk, flags, namebuf, sizeof(namebuf), 0);
   2511 		if (fd < 0) {
   2512 			if (errno == ENODEV)
   2513 				warnx("%s is not a character device", namebuf);
   2514 			else
   2515 				warn("cannot opendisk %s", namebuf);
   2516 			return (-1);
   2517 		}
   2518 		disk = namebuf;
   2519 	} else {
   2520 		fd = open(disk, flags, 0);
   2521 		if (fd == -1) {
   2522 			warn("cannot open %s", disk);
   2523 			return -1;
   2524 		}
   2525 	}
   2526 
   2527 	if (get_params() == -1) {
   2528 		close(fd);
   2529 		fd = -1;
   2530 		return (-1);
   2531 	}
   2532 	if (disk_file != NULL) {
   2533 		/* for testing: read/write data from a disk file */
   2534 		wfd = open(disk_file, update ? O_RDWR|O_CREAT : O_RDONLY, 0777);
   2535 		if (wfd == -1) {
   2536 			warn("%s", disk_file);
   2537 			close(fd);
   2538 			fd = -1;
   2539 			return -1;
   2540 		}
   2541 	} else
   2542 		wfd = fd;
   2543 	return (0);
   2544 }
   2545 
   2546 static ssize_t
   2547 read_disk(daddr_t sector, void *buf)
   2548 {
   2549 	ssize_t nr;
   2550 
   2551 	if (*rfd == -1)
   2552 		errx(1, "read_disk(); fd == -1");
   2553 
   2554 	off_t offs = sector * (off_t)secsize;
   2555 	off_t mod = offs & (secsize - 1);
   2556 	off_t rnd = offs & ~(secsize - 1);
   2557 
   2558 	if (lseek(*rfd, rnd, SEEK_SET) == (off_t)-1)
   2559 		return -1;
   2560 
   2561 	if (secsize == 512)
   2562 		return read(*rfd, buf, 512);
   2563 
   2564 	if ((nr = read(*rfd, iobuf, secsize)) != secsize)
   2565 		return nr;
   2566 
   2567 	memcpy(buf, &iobuf[mod], 512);
   2568 
   2569 	return 512;
   2570 }
   2571 
   2572 static ssize_t
   2573 write_disk(daddr_t sector, void *buf)
   2574 {
   2575 	ssize_t nr;
   2576 
   2577 	if (wfd == -1)
   2578 		errx(1, "write_disk(); wfd == -1");
   2579 
   2580 	off_t offs = sector * (off_t)secsize;
   2581 	off_t mod = offs & (secsize - 1);
   2582 	off_t rnd = offs & ~(secsize - 1);
   2583 
   2584 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
   2585 		return -1;
   2586 
   2587 	if (secsize == 512)
   2588 		return write(wfd, buf, 512);
   2589 
   2590 	if ((nr = read(wfd, iobuf, secsize)) != secsize)
   2591 		return nr;
   2592 
   2593 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
   2594 		return -1;
   2595 
   2596 	memcpy(&iobuf[mod], buf, 512);
   2597 
   2598 	if ((nr = write(wfd, iobuf, secsize)) != secsize)
   2599 		return nr;
   2600 
   2601 	return 512;
   2602 }
   2603 
   2604 static void
   2605 guess_geometry(daddr_t _sectors)
   2606 {
   2607 	dos_sectors = MAXSECTOR;
   2608 	dos_heads = MAXHEAD - 1;	/* some BIOS might use 256 */
   2609 	dos_cylinders = _sectors / (MAXSECTOR * (MAXHEAD - 1));
   2610 	if (dos_cylinders < 1)
   2611 		dos_cylinders = 1;
   2612 	else if (dos_cylinders > MAXCYL - 1)
   2613 		dos_cylinders = MAXCYL - 1;
   2614 }
   2615 
   2616 static int
   2617 get_params(void)
   2618 {
   2619 	if (disk_type != NULL) {
   2620 		struct disklabel *tmplabel;
   2621 
   2622 		if ((tmplabel = getdiskbyname(disk_type)) == NULL) {
   2623 			warn("bad disktype");
   2624 			return (-1);
   2625 		}
   2626 		disklabel = *tmplabel;
   2627 	} else if (F_flag) {
   2628 		struct stat st;
   2629 		if (fstat(fd, &st) == -1) {
   2630 			warn("fstat");
   2631 			return (-1);
   2632 		}
   2633 		if (st.st_size % 512 != 0) {
   2634 			warnx("%s size (%lld) is not divisible "
   2635 			    "by sector size (%d)", disk, (long long)st.st_size,
   2636 			    512);
   2637 		}
   2638 		disklabel.d_secperunit = st.st_size / 512;
   2639 		guess_geometry(disklabel.d_secperunit);
   2640 		disklabel.d_ncylinders = dos_cylinders;
   2641 		disklabel.d_ntracks = dos_heads;
   2642 		disklabel.d_secsize = 512;
   2643 		disklabel.d_nsectors = dos_sectors;
   2644 	}
   2645 #if !HAVE_NBTOOL_CONFIG_H
   2646 	else if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
   2647 		warn("DIOCGDEFLABEL");
   2648 		if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
   2649 			warn("DIOCGDINFO");
   2650 			return (-1);
   2651 		}
   2652 	}
   2653 #endif
   2654 
   2655 	disksectors = disklabel.d_secperunit;
   2656 	cylinders = disklabel.d_ncylinders;
   2657 	heads = disklabel.d_ntracks;
   2658 	secsize = disklabel.d_secsize;
   2659 	sectors = disklabel.d_nsectors;
   2660 
   2661 	/* pick up some defaults for the BIOS sizes */
   2662 	if (sectors <= MAXSECTOR) {
   2663 		dos_cylinders = cylinders;
   2664 		dos_heads = heads;
   2665 		dos_sectors = sectors;
   2666 	} else {
   2667 		/* guess - has to better than the above */
   2668 		guess_geometry(disksectors);
   2669 	}
   2670 	dos_disksectors = disksectors;
   2671 
   2672 	return (0);
   2673 }
   2674 
   2675 #ifdef BOOTSEL
   2676 /*
   2677  * Rather unfortunately the bootsel 'magic' number is at the end of the
   2678  * the structure, and there is no checksum.  So when other operating
   2679  * systems install mbr code by only writing the length of their code they
   2680  * can overwrite part of the structure but keeping the magic number intact.
   2681  * This code attempts to empirically detect this problem.
   2682  */
   2683 static int
   2684 validate_bootsel(struct mbr_bootsel *mbs)
   2685 {
   2686 	unsigned int key = mbs->mbrbs_defkey;
   2687 	unsigned int tmo;
   2688 	size_t i;
   2689 
   2690 	if (v_flag)
   2691 		return 0;
   2692 
   2693 	/*
   2694 	 * Check default key is sane
   2695 	 * - this is the most likely field to be stuffed
   2696 	 * 16 disks and 16 bootable partitions seems enough!
   2697 	 * (the keymap decode starts falling apart at that point)
   2698 	 */
   2699 	if (mbs->mbrbs_flags & MBR_BS_ASCII) {
   2700 		if (key != 0 && !(key == '\r'
   2701 		    || (key >= '1' && key < '1' + MAX_BIOS_DISKS)
   2702 		    || (key >= 'a' && key < 'a' + MAX_BIOS_DISKS)))
   2703 			return 1;
   2704 	} else {
   2705 		if (key != 0 && !(key == SCAN_ENTER
   2706 		    || (key >= SCAN_1 && key < SCAN_1 + MAX_BIOS_DISKS)
   2707 		    || (key >= SCAN_F1 && key < SCAN_F1 + MAX_BIOS_DISKS)))
   2708 			return 1;
   2709 	}
   2710 
   2711 	/* Checking the flags will lead to breakage... */
   2712 
   2713 	/* Timeout value is expected to be a multiple of a second */
   2714 	tmo = htole16(mbs->mbrbs_timeo);
   2715 	if (tmo != 0 && tmo != 0xffff && tmo != (10 * tmo + 9) / 182 * 182 / 10)
   2716 		return 2;
   2717 
   2718 	/* Check the menu strings are printable */
   2719 	/* Unfortunately they aren't zero filled... */
   2720 	for (i = 0; i < sizeof(mbs->mbrbs_nametab); i++) {
   2721 		int c = (uint8_t)mbs->mbrbs_nametab[0][i];
   2722 		if (c == 0 || isprint(c))
   2723 			continue;
   2724 		return 3;
   2725 	}
   2726 
   2727 	return 0;
   2728 }
   2729 #endif
   2730 
   2731 static int
   2732 read_s0(daddr_t offset, struct mbr_sector *boot)
   2733 {
   2734 	const char *tabletype = offset ? "extended" : "primary";
   2735 #ifdef BOOTSEL
   2736 	static int reported;
   2737 #endif
   2738 
   2739 	if (read_disk(offset, boot) == -1) {
   2740 		warn("Can't read %s partition table", tabletype);
   2741 		return -1;
   2742 	}
   2743 	if (boot->mbr_magic != LE_MBR_MAGIC) {
   2744 		if (F_flag && boot->mbr_magic == 0)
   2745 			return -1;
   2746 		warnx("%s partition table invalid, "
   2747 		    "no magic in sector %"PRIdaddr, tabletype, offset);
   2748 		return -1;
   2749 
   2750 	}
   2751 #ifdef BOOTSEL
   2752 	if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
   2753 		/* mbr_bootsel in new location */
   2754 		if (validate_bootsel(&boot->mbr_bootsel)) {
   2755 			warnx("removing corrupt bootsel information");
   2756 			boot->mbr_bootsel_magic = 0;
   2757 		}
   2758 		return 0;
   2759 	}
   2760 	if (boot->mbr_bootsel_magic != LE_MBR_MAGIC)
   2761 		return 0;
   2762 
   2763 	/* mbr_bootsel in old location */
   2764 	if (!reported)
   2765 		warnx("%s partition table: using old-style bootsel information",
   2766 		    tabletype);
   2767 	reported = 1;
   2768 	if (validate_bootsel((void *)((uint8_t *)boot + MBR_BS_OFFSET + 4))) {
   2769 		warnx("%s bootsel information corrupt - ignoring", tabletype);
   2770 		return 0;
   2771 	}
   2772 	memmove((uint8_t *)boot + MBR_BS_OFFSET,
   2773 		(uint8_t *)boot + MBR_BS_OFFSET + 4,
   2774 		sizeof(struct mbr_bootsel));
   2775 	if ( ! (boot->mbr_bootsel.mbrbs_flags & MBR_BS_NEWMBR)) {
   2776 			/* old style default key */
   2777 		int id;
   2778 			/* F1..F4 => ptn 0..3, F5+ => disk 0+ */
   2779 		id = boot->mbr_bootsel.mbrbs_defkey;
   2780 		id -= SCAN_F1;
   2781 		if (id >= MBR_PART_COUNT)
   2782 			id -= MBR_PART_COUNT; /* Use number of disk */
   2783 		else if (mboot.mbr_parts[id].mbrp_type != 0)
   2784 			id = le32toh(boot->mbr_parts[id].mbrp_start);
   2785 		else
   2786 			id = DEFAULT_ACTIVE;
   2787 		boot->mbr_bootsel.mbrbs_defkey = id;
   2788 	}
   2789 	boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
   2790 		/* highlight that new bootsel code is necessary */
   2791 	boot->mbr_bootsel.mbrbs_flags &= ~MBR_BS_NEWMBR;
   2792 #endif /* BOOTSEL */
   2793 	return 0;
   2794 }
   2795 
   2796 static int
   2797 write_mbr(void)
   2798 {
   2799 	int flag, i;
   2800 	daddr_t offset;
   2801 	int rval = -1;
   2802 
   2803 	/*
   2804 	 * write enable label sector before write (if necessary),
   2805 	 * disable after writing.
   2806 	 * needed if the disklabel protected area also protects
   2807 	 * sector 0. (e.g. empty disk)
   2808 	 */
   2809 	flag = 1;
   2810 #if !HAVE_NBTOOL_CONFIG_H
   2811 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
   2812 		warn("DIOCWLABEL");
   2813 #endif
   2814 	if (write_disk(0, &mboot) == -1) {
   2815 		warn("Can't write fdisk partition table");
   2816 		goto protect_label;
   2817 	}
   2818 	if (boot_installed)
   2819 		for (i = bootsize; (i -= 0x200) > 0;)
   2820 			if (write_disk(i / 0x200, &bootcode[i / 0x200]) == -1) {
   2821 				warn("Can't write bootcode");
   2822 				goto protect_label;
   2823 			}
   2824 	for (offset = 0, i = 0; i < ext.num_ptn; i++) {
   2825 		if (write_disk(ext.base + offset, ext.ptn + i) == -1) {
   2826 			warn("Can't write %dth extended partition", i);
   2827 			goto protect_label;
   2828 		}
   2829 		offset = le32toh(ext.ptn[i].mbr_parts[1].mbrp_start);
   2830 	}
   2831 	rval = 0;
   2832     protect_label:
   2833 	flag = 0;
   2834 #if !HAVE_NBTOOL_CONFIG_H
   2835 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
   2836 		warn("DIOCWLABEL");
   2837 #endif
   2838 	return rval;
   2839 }
   2840 
   2841 static int
   2842 yesno(const char *str, ...)
   2843 {
   2844 	int ch, first;
   2845 	va_list ap;
   2846 
   2847 	va_start(ap, str);
   2848 	vprintf(str, ap);
   2849 	va_end(ap);
   2850 	printf(" [n] ");
   2851 
   2852 	first = ch = getchar();
   2853 	while (ch != '\n' && ch != EOF)
   2854 		ch = getchar();
   2855 	if (ch == EOF)
   2856 		errx(1, "EOF");
   2857 	return (first == 'y' || first == 'Y');
   2858 }
   2859 
   2860 static int64_t
   2861 decimal(const char *prompt, int64_t dflt, int flags, int64_t minval, int64_t maxval)
   2862 {
   2863 	int64_t acc = 0;
   2864 	int valid;
   2865 	int len;
   2866 	char *cp;
   2867 
   2868 	for (;;) {
   2869 		if (flags & DEC_SEC) {
   2870 			printf("%s: [%" PRId64 "..%" PRId64 "cyl default: %" PRId64 ", %" PRId64 "cyl, %uMB] ",
   2871 			    prompt, SEC_TO_CYL(minval), SEC_TO_CYL(maxval),
   2872 			    dflt, SEC_TO_CYL(dflt), SEC_TO_MB(dflt));
   2873 		} else
   2874 			printf("%s: [%" PRId64 "..%" PRId64 " default: %" PRId64 "] ",
   2875 			    prompt, minval, maxval, dflt);
   2876 
   2877 		if (!fgets(lbuf, LBUF, stdin))
   2878 			errx(1, "EOF");
   2879 		cp = lbuf;
   2880 
   2881 		cp += strspn(cp, " \t");
   2882 		if (*cp == '\n')
   2883 			return dflt;
   2884 
   2885 		if (cp[0] == '$' && cp[1] == '\n')
   2886 			return maxval;
   2887 
   2888 		if (isdigit((unsigned char)*cp) || *cp == '-') {
   2889 			acc = strtoll(lbuf, &cp, 10);
   2890 			len = strcspn(cp, " \t\n");
   2891 			valid = 0;
   2892 			if (len != 0 && (flags & DEC_SEC)) {
   2893 				if (!strncasecmp(cp, "gb", len)) {
   2894 					acc *= 1024;
   2895 					valid = 1;
   2896 				}
   2897 				if (valid || !strncasecmp(cp, "mb", len)) {
   2898 					acc *= SEC_IN_1M;
   2899 					/* round to whole number of cylinders */
   2900 					acc += ptn_alignment / 2;
   2901 					acc /= ptn_alignment;
   2902 					valid = 1;
   2903 				}
   2904 				if (valid || !strncasecmp(cp, "cyl", len)) {
   2905 					acc *= ptn_alignment;
   2906 					/* adjustments for cylinder boundary */
   2907 					if (acc == 0 && flags & DEC_RND_0)
   2908 						acc += ptn_0_offset;
   2909 					if (flags & DEC_RND)
   2910 						acc += ptn_0_offset;
   2911 					if (flags & DEC_RND_DOWN)
   2912 						acc -= ptn_0_offset;
   2913 					if (flags & DEC_RND_DOWN_2)
   2914 						acc -= ptn_0_offset;
   2915 					cp += len;
   2916 				}
   2917 			}
   2918 		}
   2919 
   2920 		cp += strspn(cp, " \t");
   2921 		if (*cp != '\n') {
   2922 			lbuf[strlen(lbuf) - 1] = 0;
   2923 			printf("%s is not a valid %s number.\n", lbuf,
   2924 			    flags & DEC_SEC ? "sector" : "decimal");
   2925 			continue;
   2926 		}
   2927 
   2928 		if (acc >= minval && acc <= maxval)
   2929 			return acc;
   2930 		printf("%" PRId64 " is not between %" PRId64 " and %" PRId64 ".\n", acc, minval, maxval);
   2931 	}
   2932 }
   2933 
   2934 static int
   2935 ptn_id(const char *prompt, int *extended)
   2936 {
   2937 	unsigned int acc = 0;
   2938 	char *cp;
   2939 
   2940 	for (;; printf("%s is not a valid partition number.\n", lbuf)) {
   2941 		printf("%s: [none] ", prompt);
   2942 
   2943 		if (!fgets(lbuf, LBUF, stdin))
   2944 			errx(1, "EOF");
   2945 		lbuf[strlen(lbuf)-1] = '\0';
   2946 		cp = lbuf;
   2947 
   2948 		cp += strspn(cp, " \t");
   2949 		*extended = 0;
   2950 		if (*cp == 0)
   2951 			return -1;
   2952 
   2953 		if (*cp == 'E' || *cp == 'e') {
   2954 			cp++;
   2955 			*extended = 1;
   2956 		}
   2957 
   2958 		acc = strtoul(cp, &cp, 10);
   2959 
   2960 		cp += strspn(cp, " \t");
   2961 		if (*cp != '\0')
   2962 			continue;
   2963 
   2964 		if (*extended || acc < MBR_PART_COUNT)
   2965 			return acc;
   2966 	}
   2967 }
   2968 
   2969 #ifdef BOOTSEL
   2970 static void
   2971 string(const char *prompt, int length, char *buf)
   2972 {
   2973 	int len;
   2974 
   2975 	for (;;) {
   2976 		printf("%s: [%.*s] (space to clear)", prompt, length, buf);
   2977 
   2978 		if (!fgets(lbuf, LBUF, stdin))
   2979 			errx(1, "EOF");
   2980 		len = strlen(lbuf);
   2981 		if (len <= 1)
   2982 			/* unchanged if just <enter> */
   2983 			return;
   2984 		/* now strip trailing spaces, <space><enter> deletes string */
   2985 		do
   2986 			lbuf[--len] = 0;
   2987 		while (len != 0 && lbuf[len - 1] == ' ');
   2988 		if (len < length)
   2989 			break;
   2990 		printf("'%s' is longer than %d characters.\n",
   2991 		    lbuf, length - 1);
   2992 	}
   2993 	strncpy(buf, lbuf, length);
   2994 }
   2995 #endif
   2996 
   2997 static int
   2998 type_match(const void *key, const void *item)
   2999 {
   3000 	const int *idp = key;
   3001 	const struct mbr_ptype *ptr = item;
   3002 
   3003 	if (*idp < ptr->id)
   3004 		return (-1);
   3005 	if (*idp > ptr->id)
   3006 		return (1);
   3007 	return (0);
   3008 }
   3009 
   3010 static const char *
   3011 get_type(int type)
   3012 {
   3013 	struct mbr_ptype *ptr;
   3014 
   3015 	ptr = bsearch(&type, mbr_ptypes, KNOWN_SYSIDS,
   3016 	    sizeof(mbr_ptypes[0]), type_match);
   3017 	if (ptr == 0)
   3018 		return ("unknown");
   3019 	return (ptr->name);
   3020 }
   3021 
   3022 static int
   3023 read_gpt(daddr_t offset, struct gpt_hdr *gptp)
   3024 {
   3025 	char buf[512];
   3026 	struct gpt_hdr *hdr = (void *)buf;
   3027 	const char *tabletype = GPT_TYPE(offset);
   3028 
   3029 	if (read_disk(offset, buf) == -1) {
   3030 		warn("Can't read %s GPT header", tabletype);
   3031 		return -1;
   3032 	}
   3033 	(void)memcpy(gptp, buf, GPT_HDR_SIZE);
   3034 
   3035 	/* GPT CRC should be calculated with CRC field preset to zero */
   3036 	hdr->hdr_crc_self = 0;
   3037 
   3038 	if (memcmp(gptp->hdr_sig, GPT_HDR_SIG, sizeof(gptp->hdr_sig))
   3039 	    || gptp->hdr_lba_self != (uint64_t)offset
   3040 	    || crc32(0, (void *)hdr, gptp->hdr_size) != gptp->hdr_crc_self) {
   3041 		/* not a GPT */
   3042 		(void)memset(gptp, 0, GPT_HDR_SIZE);
   3043 	}
   3044 
   3045 	if (v_flag && gptp->hdr_size != 0) {
   3046 		printf("Found %s GPT header CRC %"PRIu32" "
   3047 		    "at sector %"PRIdaddr", backup at %"PRIdaddr"\n",
   3048 		    tabletype, gptp->hdr_crc_self, offset, gptp->hdr_lba_alt);
   3049 	}
   3050 	return gptp->hdr_size;
   3051 
   3052 }
   3053 
   3054 static int
   3055 delete_gpt(struct gpt_hdr *gptp)
   3056 {
   3057 	char buf[512];
   3058 	struct gpt_hdr *hdr = (void *)buf;
   3059 
   3060 	if (gptp->hdr_size == 0)
   3061 		return 0;
   3062 
   3063 	/* don't accidently overwrite something important */
   3064 	if (gptp->hdr_lba_self != GPT_HDR_BLKNO &&
   3065 	    gptp->hdr_lba_self != (uint64_t)disksectors - 1) {
   3066 		warnx("given GPT header location doesn't seem correct");
   3067 		return -1;
   3068 	}
   3069 
   3070 	(void)memcpy(buf, gptp, GPT_HDR_SIZE);
   3071 	/*
   3072 	 * Don't really delete GPT, just "disable" it, so it can
   3073 	 * be recovered later in case of mistake or something
   3074 	 */
   3075 	(void)memset(hdr->hdr_sig, 0, sizeof(gptp->hdr_sig));
   3076 	if (write_disk(gptp->hdr_lba_self, hdr) == -1) {
   3077 		warn("can't delete %s GPT header",
   3078 		    GPT_TYPE(gptp->hdr_lba_self));
   3079 		return -1;
   3080 	}
   3081 	(void)memset(gptp, 0, GPT_HDR_SIZE);
   3082 	return 1;
   3083 }
   3084