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