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