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