fdisk.c revision 187239
18871Srgrimes/*
24Srgrimes * Mach Operating System
34Srgrimes * Copyright (c) 1992 Carnegie Mellon University
44Srgrimes * All Rights Reserved.
58871Srgrimes *
64Srgrimes * Permission to use, copy, modify and distribute this software and its
74Srgrimes * documentation is hereby granted, provided that both the copyright
84Srgrimes * notice and this permission notice appear in all copies of the
94Srgrimes * software, derivative works or modified versions, and any portions
104Srgrimes * thereof, and that both notices appear in supporting documentation.
118871Srgrimes *
124Srgrimes * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
134Srgrimes * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
144Srgrimes * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
158871Srgrimes *
164Srgrimes * Carnegie Mellon requests users of this software to return to
178871Srgrimes *
184Srgrimes *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
194Srgrimes *  School of Computer Science
204Srgrimes *  Carnegie Mellon University
214Srgrimes *  Pittsburgh PA 15213-3890
228871Srgrimes *
234Srgrimes * any improvements or extensions that they make and grant Carnegie Mellon
244Srgrimes * the rights to redistribute these changes.
254Srgrimes */
264Srgrimes
27114589Sobrien#include <sys/cdefs.h>
28114589Sobrien__FBSDID("$FreeBSD: head/sbin/fdisk/fdisk.c 187239 2009-01-14 20:53:46Z luigi $");
2937415Scharnier
30103348Sphk#include <sys/disk.h>
314Srgrimes#include <sys/disklabel.h>
32104272Sphk#include <sys/diskmbr.h>
33113454Sphk#include <sys/endian.h>
3479681Sjoerg#include <sys/param.h>
3537415Scharnier#include <sys/stat.h>
3679681Sjoerg#include <sys/mount.h>
3737415Scharnier#include <ctype.h>
3837415Scharnier#include <fcntl.h>
3937415Scharnier#include <err.h>
4037415Scharnier#include <errno.h>
41148035Sphk#include <libgeom.h>
4279681Sjoerg#include <paths.h>
4379681Sjoerg#include <regex.h>
44100202Sbde#include <stdint.h>
454Srgrimes#include <stdio.h>
4637415Scharnier#include <stdlib.h>
4716561Salex#include <string.h>
4816561Salex#include <unistd.h>
494Srgrimes
504Srgrimesint iotest;
514Srgrimes
524Srgrimes#define LBUF 100
534Srgrimesstatic char lbuf[LBUF];
544Srgrimes
554Srgrimes/*
564Srgrimes *
574Srgrimes * Ported to 386bsd by Julian Elischer  Thu Oct 15 20:26:46 PDT 1992
584Srgrimes *
594Srgrimes * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
604Srgrimes *	Copyright (c) 1989	Robert. V. Baron
614Srgrimes *	Created.
624Srgrimes */
634Srgrimes
644Srgrimes#define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp
654Srgrimes
664Srgrimes#define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs)
674Srgrimes
6820061Ssos#define MAX_SEC_SIZE 2048	/* maximum section size that is supported */
6920061Ssos#define MIN_SEC_SIZE 512	/* the sector size to start sensing at */
7093394Sphkstatic int secsize = 0;		/* the sensed sector size */
714Srgrimes
7293394Sphkstatic char *disk;
7310514Sjoerg
7493394Sphkstatic int cyls, sectors, heads, cylsecs, disksecs;
754Srgrimes
7693394Sphkstruct mboot {
77145763Snyan	unsigned char *bootinst;  /* boot code */
78145763Snyan	off_t bootinst_size;
79113454Sphk	struct	dos_partition parts[NDOSPART];
804Srgrimes};
814Srgrimes
8293394Sphkstatic struct mboot mboot;
83148035Sphkstatic int fd;
8493394Sphk
854Srgrimes#define ACTIVE 0x80
864Srgrimes
8793394Sphkstatic uint dos_cyls;
8893394Sphkstatic uint dos_heads;
8993394Sphkstatic uint dos_sectors;
9093394Sphkstatic uint dos_cylsecs;
914Srgrimes
924Srgrimes#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
934Srgrimes#define DOSCYL(c)	(c & 0xff)
944Srgrimes
9519459Sjkh#define MAX_ARGS	10
9619459Sjkh
9719459Sjkhstatic int	current_line_number;
9819459Sjkh
9919459Sjkhstatic int	geom_processed = 0;
10019459Sjkhstatic int	part_processed = 0;
10119459Sjkhstatic int	active_processed = 0;
10219459Sjkh
10319459Sjkhtypedef struct cmd {
10419459Sjkh    char		cmd;
10519459Sjkh    int			n_args;
10619459Sjkh    struct arg {
10719459Sjkh	char	argtype;
10819459Sjkh	int	arg_val;
10919459Sjkh    }			args[MAX_ARGS];
11019459Sjkh} CMD;
11119459Sjkh
11248282Srnordierstatic int B_flag  = 0;		/* replace boot code */
11357896Simpstatic int I_flag  = 0;		/* use entire disk for FreeBSD */
1144Srgrimesstatic int a_flag  = 0;		/* set active partition */
11548282Srnordierstatic char *b_flag = NULL;	/* path to boot code */
1164Srgrimesstatic int i_flag  = 0;		/* replace partition data */
117181036Sobrienstatic int q_flag  = 0;		/* Be quiet */
1184Srgrimesstatic int u_flag  = 0;		/* update partition data */
11957896Simpstatic int s_flag  = 0;		/* Print a summary and exit */
12095002Strhodesstatic int t_flag  = 0;		/* test only */
12119459Sjkhstatic char *f_flag = NULL;	/* Read config info from file */
12219459Sjkhstatic int v_flag  = 0;		/* Be verbose */
123169143Smaximstatic int print_config_flag = 0;
1244Srgrimes
12593394Sphkstatic struct part_type
1264Srgrimes{
127145763Snyan	unsigned char type;
12893394Sphk	const char *name;
12993394Sphk} part_types[] = {
1308871Srgrimes	 {0x00, "unused"}
1318871Srgrimes	,{0x01, "Primary DOS with 12 bit FAT"}
132102231Strhodes	,{0x02, "XENIX / file system"}
133102231Strhodes	,{0x03, "XENIX /usr file system"}
13490866Sjoe	,{0x04, "Primary DOS with 16 bit FAT (< 32MB)"}
1358871Srgrimes	,{0x05, "Extended DOS"}
13690866Sjoe	,{0x06, "Primary 'big' DOS (>= 32MB)"}
13761461Sghelmer	,{0x07, "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX"}
138102231Strhodes	,{0x08, "AIX file system or SplitDrive"}
1398871Srgrimes	,{0x09, "AIX boot partition or Coherent"}
14090866Sjoe	,{0x0A, "OS/2 Boot Manager, OPUS or Coherent swap"}
14134582Sache	,{0x0B, "DOS or Windows 95 with 32 bit FAT"}
14290866Sjoe	,{0x0C, "DOS or Windows 95 with 32 bit FAT (LBA)"}
14390866Sjoe	,{0x0E, "Primary 'big' DOS (>= 32MB, LBA)"}
14490866Sjoe	,{0x0F, "Extended DOS (LBA)"}
1458871Srgrimes	,{0x10, "OPUS"}
14690866Sjoe	,{0x11, "OS/2 BM: hidden DOS with 12-bit FAT"}
14790866Sjoe	,{0x12, "Compaq diagnostics"}
14890866Sjoe	,{0x14, "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)"}
14990866Sjoe	,{0x16, "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)"}
15090866Sjoe	,{0x17, "OS/2 BM: hidden IFS (e.g. HPFS)"}
15190866Sjoe	,{0x18, "AST Windows swapfile"}
15290866Sjoe	,{0x24, "NEC DOS"}
15390866Sjoe	,{0x3C, "PartitionMagic recovery"}
15461568Sbrian	,{0x39, "plan9"}
1558871Srgrimes	,{0x40, "VENIX 286"}
15690866Sjoe	,{0x41, "Linux/MINIX (sharing disk with DRDOS)"}
15790866Sjoe	,{0x42, "SFS or Linux swap (sharing disk with DRDOS)"}
15890866Sjoe	,{0x43, "Linux native (sharing disk with DRDOS)"}
15961461Sghelmer	,{0x4D, "QNX 4.2 Primary"}
16061461Sghelmer	,{0x4E, "QNX 4.2 Secondary"}
16161461Sghelmer	,{0x4F, "QNX 4.2 Tertiary"}
16290866Sjoe	,{0x50, "DM (disk manager)"}
16390866Sjoe	,{0x51, "DM6 Aux1 (or Novell)"}
1648871Srgrimes	,{0x52, "CP/M or Microport SysV/AT"}
16590866Sjoe	,{0x53, "DM6 Aux3"}
16690866Sjoe	,{0x54, "DM6"}
16790866Sjoe	,{0x55, "EZ-Drive (disk manager)"}
16890866Sjoe	,{0x56, "Golden Bow (disk manager)"}
16990866Sjoe	,{0x5c, "Priam Edisk (disk manager)"} /* according to S. Widlake */
17090866Sjoe	,{0x61, "SpeedStor"}
17190866Sjoe	,{0x63, "System V/386 (such as ISC UNIX), GNU HURD or Mach"}
17290866Sjoe	,{0x64, "Novell Netware/286 2.xx"}
17390866Sjoe	,{0x65, "Novell Netware/386 3.xx"}
17490866Sjoe	,{0x70, "DiskSecure Multi-Boot"}
1758871Srgrimes	,{0x75, "PCIX"}
17690866Sjoe	,{0x77, "QNX4.x"}
17790866Sjoe	,{0x78, "QNX4.x 2nd part"}
17890866Sjoe	,{0x79, "QNX4.x 3rd part"}
17990866Sjoe	,{0x80, "Minix until 1.4a"}
18093394Sphk	,{0x81, "Minix since 1.4b, early Linux partition or Mitac disk manager"}
18139377Sobrien	,{0x82, "Linux swap or Solaris x86"}
18290866Sjoe	,{0x83, "Linux native"}
18390866Sjoe	,{0x84, "OS/2 hidden C: drive"}
18490866Sjoe	,{0x85, "Linux extended"}
18590866Sjoe	,{0x86, "NTFS volume set??"}
18690866Sjoe	,{0x87, "NTFS volume set??"}
187102231Strhodes	,{0x93, "Amoeba file system"}
1888871Srgrimes	,{0x94, "Amoeba bad block table"}
18940946Sjkoshy	,{0x9F, "BSD/OS"}
19064316Sjoe	,{0xA0, "Suspend to Disk"}
1918871Srgrimes	,{0xA5, "FreeBSD/NetBSD/386BSD"}
19225378Simp	,{0xA6, "OpenBSD"}
19390866Sjoe	,{0xA7, "NeXTSTEP"}
19440947Salex	,{0xA9, "NetBSD"}
19595602Sgrog	,{0xAC, "IBM JFS"}
196169324Sandre	,{0xAF, "HFS+"}
197102231Strhodes	,{0xB7, "BSDI BSD/386 file system"}
1988871Srgrimes	,{0xB8, "BSDI BSD/386 swap"}
199123637Sharti	,{0xBE, "Solaris x86 boot"}
200137511Sphk	,{0xBF, "Solaris x86 (new)"}
20190866Sjoe	,{0xC1, "DRDOS/sec with 12-bit FAT"}
20290866Sjoe	,{0xC4, "DRDOS/sec with 16-bit FAT (< 32MB)"}
20390866Sjoe	,{0xC6, "DRDOS/sec with 16-bit FAT (>= 32MB)"}
20490866Sjoe	,{0xC7, "Syrinx"}
20590866Sjoe	,{0xDB, "CP/M, Concurrent CP/M, Concurrent DOS or CTOS"}
20690866Sjoe	,{0xE1, "DOS access or SpeedStor with 12-bit FAT extended partition"}
20790866Sjoe	,{0xE3, "DOS R/O or SpeedStor"}
20890866Sjoe	,{0xE4, "SpeedStor with 16-bit FAT extended partition < 1024 cyl."}
209102231Strhodes	,{0xEB, "BeOS file system"}
21084964Speter	,{0xEE, "EFI GPT"}
21185027Sbde	,{0xEF, "EFI System Partition"}
21290866Sjoe	,{0xF1, "SpeedStor"}
2138871Srgrimes	,{0xF2, "DOS 3.3+ Secondary"}
21490866Sjoe	,{0xF4, "SpeedStor large partition"}
21590866Sjoe	,{0xFE, "SpeedStor >1024 cyl. or LANstep"}
21690866Sjoe	,{0xFF, "Xenix bad blocks table"}
2174Srgrimes};
2184Srgrimes
219187239Sluigistatic void print_s0(void);
22016561Salexstatic void print_part(int i);
22116561Salexstatic void init_sector0(unsigned long start);
22219459Sjkhstatic void init_boot(void);
22316561Salexstatic void change_part(int i);
22493394Sphkstatic void print_params(void);
22516561Salexstatic void change_active(int which);
22693394Sphkstatic void change_code(void);
22793394Sphkstatic void get_params_to_use(void);
22879681Sjoergstatic char *get_rootdisk(void);
22981164Siedowsestatic void dos(struct dos_partition *partp);
23093394Sphkstatic int open_disk(int flag);
23116561Salexstatic ssize_t read_disk(off_t sector, void *buf);
232148035Sphkstatic int write_disk(off_t sector, void *buf);
23393394Sphkstatic int get_params(void);
23493394Sphkstatic int read_s0(void);
23593394Sphkstatic int write_s0(void);
23693394Sphkstatic int ok(const char *str);
23793394Sphkstatic int decimal(const char *str, int *num, int deflt);
23893394Sphkstatic const char *get_type(int type);
23919459Sjkhstatic int read_config(char *config_file);
24019459Sjkhstatic void reset_boot(void);
24165054Sjhbstatic int sanitize_partition(struct dos_partition *);
24237415Scharnierstatic void usage(void);
2434Srgrimes
24416561Salexint
24516561Salexmain(int argc, char *argv[])
2464Srgrimes{
24748282Srnordier	int	c, i;
24893394Sphk	int	partition = -1;
24993394Sphk	struct	dos_partition *partp;
2504Srgrimes
251181036Sobrien	while ((c = getopt(argc, argv, "BIab:f:ipqstuv1234")) != -1)
25248282Srnordier		switch (c) {
25348282Srnordier		case 'B':
25448282Srnordier			B_flag = 1;
2554Srgrimes			break;
25657896Simp		case 'I':
25757896Simp			I_flag = 1;
25857896Simp			break;
25948282Srnordier		case 'a':
26048282Srnordier			a_flag = 1;
26148282Srnordier			break;
26248282Srnordier		case 'b':
26348282Srnordier			b_flag = optarg;
26448282Srnordier			break;
26548282Srnordier		case 'f':
26648282Srnordier			f_flag = optarg;
26748282Srnordier			break;
26848282Srnordier		case 'i':
26948282Srnordier			i_flag = 1;
27048282Srnordier			break;
271169143Smaxim		case 'p':
272169143Smaxim			print_config_flag = 1;
273169143Smaxim			break;
274181036Sobrien		case 'q':
275181036Sobrien			q_flag = 1;
276181036Sobrien			break;
27757896Simp		case 's':
27857896Simp			s_flag = 1;
27957896Simp			break;
28048282Srnordier		case 't':
28148282Srnordier			t_flag = 1;
28248282Srnordier			break;
28348282Srnordier		case 'u':
28448282Srnordier			u_flag = 1;
28548282Srnordier			break;
28648282Srnordier		case 'v':
28748282Srnordier			v_flag = 1;
28848282Srnordier			break;
28948282Srnordier		case '1':
29048282Srnordier		case '2':
29148282Srnordier		case '3':
29248282Srnordier		case '4':
29348282Srnordier			partition = c - '0';
29448282Srnordier			break;
29548282Srnordier		default:
29648282Srnordier			usage();
2974Srgrimes		}
29848282Srnordier	if (f_flag || i_flag)
29948282Srnordier		u_flag = 1;
30048282Srnordier	if (t_flag)
30148282Srnordier		v_flag = 1;
30248282Srnordier	argc -= optind;
30348282Srnordier	argv += optind;
3044Srgrimes
30579681Sjoerg	if (argc == 0) {
30679681Sjoerg		disk = get_rootdisk();
30779681Sjoerg	} else {
308182844Slulf		disk = g_device_path(argv[0]);
309182844Slulf		if (disk == NULL)
310187203Sluigi			err(1, "unable to get correct path for %s", argv[0]);
31110514Sjoerg	}
31279681Sjoerg	if (open_disk(u_flag) < 0)
31379681Sjoerg		err(1, "cannot open disk %s", disk);
3144Srgrimes
31563027Sjhb	/* (abu)use mboot.bootinst to probe for the sector size */
31663027Sjhb	if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
31763027Sjhb		err(1, "cannot allocate buffer to determine disk sector size");
318159757Ssimon	if (read_disk(0, mboot.bootinst) == -1)
319159757Ssimon		errx(1, "could not detect sector size");
32063329Sjhb	free(mboot.bootinst);
32163329Sjhb	mboot.bootinst = NULL;
32263027Sjhb
323169143Smaxim	if (print_config_flag) {
324169143Smaxim		if (read_s0())
325169143Smaxim			err(1, "read_s0");
326169143Smaxim
327169143Smaxim		printf("# %s\n", disk);
328169143Smaxim		printf("g c%d h%d s%d\n", dos_cyls, dos_heads, dos_sectors);
329169143Smaxim
330169143Smaxim		for (i = 0; i < NDOSPART; i++) {
331187203Sluigi			partp = &mboot.parts[i];
332169143Smaxim
333169143Smaxim			if (partp->dp_start == 0 && partp->dp_size == 0)
334169143Smaxim				continue;
335169143Smaxim
336169143Smaxim			printf("p %d 0x%02x %lu %lu\n", i + 1, partp->dp_typ,
337169143Smaxim			    (u_long)partp->dp_start, (u_long)partp->dp_size);
338169143Smaxim
339169143Smaxim			/* Fill flags for the partition. */
340169143Smaxim			if (partp->dp_flag & 0x80)
341169143Smaxim				printf("a %d\n", i + 1);
342169143Smaxim		}
343169143Smaxim		exit(0);
344169143Smaxim	}
34593394Sphk	if (s_flag) {
34657896Simp		if (read_s0())
34757896Simp			err(1, "read_s0");
34857896Simp		printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
34957896Simp		    dos_sectors);
35057896Simp		printf("Part  %11s %11s Type Flags\n", "Start", "Size");
35157896Simp		for (i = 0; i < NDOSPART; i++) {
352187203Sluigi			partp = &mboot.parts[i];
35357896Simp			if (partp->dp_start == 0 && partp->dp_size == 0)
35457896Simp				continue;
35557896Simp			printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
35657896Simp			    (u_long) partp->dp_start,
35757896Simp			    (u_long) partp->dp_size, partp->dp_typ,
35857896Simp			    partp->dp_flag);
35957896Simp		}
36057896Simp		exit(0);
36157896Simp	}
36257896Simp
3634Srgrimes	printf("******* Working on device %s *******\n",disk);
36419459Sjkh
36593394Sphk	if (I_flag) {
36650215Sphk		read_s0();
36750215Sphk		reset_boot();
368187203Sluigi		partp = &mboot.parts[0];
36950215Sphk		partp->dp_typ = DOSPTYP_386BSD;
37050215Sphk		partp->dp_flag = ACTIVE;
37150215Sphk		partp->dp_start = dos_sectors;
37265054Sjhb		partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs -
37365054Sjhb		    dos_sectors;
37481164Siedowse		dos(partp);
37550215Sphk		if (v_flag)
376187239Sluigi			print_s0();
37795002Strhodes		if (!t_flag)
37895002Strhodes			write_s0();
37950215Sphk		exit(0);
38050215Sphk	}
38193394Sphk	if (f_flag) {
38219459Sjkh	    if (read_s0() || i_flag)
38319459Sjkh		reset_boot();
38419459Sjkh	    if (!read_config(f_flag))
38519459Sjkh		exit(1);
38619459Sjkh	    if (v_flag)
387187239Sluigi		print_s0();
38819459Sjkh	    if (!t_flag)
38919459Sjkh		write_s0();
39093394Sphk	} else {
39119459Sjkh	    if(u_flag)
39219459Sjkh		get_params_to_use();
39319459Sjkh	    else
3944Srgrimes		print_params();
3954Srgrimes
39619459Sjkh	    if (read_s0())
39765054Sjhb		init_sector0(dos_sectors);
3984Srgrimes
39920061Ssos	    printf("Media sector size is %d\n", secsize);
40019459Sjkh	    printf("Warning: BIOS sector numbering starts with sector 1\n");
40119459Sjkh	    printf("Information from DOS bootblock is:\n");
40219459Sjkh	    if (partition == -1)
40326421Sbrian		for (i = 1; i <= NDOSPART; i++)
40419459Sjkh		    change_part(i);
40519459Sjkh	    else
4064Srgrimes		change_part(partition);
4074Srgrimes
40819459Sjkh	    if (u_flag || a_flag)
4094Srgrimes		change_active(partition);
4104Srgrimes
41148282Srnordier	    if (B_flag)
41243054Srnordier		change_code();
41343054Srnordier
41448282Srnordier	    if (u_flag || a_flag || B_flag) {
41595002Strhodes		if (!t_flag) {
41619459Sjkh		    printf("\nWe haven't changed the partition table yet.  ");
41719459Sjkh		    printf("This is your last chance.\n");
41819459Sjkh		}
419187239Sluigi		print_s0();
42095002Strhodes		if (!t_flag) {
42119459Sjkh		    if (ok("Should we write new partition table?"))
4224Srgrimes			write_s0();
423145763Snyan		} else {
42419459Sjkh		    printf("\n-t flag specified -- partition table not written.\n");
42519459Sjkh		}
42619459Sjkh	    }
4274Srgrimes	}
4284Srgrimes
4294Srgrimes	exit(0);
43037415Scharnier}
4314Srgrimes
43237415Scharnierstatic void
43337415Scharnierusage()
43437415Scharnier{
43548282Srnordier	fprintf(stderr, "%s%s",
436181036Sobrien		"usage: fdisk [-BIaipqstu] [-b bootcode] [-1234] [disk]\n",
43748282Srnordier 		"       fdisk -f configfile [-itv] [disk]\n");
43837415Scharnier        exit(1);
4394Srgrimes}
4404Srgrimes
44116561Salexstatic void
442187239Sluigiprint_s0(void)
4434Srgrimes{
44493394Sphk	int	i;
4454Srgrimes
4464Srgrimes	print_params();
4474Srgrimes	printf("Information from DOS bootblock is:\n");
448187239Sluigi	for (i = 1; i <= NDOSPART; i++)
449187239Sluigi		printf("%d: ", i), print_part(i);
4504Srgrimes}
4514Srgrimes
45293394Sphkstatic struct dos_partition mtpart;
4534Srgrimes
45416561Salexstatic void
45516561Salexprint_part(int i)
4564Srgrimes{
45726389Sgibbs	struct	  dos_partition *partp;
45826389Sgibbs	u_int64_t part_mb;
4594Srgrimes
460187203Sluigi	partp = &mboot.parts[i - 1];
4614Srgrimes
4624Srgrimes	if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
4634Srgrimes		printf("<UNUSED>\n");
4644Srgrimes		return;
4654Srgrimes	}
46626389Sgibbs	/*
46726389Sgibbs	 * Be careful not to overflow.
46826389Sgibbs	 */
46926389Sgibbs	part_mb = partp->dp_size;
47026389Sgibbs	part_mb *= secsize;
47126389Sgibbs	part_mb /= (1024 * 1024);
47290866Sjoe	printf("sysid %d (%#04x),(%s)\n", partp->dp_typ, partp->dp_typ,
47390866Sjoe	    get_type(partp->dp_typ));
474100202Sbde	printf("    start %lu, size %lu (%ju Meg), flag %x%s\n",
47537244Sbde		(u_long)partp->dp_start,
47637244Sbde		(u_long)partp->dp_size,
477100202Sbde		(uintmax_t)part_mb,
47834952Sobrien		partp->dp_flag,
47934952Sobrien		partp->dp_flag == ACTIVE ? " (active)" : "");
48069371Sobrien	printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
4814Srgrimes		,DPCYL(partp->dp_scyl, partp->dp_ssect)
48269371Sobrien		,partp->dp_shd
4834Srgrimes		,DPSECT(partp->dp_ssect)
4844Srgrimes		,DPCYL(partp->dp_ecyl, partp->dp_esect)
48569371Sobrien		,partp->dp_ehd
48669371Sobrien		,DPSECT(partp->dp_esect));
4874Srgrimes}
4884Srgrimes
48919459Sjkh
49016561Salexstatic void
49119459Sjkhinit_boot(void)
49219459Sjkh{
49395860Speter#ifndef __ia64__
49448282Srnordier	const char *fname;
49593394Sphk	int fdesc, n;
49663027Sjhb	struct stat sb;
49748282Srnordier
49848282Srnordier	fname = b_flag ? b_flag : "/boot/mbr";
49993394Sphk	if ((fdesc = open(fname, O_RDONLY)) == -1 ||
50093394Sphk	    fstat(fdesc, &sb) == -1)
50163027Sjhb		err(1, "%s", fname);
50263027Sjhb	if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
50363027Sjhb		errx(1, "%s: length must be a multiple of sector size", fname);
50463218Sache	if (mboot.bootinst != NULL)
50563218Sache		free(mboot.bootinst);
50663027Sjhb	if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
50763027Sjhb		errx(1, "%s: unable to allocate read buffer", fname);
50893394Sphk	if ((n = read(fdesc, mboot.bootinst, mboot.bootinst_size)) == -1 ||
50993394Sphk	    close(fdesc))
51048282Srnordier		err(1, "%s", fname);
51163027Sjhb	if (n != mboot.bootinst_size)
51263027Sjhb		errx(1, "%s: short read", fname);
51395860Speter#else
51495860Speter	if (mboot.bootinst != NULL)
51595860Speter		free(mboot.bootinst);
51695860Speter	mboot.bootinst_size = secsize;
51795860Speter	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL)
51895860Speter		errx(1, "unable to allocate boot block buffer");
51995860Speter	memset(mboot.bootinst, 0, mboot.bootinst_size);
520113454Sphk	le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC);
52195860Speter#endif
52219459Sjkh}
52319459Sjkh
52419459Sjkh
52519459Sjkhstatic void
52616561Salexinit_sector0(unsigned long start)
5274Srgrimes{
528187203Sluigi	struct dos_partition *partp = &mboot.parts[0];
5294Srgrimes
53019459Sjkh	init_boot();
5314Srgrimes
5324Srgrimes	partp->dp_typ = DOSPTYP_386BSD;
5334Srgrimes	partp->dp_flag = ACTIVE;
53465054Sjhb	start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors;
53563027Sjhb	if(start == 0)
53663027Sjhb		start = dos_sectors;
5374Srgrimes	partp->dp_start = start;
53865054Sjhb	partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start;
5394Srgrimes
54081164Siedowse	dos(partp);
5414Srgrimes}
5424Srgrimes
54316561Salexstatic void
54416561Salexchange_part(int i)
5454Srgrimes{
546187203Sluigi    struct dos_partition *partp = &mboot.parts[i - 1];
5474Srgrimes
5484Srgrimes    printf("The data for partition %d is:\n", i);
5494Srgrimes    print_part(i);
5504Srgrimes
5514Srgrimes    if (u_flag && ok("Do you want to change it?")) {
5524Srgrimes	int tmp;
5534Srgrimes
5544Srgrimes	if (i_flag) {
555187203Sluigi		bzero(partp, sizeof (*partp));
556130452Sphk		if (i == 1) {
5574Srgrimes			init_sector0(1);
558130452Sphk			printf("\nThe static data for the slice 1 has been reinitialized to:\n");
5594Srgrimes			print_part(i);
5604Srgrimes		}
5614Srgrimes	}
5624Srgrimes
5634Srgrimes	do {
56434952Sobrien		Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp);
5654Srgrimes		Decimal("start", partp->dp_start, tmp);
5664Srgrimes		Decimal("size", partp->dp_size, tmp);
56781164Siedowse		if (!sanitize_partition(partp)) {
56881164Siedowse			warnx("ERROR: failed to adjust; setting sysid to 0");
56981164Siedowse			partp->dp_typ = 0;
57081164Siedowse		}
5714Srgrimes
57236262Sjraynard		if (ok("Explicitly specify beg/end address ?"))
5734Srgrimes		{
5744Srgrimes			int	tsec,tcyl,thd;
5754Srgrimes			tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
5764Srgrimes			thd = partp->dp_shd;
5774Srgrimes			tsec = DPSECT(partp->dp_ssect);
5784Srgrimes			Decimal("beginning cylinder", tcyl, tmp);
57969371Sobrien			Decimal("beginning head", thd, tmp);
58068871Sobrien			Decimal("beginning sector", tsec, tmp);
5814Srgrimes			partp->dp_scyl = DOSCYL(tcyl);
5824Srgrimes			partp->dp_ssect = DOSSECT(tsec,tcyl);
5834Srgrimes			partp->dp_shd = thd;
5844Srgrimes
5854Srgrimes			tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
5864Srgrimes			thd = partp->dp_ehd;
5874Srgrimes			tsec = DPSECT(partp->dp_esect);
5884Srgrimes			Decimal("ending cylinder", tcyl, tmp);
58969371Sobrien			Decimal("ending head", thd, tmp);
59068871Sobrien			Decimal("ending sector", tsec, tmp);
5914Srgrimes			partp->dp_ecyl = DOSCYL(tcyl);
5924Srgrimes			partp->dp_esect = DOSSECT(tsec,tcyl);
5934Srgrimes			partp->dp_ehd = thd;
59481164Siedowse		} else
59581164Siedowse			dos(partp);
5968871Srgrimes
5974Srgrimes		print_part(i);
5984Srgrimes	} while (!ok("Are we happy with this entry?"));
5994Srgrimes    }
600145763Snyan}
6014Srgrimes
60216561Salexstatic void
6034Srgrimesprint_params()
6044Srgrimes{
6054Srgrimes	printf("parameters extracted from in-core disklabel are:\n");
6064Srgrimes	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
6074Srgrimes			,cyls,heads,sectors,cylsecs);
608145763Snyan	if (dos_cyls > 1023 || dos_heads > 255 || dos_sectors > 63)
60920061Ssos		printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
6104Srgrimes	printf("parameters to be used for BIOS calculations are:\n");
6114Srgrimes	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
6124Srgrimes		,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
6134Srgrimes}
6144Srgrimes
61516561Salexstatic void
61616561Salexchange_active(int which)
6174Srgrimes{
61881164Siedowse	struct dos_partition *partp = &mboot.parts[0];
61981164Siedowse	int active, i, new, tmp;
6204Srgrimes
62181164Siedowse	active = -1;
62281164Siedowse	for (i = 0; i < NDOSPART; i++) {
62381164Siedowse		if ((partp[i].dp_flag & ACTIVE) == 0)
62481164Siedowse			continue;
62581164Siedowse		printf("Partition %d is marked active\n", i + 1);
62681164Siedowse		if (active == -1)
62781164Siedowse			active = i + 1;
62881164Siedowse	}
6294Srgrimes	if (a_flag && which != -1)
6304Srgrimes		active = which;
63181164Siedowse	else if (active == -1)
63281164Siedowse		active = 1;
63381164Siedowse
6343723Sbde	if (!ok("Do you want to change the active partition?"))
6353723Sbde		return;
63634952Sobriensetactive:
63734952Sobrien	do {
63881164Siedowse		new = active;
63981164Siedowse		Decimal("active partition", new, tmp);
64081164Siedowse		if (new < 1 || new > 4) {
64134952Sobrien			printf("Active partition number must be in range 1-4."
64234952Sobrien					"  Try again.\n");
64334952Sobrien			goto setactive;
64434952Sobrien		}
64581164Siedowse		active = new;
64634952Sobrien	} while (!ok("Are you happy with this choice"));
6474Srgrimes	for (i = 0; i < NDOSPART; i++)
6484Srgrimes		partp[i].dp_flag = 0;
64926421Sbrian	if (active > 0 && active <= NDOSPART)
65026421Sbrian		partp[active-1].dp_flag = ACTIVE;
6514Srgrimes}
6524Srgrimes
65343054Srnordierstatic void
65443054Srnordierchange_code()
65543054Srnordier{
65643054Srnordier	if (ok("Do you want to change the boot code?"))
65743054Srnordier		init_boot();
65843054Srnordier}
65943054Srnordier
66016561Salexvoid
6614Srgrimesget_params_to_use()
6624Srgrimes{
6634Srgrimes	int	tmp;
6644Srgrimes	print_params();
6654Srgrimes	if (ok("Do you want to change our idea of what BIOS thinks ?"))
6664Srgrimes	{
6674Srgrimes		do
6684Srgrimes		{
6694Srgrimes			Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
6704Srgrimes			Decimal("BIOS's idea of #heads", dos_heads, tmp);
6714Srgrimes			Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
6724Srgrimes			dos_cylsecs = dos_heads * dos_sectors;
6734Srgrimes			print_params();
6744Srgrimes		}
6754Srgrimes		while(!ok("Are you happy with this choice"));
6764Srgrimes	}
6774Srgrimes}
6784Srgrimes
67919459Sjkh
6804Srgrimes/***********************************************\
6814Srgrimes* Change real numbers into strange dos numbers	*
6824Srgrimes\***********************************************/
68316561Salexstatic void
68493394Sphkdos(struct dos_partition *partp)
6854Srgrimes{
68681164Siedowse	int cy, sec;
68781164Siedowse	u_int32_t end;
6884Srgrimes
68988714Siedowse	if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) {
69088714Siedowse		memcpy(partp, &mtpart, sizeof(*partp));
6913723Sbde		return;
6923723Sbde	}
6933723Sbde
69481164Siedowse	/* Start c/h/s. */
69581164Siedowse	partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors;
69681164Siedowse	cy = partp->dp_start / dos_cylsecs;
69781164Siedowse	sec = partp->dp_start % dos_sectors + 1;
69881164Siedowse	partp->dp_scyl = DOSCYL(cy);
69981164Siedowse	partp->dp_ssect = DOSSECT(sec, cy);
7004Srgrimes
70181164Siedowse	/* End c/h/s. */
70281164Siedowse	end = partp->dp_start + partp->dp_size - 1;
70381164Siedowse	partp->dp_ehd = end % dos_cylsecs / dos_sectors;
70481164Siedowse	cy = end / dos_cylsecs;
70581164Siedowse	sec = end % dos_sectors + 1;
70681164Siedowse	partp->dp_ecyl = DOSCYL(cy);
70781164Siedowse	partp->dp_esect = DOSSECT(sec, cy);
7084Srgrimes}
7094Srgrimes
71016561Salexstatic int
71193394Sphkopen_disk(int flag)
7124Srgrimes{
713148035Sphk	int rwmode;
7144Srgrimes
715182844Slulf	/* Write mode if one of these flags are set. */
716182844Slulf	rwmode = (a_flag || I_flag || B_flag || flag);
717182844Slulf	fd = g_open(disk, rwmode);
718182844Slulf	/* If the mode fails, try read-only if we didn't. */
719182844Slulf	if (fd == -1 && errno == EPERM && rwmode)
720182844Slulf		fd = g_open(disk, 0);
721108395Sphk	if (fd == -1 && errno == ENXIO)
722108395Sphk		return -2;
723108395Sphk	if (fd == -1) {
72437415Scharnier		warnx("can't open device %s", disk);
7254Srgrimes		return -1;
7264Srgrimes	}
72793394Sphk	if (get_params() == -1) {
72837415Scharnier		warnx("can't get disk parameters on %s", disk);
7294Srgrimes		return -1;
7304Srgrimes	}
7314Srgrimes	return fd;
7324Srgrimes}
7334Srgrimes
73416561Salexstatic ssize_t
73516561Salexread_disk(off_t sector, void *buf)
7364Srgrimes{
737145763Snyan
738145763Snyan	lseek(fd, (sector * 512), 0);
739145763Snyan	if (secsize == 0)
740145763Snyan		for (secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE;
741145763Snyan		     secsize *= 2) {
74220061Ssos			/* try the read */
74320061Ssos			int size = read(fd, buf, secsize);
744145763Snyan			if (size == secsize)
74520061Ssos				/* it worked so return */
74620061Ssos				return secsize;
747145763Snyan		}
74820061Ssos	else
749145763Snyan		return read(fd, buf, secsize);
75020061Ssos
75120061Ssos	/* we failed to read at any of the sizes */
75220061Ssos	return -1;
7534Srgrimes}
7544Srgrimes
755148035Sphkstatic int
75616561Salexwrite_disk(off_t sector, void *buf)
7574Srgrimes{
758148035Sphk	int error;
759148035Sphk	struct gctl_req *grq;
760182844Slulf	const char *errmsg;
761182844Slulf	char fbuf[BUFSIZ], *pname;
762148035Sphk	int i, fdw;
763108395Sphk
764148035Sphk	grq = gctl_get_handle();
765148035Sphk	gctl_ro_param(grq, "verb", -1, "write MBR");
766148035Sphk	gctl_ro_param(grq, "class", -1, "MBR");
767182844Slulf	pname = g_providername(fd);
768182844Slulf	if (pname == NULL) {
769183487Slulf		warn("Error getting providername for %s", disk);
770182844Slulf		return (-1);
771182844Slulf	}
772182844Slulf	gctl_ro_param(grq, "geom", -1, pname);
773148035Sphk	gctl_ro_param(grq, "data", secsize, buf);
774182844Slulf	errmsg = gctl_issue(grq);
775182844Slulf	free(pname);
776182844Slulf	if (errmsg == NULL) {
777150249Srodrigc		gctl_free(grq);
778148035Sphk		return(0);
779150249Srodrigc	}
780181036Sobrien	if (!q_flag)	/* GEOM errors are benign, not all devices supported */
781182844Slulf		warnx("%s", errmsg);
782150249Srodrigc	gctl_free(grq);
783182844Slulf
784148035Sphk	error = pwrite(fd, buf, secsize, (sector * 512));
785148035Sphk	if (error == secsize)
786148035Sphk		return (0);
787148035Sphk
788148035Sphk	for (i = 1; i < 5; i++) {
789148035Sphk		sprintf(fbuf, "%ss%d", disk, i);
790148035Sphk		fdw = open(fbuf, O_RDWR, 0);
791148035Sphk		if (fdw < 0)
792148035Sphk			continue;
793148035Sphk		error = ioctl(fdw, DIOCSMBR, buf);
794148035Sphk		close(fdw);
795148035Sphk		if (error == 0)
796148035Sphk			return (0);
797108395Sphk	}
798148035Sphk	warnx("Failed to write sector zero");
799148035Sphk	return(EINVAL);
8004Srgrimes}
8014Srgrimes
80216561Salexstatic int
80316561Salexget_params()
8044Srgrimes{
805103665Sphk	int error;
806103665Sphk	u_int u;
807103665Sphk	off_t o;
8084Srgrimes
809103665Sphk	error = ioctl(fd, DIOCGFWSECTORS, &u);
810103665Sphk	if (error == 0)
811103665Sphk		sectors = dos_sectors = u;
812112826Sphk	else
813112826Sphk		sectors = dos_sectors = 63;
814112826Sphk
815103665Sphk	error = ioctl(fd, DIOCGFWHEADS, &u);
816103665Sphk	if (error == 0)
817103665Sphk		heads = dos_heads = u;
818112826Sphk	else
819112826Sphk		heads = dos_heads = 255;
820103665Sphk
8212810Sbde	dos_cylsecs = cylsecs = heads * sectors;
8222810Sbde	disksecs = cyls * heads * sectors;
8234Srgrimes
824182844Slulf	u = g_sectorsize(fd);
825182844Slulf	if (u <= 0)
826182844Slulf		return (-1);
8274Srgrimes
828182844Slulf	o = g_mediasize(fd);
829182844Slulf	if (o < 0)
830182844Slulf		return (-1);
831182844Slulf	disksecs = o / u;
832182844Slulf	cyls = dos_cyls = o / (u * dos_heads * dos_sectors);
833103665Sphk
834103665Sphk	return (disksecs);
8354Srgrimes}
8364Srgrimes
83716561Salexstatic int
8384Srgrimesread_s0()
8394Srgrimes{
840113454Sphk	int i;
841113454Sphk
84263218Sache	mboot.bootinst_size = secsize;
84363218Sache	if (mboot.bootinst != NULL)
84463027Sjhb		free(mboot.bootinst);
84563218Sache	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
84663218Sache		warnx("unable to allocate buffer to read fdisk "
84763218Sache		      "partition table");
84863218Sache		return -1;
84963027Sjhb	}
85063027Sjhb	if (read_disk(0, mboot.bootinst) == -1) {
85137415Scharnier		warnx("can't read fdisk partition table");
8524Srgrimes		return -1;
8534Srgrimes	}
854113454Sphk	if (le16dec(&mboot.bootinst[DOSMAGICOFFSET]) != DOSMAGIC) {
85537415Scharnier		warnx("invalid fdisk partition table found");
8564Srgrimes		/* So should we initialize things */
8574Srgrimes		return -1;
8584Srgrimes	}
859113454Sphk	for (i = 0; i < NDOSPART; i++)
860113454Sphk		dos_partition_dec(
861113454Sphk		    &mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
862113454Sphk		    &mboot.parts[i]);
8634Srgrimes	return 0;
8644Srgrimes}
8654Srgrimes
86616561Salexstatic int
8674Srgrimeswrite_s0()
8684Srgrimes{
869113454Sphk	int	sector, i;
87063027Sjhb
8714Srgrimes	if (iotest) {
872187239Sluigi		print_s0();
8734Srgrimes		return 0;
8744Srgrimes	}
875113454Sphk	for(i = 0; i < NDOSPART; i++)
876113454Sphk		dos_partition_enc(&mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
877113454Sphk		    &mboot.parts[i]);
878113454Sphk	le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC);
87963027Sjhb	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
88063027Sjhb		if (write_disk(sector,
88163027Sjhb			       &mboot.bootinst[sector * secsize]) == -1) {
88263027Sjhb			warn("can't write fdisk partition table");
88363027Sjhb			return -1;
88463027Sjhb		}
88516561Salex	return(0);
8864Srgrimes}
8874Srgrimes
8884Srgrimes
88916561Salexstatic int
89093394Sphkok(const char *str)
8914Srgrimes{
8924Srgrimes	printf("%s [n] ", str);
89381164Siedowse	fflush(stdout);
89481164Siedowse	if (fgets(lbuf, LBUF, stdin) == NULL)
89581164Siedowse		exit(1);
8964Srgrimes	lbuf[strlen(lbuf)-1] = 0;
8974Srgrimes
8984Srgrimes	if (*lbuf &&
8994Srgrimes		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
9004Srgrimes		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
9014Srgrimes		return 1;
9024Srgrimes	else
9034Srgrimes		return 0;
9044Srgrimes}
9054Srgrimes
90616561Salexstatic int
90793394Sphkdecimal(const char *str, int *num, int deflt)
9084Srgrimes{
90993394Sphk	int acc = 0, c;
91093394Sphk	char *cp;
9114Srgrimes
9124Srgrimes	while (1) {
9134Srgrimes		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
91481164Siedowse		fflush(stdout);
91581164Siedowse		if (fgets(lbuf, LBUF, stdin) == NULL)
91681164Siedowse			exit(1);
9174Srgrimes		lbuf[strlen(lbuf)-1] = 0;
9184Srgrimes
9194Srgrimes		if (!*lbuf)
9204Srgrimes			return 0;
9214Srgrimes
9224Srgrimes		cp = lbuf;
9234Srgrimes		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
9244Srgrimes		if (!c)
9254Srgrimes			return 0;
92616561Salex		while ((c = *cp++)) {
9274Srgrimes			if (c <= '9' && c >= '0')
9284Srgrimes				acc = acc * 10 + c - '0';
9294Srgrimes			else
9304Srgrimes				break;
9314Srgrimes		}
9324Srgrimes		if (c == ' ' || c == '\t')
9334Srgrimes			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
9344Srgrimes		if (!c) {
9354Srgrimes			*num = acc;
9364Srgrimes			return 1;
9374Srgrimes		} else
93834952Sobrien			printf("%s is an invalid decimal number.  Try again.\n",
9394Srgrimes				lbuf);
9404Srgrimes	}
9414Srgrimes
9424Srgrimes}
9434Srgrimes
94493394Sphkstatic const char *
94516561Salexget_type(int type)
9464Srgrimes{
9474Srgrimes	int	numentries = (sizeof(part_types)/sizeof(struct part_type));
9484Srgrimes	int	counter = 0;
9494Srgrimes	struct	part_type *ptr = part_types;
9504Srgrimes
9518871Srgrimes
95293394Sphk	while(counter < numentries) {
9534Srgrimes		if(ptr->type == type)
9544Srgrimes			return(ptr->name);
9554Srgrimes		ptr++;
9564Srgrimes		counter++;
9574Srgrimes	}
9584Srgrimes	return("unknown");
9594Srgrimes}
96019459Sjkh
96119459Sjkh
96219459Sjkhstatic void
96393394Sphkparse_config_line(char *line, CMD *command)
96419459Sjkh{
96519459Sjkh    char	*cp, *end;
96619459Sjkh
96719459Sjkh    cp = line;
96893394Sphk    while (1) {
96919459Sjkh	memset(command, 0, sizeof(*command));
97019459Sjkh
97119459Sjkh	while (isspace(*cp)) ++cp;
97219459Sjkh	if (*cp == '\0' || *cp == '#')
97319459Sjkh	    break;
97419459Sjkh	command->cmd = *cp++;
97519459Sjkh
97619459Sjkh	/*
97719459Sjkh	 * Parse args
97819459Sjkh	 */
97993394Sphk	    while (1) {
98019459Sjkh	    while (isspace(*cp)) ++cp;
98119459Sjkh	    if (*cp == '#')
98219459Sjkh		break;		/* found comment */
98319459Sjkh	    if (isalpha(*cp))
98419459Sjkh		command->args[command->n_args].argtype = *cp++;
98519459Sjkh	    if (!isdigit(*cp))
98619459Sjkh		break;		/* assume end of line */
98719459Sjkh	    end = NULL;
98819459Sjkh	    command->args[command->n_args].arg_val = strtol(cp, &end, 0);
98919459Sjkh	    if (cp == end)
99019459Sjkh		break;		/* couldn't parse number */
99119459Sjkh	    cp = end;
99219459Sjkh	    command->n_args++;
99319459Sjkh	}
99419459Sjkh	break;
99519459Sjkh    }
99619459Sjkh}
99719459Sjkh
99819459Sjkh
99919459Sjkhstatic int
100093394Sphkprocess_geometry(CMD *command)
100119459Sjkh{
100219459Sjkh    int		status = 1, i;
100319459Sjkh
100493394Sphk    while (1) {
100519459Sjkh	geom_processed = 1;
100693394Sphk	    if (part_processed) {
100737415Scharnier	    warnx(
100837415Scharnier	"ERROR line %d: the geometry specification line must occur before\n\
100937415Scharnier    all partition specifications",
101037415Scharnier		    current_line_number);
101119459Sjkh	    status = 0;
101219459Sjkh	    break;
101319459Sjkh	}
101493394Sphk	    if (command->n_args != 3) {
101537415Scharnier	    warnx("ERROR line %d: incorrect number of geometry args",
101637415Scharnier		    current_line_number);
101719459Sjkh	    status = 0;
101819459Sjkh	    break;
101919459Sjkh	}
102093394Sphk	    dos_cyls = 0;
102193394Sphk	    dos_heads = 0;
102293394Sphk	    dos_sectors = 0;
102393394Sphk	    for (i = 0; i < 3; ++i) {
102493394Sphk		    switch (command->args[i].argtype) {
102519459Sjkh	    case 'c':
102619459Sjkh		dos_cyls = command->args[i].arg_val;
102719459Sjkh		break;
102819459Sjkh	    case 'h':
102919459Sjkh		dos_heads = command->args[i].arg_val;
103019459Sjkh		break;
103119459Sjkh	    case 's':
103219459Sjkh		dos_sectors = command->args[i].arg_val;
103319459Sjkh		break;
103419459Sjkh	    default:
103537415Scharnier		warnx(
103637415Scharnier		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
103737415Scharnier			current_line_number, command->args[i].argtype,
103819459Sjkh			command->args[i].argtype);
103919459Sjkh		status = 0;
104019459Sjkh		break;
104119459Sjkh	    }
104219459Sjkh	}
104319459Sjkh	if (status == 0)
104419459Sjkh	    break;
104519459Sjkh
104619459Sjkh	dos_cylsecs = dos_heads * dos_sectors;
104719459Sjkh
104819459Sjkh	/*
104919459Sjkh	 * Do sanity checks on parameter values
105019459Sjkh	 */
105193394Sphk	    if (dos_cyls == 0) {
105237415Scharnier	    warnx("ERROR line %d: number of cylinders not specified",
105337415Scharnier		    current_line_number);
105419459Sjkh	    status = 0;
105519459Sjkh	}
105693394Sphk	    if (dos_cyls > 1024) {
105737415Scharnier	    warnx(
105837415Scharnier	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
105919459Sjkh    (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
106037415Scharnier    is dedicated to FreeBSD)",
106137415Scharnier		    current_line_number, dos_cyls);
106219459Sjkh	}
106319459Sjkh
106493394Sphk	    if (dos_heads == 0) {
106537415Scharnier	    warnx("ERROR line %d: number of heads not specified",
106637415Scharnier		    current_line_number);
106719459Sjkh	    status = 0;
106893394Sphk	    } else if (dos_heads > 256) {
106937415Scharnier	    warnx("ERROR line %d: number of heads must be within (1-256)",
107037415Scharnier		    current_line_number);
107119459Sjkh	    status = 0;
107219459Sjkh	}
107319459Sjkh
107493394Sphk	    if (dos_sectors == 0) {
107537415Scharnier	    warnx("ERROR line %d: number of sectors not specified",
107637415Scharnier		    current_line_number);
107719459Sjkh	    status = 0;
107893394Sphk	    } else if (dos_sectors > 63) {
107937415Scharnier	    warnx("ERROR line %d: number of sectors must be within (1-63)",
108037415Scharnier		    current_line_number);
108119459Sjkh	    status = 0;
108219459Sjkh	}
108319459Sjkh
108419459Sjkh	break;
108519459Sjkh    }
108619459Sjkh    return (status);
108719459Sjkh}
108819459Sjkh
108919459Sjkh
109019459Sjkhstatic int
109193394Sphkprocess_partition(CMD *command)
109219459Sjkh{
109319459Sjkh    int				status = 0, partition;
109465054Sjhb    u_int32_t			prev_head_boundary, prev_cyl_boundary;
109565054Sjhb    u_int32_t			adj_size, max_end;
109619459Sjkh    struct dos_partition	*partp;
109719459Sjkh
109893394Sphk	while (1) {
109919459Sjkh	part_processed = 1;
110093394Sphk		if (command->n_args != 4) {
110137415Scharnier	    warnx("ERROR line %d: incorrect number of partition args",
110237415Scharnier		    current_line_number);
110319459Sjkh	    break;
110419459Sjkh	}
110519459Sjkh	partition = command->args[0].arg_val;
110693394Sphk		if (partition < 1 || partition > 4) {
110737415Scharnier	    warnx("ERROR line %d: invalid partition number %d",
110837415Scharnier		    current_line_number, partition);
110919459Sjkh	    break;
111019459Sjkh	}
1111187203Sluigi	partp = &mboot.parts[partition - 1];
1112187203Sluigi	bzero(partp, sizeof (*partp));
111319459Sjkh	partp->dp_typ = command->args[1].arg_val;
111419459Sjkh	partp->dp_start = command->args[2].arg_val;
111519459Sjkh	partp->dp_size = command->args[3].arg_val;
111619459Sjkh	max_end = partp->dp_start + partp->dp_size;
111719459Sjkh
1118187203Sluigi	if (partp->dp_typ == 0) {
111919459Sjkh	    /*
112019459Sjkh	     * Get out, the partition is marked as unused.
112119459Sjkh	     */
112219459Sjkh	    /*
112319459Sjkh	     * Insure that it's unused.
112419459Sjkh	     */
1125187203Sluigi	    bzero(partp, sizeof(*partp));
112619459Sjkh	    status = 1;
112719459Sjkh	    break;
112819459Sjkh	}
112919459Sjkh
113019459Sjkh	/*
1131108470Sschweikh	 * Adjust start upwards, if necessary, to fall on a head boundary.
113219459Sjkh	 */
113393394Sphk		if (partp->dp_start % dos_sectors != 0) {
113465054Sjhb	    prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
113565054Sjhb	    if (max_end < dos_sectors ||
113693394Sphk			    prev_head_boundary > max_end - dos_sectors) {
113719459Sjkh		/*
113819459Sjkh		 * Can't go past end of partition
113919459Sjkh		 */
114037415Scharnier		warnx(
114137415Scharnier	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
114265054Sjhb    a head boundary",
114337415Scharnier			current_line_number, partition);
114419459Sjkh		break;
114519459Sjkh	    }
114637415Scharnier	    warnx(
114765054Sjhb	"WARNING: adjusting start offset of partition %d\n\
114865054Sjhb    from %u to %u, to fall on a head boundary",
114965054Sjhb		    partition, (u_int)partp->dp_start,
115065054Sjhb		    (u_int)(prev_head_boundary + dos_sectors));
115165054Sjhb	    partp->dp_start = prev_head_boundary + dos_sectors;
115219459Sjkh	}
115319459Sjkh
115419459Sjkh	/*
115519459Sjkh	 * Adjust size downwards, if necessary, to fall on a cylinder
115619459Sjkh	 * boundary.
115719459Sjkh	 */
115865054Sjhb	prev_cyl_boundary =
115919459Sjkh	    ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
116065054Sjhb	if (prev_cyl_boundary > partp->dp_start)
116165054Sjhb	    adj_size = prev_cyl_boundary - partp->dp_start;
116293394Sphk		else {
116365054Sjhb	    warnx(
116465054Sjhb	"ERROR: could not adjust partition to start on a head boundary\n\
116565054Sjhb    and end on a cylinder boundary.");
116665054Sjhb	    return (0);
116765054Sjhb	}
116893394Sphk		if (adj_size != partp->dp_size) {
116937415Scharnier	    warnx(
117065054Sjhb	"WARNING: adjusting size of partition %d from %u to %u\n\
117165054Sjhb    to end on a cylinder boundary",
117265054Sjhb		    partition, (u_int)partp->dp_size, (u_int)adj_size);
117365054Sjhb	    partp->dp_size = adj_size;
117419459Sjkh	}
117593394Sphk		if (partp->dp_size == 0) {
117681164Siedowse	    warnx("ERROR line %d: size of partition %d is zero",
117737415Scharnier		    current_line_number, partition);
117819459Sjkh	    break;
117919459Sjkh	}
118019459Sjkh
118181164Siedowse	dos(partp);
118219459Sjkh	status = 1;
118319459Sjkh	break;
118419459Sjkh    }
118519459Sjkh    return (status);
118619459Sjkh}
118719459Sjkh
118819459Sjkh
118919459Sjkhstatic int
119093394Sphkprocess_active(CMD *command)
119119459Sjkh{
119219459Sjkh    int				status = 0, partition, i;
119319459Sjkh    struct dos_partition	*partp;
119419459Sjkh
119593394Sphk	while (1) {
119619459Sjkh	active_processed = 1;
119793394Sphk		if (command->n_args != 1) {
119837415Scharnier	    warnx("ERROR line %d: incorrect number of active args",
119937415Scharnier		    current_line_number);
120019459Sjkh	    status = 0;
120119459Sjkh	    break;
120219459Sjkh	}
120319459Sjkh	partition = command->args[0].arg_val;
120493394Sphk		if (partition < 1 || partition > 4) {
120537415Scharnier	    warnx("ERROR line %d: invalid partition number %d",
120637415Scharnier		    current_line_number, partition);
120719459Sjkh	    break;
120819459Sjkh	}
120919459Sjkh	/*
121019459Sjkh	 * Reset active partition
121119459Sjkh	 */
1212187203Sluigi	partp = mboot.parts;
121319459Sjkh	for (i = 0; i < NDOSPART; i++)
121419459Sjkh	    partp[i].dp_flag = 0;
121526421Sbrian	partp[partition-1].dp_flag = ACTIVE;
121619459Sjkh
121719459Sjkh	status = 1;
121819459Sjkh	break;
121919459Sjkh    }
122019459Sjkh    return (status);
122119459Sjkh}
122219459Sjkh
122319459Sjkh
122419459Sjkhstatic int
122593394Sphkprocess_line(char *line)
122619459Sjkh{
122719459Sjkh    CMD		command;
122819459Sjkh    int		status = 1;
122919459Sjkh
123093394Sphk	while (1) {
123119459Sjkh	parse_config_line(line, &command);
123293394Sphk		switch (command.cmd) {
123319459Sjkh	case 0:
123419459Sjkh	    /*
123519459Sjkh	     * Comment or blank line
123619459Sjkh	     */
123719459Sjkh	    break;
123819459Sjkh	case 'g':
123919459Sjkh	    /*
124019459Sjkh	     * Set geometry
124119459Sjkh	     */
124219459Sjkh	    status = process_geometry(&command);
124319459Sjkh	    break;
124419459Sjkh	case 'p':
124519459Sjkh	    status = process_partition(&command);
124619459Sjkh	    break;
124719459Sjkh	case 'a':
124819459Sjkh	    status = process_active(&command);
124919459Sjkh	    break;
125019459Sjkh	default:
125119459Sjkh	    status = 0;
125219459Sjkh	    break;
125319459Sjkh	}
125419459Sjkh	break;
125519459Sjkh    }
125619459Sjkh    return (status);
125719459Sjkh}
125819459Sjkh
125919459Sjkh
126019459Sjkhstatic int
126193394Sphkread_config(char *config_file)
126219459Sjkh{
126319459Sjkh    FILE	*fp = NULL;
126419459Sjkh    int		status = 1;
126519459Sjkh    char	buf[1010];
126619459Sjkh
126793394Sphk	while (1) {
126893394Sphk		if (strcmp(config_file, "-") != 0) {
126919459Sjkh	    /*
127019459Sjkh	     * We're not reading from stdin
127119459Sjkh	     */
127293394Sphk			if ((fp = fopen(config_file, "r")) == NULL) {
127319459Sjkh		status = 0;
127419459Sjkh		break;
127519459Sjkh	    }
127693394Sphk		} else {
127719459Sjkh	    fp = stdin;
127819459Sjkh	}
127919459Sjkh	current_line_number = 0;
128093394Sphk		while (!feof(fp)) {
128119459Sjkh	    if (fgets(buf, sizeof(buf), fp) == NULL)
128219459Sjkh		break;
128319459Sjkh	    ++current_line_number;
128419459Sjkh	    status = process_line(buf);
128519459Sjkh	    if (status == 0)
128619459Sjkh		break;
128719459Sjkh	    }
128819459Sjkh	break;
128919459Sjkh    }
129093394Sphk	if (fp) {
129119459Sjkh	/*
129219459Sjkh	 * It doesn't matter if we're reading from stdin, as we've reached EOF
129319459Sjkh	 */
129419459Sjkh	fclose(fp);
129519459Sjkh    }
129619459Sjkh    return (status);
129719459Sjkh}
129819459Sjkh
129919459Sjkh
130019459Sjkhstatic void
130119459Sjkhreset_boot(void)
130219459Sjkh{
130319459Sjkh    int				i;
130419459Sjkh    struct dos_partition	*partp;
130519459Sjkh
130619459Sjkh    init_boot();
1307187203Sluigi    for (i = 0; i < 4; ++i) {
1308187203Sluigi	partp = &mboot.parts[i];
1309187203Sluigi	bzero(partp, sizeof(*partp));
131019459Sjkh    }
131119459Sjkh}
131265054Sjhb
131365054Sjhbstatic int
131493394Sphksanitize_partition(struct dos_partition *partp)
131565054Sjhb{
131665054Sjhb    u_int32_t			prev_head_boundary, prev_cyl_boundary;
131781164Siedowse    u_int32_t			max_end, size, start;
131865054Sjhb
131981164Siedowse    start = partp->dp_start;
132081164Siedowse    size = partp->dp_size;
132181164Siedowse    max_end = start + size;
132281164Siedowse    /* Only allow a zero size if the partition is being marked unused. */
132381164Siedowse    if (size == 0) {
132481164Siedowse	if (start == 0 && partp->dp_typ == 0)
132581164Siedowse	    return (1);
132681164Siedowse	warnx("ERROR: size of partition is zero");
132781164Siedowse	return (0);
132881164Siedowse    }
132981164Siedowse    /* Return if no adjustment is necessary. */
133081164Siedowse    if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0)
133181164Siedowse	return (1);
133265054Sjhb
1333122627Sdes    if (start == 0) {
1334122627Sdes	    warnx("WARNING: partition overlaps with partition table");
1335122627Sdes	    if (ok("Correct this automatically?"))
1336122627Sdes		    start = dos_sectors;
1337122627Sdes    }
133881164Siedowse    if (start % dos_sectors != 0)
133981164Siedowse	warnx("WARNING: partition does not start on a head boundary");
134081164Siedowse    if ((start  +size) % dos_sectors != 0)
134181164Siedowse	warnx("WARNING: partition does not end on a cylinder boundary");
134281164Siedowse    warnx("WARNING: this may confuse the BIOS or some operating systems");
134381164Siedowse    if (!ok("Correct this automatically?"))
134481164Siedowse	return (1);
134581164Siedowse
134665054Sjhb    /*
1347108470Sschweikh     * Adjust start upwards, if necessary, to fall on a head boundary.
134865054Sjhb     */
134981164Siedowse    if (start % dos_sectors != 0) {
135081164Siedowse	prev_head_boundary = start / dos_sectors * dos_sectors;
135165054Sjhb	if (max_end < dos_sectors ||
135281164Siedowse	    prev_head_boundary >= max_end - dos_sectors) {
135365054Sjhb	    /*
135465054Sjhb	     * Can't go past end of partition
135565054Sjhb	     */
135665054Sjhb	    warnx(
135765054Sjhb    "ERROR: unable to adjust start of partition to fall on a head boundary");
135865054Sjhb	    return (0);
135965054Sjhb        }
136081164Siedowse	start = prev_head_boundary + dos_sectors;
136165054Sjhb    }
136265054Sjhb
136365054Sjhb    /*
136465054Sjhb     * Adjust size downwards, if necessary, to fall on a cylinder
136565054Sjhb     * boundary.
136665054Sjhb     */
136781164Siedowse    prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs;
136881164Siedowse    if (prev_cyl_boundary > start)
136981164Siedowse	size = prev_cyl_boundary - start;
137081164Siedowse    else {
137165054Sjhb	warnx("ERROR: could not adjust partition to start on a head boundary\n\
137265054Sjhb    and end on a cylinder boundary.");
137365054Sjhb	return (0);
137465054Sjhb    }
137581164Siedowse
137681164Siedowse    /* Finally, commit any changes to partp and return. */
137781164Siedowse    if (start != partp->dp_start) {
137881164Siedowse	warnx("WARNING: adjusting start offset of partition to %u",
137981164Siedowse	    (u_int)start);
138081164Siedowse	partp->dp_start = start;
138165054Sjhb    }
138281164Siedowse    if (size != partp->dp_size) {
138381164Siedowse	warnx("WARNING: adjusting size of partition to %u", (u_int)size);
138481164Siedowse	partp->dp_size = size;
138565054Sjhb    }
138665054Sjhb
138765054Sjhb    return (1);
138865054Sjhb}
138979681Sjoerg
139079681Sjoerg/*
139179681Sjoerg * Try figuring out the root device's canonical disk name.
139279681Sjoerg * The following choices are considered:
139379681Sjoerg *   /dev/ad0s1a     => /dev/ad0
139479681Sjoerg *   /dev/da0a       => /dev/da0
139579681Sjoerg *   /dev/vinum/root => /dev/vinum/root
139679681Sjoerg */
139779681Sjoergstatic char *
139879681Sjoergget_rootdisk(void)
139979681Sjoerg{
140079681Sjoerg	struct statfs rootfs;
140179681Sjoerg	regex_t re;
140279681Sjoerg#define NMATCHES 2
140379681Sjoerg	regmatch_t rm[NMATCHES];
140479681Sjoerg	char *s;
140579681Sjoerg	int rv;
140679681Sjoerg
140779681Sjoerg	if (statfs("/", &rootfs) == -1)
140879681Sjoerg		err(1, "statfs(\"/\")");
140979681Sjoerg
1410159757Ssimon	if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]+)([sp][0-9]+)?[a-h]?$",
141179681Sjoerg		    REG_EXTENDED)) != 0)
141279681Sjoerg		errx(1, "regcomp() failed (%d)", rv);
141379681Sjoerg	if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0)
141479681Sjoerg		errx(1,
141579681Sjoerg"mounted root fs resource doesn't match expectations (regexec returned %d)",
141679681Sjoerg		    rv);
141779681Sjoerg	if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL)
141879681Sjoerg		errx(1, "out of memory");
141979681Sjoerg	memcpy(s, rootfs.f_mntfromname + rm[1].rm_so,
142079681Sjoerg	    rm[1].rm_eo - rm[1].rm_so);
142179681Sjoerg	s[rm[1].rm_eo - rm[1].rm_so] = 0;
142279681Sjoerg
142379681Sjoerg	return s;
142479681Sjoerg}
1425