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