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