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