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