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