fdisk.c revision 130452
1119418Sobrien/*
269953Smsmith * Mach Operating System
369953Smsmith * Copyright (c) 1992 Carnegie Mellon University
469953Smsmith * All Rights Reserved.
569953Smsmith *
669953Smsmith * Permission to use, copy, modify and distribute this software and its
769953Smsmith * documentation is hereby granted, provided that both the copyright
869953Smsmith * notice and this permission notice appear in all copies of the
969953Smsmith * software, derivative works or modified versions, and any portions
1069953Smsmith * thereof, and that both notices appear in supporting documentation.
1169953Smsmith *
1269953Smsmith * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
1369953Smsmith * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
1469953Smsmith * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
1569953Smsmith *
1669953Smsmith * Carnegie Mellon requests users of this software to return to
1769953Smsmith *
1869953Smsmith *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
1969953Smsmith *  School of Computer Science
2069953Smsmith *  Carnegie Mellon University
2169953Smsmith *  Pittsburgh PA 15213-3890
2269953Smsmith *
2369953Smsmith * any improvements or extensions that they make and grant Carnegie Mellon
2469953Smsmith * the rights to redistribute these changes.
2569953Smsmith */
2669953Smsmith
27119418Sobrien#include <sys/cdefs.h>
28119418Sobrien__FBSDID("$FreeBSD: head/sbin/fdisk/fdisk.c 130452 2004-06-14 07:21:19Z phk $");
29119418Sobrien
3069953Smsmith#include <sys/disk.h>
3169953Smsmith#include <sys/disklabel.h>
3269953Smsmith#include <sys/diskmbr.h>
3369953Smsmith#include <sys/endian.h>
3469953Smsmith#include <sys/param.h>
3569953Smsmith#include <sys/stat.h>
3669953Smsmith#include <sys/mount.h>
3769953Smsmith#include <ctype.h>
3869953Smsmith#include <fcntl.h>
3969953Smsmith#include <err.h>
4083975Srwatson#include <errno.h>
4169953Smsmith#include <paths.h>
4269953Smsmith#include <regex.h>
4369953Smsmith#include <stdint.h>
4469953Smsmith#include <stdio.h>
4569953Smsmith#include <stdlib.h>
4669953Smsmith#include <string.h>
4769953Smsmith#include <unistd.h>
4869953Smsmith
4969953Smsmithint iotest;
5069953Smsmith
5169953Smsmith#define LBUF 100
5269953Smsmithstatic char lbuf[LBUF];
5369953Smsmith
54119285Simp#define MBRSIGOFF	510
55119285Simp
5669953Smsmith/*
5769953Smsmith *
5869953Smsmith * Ported to 386bsd by Julian Elischer  Thu Oct 15 20:26:46 PDT 1992
5969953Smsmith *
6069953Smsmith * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
6169953Smsmith *	Copyright (c) 1989	Robert. V. Baron
6269953Smsmith *	Created.
6369953Smsmith */
6483366Sjulian
6583366Sjulian#define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp
6669953Smsmith
6769953Smsmith#define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs)
6883366Sjulian
6969953Smsmith#define MAX_SEC_SIZE 2048	/* maximum section size that is supported */
7069953Smsmith#define MIN_SEC_SIZE 512	/* the sector size to start sensing at */
71126080Sphkstatic int secsize = 0;		/* the sensed sector size */
72126080Sphk
73111815Sphkstatic char *disk;
74111815Sphk
75111815Sphkstatic int cyls, sectors, heads, cylsecs, disksecs;
76111815Sphk
7769953Smsmithstruct mboot {
7869953Smsmith	unsigned char padding[2]; /* force the longs to be long aligned */
7969953Smsmith  	unsigned char *bootinst;  /* boot code */
80130585Sphk  	off_t bootinst_size;
8169953Smsmith	struct	dos_partition parts[NDOSPART];
8283975Srwatson};
8383975Srwatson
8483975Srwatsonstatic struct mboot mboot;
8591406Sjhbstatic int fd, fdw;
8683975Srwatson
8783975Srwatson
8869953Smsmith#define ACTIVE 0x80
8983975Srwatson
9083975Srwatsonstatic uint dos_cyls;
9169953Smsmithstatic uint dos_heads;
9269953Smsmithstatic uint dos_sectors;
9369953Smsmithstatic uint dos_cylsecs;
94130585Sphk
9569953Smsmith#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
9669953Smsmith#define DOSCYL(c)	(c & 0xff)
9769953Smsmith
9869953Smsmith#define MAX_ARGS	10
9969953Smsmith
10069953Smsmithstatic int	current_line_number;
10169953Smsmith
10269953Smsmithstatic int	geom_processed = 0;
10369953Smsmithstatic int	part_processed = 0;
10469953Smsmithstatic int	active_processed = 0;
10569953Smsmith
10669953Smsmithtypedef struct cmd {
10769953Smsmith    char		cmd;
10869953Smsmith    int			n_args;
10969953Smsmith    struct arg {
11069953Smsmith	char	argtype;
11169953Smsmith	int	arg_val;
11269953Smsmith    }			args[MAX_ARGS];
11369953Smsmith} CMD;
11469953Smsmith
11569953Smsmithstatic int B_flag  = 0;		/* replace boot code */
11669953Smsmithstatic int I_flag  = 0;		/* use entire disk for FreeBSD */
11769953Smsmithstatic int a_flag  = 0;		/* set active partition */
11869953Smsmithstatic char *b_flag = NULL;	/* path to boot code */
11969953Smsmithstatic int i_flag  = 0;		/* replace partition data */
12069953Smsmithstatic int u_flag  = 0;		/* update partition data */
12169953Smsmithstatic int s_flag  = 0;		/* Print a summary and exit */
12269953Smsmithstatic int t_flag  = 0;		/* test only */
12369953Smsmithstatic char *f_flag = NULL;	/* Read config info from file */
12469953Smsmithstatic int v_flag  = 0;		/* Be verbose */
12569953Smsmith
12669953Smsmithstatic struct part_type
12769953Smsmith{
12869953Smsmith unsigned char type;
12969953Smsmith	const char *name;
13069953Smsmith} part_types[] = {
13169953Smsmith	 {0x00, "unused"}
13269953Smsmith	,{0x01, "Primary DOS with 12 bit FAT"}
13369953Smsmith	,{0x02, "XENIX / file system"}
13469953Smsmith	,{0x03, "XENIX /usr file system"}
13569953Smsmith	,{0x04, "Primary DOS with 16 bit FAT (< 32MB)"}
13669953Smsmith	,{0x05, "Extended DOS"}
13769953Smsmith	,{0x06, "Primary 'big' DOS (>= 32MB)"}
13869953Smsmith	,{0x07, "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX"}
13969953Smsmith	,{0x08, "AIX file system or SplitDrive"}
14069953Smsmith	,{0x09, "AIX boot partition or Coherent"}
14169953Smsmith	,{0x0A, "OS/2 Boot Manager, OPUS or Coherent swap"}
14269953Smsmith	,{0x0B, "DOS or Windows 95 with 32 bit FAT"}
14369953Smsmith	,{0x0C, "DOS or Windows 95 with 32 bit FAT (LBA)"}
14469953Smsmith	,{0x0E, "Primary 'big' DOS (>= 32MB, LBA)"}
14569953Smsmith	,{0x0F, "Extended DOS (LBA)"}
14669953Smsmith	,{0x10, "OPUS"}
14769953Smsmith	,{0x11, "OS/2 BM: hidden DOS with 12-bit FAT"}
14869953Smsmith	,{0x12, "Compaq diagnostics"}
14969953Smsmith	,{0x14, "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)"}
15069953Smsmith	,{0x16, "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)"}
15169953Smsmith	,{0x17, "OS/2 BM: hidden IFS (e.g. HPFS)"}
15269953Smsmith	,{0x18, "AST Windows swapfile"}
15369953Smsmith	,{0x24, "NEC DOS"}
15469953Smsmith	,{0x3C, "PartitionMagic recovery"}
15569953Smsmith	,{0x39, "plan9"}
15669953Smsmith	,{0x40, "VENIX 286"}
15769953Smsmith	,{0x41, "Linux/MINIX (sharing disk with DRDOS)"}
15869953Smsmith	,{0x42, "SFS or Linux swap (sharing disk with DRDOS)"}
15969953Smsmith	,{0x43, "Linux native (sharing disk with DRDOS)"}
16069953Smsmith	,{0x4D, "QNX 4.2 Primary"}
16169953Smsmith	,{0x4E, "QNX 4.2 Secondary"}
16269953Smsmith	,{0x4F, "QNX 4.2 Tertiary"}
16369953Smsmith	,{0x50, "DM (disk manager)"}
16469953Smsmith	,{0x51, "DM6 Aux1 (or Novell)"}
16569953Smsmith	,{0x52, "CP/M or Microport SysV/AT"}
16669953Smsmith	,{0x53, "DM6 Aux3"}
167130585Sphk	,{0x54, "DM6"}
16869953Smsmith	,{0x55, "EZ-Drive (disk manager)"}
169145022Sbms	,{0x56, "Golden Bow (disk manager)"}
17069953Smsmith	,{0x5c, "Priam Edisk (disk manager)"} /* according to S. Widlake */
17169953Smsmith	,{0x61, "SpeedStor"}
17269953Smsmith	,{0x63, "System V/386 (such as ISC UNIX), GNU HURD or Mach"}
17369953Smsmith	,{0x64, "Novell Netware/286 2.xx"}
174116702Sjmg	,{0x65, "Novell Netware/386 3.xx"}
17569953Smsmith	,{0x70, "DiskSecure Multi-Boot"}
17669953Smsmith	,{0x75, "PCIX"}
17769953Smsmith	,{0x77, "QNX4.x"}
17869953Smsmith	,{0x78, "QNX4.x 2nd part"}
17969953Smsmith	,{0x79, "QNX4.x 3rd part"}
18069953Smsmith	,{0x80, "Minix until 1.4a"}
18169953Smsmith	,{0x81, "Minix since 1.4b, early Linux partition or Mitac disk manager"}
18269953Smsmith	,{0x82, "Linux swap or Solaris x86"}
18369953Smsmith	,{0x83, "Linux native"}
18469953Smsmith	,{0x84, "OS/2 hidden C: drive"}
18569953Smsmith	,{0x85, "Linux extended"}
18669953Smsmith	,{0x86, "NTFS volume set??"}
18769953Smsmith	,{0x87, "NTFS volume set??"}
18869953Smsmith	,{0x93, "Amoeba file system"}
18969953Smsmith	,{0x94, "Amoeba bad block table"}
19069953Smsmith	,{0x9F, "BSD/OS"}
19169953Smsmith	,{0xA0, "Suspend to Disk"}
19269953Smsmith	,{0xA5, "FreeBSD/NetBSD/386BSD"}
19369953Smsmith	,{0xA6, "OpenBSD"}
19469953Smsmith	,{0xA7, "NeXTSTEP"}
19569953Smsmith	,{0xA9, "NetBSD"}
19669953Smsmith	,{0xAC, "IBM JFS"}
19769953Smsmith	,{0xB7, "BSDI BSD/386 file system"}
19869953Smsmith	,{0xB8, "BSDI BSD/386 swap"}
19969953Smsmith	,{0xBE, "Solaris x86 boot"}
20069953Smsmith	,{0xC1, "DRDOS/sec with 12-bit FAT"}
20169953Smsmith	,{0xC4, "DRDOS/sec with 16-bit FAT (< 32MB)"}
20269953Smsmith	,{0xC6, "DRDOS/sec with 16-bit FAT (>= 32MB)"}
20369953Smsmith	,{0xC7, "Syrinx"}
20469953Smsmith	,{0xDB, "CP/M, Concurrent CP/M, Concurrent DOS or CTOS"}
20569953Smsmith	,{0xE1, "DOS access or SpeedStor with 12-bit FAT extended partition"}
20669953Smsmith	,{0xE3, "DOS R/O or SpeedStor"}
20769953Smsmith	,{0xE4, "SpeedStor with 16-bit FAT extended partition < 1024 cyl."}
20869953Smsmith	,{0xEB, "BeOS file system"}
20969953Smsmith	,{0xEE, "EFI GPT"}
21069953Smsmith	,{0xEF, "EFI System Partition"}
21169953Smsmith	,{0xF1, "SpeedStor"}
21269953Smsmith	,{0xF2, "DOS 3.3+ Secondary"}
21369953Smsmith	,{0xF4, "SpeedStor large partition"}
21469953Smsmith	,{0xFE, "SpeedStor >1024 cyl. or LANstep"}
21569953Smsmith	,{0xFF, "Xenix bad blocks table"}
21669953Smsmith};
21769953Smsmith
21869953Smsmithstatic void print_s0(int which);
21969953Smsmithstatic void print_part(int i);
22069953Smsmithstatic void init_sector0(unsigned long start);
22169953Smsmithstatic void init_boot(void);
22269953Smsmithstatic void change_part(int i);
22369953Smsmithstatic void print_params(void);
22469953Smsmithstatic void change_active(int which);
22569953Smsmithstatic void change_code(void);
22669953Smsmithstatic void get_params_to_use(void);
22769953Smsmithstatic char *get_rootdisk(void);
22869953Smsmithstatic void dos(struct dos_partition *partp);
22969953Smsmithstatic int open_disk(int flag);
23069953Smsmithstatic ssize_t read_disk(off_t sector, void *buf);
23169953Smsmithstatic ssize_t write_disk(off_t sector, void *buf);
23269953Smsmithstatic int get_params(void);
23369953Smsmithstatic int read_s0(void);
23469953Smsmithstatic int write_s0(void);
23569953Smsmithstatic int ok(const char *str);
23669953Smsmithstatic int decimal(const char *str, int *num, int deflt);
23769953Smsmithstatic const char *get_type(int type);
23869953Smsmithstatic int read_config(char *config_file);
23969953Smsmithstatic void reset_boot(void);
24069953Smsmithstatic int sanitize_partition(struct dos_partition *);
241116704Sjmgstatic void usage(void);
24269953Smsmith
24369953Smsmithint
24469953Smsmithmain(int argc, char *argv[])
24569953Smsmith{
24669953Smsmith	struct	stat sb;
24769953Smsmith	int	c, i;
24869953Smsmith	int	partition = -1;
24969953Smsmith	struct	dos_partition *partp;
25069953Smsmith
25169953Smsmith	while ((c = getopt(argc, argv, "BIab:f:istuv1234")) != -1)
25269953Smsmith		switch (c) {
25369953Smsmith		case 'B':
25469953Smsmith			B_flag = 1;
25569953Smsmith			break;
25669953Smsmith		case 'I':
25769953Smsmith			I_flag = 1;
25869953Smsmith			break;
25969953Smsmith		case 'a':
26069953Smsmith			a_flag = 1;
26169953Smsmith			break;
26269953Smsmith		case 'b':
26369953Smsmith			b_flag = optarg;
26469953Smsmith			break;
26569953Smsmith		case 'f':
26669953Smsmith			f_flag = optarg;
26769953Smsmith			break;
26869953Smsmith		case 'i':
269111119Simp			i_flag = 1;
27069953Smsmith			break;
27169953Smsmith		case 's':
272116702Sjmg			s_flag = 1;
273116702Sjmg			break;
274116702Sjmg		case 't':
275116702Sjmg			t_flag = 1;
27669953Smsmith			break;
27769953Smsmith		case 'u':
27869953Smsmith			u_flag = 1;
27969953Smsmith			break;
28069953Smsmith		case 'v':
28169953Smsmith			v_flag = 1;
28269953Smsmith			break;
28369953Smsmith		case '1':
28469953Smsmith		case '2':
28569953Smsmith		case '3':
28669953Smsmith		case '4':
28769953Smsmith			partition = c - '0';
28869953Smsmith			break;
28969953Smsmith		default:
29069953Smsmith			usage();
29169953Smsmith		}
29269953Smsmith	if (f_flag || i_flag)
29369953Smsmith		u_flag = 1;
29469953Smsmith	if (t_flag)
29569953Smsmith		v_flag = 1;
29669953Smsmith	argc -= optind;
297116702Sjmg	argv += optind;
29869953Smsmith
29969953Smsmith	if (argc == 0) {
30069953Smsmith		disk = get_rootdisk();
30169953Smsmith	} else {
30269953Smsmith		if (stat(argv[0], &sb) == 0) {
30369953Smsmith			/* OK, full pathname given */
30469953Smsmith			disk = argv[0];
30569953Smsmith		} else if (errno == ENOENT) {
30669953Smsmith			/* Try prepending "/dev" */
30769953Smsmith			asprintf(&disk, "%s%s", _PATH_DEV, argv[0]);
30869953Smsmith			if (disk == NULL)
30969953Smsmith				errx(1, "out of memory");
31069953Smsmith		} else {
31169953Smsmith			/* other stat error, let it fail below */
31269953Smsmith			disk = argv[0];
31369953Smsmith		}
31469953Smsmith	}
31569953Smsmith	if (open_disk(u_flag) < 0)
31669953Smsmith		err(1, "cannot open disk %s", disk);
31769953Smsmith
31869953Smsmith	/* (abu)use mboot.bootinst to probe for the sector size */
31969953Smsmith	if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
32069953Smsmith		err(1, "cannot allocate buffer to determine disk sector size");
32169953Smsmith	read_disk(0, mboot.bootinst);
32269953Smsmith	free(mboot.bootinst);
32369953Smsmith	mboot.bootinst = NULL;
32469953Smsmith
32569953Smsmith	if (s_flag) {
32669953Smsmith		if (read_s0())
32769953Smsmith			err(1, "read_s0");
32869953Smsmith		printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
32969953Smsmith		    dos_sectors);
330116702Sjmg		printf("Part  %11s %11s Type Flags\n", "Start", "Size");
331116702Sjmg		for (i = 0; i < NDOSPART; i++) {
332116702Sjmg			partp = ((struct dos_partition *) &mboot.parts) + i;
333116702Sjmg			if (partp->dp_start == 0 && partp->dp_size == 0)
334116702Sjmg				continue;
335116702Sjmg			printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
33669953Smsmith			    (u_long) partp->dp_start,
33769953Smsmith			    (u_long) partp->dp_size, partp->dp_typ,
33869953Smsmith			    partp->dp_flag);
33969953Smsmith		}
34069953Smsmith		exit(0);
34169953Smsmith	}
34269953Smsmith
34369953Smsmith	printf("******* Working on device %s *******\n",disk);
34469953Smsmith
34569953Smsmith	if (I_flag) {
34669953Smsmith		read_s0();
34769953Smsmith		reset_boot();
34869953Smsmith		partp = (struct dos_partition *) (&mboot.parts[0]);
34969953Smsmith		partp->dp_typ = DOSPTYP_386BSD;
35069953Smsmith		partp->dp_flag = ACTIVE;
35169953Smsmith		partp->dp_start = dos_sectors;
35269953Smsmith		partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs -
35369953Smsmith		    dos_sectors;
35469953Smsmith		dos(partp);
35569953Smsmith		if (v_flag)
35669953Smsmith			print_s0(-1);
35769953Smsmith		if (!t_flag)
35869953Smsmith			write_s0();
35969953Smsmith		exit(0);
36069953Smsmith	}
36169953Smsmith	if (f_flag) {
362116702Sjmg	    if (read_s0() || i_flag)
36369953Smsmith		reset_boot();
36469953Smsmith	    if (!read_config(f_flag))
36569953Smsmith		exit(1);
36669953Smsmith	    if (v_flag)
36769953Smsmith		print_s0(-1);
368121013Sse	    if (!t_flag)
36969953Smsmith		write_s0();
370121013Sse	} else {
37169953Smsmith	    if(u_flag)
37269953Smsmith		get_params_to_use();
37369953Smsmith	    else
37469953Smsmith		print_params();
37569953Smsmith
376121013Sse	    if (read_s0())
377121013Sse		init_sector0(dos_sectors);
378121013Sse
379121013Sse	    printf("Media sector size is %d\n", secsize);
380121013Sse	    printf("Warning: BIOS sector numbering starts with sector 1\n");
381121013Sse	    printf("Information from DOS bootblock is:\n");
38269953Smsmith	    if (partition == -1)
38369953Smsmith		for (i = 1; i <= NDOSPART; i++)
384145022Sbms		    change_part(i);
385145022Sbms	    else
386145022Sbms		change_part(partition);
38769953Smsmith
388145022Sbms	    if (u_flag || a_flag)
389145022Sbms		change_active(partition);
390145022Sbms
391145022Sbms	    if (B_flag)
392145022Sbms		change_code();
393145022Sbms
394145022Sbms	    if (u_flag || a_flag || B_flag) {
395145022Sbms		if (!t_flag) {
396121013Sse		    printf("\nWe haven't changed the partition table yet.  ");
397145022Sbms		    printf("This is your last chance.\n");
398145022Sbms		}
399121013Sse		print_s0(-1);
400121013Sse		if (!t_flag) {
401121013Sse		    if (ok("Should we write new partition table?"))
402121013Sse			write_s0();
403121013Sse			} else {
404121013Sse		    printf("\n-t flag specified -- partition table not written.\n");
405121013Sse		}
406145022Sbms	    }
407145022Sbms	}
408121013Sse
409121013Sse	exit(0);
410121013Sse}
411121013Sse
41269953Smsmithstatic void
41369953Smsmithusage()
41469953Smsmith{
41569953Smsmith	fprintf(stderr, "%s%s",
41669953Smsmith		"usage: fdisk [-BIaistu] [-b bootcode] [-1234] [disk]\n",
41769953Smsmith 		"       fdisk -f configfile [-itv] [disk]\n");
418116702Sjmg        exit(1);
41969953Smsmith}
42069953Smsmith
42169953Smsmithstatic void
42269953Smsmithprint_s0(int which)
42369953Smsmith{
42469953Smsmith	int	i;
42569953Smsmith
42669953Smsmith	print_params();
42769953Smsmith	printf("Information from DOS bootblock is:\n");
42869953Smsmith	if (which == -1)
42969953Smsmith		for (i = 1; i <= NDOSPART; i++)
430			printf("%d: ", i), print_part(i);
431	else
432		print_part(which);
433}
434
435static struct dos_partition mtpart;
436
437static void
438print_part(int i)
439{
440	struct	  dos_partition *partp;
441	u_int64_t part_mb;
442
443	partp = ((struct dos_partition *) &mboot.parts) + i - 1;
444
445	if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
446		printf("<UNUSED>\n");
447		return;
448	}
449	/*
450	 * Be careful not to overflow.
451	 */
452	part_mb = partp->dp_size;
453	part_mb *= secsize;
454	part_mb /= (1024 * 1024);
455	printf("sysid %d (%#04x),(%s)\n", partp->dp_typ, partp->dp_typ,
456	    get_type(partp->dp_typ));
457	printf("    start %lu, size %lu (%ju Meg), flag %x%s\n",
458		(u_long)partp->dp_start,
459		(u_long)partp->dp_size,
460		(uintmax_t)part_mb,
461		partp->dp_flag,
462		partp->dp_flag == ACTIVE ? " (active)" : "");
463	printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
464		,DPCYL(partp->dp_scyl, partp->dp_ssect)
465		,partp->dp_shd
466		,DPSECT(partp->dp_ssect)
467		,DPCYL(partp->dp_ecyl, partp->dp_esect)
468		,partp->dp_ehd
469		,DPSECT(partp->dp_esect));
470}
471
472
473static void
474init_boot(void)
475{
476#ifndef __ia64__
477	const char *fname;
478	int fdesc, n;
479	struct stat sb;
480
481	fname = b_flag ? b_flag : "/boot/mbr";
482	if ((fdesc = open(fname, O_RDONLY)) == -1 ||
483	    fstat(fdesc, &sb) == -1)
484		err(1, "%s", fname);
485	if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
486		errx(1, "%s: length must be a multiple of sector size", fname);
487	if (mboot.bootinst != NULL)
488		free(mboot.bootinst);
489	if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
490		errx(1, "%s: unable to allocate read buffer", fname);
491	if ((n = read(fdesc, mboot.bootinst, mboot.bootinst_size)) == -1 ||
492	    close(fdesc))
493		err(1, "%s", fname);
494	if (n != mboot.bootinst_size)
495		errx(1, "%s: short read", fname);
496#else
497	if (mboot.bootinst != NULL)
498		free(mboot.bootinst);
499	mboot.bootinst_size = secsize;
500	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL)
501		errx(1, "unable to allocate boot block buffer");
502	memset(mboot.bootinst, 0, mboot.bootinst_size);
503	le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC);
504#endif
505}
506
507
508static void
509init_sector0(unsigned long start)
510{
511	struct dos_partition *partp = (struct dos_partition *) (&mboot.parts[0]);
512
513	init_boot();
514
515	partp->dp_typ = DOSPTYP_386BSD;
516	partp->dp_flag = ACTIVE;
517	start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors;
518	if(start == 0)
519		start = dos_sectors;
520	partp->dp_start = start;
521	partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start;
522
523	dos(partp);
524}
525
526static void
527change_part(int i)
528{
529	struct dos_partition *partp = ((struct dos_partition *) &mboot.parts) + i - 1;
530
531    printf("The data for partition %d is:\n", i);
532    print_part(i);
533
534    if (u_flag && ok("Do you want to change it?")) {
535	int tmp;
536
537	if (i_flag) {
538		bzero((char *)partp, sizeof (struct dos_partition));
539		if (i == 1) {
540			init_sector0(1);
541			printf("\nThe static data for the slice 1 has been reinitialized to:\n");
542			print_part(i);
543		}
544	}
545
546	do {
547		Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp);
548		Decimal("start", partp->dp_start, tmp);
549		Decimal("size", partp->dp_size, tmp);
550		if (!sanitize_partition(partp)) {
551			warnx("ERROR: failed to adjust; setting sysid to 0");
552			partp->dp_typ = 0;
553		}
554
555		if (ok("Explicitly specify beg/end address ?"))
556		{
557			int	tsec,tcyl,thd;
558			tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
559			thd = partp->dp_shd;
560			tsec = DPSECT(partp->dp_ssect);
561			Decimal("beginning cylinder", tcyl, tmp);
562			Decimal("beginning head", thd, tmp);
563			Decimal("beginning sector", tsec, tmp);
564			partp->dp_scyl = DOSCYL(tcyl);
565			partp->dp_ssect = DOSSECT(tsec,tcyl);
566			partp->dp_shd = thd;
567
568			tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
569			thd = partp->dp_ehd;
570			tsec = DPSECT(partp->dp_esect);
571			Decimal("ending cylinder", tcyl, tmp);
572			Decimal("ending head", thd, tmp);
573			Decimal("ending sector", tsec, tmp);
574			partp->dp_ecyl = DOSCYL(tcyl);
575			partp->dp_esect = DOSSECT(tsec,tcyl);
576			partp->dp_ehd = thd;
577		} else
578			dos(partp);
579
580		print_part(i);
581	} while (!ok("Are we happy with this entry?"));
582    }
583    }
584
585static void
586print_params()
587{
588	printf("parameters extracted from in-core disklabel are:\n");
589	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
590			,cyls,heads,sectors,cylsecs);
591	if((dos_sectors > 63) || (dos_cyls > 1023) || (dos_heads > 255))
592		printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
593	printf("parameters to be used for BIOS calculations are:\n");
594	printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
595		,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
596}
597
598static void
599change_active(int which)
600{
601	struct dos_partition *partp = &mboot.parts[0];
602	int active, i, new, tmp;
603
604	active = -1;
605	for (i = 0; i < NDOSPART; i++) {
606		if ((partp[i].dp_flag & ACTIVE) == 0)
607			continue;
608		printf("Partition %d is marked active\n", i + 1);
609		if (active == -1)
610			active = i + 1;
611	}
612	if (a_flag && which != -1)
613		active = which;
614	else if (active == -1)
615		active = 1;
616
617	if (!ok("Do you want to change the active partition?"))
618		return;
619setactive:
620	do {
621		new = active;
622		Decimal("active partition", new, tmp);
623		if (new < 1 || new > 4) {
624			printf("Active partition number must be in range 1-4."
625					"  Try again.\n");
626			goto setactive;
627		}
628		active = new;
629	} while (!ok("Are you happy with this choice"));
630	for (i = 0; i < NDOSPART; i++)
631		partp[i].dp_flag = 0;
632	if (active > 0 && active <= NDOSPART)
633		partp[active-1].dp_flag = ACTIVE;
634}
635
636static void
637change_code()
638{
639	if (ok("Do you want to change the boot code?"))
640		init_boot();
641}
642
643void
644get_params_to_use()
645{
646	int	tmp;
647	print_params();
648	if (ok("Do you want to change our idea of what BIOS thinks ?"))
649	{
650		do
651		{
652			Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
653			Decimal("BIOS's idea of #heads", dos_heads, tmp);
654			Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
655			dos_cylsecs = dos_heads * dos_sectors;
656			print_params();
657		}
658		while(!ok("Are you happy with this choice"));
659	}
660}
661
662
663/***********************************************\
664* Change real numbers into strange dos numbers	*
665\***********************************************/
666static void
667dos(struct dos_partition *partp)
668{
669	int cy, sec;
670	u_int32_t end;
671
672	if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) {
673		memcpy(partp, &mtpart, sizeof(*partp));
674		return;
675	}
676
677	/* Start c/h/s. */
678	partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors;
679	cy = partp->dp_start / dos_cylsecs;
680	sec = partp->dp_start % dos_sectors + 1;
681	partp->dp_scyl = DOSCYL(cy);
682	partp->dp_ssect = DOSSECT(sec, cy);
683
684	/* End c/h/s. */
685	end = partp->dp_start + partp->dp_size - 1;
686	partp->dp_ehd = end % dos_cylsecs / dos_sectors;
687	cy = end / dos_cylsecs;
688	sec = end % dos_sectors + 1;
689	partp->dp_ecyl = DOSCYL(cy);
690	partp->dp_esect = DOSSECT(sec, cy);
691}
692
693static int
694open_disk(int flag)
695{
696	struct stat 	st;
697	int rwmode, p;
698	char *s;
699
700	fdw = -1;
701	if (stat(disk, &st) == -1) {
702		if (errno == ENOENT)
703			return -2;
704		warnx("can't get file status of %s", disk);
705		return -1;
706	}
707	if ( !(st.st_mode & S_IFCHR) )
708		warnx("device %s is not character special", disk);
709	rwmode = a_flag || I_flag || B_flag || flag ? O_RDWR : O_RDONLY;
710	fd = open(disk, rwmode);
711	if (fd == -1 && errno == ENXIO)
712		return -2;
713	if (fd == -1 && errno == EPERM && rwmode == O_RDWR) {
714		fd = open(disk, O_RDONLY);
715		if (fd == -1)
716			return -3;
717		for (p = 1; p < 5; p++) {
718			asprintf(&s, "%ss%d", disk, p);
719			fdw = open(s, O_RDONLY);
720			free(s);
721			if (fdw == -1)
722				continue;
723			break;
724		}
725		if (fdw == -1)
726			return -4;
727	}
728	if (fd == -1) {
729		warnx("can't open device %s", disk);
730		return -1;
731	}
732	if (get_params() == -1) {
733		warnx("can't get disk parameters on %s", disk);
734		return -1;
735	}
736	return fd;
737}
738
739static ssize_t
740read_disk(off_t sector, void *buf)
741{
742	lseek(fd,(sector * 512), 0);
743	if( secsize == 0 )
744		for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
745			{
746			/* try the read */
747			int size = read(fd, buf, secsize);
748			if( size == secsize )
749				/* it worked so return */
750				return secsize;
751			}
752	else
753		return read( fd, buf, secsize );
754
755	/* we failed to read at any of the sizes */
756	return -1;
757}
758
759static ssize_t
760write_disk(off_t sector, void *buf)
761{
762
763	if (fdw != -1) {
764		return ioctl(fdw, DIOCSMBR, buf);
765	} else {
766		lseek(fd,(sector * 512), 0);
767		/* write out in the size that the read_disk found worked */
768		return write(fd, buf, secsize);
769	}
770}
771
772static int
773get_params()
774{
775	int error;
776	u_int u;
777	off_t o;
778
779	error = ioctl(fd, DIOCGFWSECTORS, &u);
780	if (error == 0)
781		sectors = dos_sectors = u;
782	else
783		sectors = dos_sectors = 63;
784
785	error = ioctl(fd, DIOCGFWHEADS, &u);
786	if (error == 0)
787		heads = dos_heads = u;
788	else
789		heads = dos_heads = 255;
790
791	dos_cylsecs = cylsecs = heads * sectors;
792	disksecs = cyls * heads * sectors;
793
794	error = ioctl(fd, DIOCGSECTORSIZE, &u);
795	if (error != 0 || u == 0)
796		u = 512;
797
798	error = ioctl(fd, DIOCGMEDIASIZE, &o);
799	if (error == 0) {
800		disksecs = o / u;
801		cyls = dos_cyls = o / (u * dos_heads * dos_sectors);
802	}
803
804	return (disksecs);
805}
806
807
808static int
809read_s0()
810{
811	int i;
812
813	mboot.bootinst_size = secsize;
814	if (mboot.bootinst != NULL)
815		free(mboot.bootinst);
816	if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
817		warnx("unable to allocate buffer to read fdisk "
818		      "partition table");
819		return -1;
820	}
821	if (read_disk(0, mboot.bootinst) == -1) {
822		warnx("can't read fdisk partition table");
823		return -1;
824	}
825	if (le16dec(&mboot.bootinst[DOSMAGICOFFSET]) != DOSMAGIC) {
826		warnx("invalid fdisk partition table found");
827		/* So should we initialize things */
828		return -1;
829	}
830	for (i = 0; i < NDOSPART; i++)
831		dos_partition_dec(
832		    &mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
833		    &mboot.parts[i]);
834	return 0;
835}
836
837static int
838write_s0()
839{
840	int	sector, i;
841
842	if (iotest) {
843		print_s0(-1);
844		return 0;
845	}
846	for(i = 0; i < NDOSPART; i++)
847		dos_partition_enc(&mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE],
848		    &mboot.parts[i]);
849	le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC);
850	for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
851		if (write_disk(sector,
852			       &mboot.bootinst[sector * secsize]) == -1) {
853			warn("can't write fdisk partition table");
854			return -1;
855		}
856	return(0);
857}
858
859
860static int
861ok(const char *str)
862{
863	printf("%s [n] ", str);
864	fflush(stdout);
865	if (fgets(lbuf, LBUF, stdin) == NULL)
866		exit(1);
867	lbuf[strlen(lbuf)-1] = 0;
868
869	if (*lbuf &&
870		(!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
871		 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
872		return 1;
873	else
874		return 0;
875}
876
877static int
878decimal(const char *str, int *num, int deflt)
879{
880	int acc = 0, c;
881	char *cp;
882
883	while (1) {
884		printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
885		fflush(stdout);
886		if (fgets(lbuf, LBUF, stdin) == NULL)
887			exit(1);
888		lbuf[strlen(lbuf)-1] = 0;
889
890		if (!*lbuf)
891			return 0;
892
893		cp = lbuf;
894		while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
895		if (!c)
896			return 0;
897		while ((c = *cp++)) {
898			if (c <= '9' && c >= '0')
899				acc = acc * 10 + c - '0';
900			else
901				break;
902		}
903		if (c == ' ' || c == '\t')
904			while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
905		if (!c) {
906			*num = acc;
907			return 1;
908		} else
909			printf("%s is an invalid decimal number.  Try again.\n",
910				lbuf);
911	}
912
913}
914
915static const char *
916get_type(int type)
917{
918	int	numentries = (sizeof(part_types)/sizeof(struct part_type));
919	int	counter = 0;
920	struct	part_type *ptr = part_types;
921
922
923	while(counter < numentries) {
924		if(ptr->type == type)
925			return(ptr->name);
926		ptr++;
927		counter++;
928	}
929	return("unknown");
930}
931
932
933static void
934parse_config_line(char *line, CMD *command)
935{
936    char	*cp, *end;
937
938    cp = line;
939    while (1) {
940	memset(command, 0, sizeof(*command));
941
942	while (isspace(*cp)) ++cp;
943	if (*cp == '\0' || *cp == '#')
944	    break;
945	command->cmd = *cp++;
946
947	/*
948	 * Parse args
949	 */
950	    while (1) {
951	    while (isspace(*cp)) ++cp;
952	    if (*cp == '#')
953		break;		/* found comment */
954	    if (isalpha(*cp))
955		command->args[command->n_args].argtype = *cp++;
956	    if (!isdigit(*cp))
957		break;		/* assume end of line */
958	    end = NULL;
959	    command->args[command->n_args].arg_val = strtol(cp, &end, 0);
960	    if (cp == end)
961		break;		/* couldn't parse number */
962	    cp = end;
963	    command->n_args++;
964	}
965	break;
966    }
967}
968
969
970static int
971process_geometry(CMD *command)
972{
973    int		status = 1, i;
974
975    while (1) {
976	geom_processed = 1;
977	    if (part_processed) {
978	    warnx(
979	"ERROR line %d: the geometry specification line must occur before\n\
980    all partition specifications",
981		    current_line_number);
982	    status = 0;
983	    break;
984	}
985	    if (command->n_args != 3) {
986	    warnx("ERROR line %d: incorrect number of geometry args",
987		    current_line_number);
988	    status = 0;
989	    break;
990	}
991	    dos_cyls = 0;
992	    dos_heads = 0;
993	    dos_sectors = 0;
994	    for (i = 0; i < 3; ++i) {
995		    switch (command->args[i].argtype) {
996	    case 'c':
997		dos_cyls = command->args[i].arg_val;
998		break;
999	    case 'h':
1000		dos_heads = command->args[i].arg_val;
1001		break;
1002	    case 's':
1003		dos_sectors = command->args[i].arg_val;
1004		break;
1005	    default:
1006		warnx(
1007		"ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1008			current_line_number, command->args[i].argtype,
1009			command->args[i].argtype);
1010		status = 0;
1011		break;
1012	    }
1013	}
1014	if (status == 0)
1015	    break;
1016
1017	dos_cylsecs = dos_heads * dos_sectors;
1018
1019	/*
1020	 * Do sanity checks on parameter values
1021	 */
1022	    if (dos_cyls == 0) {
1023	    warnx("ERROR line %d: number of cylinders not specified",
1024		    current_line_number);
1025	    status = 0;
1026	}
1027	    if (dos_cyls > 1024) {
1028	    warnx(
1029	"WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1030    (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1031    is dedicated to FreeBSD)",
1032		    current_line_number, dos_cyls);
1033	}
1034
1035	    if (dos_heads == 0) {
1036	    warnx("ERROR line %d: number of heads not specified",
1037		    current_line_number);
1038	    status = 0;
1039	    } else if (dos_heads > 256) {
1040	    warnx("ERROR line %d: number of heads must be within (1-256)",
1041		    current_line_number);
1042	    status = 0;
1043	}
1044
1045	    if (dos_sectors == 0) {
1046	    warnx("ERROR line %d: number of sectors not specified",
1047		    current_line_number);
1048	    status = 0;
1049	    } else if (dos_sectors > 63) {
1050	    warnx("ERROR line %d: number of sectors must be within (1-63)",
1051		    current_line_number);
1052	    status = 0;
1053	}
1054
1055	break;
1056    }
1057    return (status);
1058}
1059
1060
1061static int
1062process_partition(CMD *command)
1063{
1064    int				status = 0, partition;
1065    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1066    u_int32_t			adj_size, max_end;
1067    struct dos_partition	*partp;
1068
1069	while (1) {
1070	part_processed = 1;
1071		if (command->n_args != 4) {
1072	    warnx("ERROR line %d: incorrect number of partition args",
1073		    current_line_number);
1074	    break;
1075	}
1076	partition = command->args[0].arg_val;
1077		if (partition < 1 || partition > 4) {
1078	    warnx("ERROR line %d: invalid partition number %d",
1079		    current_line_number, partition);
1080	    break;
1081	}
1082	partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1083	bzero((char *)partp, sizeof (struct dos_partition));
1084	partp->dp_typ = command->args[1].arg_val;
1085	partp->dp_start = command->args[2].arg_val;
1086	partp->dp_size = command->args[3].arg_val;
1087	max_end = partp->dp_start + partp->dp_size;
1088
1089		if (partp->dp_typ == 0) {
1090	    /*
1091	     * Get out, the partition is marked as unused.
1092	     */
1093	    /*
1094	     * Insure that it's unused.
1095	     */
1096	    bzero((char *)partp, sizeof (struct dos_partition));
1097	    status = 1;
1098	    break;
1099	}
1100
1101	/*
1102	 * Adjust start upwards, if necessary, to fall on a head boundary.
1103	 */
1104		if (partp->dp_start % dos_sectors != 0) {
1105	    prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1106	    if (max_end < dos_sectors ||
1107			    prev_head_boundary > max_end - dos_sectors) {
1108		/*
1109		 * Can't go past end of partition
1110		 */
1111		warnx(
1112	"ERROR line %d: unable to adjust start of partition %d to fall on\n\
1113    a head boundary",
1114			current_line_number, partition);
1115		break;
1116	    }
1117	    warnx(
1118	"WARNING: adjusting start offset of partition %d\n\
1119    from %u to %u, to fall on a head boundary",
1120		    partition, (u_int)partp->dp_start,
1121		    (u_int)(prev_head_boundary + dos_sectors));
1122	    partp->dp_start = prev_head_boundary + dos_sectors;
1123	}
1124
1125	/*
1126	 * Adjust size downwards, if necessary, to fall on a cylinder
1127	 * boundary.
1128	 */
1129	prev_cyl_boundary =
1130	    ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1131	if (prev_cyl_boundary > partp->dp_start)
1132	    adj_size = prev_cyl_boundary - partp->dp_start;
1133		else {
1134	    warnx(
1135	"ERROR: could not adjust partition to start on a head boundary\n\
1136    and end on a cylinder boundary.");
1137	    return (0);
1138	}
1139		if (adj_size != partp->dp_size) {
1140	    warnx(
1141	"WARNING: adjusting size of partition %d from %u to %u\n\
1142    to end on a cylinder boundary",
1143		    partition, (u_int)partp->dp_size, (u_int)adj_size);
1144	    partp->dp_size = adj_size;
1145	}
1146		if (partp->dp_size == 0) {
1147	    warnx("ERROR line %d: size of partition %d is zero",
1148		    current_line_number, partition);
1149	    break;
1150	}
1151
1152	dos(partp);
1153	status = 1;
1154	break;
1155    }
1156    return (status);
1157}
1158
1159
1160static int
1161process_active(CMD *command)
1162{
1163    int				status = 0, partition, i;
1164    struct dos_partition	*partp;
1165
1166	while (1) {
1167	active_processed = 1;
1168		if (command->n_args != 1) {
1169	    warnx("ERROR line %d: incorrect number of active args",
1170		    current_line_number);
1171	    status = 0;
1172	    break;
1173	}
1174	partition = command->args[0].arg_val;
1175		if (partition < 1 || partition > 4) {
1176	    warnx("ERROR line %d: invalid partition number %d",
1177		    current_line_number, partition);
1178	    break;
1179	}
1180	/*
1181	 * Reset active partition
1182	 */
1183	partp = ((struct dos_partition *) &mboot.parts);
1184	for (i = 0; i < NDOSPART; i++)
1185	    partp[i].dp_flag = 0;
1186	partp[partition-1].dp_flag = ACTIVE;
1187
1188	status = 1;
1189	break;
1190    }
1191    return (status);
1192}
1193
1194
1195static int
1196process_line(char *line)
1197{
1198    CMD		command;
1199    int		status = 1;
1200
1201	while (1) {
1202	parse_config_line(line, &command);
1203		switch (command.cmd) {
1204	case 0:
1205	    /*
1206	     * Comment or blank line
1207	     */
1208	    break;
1209	case 'g':
1210	    /*
1211	     * Set geometry
1212	     */
1213	    status = process_geometry(&command);
1214	    break;
1215	case 'p':
1216	    status = process_partition(&command);
1217	    break;
1218	case 'a':
1219	    status = process_active(&command);
1220	    break;
1221	default:
1222	    status = 0;
1223	    break;
1224	}
1225	break;
1226    }
1227    return (status);
1228}
1229
1230
1231static int
1232read_config(char *config_file)
1233{
1234    FILE	*fp = NULL;
1235    int		status = 1;
1236    char	buf[1010];
1237
1238	while (1) {
1239		if (strcmp(config_file, "-") != 0) {
1240	    /*
1241	     * We're not reading from stdin
1242	     */
1243			if ((fp = fopen(config_file, "r")) == NULL) {
1244		status = 0;
1245		break;
1246	    }
1247		} else {
1248	    fp = stdin;
1249	}
1250	current_line_number = 0;
1251		while (!feof(fp)) {
1252	    if (fgets(buf, sizeof(buf), fp) == NULL)
1253		break;
1254	    ++current_line_number;
1255	    status = process_line(buf);
1256	    if (status == 0)
1257		break;
1258	    }
1259	break;
1260    }
1261	if (fp) {
1262	/*
1263	 * It doesn't matter if we're reading from stdin, as we've reached EOF
1264	 */
1265	fclose(fp);
1266    }
1267    return (status);
1268}
1269
1270
1271static void
1272reset_boot(void)
1273{
1274    int				i;
1275    struct dos_partition	*partp;
1276
1277    init_boot();
1278	for (i = 0; i < 4; ++i) {
1279	partp = ((struct dos_partition *) &mboot.parts) + i;
1280	bzero((char *)partp, sizeof (struct dos_partition));
1281    }
1282}
1283
1284static int
1285sanitize_partition(struct dos_partition *partp)
1286{
1287    u_int32_t			prev_head_boundary, prev_cyl_boundary;
1288    u_int32_t			max_end, size, start;
1289
1290    start = partp->dp_start;
1291    size = partp->dp_size;
1292    max_end = start + size;
1293    /* Only allow a zero size if the partition is being marked unused. */
1294    if (size == 0) {
1295	if (start == 0 && partp->dp_typ == 0)
1296	    return (1);
1297	warnx("ERROR: size of partition is zero");
1298	return (0);
1299    }
1300    /* Return if no adjustment is necessary. */
1301    if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0)
1302	return (1);
1303
1304    if (start == 0) {
1305	    warnx("WARNING: partition overlaps with partition table");
1306	    if (ok("Correct this automatically?"))
1307		    start = dos_sectors;
1308    }
1309    if (start % dos_sectors != 0)
1310	warnx("WARNING: partition does not start on a head boundary");
1311    if ((start  +size) % dos_sectors != 0)
1312	warnx("WARNING: partition does not end on a cylinder boundary");
1313    warnx("WARNING: this may confuse the BIOS or some operating systems");
1314    if (!ok("Correct this automatically?"))
1315	return (1);
1316
1317    /*
1318     * Adjust start upwards, if necessary, to fall on a head boundary.
1319     */
1320    if (start % dos_sectors != 0) {
1321	prev_head_boundary = start / dos_sectors * dos_sectors;
1322	if (max_end < dos_sectors ||
1323	    prev_head_boundary >= max_end - dos_sectors) {
1324	    /*
1325	     * Can't go past end of partition
1326	     */
1327	    warnx(
1328    "ERROR: unable to adjust start of partition to fall on a head boundary");
1329	    return (0);
1330        }
1331	start = prev_head_boundary + dos_sectors;
1332    }
1333
1334    /*
1335     * Adjust size downwards, if necessary, to fall on a cylinder
1336     * boundary.
1337     */
1338    prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs;
1339    if (prev_cyl_boundary > start)
1340	size = prev_cyl_boundary - start;
1341    else {
1342	warnx("ERROR: could not adjust partition to start on a head boundary\n\
1343    and end on a cylinder boundary.");
1344	return (0);
1345    }
1346
1347    /* Finally, commit any changes to partp and return. */
1348    if (start != partp->dp_start) {
1349	warnx("WARNING: adjusting start offset of partition to %u",
1350	    (u_int)start);
1351	partp->dp_start = start;
1352    }
1353    if (size != partp->dp_size) {
1354	warnx("WARNING: adjusting size of partition to %u", (u_int)size);
1355	partp->dp_size = size;
1356    }
1357
1358    return (1);
1359}
1360
1361/*
1362 * Try figuring out the root device's canonical disk name.
1363 * The following choices are considered:
1364 *   /dev/ad0s1a     => /dev/ad0
1365 *   /dev/da0a       => /dev/da0
1366 *   /dev/vinum/root => /dev/vinum/root
1367 */
1368static char *
1369get_rootdisk(void)
1370{
1371	struct statfs rootfs;
1372	regex_t re;
1373#define NMATCHES 2
1374	regmatch_t rm[NMATCHES];
1375	char *s;
1376	int rv;
1377
1378	if (statfs("/", &rootfs) == -1)
1379		err(1, "statfs(\"/\")");
1380
1381	if ((rv = regcomp(&re, "^(/dev/[a-z]+[0-9]+)([sp][0-9]+)?[a-h]?$",
1382		    REG_EXTENDED)) != 0)
1383		errx(1, "regcomp() failed (%d)", rv);
1384	if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0)
1385		errx(1,
1386"mounted root fs resource doesn't match expectations (regexec returned %d)",
1387		    rv);
1388	if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL)
1389		errx(1, "out of memory");
1390	memcpy(s, rootfs.f_mntfromname + rm[1].rm_so,
1391	    rm[1].rm_eo - rm[1].rm_so);
1392	s[rm[1].rm_eo - rm[1].rm_so] = 0;
1393
1394	return s;
1395}
1396