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