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