fdisk.c revision 79306
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
28static const char rcsid[] =
29  "$FreeBSD: head/sbin/fdisk/fdisk.c 79306 2001-07-05 10:04:43Z joerg $";
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
43int iotest;
44
45#define LBUF 100
46static 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 */
67int secsize = 0;		/* the sensed sector size */
68
69const char *disk;
70const char *disks[] =
71{
72  "/dev/ad0", "/dev/da0", 0
73};
74
75struct disklabel disklabel;		/* disk parameters */
76
77int cyls, sectors, heads, cylsecs, disksecs;
78
79struct 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};
86struct mboot mboot = {{0}, NULL, 0};
87
88#define ACTIVE 0x80
89#define BOOT_MAGIC 0xAA55
90
91int dos_cyls;
92int dos_heads;
93int dos_sectors;
94int dos_cylsecs;
95
96#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
97#define DOSCYL(c)	(c & 0xff)
98static int partition = -1;
99
100
101#define MAX_ARGS	10
102
103static int	current_line_number;
104
105static int	geom_processed = 0;
106static int	part_processed = 0;
107static int	active_processed = 0;
108
109
110typedef 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
120static int B_flag  = 0;		/* replace boot code */
121static int I_flag  = 0;		/* use entire disk for FreeBSD */
122static int a_flag  = 0;		/* set active partition */
123static char *b_flag = NULL;	/* path to boot code */
124static int i_flag  = 0;		/* replace partition data */
125static int u_flag  = 0;		/* update partition data */
126static int s_flag  = 0;		/* Print a summary and exit */
127static int t_flag  = 0;		/* test only, if f_flag is given */
128static char *f_flag = NULL;	/* Read config info from file */
129static int v_flag  = 0;		/* Be verbose */
130
131struct 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
191static void print_s0(int which);
192static void print_part(int i);
193static void init_sector0(unsigned long start);
194static void init_boot(void);
195static void change_part(int i);
196static void print_params();
197static void change_active(int which);
198static void change_code();
199static void get_params_to_use();
200static void dos(int sec, int size, unsigned char *c, unsigned char *s,
201		unsigned char *h);
202static int open_disk(int u_flag);
203static ssize_t read_disk(off_t sector, void *buf);
204static ssize_t write_disk(off_t sector, void *buf);
205static int get_params();
206static int read_s0();
207static int write_s0();
208static int ok(char *str);
209static int decimal(char *str, int *num, int deflt);
210static char *get_type(int type);
211static int read_config(char *config_file);
212static void reset_boot(void);
213static int sanitize_partition(struct dos_partition *);
214static void usage(void);
215#if 0
216static int hex(char *str, int *num, int deflt);
217static int string(char *str, char **ans);
218#endif
219
220
221int
222main(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
427static void
428usage()
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
436static void
437print_s0(int which)
438{
439int	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
450static struct dos_partition mtpart = { 0 };
451
452static void
453print_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
487static void
488init_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
512static void
513init_sector0(unsigned long start)
514{
515struct 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
533static void
534change_part(int i)
535{
536struct 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
594static void
595print_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
607static void
608change_active(int which)
609{
610int i;
611int active = 4, tmp;
612struct 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;
618setactive:
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
634static void
635change_code()
636{
637	if (ok("Do you want to change the boot code?"))
638		init_boot();
639}
640
641void
642get_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\***********************************************/
664static void
665dos(sec, size, c, s, h)
666int sec, size;
667unsigned char *c, *s, *h;
668{
669int cy;
670int 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
688int fd;
689
690	/* Getting device status */
691
692static int
693open_disk(int u_flag)
694{
695	struct stat 	st;
696
697	if (stat(disk, &st) == -1) {
698		if (errno == ENOENT)
699			return -2;
700		warnx("can't get file status of %s", disk);
701		return -1;
702	}
703	if ( !(st.st_mode & S_IFCHR) )
704		warnx("device %s is not character special", disk);
705	if ((fd = open(disk,
706	    a_flag || I_flag || B_flag || u_flag ? O_RDWR : O_RDONLY)) == -1) {
707		if(errno == ENXIO)
708			return -2;
709		warnx("can't open device %s", disk);
710		return -1;
711	}
712	if (get_params(0) == -1) {
713		warnx("can't get disk parameters on %s", disk);
714		return -1;
715	}
716	return fd;
717}
718
719static ssize_t
720read_disk(off_t sector, void *buf)
721{
722	lseek(fd,(sector * 512), 0);
723	if( secsize == 0 )
724		for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
725			{
726			/* try the read */
727			int size = read(fd, buf, secsize);
728			if( size == secsize )
729				/* it worked so return */
730				return secsize;
731			}
732	else
733		return read( fd, buf, secsize );
734
735	/* we failed to read at any of the sizes */
736	return -1;
737}
738
739static ssize_t
740write_disk(off_t sector, void *buf)
741{
742	lseek(fd,(sector * 512), 0);
743	/* write out in the size that the read_disk found worked */
744	return write(fd, buf, secsize);
745}
746
747static int
748get_params()
749{
750
751    if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
752	warnx("can't get disk parameters on %s; supplying dummy ones", disk);
753	dos_cyls = cyls = 1;
754	dos_heads = heads = 1;
755	dos_sectors = sectors = 1;
756	dos_cylsecs = cylsecs = heads * sectors;
757	disksecs = cyls * heads * sectors;
758	return disksecs;
759    }
760
761    dos_cyls = cyls = disklabel.d_ncylinders;
762    dos_heads = heads = disklabel.d_ntracks;
763    dos_sectors = sectors = disklabel.d_nsectors;
764    dos_cylsecs = cylsecs = heads * sectors;
765    disksecs = cyls * heads * sectors;
766
767    return (disksecs);
768}
769
770
771static int
772read_s0()
773{
774	mboot.bootinst_size = secsize;
775	if (mboot.bootinst != NULL)
776		free(mboot.bootinst);
777	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
778		warnx("unable to allocate buffer to read fdisk "
779		      "partition table");
780		return -1;
781	}
782	if (read_disk(0, mboot.bootinst) == -1) {
783		warnx("can't read fdisk partition table");
784		return -1;
785	}
786	if (*(uint16_t *)&mboot.bootinst[MBRSIGOFF] != BOOT_MAGIC) {
787		warnx("invalid fdisk partition table found");
788		/* So should we initialize things */
789		return -1;
790	}
791	memcpy(mboot.parts, &mboot.bootinst[DOSPARTOFF], sizeof(mboot.parts));
792	return 0;
793}
794
795static int
796write_s0()
797{
798#ifdef NOT_NOW
799	int	flag;
800#endif
801	int	sector;
802
803	if (iotest) {
804		print_s0(-1);
805		return 0;
806	}
807	memcpy(&mboot.bootinst[DOSPARTOFF], mboot.parts, sizeof(mboot.parts));
808	/*
809	 * write enable label sector before write (if necessary),
810	 * disable after writing.
811	 * needed if the disklabel protected area also protects
812	 * sector 0. (e.g. empty disk)
813	 */
814#ifdef NOT_NOW
815	flag = 1;
816	if (ioctl(fd, DIOCWLABEL, &flag) < 0)
817		warn("ioctl DIOCWLABEL");
818#endif
819	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
820		if (write_disk(sector,
821			       &mboot.bootinst[sector * secsize]) == -1) {
822			warn("can't write fdisk partition table");
823			return -1;
824#ifdef NOT_NOW
825			flag = 0;
826			(void) ioctl(fd, DIOCWLABEL, &flag);
827#endif
828		}
829#ifdef NOT_NOW
830	flag = 0;
831	(void) ioctl(fd, DIOCWLABEL, &flag);
832#endif
833	return(0);
834}
835
836
837static int
838ok(str)
839char *str;
840{
841	printf("%s [n] ", str);
842	fgets(lbuf, LBUF, stdin);
843	lbuf[strlen(lbuf)-1] = 0;
844
845	if (*lbuf &&
846		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
847		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
848		return 1;
849	else
850		return 0;
851}
852
853static int
854decimal(char *str, int *num, int deflt)
855{
856int acc = 0, c;
857char *cp;
858
859	while (1) {
860		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
861		fgets(lbuf, LBUF, stdin);
862		lbuf[strlen(lbuf)-1] = 0;
863
864		if (!*lbuf)
865			return 0;
866
867		cp = lbuf;
868		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
869		if (!c)
870			return 0;
871		while ((c = *cp++)) {
872			if (c <= '9' && c >= '0')
873				acc = acc * 10 + c - '0';
874			else
875				break;
876		}
877		if (c == ' ' || c == '\t')
878			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
879		if (!c) {
880			*num = acc;
881			return 1;
882		} else
883			printf("%s is an invalid decimal number.  Try again.\n",
884				lbuf);
885	}
886
887}
888
889#if 0
890static int
891hex(char *str, int *num, int deflt)
892{
893int acc = 0, c;
894char *cp;
895
896	while (1) {
897		printf("Supply a hex value for \"%s\" [%x] ", str, deflt);
898		fgets(lbuf, LBUF, stdin);
899		lbuf[strlen(lbuf)-1] = 0;
900
901		if (!*lbuf)
902			return 0;
903
904		cp = lbuf;
905		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
906		if (!c)
907			return 0;
908		while ((c = *cp++)) {
909			if (c <= '9' && c >= '0')
910				acc = (acc << 4) + c - '0';
911			else if (c <= 'f' && c >= 'a')
912				acc = (acc << 4) + c - 'a' + 10;
913			else if (c <= 'F' && c >= 'A')
914				acc = (acc << 4) + c - 'A' + 10;
915			else
916				break;
917		}
918		if (c == ' ' || c == '\t')
919			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
920		if (!c) {
921			*num = acc;
922			return 1;
923		} else
924			printf("%s is an invalid hex number.  Try again.\n",
925				lbuf);
926	}
927
928}
929
930static int
931string(char *str, char **ans)
932{
933int c;
934char *cp = lbuf;
935
936	while (1) {
937		printf("Supply a string value for \"%s\" [%s] ", str, *ans);
938		fgets(lbuf, LBUF, stdin);
939		lbuf[strlen(lbuf)-1] = 0;
940
941		if (!*lbuf)
942			return 0;
943
944		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
945		if (c == '"') {
946			c = *++cp;
947			*ans = cp;
948			while ((c = *cp) && c != '"') cp++;
949		} else {
950			*ans = cp;
951			while ((c = *cp) && c != ' ' && c != '\t') cp++;
952		}
953
954		if (c)
955			*cp = 0;
956		return 1;
957	}
958}
959#endif
960
961static char *
962get_type(int type)
963{
964	int	numentries = (sizeof(part_types)/sizeof(struct part_type));
965	int	counter = 0;
966	struct	part_type *ptr = part_types;
967
968
969	while(counter < numentries)
970	{
971		if(ptr->type == type)
972		{
973			return(ptr->name);
974		}
975		ptr++;
976		counter++;
977	}
978	return("unknown");
979}
980
981
982static void
983parse_config_line(line, command)
984    char	*line;
985    CMD		*command;
986{
987    char	*cp, *end;
988
989    cp = line;
990    while (1)	/* dirty trick used to insure one exit point for this
991		   function */
992    {
993	memset(command, 0, sizeof(*command));
994
995	while (isspace(*cp)) ++cp;
996	if (*cp == '\0' || *cp == '#')
997	{
998	    break;
999	}
1000	command->cmd = *cp++;
1001
1002	/*
1003	 * Parse args
1004	 */
1005	while (1)
1006	{
1007	    while (isspace(*cp)) ++cp;
1008	    if (*cp == '#')
1009	    {
1010		break;		/* found comment */
1011	    }
1012	    if (isalpha(*cp))
1013	    {
1014		command->args[command->n_args].argtype = *cp++;
1015	    }
1016	    if (!isdigit(*cp))
1017	    {
1018		break;		/* assume end of line */
1019	    }
1020	    end = NULL;
1021	    command->args[command->n_args].arg_val = strtol(cp, &end, 0);
1022	    if (cp == end)
1023	    {
1024		break;		/* couldn't parse number */
1025	    }
1026	    cp = end;
1027	    command->n_args++;
1028	}
1029	break;
1030    }
1031}
1032
1033
1034static int
1035process_geometry(command)
1036    CMD		*command;
1037{
1038    int		status = 1, i;
1039
1040    while (1)
1041    {
1042	geom_processed = 1;
1043	if (part_processed)
1044	{
1045	    warnx(
1046	"ERROR line %d: the geometry specification line must occur before\n\
1047    all partition specifications",
1048		    current_line_number);
1049	    status = 0;
1050	    break;
1051	}
1052	if (command->n_args != 3)
1053	{
1054	    warnx("ERROR line %d: incorrect number of geometry args",
1055		    current_line_number);
1056	    status = 0;
1057	    break;
1058	}
1059	dos_cyls = -1;
1060	dos_heads = -1;
1061	dos_sectors = -1;
1062	for (i = 0; i < 3; ++i)
1063	{
1064	    switch (command->args[i].argtype)
1065	    {
1066	    case 'c':
1067		dos_cyls = command->args[i].arg_val;
1068		break;
1069	    case 'h':
1070		dos_heads = command->args[i].arg_val;
1071		break;
1072	    case 's':
1073		dos_sectors = command->args[i].arg_val;
1074		break;
1075	    default:
1076		warnx(
1077		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1078			current_line_number, command->args[i].argtype,
1079			command->args[i].argtype);
1080		status = 0;
1081		break;
1082	    }
1083	}
1084	if (status == 0)
1085	{
1086	    break;
1087	}
1088
1089	dos_cylsecs = dos_heads * dos_sectors;
1090
1091	/*
1092	 * Do sanity checks on parameter values
1093	 */
1094	if (dos_cyls < 0)
1095	{
1096	    warnx("ERROR line %d: number of cylinders not specified",
1097		    current_line_number);
1098	    status = 0;
1099	}
1100	if (dos_cyls == 0 || dos_cyls > 1024)
1101	{
1102	    warnx(
1103	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1104    (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1105    is dedicated to FreeBSD)",
1106		    current_line_number, dos_cyls);
1107	}
1108
1109	if (dos_heads < 0)
1110	{
1111	    warnx("ERROR line %d: number of heads not specified",
1112		    current_line_number);
1113	    status = 0;
1114	}
1115	else if (dos_heads < 1 || dos_heads > 256)
1116	{
1117	    warnx("ERROR line %d: number of heads must be within (1-256)",
1118		    current_line_number);
1119	    status = 0;
1120	}
1121
1122	if (dos_sectors < 0)
1123	{
1124	    warnx("ERROR line %d: number of sectors not specified",
1125		    current_line_number);
1126	    status = 0;
1127	}
1128	else if (dos_sectors < 1 || dos_sectors > 63)
1129	{
1130	    warnx("ERROR line %d: number of sectors must be within (1-63)",
1131		    current_line_number);
1132	    status = 0;
1133	}
1134
1135	break;
1136    }
1137    return (status);
1138}
1139
1140
1141static int
1142process_partition(command)
1143    CMD		*command;
1144{
1145    int				status = 0, partition;
1146    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1147    u_int32_t			adj_size, max_end;
1148    struct dos_partition	*partp;
1149
1150    while (1)
1151    {
1152	part_processed = 1;
1153	if (command->n_args != 4)
1154	{
1155	    warnx("ERROR line %d: incorrect number of partition args",
1156		    current_line_number);
1157	    break;
1158	}
1159	partition = command->args[0].arg_val;
1160	if (partition < 1 || partition > 4)
1161	{
1162	    warnx("ERROR line %d: invalid partition number %d",
1163		    current_line_number, partition);
1164	    break;
1165	}
1166	partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1167	bzero((char *)partp, sizeof (struct dos_partition));
1168	partp->dp_typ = command->args[1].arg_val;
1169	partp->dp_start = command->args[2].arg_val;
1170	partp->dp_size = command->args[3].arg_val;
1171	max_end = partp->dp_start + partp->dp_size;
1172
1173	if (partp->dp_typ == 0)
1174	{
1175	    /*
1176	     * Get out, the partition is marked as unused.
1177	     */
1178	    /*
1179	     * Insure that it's unused.
1180	     */
1181	    bzero((char *)partp, sizeof (struct dos_partition));
1182	    status = 1;
1183	    break;
1184	}
1185
1186	/*
1187	 * Adjust start upwards, if necessary, to fall on an head boundary.
1188	 */
1189	if (partp->dp_start % dos_sectors != 0)
1190	{
1191	    prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1192	    if (max_end < dos_sectors ||
1193		prev_head_boundary > max_end - dos_sectors)
1194	    {
1195		/*
1196		 * Can't go past end of partition
1197		 */
1198		warnx(
1199	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
1200    a head boundary",
1201			current_line_number, partition);
1202		break;
1203	    }
1204	    warnx(
1205	"WARNING: adjusting start offset of partition %d\n\
1206    from %u to %u, to fall on a head boundary",
1207		    partition, (u_int)partp->dp_start,
1208		    (u_int)(prev_head_boundary + dos_sectors));
1209	    partp->dp_start = prev_head_boundary + dos_sectors;
1210	}
1211
1212	/*
1213	 * Adjust size downwards, if necessary, to fall on a cylinder
1214	 * boundary.
1215	 */
1216	prev_cyl_boundary =
1217	    ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1218	if (prev_cyl_boundary > partp->dp_start)
1219	    adj_size = prev_cyl_boundary - partp->dp_start;
1220	else
1221	{
1222	    warnx(
1223	"ERROR: could not adjust partition to start on a head boundary\n\
1224    and end on a cylinder boundary.");
1225	    return (0);
1226	}
1227	if (adj_size != partp->dp_size)
1228	{
1229	    warnx(
1230	"WARNING: adjusting size of partition %d from %u to %u\n\
1231    to end on a cylinder boundary",
1232		    partition, (u_int)partp->dp_size, (u_int)adj_size);
1233	    partp->dp_size = adj_size;
1234	}
1235	if (partp->dp_size == 0)
1236	{
1237	    warnx("ERROR line %d: size for partition %d is zero",
1238		    current_line_number, partition);
1239	    break;
1240	}
1241
1242	dos(partp->dp_start, partp->dp_size,
1243	    &partp->dp_scyl, &partp->dp_ssect, &partp->dp_shd);
1244	dos(partp->dp_start+partp->dp_size - 1, partp->dp_size,
1245	    &partp->dp_ecyl, &partp->dp_esect, &partp->dp_ehd);
1246	status = 1;
1247	break;
1248    }
1249    return (status);
1250}
1251
1252
1253static int
1254process_active(command)
1255    CMD		*command;
1256{
1257    int				status = 0, partition, i;
1258    struct dos_partition	*partp;
1259
1260    while (1)
1261    {
1262	active_processed = 1;
1263	if (command->n_args != 1)
1264	{
1265	    warnx("ERROR line %d: incorrect number of active args",
1266		    current_line_number);
1267	    status = 0;
1268	    break;
1269	}
1270	partition = command->args[0].arg_val;
1271	if (partition < 1 || partition > 4)
1272	{
1273	    warnx("ERROR line %d: invalid partition number %d",
1274		    current_line_number, partition);
1275	    break;
1276	}
1277	/*
1278	 * Reset active partition
1279	 */
1280	partp = ((struct dos_partition *) &mboot.parts);
1281	for (i = 0; i < NDOSPART; i++)
1282	    partp[i].dp_flag = 0;
1283	partp[partition-1].dp_flag = ACTIVE;
1284
1285	status = 1;
1286	break;
1287    }
1288    return (status);
1289}
1290
1291
1292static int
1293process_line(line)
1294    char	*line;
1295{
1296    CMD		command;
1297    int		status = 1;
1298
1299    while (1)
1300    {
1301	parse_config_line(line, &command);
1302	switch (command.cmd)
1303	{
1304	case 0:
1305	    /*
1306	     * Comment or blank line
1307	     */
1308	    break;
1309	case 'g':
1310	    /*
1311	     * Set geometry
1312	     */
1313	    status = process_geometry(&command);
1314	    break;
1315	case 'p':
1316	    status = process_partition(&command);
1317	    break;
1318	case 'a':
1319	    status = process_active(&command);
1320	    break;
1321	default:
1322	    status = 0;
1323	    break;
1324	}
1325	break;
1326    }
1327    return (status);
1328}
1329
1330
1331static int
1332read_config(config_file)
1333    char *config_file;
1334{
1335    FILE	*fp = NULL;
1336    int		status = 1;
1337    char	buf[1010];
1338
1339    while (1)	/* dirty trick used to insure one exit point for this
1340		   function */
1341    {
1342	if (strcmp(config_file, "-") != 0)
1343	{
1344	    /*
1345	     * We're not reading from stdin
1346	     */
1347	    if ((fp = fopen(config_file, "r")) == NULL)
1348	    {
1349		status = 0;
1350		break;
1351	    }
1352	}
1353	else
1354	{
1355	    fp = stdin;
1356	}
1357	current_line_number = 0;
1358	while (!feof(fp))
1359	{
1360	    if (fgets(buf, sizeof(buf), fp) == NULL)
1361	    {
1362		break;
1363	    }
1364	    ++current_line_number;
1365	    status = process_line(buf);
1366	    if (status == 0)
1367	    {
1368		break;
1369	    }
1370	}
1371	break;
1372    }
1373    if (fp)
1374    {
1375	/*
1376	 * It doesn't matter if we're reading from stdin, as we've reached EOF
1377	 */
1378	fclose(fp);
1379    }
1380    return (status);
1381}
1382
1383
1384static void
1385reset_boot(void)
1386{
1387    int				i;
1388    struct dos_partition	*partp;
1389
1390    init_boot();
1391    for (i = 0; i < 4; ++i)
1392    {
1393	partp = ((struct dos_partition *) &mboot.parts) + i;
1394	bzero((char *)partp, sizeof (struct dos_partition));
1395    }
1396}
1397
1398static int
1399sanitize_partition(partp)
1400    struct dos_partition	*partp;
1401{
1402    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1403    u_int32_t			adj_size, max_end;
1404
1405    max_end = partp->dp_start + partp->dp_size;
1406
1407    /*
1408     * Adjust start upwards, if necessary, to fall on an head boundary.
1409     */
1410    if (partp->dp_start % dos_sectors != 0) {
1411	prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1412	if (max_end < dos_sectors ||
1413	    prev_head_boundary > max_end - dos_sectors) {
1414	    /*
1415	     * Can't go past end of partition
1416	     */
1417	    warnx(
1418    "ERROR: unable to adjust start of partition to fall on a head boundary");
1419	    return (0);
1420        }
1421	warnx(
1422    "WARNING: adjusting start offset of partition\n\
1423    to %u to fall on a head boundary",
1424	    (u_int)(prev_head_boundary + dos_sectors));
1425	partp->dp_start = prev_head_boundary + dos_sectors;
1426    }
1427
1428    /*
1429     * Adjust size downwards, if necessary, to fall on a cylinder
1430     * boundary.
1431     */
1432    prev_cyl_boundary = ((partp->dp_start + partp->dp_size) / dos_cylsecs) *
1433	dos_cylsecs;
1434    if (prev_cyl_boundary > partp->dp_start)
1435	adj_size = prev_cyl_boundary - partp->dp_start;
1436    else
1437    {
1438	warnx("ERROR: could not adjust partition to start on a head boundary\n\
1439    and end on a cylinder boundary.");
1440	return (0);
1441    }
1442    if (adj_size != partp->dp_size) {
1443	warnx(
1444    "WARNING: adjusting size of partition to %u to end on a\n\
1445    cylinder boundary",
1446	    (u_int)adj_size);
1447	partp->dp_size = adj_size;
1448    }
1449    if (partp->dp_size == 0) {
1450	warnx("ERROR: size for partition is zero");
1451	return (0);
1452    }
1453
1454    return (1);
1455}
1456