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