Home | History | Annotate | Line # | Download | only in fdisk
fdisk.c revision 1.32
      1 /*	$NetBSD: fdisk.c,v 1.32 1999/01/27 21:41:31 thorpej 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.32 1999/01/27 21:41:31 thorpej 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 #define LBUF 100
     54 static char lbuf[LBUF];
     55 
     56 /*
     57  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
     58  *	Copyright (c) 1989	Robert. V. Baron
     59  *	Created.
     60  */
     61 
     62 char *disk = "/dev/rwd0d";
     63 
     64 struct disklabel disklabel;		/* disk parameters */
     65 
     66 int cylinders, sectors, heads, cylindersectors, disksectors;
     67 
     68 struct mboot {
     69 	u_int8_t	padding[2]; /* force the longs to be long alligned */
     70 	u_int8_t	bootinst[MBR_PARTOFF];
     71 	struct mbr_partition parts[NMBRPART];
     72 	u_int16_t	signature;
     73 };
     74 struct mboot mboot;
     75 
     76 #ifdef	__i386__
     77 #define	DEFAULT_BOOTCODE	"/usr/mdec/mbr"
     78 #endif
     79 
     80 #define ACTIVE 0x80
     81 
     82 int dos_cylinders;
     83 int dos_heads;
     84 int dos_sectors;
     85 int dos_cylindersectors;
     86 
     87 #define DOSSECT(s,c)	(((s) & 0x3f) | (((c) >> 2) & 0xc0))
     88 #define DOSCYL(c)	((c) & 0xff)
     89 
     90 #define	MAXCYL	1024
     91 int partition = -1;
     92 
     93 int a_flag;		/* set active partition */
     94 int i_flag;		/* init bootcode */
     95 int u_flag;		/* update partition data */
     96 int sh_flag;		/* Output data as shell defines */
     97 int f_flag;		/* force --not interactive */
     98 int s_flag;		/* set id,offset,size */
     99 int b_flag;		/* Set cyl, heads, secs (as c/h/s) */
    100 int b_cyl, b_head, b_sec;  /* b_flag values. */
    101 
    102 unsigned char bootcode[8192];	/* maximum size of bootcode */
    103 int bootsize;		/* actual size of bootcode */
    104 
    105 
    106 static char reserved[] = "reserved";
    108 
    109 struct part_type {
    110 	int type;
    111 	char *name;
    112 } part_types[] = {
    113 	{0x00, "unused"},
    114 	{0x01, "Primary DOS with 12 bit FAT"},
    115 	{0x02, "XENIX / filesystem"},
    116 	{0x03, "XENIX /usr filesystem"},
    117 	{0x04, "Primary DOS with 16 bit FAT <32M"},
    118 	{0x05, "Extended partition"},
    119 	{0x06, "Primary 'big' DOS, 16-bit FAT (> 32MB)"},
    120 	{0x07, "OS/2 HPFS or NTFS or QNX2 or Advanced UNIX"},
    121 	{0x08, "AIX filesystem or OS/2 (thru v1.3) or DELL multiple drives"
    122 	       "or Commodore DOS or SplitDrive"},
    123 	{0x09, "AIX boot partition or Coherent"},
    124 	{0x0A, "OS/2 Boot Manager or Coherent swap or OPUS"},
    125 	{0x0b, "Primary DOS with 32 bit FAT"},
    126 	{0x0c, "Primary DOS with 32 bit FAT - LBA"},
    127 	{0x0d, "Type 7??? - LBA"},
    128 	{0x0E, "DOS (16-bit FAT) - LBA"},
    129 	{0x0F, "Ext. partition - LBA"},
    130 	{0x10, "OPUS"},
    131 	{0x11, "OS/2 BM: hidden DOS 12-bit FAT"},
    132 	{0x12, "Compaq diagnostics"},
    133 	{0x14, "OS/2 BM: hidden DOS 16-bit FAT <32M or Novell DOS 7.0 bug"},
    134 	{0x16, "OS/2 BM: hidden DOS 16-bit FAT >=32M"},
    135 	{0x17, "OS/2 BM: hidden IFS"},
    136 	{0x18, "AST Windows swapfile"},
    137 	{0x19, "Willowtech Photon coS"},
    138 	{0x1e, "hidden FAT95"},
    139 	{0x20, "Willowsoft OFS1"},
    140 	{0x21, reserved},
    141 	{0x23, reserved},
    142 	{0x24, "NEC DOS"},
    143 	{0x26, reserved},
    144 	{0x31, reserved},
    145 	{0x33, reserved},
    146 	{0x34, reserved},
    147 	{0x36, reserved},
    148 	{0x38, "Theos"},
    149 	{0x3C, "PartitionMagic recovery"},
    150 	{0x40, "VENIX 286 or LynxOS"},
    151 	{0x41, "Linux/MINIX (sharing disk with DRDOS) or Personal RISC boot"},
    152 	{0x42, "SFS or Linux swap (sharing disk with DRDOS)"},
    153 	{0x43, "Linux native (sharing disk with DRDOS)"},
    154 	{0x50, "DM (disk manager)"},
    155 	{0x51, "DM6 Aux1 (or Novell)"},
    156 	{0x52, "CP/M or Microport SysV/AT"},
    157 	{0x53, "DM6 Aux3"},
    158 	{0x54, "DM6 DDO"},
    159 	{0x55, "EZ-Drive (disk manager)"},
    160 	{0x56, "Golden Bow (disk manager)"},
    161 	{0x5C, "Priam Edisk (disk manager)"},
    162 	{0x61, "SpeedStor"},
    163 	{0x63, "GNU HURD or Mach or Sys V/386 (such as ISC UNIX) or MtXinu"},
    164 	{0x64, "Novell Netware 2.xx or Speedstore"},
    165 	{0x65, "Novell Netware 3.xx"},
    166 	{0x66, "Novell 386 Netware"},
    167 	{0x67, "Novell"},
    168 	{0x68, "Novell"},
    169 	{0x69, "Novell"},
    170 	{0x70, "DiskSecure Multi-Boot"},
    171 	{0x71, reserved},
    172 	{0x73, reserved},
    173 	{0x74, reserved},
    174 	{0x75, "PC/IX"},
    175 	{0x76, reserved},
    176 	{0x77, "QNX4.x"},
    177 	{0x78, "QNX4.x 2nd part"},
    178 	{0x79, "QNX4.x 3rd part"},
    179 	{0x80, "MINIX until 1.4a"},
    180 	{0x81, "MINIX since 1.4b, early Linux, Mitac dmgr"},
    181 	{0x82, "Linux swap or Prime or Solaris"},
    182 	{0x83, "Linux native"},
    183 	{0x84, "OS/2 hidden C: drive"},
    184 	{0x85, "Linux extended"},
    185 	{0x86, "NT FAT volume set"},
    186 	{0x87, "NTFS volume set or HPFS mirrored"},
    187 	{0x93, "Amoeba filesystem"},
    188 	{0x94, "Amoeba bad block table"},
    189 	{0x99, "Mylex EISA SCSI"},
    190 	{0x9f, "BSDI?"},
    191 	{0xA0, "IBM Thinkpad hibernation"},
    192 	{0xa1, reserved},
    193 	{0xa3, reserved},
    194 	{0xa4, reserved},
    195 	{0xA5, "FreeBSD or 386BSD or old NetBSD"},
    196 	{0xA6, "OpenBSD"},
    197 	{0xA7, "NeXTSTEP 486"},
    198 	{0xa9, "NetBSD"},
    199 	{0xb1, reserved},
    200 	{0xb3, reserved},
    201 	{0xb4, reserved},
    202 	{0xb6, reserved},
    203 	{0xB7, "BSDI BSD/386 filesystem"},
    204 	{0xB8, "BSDI BSD/386 swap"},
    205 	{0xc0, "CTOS"},
    206 	{0xC1, "DRDOS/sec (FAT-12)"},
    207 	{0xC4, "DRDOS/sec (FAT-16, < 32M)"},
    208 	{0xC6, "DRDOS/sec (FAT-16, >= 32M)"},
    209 	{0xC7, "Syrinx (Cyrnix?) or HPFS disabled"},
    210 	{0xd8, "CP/M 86"},
    211 	{0xDB, "CP/M or Concurrent CP/M or Concurrent DOS or CTOS"},
    212 	{0xE1, "DOS access or SpeedStor 12-bit FAT extended partition"},
    213 	{0xE3, "DOS R/O or SpeedStor or Storage Dimensions"},
    214 	{0xE4, "SpeedStor 16-bit FAT extended partition < 1024 cyl."},
    215 	{0xe5, reserved},
    216 	{0xe6, reserved},
    217 	{0xF1, "SpeedStor or Storage Dimensions"},
    218 	{0xF2, "DOS 3.3+ Secondary"},
    219 	{0xf3, reserved},
    220 	{0xF4, "SpeedStor large partition or Storage Dimensions"},
    221 	{0xf6, reserved},
    222 	{0xFE, "SpeedStor >1024 cyl. or LANstep or IBM PS/2 IML"},
    223 	{0xFF, "Xenix Bad Block Table"},
    224 };
    225 
    226 void	usage __P((void));
    227 void	print_s0 __P((int));
    228 void	print_part __P((int));
    229 void	read_boot __P((char *));
    230 void	init_sector0 __P((int, int));
    231 void	intuit_translated_geometry __P((void));
    232 int	try_heads __P((quad_t, quad_t, quad_t, quad_t, quad_t, quad_t, quad_t,
    233 		       quad_t));
    234 int	try_sectors __P((quad_t, quad_t, quad_t, quad_t, quad_t));
    235 void	change_part __P((int, int, int, int));
    236 void	print_params __P((void));
    237 void	change_active __P((int));
    238 void	get_params_to_use __P((void));
    239 void	dos __P((int, unsigned char *, unsigned char *, unsigned char *));
    240 int	open_disk __P((int));
    241 int	read_disk __P((int, void *));
    242 int	write_disk __P((int, void *));
    243 int	get_params __P((void));
    244 int	read_s0 __P((void));
    245 int	write_s0 __P((void));
    246 int	yesno __P((char *));
    247 void	decimal __P((char *, int *));
    248 int	type_match __P((const void *, const void *));
    249 char	*get_type __P((int));
    250 int	get_mapping __P((int, int *, int *, int *, long *));
    251 
    252 static inline unsigned short getshort __P((void *));
    253 static inline void putshort __P((void *p, unsigned short));
    254 static inline unsigned long getlong __P((void *));
    255 static inline void putlong __P((void *,	unsigned long));
    256 
    257 
    258 int	main __P((int, char **));
    259 
    260 int
    261 main(argc, argv)
    262 	int argc;
    263 	char *argv[];
    264 {
    265 	int ch;
    266 	int part;
    267 
    268 	int csysid, cstart, csize;	/* For the b_flag. */
    269 
    270 	a_flag = i_flag = u_flag = sh_flag = f_flag = s_flag = b_flag = 0;
    271 	csysid = cstart = csize = 0;
    272 	while ((ch = getopt(argc, argv, "0123Safius:b:c:")) != -1)
    273 		switch (ch) {
    274 		case '0':
    275 			partition = 0;
    276 			break;
    277 		case '1':
    278 			partition = 1;
    279 			break;
    280 		case '2':
    281 			partition = 2;
    282 			break;
    283 		case '3':
    284 			partition = 3;
    285 			break;
    286 		case 'S':
    287 			sh_flag = 1;
    288 			break;
    289 		case 'a':
    290 			a_flag = 1;
    291 			break;
    292 		case 'f':
    293 			f_flag = 1;
    294 			break;
    295 		case 'i':
    296 			i_flag = 1;
    297 			break;
    298 		case 'u':
    299 			u_flag = 1;
    300 			break;
    301 		case 's':
    302 			s_flag = 1;
    303 			if (sscanf (optarg, "%d/%d/%d",
    304 				    &csysid, &cstart, &csize) != 3) {
    305 				(void)fprintf (stderr, "%s: Bad argument "
    306 					       "to the -s flag.\n",
    307 					       argv[0]);
    308 				exit (1);
    309 			}
    310 			break;
    311 		case 'b':
    312 			b_flag = 1;
    313 			if (sscanf (optarg, "%d/%d/%d",
    314 				    &b_cyl, &b_head, &b_sec) != 3) {
    315 				(void)fprintf (stderr, "%s: Bad argument "
    316 					       "to the -b flag.\n",
    317 					       argv[0]);
    318 				exit (1);
    319 			}
    320 			if (b_cyl > MAXCYL)
    321 				b_cyl = MAXCYL;
    322 			break;
    323 		case 'c':
    324 			read_boot(optarg);
    325 			break;
    326 		default:
    327 			usage();
    328 		}
    329 	argc -= optind;
    330 	argv += optind;
    331 
    332 	if (sh_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
    333 		usage();
    334 
    335 	if (partition == -1 && s_flag) {
    336 		(void) fprintf (stderr,
    337 				"-s flag requires a partition selected.\n");
    338 		usage();
    339 	}
    340 
    341 	if (argc > 0)
    342 		disk = argv[0];
    343 
    344 	if (open_disk(a_flag || i_flag || u_flag) < 0)
    345 		exit(1);
    346 
    347 	if (read_s0())
    348 		init_sector0(sectors > 63 ? 63 : sectors, 1);
    349 
    350 	intuit_translated_geometry();
    351 
    352 	if (!sh_flag && !f_flag)
    353 		printf("******* Working on device %s *******\n", disk);
    354 
    355 
    356 	if ((i_flag || u_flag) && (!f_flag || b_flag))
    357 		get_params_to_use();
    358 
    359 	if (i_flag)
    360 		init_sector0(dos_sectors > 63 ? 63 : dos_sectors, 0);
    361 
    362 	if (!sh_flag && !f_flag)
    363 		printf("Warning: BIOS sector numbering starts with sector 1\n");
    364 
    365 	/* Do the update stuff! */
    366 	if (u_flag) {
    367 		if (!f_flag)
    368 			printf("Information from DOS bootblock is:\n");
    369 		if (partition == -1)
    370 			for (part = 0; part < NMBRPART; part++)
    371 				change_part(part,-1, -1, -1);
    372 		else
    373 			change_part(partition, csysid, cstart, csize);
    374 	} else
    375 		if (!i_flag)
    376 			print_s0(partition);
    377 
    378 	if (a_flag)
    379 		change_active(partition);
    380 
    381 	if (u_flag || a_flag || i_flag) {
    382 		if (!f_flag) {
    383 			printf("\nWe haven't changed the partition table "
    384 			       "yet.  This is your last chance.\n");
    385 			print_s0(-1);
    386 			if (yesno("Should we write new partition table?"))
    387 				write_s0();
    388 		} else
    389 			write_s0();
    390 	}
    391 
    392 	exit(0);
    393 }
    394 
    395 void
    396 usage()
    397 {
    398 	(void)fprintf(stderr, "usage: fdisk [-aiufSc] [-0|-1|-2|-3] "
    399 		      "[device]\n");
    400 	exit(1);
    401 }
    402 
    403 void
    404 print_s0(which)
    405 	int which;
    406 {
    407 	int part;
    408 
    409 	print_params();
    410 	if (!sh_flag)
    411 		printf("Information from DOS bootblock is:\n");
    412 	if (which == -1) {
    413 		for (part = 0; part < NMBRPART; part++) {
    414 			if (!sh_flag)
    415 				printf("%d: ", part);
    416 			print_part(part);
    417 		}
    418 	} else
    419 		print_part(which);
    420 }
    421 
    422 static struct mbr_partition mtpart = { 0 };
    423 
    424 static inline unsigned short
    425 getshort(p)
    426 	void *p;
    427 {
    428 	unsigned char *cp = p;
    429 
    430 	return cp[0] | (cp[1] << 8);
    431 }
    432 
    433 static inline void
    434 putshort(p, l)
    435 	void *p;
    436 	unsigned short l;
    437 {
    438 	unsigned char *cp = p;
    439 
    440 	*cp++ = l;
    441 	*cp++ = l >> 8;
    442 }
    443 
    444 static inline unsigned long
    445 getlong(p)
    446 	void *p;
    447 {
    448 	unsigned char *cp = p;
    449 
    450 	return cp[0] | (cp[1] << 8) | (cp[2] << 16) | (cp[3] << 24);
    451 }
    452 
    453 static inline void
    454 putlong(p, l)
    455 	void *p;
    456 	unsigned long l;
    457 {
    458 	unsigned char *cp = p;
    459 
    460 	*cp++ = l;
    461 	*cp++ = l >> 8;
    462 	*cp++ = l >> 16;
    463 	*cp++ = l >> 24;
    464 }
    465 
    466 void
    467 print_part(part)
    468 	int part;
    469 {
    470 	struct mbr_partition *partp;
    471 	int empty;
    472 
    473 	partp = &mboot.parts[part];
    474 	empty = !memcmp(partp, &mtpart, sizeof(struct mbr_partition));
    475 
    476 	if (sh_flag) {
    477 		if (empty) {
    478 			printf("PART%dSIZE=0\n", part);
    479 			return;
    480 		}
    481 
    482 		printf("PART%dID=%d\n", part, partp->mbrp_typ);
    483 		printf("PART%dSIZE=%ld\n", part, getlong(&partp->mbrp_size));
    484 		printf("PART%dSTART=%ld\n", part, getlong(&partp->mbrp_start));
    485 		printf("PART%dFLAG=0x%x\n", part, partp->mbrp_flag);
    486 		printf("PART%dBCYL=%d\n", part, MBR_PCYL(partp->mbrp_scyl,
    487 						      partp->mbrp_ssect));
    488 		printf("PART%dBHEAD=%d\n", part, partp->mbrp_shd);
    489 		printf("PART%dBSEC=%d\n", part, MBR_PSECT(partp->mbrp_ssect));
    490 		printf("PART%dECYL=%d\n", part, MBR_PCYL(partp->mbrp_ecyl,
    491 						      partp->mbrp_esect));
    492 		printf("PART%dEHEAD=%d\n", part, partp->mbrp_ehd);
    493 		printf("PART%dESEC=%d\n", part, MBR_PSECT(partp->mbrp_esect));
    494 		return;
    495 	}
    496 
    497 	/* Not sh_flag. */
    498 	if (empty) {
    499 		printf("<UNUSED>\n");
    500 		return;
    501 	}
    502 	printf("sysid %d (%s)\n", partp->mbrp_typ, get_type(partp->mbrp_typ));
    503 	printf("    start %ld, size %ld (%ld MB), flag 0x%x\n",
    504 	    getlong(&partp->mbrp_start), getlong(&partp->mbrp_size),
    505 	    getlong(&partp->mbrp_size) * 512 / (1024 * 1024), partp->mbrp_flag);
    506 	printf("\tbeg: cylinder %4d, head %3d, sector %2d\n",
    507 	    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
    508 	    partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
    509 	printf("\tend: cylinder %4d, head %3d, sector %2d\n",
    510 	    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
    511 	    partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
    512 }
    513 
    514 void
    515 read_boot(name)
    516 	char *name;
    517 {
    518 	int fd;
    519 	struct stat st;
    520 
    521 	if ((fd = open(name, O_RDONLY)) < 0)
    522 		err(1, "%s", name);
    523 	if (fstat(fd, &st) == -1)
    524 		err(1, "%s", name);
    525 	if (st.st_size > sizeof(bootcode))
    526 		errx(1, "%s: bootcode too large", name);
    527 	bootsize = st.st_size;
    528 	if (bootsize < 0x200)
    529 		errx(1, "%s: bootcode too small", name);
    530 	if (read(fd, bootcode, bootsize) != bootsize)
    531 		err(1, "%s", name);
    532 	close(fd);
    533 
    534 	/*
    535 	 * Do some sanity checking here
    536 	 */
    537 	if (getshort(bootcode + MBR_MAGICOFF) != MBR_MAGIC)
    538 		errx(1, "%s: invalid magic", name);
    539 	bootsize = (bootsize + 0x1ff) / 0x200;
    540 	bootsize *= 0x200;
    541 }
    542 
    543 void
    544 init_sector0(start, dopart)
    545 	int start, dopart;
    546 {
    547 	int i;
    548 
    549 #ifdef	DEFAULT_BOOTCODE
    550 	if (!bootsize)
    551 		read_boot(DEFAULT_BOOTCODE);
    552 #endif
    553 
    554 	memcpy(mboot.bootinst, bootcode, sizeof(mboot.bootinst));
    555 	putshort(&mboot.signature, MBR_MAGIC);
    556 
    557 	if (dopart)
    558 		for (i=0; i<3; i++)
    559 			memset (&mboot.parts[i], 0, sizeof(struct mbr_partition));
    560 
    561 }
    562 
    563 /* Prerequisite: the disklabel parameters and master boot record must
    564  *		 have been read (i.e. dos_* and mboot are meaningful).
    565  * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
    566  *		  dos_cylindersectors to be consistent with what the
    567  *		  partition table is using, if we can find a geometry
    568  *		  which is consistent with all partition table entries.
    569  *		  We may get the number of cylinders slightly wrong (in
    570  *		  the conservative direction).  The idea is to be able
    571  *		  to create a NetBSD partition on a disk we don't know
    572  *		  the translated geometry of.
    573  * This whole routine should be replaced with a kernel interface to get
    574  * the BIOS geometry (which in turn requires modifications to the i386
    575  * boot loader to pass in the BIOS geometry for each disk). */
    576 void
    577 intuit_translated_geometry()
    578 {
    579 
    580 	int cylinders = -1, heads = -1, sectors = -1, i, j;
    581 	int c1, h1, s1, c2, h2, s2;
    582 	long a1, a2;
    583 	quad_t num, denom;
    584 
    585 	/* Try to deduce the number of heads from two different mappings. */
    586 	for (i = 0; i < NMBRPART * 2; i++) {
    587 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    588 			continue;
    589 		for (j = 0; j < 8; j++) {
    590 			if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
    591 				continue;
    592 			num = (quad_t)h1*(a2-s2) - (quad_t)h2*(a1-s1);
    593 			denom = (quad_t)c2*(a1-s1) - (quad_t)c1*(a2-s2);
    594 			if (denom != 0 && num % denom == 0) {
    595 				heads = num / denom;
    596 				break;
    597 			}
    598 		}
    599 		if (heads != -1)
    600 			break;
    601 	}
    602 
    603 	if (heads == -1)
    604 		return;
    605 
    606 	/* Now figure out the number of sectors from a single mapping. */
    607 	for (i = 0; i < NMBRPART * 2; i++) {
    608 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    609 			continue;
    610 		num = a1 - s1;
    611 		denom = c1 * heads + h1;
    612 		if (denom != 0 && num % denom == 0) {
    613 			sectors = num / denom;
    614 			break;
    615 		}
    616 	}
    617 
    618 	if (sectors == -1)
    619 		return;
    620 
    621 	/* Estimate the number of cylinders. */
    622 	cylinders = disklabel.d_secperunit / heads / sectors;
    623 
    624 	/* Now verify consistency with each of the partition table entries.
    625 	 * Be willing to shove cylinders up a little bit to make things work,
    626 	 * but translation mismatches are fatal. */
    627 	for (i = 0; i < NMBRPART * 2; i++) {
    628 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
    629 			continue;
    630 		if (sectors * (c1 * heads + h1) + s1 != a1)
    631 			return;
    632 		if (c1 >= cylinders)
    633 			cylinders = c1 + 1;
    634 	}
    635 
    636 	/* Everything checks out.  Reset the geometry to use for further
    637 	 * calculations. */
    638 	dos_cylinders = cylinders;
    639 	dos_heads = heads;
    640 	dos_sectors = sectors;
    641 	dos_cylindersectors = heads * sectors;
    642 }
    643 
    644 /* For the purposes of intuit_translated_geometry(), treat the partition
    645  * table as a list of eight mapping between (cylinder, head, sector)
    646  * triplets and absolute sectors.  Get the relevant geometry triplet and
    647  * absolute sectors for a given entry, or return -1 if it isn't present.
    648  * Note: for simplicity, the returned sector is 0-based. */
    649 int
    650 get_mapping(i, cylinder, head, sector, absolute)
    651 	int i, *cylinder, *head, *sector;
    652 	long *absolute;
    653 {
    654 	struct mbr_partition *part = &mboot.parts[i / 2];
    655 
    656 	if (part->mbrp_typ == 0)
    657 		return -1;
    658 	if (i % 2 == 0) {
    659 		*cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
    660 		*head = part->mbrp_shd;
    661 		*sector = MBR_PSECT(part->mbrp_ssect) - 1;
    662 		*absolute = getlong(&part->mbrp_start);
    663 	} else {
    664 		*cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
    665 		*head = part->mbrp_ehd;
    666 		*sector = MBR_PSECT(part->mbrp_esect) - 1;
    667 		*absolute = getlong(&part->mbrp_start)
    668 		    + getlong(&part->mbrp_size) - 1;
    669 	}
    670 	return 0;
    671 }
    672 
    673 void
    674 change_part(part, csysid, cstart, csize)
    675 	int part, csysid, cstart, csize;
    676 {
    677 	struct mbr_partition *partp;
    678 
    679 	partp = &mboot.parts[part];
    680 
    681 	if (s_flag) {
    682 		if (csysid == 0 && cstart == 0 && csize == 0)
    683 			memset(partp, 0, sizeof *partp);
    684 		else {
    685 			partp->mbrp_typ = csysid;
    686 #if 0
    687 			checkcyl(cstart / dos_cylindersectors);
    688 #endif
    689 			putlong(&partp->mbrp_start, cstart);
    690 			putlong(&partp->mbrp_size, csize);
    691 			dos(getlong(&partp->mbrp_start),
    692 			    &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
    693 			dos(getlong(&partp->mbrp_start)
    694 			    + getlong(&partp->mbrp_size) - 1,
    695 			    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
    696 		}
    697 		if (f_flag)
    698 			return;
    699 	}
    700 
    701 	printf("The data for partition %d is:\n", part);
    702 	print_part(part);
    703 	if (!u_flag || !yesno("Do you want to change it?"))
    704 		return;
    705 
    706 	do {
    707 		{
    708 			int sysid, start, size;
    709 
    710 			sysid = partp->mbrp_typ,
    711 			start = getlong(&partp->mbrp_start),
    712 			size = getlong(&partp->mbrp_size);
    713 			decimal("sysid", &sysid);
    714 			decimal("start", &start);
    715 			decimal("size", &size);
    716 			partp->mbrp_typ = sysid;
    717 			putlong(&partp->mbrp_start, start);
    718 			putlong(&partp->mbrp_size, size);
    719 		}
    720 
    721 		if (yesno("Explicitly specify beg/end address?")) {
    722 			int tsector, tcylinder, thead;
    723 
    724 			tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
    725 			thead = partp->mbrp_shd;
    726 			tsector = MBR_PSECT(partp->mbrp_ssect);
    727 			decimal("beginning cylinder", &tcylinder);
    728 #if 0
    729 			checkcyl(tcylinder);
    730 #endif
    731 			decimal("beginning head", &thead);
    732 			decimal("beginning sector", &tsector);
    733 			partp->mbrp_scyl = DOSCYL(tcylinder);
    734 			partp->mbrp_shd = thead;
    735 			partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
    736 
    737 			tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
    738 			thead = partp->mbrp_ehd;
    739 			tsector = MBR_PSECT(partp->mbrp_esect);
    740 			decimal("ending cylinder", &tcylinder);
    741 			decimal("ending head", &thead);
    742 			decimal("ending sector", &tsector);
    743 			partp->mbrp_ecyl = DOSCYL(tcylinder);
    744 			partp->mbrp_ehd = thead;
    745 			partp->mbrp_esect = DOSSECT(tsector, tcylinder);
    746 		} else {
    747 
    748 			if (partp->mbrp_typ == 0
    749 			    && getlong(&partp->mbrp_start) == 0
    750 			    && getlong(&partp->mbrp_size) == 0)
    751 				memset(partp, 0, sizeof *partp);
    752 			else {
    753 #if 0
    754 				checkcyl(getlong(&partp->mbrp_start)
    755 					 / dos_cylindersectors);
    756 #endif
    757 				dos(getlong(&partp->mbrp_start), &partp->mbrp_scyl,
    758 				    &partp->mbrp_shd, &partp->mbrp_ssect);
    759 				dos(getlong(&partp->mbrp_start)
    760 				    + getlong(&partp->mbrp_size) - 1,
    761 				    &partp->mbrp_ecyl, &partp->mbrp_ehd,
    762 				    &partp->mbrp_esect);
    763 			}
    764 		}
    765 
    766 		print_part(part);
    767 	} while (!yesno("Is this entry okay?"));
    768 }
    769 
    770 void
    771 print_params()
    772 {
    773 
    774 	if (sh_flag) {
    775 		printf ("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%d\n",
    776 			cylinders, heads, sectors, disksectors);
    777 		printf ("BCYL=%d\nBHEAD=%d\nBSEC=%d\n",
    778 			dos_cylinders, dos_heads, dos_sectors);
    779 		return;
    780 	}
    781 
    782 	/* Not sh_flag */
    783 	printf("parameters extracted from in-core disklabel are:\n");
    784 	printf("cylinders=%d heads=%d sectors/track=%d (%d sectors/cylinder)\n\n",
    785 	    cylinders, heads, sectors, cylindersectors);
    786 	if (dos_sectors > 63 || dos_heads > 255)
    787 		printf("Figures below won't work with BIOS for partitions not in cylinder 1\n");
    788 	printf("parameters to be used for BIOS calculations are:\n");
    789 	printf("cylinders=%d heads=%d sectors/track=%d (%d sectors/cylinder)\n\n",
    790 	    dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors);
    791 }
    792 
    793 void
    794 change_active(which)
    795 	int which;
    796 {
    797 	struct mbr_partition *partp;
    798 	int part;
    799 	int active = 4;
    800 
    801 	partp = &mboot.parts[0];
    802 
    803 	if (a_flag && which != -1)
    804 		active = which;
    805 	else {
    806 		for (part = 0; part < NMBRPART; part++)
    807 			if (partp[part].mbrp_flag & ACTIVE)
    808 				active = part;
    809 	}
    810 	if (!f_flag) {
    811 		if (yesno("Do you want to change the active partition?")) {
    812 			printf ("Choosing 4 will make no partition active.\n");
    813 			do {
    814 				decimal("active partition", &active);
    815 			} while (!yesno("Are you happy with this choice?"));
    816 		} else
    817 			return;
    818 	} else
    819 		if (active != 4)
    820 			printf ("Making partition %d active.\n", active);
    821 
    822 	for (part = 0; part < NMBRPART; part++)
    823 		partp[part].mbrp_flag &= ~ACTIVE;
    824 	if (active < 4)
    825 		partp[active].mbrp_flag |= ACTIVE;
    826 }
    827 
    828 void
    829 get_params_to_use()
    830 {
    831 	if (b_flag) {
    832 		dos_cylinders = b_cyl;
    833 		dos_heads = b_head;
    834 		dos_sectors = b_sec;
    835 		dos_cylindersectors = dos_heads * dos_sectors;
    836 		return;
    837 	}
    838 
    839 	print_params();
    840 	if (yesno("Do you want to change our idea of what BIOS thinks?")) {
    841 		do {
    842 			decimal("BIOS's idea of #cylinders", &dos_cylinders);
    843 			decimal("BIOS's idea of #heads", &dos_heads);
    844 			decimal("BIOS's idea of #sectors", &dos_sectors);
    845 			dos_cylindersectors = dos_heads * dos_sectors;
    846 			print_params();
    847 		} while (!yesno("Are you happy with this choice?"));
    848 	}
    849 }
    850 
    851 /***********************************************\
    852 * Change real numbers into strange dos numbers	*
    853 \***********************************************/
    854 void
    855 dos(sector, cylinderp, headp, sectorp)
    856 	int sector;
    857 	unsigned char *cylinderp, *headp, *sectorp;
    858 {
    859 	int cylinder, head;
    860 
    861 	cylinder = sector / dos_cylindersectors;
    862 
    863 	sector -= cylinder * dos_cylindersectors;
    864 
    865 	head = sector / dos_sectors;
    866 	sector -= head * dos_sectors;
    867 
    868 	if (cylinder >= MAXCYL)
    869 		cylinder = MAXCYL - 1;
    870 	*cylinderp = DOSCYL(cylinder);
    871 	*headp = head;
    872 	*sectorp = DOSSECT(sector + 1, cylinder);
    873 }
    874 
    875 #if 0
    876 void
    877 checkcyl(cyl)
    878 	int cyl;
    879 {
    880 	if (cyl >= MAXCYL)
    881 		warnx("partition start beyond BIOS limit");
    882 }
    883 #endif
    884 
    885 int fd;
    886 
    887 int
    888 open_disk(u_flag)
    889 	int u_flag;
    890 {
    891 	static char namebuf[MAXPATHLEN + 1];
    892 	struct stat st;
    893 
    894 	fd = opendisk(disk, u_flag ? O_RDWR : O_RDONLY, namebuf,
    895 	    sizeof(namebuf), 0);
    896 	if (fd < 0) {
    897 		warn("%s", namebuf);
    898 		return (-1);
    899 	}
    900 	disk = namebuf;
    901 	if (fstat(fd, &st) == -1) {
    902 		close(fd);
    903 		warn("%s", disk);
    904 		return (-1);
    905 	}
    906 	if (!S_ISCHR(st.st_mode) && !S_ISREG(st.st_mode)) {
    907 		close(fd);
    908 		warnx("%s is not a character device or regular file", disk);
    909 		return (-1);
    910 	}
    911 	if (get_params() == -1) {
    912 		close(fd);
    913 		return (-1);
    914 	}
    915 	return (0);
    916 }
    917 
    918 int
    919 read_disk(sector, buf)
    920 	int sector;
    921 	void *buf;
    922 {
    923 
    924 	if (lseek(fd, (off_t)(sector * 512), 0) == -1)
    925 		return (-1);
    926 	return (read(fd, buf, 512));
    927 }
    928 
    929 int
    930 write_disk(sector, buf)
    931 	int sector;
    932 	void *buf;
    933 {
    934 
    935 	if (lseek(fd, (off_t)(sector * 512), 0) == -1)
    936 		return (-1);
    937 	return (write(fd, buf, 512));
    938 }
    939 
    940 int
    941 get_params()
    942 {
    943 
    944 	if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
    945 		warn("DIOCGDINFO");
    946 		return (-1);
    947 	}
    948 
    949 	dos_cylinders = cylinders = disklabel.d_ncylinders;
    950 	dos_heads = heads = disklabel.d_ntracks;
    951 	dos_sectors = sectors = disklabel.d_nsectors;
    952 	dos_cylindersectors = cylindersectors = heads * sectors;
    953 	disksectors = disklabel.d_secperunit;
    954 
    955 	return (0);
    956 }
    957 
    958 int
    959 read_s0()
    960 {
    961 
    962 	if (read_disk(0, mboot.bootinst) == -1) {
    963 		warn("can't read fdisk partition table");
    964 		return (-1);
    965 	}
    966 	if (getshort(&mboot.signature) != MBR_MAGIC) {
    967 		warnx("invalid fdisk partition table found");
    968 		return (-1);
    969 	}
    970 	return (0);
    971 }
    972 
    973 int
    974 write_s0()
    975 {
    976 	int flag, i;
    977 
    978 	/*
    979 	 * write enable label sector before write (if necessary),
    980 	 * disable after writing.
    981 	 * needed if the disklabel protected area also protects
    982 	 * sector 0. (e.g. empty disk)
    983 	 */
    984 	flag = 1;
    985 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
    986 		warn("DIOCWLABEL");
    987 	if (write_disk(0, mboot.bootinst) == -1) {
    988 		warn("can't write fdisk partition table");
    989 		return -1;
    990 	}
    991 	for (i = bootsize; (i -= 0x200) > 0;)
    992 		if (write_disk(i / 0x200, bootcode + i) == -1) {
    993 			warn("can't write bootcode");
    994 			return -1;
    995 		}
    996 	flag = 0;
    997 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
    998 		warn("DIOCWLABEL");
    999 	return 0;
   1000 }
   1001 
   1002 int
   1003 yesno(str)
   1004 	char *str;
   1005 {
   1006 	int ch, first;
   1007 
   1008 	printf("%s [n] ", str);
   1009 
   1010 	first = ch = getchar();
   1011 	while (ch != '\n' && ch != EOF)
   1012 		ch = getchar();
   1013 	return (first == 'y' || first == 'Y');
   1014 }
   1015 
   1016 void
   1017 decimal(str, num)
   1018 	char *str;
   1019 	int *num;
   1020 {
   1021 	int acc = 0;
   1022 	char *cp;
   1023 
   1024 	for (;; printf("%s is not a valid decimal number.\n", lbuf)) {
   1025 		printf("Supply a decimal value for \"%s\" [%d] ", str, *num);
   1026 
   1027 		fgets(lbuf, LBUF, stdin);
   1028 		lbuf[strlen(lbuf)-1] = '\0';
   1029 		cp = lbuf;
   1030 
   1031 		cp += strspn(cp, " \t");
   1032 		if (*cp == '\0')
   1033 			return;
   1034 
   1035 		if (!isdigit(*cp))
   1036 			continue;
   1037 		acc = strtol(lbuf, &cp, 10);
   1038 
   1039 		cp += strspn(cp, " \t");
   1040 		if (*cp != '\0')
   1041 			continue;
   1042 
   1043 		*num = acc;
   1044 		return;
   1045 	}
   1046 
   1047 }
   1048 
   1049 int
   1050 type_match(key, item)
   1051 	const void *key, *item;
   1052 {
   1053 	const int *typep = key;
   1054 	const struct part_type *ptr = item;
   1055 
   1056 	if (*typep < ptr->type)
   1057 		return (-1);
   1058 	if (*typep > ptr->type)
   1059 		return (1);
   1060 	return (0);
   1061 }
   1062 
   1063 char *
   1064 get_type(type)
   1065 	int type;
   1066 {
   1067 	struct part_type *ptr;
   1068 
   1069 	ptr = bsearch(&type, part_types,
   1070 	    sizeof(part_types) / sizeof(struct part_type),
   1071 	    sizeof(struct part_type), type_match);
   1072 	if (ptr == 0)
   1073 		return ("unknown");
   1074 	return (ptr->name);
   1075 }
   1076