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