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