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