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