xref: /freebsd/sbin/fdisk/fdisk.c (revision c1462236787ec09d00d5e2d222edc3e34bce1e69)
1 /*
2  * Mach Operating System
3  * Copyright (c) 1992 Carnegie Mellon University
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify and distribute this software and its
7  * documentation is hereby granted, provided that both the copyright
8  * notice and this permission notice appear in all copies of the
9  * software, derivative works or modified versions, and any portions
10  * thereof, and that both notices appear in supporting documentation.
11  *
12  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
13  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
14  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
15  *
16  * Carnegie Mellon requests users of this software to return to
17  *
18  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
19  *  School of Computer Science
20  *  Carnegie Mellon University
21  *  Pittsburgh PA 15213-3890
22  *
23  * any improvements or extensions that they make and grant Carnegie Mellon
24  * the rights to redistribute these changes.
25  */
26 
27 #ifndef lint
28 static const char rcsid[] =
29   "$FreeBSD$";
30 #endif /* not lint */
31 
32 #include <sys/disklabel.h>
33 #include <sys/stat.h>
34 #include <ctype.h>
35 #include <fcntl.h>
36 #include <err.h>
37 #include <errno.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 int iotest;
44 
45 #define LBUF 100
46 static char lbuf[LBUF];
47 
48 #define MBRSIGOFF	510
49 
50 /*
51  *
52  * Ported to 386bsd by Julian Elischer  Thu Oct 15 20:26:46 PDT 1992
53  *
54  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
55  *	Copyright (c) 1989	Robert. V. Baron
56  *	Created.
57  */
58 
59 #define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp
60 #define Hex(str, ans, tmp) if (hex(str, &tmp, ans)) ans = tmp
61 #define String(str, ans, len) {char *z = ans; char **dflt = &z; if (string(str, dflt)) strncpy(ans, *dflt, len); }
62 
63 #define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs)
64 
65 #define MAX_SEC_SIZE 2048	/* maximum section size that is supported */
66 #define MIN_SEC_SIZE 512	/* the sector size to start sensing at */
67 int secsize = 0;		/* the sensed sector size */
68 
69 const char *disk;
70 const char *disks[] =
71 {
72   "/dev/ad0", "/dev/wd0", "/dev/da0", "/dev/od0", 0
73 };
74 
75 struct disklabel disklabel;		/* disk parameters */
76 
77 int cyls, sectors, heads, cylsecs, disksecs;
78 
79 struct mboot
80 {
81 	unsigned char padding[2]; /* force the longs to be long aligned */
82   	unsigned char *bootinst;  /* boot code */
83   	off_t bootinst_size;
84 	struct	dos_partition parts[4];
85 };
86 struct mboot mboot = {{0}, NULL, 0};
87 
88 #define ACTIVE 0x80
89 #define BOOT_MAGIC 0xAA55
90 
91 int dos_cyls;
92 int dos_heads;
93 int dos_sectors;
94 int dos_cylsecs;
95 
96 #define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
97 #define DOSCYL(c)	(c & 0xff)
98 static int partition = -1;
99 
100 
101 #define MAX_ARGS	10
102 
103 static int	current_line_number;
104 
105 static int	geom_processed = 0;
106 static int	part_processed = 0;
107 static int	active_processed = 0;
108 
109 
110 typedef struct cmd {
111     char		cmd;
112     int			n_args;
113     struct arg {
114 	char	argtype;
115 	int	arg_val;
116     }			args[MAX_ARGS];
117 } CMD;
118 
119 
120 static int B_flag  = 0;		/* replace boot code */
121 static int I_flag  = 0;		/* use entire disk for FreeBSD */
122 static int a_flag  = 0;		/* set active partition */
123 static char *b_flag = NULL;	/* path to boot code */
124 static int i_flag  = 0;		/* replace partition data */
125 static int u_flag  = 0;		/* update partition data */
126 static int s_flag  = 0;		/* Print a summary and exit */
127 static int t_flag  = 0;		/* test only, if f_flag is given */
128 static char *f_flag = NULL;	/* Read config info from file */
129 static int v_flag  = 0;		/* Be verbose */
130 
131 struct part_type
132 {
133  unsigned char type;
134  char *name;
135 }part_types[] =
136 {
137 	 {0x00, "unused"}
138 	,{0x01, "Primary DOS with 12 bit FAT"}
139 	,{0x02, "XENIX / filesystem"}
140 	,{0x03, "XENIX /usr filesystem"}
141 	,{0x04, "Primary DOS with 16 bit FAT (<= 32MB)"}
142 	,{0x05, "Extended DOS"}
143 	,{0x06, "Primary 'big' DOS (> 32MB)"}
144 	,{0x07, "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX"}
145 	,{0x08, "AIX filesystem"}
146 	,{0x09, "AIX boot partition or Coherent"}
147 	,{0x0A, "OS/2 Boot Manager or OPUS"}
148 	,{0x0B, "DOS or Windows 95 with 32 bit FAT"}
149 	,{0x0C, "DOS or Windows 95 with 32 bit FAT, LBA"}
150 	,{0x0E, "Primary 'big' DOS (> 32MB, LBA)"}
151 	,{0x0F, "Extended DOS, LBA"}
152 	,{0x10, "OPUS"}
153 	,{0x39, "plan9"}
154 	,{0x40, "VENIX 286"}
155 	,{0x4D, "QNX 4.2 Primary"}
156 	,{0x4E, "QNX 4.2 Secondary"}
157 	,{0x4F, "QNX 4.2 Tertiary"}
158 	,{0x50, "DM"}
159 	,{0x51, "DM"}
160 	,{0x52, "CP/M or Microport SysV/AT"}
161 	,{0x56, "GB"}
162 	,{0x61, "Speed"}
163 	,{0x63, "ISC UNIX, other System V/386, GNU HURD or Mach"}
164 	,{0x64, "Novell Netware 2.xx"}
165 	,{0x65, "Novell Netware 3.xx"}
166 	,{0x75, "PCIX"}
167 	,{0x80, "Minix 1.1 ... 1.4a"}
168 	,{0x81, "Minix 1.4b ... 1.5.10"}
169 	,{0x82, "Linux swap or Solaris x86"}
170 	,{0x83, "Linux filesystem"}
171 	,{0x93, "Amoeba filesystem"}
172 	,{0x94, "Amoeba bad block table"}
173 	,{0x9F, "BSD/OS"}
174 	,{0xA5, "FreeBSD/NetBSD/386BSD"}
175 	,{0xA6, "OpenBSD"}
176 	,{0xA7, "NEXTSTEP"}
177 	,{0xA9, "NetBSD"}
178 	,{0xB7, "BSDI BSD/386 filesystem"}
179 	,{0xB8, "BSDI BSD/386 swap"}
180 	,{0xDB, "Concurrent CPM or C.DOS or CTOS"}
181 	,{0xE1, "Speed"}
182 	,{0xE3, "Speed"}
183 	,{0xE4, "Speed"}
184 	,{0xF1, "Speed"}
185 	,{0xF2, "DOS 3.3+ Secondary"}
186 	,{0xF4, "Speed"}
187 	,{0xFF, "BBT (Bad Blocks Table)"}
188 };
189 
190 static void print_s0(int which);
191 static void print_part(int i);
192 static void init_sector0(unsigned long start);
193 static void init_boot(void);
194 static void change_part(int i);
195 static void print_params();
196 static void change_active(int which);
197 static void change_code();
198 static void get_params_to_use();
199 static void dos(int sec, int size, unsigned char *c, unsigned char *s,
200 		unsigned char *h);
201 static int open_disk(int u_flag);
202 static ssize_t read_disk(off_t sector, void *buf);
203 static ssize_t write_disk(off_t sector, void *buf);
204 static int get_params();
205 static int read_s0();
206 static int write_s0();
207 static int ok(char *str);
208 static int decimal(char *str, int *num, int deflt);
209 static char *get_type(int type);
210 static int read_config(char *config_file);
211 static void reset_boot(void);
212 static void usage(void);
213 #if 0
214 static int hex(char *str, int *num, int deflt);
215 static int string(char *str, char **ans);
216 #endif
217 
218 
219 int
220 main(int argc, char *argv[])
221 {
222 	int	c, i;
223 
224 	while ((c = getopt(argc, argv, "BIab:f:istuv1234")) != -1)
225 		switch (c) {
226 		case 'B':
227 			B_flag = 1;
228 			break;
229 		case 'I':
230 			I_flag = 1;
231 			break;
232 		case 'a':
233 			a_flag = 1;
234 			break;
235 		case 'b':
236 			b_flag = optarg;
237 			break;
238 		case 'f':
239 			f_flag = optarg;
240 			break;
241 		case 'i':
242 			i_flag = 1;
243 			break;
244 		case 's':
245 			s_flag = 1;
246 			break;
247 		case 't':
248 			t_flag = 1;
249 			break;
250 		case 'u':
251 			u_flag = 1;
252 			break;
253 		case 'v':
254 			v_flag = 1;
255 			break;
256 		case '1':
257 		case '2':
258 		case '3':
259 		case '4':
260 			partition = c - '0';
261 			break;
262 		default:
263 			usage();
264 		}
265 	if (f_flag || i_flag)
266 		u_flag = 1;
267 	if (t_flag)
268 		v_flag = 1;
269 	argc -= optind;
270 	argv += optind;
271 
272 	if (argc > 0)
273 	{
274 		static char realname[12];
275 
276 		if(strncmp(argv[0], "/dev", 4) == 0)
277 			disk = argv[0];
278 		else
279 		{
280 			snprintf(realname, 12, "/dev/%s", argv[0]);
281 			disk = realname;
282 		}
283 
284 		if (open_disk(u_flag) < 0)
285 			err(1, "cannot open disk %s", disk);
286 	}
287 	else
288 	{
289 		int rv = 0;
290 
291 		for(i = 0; disks[i]; i++)
292 		{
293 			disk = disks[i];
294 			rv = open_disk(u_flag);
295 			if(rv != -2) break;
296 		}
297 		if(rv < 0)
298 			err(1, "cannot open any disk");
299 	}
300 
301 	/* (abu)use mboot.bootinst to probe for the sector size */
302 	if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
303 		err(1, "cannot allocate buffer to determine disk sector size");
304 	read_disk(0, mboot.bootinst);
305 	free(mboot.bootinst);
306 	mboot.bootinst = NULL;
307 
308 	if (s_flag)
309 	{
310 		int i;
311 		struct dos_partition *partp;
312 
313 		if (read_s0())
314 			err(1, "read_s0");
315 		printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
316 		    dos_sectors);
317 		printf("Part  %11s %11s Type Flags\n", "Start", "Size");
318 		for (i = 0; i < NDOSPART; i++) {
319 			partp = ((struct dos_partition *) &mboot.parts) + i;
320 			if (partp->dp_start == 0 && partp->dp_size == 0)
321 				continue;
322 			printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
323 			    (u_long) partp->dp_start,
324 			    (u_long) partp->dp_size, partp->dp_typ,
325 			    partp->dp_flag);
326 		}
327 		exit(0);
328 	}
329 
330 	printf("******* Working on device %s *******\n",disk);
331 
332 	if (I_flag)
333 	{
334 		struct dos_partition *partp;
335 
336 		read_s0();
337 		reset_boot();
338 		partp = (struct dos_partition *) (&mboot.parts[0]);
339 		partp->dp_typ = DOSPTYP_386BSD;
340 		partp->dp_flag = ACTIVE;
341 		partp->dp_start = dos_sectors;
342 		partp->dp_size = ((disksecs - dos_sectors) / dos_cylsecs) *
343 			dos_cylsecs;
344 
345 		dos(partp->dp_start, partp->dp_size,
346 		    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
347 		dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
348 		    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
349 		if (v_flag)
350 			print_s0(-1);
351 		write_s0();
352 		exit(0);
353 	}
354 	if (f_flag)
355 	{
356 	    if (read_s0() || i_flag)
357 	    {
358 		reset_boot();
359 	    }
360 
361 	    if (!read_config(f_flag))
362 	    {
363 		exit(1);
364 	    }
365 	    if (v_flag)
366 	    {
367 		print_s0(-1);
368 	    }
369 	    if (!t_flag)
370 	    {
371 		write_s0();
372 	    }
373 	}
374 	else
375 	{
376 	    if(u_flag)
377 	    {
378 		get_params_to_use();
379 	    }
380 	    else
381 	    {
382 		print_params();
383 	    }
384 
385 	    if (read_s0())
386 		init_sector0(1);
387 
388 	    printf("Media sector size is %d\n", secsize);
389 	    printf("Warning: BIOS sector numbering starts with sector 1\n");
390 	    printf("Information from DOS bootblock is:\n");
391 	    if (partition == -1)
392 		for (i = 1; i <= NDOSPART; i++)
393 		    change_part(i);
394 	    else
395 		change_part(partition);
396 
397 	    if (u_flag || a_flag)
398 		change_active(partition);
399 
400 	    if (B_flag)
401 		change_code();
402 
403 	    if (u_flag || a_flag || B_flag) {
404 		if (!t_flag)
405 		{
406 		    printf("\nWe haven't changed the partition table yet.  ");
407 		    printf("This is your last chance.\n");
408 		}
409 		print_s0(-1);
410 		if (!t_flag)
411 		{
412 		    if (ok("Should we write new partition table?"))
413 			write_s0();
414 		}
415 		else
416 		{
417 		    printf("\n-t flag specified -- partition table not written.\n");
418 		}
419 	    }
420 	}
421 
422 	exit(0);
423 }
424 
425 static void
426 usage()
427 {
428 	fprintf(stderr, "%s%s",
429 		"usage: fdisk [-BIaistu] [-b bootcode] [-1234] [disk]\n",
430  		"       fdisk -f configfile [-itv] [disk]\n");
431         exit(1);
432 }
433 
434 static void
435 print_s0(int which)
436 {
437 int	i;
438 
439 	print_params();
440 	printf("Information from DOS bootblock is:\n");
441 	if (which == -1)
442 		for (i = 1; i <= NDOSPART; i++)
443 			printf("%d: ", i), print_part(i);
444 	else
445 		print_part(which);
446 }
447 
448 static struct dos_partition mtpart = { 0 };
449 
450 static void
451 print_part(int i)
452 {
453 	struct	  dos_partition *partp;
454 	u_int64_t part_mb;
455 
456 	partp = ((struct dos_partition *) &mboot.parts) + i - 1;
457 
458 	if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
459 		printf("<UNUSED>\n");
460 		return;
461 	}
462 	/*
463 	 * Be careful not to overflow.
464 	 */
465 	part_mb = partp->dp_size;
466 	part_mb *= secsize;
467 	part_mb /= (1024 * 1024);
468 	printf("sysid %d,(%s)\n", partp->dp_typ, get_type(partp->dp_typ));
469 	printf("    start %lu, size %lu (%qd Meg), flag %x%s\n",
470 		(u_long)partp->dp_start,
471 		(u_long)partp->dp_size,
472 		part_mb,
473 		partp->dp_flag,
474 		partp->dp_flag == ACTIVE ? " (active)" : "");
475 	printf("\tbeg: cyl %d/ sector %d/ head %d;\n\tend: cyl %d/ sector %d/ head %d\n"
476 		,DPCYL(partp->dp_scyl, partp->dp_ssect)
477 		,DPSECT(partp->dp_ssect)
478 		,partp->dp_shd
479 		,DPCYL(partp->dp_ecyl, partp->dp_esect)
480 		,DPSECT(partp->dp_esect)
481 		,partp->dp_ehd);
482 }
483 
484 
485 static void
486 init_boot(void)
487 {
488 	const char *fname;
489 	int fd, n;
490 	struct stat sb;
491 
492 	fname = b_flag ? b_flag : "/boot/mbr";
493 	if ((fd = open(fname, O_RDONLY)) == -1 ||
494 	    fstat(fd, &sb) == -1)
495 		err(1, "%s", fname);
496 	if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
497 		errx(1, "%s: length must be a multiple of sector size", fname);
498 	if (mboot.bootinst != NULL)
499 		free(mboot.bootinst);
500 	if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
501 		errx(1, "%s: unable to allocate read buffer", fname);
502 	if ((n = read(fd, mboot.bootinst, mboot.bootinst_size)) == -1 ||
503 	    close(fd))
504 		err(1, "%s", fname);
505 	if (n != mboot.bootinst_size)
506 		errx(1, "%s: short read", fname);
507 }
508 
509 
510 static void
511 init_sector0(unsigned long start)
512 {
513 struct dos_partition *partp = (struct dos_partition *) (&mboot.parts[3]);
514 unsigned long size;
515 
516 	init_boot();
517 
518 	partp->dp_typ = DOSPTYP_386BSD;
519 	partp->dp_flag = ACTIVE;
520 	/* ensure cylinder boundaries */
521 	start = (start / dos_sectors) * dos_sectors;
522 	if(start == 0)
523 		start = dos_sectors;
524 	size = ((disksecs - start) / dos_cylsecs) * dos_cylsecs;
525 	partp->dp_start = start;
526 	partp->dp_size = size;
527 
528 	dos(partp->dp_start, partp->dp_size,
529 	    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
530 	dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
531 	    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
532 }
533 
534 static void
535 change_part(int i)
536 {
537 struct dos_partition *partp = ((struct dos_partition *) &mboot.parts) + i - 1;
538 
539     printf("The data for partition %d is:\n", i);
540     print_part(i);
541 
542     if (u_flag && ok("Do you want to change it?")) {
543 	int tmp;
544 
545 	if (i_flag) {
546 		bzero((char *)partp, sizeof (struct dos_partition));
547 		if (i == 4) {
548 			init_sector0(1);
549 			printf("\nThe static data for the DOS partition 4 has been reinitialized to:\n");
550 			print_part(i);
551 		}
552 	}
553 
554 	do {
555 		Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp);
556 		Decimal("start", partp->dp_start, tmp);
557 		Decimal("size", partp->dp_size, tmp);
558 
559 		if (ok("Explicitly specify beg/end address ?"))
560 		{
561 			int	tsec,tcyl,thd;
562 			tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
563 			thd = partp->dp_shd;
564 			tsec = DPSECT(partp->dp_ssect);
565 			Decimal("beginning cylinder", tcyl, tmp);
566 			Decimal("beginning head", thd, tmp);
567 			Decimal("beginning sector", tsec, tmp);
568 			partp->dp_scyl = DOSCYL(tcyl);
569 			partp->dp_ssect = DOSSECT(tsec,tcyl);
570 			partp->dp_shd = thd;
571 
572 			tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
573 			thd = partp->dp_ehd;
574 			tsec = DPSECT(partp->dp_esect);
575 			Decimal("ending cylinder", tcyl, tmp);
576 			Decimal("ending head", thd, tmp);
577 			Decimal("ending sector", tsec, tmp);
578 			partp->dp_ecyl = DOSCYL(tcyl);
579 			partp->dp_esect = DOSSECT(tsec,tcyl);
580 			partp->dp_ehd = thd;
581 		} else {
582 			if(partp->dp_start % dos_sectors != 0) {
583 				printf("Adjusting partition to start at a "
584 				   "cylinder boundary\n");
585 				partp->dp_start =
586 				    (partp->dp_start / dos_sectors) *
587 				    dos_sectors;
588 			}
589 			if(partp->dp_size % dos_cylsecs != 0) {
590 				printf("Adjusting partition to end at a "
591 				    "cylinder boundary\n");
592 				partp->dp_size =
593 				    (partp->dp_size / dos_cylsecs) *
594 				    dos_cylsecs;
595 			}
596 			dos(partp->dp_start, partp->dp_size,
597 			    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
598 			dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
599 			    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
600 		}
601 
602 		print_part(i);
603 	} while (!ok("Are we happy with this entry?"));
604     }
605 }
606 
607 static void
608 print_params()
609 {
610 	printf("parameters extracted from in-core disklabel are:\n");
611 	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
612 			,cyls,heads,sectors,cylsecs);
613 	if((dos_sectors > 63) || (dos_cyls > 1023) || (dos_heads > 255))
614 		printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
615 	printf("parameters to be used for BIOS calculations are:\n");
616 	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
617 		,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
618 }
619 
620 static void
621 change_active(int which)
622 {
623 int i;
624 int active = 4, tmp;
625 struct dos_partition *partp = ((struct dos_partition *) &mboot.parts);
626 
627 	if (a_flag && which != -1)
628 		active = which;
629 	if (!ok("Do you want to change the active partition?"))
630 		return;
631 setactive:
632 	active = 4;
633 	do {
634 		Decimal("active partition", active, tmp);
635 		if (active < 1 || 4 < active) {
636 			printf("Active partition number must be in range 1-4."
637 					"  Try again.\n");
638 			goto setactive;
639 		}
640 	} while (!ok("Are you happy with this choice"));
641 	for (i = 0; i < NDOSPART; i++)
642 		partp[i].dp_flag = 0;
643 	if (active > 0 && active <= NDOSPART)
644 		partp[active-1].dp_flag = ACTIVE;
645 }
646 
647 static void
648 change_code()
649 {
650 	if (ok("Do you want to change the boot code?"))
651 		init_boot();
652 }
653 
654 void
655 get_params_to_use()
656 {
657 	int	tmp;
658 	print_params();
659 	if (ok("Do you want to change our idea of what BIOS thinks ?"))
660 	{
661 		do
662 		{
663 			Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
664 			Decimal("BIOS's idea of #heads", dos_heads, tmp);
665 			Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
666 			dos_cylsecs = dos_heads * dos_sectors;
667 			print_params();
668 		}
669 		while(!ok("Are you happy with this choice"));
670 	}
671 }
672 
673 
674 /***********************************************\
675 * Change real numbers into strange dos numbers	*
676 \***********************************************/
677 static void
678 dos(sec, size, c, s, h)
679 int sec, size;
680 unsigned char *c, *s, *h;
681 {
682 int cy;
683 int hd;
684 
685 	if (sec == 0 && size == 0) {
686 		*s = *c = *h = 0;
687 		return;
688 	}
689 
690 	cy = sec / ( dos_cylsecs );
691 	sec = sec - cy * ( dos_cylsecs );
692 
693 	hd = sec / dos_sectors;
694 	sec = (sec - hd * dos_sectors) + 1;
695 
696 	*h = hd;
697 	*c = cy & 0xff;
698 	*s = (sec & 0x3f) | ( (cy & 0x300) >> 2);
699 }
700 
701 int fd;
702 
703 	/* Getting device status */
704 
705 static int
706 open_disk(int u_flag)
707 {
708 struct stat 	st;
709 
710 	if (stat(disk, &st) == -1) {
711 		warnx("can't get file status of %s", disk);
712 		return -1;
713 	}
714 	if ( !(st.st_mode & S_IFCHR) )
715 		warnx("device %s is not character special", disk);
716 	if ((fd = open(disk,
717 	    a_flag || I_flag || B_flag || u_flag ? O_RDWR : O_RDONLY)) == -1) {
718 		if(errno == ENXIO)
719 			return -2;
720 		warnx("can't open device %s", disk);
721 		return -1;
722 	}
723 	if (get_params(0) == -1) {
724 		warnx("can't get disk parameters on %s", disk);
725 		return -1;
726 	}
727 	return fd;
728 }
729 
730 static ssize_t
731 read_disk(off_t sector, void *buf)
732 {
733 	lseek(fd,(sector * 512), 0);
734 	if( secsize == 0 )
735 		for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
736 			{
737 			/* try the read */
738 			int size = read(fd, buf, secsize);
739 			if( size == secsize )
740 				/* it worked so return */
741 				return secsize;
742 			}
743 	else
744 		return read( fd, buf, secsize );
745 
746 	/* we failed to read at any of the sizes */
747 	return -1;
748 }
749 
750 static ssize_t
751 write_disk(off_t sector, void *buf)
752 {
753 	lseek(fd,(sector * 512), 0);
754 	/* write out in the size that the read_disk found worked */
755 	return write(fd, buf, secsize);
756 }
757 
758 static int
759 get_params()
760 {
761 
762     if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
763 	warnx("can't get disk parameters on %s; supplying dummy ones", disk);
764 	dos_cyls = cyls = 1;
765 	dos_heads = heads = 1;
766 	dos_sectors = sectors = 1;
767 	dos_cylsecs = cylsecs = heads * sectors;
768 	disksecs = cyls * heads * sectors;
769 	return disksecs;
770     }
771 
772     dos_cyls = cyls = disklabel.d_ncylinders;
773     dos_heads = heads = disklabel.d_ntracks;
774     dos_sectors = sectors = disklabel.d_nsectors;
775     dos_cylsecs = cylsecs = heads * sectors;
776     disksecs = cyls * heads * sectors;
777 
778     return (disksecs);
779 }
780 
781 
782 static int
783 read_s0()
784 {
785 	mboot.bootinst_size = secsize;
786 	if (mboot.bootinst != NULL)
787 		free(mboot.bootinst);
788 	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
789 		warnx("unable to allocate buffer to read fdisk "
790 		      "partition table");
791 		return -1;
792 	}
793 	if (read_disk(0, mboot.bootinst) == -1) {
794 		warnx("can't read fdisk partition table");
795 		return -1;
796 	}
797 	if (*(uint16_t *)&mboot.bootinst[MBRSIGOFF] != BOOT_MAGIC) {
798 		warnx("invalid fdisk partition table found");
799 		/* So should we initialize things */
800 		return -1;
801 	}
802 	memcpy(mboot.parts, &mboot.bootinst[DOSPARTOFF], sizeof(mboot.parts));
803 	return 0;
804 }
805 
806 static int
807 write_s0()
808 {
809 #ifdef NOT_NOW
810 	int	flag;
811 #endif
812 	int	sector;
813 
814 	if (iotest) {
815 		print_s0(-1);
816 		return 0;
817 	}
818 	memcpy(&mboot.bootinst[DOSPARTOFF], mboot.parts, sizeof(mboot.parts));
819 	/*
820 	 * write enable label sector before write (if necessary),
821 	 * disable after writing.
822 	 * needed if the disklabel protected area also protects
823 	 * sector 0. (e.g. empty disk)
824 	 */
825 #ifdef NOT_NOW
826 	flag = 1;
827 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
828 		warn("ioctl DIOCWLABEL");
829 #endif
830 	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
831 		if (write_disk(sector,
832 			       &mboot.bootinst[sector * secsize]) == -1) {
833 			warn("can't write fdisk partition table");
834 			return -1;
835 #ifdef NOT_NOW
836 			flag = 0;
837 			(void) ioctl(fd, DIOCWLABEL, &flag);
838 #endif
839 		}
840 #ifdef NOT_NOW
841 	flag = 0;
842 	(void) ioctl(fd, DIOCWLABEL, &flag);
843 #endif
844 	return(0);
845 }
846 
847 
848 static int
849 ok(str)
850 char *str;
851 {
852 	printf("%s [n] ", str);
853 	fgets(lbuf, LBUF, stdin);
854 	lbuf[strlen(lbuf)-1] = 0;
855 
856 	if (*lbuf &&
857 		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
858 		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
859 		return 1;
860 	else
861 		return 0;
862 }
863 
864 static int
865 decimal(char *str, int *num, int deflt)
866 {
867 int acc = 0, c;
868 char *cp;
869 
870 	while (1) {
871 		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
872 		fgets(lbuf, LBUF, stdin);
873 		lbuf[strlen(lbuf)-1] = 0;
874 
875 		if (!*lbuf)
876 			return 0;
877 
878 		cp = lbuf;
879 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
880 		if (!c)
881 			return 0;
882 		while ((c = *cp++)) {
883 			if (c <= '9' && c >= '0')
884 				acc = acc * 10 + c - '0';
885 			else
886 				break;
887 		}
888 		if (c == ' ' || c == '\t')
889 			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
890 		if (!c) {
891 			*num = acc;
892 			return 1;
893 		} else
894 			printf("%s is an invalid decimal number.  Try again.\n",
895 				lbuf);
896 	}
897 
898 }
899 
900 #if 0
901 static int
902 hex(char *str, int *num, int deflt)
903 {
904 int acc = 0, c;
905 char *cp;
906 
907 	while (1) {
908 		printf("Supply a hex value for \"%s\" [%x] ", str, deflt);
909 		fgets(lbuf, LBUF, stdin);
910 		lbuf[strlen(lbuf)-1] = 0;
911 
912 		if (!*lbuf)
913 			return 0;
914 
915 		cp = lbuf;
916 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
917 		if (!c)
918 			return 0;
919 		while ((c = *cp++)) {
920 			if (c <= '9' && c >= '0')
921 				acc = (acc << 4) + c - '0';
922 			else if (c <= 'f' && c >= 'a')
923 				acc = (acc << 4) + c - 'a' + 10;
924 			else if (c <= 'F' && c >= 'A')
925 				acc = (acc << 4) + c - 'A' + 10;
926 			else
927 				break;
928 		}
929 		if (c == ' ' || c == '\t')
930 			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
931 		if (!c) {
932 			*num = acc;
933 			return 1;
934 		} else
935 			printf("%s is an invalid hex number.  Try again.\n",
936 				lbuf);
937 	}
938 
939 }
940 
941 static int
942 string(char *str, char **ans)
943 {
944 int c;
945 char *cp = lbuf;
946 
947 	while (1) {
948 		printf("Supply a string value for \"%s\" [%s] ", str, *ans);
949 		fgets(lbuf, LBUF, stdin);
950 		lbuf[strlen(lbuf)-1] = 0;
951 
952 		if (!*lbuf)
953 			return 0;
954 
955 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
956 		if (c == '"') {
957 			c = *++cp;
958 			*ans = cp;
959 			while ((c = *cp) && c != '"') cp++;
960 		} else {
961 			*ans = cp;
962 			while ((c = *cp) && c != ' ' && c != '\t') cp++;
963 		}
964 
965 		if (c)
966 			*cp = 0;
967 		return 1;
968 	}
969 }
970 #endif
971 
972 static char *
973 get_type(int type)
974 {
975 	int	numentries = (sizeof(part_types)/sizeof(struct part_type));
976 	int	counter = 0;
977 	struct	part_type *ptr = part_types;
978 
979 
980 	while(counter < numentries)
981 	{
982 		if(ptr->type == type)
983 		{
984 			return(ptr->name);
985 		}
986 		ptr++;
987 		counter++;
988 	}
989 	return("unknown");
990 }
991 
992 
993 static void
994 parse_config_line(line, command)
995     char	*line;
996     CMD		*command;
997 {
998     char	*cp, *end;
999 
1000     cp = line;
1001     while (1)	/* dirty trick used to insure one exit point for this
1002 		   function */
1003     {
1004 	memset(command, 0, sizeof(*command));
1005 
1006 	while (isspace(*cp)) ++cp;
1007 	if (*cp == '\0' || *cp == '#')
1008 	{
1009 	    break;
1010 	}
1011 	command->cmd = *cp++;
1012 
1013 	/*
1014 	 * Parse args
1015 	 */
1016 	while (1)
1017 	{
1018 	    while (isspace(*cp)) ++cp;
1019 	    if (*cp == '#')
1020 	    {
1021 		break;		/* found comment */
1022 	    }
1023 	    if (isalpha(*cp))
1024 	    {
1025 		command->args[command->n_args].argtype = *cp++;
1026 	    }
1027 	    if (!isdigit(*cp))
1028 	    {
1029 		break;		/* assume end of line */
1030 	    }
1031 	    end = NULL;
1032 	    command->args[command->n_args].arg_val = strtol(cp, &end, 0);
1033 	    if (cp == end)
1034 	    {
1035 		break;		/* couldn't parse number */
1036 	    }
1037 	    cp = end;
1038 	    command->n_args++;
1039 	}
1040 	break;
1041     }
1042 }
1043 
1044 
1045 static int
1046 process_geometry(command)
1047     CMD		*command;
1048 {
1049     int		status = 1, i;
1050 
1051     while (1)
1052     {
1053 	geom_processed = 1;
1054 	if (part_processed)
1055 	{
1056 	    warnx(
1057 	"ERROR line %d: the geometry specification line must occur before\n\
1058     all partition specifications",
1059 		    current_line_number);
1060 	    status = 0;
1061 	    break;
1062 	}
1063 	if (command->n_args != 3)
1064 	{
1065 	    warnx("ERROR line %d: incorrect number of geometry args",
1066 		    current_line_number);
1067 	    status = 0;
1068 	    break;
1069 	}
1070 	dos_cyls = -1;
1071 	dos_heads = -1;
1072 	dos_sectors = -1;
1073 	for (i = 0; i < 3; ++i)
1074 	{
1075 	    switch (command->args[i].argtype)
1076 	    {
1077 	    case 'c':
1078 		dos_cyls = command->args[i].arg_val;
1079 		break;
1080 	    case 'h':
1081 		dos_heads = command->args[i].arg_val;
1082 		break;
1083 	    case 's':
1084 		dos_sectors = command->args[i].arg_val;
1085 		break;
1086 	    default:
1087 		warnx(
1088 		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1089 			current_line_number, command->args[i].argtype,
1090 			command->args[i].argtype);
1091 		status = 0;
1092 		break;
1093 	    }
1094 	}
1095 	if (status == 0)
1096 	{
1097 	    break;
1098 	}
1099 
1100 	dos_cylsecs = dos_heads * dos_sectors;
1101 
1102 	/*
1103 	 * Do sanity checks on parameter values
1104 	 */
1105 	if (dos_cyls < 0)
1106 	{
1107 	    warnx("ERROR line %d: number of cylinders not specified",
1108 		    current_line_number);
1109 	    status = 0;
1110 	}
1111 	if (dos_cyls == 0 || dos_cyls > 1024)
1112 	{
1113 	    warnx(
1114 	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1115     (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1116     is dedicated to FreeBSD)",
1117 		    current_line_number, dos_cyls);
1118 	}
1119 
1120 	if (dos_heads < 0)
1121 	{
1122 	    warnx("ERROR line %d: number of heads not specified",
1123 		    current_line_number);
1124 	    status = 0;
1125 	}
1126 	else if (dos_heads < 1 || dos_heads > 256)
1127 	{
1128 	    warnx("ERROR line %d: number of heads must be within (1-256)",
1129 		    current_line_number);
1130 	    status = 0;
1131 	}
1132 
1133 	if (dos_sectors < 0)
1134 	{
1135 	    warnx("ERROR line %d: number of sectors not specified",
1136 		    current_line_number);
1137 	    status = 0;
1138 	}
1139 	else if (dos_sectors < 1 || dos_sectors > 63)
1140 	{
1141 	    warnx("ERROR line %d: number of sectors must be within (1-63)",
1142 		    current_line_number);
1143 	    status = 0;
1144 	}
1145 
1146 	break;
1147     }
1148     return (status);
1149 }
1150 
1151 
1152 static int
1153 process_partition(command)
1154     CMD		*command;
1155 {
1156     int				status = 0, partition;
1157     unsigned long		chunks, adj_size, max_end;
1158     struct dos_partition	*partp;
1159 
1160     while (1)
1161     {
1162 	part_processed = 1;
1163 	if (command->n_args != 4)
1164 	{
1165 	    warnx("ERROR line %d: incorrect number of partition args",
1166 		    current_line_number);
1167 	    break;
1168 	}
1169 	partition = command->args[0].arg_val;
1170 	if (partition < 1 || partition > 4)
1171 	{
1172 	    warnx("ERROR line %d: invalid partition number %d",
1173 		    current_line_number, partition);
1174 	    break;
1175 	}
1176 	partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1177 	bzero((char *)partp, sizeof (struct dos_partition));
1178 	partp->dp_typ = command->args[1].arg_val;
1179 	partp->dp_start = command->args[2].arg_val;
1180 	partp->dp_size = command->args[3].arg_val;
1181 	max_end = partp->dp_start + partp->dp_size;
1182 
1183 	if (partp->dp_typ == 0)
1184 	{
1185 	    /*
1186 	     * Get out, the partition is marked as unused.
1187 	     */
1188 	    /*
1189 	     * Insure that it's unused.
1190 	     */
1191 	    bzero((char *)partp, sizeof (struct dos_partition));
1192 	    status = 1;
1193 	    break;
1194 	}
1195 
1196 	/*
1197 	 * Adjust start upwards, if necessary, to fall on an head boundary.
1198 	 */
1199 	if (partp->dp_start % dos_sectors != 0)
1200 	{
1201 	    adj_size =
1202 		(partp->dp_start / dos_sectors + 1) * dos_sectors;
1203 	    if (adj_size > max_end)
1204 	    {
1205 		/*
1206 		 * Can't go past end of partition
1207 		 */
1208 		warnx(
1209 	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
1210     a cylinder boundary",
1211 			current_line_number, partition);
1212 		break;
1213 	    }
1214 	    warnx(
1215 	"WARNING: adjusting start offset of partition '%d' from %lu\n\
1216     to %lu, to round to an head boundary",
1217 		    partition, (u_long)partp->dp_start, adj_size);
1218 	    partp->dp_start = adj_size;
1219 	}
1220 
1221 	/*
1222 	 * Adjust size downwards, if necessary, to fall on a cylinder
1223 	 * boundary.
1224 	 */
1225 	chunks =
1226 	    ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1227 	adj_size = chunks - partp->dp_start;
1228 	if (adj_size != partp->dp_size)
1229 	{
1230 	    warnx(
1231 	"WARNING: adjusting size of partition '%d' from %lu to %lu,\n\
1232     to round to a cylinder boundary",
1233 		    partition, (u_long)partp->dp_size, adj_size);
1234 	    if (chunks > 0)
1235 	    {
1236 		partp->dp_size = adj_size;
1237 	    }
1238 	    else
1239 	    {
1240 		partp->dp_size = 0;
1241 	    }
1242 	}
1243 	if (partp->dp_size < 1)
1244 	{
1245 	    warnx("ERROR line %d: size for partition '%d' is zero",
1246 		    current_line_number, partition);
1247 	    break;
1248 	}
1249 
1250 	dos(partp->dp_start, partp->dp_size,
1251 	    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
1252 	dos(partp->dp_start+partp->dp_size - 1, partp->dp_size,
1253 	    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
1254 	status = 1;
1255 	break;
1256     }
1257     return (status);
1258 }
1259 
1260 
1261 static int
1262 process_active(command)
1263     CMD		*command;
1264 {
1265     int				status = 0, partition, i;
1266     struct dos_partition	*partp;
1267 
1268     while (1)
1269     {
1270 	active_processed = 1;
1271 	if (command->n_args != 1)
1272 	{
1273 	    warnx("ERROR line %d: incorrect number of active args",
1274 		    current_line_number);
1275 	    status = 0;
1276 	    break;
1277 	}
1278 	partition = command->args[0].arg_val;
1279 	if (partition < 1 || partition > 4)
1280 	{
1281 	    warnx("ERROR line %d: invalid partition number %d",
1282 		    current_line_number, partition);
1283 	    break;
1284 	}
1285 	/*
1286 	 * Reset active partition
1287 	 */
1288 	partp = ((struct dos_partition *) &mboot.parts);
1289 	for (i = 0; i < NDOSPART; i++)
1290 	    partp[i].dp_flag = 0;
1291 	partp[partition-1].dp_flag = ACTIVE;
1292 
1293 	status = 1;
1294 	break;
1295     }
1296     return (status);
1297 }
1298 
1299 
1300 static int
1301 process_line(line)
1302     char	*line;
1303 {
1304     CMD		command;
1305     int		status = 1;
1306 
1307     while (1)
1308     {
1309 	parse_config_line(line, &command);
1310 	switch (command.cmd)
1311 	{
1312 	case 0:
1313 	    /*
1314 	     * Comment or blank line
1315 	     */
1316 	    break;
1317 	case 'g':
1318 	    /*
1319 	     * Set geometry
1320 	     */
1321 	    status = process_geometry(&command);
1322 	    break;
1323 	case 'p':
1324 	    status = process_partition(&command);
1325 	    break;
1326 	case 'a':
1327 	    status = process_active(&command);
1328 	    break;
1329 	default:
1330 	    status = 0;
1331 	    break;
1332 	}
1333 	break;
1334     }
1335     return (status);
1336 }
1337 
1338 
1339 static int
1340 read_config(config_file)
1341     char *config_file;
1342 {
1343     FILE	*fp = NULL;
1344     int		status = 1;
1345     char	buf[1010];
1346 
1347     while (1)	/* dirty trick used to insure one exit point for this
1348 		   function */
1349     {
1350 	if (strcmp(config_file, "-") != 0)
1351 	{
1352 	    /*
1353 	     * We're not reading from stdin
1354 	     */
1355 	    if ((fp = fopen(config_file, "r")) == NULL)
1356 	    {
1357 		status = 0;
1358 		break;
1359 	    }
1360 	}
1361 	else
1362 	{
1363 	    fp = stdin;
1364 	}
1365 	current_line_number = 0;
1366 	while (!feof(fp))
1367 	{
1368 	    if (fgets(buf, sizeof(buf), fp) == NULL)
1369 	    {
1370 		break;
1371 	    }
1372 	    ++current_line_number;
1373 	    status = process_line(buf);
1374 	    if (status == 0)
1375 	    {
1376 		break;
1377 	    }
1378 	}
1379 	break;
1380     }
1381     if (fp)
1382     {
1383 	/*
1384 	 * It doesn't matter if we're reading from stdin, as we've reached EOF
1385 	 */
1386 	fclose(fp);
1387     }
1388     return (status);
1389 }
1390 
1391 
1392 static void
1393 reset_boot(void)
1394 {
1395     int				i;
1396     struct dos_partition	*partp;
1397 
1398     init_boot();
1399     for (i = 0; i < 4; ++i)
1400     {
1401 	partp = ((struct dos_partition *) &mboot.parts) + i;
1402 	bzero((char *)partp, sizeof (struct dos_partition));
1403     }
1404 }
1405