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