Home | History | Annotate | Line # | Download | only in fdisk
fdisk.c revision 1.51
      1 /*	$NetBSD: fdisk.c,v 1.51 2002/03/26 23:56:45 christos Exp $ */
      2 
      3 /*
      4  * Mach Operating System
      5  * Copyright (c) 1992 Carnegie Mellon University
      6  * All Rights Reserved.
      7  *
      8  * Permission to use, copy, modify and distribute this software and its
      9  * documentation is hereby granted, provided that both the copyright
     10  * notice and this permission notice appear in all copies of the
     11  * software, derivative works or modified versions, and any portions
     12  * thereof, and that both notices appear in supporting documentation.
     13  *
     14  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     15  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
     16  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     17  *
     18  * Carnegie Mellon requests users of this software to return to
     19  *
     20  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     21  *  School of Computer Science
     22  *  Carnegie Mellon University
     23  *  Pittsburgh PA 15213-3890
     24  *
     25  * any improvements or extensions that they make and grant Carnegie Mellon
     26  * the rights to redistribute these changes.
     27  */
     28 
     29 #include <sys/cdefs.h>
     30 
     31 #ifndef lint
     32 __RCSID("$NetBSD: fdisk.c,v 1.51 2002/03/26 23:56:45 christos Exp $");
     33 #endif /* not lint */
     34 
     35 #include <sys/types.h>
     36 #include <sys/disklabel.h>
     37 #include <sys/disklabel_mbr.h>
     38 #include <sys/ioctl.h>
     39 #include <sys/param.h>
     40 #include <sys/stat.h>
     41 #include <sys/sysctl.h>
     42 
     43 #include <ctype.h>
     44 #include <err.h>
     45 #include <errno.h>
     46 #include <fcntl.h>
     47 #include <paths.h>
     48 #include <stdio.h>
     49 #include <stdlib.h>
     50 #include <string.h>
     51 #include <unistd.h>
     52 #include <util.h>
     53 
     54 #ifdef __i386__
     55 #include <machine/cpu.h>
     56 #endif
     57 
     58 #define LBUF 100
     59 static char lbuf[LBUF];
     60 
     61 /*
     62  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
     63  *	Copyright (c) 1989	Robert. V. Baron
     64  *	Created.
     65  */
     66 
     67 #ifndef _PATH_DEFDISK
     68 #define	_PATH_DEFDISK	"/dev/rwd0d"
     69 #endif
     70 
     71 const char *disk = _PATH_DEFDISK;
     72 
     73 struct disklabel disklabel;		/* disk parameters */
     74 
     75 int cylinders, sectors, heads, cylindersectors, disksectors;
     76 
     77 struct mboot {
     78 	u_int8_t	padding[2]; /* force the longs to be long alligned */
     79 	u_int8_t	bootinst[MBR_PARTOFF];
     80 	struct mbr_partition parts[NMBRPART];
     81 	u_int16_t	signature;
     82 };
     83 struct mboot mboot;
     84 
     85 #ifdef	__i386__
     86 
     87 #define PARTNAMESIZE	8	/* From mbr_bootsel.S */
     88 
     89 struct mbr_bootsel {
     90 	u_int8_t defkey;
     91 	u_int8_t flags;
     92 	u_int16_t timeo;
     93 	char nametab[4][PARTNAMESIZE + 1];
     94 	u_int16_t magic;
     95 } __attribute__((packed));
     96 
     97 #define BFL_SELACTIVE   0x01
     98 #define BFL_EXTINT13	0x02
     99 
    100 #define SCAN_ENTER      0x1c
    101 #define SCAN_F1         0x3b
    102 
    103 #define MBR_BOOTSELOFF	(MBR_PARTOFF - sizeof (struct mbr_bootsel))
    104 
    105 #define	DEFAULT_BOOTCODE	"/usr/mdec/mbr"
    106 #define DEFAULT_BOOTSELCODE	"/usr/mdec/mbr_bootsel"
    107 #define OPTIONS			"0123BSafilus:b:c:"
    108 #else
    109 #define OPTIONS			"0123Safilus:b:c:"
    110 #endif
    111 
    112 #define ACTIVE 0x80
    113 
    114 int dos_cylinders;
    115 int dos_heads;
    116 int dos_sectors;
    117 int dos_cylindersectors;
    118 
    119 #define DOSSECT(s,c)	(((s) & 0x3f) | (((c) >> 2) & 0xc0))
    120 #define DOSCYL(c)	((c) & 0xff)
    121 
    122 #define	MAXCYL	1024
    123 int partition = -1;
    124 
    125 int a_flag;		/* set active partition */
    126 int i_flag;		/* init bootcode */
    127 int u_flag;		/* update partition data */
    128 int sh_flag;		/* Output data as shell defines */
    129 int f_flag;		/* force --not interactive */
    130 int s_flag;		/* set id,offset,size */
    131 int b_flag;		/* Set cyl, heads, secs (as c/h/s) */
    132 int B_flag;		/* Edit/install bootselect code */
    133 int b_cyl, b_head, b_sec;  /* b_flag values. */
    134 int bootsel_modified;
    135 
    136 unsigned char bootcode[8192];	/* maximum size of bootcode */
    137 unsigned char tempcode[8192];
    138 int bootsize;		/* actual size of bootcode */
    139 
    140 
    141 static char reserved[] = "reserved";
    142 
    143 struct part_type {
    144 	int		 type;
    145 	const char	*name;
    146 } part_types[] = {
    147 	{0x00, "unused"},
    148 	{0x01, "Primary DOS with 12 bit FAT"},
    149 	{0x02, "XENIX / filesystem"},
    150 	{0x03, "XENIX /usr filesystem"},
    151 	{0x04, "Primary DOS with 16 bit FAT <32M"},
    152 	{0x05, "Extended partition"},
    153 	{0x06, "Primary 'big' DOS, 16-bit FAT (> 32MB)"},
    154 	{0x07, "OS/2 HPFS or NTFS or QNX2 or Advanced UNIX"},
    155 	{0x08, "AIX filesystem or OS/2 (thru v1.3) or DELL multiple drives"
    156 	       "or Commodore DOS or SplitDrive"},
    157 	{0x09, "AIX boot partition or Coherent"},
    158 	{0x0A, "OS/2 Boot Manager or Coherent swap or OPUS"},
    159 	{0x0b, "Primary DOS with 32 bit FAT"},
    160 	{0x0c, "Primary DOS with 32 bit FAT - LBA"},
    161 	{0x0d, "Type 7??? - LBA"},
    162 	{0x0E, "DOS (16-bit FAT) - LBA"},
    163 	{0x0F, "Ext. partition - LBA"},
    164 	{0x10, "OPUS"},
    165 	{0x11, "OS/2 BM: hidden DOS 12-bit FAT"},
    166 	{0x12, "Compaq diagnostics"},
    167 	{0x14, "OS/2 BM: hidden DOS 16-bit FAT <32M or Novell DOS 7.0 bug"},
    168 	{0x16, "OS/2 BM: hidden DOS 16-bit FAT >=32M"},
    169 	{0x17, "OS/2 BM: hidden IFS"},
    170 	{0x18, "AST Windows swapfile"},
    171 	{0x19, "Willowtech Photon coS"},
    172 	{0x1e, "hidden FAT95"},
    173 	{0x20, "Willowsoft OFS1"},
    174 	{0x21, reserved},
    175 	{0x23, reserved},
    176 	{0x24, "NEC DOS"},
    177 	{0x26, reserved},
    178 	{0x31, reserved},
    179 	{0x33, reserved},
    180 	{0x34, reserved},
    181 	{0x36, reserved},
    182 	{0x38, "Theos"},
    183 	{0x3C, "PartitionMagic recovery"},
    184 	{0x40, "VENIX 286 or LynxOS"},
    185 	{0x41, "Linux/MINIX (sharing disk with DRDOS) or Personal RISC boot"},
    186 	{0x42, "SFS or Linux swap (sharing disk with DRDOS)"},
    187 	{0x43, "Linux native (sharing disk with DRDOS)"},
    188 	{0x4D, "QNX4.x"},
    189 	{0x4E, "QNX4.x 2nd part"},
    190 	{0x4F, "QNX4.x 3rd part"},
    191 	{0x50, "DM (disk manager)"},
    192 	{0x51, "DM6 Aux1 (or Novell)"},
    193 	{0x52, "CP/M or Microport SysV/AT"},
    194 	{0x53, "DM6 Aux3"},
    195 	{0x54, "DM6 DDO"},
    196 	{0x55, "EZ-Drive (disk manager)"},
    197 	{0x56, "Golden Bow (disk manager)"},
    198 	{0x5C, "Priam Edisk (disk manager)"},
    199 	{0x61, "SpeedStor"},
    200 	{0x63, "GNU HURD or Mach or Sys V/386 (such as ISC UNIX) or MtXinu"},
    201 	{0x64, "Novell Netware 2.xx or Speedstore"},
    202 	{0x65, "Novell Netware 3.xx"},
    203 	{0x66, "Novell 386 Netware"},
    204 	{0x67, "Novell"},
    205 	{0x68, "Novell"},
    206 	{0x69, "Novell"},
    207 	{0x70, "DiskSecure Multi-Boot"},
    208 	{0x71, reserved},
    209 	{0x73, reserved},
    210 	{0x74, reserved},
    211 	{0x75, "PC/IX"},
    212 	{0x76, reserved},
    213 	{0x80, "MINIX until 1.4a"},
    214 	{0x81, "MINIX since 1.4b, early Linux, Mitac dmgr"},
    215 	{0x82, "Linux swap or Prime or Solaris"},
    216 	{0x83, "Linux native"},
    217 	{0x84, "OS/2 hidden C: drive"},
    218 	{0x85, "Linux extended"},
    219 	{0x86, "NT FAT volume set"},
    220 	{0x87, "NTFS volume set or HPFS mirrored"},
    221 	{0x93, "Amoeba filesystem"},
    222 	{0x94, "Amoeba bad block table"},
    223 	{0x99, "Mylex EISA SCSI"},
    224 	{0x9f, "BSDI?"},
    225 	{0xA0, "IBM Thinkpad hibernation"},
    226 	{0xa1, reserved},
    227 	{0xa3, reserved},
    228 	{0xa4, reserved},
    229 	{0xA5, "FreeBSD or 386BSD or old NetBSD"},
    230 	{0xA6, "OpenBSD"},
    231 	{0xA7, "NeXTSTEP 486"},
    232 	{0xa8, "Apple UFS"},
    233 	{0xa9, "NetBSD"},
    234 	{0xab, "Apple Boot"},
    235 	{0xb1, reserved},
    236 	{0xb3, reserved},
    237 	{0xb4, reserved},
    238 	{0xb6, reserved},
    239 	{0xB7, "BSDI BSD/386 filesystem"},
    240 	{0xB8, "BSDI BSD/386 swap"},
    241 	{0xc0, "CTOS"},
    242 	{0xC1, "DRDOS/sec (FAT-12)"},
    243 	{0xC4, "DRDOS/sec (FAT-16, < 32M)"},
    244 	{0xC6, "DRDOS/sec (FAT-16, >= 32M)"},
    245 	{0xC7, "Syrinx (Cyrnix?) or HPFS disabled"},
    246 	{0xd8, "CP/M 86"},
    247 	{0xDB, "CP/M or Concurrent CP/M or Concurrent DOS or CTOS"},
    248 	{0xE1, "DOS access or SpeedStor 12-bit FAT extended partition"},
    249 	{0xE3, "DOS R/O or SpeedStor or Storage Dimensions"},
    250 	{0xE4, "SpeedStor 16-bit FAT extended partition < 1024 cyl."},
    251 	{0xe5, reserved},
    252 	{0xe6, reserved},
    253 	{0xeb, "BeOS"},
    254 	{0xF1, "SpeedStor or Storage Dimensions"},
    255 	{0xF2, "DOS 3.3+ Secondary"},
    256 	{0xf3, reserved},
    257 	{0xF4, "SpeedStor large partition or Storage Dimensions"},
    258 	{0xf6, reserved},
    259 	{0xFE, "SpeedStor >1024 cyl. or LANstep or IBM PS/2 IML"},
    260 	{0xFF, "Xenix Bad Block Table"},
    261 };
    262 
    263 #define KNOWN_SYSIDS	(sizeof(part_types)/sizeof(part_types[0]))
    264 
    265 void	usage(void);
    266 void	print_s0(int);
    267 void	print_part(int);
    268 void	print_mbr_partition(struct mbr_partition *, off_t, off_t, int);
    269 int	read_boot(const char *, void *, size_t);
    270 void	init_sector0(int, int);
    271 void	intuit_translated_geometry(void);
    272 void	get_geometry(void);
    273 void	get_diskname(const char *, char *, size_t);
    274 int	try_heads(quad_t, quad_t, quad_t, quad_t, quad_t, quad_t, quad_t,
    275     quad_t);
    276 int	try_sectors(quad_t, quad_t, quad_t, quad_t, quad_t);
    277 void	change_part(int, int, int, int);
    278 void	print_params(void);
    279 void	change_active(int);
    280 void	get_params_to_use(void);
    281 void	dos(int, unsigned char *, unsigned char *, unsigned char *);
    282 int	open_disk(int);
    283 int	read_disk(off_t, void *);
    284 int	write_disk(off_t, void *);
    285 int	get_params(void);
    286 int	read_s0(off_t, struct mboot *);
    287 int	write_s0(void);
    288 int	yesno(const char *);
    289 void	decimal(const char *, int *);
    290 int	type_match(const void *, const void *);
    291 const char *get_type(int);
    292 int	get_mapping(int, int *, int *, int *, unsigned long *);
    293 #ifdef __i386__
    294 void	configure_bootsel(void);
    295 #endif
    296 
    297 static unsigned short getshort(void *);
    298 static void putshort(void *p, unsigned short);
    299 static unsigned long getlong(void *);
    300 static void putlong(void *, unsigned long);
    301 
    302 
    303 int	main(int, char *[]);
    304 
    305 int
    306 main(int argc, char *argv[])
    307 {
    308 	int ch, part, mib[2], len;
    309 	char *root_device;
    310 
    311 	int csysid, cstart, csize;	/* For the b_flag. */
    312 
    313 	mib[0] = CTL_KERN;
    314 	mib[1] = KERN_ROOT_DEVICE;
    315 	if (sysctl(mib, 2, NULL, &len, NULL, 0) != -1 &&
    316 	    (root_device = malloc(len)) != NULL &&
    317 	    sysctl(mib, 2, root_device, &len, NULL, 0) != -1)
    318 		disk = root_device;
    319 
    320 	a_flag = i_flag = u_flag = sh_flag = f_flag = s_flag = b_flag = 0;
    321 	csysid = cstart = csize = 0;
    322 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
    323 		switch (ch) {
    324 		case '0':
    325 			partition = 0;
    326 			break;
    327 		case '1':
    328 			partition = 1;
    329 			break;
    330 		case '2':
    331 			partition = 2;
    332 			break;
    333 		case '3':
    334 			partition = 3;
    335 			break;
    336 #ifdef __i386__
    337 		case 'B':
    338 			B_flag = 1;
    339 			break;
    340 #endif
    341 		case 'S':
    342 			sh_flag = 1;
    343 			break;
    344 		case 'a':
    345 			a_flag = 1;
    346 			break;
    347 		case 'f':
    348 			f_flag = 1;
    349 			break;
    350 		case 'i':
    351 			i_flag = 1;
    352 			break;
    353 		case 'l':
    354 			for (len = 0; len < KNOWN_SYSIDS; len++)
    355 				printf("%03d %s\n", len, part_types[len].name);
    356 			return 0;
    357 		case 'u':
    358 			u_flag = 1;
    359 			break;
    360 		case 's':
    361 			s_flag = 1;
    362 			if (sscanf(optarg, "%d/%d/%d", &csysid, &cstart,
    363 			    &csize) != 3)
    364 				err(1, "Bad argument to the -s flag.\n");
    365 			break;
    366 		case 'b':
    367 			b_flag = 1;
    368 			if (sscanf(optarg, "%d/%d/%d", &b_cyl, &b_head,
    369 			    &b_sec) != 3)
    370 				err(1, "Bad argument to the -s flag.\n");
    371 			if (b_cyl > MAXCYL)
    372 				b_cyl = MAXCYL;
    373 			break;
    374 		case 'c':
    375 			bootsize = read_boot(optarg, bootcode, sizeof bootcode);
    376 			break;
    377 		default:
    378 			usage();
    379 		}
    380 	argc -= optind;
    381 	argv += optind;
    382 
    383 	if (sh_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
    384 		usage();
    385 
    386 	if (B_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
    387 		usage();
    388 
    389 	if (partition == -1 && s_flag) {
    390 		warnx("-s flag requires a partition selected.");
    391 		usage();
    392 	}
    393 
    394 	if (argc > 0)
    395 		disk = argv[0];
    396 
    397 	if (open_disk(B_flag || a_flag || i_flag || u_flag) < 0)
    398 		exit(1);
    399 
    400 	if (read_s0(0, &mboot))
    401 		init_sector0(sectors > 63 ? 63 : sectors, 1);
    402 
    403 #ifdef __i386__
    404 	get_geometry();
    405 #else
    406 	intuit_translated_geometry();
    407 #endif
    408 
    409 
    410 	if ((i_flag || u_flag) && (!f_flag || b_flag))
    411 		get_params_to_use();
    412 
    413 	if (i_flag)
    414 		init_sector0(dos_sectors > 63 ? 63 : dos_sectors, 0);
    415 
    416 	/* Do the update stuff! */
    417 	if (u_flag) {
    418 		if (!f_flag)
    419 			printf("Partition table:\n");
    420 		if (partition == -1)
    421 			for (part = 0; part < NMBRPART; part++)
    422 				change_part(part,-1, -1, -1);
    423 		else
    424 			change_part(partition, csysid, cstart, csize);
    425 	} else
    426 		if (!i_flag)
    427 			print_s0(partition);
    428 
    429 	if (a_flag)
    430 		change_active(partition);
    431 
    432 #ifdef __i386__
    433 	if (B_flag) {
    434 		configure_bootsel();
    435 		if (B_flag && bootsel_modified)
    436 			write_s0();
    437 	}
    438 #endif
    439 
    440 	if (u_flag || a_flag || i_flag) {
    441 		if (!f_flag) {
    442 			printf("\nWe haven't written the MBR back to disk "
    443 			       "yet.  This is your last chance.\n");
    444 			print_s0(-1);
    445 			if (yesno("Should we write new partition table?"))
    446 				write_s0();
    447 		} else
    448 			write_s0();
    449 	}
    450 
    451 	exit(0);
    452 }
    453 
    454 void
    455 usage(void)
    456 {
    457 
    458 	(void)fprintf(stderr, "Usage: %s [-aiufBS] [-0|-1|-2|-3] "
    459 	      "[-b cylinders/heads/sectors]\n"
    460 	      "\t%s [-s id/start/size] [-c bootcode] [device]\n",
    461 	      getprogname(), getprogname());
    462 	exit(1);
    463 }
    464 
    465 void
    466 print_s0(int which)
    467 {
    468 	int part;
    469 
    470 	print_params();
    471 	if (!sh_flag)
    472 		printf("Partition table:\n");
    473 	if (which == -1) {
    474 		for (part = 0; part < NMBRPART; part++) {
    475 			if (!sh_flag)
    476 				printf("%d: ", part);
    477 			print_part(part);
    478 		}
    479 	} else
    480 		print_part(which);
    481 }
    482 
    483 static unsigned short
    484 getshort(void *p)
    485 {
    486 	unsigned char *cp = p;
    487 
    488 	return cp[0] | (cp[1] << 8);
    489 }
    490 
    491 static void
    492 putshort(void *p, unsigned short l)
    493 {
    494 	unsigned char *cp = p;
    495 
    496 	*cp++ = l;
    497 	*cp++ = l >> 8;
    498 }
    499 
    500 static unsigned long
    501 getlong(void *p)
    502 {
    503 	unsigned char *cp = p;
    504 
    505 	return cp[0] | (cp[1] << 8) | (cp[2] << 16) | (cp[3] << 24);
    506 }
    507 
    508 static void
    509 putlong(void *p, unsigned long l)
    510 {
    511 	unsigned char *cp = p;
    512 
    513 	*cp++ = l;
    514 	*cp++ = l >> 8;
    515 	*cp++ = l >> 16;
    516 	*cp++ = l >> 24;
    517 }
    518 
    519 void
    520 print_part(int part)
    521 {
    522 	struct mbr_partition *partp;
    523 	int empty;
    524 
    525 	partp = &mboot.parts[part];
    526 	empty = (partp->mbrp_typ == 0);
    527 
    528 	if (sh_flag) {
    529 		if (empty) {
    530 			printf("PART%dSIZE=0\n", part);
    531 			return;
    532 		}
    533 
    534 		printf("PART%dID=%d\n", part, partp->mbrp_typ);
    535 		printf("PART%dSIZE=%ld\n", part, getlong(&partp->mbrp_size));
    536 		printf("PART%dSTART=%ld\n", part, getlong(&partp->mbrp_start));
    537 		printf("PART%dFLAG=0x%x\n", part, partp->mbrp_flag);
    538 		printf("PART%dBCYL=%d\n", part, MBR_PCYL(partp->mbrp_scyl,
    539 		    partp->mbrp_ssect));
    540 		printf("PART%dBHEAD=%d\n", part, partp->mbrp_shd);
    541 		printf("PART%dBSEC=%d\n", part, MBR_PSECT(partp->mbrp_ssect));
    542 		printf("PART%dECYL=%d\n", part, MBR_PCYL(partp->mbrp_ecyl,
    543 		    partp->mbrp_esect));
    544 		printf("PART%dEHEAD=%d\n", part, partp->mbrp_ehd);
    545 		printf("PART%dESEC=%d\n", part, MBR_PSECT(partp->mbrp_esect));
    546 		return;
    547 	}
    548 	print_mbr_partition(partp, 0, 0, 0);
    549 }
    550 
    551 void
    552 print_mbr_partition(struct mbr_partition *partp,
    553     off_t offset, off_t exoffset, int indent)
    554 {
    555 	int	empty;
    556 	off_t	start;
    557 
    558 	empty = (partp->mbrp_typ == 0);
    559 	if (MBR_IS_EXTENDED(partp->mbrp_typ))
    560 		start = (off_t)getlong(&partp->mbrp_start) + exoffset;
    561 	else
    562 		start = (off_t)getlong(&partp->mbrp_start) + offset;
    563 	if (empty) {
    564 		printf("<UNUSED>\n");
    565 		return;
    566 	}
    567 	printf("sysid %d (%s)\n",
    568 	    partp->mbrp_typ, get_type(partp->mbrp_typ));
    569 	printf("%*s    start %lld, size %ld (%ld MB), flag 0x%x\n",
    570 	    indent, "",
    571 	    start, getlong(&partp->mbrp_size),
    572 	    getlong(&partp->mbrp_size) * 512 / (1024 * 1024), partp->mbrp_flag);
    573 	printf("%*s        beg: cylinder %4d, head %3d, sector %2d\n",
    574 	    indent, "",
    575 	    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
    576 	    partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
    577 	printf("%*s        end: cylinder %4d, head %3d, sector %2d\n",
    578 	    indent, "",
    579 	    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
    580 	    partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
    581 
    582 	if (MBR_IS_EXTENDED(partp->mbrp_typ)) {
    583 		struct mboot	eboot;
    584 		int		part;
    585 
    586 		printf("%*s    Extended partition table:\n", indent, "");
    587 		if (read_s0(start, &eboot) == -1)
    588 			return;
    589 		indent += 8;
    590 		if (exoffset == 0)
    591 			exoffset = start;
    592 		for (part = 0; part < NMBRPART; part++) {
    593 			printf("%*s%d: ", indent, "", part);
    594 			print_mbr_partition(&eboot.parts[part],
    595 			    start, exoffset, indent);
    596 		}
    597 	}
    598 }
    599 
    600 int
    601 read_boot(const char *name, void *buf, size_t len)
    602 {
    603 	int bfd, ret;
    604 	struct stat st;
    605 
    606 	if ((bfd = open(name, O_RDONLY)) < 0)
    607 		err(1, "%s", name);
    608 	if (fstat(bfd, &st) == -1)
    609 		err(1, "%s", name);
    610 	if (st.st_size > len)
    611 		errx(1, "%s: bootcode too large", name);
    612 	ret = st.st_size;
    613 	if (ret < 0x200)
    614 		errx(1, "%s: bootcode too small", name);
    615 	if (read(bfd, buf, len) != ret)
    616 		err(1, "%s", name);
    617 	close(bfd);
    618 
    619 	/*
    620 	 * Do some sanity checking here
    621 	 */
    622 	if (getshort(bootcode + MBR_MAGICOFF) != MBR_MAGIC)
    623 		errx(1, "%s: invalid magic", name);
    624 	ret = (ret + 0x1ff) / 0x200;
    625 	ret *= 0x200;
    626 	return ret;
    627 }
    628 
    629 void
    630 init_sector0(int start, int dopart)
    631 {
    632 	int i;
    633 
    634 #ifdef	DEFAULT_BOOTCODE
    635 	if (!bootsize)
    636 		bootsize = read_boot(DEFAULT_BOOTCODE, bootcode,
    637 		    sizeof bootcode);
    638 #endif
    639 
    640 	memcpy(mboot.bootinst, bootcode, sizeof(mboot.bootinst));
    641 	putshort(&mboot.signature, MBR_MAGIC);
    642 
    643 	if (dopart)
    644 		for (i = 0; i < 4; i++)
    645 			memset(&mboot.parts[i], 0, sizeof(mboot.parts[i]));
    646 
    647 }
    648 
    649 #ifdef __i386__
    650 
    651 void
    652 get_diskname(const char *fullname, char *diskname, size_t size)
    653 {
    654 	const char *p, *p2;
    655 	size_t len;
    656 
    657 	p = strrchr(fullname, '/');
    658 	if (p == NULL)
    659 		p = fullname;
    660 	else
    661 		p++;
    662 
    663 	if (*p == 0) {
    664 		strncpy(diskname, fullname, size - 1);
    665 		diskname[size - 1] = '\0';
    666 		return;
    667 	}
    668 
    669 	if (*p == 'r')
    670 		p++;
    671 
    672 	for (p2 = p; *p2 != 0; p2++)
    673 		if (isdigit(*p2))
    674 			break;
    675 	if (*p2 == 0) {
    676 		/* XXX invalid diskname? */
    677 		strncpy(diskname, fullname, size - 1);
    678 		diskname[size - 1] = '\0';
    679 		return;
    680 	}
    681 	while (isdigit(*p2))
    682 		p2++;
    683 
    684 	len = p2 - p;
    685 	if (len > size) {
    686 		/* XXX */
    687 		strncpy(diskname, fullname, size - 1);
    688 		diskname[size - 1] = '\0';
    689 		return;
    690 	}
    691 
    692 	strncpy(diskname, p, len);
    693 	diskname[len] = 0;
    694 }
    695 
    696 void
    697 get_geometry(void)
    698 {
    699 	int mib[2], i;
    700 	size_t len;
    701 	struct disklist *dl;
    702 	struct biosdisk_info *bip;
    703 	struct nativedisk_info *nip;
    704 	char diskname[8];
    705 
    706 	mib[0] = CTL_MACHDEP;
    707 	mib[1] = CPU_DISKINFO;
    708 	if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
    709 		intuit_translated_geometry();
    710 		return;
    711 	}
    712 	dl = (struct disklist *) malloc(len);
    713 	sysctl(mib, 2, dl, &len, NULL, 0);
    714 
    715 	get_diskname(disk, diskname, sizeof diskname);
    716 
    717 	for (i = 0; i < dl->dl_nnativedisks; i++) {
    718 		nip = &dl->dl_nativedisks[i];
    719 		if (strcmp(diskname, nip->ni_devname))
    720 			continue;
    721 		/*
    722 		 * XXX listing possible matches is better. This is ok
    723 		 * for now because the user has a chance to change
    724 		 * it later.
    725 		 */
    726 		if (nip->ni_nmatches != 0) {
    727 			bip = &dl->dl_biosdisks[nip->ni_biosmatches[0]];
    728 			dos_cylinders = bip->bi_cyl;
    729 			dos_heads = bip->bi_head;
    730 			dos_sectors = bip->bi_sec;
    731 			dos_cylindersectors = bip->bi_head * bip->bi_sec;
    732 			return;
    733 		}
    734 	}
    735 	/* Allright, allright, make a stupid guess.. */
    736 	intuit_translated_geometry();
    737 }
    738 
    739 void
    740 configure_bootsel(void)
    741 {
    742 	struct mbr_bootsel *mbs =
    743 	    (struct mbr_bootsel *)&mboot.bootinst[MBR_BOOTSELOFF];
    744 	int i, nused, firstpart = -1, item;
    745 	char desc[PARTNAMESIZE + 2], *p;
    746 	int timo, entry_changed = 0;
    747 
    748 	for (i = nused = 0; i < NMBRPART; ++i) {
    749 		if (mboot.parts[i].mbrp_typ != 0) {
    750 			if (firstpart == -1)
    751 				firstpart = i;
    752 			nused++;
    753 		}
    754 	}
    755 
    756 	if (nused == 0) {
    757 		warnx("No used partitions found. Partition the disk first.");
    758 		return;
    759 	}
    760 
    761 	if (mbs->magic != MBR_MAGIC) {
    762 		if (!yesno("Bootselector not yet installed. Install it now?")) {
    763 			warnx("Bootselector not installed.");
    764 			return;
    765 		}
    766 		bootsize = read_boot(DEFAULT_BOOTSELCODE, bootcode,
    767 		    sizeof bootcode);
    768 		memcpy(mboot.bootinst, bootcode, sizeof(mboot.bootinst));
    769 		bootsel_modified = 1;
    770 		mbs->flags |= BFL_SELACTIVE;
    771 	} else {
    772 		if (mbs->flags & BFL_SELACTIVE) {
    773 			printf("The bootselector is installed and active.");
    774 			if (!yesno("Do you want to change its settings?")) {
    775 				if (yesno("Do you want to deactivate it?")) {
    776 					mbs->flags &= ~BFL_SELACTIVE;
    777 					bootsel_modified = 1;
    778 					goto done;
    779 				}
    780 				return;
    781 			}
    782 		} else {
    783 			printf("The bootselector is installed but not active.");
    784 			if (yesno("Do you want to activate it?")) {
    785 				mbs->flags |= BFL_SELACTIVE;
    786 				bootsel_modified = 1;
    787 			}
    788 			if (!yesno("Do you want to change its settings?"))
    789 				goto done;
    790 		}
    791 	}
    792 
    793 	printf("\n\nPartition table:\n");
    794 	for (i = 0; i < NMBRPART; i++) {
    795 		printf("%d: ", i);
    796 		print_part(i);
    797 	}
    798 
    799 	printf("\n\nCurrent boot selection menu option names:\n");
    800 	for (i = 0; i < NMBRPART; i++) {
    801 		if (mbs->nametab[i][0] != 0)
    802 			printf("%d: %s\n", i, &mbs->nametab[i][0]);
    803 		else
    804 			printf("%d: <UNUSED>\n", i);
    805 	}
    806 	printf("\n");
    807 
    808 	item = firstpart;
    809 
    810 editentries:
    811 	while (1) {
    812 		decimal("Change which entry (-1 quits)?", &item);
    813 		if (item == -1)
    814 			break;
    815 		if (item < 0 || item >= NMBRPART) {
    816 			printf("Invalid entry number\n");
    817 			item = -1;
    818 			continue;
    819 		}
    820 		if (mboot.parts[item].mbrp_typ == 0) {
    821 			printf("The partition entry is unused\n");
    822 			item = -1;
    823 			continue;
    824 		}
    825 
    826 		printf("Enter descriptions (max. 8 characters): ");
    827 		rewind(stdin);
    828 		fgets(desc, PARTNAMESIZE + 1, stdin);
    829 		fpurge(stdin);
    830 		p = strchr(desc, '\n');
    831 		if (p != NULL)
    832 			*p = 0;
    833 		strcpy(&mbs->nametab[item][0], desc);
    834 		entry_changed = bootsel_modified = 1;
    835 
    836 		item++;
    837 	}
    838 
    839 	if (entry_changed)
    840 		printf("Boot selection menu option names are now:\n");
    841 
    842 	firstpart = -1;
    843 	for (i = 0; i < NMBRPART; i++) {
    844 		if (mbs->nametab[i][0] != 0) {
    845 			firstpart = i;
    846 			if (entry_changed)
    847 				printf("%d: %s\n", i, &mbs->nametab[i][0]);
    848 		} else {
    849 			if (entry_changed)
    850 				printf("%d: <UNUSED>\n", i);
    851 		}
    852 	}
    853 	if (entry_changed)
    854 		printf("\n");
    855 
    856 	if (firstpart == -1) {
    857 		printf("All menu entries are now inactive.\n");
    858 		if (!yesno("Are you sure about this?"))
    859 			goto editentries;
    860 	} else {
    861 		if (!(mbs->flags & BFL_SELACTIVE)) {
    862 			printf("The bootselector is not yet active.\n");
    863 			if (yesno("Activate it now?"))
    864 				mbs->flags |= BFL_SELACTIVE;
    865 		}
    866 	}
    867 
    868 	/* bootsel is dirty from here on out. */
    869 	bootsel_modified = 1;
    870 
    871 	/* The timeout value is in ticks, 18.2 Hz. Avoid using floats. */
    872 	timo = ((1000 * mbs->timeo) / 18200);
    873 	do {
    874 		decimal("Timeout value", &timo);
    875 	} while (timo < 0 || timo > 3600);
    876 	mbs->timeo = (u_int16_t)((timo * 18200) / 1000);
    877 
    878 	printf("Select the default boot option. Options are:\n\n");
    879 	for (i = 0; i < NMBRPART; i++) {
    880 		if (mbs->nametab[i][0] != 0)
    881 			printf("%d: %s\n", i, &mbs->nametab[i][0]);
    882 	}
    883 	for (i = 4; i < 10; i++)
    884 		printf("%d: Harddisk %d\n", i, i - 4);
    885 	printf("10: The first active partition\n");
    886 
    887 	if (mbs->defkey == SCAN_ENTER)
    888 		item = 10;
    889 	else
    890 		item = mbs->defkey - SCAN_F1;
    891 
    892 	if (item < 0 || item > 10 || mbs->nametab[item][0] == 0)
    893 		item = 10;
    894 
    895 	do {
    896 		decimal("Default boot option", &item);
    897 	} while (item < 0 || item > 10 ||
    898 		    (item <= 3 && mbs->nametab[item][0] == 0));
    899 
    900 	if (item == 10)
    901 		mbs->defkey = SCAN_ENTER;
    902 	else
    903 		mbs->defkey = SCAN_F1 + item;
    904 
    905 done:
    906 	for (i = 0; i < NMBRPART; i++) {
    907 		if (mboot.parts[i].mbrp_typ != 0 &&
    908 		   mboot.parts[i].mbrp_start >=
    909 		     (dos_cylinders * dos_heads * dos_sectors)) {
    910 			mbs->flags |= BFL_EXTINT13;
    911 			break;
    912 		}
    913 	}
    914 
    915 	if (bootsel_modified != 0 && !yesno("Update the bootselector?"))
    916 		bootsel_modified = 0;
    917 }
    918 #endif
    919 
    920 
    921 /* Prerequisite: the disklabel parameters and master boot record must
    922  *		 have been read (i.e. dos_* and mboot are meaningful).
    923  * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
    924  *		  dos_cylindersectors to be consistent with what the
    925  *		  partition table is using, if we can find a geometry
    926  *		  which is consistent with all partition table entries.
    927  *		  We may get the number of cylinders slightly wrong (in
    928  *		  the conservative direction).  The idea is to be able
    929  *		  to create a NetBSD partition on a disk we don't know
    930  *		  the translated geometry of.
    931  * This whole routine should be replaced with a kernel interface to get
    932  * the BIOS geometry (which in turn requires modifications to the i386
    933  * boot loader to pass in the BIOS geometry for each disk). */
    934 void
    935 intuit_translated_geometry(void)
    936 {
    937 
    938 	int xcylinders = -1, xheads = -1, xsectors = -1, i, j;
    939 	int c1, h1, s1, c2, h2, s2;
    940 	long a1, a2;
    941 	quad_t num, denom;
    942 
    943 	/* Try to deduce the number of heads from two different mappings. */
    944 	for (i = 0; i < NMBRPART * 2; i++) {
    945 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    946 			continue;
    947 		for (j = 0; j < 8; j++) {
    948 			if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
    949 				continue;
    950 			num = (quad_t)h1*(a2-s2) - (quad_t)h2*(a1-s1);
    951 			denom = (quad_t)c2*(a1-s1) - (quad_t)c1*(a2-s2);
    952 			if (denom != 0 && num % denom == 0) {
    953 				xheads = num / denom;
    954 				break;
    955 			}
    956 		}
    957 		if (xheads != -1)
    958 			break;
    959 	}
    960 
    961 	if (xheads == -1)
    962 		return;
    963 
    964 	/* Now figure out the number of sectors from a single mapping. */
    965 	for (i = 0; i < NMBRPART * 2; i++) {
    966 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    967 			continue;
    968 		num = a1 - s1;
    969 		denom = c1 * xheads + h1;
    970 		if (denom != 0 && num % denom == 0) {
    971 			xsectors = num / denom;
    972 			break;
    973 		}
    974 	}
    975 
    976 	if (xsectors == -1)
    977 		return;
    978 
    979 	/* Estimate the number of cylinders. */
    980 	xcylinders = disklabel.d_secperunit / xheads / xsectors;
    981 
    982 	/* Now verify consistency with each of the partition table entries.
    983 	 * Be willing to shove cylinders up a little bit to make things work,
    984 	 * but translation mismatches are fatal. */
    985 	for (i = 0; i < NMBRPART * 2; i++) {
    986 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    987 			continue;
    988 		if (xsectors * (c1 * xheads + h1) + s1 != a1)
    989 			return;
    990 		if (c1 >= xcylinders)
    991 			xcylinders = c1 + 1;
    992 	}
    993 
    994 	/* Everything checks out.  Reset the geometry to use for further
    995 	 * calculations. */
    996 	dos_cylinders = xcylinders;
    997 	dos_heads = xheads;
    998 	dos_sectors = xsectors;
    999 	dos_cylindersectors = xheads * xsectors;
   1000 }
   1001 
   1002 /* For the purposes of intuit_translated_geometry(), treat the partition
   1003  * table as a list of eight mapping between (cylinder, head, sector)
   1004  * triplets and absolute sectors.  Get the relevant geometry triplet and
   1005  * absolute sectors for a given entry, or return -1 if it isn't present.
   1006  * Note: for simplicity, the returned sector is 0-based. */
   1007 int
   1008 get_mapping(int i, int *cylinder, int *head, int *sector,
   1009     unsigned long *absolute)
   1010 {
   1011 	struct mbr_partition *part = &mboot.parts[i / 2];
   1012 
   1013 	if (part->mbrp_typ == 0)
   1014 		return -1;
   1015 	if (i % 2 == 0) {
   1016 		*cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
   1017 		*head = part->mbrp_shd;
   1018 		*sector = MBR_PSECT(part->mbrp_ssect) - 1;
   1019 		*absolute = getlong(&part->mbrp_start);
   1020 	} else {
   1021 		*cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
   1022 		*head = part->mbrp_ehd;
   1023 		*sector = MBR_PSECT(part->mbrp_esect) - 1;
   1024 		*absolute = getlong(&part->mbrp_start)
   1025 		    + getlong(&part->mbrp_size) - 1;
   1026 	}
   1027 	return 0;
   1028 }
   1029 
   1030 void
   1031 change_part(int part, int csysid, int cstart, int csize)
   1032 {
   1033 	struct mbr_partition *partp;
   1034 
   1035 	partp = &mboot.parts[part];
   1036 
   1037 	if (s_flag) {
   1038 		if (csysid == 0 && cstart == 0 && csize == 0)
   1039 			memset(partp, 0, sizeof *partp);
   1040 		else {
   1041 			partp->mbrp_typ = csysid;
   1042 #if 0
   1043 			checkcyl(cstart / dos_cylindersectors);
   1044 #endif
   1045 			putlong(&partp->mbrp_start, cstart);
   1046 			putlong(&partp->mbrp_size, csize);
   1047 			dos(getlong(&partp->mbrp_start),
   1048 			    &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
   1049 			dos(getlong(&partp->mbrp_start)
   1050 			    + getlong(&partp->mbrp_size) - 1,
   1051 			    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
   1052 		}
   1053 		if (f_flag)
   1054 			return;
   1055 	}
   1056 
   1057 	printf("The data for partition %d is:\n", part);
   1058 	print_part(part);
   1059 	if (!u_flag || !yesno("Do you want to change it?"))
   1060 		return;
   1061 
   1062 	do {
   1063 		{
   1064 			int sysid, start, size;
   1065 
   1066 			sysid = partp->mbrp_typ,
   1067 			start = getlong(&partp->mbrp_start),
   1068 			size = getlong(&partp->mbrp_size);
   1069 			decimal("sysid", &sysid);
   1070 			decimal("start", &start);
   1071 			decimal("size", &size);
   1072 			partp->mbrp_typ = sysid;
   1073 			putlong(&partp->mbrp_start, start);
   1074 			putlong(&partp->mbrp_size, size);
   1075 		}
   1076 
   1077 		if (yesno("Explicitly specify beg/end address?")) {
   1078 			int tsector, tcylinder, thead;
   1079 
   1080 			tcylinder = MBR_PCYL(partp->mbrp_scyl,
   1081 			    partp->mbrp_ssect);
   1082 			thead = partp->mbrp_shd;
   1083 			tsector = MBR_PSECT(partp->mbrp_ssect);
   1084 			decimal("beginning cylinder", &tcylinder);
   1085 #if 0
   1086 			checkcyl(tcylinder);
   1087 #endif
   1088 			decimal("beginning head", &thead);
   1089 			decimal("beginning sector", &tsector);
   1090 			partp->mbrp_scyl = DOSCYL(tcylinder);
   1091 			partp->mbrp_shd = thead;
   1092 			partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
   1093 
   1094 			tcylinder = MBR_PCYL(partp->mbrp_ecyl,
   1095 			    partp->mbrp_esect);
   1096 			thead = partp->mbrp_ehd;
   1097 			tsector = MBR_PSECT(partp->mbrp_esect);
   1098 			decimal("ending cylinder", &tcylinder);
   1099 			decimal("ending head", &thead);
   1100 			decimal("ending sector", &tsector);
   1101 			partp->mbrp_ecyl = DOSCYL(tcylinder);
   1102 			partp->mbrp_ehd = thead;
   1103 			partp->mbrp_esect = DOSSECT(tsector, tcylinder);
   1104 		} else {
   1105 
   1106 			if (partp->mbrp_typ == 0
   1107 			    && getlong(&partp->mbrp_start) == 0
   1108 			    && getlong(&partp->mbrp_size) == 0)
   1109 				memset(partp, 0, sizeof *partp);
   1110 			else {
   1111 #if 0
   1112 				checkcyl(getlong(&partp->mbrp_start)
   1113 					 / dos_cylindersectors);
   1114 #endif
   1115 				dos(getlong(&partp->mbrp_start),
   1116 				    &partp->mbrp_scyl,
   1117 				    &partp->mbrp_shd, &partp->mbrp_ssect);
   1118 				dos(getlong(&partp->mbrp_start)
   1119 				    + getlong(&partp->mbrp_size) - 1,
   1120 				    &partp->mbrp_ecyl, &partp->mbrp_ehd,
   1121 				    &partp->mbrp_esect);
   1122 			}
   1123 		}
   1124 
   1125 		print_part(part);
   1126 	} while (!yesno("Is this entry okay?"));
   1127 }
   1128 
   1129 void
   1130 print_params(void)
   1131 {
   1132 
   1133 	if (sh_flag) {
   1134 		printf ("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%d\n",
   1135 			cylinders, heads, sectors, disksectors);
   1136 		printf ("BCYL=%d\nBHEAD=%d\nBSEC=%d\n",
   1137 			dos_cylinders, dos_heads, dos_sectors);
   1138 		return;
   1139 	}
   1140 
   1141 	/* Not sh_flag */
   1142 	printf("Disk: %s\n", disk);
   1143 	printf("NetBSD disklabel disk geometry:\n");
   1144 	printf("cylinders: %d heads: %d sectors/track: %d (%d sectors/cylinder)\n\n",
   1145 	    cylinders, heads, sectors, cylindersectors);
   1146 	printf("BIOS disk geometry:\n");
   1147 	printf("cylinders: %d heads: %d sectors/track: %d (%d sectors/cylinder)\n\n",
   1148 	    dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors);
   1149 }
   1150 
   1151 void
   1152 change_active(int which)
   1153 {
   1154 	struct mbr_partition *partp;
   1155 	int part;
   1156 	int active = 4;
   1157 
   1158 	partp = &mboot.parts[0];
   1159 
   1160 	if (a_flag && which != -1)
   1161 		active = which;
   1162 	else {
   1163 		for (part = 0; part < NMBRPART; part++)
   1164 			if (partp[part].mbrp_flag & ACTIVE)
   1165 				active = part;
   1166 	}
   1167 	if (!f_flag) {
   1168 		if (yesno("Do you want to change the active partition?")) {
   1169 			printf ("Choosing 4 will make no partition active.\n");
   1170 			do {
   1171 				decimal("active partition", &active);
   1172 			} while (!yesno("Are you happy with this choice?"));
   1173 		} else
   1174 			return;
   1175 	} else
   1176 		if (active != 4)
   1177 			printf ("Making partition %d active.\n", active);
   1178 
   1179 	for (part = 0; part < NMBRPART; part++)
   1180 		partp[part].mbrp_flag &= ~ACTIVE;
   1181 	if (active < 4)
   1182 		partp[active].mbrp_flag |= ACTIVE;
   1183 }
   1184 
   1185 void
   1186 get_params_to_use(void)
   1187 {
   1188 
   1189 	if (b_flag) {
   1190 		dos_cylinders = b_cyl;
   1191 		dos_heads = b_head;
   1192 		dos_sectors = b_sec;
   1193 		dos_cylindersectors = dos_heads * dos_sectors;
   1194 		return;
   1195 	}
   1196 
   1197 	print_params();
   1198 	if (yesno("Do you want to change our idea of what BIOS thinks?")) {
   1199 		do {
   1200 			decimal("BIOS's idea of #cylinders", &dos_cylinders);
   1201 			decimal("BIOS's idea of #heads", &dos_heads);
   1202 			decimal("BIOS's idea of #sectors", &dos_sectors);
   1203 			dos_cylindersectors = dos_heads * dos_sectors;
   1204 			print_params();
   1205 		} while (!yesno("Are you happy with this choice?"));
   1206 	}
   1207 }
   1208 
   1209 /***********************************************\
   1210 * Change real numbers into strange dos numbers	*
   1211 \***********************************************/
   1212 void
   1213 dos(int sector, unsigned char *cylinderp, unsigned char *headp,
   1214     unsigned char *sectorp)
   1215 {
   1216 	int cylinder, head;
   1217 	int biosmaxsec;
   1218 
   1219 	biosmaxsec = dos_cylinders * dos_heads * dos_sectors - 1;
   1220 	if (sector > biosmaxsec)
   1221 		sector = biosmaxsec;
   1222 
   1223 	cylinder = sector / dos_cylindersectors;
   1224 
   1225 	sector -= cylinder * dos_cylindersectors;
   1226 
   1227 	head = sector / dos_sectors;
   1228 	sector -= head * dos_sectors;
   1229 
   1230 	*cylinderp = DOSCYL(cylinder);
   1231 	*headp = head;
   1232 	*sectorp = DOSSECT(sector + 1, cylinder);
   1233 }
   1234 
   1235 #if 0
   1236 void
   1237 checkcyl(int cyl)
   1238 {
   1239 
   1240 	if (cyl >= MAXCYL)
   1241 		warnx("partition start beyond BIOS limit");
   1242 }
   1243 #endif
   1244 
   1245 int fd = -1;
   1246 
   1247 int
   1248 open_disk(int update)
   1249 {
   1250 	static char namebuf[MAXPATHLEN + 1];
   1251 
   1252 	fd = opendisk(disk, update ? O_RDWR : O_RDONLY, namebuf,
   1253 	    sizeof(namebuf), 0);
   1254 	if (fd < 0) {
   1255 		if (errno == ENODEV)
   1256 			warnx("%s is not a character device", namebuf);
   1257 		else
   1258 			warn("%s", namebuf);
   1259 		return (-1);
   1260 	}
   1261 	disk = namebuf;
   1262 	if (get_params() == -1) {
   1263 		close(fd);
   1264 		return (-1);
   1265 	}
   1266 	return (0);
   1267 }
   1268 
   1269 int
   1270 read_disk(off_t sector, void *buf)
   1271 {
   1272 
   1273 	if (fd == -1)
   1274 		errx(1, "read_disk(); fd == -1");
   1275 	if (lseek(fd, sector * 512, 0) == -1)
   1276 		return (-1);
   1277 	return (read(fd, buf, 512));
   1278 }
   1279 
   1280 int
   1281 write_disk(off_t sector, void *buf)
   1282 {
   1283 
   1284 	if (fd == -1)
   1285 		errx(1, "write_disk(); fd == -1");
   1286 	if (lseek(fd, sector * 512, 0) == -1)
   1287 		return (-1);
   1288 	return (write(fd, buf, 512));
   1289 }
   1290 
   1291 int
   1292 get_params(void)
   1293 {
   1294 
   1295 	if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
   1296 		warn("DIOCGDEFLABEL");
   1297 		if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
   1298 			warn("DIOCGDINFO");
   1299 			return (-1);
   1300 		}
   1301 	}
   1302 
   1303 	dos_cylinders = cylinders = disklabel.d_ncylinders;
   1304 	dos_heads = heads = disklabel.d_ntracks;
   1305 	dos_sectors = sectors = disklabel.d_nsectors;
   1306 	dos_cylindersectors = cylindersectors = heads * sectors;
   1307 	disksectors = disklabel.d_secperunit;
   1308 
   1309 	return (0);
   1310 }
   1311 
   1312 int
   1313 read_s0(off_t offset, struct mboot *boot)
   1314 {
   1315 
   1316 	if (read_disk(offset, boot->bootinst) == -1) {
   1317 		warn("can't read %s partition table",
   1318 		    offset ? "extended" : "fdisk");
   1319 		return (-1);
   1320 	}
   1321 	if (getshort(&boot->signature) != MBR_MAGIC) {
   1322 		warnx("invalid %s partition table found",
   1323 		    offset ? "extended" : "fdisk");
   1324 		return (-1);
   1325 	}
   1326 	return (0);
   1327 }
   1328 
   1329 int
   1330 write_s0(void)
   1331 {
   1332 	int flag, i;
   1333 
   1334 	/*
   1335 	 * write enable label sector before write (if necessary),
   1336 	 * disable after writing.
   1337 	 * needed if the disklabel protected area also protects
   1338 	 * sector 0. (e.g. empty disk)
   1339 	 */
   1340 	flag = 1;
   1341 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
   1342 		warn("DIOCWLABEL");
   1343 	if (write_disk(0, mboot.bootinst) == -1) {
   1344 		warn("can't write fdisk partition table");
   1345 		return -1;
   1346 	}
   1347 	for (i = bootsize; (i -= 0x200) > 0;)
   1348 		if (write_disk(i / 0x200, bootcode + i) == -1) {
   1349 			warn("can't write bootcode");
   1350 			return -1;
   1351 		}
   1352 	flag = 0;
   1353 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
   1354 		warn("DIOCWLABEL");
   1355 	return 0;
   1356 }
   1357 
   1358 int
   1359 yesno(const char *str)
   1360 {
   1361 	int ch, first;
   1362 
   1363 	printf("%s [n] ", str);
   1364 
   1365 	first = ch = getchar();
   1366 	while (ch != '\n' && ch != EOF)
   1367 		ch = getchar();
   1368 	return (first == 'y' || first == 'Y');
   1369 }
   1370 
   1371 void
   1372 decimal(const char *str, int *num)
   1373 {
   1374 	int acc = 0;
   1375 	char *cp;
   1376 
   1377 	for (;; printf("%s is not a valid decimal number.\n", lbuf)) {
   1378 		printf("%s: [%d] ", str, *num);
   1379 
   1380 		fgets(lbuf, LBUF, stdin);
   1381 		lbuf[strlen(lbuf)-1] = '\0';
   1382 		cp = lbuf;
   1383 
   1384 		cp += strspn(cp, " \t");
   1385 		if (*cp == '\0')
   1386 			return;
   1387 
   1388 		if (!isdigit(*cp) && *cp != '-')
   1389 			continue;
   1390 		acc = strtol(lbuf, &cp, 10);
   1391 
   1392 		cp += strspn(cp, " \t");
   1393 		if (*cp != '\0')
   1394 			continue;
   1395 
   1396 		*num = acc;
   1397 		return;
   1398 	}
   1399 
   1400 }
   1401 
   1402 int
   1403 type_match(const void *key, const void *item)
   1404 {
   1405 	const int *typep = key;
   1406 	const struct part_type *ptr = item;
   1407 
   1408 	if (*typep < ptr->type)
   1409 		return (-1);
   1410 	if (*typep > ptr->type)
   1411 		return (1);
   1412 	return (0);
   1413 }
   1414 
   1415 const char *
   1416 get_type(int type)
   1417 {
   1418 	struct part_type *ptr;
   1419 
   1420 	ptr = bsearch(&type, part_types,
   1421 	    sizeof(part_types) / sizeof(struct part_type),
   1422 	    sizeof(struct part_type), type_match);
   1423 	if (ptr == 0)
   1424 		return ("unknown");
   1425 	return (ptr->name);
   1426 }
   1427