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