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