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