1238384Sjkim/*
2280304Sjkim * Mach Operating System
3280304Sjkim * Copyright (c) 1992 Carnegie Mellon University
4280304Sjkim * All Rights Reserved.
5238384Sjkim *
6238384Sjkim * Permission to use, copy, modify and distribute this software and its
7238384Sjkim * documentation is hereby granted, provided that both the copyright
8238384Sjkim * notice and this permission notice appear in all copies of the
9238384Sjkim * software, derivative works or modified versions, and any portions
10238384Sjkim * thereof, and that both notices appear in supporting documentation.
11238384Sjkim *
12238384Sjkim * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
13238384Sjkim * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
14280304Sjkim * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
15238384Sjkim *
16238384Sjkim * Carnegie Mellon requests users of this software to return to
17238384Sjkim *
18238384Sjkim *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
19238384Sjkim *  School of Computer Science
20238384Sjkim *  Carnegie Mellon University
21238384Sjkim *  Pittsburgh PA 15213-3890
22238384Sjkim *
23238384Sjkim * any improvements or extensions that they make and grant Carnegie Mellon
24238384Sjkim * the rights to redistribute these changes.
25238384Sjkim */
26238384Sjkim
27238384Sjkim#include <sys/cdefs.h>
28238384Sjkim#include <sys/disk.h>
29238384Sjkim#include <sys/disklabel.h>
30238384Sjkim#include <sys/diskmbr.h>
31238384Sjkim#include <sys/endian.h>
32238384Sjkim#include <sys/param.h>
33238384Sjkim#include <sys/stat.h>
34238384Sjkim#include <sys/mount.h>
35238384Sjkim#include <ctype.h>
36238384Sjkim#include <fcntl.h>
37238384Sjkim#include <err.h>
38238384Sjkim#include <errno.h>
39238384Sjkim#include <libgeom.h>
40238384Sjkim#include <paths.h>
41238384Sjkim#include <regex.h>
42238384Sjkim#include <stdint.h>
43238384Sjkim#include <stdio.h>
44238384Sjkim#include <stdlib.h>
45238384Sjkim#include <string.h>
46238384Sjkim#include <unistd.h>
47238384Sjkim
48238384Sjkim#include "fdisk_mbr_enc.h"
49238384Sjkim
50238384Sjkimstatic int iotest;
51238384Sjkim
52238384Sjkim#define NO_DISK_SECTORS ((u_int32_t)-1)
53238384Sjkim#define NO_TRACK_CYLINDERS 1023
54238384Sjkim#define NO_TRACK_HEADS 255
55238384Sjkim#define NO_TRACK_SECTORS 63
56238384Sjkim#define LBUF 100
57238384Sjkimstatic char lbuf[LBUF];
58238384Sjkim
59238384Sjkim/*
60238384Sjkim *
61238384Sjkim * Ported to 386bsd by Julian Elischer  Thu Oct 15 20:26:46 PDT 1992
62238384Sjkim *
63238384Sjkim * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
64238384Sjkim *	Copyright (c) 1989	Robert. V. Baron
65238384Sjkim *	Created.
66280304Sjkim */
67238384Sjkim
68238384Sjkim#define Decimal(str, ans, tmp, maxval) if (decimal(str, &tmp, ans, maxval)) ans = tmp
69238384Sjkim
70238384Sjkim#define MAX_SEC_SIZE 65536	/* maximum sector size that is supported */
71238384Sjkim#define MIN_SEC_SIZE 512	/* the sector size to start sensing at */
72280304Sjkimstatic int secsize = 0;		/* the sensed sector size */
73280304Sjkim
74280304Sjkimstatic char *disk;
75280304Sjkim
76280304Sjkimstatic int cyls, sectors, heads, cylsecs;
77280304Sjkimstatic u_int32_t disksecs;
78280304Sjkim
79280304Sjkimstruct mboot {
80280304Sjkim	unsigned char *bootinst;  /* boot code */
81280304Sjkim	off_t bootinst_size;
82280304Sjkim	struct	dos_partition parts[NDOSPART];
83280304Sjkim};
84280304Sjkim
85280304Sjkimstatic struct mboot mboot;
86280304Sjkimstatic int fd;
87280304Sjkim
88280304Sjkim#define ACTIVE 0x80
89280304Sjkim
90280304Sjkimstatic uint dos_cyls;
91280304Sjkimstatic uint dos_heads;
92238384Sjkimstatic uint dos_sectors;
93238384Sjkimstatic uint dos_cylsecs;
94238384Sjkim
95238384Sjkim#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
96280304Sjkim#define DOSCYL(c)	(c & 0xff)
97280304Sjkim
98280304Sjkim#define MAX_ARGS	10
99238384Sjkim
100280304Sjkimstatic int	current_line_number;
101280304Sjkim
102280304Sjkimstatic int	geom_processed = 0;
103280304Sjkimstatic int	part_processed = 0;
104280304Sjkimstatic int	active_processed = 0;
105280304Sjkim
106280304Sjkimtypedef struct cmd {
107280304Sjkim    char		cmd;
108280304Sjkim    int			n_args;
109238384Sjkim    struct arg {
110238384Sjkim	char		argtype;
111280304Sjkim	unsigned long	arg_val;
112280304Sjkim	char *		arg_str;
113280304Sjkim    }			args[MAX_ARGS];
114280304Sjkim} CMD;
115280304Sjkim
116238384Sjkimstatic int B_flag  = 0;		/* replace boot code */
117280304Sjkimstatic int I_flag  = 0;		/* use entire disk for FreeBSD */
118280304Sjkimstatic int a_flag  = 0;		/* set active partition */
119238384Sjkimstatic char *b_flag = NULL;	/* path to boot code */
120280304Sjkimstatic int i_flag  = 0;		/* replace partition data */
121280304Sjkimstatic int q_flag  = 0;		/* Be quiet */
122280304Sjkimstatic int u_flag  = 0;		/* update partition data */
123280304Sjkimstatic int s_flag  = 0;		/* Print a summary and exit */
124280304Sjkimstatic int t_flag  = 0;		/* test only */
125280304Sjkimstatic char *f_flag = NULL;	/* Read config info from file */
126280304Sjkimstatic int v_flag  = 0;		/* Be verbose */
127280304Sjkimstatic int print_config_flag = 0;
128280304Sjkim
129280304Sjkim/*
130280304Sjkim * A list of partition types, probably outdated.
131280304Sjkim */
132280304Sjkimstatic const char *const part_types[256] = {
133280304Sjkim	[0x00] = "unused",
134280304Sjkim	[0x01] = "Primary DOS with 12 bit FAT",
135280304Sjkim	[0x02] = "XENIX / file system",
136280304Sjkim	[0x03] = "XENIX /usr file system",
137238384Sjkim	[0x04] = "Primary DOS with 16 bit FAT (< 32MB)",
138238384Sjkim	[0x05] = "Extended DOS",
139280304Sjkim	[0x06] = "Primary DOS, 16 bit FAT (>= 32MB)",
140280304Sjkim	[0x07] = "NTFS, OS/2 HPFS, QNX-2 (16 bit) or Advanced UNIX",
141280304Sjkim	[0x08] = "AIX file system or SplitDrive",
142238384Sjkim	[0x09] = "AIX boot partition or Coherent",
143280304Sjkim	[0x0A] = "OS/2 Boot Manager, OPUS or Coherent swap",
144280304Sjkim	[0x0B] = "DOS or Windows 95 with 32 bit FAT",
145280304Sjkim	[0x0C] = "DOS or Windows 95 with 32 bit FAT (LBA)",
146238384Sjkim	[0x0E] = "Primary 'big' DOS (>= 32MB, LBA)",
147280304Sjkim	[0x0F] = "Extended DOS (LBA)",
148280304Sjkim	[0x10] = "OPUS",
149280304Sjkim	[0x11] = "OS/2 BM: hidden DOS with 12-bit FAT",
150280304Sjkim	[0x12] = "Compaq diagnostics",
151280304Sjkim	[0x14] = "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)",
152238384Sjkim	[0x16] = "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)",
153238384Sjkim	[0x17] = "OS/2 BM: hidden IFS (e.g. HPFS)",
154238384Sjkim	[0x18] = "AST Windows swapfile",
155238384Sjkim	[0x1b] = "ASUS Recovery partition (NTFS)",
156280304Sjkim	[0x24] = "NEC DOS",
157280304Sjkim	[0x3C] = "PartitionMagic recovery",
158280304Sjkim	[0x39] = "plan9",
159238384Sjkim	[0x40] = "VENIX 286",
160238384Sjkim	[0x41] = "Linux/MINIX (sharing disk with DRDOS)",
161280304Sjkim	[0x42] = "SFS or Linux swap (sharing disk with DRDOS)",
162280304Sjkim	[0x43] = "Linux native (sharing disk with DRDOS)",
163280304Sjkim	[0x4D] = "QNX 4.2 Primary",
164238384Sjkim	[0x4E] = "QNX 4.2 Secondary",
165238384Sjkim	[0x4F] = "QNX 4.2 Tertiary",
166280304Sjkim	[0x50] = "DM (disk manager)",
167280304Sjkim	[0x51] = "DM6 Aux1 (or Novell)",
168280304Sjkim	[0x52] = "CP/M or Microport SysV/AT",
169280304Sjkim	[0x53] = "DM6 Aux3",
170280304Sjkim	[0x54] = "DM6",
171280304Sjkim	[0x55] = "EZ-Drive (disk manager)",
172280304Sjkim	[0x56] = "Golden Bow (disk manager)",
173280304Sjkim	[0x5c] = "Priam Edisk (disk manager)", /* according to S. Widlake */
174238384Sjkim	[0x61] = "SpeedStor",
175238384Sjkim	[0x63] = "System V/386 (such as ISC UNIX), GNU HURD or Mach",
176280304Sjkim	[0x64] = "Novell Netware/286 2.xx",
177280304Sjkim	[0x65] = "Novell Netware/386 3.xx",
178280304Sjkim	[0x6C] = "DragonFlyBSD",
179280304Sjkim	[0x70] = "DiskSecure Multi-Boot",
180280304Sjkim	[0x75] = "PCIX",
181280304Sjkim	[0x77] = "QNX4.x",
182280304Sjkim	[0x78] = "QNX4.x 2nd part",
183280304Sjkim	[0x79] = "QNX4.x 3rd part",
184280304Sjkim	[0x80] = "Minix until 1.4a",
185238384Sjkim	[0x81] = "Minix since 1.4b, early Linux partition or Mitac disk manager",
186280304Sjkim	[0x82] = "Linux swap or Solaris x86",
187238384Sjkim	[0x83] = "Linux native",
188280304Sjkim	[0x84] = "OS/2 hidden C: drive",
189280304Sjkim	[0x85] = "Linux extended",
190238384Sjkim	[0x86] = "NTFS volume set??",
191238384Sjkim	[0x87] = "NTFS volume set??",
192238384Sjkim	[0x93] = "Amoeba file system",
193238384Sjkim	[0x94] = "Amoeba bad block table",
194280304Sjkim	[0x9F] = "BSD/OS",
195280304Sjkim	[0xA0] = "Suspend to Disk",
196280304Sjkim	[0xA5] = "FreeBSD/NetBSD/386BSD",
197238384Sjkim	[0xA6] = "OpenBSD",
198280304Sjkim	[0xA7] = "NeXTSTEP",
199280304Sjkim	[0xA9] = "NetBSD",
200280304Sjkim	[0xAC] = "IBM JFS",
201280304Sjkim	[0xAF] = "HFS+",
202280304Sjkim	[0xB7] = "BSDI BSD/386 file system",
203280304Sjkim	[0xB8] = "BSDI BSD/386 swap",
204280304Sjkim	[0xBE] = "Solaris x86 boot",
205280304Sjkim	[0xBF] = "Solaris x86 (new)",
206238384Sjkim	[0xC1] = "DRDOS/sec with 12-bit FAT",
207280304Sjkim	[0xC4] = "DRDOS/sec with 16-bit FAT (< 32MB)",
208280304Sjkim	[0xC6] = "DRDOS/sec with 16-bit FAT (>= 32MB)",
209238384Sjkim	[0xC7] = "Syrinx",
210238384Sjkim	[0xDB] = "CP/M, Concurrent CP/M, Concurrent DOS or CTOS",
211280304Sjkim	[0xDE] = "DELL Utilities - FAT filesystem",
212280304Sjkim	[0xE1] = "DOS access or SpeedStor with 12-bit FAT extended partition",
213280304Sjkim	[0xE3] = "DOS R/O or SpeedStor",
214238384Sjkim	[0xE4] = "SpeedStor with 16-bit FAT extended partition < 1024 cyl.",
215280304Sjkim	[0xEB] = "BeOS file system",
216280304Sjkim	[0xEE] = "EFI GPT",
217280304Sjkim	[0xEF] = "EFI System Partition",
218238384Sjkim	[0xF1] = "SpeedStor",
219280304Sjkim	[0xF2] = "DOS 3.3+ Secondary",
220280304Sjkim	[0xF4] = "SpeedStor large partition",
221280304Sjkim	[0xFB] = "VMware VMFS",
222280304Sjkim	[0xFE] = "SpeedStor >1024 cyl. or LANstep",
223280304Sjkim	[0xFF] = "Xenix bad blocks table",
224280304Sjkim};
225280304Sjkim
226280304Sjkimstatic const char *
227280304Sjkimget_type(int t)
228238384Sjkim{
229280304Sjkim	const char *ret;
230280304Sjkim
231280304Sjkim	ret = (t >= 0 && t <= 255) ? part_types[t] : NULL;
232280304Sjkim	return ret ? ret : "unknown";
233280304Sjkim}
234280304Sjkim
235280304Sjkim
236280304Sjkimstatic int geom_class_available(const char *);
237238384Sjkimstatic void print_s0(void);
238238384Sjkimstatic void print_part(const struct dos_partition *);
239238384Sjkimstatic void init_sector0(unsigned long start);
240238384Sjkimstatic void init_boot(void);
241280304Sjkimstatic void change_part(int i);
242280304Sjkimstatic void print_params(void);
243280304Sjkimstatic void change_active(int which);
244280304Sjkimstatic void change_code(void);
245280304Sjkimstatic void get_params_to_use(void);
246280304Sjkimstatic char *get_rootdisk(void);
247280304Sjkimstatic void dos(struct dos_partition *partp);
248280304Sjkimstatic int open_disk(int flag);
249280304Sjkimstatic ssize_t read_disk(off_t sector, void *buf);
250280304Sjkimstatic int write_disk(off_t sector, void *buf);
251280304Sjkimstatic int get_params(void);
252280304Sjkimstatic int read_s0(void);
253280304Sjkimstatic int write_s0(void);
254280304Sjkimstatic int ok(const char *str);
255238384Sjkimstatic int decimal(const char *str, int *num, int deflt, uint32_t maxval);
256280304Sjkimstatic int read_config(char *config_file);
257238384Sjkimstatic void reset_boot(void);
258280304Sjkimstatic int sanitize_partition(struct dos_partition *);
259280304Sjkimstatic void usage(void) __dead2;
260280304Sjkim
261238384Sjkimint
262238384Sjkimmain(int argc, char *argv[])
263280304Sjkim{
264280304Sjkim	int	c, i;
265280304Sjkim	int	partition = -1;
266280304Sjkim	struct	dos_partition *partp;
267280304Sjkim
268280304Sjkim	while ((c = getopt(argc, argv, "BIab:f:ipqstuv1234")) != -1)
269280304Sjkim		switch (c) {
270280304Sjkim		case 'B':
271280304Sjkim			B_flag = 1;
272280304Sjkim			break;
273280304Sjkim		case 'I':
274280304Sjkim			I_flag = 1;
275280304Sjkim			break;
276238384Sjkim		case 'a':
277280304Sjkim			a_flag = 1;
278238384Sjkim			break;
279280304Sjkim		case 'b':
280280304Sjkim			b_flag = optarg;
281280304Sjkim			break;
282238384Sjkim		case 'f':
283238384Sjkim			f_flag = optarg;
284280304Sjkim			break;
285280304Sjkim		case 'i':
286280304Sjkim			i_flag = 1;
287280304Sjkim			break;
288280304Sjkim		case 'p':
289280304Sjkim			print_config_flag = 1;
290280304Sjkim			break;
291280304Sjkim		case 'q':
292280304Sjkim			q_flag = 1;
293280304Sjkim			break;
294280304Sjkim		case 's':
295280304Sjkim			s_flag = 1;
296280304Sjkim			break;
297280304Sjkim		case 't':
298280304Sjkim			t_flag = 1;
299238384Sjkim			break;
300280304Sjkim		case 'u':
301238384Sjkim			u_flag = 1;
302280304Sjkim			break;
303280304Sjkim		case 'v':
304280304Sjkim			v_flag = 1;
305238384Sjkim			break;
306238384Sjkim		case '1':
307280304Sjkim		case '2':
308280304Sjkim		case '3':
309280304Sjkim		case '4':
310280304Sjkim			partition = c - '0';
311280304Sjkim			break;
312280304Sjkim		default:
313280304Sjkim			usage();
314280304Sjkim		}
315280304Sjkim	if (f_flag || i_flag)
316280304Sjkim		u_flag = 1;
317280304Sjkim	if (t_flag)
318280304Sjkim		v_flag = 1;
319280304Sjkim	argc -= optind;
320280304Sjkim	argv += optind;
321280304Sjkim
322280304Sjkim	if (argc == 0) {
323238384Sjkim		disk = get_rootdisk();
324280304Sjkim	} else {
325238384Sjkim		disk = g_device_path(argv[0]);
326280304Sjkim		if (disk == NULL)
327280304Sjkim			err(1, "unable to get correct path for %s", argv[0]);
328280304Sjkim	}
329238384Sjkim	if (open_disk(u_flag) < 0)
330280304Sjkim		err(1, "cannot open disk %s", disk);
331280304Sjkim
332280304Sjkim	/* (abu)use mboot.bootinst to probe for the sector size */
333280304Sjkim	if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
334280304Sjkim		err(1, "cannot allocate buffer to determine disk sector size");
335280304Sjkim	if (read_disk(0, mboot.bootinst) == -1)
336280304Sjkim		errx(1, "could not detect sector size");
337280304Sjkim	free(mboot.bootinst);
338280304Sjkim	mboot.bootinst = NULL;
339280304Sjkim
340280304Sjkim	if (print_config_flag) {
341280304Sjkim		if (read_s0())
342280304Sjkim			err(1, "read_s0");
343280304Sjkim
344280304Sjkim		printf("# %s\n", disk);
345280304Sjkim		printf("g c%d h%d s%d\n", dos_cyls, dos_heads, dos_sectors);
346280304Sjkim
347280304Sjkim		for (i = 0; i < NDOSPART; i++) {
348280304Sjkim			partp = &mboot.parts[i];
349280304Sjkim
350280304Sjkim			if (partp->dp_start == 0 && partp->dp_size == 0)
351280304Sjkim				continue;
352280304Sjkim
353280304Sjkim			printf("p %d 0x%02x %lu %lu\n", i + 1, partp->dp_typ,
354238384Sjkim			    (u_long)partp->dp_start, (u_long)partp->dp_size);
355280304Sjkim
356238384Sjkim			/* Fill flags for the partition. */
357280304Sjkim			if (partp->dp_flag & 0x80)
358280304Sjkim				printf("a %d\n", i + 1);
359280304Sjkim		}
360238384Sjkim		exit(0);
361280304Sjkim	}
362280304Sjkim	if (s_flag) {
363280304Sjkim		if (read_s0())
364280304Sjkim			err(1, "read_s0");
365280304Sjkim		printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
366280304Sjkim		    dos_sectors);
367280304Sjkim		printf("Part  %11s %11s Type Flags\n", "Start", "Size");
368280304Sjkim		for (i = 0; i < NDOSPART; i++) {
369280304Sjkim			partp = &mboot.parts[i];
370280304Sjkim			if (partp->dp_start == 0 && partp->dp_size == 0)
371280304Sjkim				continue;
372280304Sjkim			printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
373280304Sjkim			    (u_long) partp->dp_start,
374280304Sjkim			    (u_long) partp->dp_size, partp->dp_typ,
375280304Sjkim			    partp->dp_flag);
376280304Sjkim		}
377280304Sjkim		exit(0);
378280304Sjkim	}
379280304Sjkim
380280304Sjkim	printf("******* Working on device %s *******\n",disk);
381280304Sjkim
382280304Sjkim	if (I_flag) {
383280304Sjkim		read_s0();
384280304Sjkim		reset_boot();
385280304Sjkim		partp = &mboot.parts[0];
386280304Sjkim		partp->dp_typ = DOSPTYP_386BSD;
387280304Sjkim		partp->dp_flag = ACTIVE;
388280304Sjkim		partp->dp_start = dos_sectors;
389280304Sjkim		partp->dp_size = rounddown(disksecs, dos_cylsecs) -
390238384Sjkim		    dos_sectors;
391280304Sjkim		dos(partp);
392238384Sjkim		if (v_flag)
393280304Sjkim			print_s0();
394280304Sjkim		if (!t_flag)
395280304Sjkim			write_s0();
396238384Sjkim		exit(0);
397238384Sjkim	}
398280304Sjkim	if (f_flag) {
399280304Sjkim	    if (read_s0() || i_flag)
400280304Sjkim		reset_boot();
401280304Sjkim	    if (!read_config(f_flag))
402280304Sjkim		exit(1);
403280304Sjkim	    if (v_flag)
404238384Sjkim		print_s0();
405280304Sjkim	    if (!t_flag)
406280304Sjkim		write_s0();
407280304Sjkim	} else {
408280304Sjkim	    if(u_flag)
409280304Sjkim		get_params_to_use();
410280304Sjkim	    else
411280304Sjkim		print_params();
412280304Sjkim
413280304Sjkim	    if (read_s0())
414280304Sjkim		init_sector0(dos_sectors);
415280304Sjkim
416280304Sjkim	    printf("Media sector size is %d\n", secsize);
417280304Sjkim	    printf("Warning: BIOS sector numbering starts with sector 1\n");
418280304Sjkim	    printf("Information from DOS bootblock is:\n");
419280304Sjkim	    if (partition == -1)
420280304Sjkim		for (i = 1; i <= NDOSPART; i++)
421280304Sjkim		    change_part(i);
422280304Sjkim	    else
423280304Sjkim		change_part(partition);
424280304Sjkim
425280304Sjkim	    if (u_flag || a_flag)
426280304Sjkim		change_active(partition);
427238384Sjkim
428280304Sjkim	    if (B_flag)
429238384Sjkim		change_code();
430280304Sjkim
431280304Sjkim	    if (u_flag || a_flag || B_flag) {
432280304Sjkim		if (!t_flag) {
433238384Sjkim		    printf("\nWe haven't changed the partition table yet.  ");
434238384Sjkim		    printf("This is your last chance.\n");
435280304Sjkim		}
436280304Sjkim		print_s0();
437280304Sjkim		if (!t_flag) {
438280304Sjkim		    if (ok("Should we write new partition table?"))
439238384Sjkim			write_s0();
440280304Sjkim		} else {
441280304Sjkim		    printf("\n-t flag specified -- partition table not written.\n");
442280304Sjkim		}
443280304Sjkim	    }
444280304Sjkim	}
445280304Sjkim
446280304Sjkim	exit(0);
447280304Sjkim}
448280304Sjkim
449280304Sjkimstatic void
450238384Sjkimusage(void)
451280304Sjkim{
452280304Sjkim	fprintf(stderr, "%s%s",
453280304Sjkim		"usage: fdisk [-BIaipqstu] [-b bootcode] [-1234] [disk]\n",
454280304Sjkim 		"       fdisk -f configfile [-itv] [disk]\n");
455238384Sjkim        exit(1);
456280304Sjkim}
457280304Sjkim
458238384Sjkimstatic void
459280304Sjkimprint_s0(void)
460280304Sjkim{
461280304Sjkim	int	i;
462280304Sjkim
463280304Sjkim	print_params();
464280304Sjkim	printf("Information from DOS bootblock is:\n");
465280304Sjkim	for (i = 1; i <= NDOSPART; i++) {
466280304Sjkim		printf("%d: ", i);
467280304Sjkim		print_part(&mboot.parts[i - 1]);
468280304Sjkim	}
469280304Sjkim}
470280304Sjkim
471280304Sjkimstatic struct dos_partition mtpart;
472238384Sjkim
473280304Sjkimstatic void
474280304Sjkimprint_part(const struct dos_partition *partp)
475238384Sjkim{
476238384Sjkim	u_int64_t part_mb;
477280304Sjkim
478280304Sjkim	if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
479280304Sjkim		printf("<UNUSED>\n");
480238384Sjkim		return;
481238384Sjkim	}
482280304Sjkim	/*
483280304Sjkim	 * Be careful not to overflow.
484280304Sjkim	 */
485238384Sjkim	part_mb = partp->dp_size;
486238384Sjkim	part_mb *= secsize;
487280304Sjkim	part_mb /= (1024 * 1024);
488280304Sjkim	printf("sysid %d (%#04x),(%s)\n", partp->dp_typ, partp->dp_typ,
489280304Sjkim	    get_type(partp->dp_typ));
490280304Sjkim	printf("    start %lu, size %lu (%ju Meg), flag %x%s\n",
491280304Sjkim		(u_long)partp->dp_start,
492		(u_long)partp->dp_size,
493		(uintmax_t)part_mb,
494		partp->dp_flag,
495		partp->dp_flag == ACTIVE ? " (active)" : "");
496	printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
497		,DPCYL(partp->dp_scyl, partp->dp_ssect)
498		,partp->dp_shd
499		,DPSECT(partp->dp_ssect)
500		,DPCYL(partp->dp_ecyl, partp->dp_esect)
501		,partp->dp_ehd
502		,DPSECT(partp->dp_esect));
503}
504
505
506static void
507init_boot(void)
508{
509	const char *fname;
510	int fdesc, n;
511	struct stat sb;
512
513	fname = b_flag ? b_flag : "/boot/mbr";
514	if ((fdesc = open(fname, O_RDONLY)) == -1 ||
515	    fstat(fdesc, &sb) == -1)
516		err(1, "%s", fname);
517	if (sb.st_size == 0)
518		errx(1, "%s is empty, must not be.", fname);
519	if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
520		errx(1, "%s: length must be a multiple of sector size", fname);
521	if (mboot.bootinst != NULL)
522		free(mboot.bootinst);
523	if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
524		errx(1, "%s: unable to allocate read buffer", fname);
525	if ((n = read(fdesc, mboot.bootinst, mboot.bootinst_size)) == -1 ||
526	    close(fdesc))
527		err(1, "%s", fname);
528	if (n != mboot.bootinst_size)
529		errx(1, "%s: short read", fname);
530}
531
532
533static void
534init_sector0(unsigned long start)
535{
536	struct dos_partition *partp = &mboot.parts[0];
537
538	init_boot();
539
540	partp->dp_typ = DOSPTYP_386BSD;
541	partp->dp_flag = ACTIVE;
542	start = roundup(start, dos_sectors);
543	if(start == 0)
544		start = dos_sectors;
545	partp->dp_start = start;
546	partp->dp_size = rounddown(disksecs, dos_cylsecs) - start;
547
548	dos(partp);
549}
550
551static void
552change_part(int i)
553{
554    struct dos_partition *partp = &mboot.parts[i - 1];
555
556    printf("The data for partition %d is:\n", i);
557    print_part(partp);
558
559    if (u_flag && ok("Do you want to change it?")) {
560	int tmp;
561
562	if (i_flag) {
563	    bzero(partp, sizeof (*partp));
564	    if (i == 1) {
565		init_sector0(1);
566		printf("\nThe static data for the slice 1 has been reinitialized to:\n");
567		print_part(partp);
568	    }
569	}
570
571	do {
572		Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp, 255);
573		Decimal("start", partp->dp_start, tmp, NO_DISK_SECTORS);
574		Decimal("size", partp->dp_size, tmp, NO_DISK_SECTORS);
575		if (!sanitize_partition(partp)) {
576			warnx("ERROR: failed to adjust; setting sysid to 0");
577			partp->dp_typ = 0;
578		}
579
580		if (ok("Explicitly specify beg/end address ?"))
581		{
582			int	tsec,tcyl,thd;
583			tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
584			thd = partp->dp_shd;
585			tsec = DPSECT(partp->dp_ssect);
586			Decimal("beginning cylinder", tcyl, tmp, NO_TRACK_CYLINDERS);
587			Decimal("beginning head", thd, tmp, NO_TRACK_HEADS);
588			Decimal("beginning sector", tsec, tmp, NO_TRACK_SECTORS);
589			partp->dp_scyl = DOSCYL(tcyl);
590			partp->dp_ssect = DOSSECT(tsec,tcyl);
591			partp->dp_shd = thd;
592
593			tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
594			thd = partp->dp_ehd;
595			tsec = DPSECT(partp->dp_esect);
596			Decimal("ending cylinder", tcyl, tmp, NO_TRACK_CYLINDERS);
597			Decimal("ending head", thd, tmp, NO_TRACK_HEADS);
598			Decimal("ending sector", tsec, tmp, NO_TRACK_SECTORS);
599			partp->dp_ecyl = DOSCYL(tcyl);
600			partp->dp_esect = DOSSECT(tsec,tcyl);
601			partp->dp_ehd = thd;
602		} else
603			dos(partp);
604
605		print_part(partp);
606	} while (!ok("Are we happy with this entry?"));
607    }
608}
609
610static void
611print_params(void)
612{
613	printf("parameters extracted from in-core disklabel are:\n");
614	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
615			,cyls,heads,sectors,cylsecs);
616	if (dos_cyls > 1023 || dos_heads > 255 || dos_sectors > 63)
617		printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
618	printf("parameters to be used for BIOS calculations are:\n");
619	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
620		,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
621}
622
623static void
624change_active(int which)
625{
626	struct dos_partition *partp = &mboot.parts[0];
627	int active, i, new, tmp;
628
629	active = -1;
630	for (i = 0; i < NDOSPART; i++) {
631		if ((partp[i].dp_flag & ACTIVE) == 0)
632			continue;
633		printf("Partition %d is marked active\n", i + 1);
634		if (active == -1)
635			active = i + 1;
636	}
637	if (a_flag && which != -1)
638		active = which;
639	else if (active == -1)
640		active = 1;
641
642	if (!ok("Do you want to change the active partition?"))
643		return;
644setactive:
645	do {
646		new = active;
647		Decimal("active partition", new, tmp, 0);
648		if (new < 1 || new > 4) {
649			printf("Active partition number must be in range 1-4."
650					"  Try again.\n");
651			goto setactive;
652		}
653		active = new;
654	} while (!ok("Are you happy with this choice"));
655	for (i = 0; i < NDOSPART; i++)
656		partp[i].dp_flag = 0;
657	if (active > 0 && active <= NDOSPART)
658		partp[active-1].dp_flag = ACTIVE;
659}
660
661static void
662change_code(void)
663{
664	if (ok("Do you want to change the boot code?"))
665		init_boot();
666}
667
668void
669get_params_to_use(void)
670{
671	int	tmp;
672	print_params();
673	if (ok("Do you want to change our idea of what BIOS thinks ?"))
674	{
675		do
676		{
677			Decimal("BIOS's idea of #cylinders", dos_cyls, tmp, 0);
678			Decimal("BIOS's idea of #heads", dos_heads, tmp, 0);
679			Decimal("BIOS's idea of #sectors", dos_sectors, tmp, 0);
680			dos_cylsecs = dos_heads * dos_sectors;
681			print_params();
682		}
683		while(!ok("Are you happy with this choice"));
684	}
685}
686
687
688/***********************************************\
689* Change real numbers into strange dos numbers	*
690\***********************************************/
691static void
692dos(struct dos_partition *partp)
693{
694	int cy, sec;
695	u_int32_t end;
696
697	if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) {
698		memcpy(partp, &mtpart, sizeof(*partp));
699		return;
700	}
701
702	/* Start c/h/s. */
703	partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors;
704	cy = partp->dp_start / dos_cylsecs;
705	sec = partp->dp_start % dos_sectors + 1;
706	partp->dp_scyl = DOSCYL(cy);
707	partp->dp_ssect = DOSSECT(sec, cy);
708
709	/* End c/h/s. */
710	end = partp->dp_start + partp->dp_size - 1;
711	partp->dp_ehd = end % dos_cylsecs / dos_sectors;
712	cy = end / dos_cylsecs;
713	sec = end % dos_sectors + 1;
714	partp->dp_ecyl = DOSCYL(cy);
715	partp->dp_esect = DOSSECT(sec, cy);
716}
717
718static int
719open_disk(int flag)
720{
721	int rwmode;
722
723	/* Write mode if one of these flags are set. */
724	rwmode = (a_flag || I_flag || B_flag || flag);
725	fd = g_open(disk, rwmode);
726	/* If the mode fails, try read-only if we didn't. */
727	if (fd == -1 && errno == EPERM && rwmode)
728		fd = g_open(disk, 0);
729	if (fd == -1 && errno == ENXIO)
730		return -2;
731	if (fd == -1) {
732		warnx("can't open device %s", disk);
733		return -1;
734	}
735	if (get_params() == -1) {
736		warnx("can't get disk parameters on %s", disk);
737		return -1;
738	}
739	return fd;
740}
741
742static ssize_t
743read_disk(off_t sector, void *buf)
744{
745
746	lseek(fd, (sector * 512), 0);
747	if (secsize == 0)
748		for (secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE;
749		     secsize *= 2) {
750			/* try the read */
751			int size = read(fd, buf, secsize);
752			if (size == secsize)
753				/* it worked so return */
754				return secsize;
755		}
756	else
757		return read(fd, buf, secsize);
758
759	/* we failed to read at any of the sizes */
760	return -1;
761}
762
763static int
764geom_class_available(const char *name)
765{
766	struct gclass *class;
767	struct gmesh mesh;
768	int error;
769
770	error = geom_gettree(&mesh);
771	if (error != 0)
772		errc(1, error, "Cannot get GEOM tree");
773
774	LIST_FOREACH(class, &mesh.lg_class, lg_class) {
775		if (strcmp(class->lg_name, name) == 0) {
776			geom_deletetree(&mesh);
777			return (1);
778		}
779	}
780
781	geom_deletetree(&mesh);
782
783	return (0);
784}
785
786static int
787write_disk(off_t sector, void *buf)
788{
789	ssize_t wr;
790
791	/*
792	 * Try to write MBR directly. This may help when disk
793	 * is not in use.
794	 * XXX: hardcoded sectorsize
795	 */
796	wr = pwrite(fd, buf, secsize, (sector * 512));
797	if (wr == secsize)
798		return (0);
799
800	if (geom_class_available("PART") != 0)
801		warnx("Failed to write MBR. Try to use gpart(8).");
802	else
803		warnx("Failed to write sector zero");
804	return(EINVAL);
805}
806
807static int
808get_params(void)
809{
810	int error;
811	u_int u;
812	off_t o;
813
814	error = ioctl(fd, DIOCGFWSECTORS, &u);
815	if (error == 0)
816		sectors = dos_sectors = u;
817	else
818		sectors = dos_sectors = 63;
819
820	error = ioctl(fd, DIOCGFWHEADS, &u);
821	if (error == 0)
822		heads = dos_heads = u;
823	else
824		heads = dos_heads = 255;
825
826	dos_cylsecs = cylsecs = heads * sectors;
827	disksecs = cyls * heads * sectors;
828
829	u = g_sectorsize(fd);
830	if (u <= 0)
831		return (-1);
832
833	o = g_mediasize(fd);
834	if (o < 0)
835		return (-1);
836	if (o / u <= NO_DISK_SECTORS)
837		disksecs = o / u;
838	else
839		disksecs = NO_DISK_SECTORS;
840	cyls = dos_cyls = o / (u * dos_heads * dos_sectors);
841
842	return (0);
843}
844
845static int
846read_s0(void)
847{
848	int i;
849
850	mboot.bootinst_size = secsize;
851	if (mboot.bootinst != NULL)
852		free(mboot.bootinst);
853	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
854		warnx("unable to allocate buffer to read fdisk "
855		      "partition table");
856		return -1;
857	}
858	if (read_disk(0, mboot.bootinst) == -1) {
859		warnx("can't read fdisk partition table");
860		return -1;
861	}
862	if (le16dec(&mboot.bootinst[DOSMAGICOFFSET]) != DOSMAGIC) {
863		warnx("invalid fdisk partition table found");
864		/* So should we initialize things */
865		return -1;
866	}
867	for (i = 0; i < NDOSPART; i++)
868		dos_partition_dec(
869		    &mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
870		    &mboot.parts[i]);
871	return 0;
872}
873
874static int
875write_s0(void)
876{
877	int	sector, i;
878
879	if (iotest) {
880		print_s0();
881		return 0;
882	}
883	for(i = 0; i < NDOSPART; i++)
884		dos_partition_enc(&mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
885		    &mboot.parts[i]);
886	le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC);
887	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
888		if (write_disk(sector,
889			       &mboot.bootinst[sector * secsize]) == -1) {
890			warn("can't write fdisk partition table");
891			return -1;
892		}
893	return(0);
894}
895
896
897static int
898ok(const char *str)
899{
900	printf("%s [n] ", str);
901	fflush(stdout);
902	if (fgets(lbuf, LBUF, stdin) == NULL)
903		exit(1);
904	lbuf[strlen(lbuf)-1] = 0;
905
906	if (*lbuf &&
907		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
908		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
909		return 1;
910	else
911		return 0;
912}
913
914static int
915decimal(const char *str, int *num, int deflt, uint32_t maxval)
916{
917	long long acc;
918	int c;
919	char *cp;
920
921	while (1) {
922		acc = 0;
923		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
924		fflush(stdout);
925		if (fgets(lbuf, LBUF, stdin) == NULL)
926			exit(1);
927		lbuf[strlen(lbuf)-1] = 0;
928
929		if (!*lbuf)
930			return 0;
931
932		cp = lbuf;
933		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
934		if (!c)
935			return 0;
936		while ((c = *cp++)) {
937			if (c <= '9' && c >= '0') {
938				if (acc <= maxval || maxval == 0)
939					acc = acc * 10 + c - '0';
940			} else
941				break;
942		}
943		if (c == ' ' || c == '\t')
944			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
945		if (!c) {
946			if (maxval > 0 && acc > maxval) {
947				acc = maxval;
948				printf("%s exceeds maximum value allowed for "
949				  "this field. The value has been reduced "
950				  "to %lld\n", lbuf, acc);
951			}
952			*num = acc;
953			return 1;
954		} else
955			printf("%s is an invalid decimal number.  Try again.\n",
956				lbuf);
957	}
958}
959
960
961static void
962parse_config_line(char *line, CMD *command)
963{
964    char	*cp, *end;
965
966    cp = line;
967    while (1) {
968	memset(command, 0, sizeof(*command));
969
970	while (isspace(*cp)) ++cp;
971	if (*cp == '\0' || *cp == '#')
972	    break;
973	command->cmd = *cp++;
974
975	/*
976	 * Parse args
977	 */
978	    while (1) {
979	    while (isspace(*cp)) ++cp;
980	    if (*cp == '\0')
981		break;		/* eol */
982	    if (*cp == '#')
983		break;		/* found comment */
984	    if (isalpha(*cp))
985		command->args[command->n_args].argtype = *cp++;
986	    end = NULL;
987	    command->args[command->n_args].arg_val = strtoul(cp, &end, 0);
988 	    if (cp == end || (!isspace(*end) && *end != '\0')) {
989 		char ch;
990 		end = cp;
991 		while (!isspace(*end) && *end != '\0') ++end;
992 		ch = *end; *end = '\0';
993 		command->args[command->n_args].arg_str = strdup(cp);
994 		*end = ch;
995 	    } else
996 		command->args[command->n_args].arg_str = NULL;
997	    cp = end;
998	    command->n_args++;
999	}
1000	break;
1001    }
1002}
1003
1004
1005static int
1006process_geometry(CMD *command)
1007{
1008    int		status = 1, i;
1009
1010    while (1) {
1011	geom_processed = 1;
1012	    if (part_processed) {
1013	    warnx(
1014	"ERROR line %d: the geometry specification line must occur before\n\
1015    all partition specifications",
1016		    current_line_number);
1017	    status = 0;
1018	    break;
1019	}
1020	    if (command->n_args != 3) {
1021	    warnx("ERROR line %d: incorrect number of geometry args",
1022		    current_line_number);
1023	    status = 0;
1024	    break;
1025	}
1026	    dos_cyls = 0;
1027	    dos_heads = 0;
1028	    dos_sectors = 0;
1029	    for (i = 0; i < 3; ++i) {
1030		    switch (command->args[i].argtype) {
1031	    case 'c':
1032		dos_cyls = command->args[i].arg_val;
1033		break;
1034	    case 'h':
1035		dos_heads = command->args[i].arg_val;
1036		break;
1037	    case 's':
1038		dos_sectors = command->args[i].arg_val;
1039		break;
1040	    default:
1041		warnx(
1042		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1043			current_line_number, command->args[i].argtype,
1044			command->args[i].argtype);
1045		status = 0;
1046		break;
1047	    }
1048	}
1049	if (status == 0)
1050	    break;
1051
1052	dos_cylsecs = dos_heads * dos_sectors;
1053
1054	/*
1055	 * Do sanity checks on parameter values
1056	 */
1057	    if (dos_cyls == 0) {
1058	    warnx("ERROR line %d: number of cylinders not specified",
1059		    current_line_number);
1060	    status = 0;
1061	}
1062	    if (dos_cyls > 1024) {
1063	    warnx(
1064	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1065    (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1066    is dedicated to FreeBSD)",
1067		    current_line_number, dos_cyls);
1068	}
1069
1070	    if (dos_heads == 0) {
1071	    warnx("ERROR line %d: number of heads not specified",
1072		    current_line_number);
1073	    status = 0;
1074	    } else if (dos_heads > 256) {
1075	    warnx("ERROR line %d: number of heads must be within (1-256)",
1076		    current_line_number);
1077	    status = 0;
1078	}
1079
1080	    if (dos_sectors == 0) {
1081	    warnx("ERROR line %d: number of sectors not specified",
1082		    current_line_number);
1083	    status = 0;
1084	    } else if (dos_sectors > 63) {
1085	    warnx("ERROR line %d: number of sectors must be within (1-63)",
1086		    current_line_number);
1087	    status = 0;
1088	}
1089
1090	break;
1091    }
1092    return (status);
1093}
1094
1095static u_int32_t
1096str2sectors(const char *str)
1097{
1098	char *end;
1099	unsigned long val;
1100
1101	val = strtoul(str, &end, 0);
1102	if (str == end || *end == '\0') {
1103		warnx("ERROR line %d: unexpected size: \'%s\'",
1104		    current_line_number, str);
1105		return NO_DISK_SECTORS;
1106	}
1107
1108	if (*end == 'K')
1109		val *= 1024UL / secsize;
1110	else if (*end == 'M')
1111		val *= 1024UL * 1024UL / secsize;
1112	else if (*end == 'G')
1113		val *= 1024UL * 1024UL * 1024UL / secsize;
1114	else {
1115		warnx("ERROR line %d: unexpected modifier: %c "
1116		    "(not K/M/G)", current_line_number, *end);
1117		return NO_DISK_SECTORS;
1118	}
1119
1120	return val;
1121}
1122
1123static int
1124process_partition(CMD *command)
1125{
1126    int				status = 0, partition;
1127    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1128    u_int32_t			adj_size, max_end;
1129    struct dos_partition	*partp;
1130
1131	while (1) {
1132	part_processed = 1;
1133		if (command->n_args != 4) {
1134	    warnx("ERROR line %d: incorrect number of partition args",
1135		    current_line_number);
1136	    break;
1137	}
1138	partition = command->args[0].arg_val;
1139		if (partition < 1 || partition > 4) {
1140	    warnx("ERROR line %d: invalid partition number %d",
1141		    current_line_number, partition);
1142	    break;
1143	}
1144	partp = &mboot.parts[partition - 1];
1145	bzero(partp, sizeof (*partp));
1146	partp->dp_typ = command->args[1].arg_val;
1147	if (command->args[2].arg_str != NULL) {
1148		if (strcmp(command->args[2].arg_str, "*") == 0) {
1149			int i;
1150			partp->dp_start = dos_sectors;
1151			for (i = 1; i < partition; i++) {
1152    				struct dos_partition *prev_partp;
1153				prev_partp = ((struct dos_partition *)
1154				    &mboot.parts) + i - 1;
1155				if (prev_partp->dp_typ != 0)
1156					partp->dp_start = prev_partp->dp_start +
1157					    prev_partp->dp_size;
1158			}
1159			if (partp->dp_start % dos_sectors != 0) {
1160				prev_head_boundary = rounddown(partp->dp_start,
1161				    dos_sectors);
1162		    		partp->dp_start = prev_head_boundary +
1163				    dos_sectors;
1164			}
1165		} else {
1166			partp->dp_start = str2sectors(command->args[2].arg_str);
1167			if (partp->dp_start == NO_DISK_SECTORS)
1168				break;
1169		}
1170	} else
1171		partp->dp_start = command->args[2].arg_val;
1172
1173	if (command->args[3].arg_str != NULL) {
1174		if (strcmp(command->args[3].arg_str, "*") == 0)
1175			partp->dp_size = rounddown(disksecs, dos_cylsecs) -
1176			    partp->dp_start;
1177		else {
1178			partp->dp_size = str2sectors(command->args[3].arg_str);
1179			if (partp->dp_size == NO_DISK_SECTORS)
1180				break;
1181		}
1182		prev_cyl_boundary = rounddown(partp->dp_start + partp->dp_size,
1183		    dos_cylsecs);
1184		if (prev_cyl_boundary > partp->dp_start)
1185			partp->dp_size = prev_cyl_boundary - partp->dp_start;
1186	} else
1187		partp->dp_size = command->args[3].arg_val;
1188
1189	max_end = partp->dp_start + partp->dp_size;
1190
1191	if (partp->dp_typ == 0) {
1192	    /*
1193	     * Get out, the partition is marked as unused.
1194	     */
1195	    /*
1196	     * Insure that it's unused.
1197	     */
1198	    bzero(partp, sizeof(*partp));
1199	    status = 1;
1200	    break;
1201	}
1202
1203	/*
1204	 * Adjust start upwards, if necessary, to fall on a head boundary.
1205	 */
1206		if (partp->dp_start % dos_sectors != 0) {
1207	    prev_head_boundary = rounddown(partp->dp_start, dos_sectors);
1208	    if (max_end < dos_sectors ||
1209			    prev_head_boundary > max_end - dos_sectors) {
1210		/*
1211		 * Can't go past end of partition
1212		 */
1213		warnx(
1214	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
1215    a head boundary",
1216			current_line_number, partition);
1217		break;
1218	    }
1219	    warnx(
1220	"WARNING: adjusting start offset of partition %d\n\
1221    from %u to %u, to fall on a head boundary",
1222		    partition, (u_int)partp->dp_start,
1223		    (u_int)(prev_head_boundary + dos_sectors));
1224	    partp->dp_start = prev_head_boundary + dos_sectors;
1225	}
1226
1227	/*
1228	 * Adjust size downwards, if necessary, to fall on a cylinder
1229	 * boundary.
1230	 */
1231	prev_cyl_boundary = rounddown(partp->dp_start + partp->dp_size,
1232	    dos_cylsecs);
1233	if (prev_cyl_boundary > partp->dp_start)
1234	    adj_size = prev_cyl_boundary - partp->dp_start;
1235		else {
1236	    warnx(
1237	"ERROR: could not adjust partition to start on a head boundary\n\
1238    and end on a cylinder boundary.");
1239	    return (0);
1240	}
1241		if (adj_size != partp->dp_size) {
1242	    warnx(
1243	"WARNING: adjusting size of partition %d from %u to %u\n\
1244    to end on a cylinder boundary",
1245		    partition, (u_int)partp->dp_size, (u_int)adj_size);
1246	    partp->dp_size = adj_size;
1247	}
1248		if (partp->dp_size == 0) {
1249	    warnx("ERROR line %d: size of partition %d is zero",
1250		    current_line_number, partition);
1251	    break;
1252	}
1253
1254	dos(partp);
1255	status = 1;
1256	break;
1257    }
1258    return (status);
1259}
1260
1261
1262static int
1263process_active(CMD *command)
1264{
1265    int				status = 0, partition, i;
1266    struct dos_partition	*partp;
1267
1268	while (1) {
1269	active_processed = 1;
1270		if (command->n_args != 1) {
1271	    warnx("ERROR line %d: incorrect number of active args",
1272		    current_line_number);
1273	    status = 0;
1274	    break;
1275	}
1276	partition = command->args[0].arg_val;
1277		if (partition < 1 || partition > 4) {
1278	    warnx("ERROR line %d: invalid partition number %d",
1279		    current_line_number, partition);
1280	    break;
1281	}
1282	/*
1283	 * Reset active partition
1284	 */
1285	partp = mboot.parts;
1286	for (i = 0; i < NDOSPART; i++)
1287	    partp[i].dp_flag = 0;
1288	partp[partition-1].dp_flag = ACTIVE;
1289
1290	status = 1;
1291	break;
1292    }
1293    return (status);
1294}
1295
1296
1297static int
1298process_line(char *line)
1299{
1300    CMD		command;
1301    int		status = 1;
1302
1303	while (1) {
1304	parse_config_line(line, &command);
1305		switch (command.cmd) {
1306	case 0:
1307	    /*
1308	     * Comment or blank line
1309	     */
1310	    break;
1311	case 'g':
1312	    /*
1313	     * Set geometry
1314	     */
1315	    status = process_geometry(&command);
1316	    break;
1317	case 'p':
1318	    status = process_partition(&command);
1319	    break;
1320	case 'a':
1321	    status = process_active(&command);
1322	    break;
1323	default:
1324	    status = 0;
1325	    break;
1326	}
1327	break;
1328    }
1329    return (status);
1330}
1331
1332
1333static int
1334read_config(char *config_file)
1335{
1336    FILE	*fp = NULL;
1337    int		status = 1;
1338    char	buf[1010];
1339
1340	while (1) {
1341		if (strcmp(config_file, "-") != 0) {
1342	    /*
1343	     * We're not reading from stdin
1344	     */
1345			if ((fp = fopen(config_file, "r")) == NULL) {
1346		status = 0;
1347		break;
1348	    }
1349		} else {
1350	    fp = stdin;
1351	}
1352	current_line_number = 0;
1353		while (!feof(fp)) {
1354	    if (fgets(buf, sizeof(buf), fp) == NULL)
1355		break;
1356	    ++current_line_number;
1357	    status = process_line(buf);
1358	    if (status == 0)
1359		break;
1360	    }
1361	break;
1362    }
1363	if (fp) {
1364	/*
1365	 * It doesn't matter if we're reading from stdin, as we've reached EOF
1366	 */
1367	fclose(fp);
1368    }
1369    return (status);
1370}
1371
1372
1373static void
1374reset_boot(void)
1375{
1376    int				i;
1377    struct dos_partition	*partp;
1378
1379    init_boot();
1380    for (i = 0; i < 4; ++i) {
1381	partp = &mboot.parts[i];
1382	bzero(partp, sizeof(*partp));
1383    }
1384}
1385
1386static int
1387sanitize_partition(struct dos_partition *partp)
1388{
1389    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1390    u_int32_t			max_end, size, start;
1391
1392    start = partp->dp_start;
1393    size = partp->dp_size;
1394    max_end = start + size;
1395    /* Only allow a zero size if the partition is being marked unused. */
1396    if (size == 0) {
1397	if (start == 0 && partp->dp_typ == 0)
1398	    return (1);
1399	warnx("ERROR: size of partition is zero");
1400	return (0);
1401    }
1402    /* Return if no adjustment is necessary. */
1403    if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0)
1404	return (1);
1405
1406    if (start == 0) {
1407	    warnx("WARNING: partition overlaps with partition table");
1408	    if (ok("Correct this automatically?"))
1409		    start = dos_sectors;
1410    }
1411    if (start % dos_sectors != 0)
1412	warnx("WARNING: partition does not start on a head boundary");
1413    if ((start  +size) % dos_sectors != 0)
1414	warnx("WARNING: partition does not end on a cylinder boundary");
1415    warnx("WARNING: this may confuse the BIOS or some operating systems");
1416    if (!ok("Correct this automatically?"))
1417	return (1);
1418
1419    /*
1420     * Adjust start upwards, if necessary, to fall on a head boundary.
1421     */
1422    if (start % dos_sectors != 0) {
1423	prev_head_boundary = rounddown(start, dos_sectors);
1424	if (max_end < dos_sectors ||
1425	    prev_head_boundary >= max_end - dos_sectors) {
1426	    /*
1427	     * Can't go past end of partition
1428	     */
1429	    warnx(
1430    "ERROR: unable to adjust start of partition to fall on a head boundary");
1431	    return (0);
1432        }
1433	start = prev_head_boundary + dos_sectors;
1434    }
1435
1436    /*
1437     * Adjust size downwards, if necessary, to fall on a cylinder
1438     * boundary.
1439     */
1440    prev_cyl_boundary = rounddown(start + size, dos_cylsecs);
1441    if (prev_cyl_boundary > start)
1442	size = prev_cyl_boundary - start;
1443    else {
1444	warnx("ERROR: could not adjust partition to start on a head boundary\n\
1445    and end on a cylinder boundary.");
1446	return (0);
1447    }
1448
1449    /* Finally, commit any changes to partp and return. */
1450    if (start != partp->dp_start) {
1451	warnx("WARNING: adjusting start offset of partition to %u",
1452	    (u_int)start);
1453	partp->dp_start = start;
1454    }
1455    if (size != partp->dp_size) {
1456	warnx("WARNING: adjusting size of partition to %u", (u_int)size);
1457	partp->dp_size = size;
1458    }
1459
1460    return (1);
1461}
1462
1463/*
1464 * Try figuring out the root device's canonical disk name.
1465 * The following choices are considered:
1466 *   /dev/ad0s1a     => /dev/ad0
1467 *   /dev/da0a       => /dev/da0
1468 *   /dev/vinum/root => /dev/vinum/root
1469 * A ".eli" part is removed if it exists (see geli(8)).
1470 * A ".journal" ending is removed if it exists (see gjournal(8)).
1471 */
1472static char *
1473get_rootdisk(void)
1474{
1475	struct statfs rootfs;
1476	regex_t re;
1477#define NMATCHES 2
1478	regmatch_t rm[NMATCHES];
1479	char dev[PATH_MAX], *s;
1480	int rv;
1481
1482	if (statfs("/", &rootfs) == -1)
1483		err(1, "statfs(\"/\")");
1484
1485	if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]*)([sp][0-9]+)?[a-h]?(\\.journal)?$",
1486		    REG_EXTENDED)) != 0)
1487		errx(1, "regcomp() failed (%d)", rv);
1488	strlcpy(dev, rootfs.f_mntfromname, sizeof (dev));
1489	if ((s = strstr(dev, ".eli")) != NULL)
1490	    memmove(s, s+4, strlen(s + 4) + 1);
1491
1492	if ((rv = regexec(&re, dev, NMATCHES, rm, 0)) != 0)
1493		errx(1,
1494"mounted root fs resource doesn't match expectations (regexec returned %d)",
1495		    rv);
1496	if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL)
1497		errx(1, "out of memory");
1498	memcpy(s, rootfs.f_mntfromname + rm[1].rm_so,
1499	    rm[1].rm_eo - rm[1].rm_so);
1500	s[rm[1].rm_eo - rm[1].rm_so] = 0;
1501
1502	return s;
1503}
1504