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