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