xref: /freebsd/sbin/fdisk/fdisk.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
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 	,{0xA0, "Suspend to Disk"}
175 	,{0xA5, "FreeBSD/NetBSD/386BSD"}
176 	,{0xA6, "OpenBSD"}
177 	,{0xA7, "NEXTSTEP"}
178 	,{0xA9, "NetBSD"}
179 	,{0xB7, "BSDI BSD/386 filesystem"}
180 	,{0xB8, "BSDI BSD/386 swap"}
181 	,{0xDB, "Concurrent CPM or C.DOS or CTOS"}
182 	,{0xE1, "Speed"}
183 	,{0xE3, "Speed"}
184 	,{0xE4, "Speed"}
185 	,{0xF1, "Speed"}
186 	,{0xF2, "DOS 3.3+ Secondary"}
187 	,{0xF4, "Speed"}
188 	,{0xFF, "BBT (Bad Blocks Table)"}
189 };
190 
191 static void print_s0(int which);
192 static void print_part(int i);
193 static void init_sector0(unsigned long start);
194 static void init_boot(void);
195 static void change_part(int i);
196 static void print_params();
197 static void change_active(int which);
198 static void change_code();
199 static void get_params_to_use();
200 static void dos(int sec, int size, unsigned char *c, unsigned char *s,
201 		unsigned char *h);
202 static int open_disk(int u_flag);
203 static ssize_t read_disk(off_t sector, void *buf);
204 static ssize_t write_disk(off_t sector, void *buf);
205 static int get_params();
206 static int read_s0();
207 static int write_s0();
208 static int ok(char *str);
209 static int decimal(char *str, int *num, int deflt);
210 static char *get_type(int type);
211 static int read_config(char *config_file);
212 static void reset_boot(void);
213 static int sanitize_partition(struct dos_partition *);
214 static void usage(void);
215 #if 0
216 static int hex(char *str, int *num, int deflt);
217 static int string(char *str, char **ans);
218 #endif
219 
220 
221 int
222 main(int argc, char *argv[])
223 {
224 	int	c, i;
225 
226 	while ((c = getopt(argc, argv, "BIab:f:istuv1234")) != -1)
227 		switch (c) {
228 		case 'B':
229 			B_flag = 1;
230 			break;
231 		case 'I':
232 			I_flag = 1;
233 			break;
234 		case 'a':
235 			a_flag = 1;
236 			break;
237 		case 'b':
238 			b_flag = optarg;
239 			break;
240 		case 'f':
241 			f_flag = optarg;
242 			break;
243 		case 'i':
244 			i_flag = 1;
245 			break;
246 		case 's':
247 			s_flag = 1;
248 			break;
249 		case 't':
250 			t_flag = 1;
251 			break;
252 		case 'u':
253 			u_flag = 1;
254 			break;
255 		case 'v':
256 			v_flag = 1;
257 			break;
258 		case '1':
259 		case '2':
260 		case '3':
261 		case '4':
262 			partition = c - '0';
263 			break;
264 		default:
265 			usage();
266 		}
267 	if (f_flag || i_flag)
268 		u_flag = 1;
269 	if (t_flag)
270 		v_flag = 1;
271 	argc -= optind;
272 	argv += optind;
273 
274 	if (argc > 0)
275 	{
276 		static char realname[12];
277 
278 		if(strncmp(argv[0], "/dev", 4) == 0)
279 			disk = argv[0];
280 		else
281 		{
282 			snprintf(realname, 12, "/dev/%s", argv[0]);
283 			disk = realname;
284 		}
285 
286 		if (open_disk(u_flag) < 0)
287 			err(1, "cannot open disk %s", disk);
288 	}
289 	else
290 	{
291 		int rv = 0;
292 
293 		for(i = 0; disks[i]; i++)
294 		{
295 			disk = disks[i];
296 			rv = open_disk(u_flag);
297 			if(rv != -2) break;
298 		}
299 		if(rv < 0)
300 			err(1, "cannot open any disk");
301 	}
302 
303 	/* (abu)use mboot.bootinst to probe for the sector size */
304 	if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
305 		err(1, "cannot allocate buffer to determine disk sector size");
306 	read_disk(0, mboot.bootinst);
307 	free(mboot.bootinst);
308 	mboot.bootinst = NULL;
309 
310 	if (s_flag)
311 	{
312 		int i;
313 		struct dos_partition *partp;
314 
315 		if (read_s0())
316 			err(1, "read_s0");
317 		printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
318 		    dos_sectors);
319 		printf("Part  %11s %11s Type Flags\n", "Start", "Size");
320 		for (i = 0; i < NDOSPART; i++) {
321 			partp = ((struct dos_partition *) &mboot.parts) + i;
322 			if (partp->dp_start == 0 && partp->dp_size == 0)
323 				continue;
324 			printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
325 			    (u_long) partp->dp_start,
326 			    (u_long) partp->dp_size, partp->dp_typ,
327 			    partp->dp_flag);
328 		}
329 		exit(0);
330 	}
331 
332 	printf("******* Working on device %s *******\n",disk);
333 
334 	if (I_flag)
335 	{
336 		struct dos_partition *partp;
337 
338 		read_s0();
339 		reset_boot();
340 		partp = (struct dos_partition *) (&mboot.parts[0]);
341 		partp->dp_typ = DOSPTYP_386BSD;
342 		partp->dp_flag = ACTIVE;
343 		partp->dp_start = dos_sectors;
344 		partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs -
345 		    dos_sectors;
346 
347 		dos(partp->dp_start, partp->dp_size,
348 		    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
349 		dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
350 		    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
351 		if (v_flag)
352 			print_s0(-1);
353 		write_s0();
354 		exit(0);
355 	}
356 	if (f_flag)
357 	{
358 	    if (read_s0() || i_flag)
359 	    {
360 		reset_boot();
361 	    }
362 
363 	    if (!read_config(f_flag))
364 	    {
365 		exit(1);
366 	    }
367 	    if (v_flag)
368 	    {
369 		print_s0(-1);
370 	    }
371 	    if (!t_flag)
372 	    {
373 		write_s0();
374 	    }
375 	}
376 	else
377 	{
378 	    if(u_flag)
379 	    {
380 		get_params_to_use();
381 	    }
382 	    else
383 	    {
384 		print_params();
385 	    }
386 
387 	    if (read_s0())
388 		init_sector0(dos_sectors);
389 
390 	    printf("Media sector size is %d\n", secsize);
391 	    printf("Warning: BIOS sector numbering starts with sector 1\n");
392 	    printf("Information from DOS bootblock is:\n");
393 	    if (partition == -1)
394 		for (i = 1; i <= NDOSPART; i++)
395 		    change_part(i);
396 	    else
397 		change_part(partition);
398 
399 	    if (u_flag || a_flag)
400 		change_active(partition);
401 
402 	    if (B_flag)
403 		change_code();
404 
405 	    if (u_flag || a_flag || B_flag) {
406 		if (!t_flag)
407 		{
408 		    printf("\nWe haven't changed the partition table yet.  ");
409 		    printf("This is your last chance.\n");
410 		}
411 		print_s0(-1);
412 		if (!t_flag)
413 		{
414 		    if (ok("Should we write new partition table?"))
415 			write_s0();
416 		}
417 		else
418 		{
419 		    printf("\n-t flag specified -- partition table not written.\n");
420 		}
421 	    }
422 	}
423 
424 	exit(0);
425 }
426 
427 static void
428 usage()
429 {
430 	fprintf(stderr, "%s%s",
431 		"usage: fdisk [-BIaistu] [-b bootcode] [-1234] [disk]\n",
432  		"       fdisk -f configfile [-itv] [disk]\n");
433         exit(1);
434 }
435 
436 static void
437 print_s0(int which)
438 {
439 int	i;
440 
441 	print_params();
442 	printf("Information from DOS bootblock is:\n");
443 	if (which == -1)
444 		for (i = 1; i <= NDOSPART; i++)
445 			printf("%d: ", i), print_part(i);
446 	else
447 		print_part(which);
448 }
449 
450 static struct dos_partition mtpart = { 0 };
451 
452 static void
453 print_part(int i)
454 {
455 	struct	  dos_partition *partp;
456 	u_int64_t part_mb;
457 
458 	partp = ((struct dos_partition *) &mboot.parts) + i - 1;
459 
460 	if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
461 		printf("<UNUSED>\n");
462 		return;
463 	}
464 	/*
465 	 * Be careful not to overflow.
466 	 */
467 	part_mb = partp->dp_size;
468 	part_mb *= secsize;
469 	part_mb /= (1024 * 1024);
470 	printf("sysid %d,(%s)\n", partp->dp_typ, get_type(partp->dp_typ));
471 	printf("    start %lu, size %lu (%qd Meg), flag %x%s\n",
472 		(u_long)partp->dp_start,
473 		(u_long)partp->dp_size,
474 		part_mb,
475 		partp->dp_flag,
476 		partp->dp_flag == ACTIVE ? " (active)" : "");
477 	printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
478 		,DPCYL(partp->dp_scyl, partp->dp_ssect)
479 		,partp->dp_shd
480 		,DPSECT(partp->dp_ssect)
481 		,DPCYL(partp->dp_ecyl, partp->dp_esect)
482 		,partp->dp_ehd
483 		,DPSECT(partp->dp_esect));
484 }
485 
486 
487 static void
488 init_boot(void)
489 {
490 	const char *fname;
491 	int fd, n;
492 	struct stat sb;
493 
494 	fname = b_flag ? b_flag : "/boot/mbr";
495 	if ((fd = open(fname, O_RDONLY)) == -1 ||
496 	    fstat(fd, &sb) == -1)
497 		err(1, "%s", fname);
498 	if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
499 		errx(1, "%s: length must be a multiple of sector size", fname);
500 	if (mboot.bootinst != NULL)
501 		free(mboot.bootinst);
502 	if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
503 		errx(1, "%s: unable to allocate read buffer", fname);
504 	if ((n = read(fd, mboot.bootinst, mboot.bootinst_size)) == -1 ||
505 	    close(fd))
506 		err(1, "%s", fname);
507 	if (n != mboot.bootinst_size)
508 		errx(1, "%s: short read", fname);
509 }
510 
511 
512 static void
513 init_sector0(unsigned long start)
514 {
515 struct dos_partition *partp = (struct dos_partition *) (&mboot.parts[3]);
516 
517 	init_boot();
518 
519 	partp->dp_typ = DOSPTYP_386BSD;
520 	partp->dp_flag = ACTIVE;
521 	start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors;
522 	if(start == 0)
523 		start = dos_sectors;
524 	partp->dp_start = start;
525 	partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start;
526 
527 	dos(partp->dp_start, partp->dp_size,
528 	    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
529 	dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
530 	    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
531 }
532 
533 static void
534 change_part(int i)
535 {
536 struct dos_partition *partp = ((struct dos_partition *) &mboot.parts) + i - 1;
537 
538     printf("The data for partition %d is:\n", i);
539     print_part(i);
540 
541     if (u_flag && ok("Do you want to change it?")) {
542 	int tmp;
543 
544 	if (i_flag) {
545 		bzero((char *)partp, sizeof (struct dos_partition));
546 		if (i == 4) {
547 			init_sector0(1);
548 			printf("\nThe static data for the DOS partition 4 has been reinitialized to:\n");
549 			print_part(i);
550 		}
551 	}
552 
553 	do {
554 		Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp);
555 		Decimal("start", partp->dp_start, tmp);
556 		Decimal("size", partp->dp_size, tmp);
557 
558 		if (ok("Explicitly specify beg/end address ?"))
559 		{
560 			int	tsec,tcyl,thd;
561 			tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
562 			thd = partp->dp_shd;
563 			tsec = DPSECT(partp->dp_ssect);
564 			Decimal("beginning cylinder", tcyl, tmp);
565 			Decimal("beginning head", thd, tmp);
566 			Decimal("beginning sector", tsec, tmp);
567 			partp->dp_scyl = DOSCYL(tcyl);
568 			partp->dp_ssect = DOSSECT(tsec,tcyl);
569 			partp->dp_shd = thd;
570 
571 			tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
572 			thd = partp->dp_ehd;
573 			tsec = DPSECT(partp->dp_esect);
574 			Decimal("ending cylinder", tcyl, tmp);
575 			Decimal("ending head", thd, tmp);
576 			Decimal("ending sector", tsec, tmp);
577 			partp->dp_ecyl = DOSCYL(tcyl);
578 			partp->dp_esect = DOSSECT(tsec,tcyl);
579 			partp->dp_ehd = thd;
580 		} else {
581 			if (!sanitize_partition(partp))
582 				partp->dp_typ = 0;
583 			dos(partp->dp_start, partp->dp_size,
584 			    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
585 			dos(partp->dp_start + partp->dp_size - 1, partp->dp_size,
586 			    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
587 		}
588 
589 		print_part(i);
590 	} while (!ok("Are we happy with this entry?"));
591     }
592 }
593 
594 static void
595 print_params()
596 {
597 	printf("parameters extracted from in-core disklabel are:\n");
598 	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
599 			,cyls,heads,sectors,cylsecs);
600 	if((dos_sectors > 63) || (dos_cyls > 1023) || (dos_heads > 255))
601 		printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
602 	printf("parameters to be used for BIOS calculations are:\n");
603 	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
604 		,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
605 }
606 
607 static void
608 change_active(int which)
609 {
610 int i;
611 int active = 4, tmp;
612 struct dos_partition *partp = ((struct dos_partition *) &mboot.parts);
613 
614 	if (a_flag && which != -1)
615 		active = which;
616 	if (!ok("Do you want to change the active partition?"))
617 		return;
618 setactive:
619 	active = 4;
620 	do {
621 		Decimal("active partition", active, tmp);
622 		if (active < 1 || 4 < active) {
623 			printf("Active partition number must be in range 1-4."
624 					"  Try again.\n");
625 			goto setactive;
626 		}
627 	} while (!ok("Are you happy with this choice"));
628 	for (i = 0; i < NDOSPART; i++)
629 		partp[i].dp_flag = 0;
630 	if (active > 0 && active <= NDOSPART)
631 		partp[active-1].dp_flag = ACTIVE;
632 }
633 
634 static void
635 change_code()
636 {
637 	if (ok("Do you want to change the boot code?"))
638 		init_boot();
639 }
640 
641 void
642 get_params_to_use()
643 {
644 	int	tmp;
645 	print_params();
646 	if (ok("Do you want to change our idea of what BIOS thinks ?"))
647 	{
648 		do
649 		{
650 			Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
651 			Decimal("BIOS's idea of #heads", dos_heads, tmp);
652 			Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
653 			dos_cylsecs = dos_heads * dos_sectors;
654 			print_params();
655 		}
656 		while(!ok("Are you happy with this choice"));
657 	}
658 }
659 
660 
661 /***********************************************\
662 * Change real numbers into strange dos numbers	*
663 \***********************************************/
664 static void
665 dos(sec, size, c, s, h)
666 int sec, size;
667 unsigned char *c, *s, *h;
668 {
669 int cy;
670 int hd;
671 
672 	if (sec == 0 && size == 0) {
673 		*s = *c = *h = 0;
674 		return;
675 	}
676 
677 	cy = sec / ( dos_cylsecs );
678 	sec = sec - cy * ( dos_cylsecs );
679 
680 	hd = sec / dos_sectors;
681 	sec = (sec - hd * dos_sectors) + 1;
682 
683 	*h = hd;
684 	*c = cy & 0xff;
685 	*s = (sec & 0x3f) | ( (cy & 0x300) >> 2);
686 }
687 
688 int fd;
689 
690 	/* Getting device status */
691 
692 static int
693 open_disk(int u_flag)
694 {
695 struct stat 	st;
696 
697 	if (stat(disk, &st) == -1) {
698 		warnx("can't get file status of %s", disk);
699 		return -1;
700 	}
701 	if ( !(st.st_mode & S_IFCHR) )
702 		warnx("device %s is not character special", disk);
703 	if ((fd = open(disk,
704 	    a_flag || I_flag || B_flag || u_flag ? O_RDWR : O_RDONLY)) == -1) {
705 		if(errno == ENXIO)
706 			return -2;
707 		warnx("can't open device %s", disk);
708 		return -1;
709 	}
710 	if (get_params(0) == -1) {
711 		warnx("can't get disk parameters on %s", disk);
712 		return -1;
713 	}
714 	return fd;
715 }
716 
717 static ssize_t
718 read_disk(off_t sector, void *buf)
719 {
720 	lseek(fd,(sector * 512), 0);
721 	if( secsize == 0 )
722 		for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
723 			{
724 			/* try the read */
725 			int size = read(fd, buf, secsize);
726 			if( size == secsize )
727 				/* it worked so return */
728 				return secsize;
729 			}
730 	else
731 		return read( fd, buf, secsize );
732 
733 	/* we failed to read at any of the sizes */
734 	return -1;
735 }
736 
737 static ssize_t
738 write_disk(off_t sector, void *buf)
739 {
740 	lseek(fd,(sector * 512), 0);
741 	/* write out in the size that the read_disk found worked */
742 	return write(fd, buf, secsize);
743 }
744 
745 static int
746 get_params()
747 {
748 
749     if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
750 	warnx("can't get disk parameters on %s; supplying dummy ones", disk);
751 	dos_cyls = cyls = 1;
752 	dos_heads = heads = 1;
753 	dos_sectors = sectors = 1;
754 	dos_cylsecs = cylsecs = heads * sectors;
755 	disksecs = cyls * heads * sectors;
756 	return disksecs;
757     }
758 
759     dos_cyls = cyls = disklabel.d_ncylinders;
760     dos_heads = heads = disklabel.d_ntracks;
761     dos_sectors = sectors = disklabel.d_nsectors;
762     dos_cylsecs = cylsecs = heads * sectors;
763     disksecs = cyls * heads * sectors;
764 
765     return (disksecs);
766 }
767 
768 
769 static int
770 read_s0()
771 {
772 	mboot.bootinst_size = secsize;
773 	if (mboot.bootinst != NULL)
774 		free(mboot.bootinst);
775 	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
776 		warnx("unable to allocate buffer to read fdisk "
777 		      "partition table");
778 		return -1;
779 	}
780 	if (read_disk(0, mboot.bootinst) == -1) {
781 		warnx("can't read fdisk partition table");
782 		return -1;
783 	}
784 	if (*(uint16_t *)&mboot.bootinst[MBRSIGOFF] != BOOT_MAGIC) {
785 		warnx("invalid fdisk partition table found");
786 		/* So should we initialize things */
787 		return -1;
788 	}
789 	memcpy(mboot.parts, &mboot.bootinst[DOSPARTOFF], sizeof(mboot.parts));
790 	return 0;
791 }
792 
793 static int
794 write_s0()
795 {
796 #ifdef NOT_NOW
797 	int	flag;
798 #endif
799 	int	sector;
800 
801 	if (iotest) {
802 		print_s0(-1);
803 		return 0;
804 	}
805 	memcpy(&mboot.bootinst[DOSPARTOFF], mboot.parts, sizeof(mboot.parts));
806 	/*
807 	 * write enable label sector before write (if necessary),
808 	 * disable after writing.
809 	 * needed if the disklabel protected area also protects
810 	 * sector 0. (e.g. empty disk)
811 	 */
812 #ifdef NOT_NOW
813 	flag = 1;
814 	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
815 		warn("ioctl DIOCWLABEL");
816 #endif
817 	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
818 		if (write_disk(sector,
819 			       &mboot.bootinst[sector * secsize]) == -1) {
820 			warn("can't write fdisk partition table");
821 			return -1;
822 #ifdef NOT_NOW
823 			flag = 0;
824 			(void) ioctl(fd, DIOCWLABEL, &flag);
825 #endif
826 		}
827 #ifdef NOT_NOW
828 	flag = 0;
829 	(void) ioctl(fd, DIOCWLABEL, &flag);
830 #endif
831 	return(0);
832 }
833 
834 
835 static int
836 ok(str)
837 char *str;
838 {
839 	printf("%s [n] ", str);
840 	fgets(lbuf, LBUF, stdin);
841 	lbuf[strlen(lbuf)-1] = 0;
842 
843 	if (*lbuf &&
844 		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
845 		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
846 		return 1;
847 	else
848 		return 0;
849 }
850 
851 static int
852 decimal(char *str, int *num, int deflt)
853 {
854 int acc = 0, c;
855 char *cp;
856 
857 	while (1) {
858 		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
859 		fgets(lbuf, LBUF, stdin);
860 		lbuf[strlen(lbuf)-1] = 0;
861 
862 		if (!*lbuf)
863 			return 0;
864 
865 		cp = lbuf;
866 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
867 		if (!c)
868 			return 0;
869 		while ((c = *cp++)) {
870 			if (c <= '9' && c >= '0')
871 				acc = acc * 10 + c - '0';
872 			else
873 				break;
874 		}
875 		if (c == ' ' || c == '\t')
876 			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
877 		if (!c) {
878 			*num = acc;
879 			return 1;
880 		} else
881 			printf("%s is an invalid decimal number.  Try again.\n",
882 				lbuf);
883 	}
884 
885 }
886 
887 #if 0
888 static int
889 hex(char *str, int *num, int deflt)
890 {
891 int acc = 0, c;
892 char *cp;
893 
894 	while (1) {
895 		printf("Supply a hex value for \"%s\" [%x] ", str, deflt);
896 		fgets(lbuf, LBUF, stdin);
897 		lbuf[strlen(lbuf)-1] = 0;
898 
899 		if (!*lbuf)
900 			return 0;
901 
902 		cp = lbuf;
903 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
904 		if (!c)
905 			return 0;
906 		while ((c = *cp++)) {
907 			if (c <= '9' && c >= '0')
908 				acc = (acc << 4) + c - '0';
909 			else if (c <= 'f' && c >= 'a')
910 				acc = (acc << 4) + c - 'a' + 10;
911 			else if (c <= 'F' && c >= 'A')
912 				acc = (acc << 4) + c - 'A' + 10;
913 			else
914 				break;
915 		}
916 		if (c == ' ' || c == '\t')
917 			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
918 		if (!c) {
919 			*num = acc;
920 			return 1;
921 		} else
922 			printf("%s is an invalid hex number.  Try again.\n",
923 				lbuf);
924 	}
925 
926 }
927 
928 static int
929 string(char *str, char **ans)
930 {
931 int c;
932 char *cp = lbuf;
933 
934 	while (1) {
935 		printf("Supply a string value for \"%s\" [%s] ", str, *ans);
936 		fgets(lbuf, LBUF, stdin);
937 		lbuf[strlen(lbuf)-1] = 0;
938 
939 		if (!*lbuf)
940 			return 0;
941 
942 		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
943 		if (c == '"') {
944 			c = *++cp;
945 			*ans = cp;
946 			while ((c = *cp) && c != '"') cp++;
947 		} else {
948 			*ans = cp;
949 			while ((c = *cp) && c != ' ' && c != '\t') cp++;
950 		}
951 
952 		if (c)
953 			*cp = 0;
954 		return 1;
955 	}
956 }
957 #endif
958 
959 static char *
960 get_type(int type)
961 {
962 	int	numentries = (sizeof(part_types)/sizeof(struct part_type));
963 	int	counter = 0;
964 	struct	part_type *ptr = part_types;
965 
966 
967 	while(counter < numentries)
968 	{
969 		if(ptr->type == type)
970 		{
971 			return(ptr->name);
972 		}
973 		ptr++;
974 		counter++;
975 	}
976 	return("unknown");
977 }
978 
979 
980 static void
981 parse_config_line(line, command)
982     char	*line;
983     CMD		*command;
984 {
985     char	*cp, *end;
986 
987     cp = line;
988     while (1)	/* dirty trick used to insure one exit point for this
989 		   function */
990     {
991 	memset(command, 0, sizeof(*command));
992 
993 	while (isspace(*cp)) ++cp;
994 	if (*cp == '\0' || *cp == '#')
995 	{
996 	    break;
997 	}
998 	command->cmd = *cp++;
999 
1000 	/*
1001 	 * Parse args
1002 	 */
1003 	while (1)
1004 	{
1005 	    while (isspace(*cp)) ++cp;
1006 	    if (*cp == '#')
1007 	    {
1008 		break;		/* found comment */
1009 	    }
1010 	    if (isalpha(*cp))
1011 	    {
1012 		command->args[command->n_args].argtype = *cp++;
1013 	    }
1014 	    if (!isdigit(*cp))
1015 	    {
1016 		break;		/* assume end of line */
1017 	    }
1018 	    end = NULL;
1019 	    command->args[command->n_args].arg_val = strtol(cp, &end, 0);
1020 	    if (cp == end)
1021 	    {
1022 		break;		/* couldn't parse number */
1023 	    }
1024 	    cp = end;
1025 	    command->n_args++;
1026 	}
1027 	break;
1028     }
1029 }
1030 
1031 
1032 static int
1033 process_geometry(command)
1034     CMD		*command;
1035 {
1036     int		status = 1, i;
1037 
1038     while (1)
1039     {
1040 	geom_processed = 1;
1041 	if (part_processed)
1042 	{
1043 	    warnx(
1044 	"ERROR line %d: the geometry specification line must occur before\n\
1045     all partition specifications",
1046 		    current_line_number);
1047 	    status = 0;
1048 	    break;
1049 	}
1050 	if (command->n_args != 3)
1051 	{
1052 	    warnx("ERROR line %d: incorrect number of geometry args",
1053 		    current_line_number);
1054 	    status = 0;
1055 	    break;
1056 	}
1057 	dos_cyls = -1;
1058 	dos_heads = -1;
1059 	dos_sectors = -1;
1060 	for (i = 0; i < 3; ++i)
1061 	{
1062 	    switch (command->args[i].argtype)
1063 	    {
1064 	    case 'c':
1065 		dos_cyls = command->args[i].arg_val;
1066 		break;
1067 	    case 'h':
1068 		dos_heads = command->args[i].arg_val;
1069 		break;
1070 	    case 's':
1071 		dos_sectors = command->args[i].arg_val;
1072 		break;
1073 	    default:
1074 		warnx(
1075 		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1076 			current_line_number, command->args[i].argtype,
1077 			command->args[i].argtype);
1078 		status = 0;
1079 		break;
1080 	    }
1081 	}
1082 	if (status == 0)
1083 	{
1084 	    break;
1085 	}
1086 
1087 	dos_cylsecs = dos_heads * dos_sectors;
1088 
1089 	/*
1090 	 * Do sanity checks on parameter values
1091 	 */
1092 	if (dos_cyls < 0)
1093 	{
1094 	    warnx("ERROR line %d: number of cylinders not specified",
1095 		    current_line_number);
1096 	    status = 0;
1097 	}
1098 	if (dos_cyls == 0 || dos_cyls > 1024)
1099 	{
1100 	    warnx(
1101 	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1102     (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1103     is dedicated to FreeBSD)",
1104 		    current_line_number, dos_cyls);
1105 	}
1106 
1107 	if (dos_heads < 0)
1108 	{
1109 	    warnx("ERROR line %d: number of heads not specified",
1110 		    current_line_number);
1111 	    status = 0;
1112 	}
1113 	else if (dos_heads < 1 || dos_heads > 256)
1114 	{
1115 	    warnx("ERROR line %d: number of heads must be within (1-256)",
1116 		    current_line_number);
1117 	    status = 0;
1118 	}
1119 
1120 	if (dos_sectors < 0)
1121 	{
1122 	    warnx("ERROR line %d: number of sectors not specified",
1123 		    current_line_number);
1124 	    status = 0;
1125 	}
1126 	else if (dos_sectors < 1 || dos_sectors > 63)
1127 	{
1128 	    warnx("ERROR line %d: number of sectors must be within (1-63)",
1129 		    current_line_number);
1130 	    status = 0;
1131 	}
1132 
1133 	break;
1134     }
1135     return (status);
1136 }
1137 
1138 
1139 static int
1140 process_partition(command)
1141     CMD		*command;
1142 {
1143     int				status = 0, partition;
1144     u_int32_t			prev_head_boundary, prev_cyl_boundary;
1145     u_int32_t			adj_size, max_end;
1146     struct dos_partition	*partp;
1147 
1148     while (1)
1149     {
1150 	part_processed = 1;
1151 	if (command->n_args != 4)
1152 	{
1153 	    warnx("ERROR line %d: incorrect number of partition args",
1154 		    current_line_number);
1155 	    break;
1156 	}
1157 	partition = command->args[0].arg_val;
1158 	if (partition < 1 || partition > 4)
1159 	{
1160 	    warnx("ERROR line %d: invalid partition number %d",
1161 		    current_line_number, partition);
1162 	    break;
1163 	}
1164 	partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1165 	bzero((char *)partp, sizeof (struct dos_partition));
1166 	partp->dp_typ = command->args[1].arg_val;
1167 	partp->dp_start = command->args[2].arg_val;
1168 	partp->dp_size = command->args[3].arg_val;
1169 	max_end = partp->dp_start + partp->dp_size;
1170 
1171 	if (partp->dp_typ == 0)
1172 	{
1173 	    /*
1174 	     * Get out, the partition is marked as unused.
1175 	     */
1176 	    /*
1177 	     * Insure that it's unused.
1178 	     */
1179 	    bzero((char *)partp, sizeof (struct dos_partition));
1180 	    status = 1;
1181 	    break;
1182 	}
1183 
1184 	/*
1185 	 * Adjust start upwards, if necessary, to fall on an head boundary.
1186 	 */
1187 	if (partp->dp_start % dos_sectors != 0)
1188 	{
1189 	    prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1190 	    if (max_end < dos_sectors ||
1191 		prev_head_boundary > max_end - dos_sectors)
1192 	    {
1193 		/*
1194 		 * Can't go past end of partition
1195 		 */
1196 		warnx(
1197 	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
1198     a head boundary",
1199 			current_line_number, partition);
1200 		break;
1201 	    }
1202 	    warnx(
1203 	"WARNING: adjusting start offset of partition %d\n\
1204     from %u to %u, to fall on a head boundary",
1205 		    partition, (u_int)partp->dp_start,
1206 		    (u_int)(prev_head_boundary + dos_sectors));
1207 	    partp->dp_start = prev_head_boundary + dos_sectors;
1208 	}
1209 
1210 	/*
1211 	 * Adjust size downwards, if necessary, to fall on a cylinder
1212 	 * boundary.
1213 	 */
1214 	prev_cyl_boundary =
1215 	    ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1216 	if (prev_cyl_boundary > partp->dp_start)
1217 	    adj_size = prev_cyl_boundary - partp->dp_start;
1218 	else
1219 	{
1220 	    warnx(
1221 	"ERROR: could not adjust partition to start on a head boundary\n\
1222     and end on a cylinder boundary.");
1223 	    return (0);
1224 	}
1225 	if (adj_size != partp->dp_size)
1226 	{
1227 	    warnx(
1228 	"WARNING: adjusting size of partition %d from %u to %u\n\
1229     to end on a cylinder boundary",
1230 		    partition, (u_int)partp->dp_size, (u_int)adj_size);
1231 	    partp->dp_size = adj_size;
1232 	}
1233 	if (partp->dp_size == 0)
1234 	{
1235 	    warnx("ERROR line %d: size for partition %d is zero",
1236 		    current_line_number, partition);
1237 	    break;
1238 	}
1239 
1240 	dos(partp->dp_start, partp->dp_size,
1241 	    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
1242 	dos(partp->dp_start+partp->dp_size - 1, partp->dp_size,
1243 	    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
1244 	status = 1;
1245 	break;
1246     }
1247     return (status);
1248 }
1249 
1250 
1251 static int
1252 process_active(command)
1253     CMD		*command;
1254 {
1255     int				status = 0, partition, i;
1256     struct dos_partition	*partp;
1257 
1258     while (1)
1259     {
1260 	active_processed = 1;
1261 	if (command->n_args != 1)
1262 	{
1263 	    warnx("ERROR line %d: incorrect number of active args",
1264 		    current_line_number);
1265 	    status = 0;
1266 	    break;
1267 	}
1268 	partition = command->args[0].arg_val;
1269 	if (partition < 1 || partition > 4)
1270 	{
1271 	    warnx("ERROR line %d: invalid partition number %d",
1272 		    current_line_number, partition);
1273 	    break;
1274 	}
1275 	/*
1276 	 * Reset active partition
1277 	 */
1278 	partp = ((struct dos_partition *) &mboot.parts);
1279 	for (i = 0; i < NDOSPART; i++)
1280 	    partp[i].dp_flag = 0;
1281 	partp[partition-1].dp_flag = ACTIVE;
1282 
1283 	status = 1;
1284 	break;
1285     }
1286     return (status);
1287 }
1288 
1289 
1290 static int
1291 process_line(line)
1292     char	*line;
1293 {
1294     CMD		command;
1295     int		status = 1;
1296 
1297     while (1)
1298     {
1299 	parse_config_line(line, &command);
1300 	switch (command.cmd)
1301 	{
1302 	case 0:
1303 	    /*
1304 	     * Comment or blank line
1305 	     */
1306 	    break;
1307 	case 'g':
1308 	    /*
1309 	     * Set geometry
1310 	     */
1311 	    status = process_geometry(&command);
1312 	    break;
1313 	case 'p':
1314 	    status = process_partition(&command);
1315 	    break;
1316 	case 'a':
1317 	    status = process_active(&command);
1318 	    break;
1319 	default:
1320 	    status = 0;
1321 	    break;
1322 	}
1323 	break;
1324     }
1325     return (status);
1326 }
1327 
1328 
1329 static int
1330 read_config(config_file)
1331     char *config_file;
1332 {
1333     FILE	*fp = NULL;
1334     int		status = 1;
1335     char	buf[1010];
1336 
1337     while (1)	/* dirty trick used to insure one exit point for this
1338 		   function */
1339     {
1340 	if (strcmp(config_file, "-") != 0)
1341 	{
1342 	    /*
1343 	     * We're not reading from stdin
1344 	     */
1345 	    if ((fp = fopen(config_file, "r")) == NULL)
1346 	    {
1347 		status = 0;
1348 		break;
1349 	    }
1350 	}
1351 	else
1352 	{
1353 	    fp = stdin;
1354 	}
1355 	current_line_number = 0;
1356 	while (!feof(fp))
1357 	{
1358 	    if (fgets(buf, sizeof(buf), fp) == NULL)
1359 	    {
1360 		break;
1361 	    }
1362 	    ++current_line_number;
1363 	    status = process_line(buf);
1364 	    if (status == 0)
1365 	    {
1366 		break;
1367 	    }
1368 	}
1369 	break;
1370     }
1371     if (fp)
1372     {
1373 	/*
1374 	 * It doesn't matter if we're reading from stdin, as we've reached EOF
1375 	 */
1376 	fclose(fp);
1377     }
1378     return (status);
1379 }
1380 
1381 
1382 static void
1383 reset_boot(void)
1384 {
1385     int				i;
1386     struct dos_partition	*partp;
1387 
1388     init_boot();
1389     for (i = 0; i < 4; ++i)
1390     {
1391 	partp = ((struct dos_partition *) &mboot.parts) + i;
1392 	bzero((char *)partp, sizeof (struct dos_partition));
1393     }
1394 }
1395 
1396 static int
1397 sanitize_partition(partp)
1398     struct dos_partition	*partp;
1399 {
1400     u_int32_t			prev_head_boundary, prev_cyl_boundary;
1401     u_int32_t			adj_size, max_end;
1402 
1403     max_end = partp->dp_start + partp->dp_size;
1404 
1405     /*
1406      * Adjust start upwards, if necessary, to fall on an head boundary.
1407      */
1408     if (partp->dp_start % dos_sectors != 0) {
1409 	prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1410 	if (max_end < dos_sectors ||
1411 	    prev_head_boundary > max_end - dos_sectors) {
1412 	    /*
1413 	     * Can't go past end of partition
1414 	     */
1415 	    warnx(
1416     "ERROR: unable to adjust start of partition to fall on a head boundary");
1417 	    return (0);
1418         }
1419 	warnx(
1420     "WARNING: adjusting start offset of partition\n\
1421     to %u to fall on a head boundary",
1422 	    (u_int)(prev_head_boundary + dos_sectors));
1423 	partp->dp_start = prev_head_boundary + dos_sectors;
1424     }
1425 
1426     /*
1427      * Adjust size downwards, if necessary, to fall on a cylinder
1428      * boundary.
1429      */
1430     prev_cyl_boundary = ((partp->dp_start + partp->dp_size) / dos_cylsecs) *
1431 	dos_cylsecs;
1432     if (prev_cyl_boundary > partp->dp_start)
1433 	adj_size = prev_cyl_boundary - partp->dp_start;
1434     else
1435     {
1436 	warnx("ERROR: could not adjust partition to start on a head boundary\n\
1437     and end on a cylinder boundary.");
1438 	return (0);
1439     }
1440     if (adj_size != partp->dp_size) {
1441 	warnx(
1442     "WARNING: adjusting size of partition to %u to end on a\n\
1443     cylinder boundary",
1444 	    (u_int)adj_size);
1445 	partp->dp_size = adj_size;
1446     }
1447     if (partp->dp_size == 0) {
1448 	warnx("ERROR: size for partition is zero");
1449 	return (0);
1450     }
1451 
1452     return (1);
1453 }
1454