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