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