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