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