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