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