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