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