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