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