Home | History | Annotate | Line # | Download | only in fdisk
fdisk.c revision 1.155
      1  1.155     sevan /*	$NetBSD: fdisk.c,v 1.155 2018/08/27 14:55:46 sevan Exp $ */
      2   1.10       cgd 
      3    1.4   mycroft /*
      4    1.1       cgd  * Mach Operating System
      5    1.1       cgd  * Copyright (c) 1992 Carnegie Mellon University
      6    1.1       cgd  * All Rights Reserved.
      7    1.4   mycroft  *
      8    1.1       cgd  * Permission to use, copy, modify and distribute this software and its
      9    1.1       cgd  * documentation is hereby granted, provided that both the copyright
     10    1.1       cgd  * notice and this permission notice appear in all copies of the
     11    1.1       cgd  * software, derivative works or modified versions, and any portions
     12    1.1       cgd  * thereof, and that both notices appear in supporting documentation.
     13    1.4   mycroft  *
     14    1.1       cgd  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     15    1.1       cgd  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
     16    1.1       cgd  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     17    1.4   mycroft  *
     18    1.1       cgd  * Carnegie Mellon requests users of this software to return to
     19    1.4   mycroft  *
     20    1.1       cgd  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     21    1.1       cgd  *  School of Computer Science
     22    1.1       cgd  *  Carnegie Mellon University
     23    1.1       cgd  *  Pittsburgh PA 15213-3890
     24    1.4   mycroft  *
     25    1.1       cgd  * any improvements or extensions that they make and grant Carnegie Mellon
     26    1.1       cgd  * the rights to redistribute these changes.
     27    1.1       cgd  */
     28    1.1       cgd 
     29   1.62       dsl /*
     30   1.62       dsl  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
     31   1.62       dsl  *	Copyright (c) 1989	Robert. V. Baron
     32   1.62       dsl  *	Created.
     33   1.62       dsl  */
     34   1.62       dsl 
     35   1.91    dyoung #if HAVE_NBTOOL_CONFIG_H
     36   1.91    dyoung #include "nbtool_config.h"
     37   1.91    dyoung #endif
     38   1.91    dyoung 
     39   1.16      phil #include <sys/cdefs.h>
     40   1.16      phil 
     41    1.2   mycroft #ifndef lint
     42  1.155     sevan __RCSID("$NetBSD: fdisk.c,v 1.155 2018/08/27 14:55:46 sevan Exp $");
     43    1.2   mycroft #endif /* not lint */
     44    1.2   mycroft 
     45   1.85  christos #define MBRPTYPENAMES
     46    1.1       cgd #include <sys/types.h>
     47   1.91    dyoung #include <sys/param.h>
     48   1.91    dyoung #include <sys/stat.h>
     49    1.8       cgd #include <ctype.h>
     50    1.4   mycroft #include <err.h>
     51   1.18     lukem #include <errno.h>
     52    1.1       cgd #include <fcntl.h>
     53   1.18     lukem #include <paths.h>
     54   1.71     lukem #include <stdarg.h>
     55   1.71     lukem #include <stddef.h>
     56    1.4   mycroft #include <stdio.h>
     57    1.4   mycroft #include <stdlib.h>
     58    1.8       cgd #include <string.h>
     59    1.8       cgd #include <unistd.h>
     60  1.103       apb #include <vis.h>
     61  1.154     joerg #include <zlib.h>
     62   1.91    dyoung 
     63  1.109       dsl #if !HAVE_NBTOOL_CONFIG_H
     64  1.109       dsl #include <sys/disklabel.h>
     65  1.121  christos #include <sys/disklabel_gpt.h>
     66  1.109       dsl #include <sys/bootblock.h>
     67  1.109       dsl #include <sys/ioctl.h>
     68  1.109       dsl #include <sys/sysctl.h>
     69   1.91    dyoung #include <disktab.h>
     70   1.19     lukem #include <util.h>
     71  1.109       dsl #else
     72  1.109       dsl #include <nbinclude/sys/disklabel.h>
     73  1.121  christos #include <nbinclude/sys/disklabel_gpt.h>
     74  1.109       dsl #include <nbinclude/sys/bootblock.h>
     75  1.109       dsl #include "../../include/disktab.h"
     76  1.109       dsl /* We enforce -F, so none of these possibly undefined items can be needed */
     77  1.109       dsl #define opendisk(path, fl, buf, buflen, cooked) (-1)
     78   1.91    dyoung #endif /* HAVE_NBTOOL_CONFIG_H */
     79    1.1       cgd 
     80  1.142   tsutsui #ifndef	DEFAULT_BOOTDIR
     81   1.72     lukem #define	DEFAULT_BOOTDIR		"/usr/mdec"
     82  1.142   tsutsui #endif
     83   1.72     lukem 
     84   1.96       dsl #define	LE_MBR_MAGIC		htole16(MBR_MAGIC)
     85   1.96       dsl #define	LE_MBR_BS_MAGIC		htole16(MBR_BS_MAGIC)
     86   1.96       dsl 
     87   1.97    dyoung #ifdef BOOTSEL
     88   1.71     lukem 
     89   1.71     lukem #define	DEFAULT_BOOTCODE	"mbr"
     90   1.71     lukem #define	DEFAULT_BOOTSELCODE	"mbr_bootsel"
     91   1.71     lukem #define	DEFAULT_BOOTEXTCODE	"mbr_ext"
     92   1.71     lukem 
     93   1.71     lukem /* Scan values for the various keys we use, as returned by the BIOS */
     94   1.71     lukem #define	SCAN_ENTER	0x1c
     95   1.71     lukem #define	SCAN_F1		0x3b
     96   1.71     lukem #define	SCAN_1		0x2
     97   1.71     lukem 
     98  1.121  christos 
     99  1.115       dsl #define	MAX_BIOS_DISKS	16	/* Going beyond F12 is hard though! */
    100  1.115       dsl 
    101  1.115       dsl /* We same the dflt 'boot partition' as a disk block, with some magic values. */
    102  1.115       dsl #define DEFAULT_ACTIVE	(~(daddr_t)0)
    103  1.115       dsl #define	DEFAULT_DISK(n)	(DEFAULT_ACTIVE - MAX_BIOS_DISKS + (n))
    104  1.115       dsl 
    105   1.34      fvdl #endif
    106   1.34      fvdl 
    107  1.122  christos #define GPT_TYPE(offs) ((offs) == GPT_HDR_BLKNO ?  "primary" : "secondary")
    108  1.122  christos 
    109   1.69       dsl #ifndef PRIdaddr
    110   1.69       dsl #define PRIdaddr PRId64
    111   1.69       dsl #endif
    112   1.69       dsl 
    113   1.39      soda #ifndef _PATH_DEFDISK
    114   1.62       dsl #define _PATH_DEFDISK	"/dev/rwd0d"
    115   1.39      soda #endif
    116   1.39      soda 
    117   1.62       dsl struct {
    118   1.71     lukem 	struct mbr_sector *ptn;		/* array of pbrs */
    119   1.62       dsl 	daddr_t		base;		/* first sector of ext. ptn */
    120   1.62       dsl 	daddr_t		limit;		/* last sector of ext. ptn */
    121   1.62       dsl 	int		num_ptn;	/* number of contained partitions */
    122   1.62       dsl 	int		ptn_id;		/* entry in mbr */
    123   1.62       dsl 	int		is_corrupt;	/* 1 if extended chain illegal */
    124   1.62       dsl } ext;
    125    1.1       cgd 
    126  1.127       dsl #define LBUF 100
    127  1.127       dsl static char lbuf[LBUF];
    128  1.127       dsl 
    129  1.132     joerg static const char *disk = _PATH_DEFDISK;
    130  1.127       dsl 
    131  1.132     joerg static struct disklabel disklabel;		/* disk parameters */
    132  1.127       dsl 
    133  1.132     joerg static struct mbr_sector mboot;
    134  1.127       dsl 
    135  1.132     joerg static const char *boot_dir = DEFAULT_BOOTDIR;
    136  1.132     joerg static char *boot_path = NULL;			/* name of file we actually opened */
    137    1.1       cgd 
    138   1.62       dsl #ifdef BOOTSEL
    139  1.129       dsl #define BOOTSEL_OPTIONS	"B"
    140   1.34      fvdl #else
    141  1.129       dsl #define BOOTSEL_OPTIONS
    142   1.62       dsl #define change_part(e, p, id, st, sz, bm) change__part(e, p, id, st, sz)
    143   1.30        ws #endif
    144  1.140  christos #define OPTIONS	BOOTSEL_OPTIONS "0123FSafiIluvA:b:c:E:r:s:w:z:"
    145   1.30        ws 
    146  1.127       dsl /*
    147  1.127       dsl  * Disk geometry and partition alignment.
    148  1.127       dsl  *
    149  1.127       dsl  * Modern disks do not have a fixed geomery and will always give a 'faked'
    150  1.127       dsl  * geometry that matches the ATA standard - max 16 heads and 256 sec/track.
    151  1.127       dsl  * The ATA geometry allows access to 2^28 sectors (as does LBA mode).
    152  1.127       dsl  *
    153  1.127       dsl  * The BIOS calls originally used an 8bit register for cylinder, head and
    154  1.127       dsl  * sector. Later 2 bits were stolen from the sector number and added to
    155  1.127       dsl  * cylinder number. The BIOS will translate this faked geometry either to
    156  1.127       dsl  * the geometry reported by the disk, or do LBA reads (possibly LBA48).
    157  1.127       dsl  * BIOS CHS reads have all sorts of limits, but 2^24 is absolute.
    158  1.127       dsl  * For historic reasons the BIOS geometry is the called the dos geometry!
    159  1.127       dsl  *
    160  1.127       dsl  * If you know the disks real geometry it is usually worth aligning
    161  1.127       dsl  * disk partitions to cylinder boundaries (certainly traditional!).
    162  1.127       dsl  * For 'mbr' disks this has always been done with the BIOS geometry.
    163  1.127       dsl  * The first track (typically 63 sectors) is reserved because the first
    164  1.127       dsl  * sector is used for boot code. Similarly the data partition in an
    165  1.127       dsl  * extended partition will start one track in. If an extended partition
    166  1.127       dsl  * starts at the beginning of the disk you lose 2 tracks.
    167  1.127       dsl  *
    168  1.127       dsl  * However non-magnetic media in particular has physical sectors that are
    169  1.127       dsl  * not the same size as those reported, so has to do read modify write
    170  1.127       dsl  * sequences for misaligned transfers. The alignment of partitions to
    171  1.127       dsl  * cylinder boundaries makes this happen all the time.
    172  1.127       dsl  *
    173  1.127       dsl  * It is thus sensible to align partitions on a sensible sector boundary.
    174  1.127       dsl  * For instance 1MB (2048 sectors).
    175  1.127       dsl  * Common code can do this by using a geometry with 1 head and 2048
    176  1.127       dsl  * sectors per track.
    177  1.127       dsl  */
    178  1.127       dsl 
    179  1.127       dsl /* Disks reported geometry and overall size from device driver */
    180  1.132     joerg static unsigned int cylinders, sectors, heads;
    181  1.132     joerg static daddr_t disksectors;
    182  1.127       dsl #define cylindersectors (heads * sectors)
    183  1.127       dsl 
    184  1.127       dsl /* Geometry from the BIOS */
    185  1.132     joerg static unsigned int dos_cylinders;
    186  1.132     joerg static unsigned int dos_heads;
    187  1.132     joerg static unsigned int dos_sectors;
    188  1.132     joerg static daddr_t dos_disksectors;
    189   1.62       dsl #define dos_cylindersectors (dos_heads * dos_sectors)
    190   1.62       dsl #define dos_totalsectors (dos_heads * dos_sectors * dos_cylinders)
    191    1.1       cgd 
    192    1.4   mycroft #define DOSSECT(s,c)	(((s) & 0x3f) | (((c) >> 2) & 0xc0))
    193    1.4   mycroft #define DOSCYL(c)	((c) & 0xff)
    194  1.145  jakllsch #define SEC_IN_1M (1024 * 1024 / secsize)
    195   1.90    dyoung #define SEC_TO_MB(sec) ((unsigned int)(((sec) + SEC_IN_1M / 2) / SEC_IN_1M))
    196   1.62       dsl #define SEC_TO_CYL(sec) (((sec) + dos_cylindersectors/2) / dos_cylindersectors)
    197   1.62       dsl 
    198   1.62       dsl #define MAXCYL		1024	/* Usual limit is 1023 */
    199   1.62       dsl #define	MAXHEAD		256	/* Usual limit is 255 */
    200   1.62       dsl #define	MAXSECTOR	63
    201  1.132     joerg static int partition = -1;
    202   1.28        ws 
    203  1.127       dsl /* Alignment of partition, and offset if first sector unusable */
    204  1.132     joerg static unsigned int ptn_alignment;	/* default dos_cylindersectors */
    205  1.132     joerg static unsigned int ptn_0_offset;	/* default dos_sectors */
    206  1.127       dsl 
    207  1.132     joerg static int fd = -1, wfd = -1, *rfd = &fd;
    208  1.132     joerg static char *disk_file = NULL;
    209  1.132     joerg static char *disk_type = NULL;
    210  1.132     joerg 
    211  1.132     joerg static int a_flag;		/* set active partition */
    212  1.132     joerg static int i_flag;		/* init bootcode */
    213  1.135  christos static int I_flag;		/* ignore errors */
    214  1.132     joerg static int u_flag;		/* update partition data */
    215  1.132     joerg static int v_flag;		/* more verbose */
    216  1.132     joerg static int sh_flag;		/* Output data as shell defines */
    217  1.132     joerg static int f_flag;		/* force --not interactive */
    218  1.132     joerg static int s_flag;		/* set id,offset,size */
    219  1.132     joerg static int b_flag;		/* Set cyl, heads, secs (as c/h/s) */
    220  1.132     joerg static int B_flag;		/* Edit/install bootselect code */
    221  1.132     joerg static int E_flag;		/* extended partition number */
    222  1.132     joerg static int b_cyl, b_head, b_sec;  /* b_flag values. */
    223  1.109       dsl 
    224  1.109       dsl #if !HAVE_NBTOOL_CONFIG_H
    225  1.132     joerg static int F_flag = 0;
    226  1.109       dsl #else
    227  1.109       dsl /* Tool - force 'file' mode to avoid unsupported functions and ioctls */
    228  1.132     joerg static int F_flag = 1;
    229  1.109       dsl #endif
    230    1.4   mycroft 
    231  1.132     joerg static struct gpt_hdr gpt1, gpt2;	/* GUID partition tables */
    232  1.121  christos 
    233  1.132     joerg static struct mbr_sector bootcode[8192 / sizeof (struct mbr_sector)];
    234  1.140  christos static ssize_t secsize = 512;	/* sector size */
    235  1.140  christos static char *iobuf;		/* buffer for non 512 sector I/O */
    236  1.132     joerg static int bootsize;		/* actual size of bootcode */
    237  1.132     joerg static int boot_installed;	/* 1 if we've copied code into the mbr */
    238   1.62       dsl 
    239  1.141   tsutsui #if defined(USE_DISKLIST)
    240  1.141   tsutsui #include <machine/cpu.h>
    241  1.132     joerg static struct disklist *dl;
    242   1.62       dsl #endif
    243   1.30        ws 
    244   1.43     lukem 
    245   1.85  christos #define KNOWN_SYSIDS	(sizeof(mbr_ptypes)/sizeof(mbr_ptypes[0]))
    246   1.50  christos 
    247  1.132     joerg __dead static void	usage(void);
    248  1.132     joerg static void	print_s0(int);
    249  1.132     joerg static void	print_part(struct mbr_sector *, int, daddr_t);
    250  1.132     joerg static void	print_mbr_partition(struct mbr_sector *, int, daddr_t, daddr_t, int);
    251  1.132     joerg static void	print_pbr(daddr_t, int, uint8_t);
    252  1.132     joerg static int	is_all_zero(const unsigned char *, size_t);
    253  1.132     joerg static void	printvis(int, const char *, const char *, size_t);
    254  1.132     joerg static int	read_boot(const char *, void *, size_t, int);
    255  1.132     joerg static void	init_sector0(int);
    256  1.132     joerg static void	intuit_translated_geometry(void);
    257  1.132     joerg static void	get_bios_geometry(void);
    258  1.132     joerg static void	get_extended_ptn(void);
    259  1.133  christos static void	get_ptn_alignmemt(void);
    260  1.130       dsl #if defined(USE_DISKLIST)
    261  1.132     joerg static void	get_diskname(const char *, char *, size_t);
    262  1.130       dsl #endif
    263  1.132     joerg static int	change_part(int, int, int, daddr_t, daddr_t, char *);
    264  1.132     joerg static void	print_geometry(void);
    265  1.132     joerg static int	first_active(void);
    266  1.132     joerg static void	change_active(int);
    267  1.132     joerg static void	change_bios_geometry(void);
    268  1.132     joerg static void	dos(int, unsigned char *, unsigned char *, unsigned char *);
    269  1.132     joerg static int	open_disk(int);
    270  1.140  christos static ssize_t	read_disk(daddr_t, void *);
    271  1.140  christos static ssize_t	write_disk(daddr_t, void *);
    272  1.132     joerg static int	get_params(void);
    273  1.132     joerg static int	read_s0(daddr_t, struct mbr_sector *);
    274  1.132     joerg static int	write_mbr(void);
    275  1.132     joerg static int	read_gpt(daddr_t, struct gpt_hdr *);
    276  1.132     joerg static int	delete_gpt(struct gpt_hdr *);
    277  1.139     joerg static int	yesno(const char *, ...) __printflike(1, 2);
    278  1.132     joerg static int64_t	decimal(const char *, int64_t, int, int64_t, int64_t);
    279   1.62       dsl #define DEC_SEC		1		/* asking for a sector number */
    280   1.62       dsl #define	DEC_RND		2		/* round to end of first track */
    281  1.129       dsl #define	DEC_RND_0	4		/* convert 0 to size of a track */
    282   1.62       dsl #define DEC_RND_DOWN	8		/* subtract 1 track */
    283   1.62       dsl #define DEC_RND_DOWN_2	16		/* subtract 2 tracks */
    284  1.132     joerg static int	ptn_id(const char *, int *);
    285  1.132     joerg static int	type_match(const void *, const void *);
    286  1.132     joerg static const char *get_type(int);
    287  1.132     joerg static int	get_mapping(int, unsigned int *, unsigned int *, unsigned int *, unsigned long *);
    288  1.132     joerg #ifdef BOOTSEL
    289  1.132     joerg static daddr_t	configure_bootsel(daddr_t);
    290  1.132     joerg static void	install_bootsel(int);
    291  1.132     joerg static daddr_t	get_default_boot(void);
    292  1.132     joerg static void	set_default_boot(daddr_t);
    293  1.134      gson static void	string(const char *, int, char *);
    294   1.34      fvdl #endif
    295   1.16      phil 
    296   1.91    dyoung static void
    297   1.91    dyoung initvar_disk(const char **diskp)
    298   1.91    dyoung {
    299  1.109       dsl #if !HAVE_NBTOOL_CONFIG_H
    300   1.91    dyoung 	int mib[2];
    301   1.91    dyoung 	size_t len;
    302   1.91    dyoung 	char *root_device;
    303   1.91    dyoung 
    304   1.91    dyoung 	mib[0] = CTL_KERN;
    305   1.91    dyoung 	mib[1] = KERN_ROOT_DEVICE;
    306   1.91    dyoung 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1 ||
    307   1.91    dyoung 	    (root_device = malloc(len)) == NULL ||
    308   1.91    dyoung 	    sysctl(mib, 2, root_device, &len, NULL, 0) == -1)
    309   1.91    dyoung 		return;
    310   1.91    dyoung 
    311   1.91    dyoung 	*diskp = root_device;
    312  1.109       dsl #endif /* HAVE_NBTOOL_CONFIG_H */
    313   1.91    dyoung }
    314   1.16      phil 
    315  1.149  christos static int
    316  1.149  christos getnum(const char *str, int *num)
    317  1.149  christos {
    318  1.149  christos 	char *e;
    319  1.149  christos 	long l;
    320  1.149  christos 
    321  1.149  christos 	errno = 0;
    322  1.149  christos 	l = strtol(str, &e, 0);
    323  1.149  christos 	if (str[0] == '\0' || *e != '\0')
    324  1.149  christos 		return -1;
    325  1.149  christos 	if (errno == ERANGE && (l == LONG_MAX || l == LONG_MIN))
    326  1.149  christos 		return -1;
    327  1.149  christos 	/* XXX: truncation */
    328  1.149  christos 	*num = (int)l;
    329  1.149  christos 	return 0;
    330  1.149  christos }
    331  1.149  christos 
    332  1.149  christos /* [<sysid>][/[<start>][/[<size>][/[<bootmenu>]]]] */
    333  1.149  christos static int
    334  1.149  christos parse_s(char *arg, int *csysid, unsigned *cstart, unsigned *csize,
    335  1.149  christos     char **cbootmenu)
    336  1.149  christos {
    337  1.149  christos 	char *ptr;
    338  1.149  christos 	int num;
    339  1.149  christos 
    340  1.149  christos 	if ((ptr = strchr(arg, '/')) != NULL)
    341  1.149  christos 		*ptr++ = '\0';
    342  1.149  christos 
    343  1.149  christos 	if (*arg) {
    344  1.149  christos 		if (getnum(arg, &num) == -1)
    345  1.149  christos 			return -1;
    346  1.149  christos 		*csysid = num;
    347  1.149  christos 	}
    348  1.149  christos 	if (ptr == NULL)
    349  1.149  christos 		return 0;
    350  1.149  christos 
    351  1.149  christos 	arg = ptr;
    352  1.149  christos 	if ((ptr = strchr(arg, '/')) != NULL)
    353  1.149  christos 		*ptr++ = '\0';
    354  1.149  christos 	if (*arg) {
    355  1.149  christos 		if (getnum(arg, &num) == -1)
    356  1.149  christos 			return -1;
    357  1.149  christos 		*cstart = num;
    358  1.149  christos 	}
    359  1.149  christos 	if (ptr == NULL)
    360  1.149  christos 		return 0;
    361  1.149  christos 
    362  1.149  christos 	arg = ptr;
    363  1.149  christos 	if ((ptr = strchr(arg, '/')) != NULL)
    364  1.149  christos 		*ptr++ = '\0';
    365  1.149  christos 	if (*arg) {
    366  1.149  christos 		if (getnum(arg, &num) == -1)
    367  1.149  christos 			return -1;
    368  1.149  christos 		*csize = num;
    369  1.149  christos 	}
    370  1.149  christos 	if (ptr != NULL && *ptr)
    371  1.149  christos 		*cbootmenu = ptr;
    372  1.149  christos 	return 0;
    373  1.149  christos }
    374  1.149  christos 
    375    1.4   mycroft int
    376   1.43     lukem main(int argc, char *argv[])
    377    1.1       cgd {
    378   1.62       dsl 	struct stat sb;
    379   1.91    dyoung 	int ch;
    380   1.52   thorpej 	size_t len;
    381   1.62       dsl 	char *cp;
    382   1.62       dsl 	int n;
    383   1.62       dsl #ifdef BOOTSEL
    384   1.62       dsl 	daddr_t default_ptn;		/* start sector of default ptn */
    385  1.149  christos #endif
    386   1.62       dsl 	char *cbootmenu = 0;
    387    1.1       cgd 
    388  1.120  drochner 	int csysid;	/* For the s_flag. */
    389  1.119  sborrill 	unsigned int cstart, csize;
    390  1.121  christos 	a_flag = u_flag = sh_flag = f_flag = s_flag = b_flag = 0;
    391  1.121  christos 	i_flag = B_flag = 0;
    392   1.62       dsl 	v_flag = 0;
    393   1.62       dsl 	E_flag = 0;
    394  1.149  christos 	csysid = -1;
    395  1.149  christos 	cstart = csize = ~0;
    396  1.129       dsl 	while ((ch = getopt(argc, argv, OPTIONS)) != -1) {
    397    1.4   mycroft 		switch (ch) {
    398    1.4   mycroft 		case '0':
    399    1.4   mycroft 			partition = 0;
    400    1.4   mycroft 			break;
    401    1.4   mycroft 		case '1':
    402    1.4   mycroft 			partition = 1;
    403    1.4   mycroft 			break;
    404    1.4   mycroft 		case '2':
    405    1.4   mycroft 			partition = 2;
    406    1.4   mycroft 			break;
    407    1.4   mycroft 		case '3':
    408    1.4   mycroft 			partition = 3;
    409    1.4   mycroft 			break;
    410   1.62       dsl 		case 'E':	/* Extended partition number */
    411   1.62       dsl 			E_flag = 1;
    412   1.62       dsl 			partition = strtoul(optarg, &cp, 0);
    413   1.62       dsl 			if (*cp || partition < 0)
    414   1.62       dsl 				errx(1, "Bad partition number -E %s.", optarg);
    415   1.62       dsl 			break;
    416   1.62       dsl #ifdef BOOTSEL
    417   1.62       dsl 		case 'B':	/* Bootselect parameters */
    418   1.34      fvdl 			B_flag = 1;
    419   1.34      fvdl 			break;
    420   1.34      fvdl #endif
    421   1.75    dyoung 		case 'F':	/* device argument is really a file */
    422   1.75    dyoung 			F_flag = 1;
    423   1.75    dyoung 			break;
    424   1.62       dsl 		case 'S':	/* Output as shell variables */
    425   1.15      phil 			sh_flag = 1;
    426   1.15      phil 			break;
    427   1.62       dsl 		case 'a':	/* Set active partition */
    428    1.4   mycroft 			a_flag = 1;
    429    1.4   mycroft 			break;
    430   1.62       dsl 		case 'f':	/* Non interactive */
    431   1.15      phil 			f_flag = 1;
    432   1.15      phil 			break;
    433   1.62       dsl 		case 'i':	/* Always update bootcode */
    434    1.4   mycroft 			i_flag = 1;
    435   1.15      phil 			break;
    436  1.135  christos 		case 'I':	/* Ignore errors */
    437  1.135  christos 			I_flag = 1;
    438  1.135  christos 			break;
    439   1.62       dsl 		case 'l':	/* List known partition types */
    440   1.50  christos 			for (len = 0; len < KNOWN_SYSIDS; len++)
    441   1.85  christos 				printf("%03d %s\n", mbr_ptypes[len].id,
    442   1.85  christos 				    mbr_ptypes[len].name);
    443   1.50  christos 			return 0;
    444   1.62       dsl 		case 'u':	/* Update partition details */
    445    1.4   mycroft 			u_flag = 1;
    446    1.1       cgd 			break;
    447   1.62       dsl 		case 'v':	/* Be verbose */
    448   1.62       dsl 			v_flag++;
    449   1.62       dsl 			break;
    450   1.62       dsl 		case 's':	/* Partition details */
    451   1.14      phil 			s_flag = 1;
    452  1.149  christos 
    453  1.149  christos 			if (parse_s(optarg, &csysid, &cstart, &csize,
    454  1.149  christos 			    &cbootmenu) == -1)
    455  1.149  christos 				errx(1, "Bad argument to the -s flag.");
    456   1.16      phil 			break;
    457   1.62       dsl 		case 'b':	/* BIOS geometry */
    458   1.16      phil 			b_flag = 1;
    459   1.62       dsl 			if (sscanf(optarg, "%d/%d/%d%n", &b_cyl, &b_head,
    460   1.62       dsl 			    &b_sec, &n) != 3 || optarg[n] != 0)
    461   1.54     soren 				errx(1, "Bad argument to the -b flag.");
    462   1.28        ws 			if (b_cyl > MAXCYL)
    463   1.28        ws 				b_cyl = MAXCYL;
    464   1.14      phil 			break;
    465  1.129       dsl 		case 'A':	/* Partition alignment[/offset] */
    466  1.131  pgoyette 			if (sscanf(optarg, "%u%n/%u%n", &ptn_alignment,
    467  1.131  pgoyette 				    &n, &ptn_0_offset, &n) < 1
    468  1.129       dsl 			    || optarg[n] != 0
    469  1.130       dsl 			    || ptn_0_offset > ptn_alignment)
    470  1.129       dsl 				errx(1, "Bad argument to the -A flag.");
    471  1.130       dsl 			if (ptn_0_offset == 0)
    472  1.130       dsl 				ptn_0_offset = ptn_alignment;
    473  1.129       dsl 			break;
    474   1.62       dsl 		case 'c':	/* file/directory containing boot code */
    475   1.62       dsl 			if (strchr(optarg, '/') != NULL &&
    476   1.62       dsl 			    stat(optarg, &sb) == 0 &&
    477   1.62       dsl 			    (sb.st_mode & S_IFMT) == S_IFDIR) {
    478   1.62       dsl 				boot_dir = optarg;
    479   1.62       dsl 				break;
    480   1.62       dsl 			}
    481   1.62       dsl 			bootsize = read_boot(optarg, bootcode,
    482   1.62       dsl 						sizeof bootcode, 1);
    483   1.62       dsl 			i_flag = 1;
    484   1.62       dsl 			break;
    485   1.62       dsl 		case 'r':	/* read data from disk_file (not raw disk) */
    486   1.62       dsl 			rfd = &wfd;
    487   1.62       dsl 			/* FALLTHROUGH */
    488   1.62       dsl 		case 'w':	/* write data to disk_file */
    489   1.62       dsl 			disk_file = optarg;
    490   1.30        ws 			break;
    491   1.75    dyoung 		case 't':
    492   1.75    dyoung 			if (setdisktab(optarg) == -1)
    493   1.75    dyoung 				errx(EXIT_FAILURE, "bad disktab");
    494   1.75    dyoung 			break;
    495   1.75    dyoung 		case 'T':
    496   1.75    dyoung 			disk_type = optarg;
    497   1.75    dyoung 			break;
    498  1.140  christos 		case 'z':
    499  1.140  christos 			secsize = atoi(optarg);
    500  1.140  christos 			if (secsize <= 512)
    501  1.140  christos out:				 errx(EXIT_FAILURE, "Invalid sector size %zd",
    502  1.140  christos 				    secsize);
    503  1.140  christos 			for (ch = secsize; (ch & 1) == 0; ch >>= 1)
    504  1.140  christos 				continue;
    505  1.140  christos 			if (ch != 1)
    506  1.140  christos 				goto out;
    507  1.140  christos 			break;
    508    1.4   mycroft 		default:
    509    1.4   mycroft 			usage();
    510    1.1       cgd 		}
    511  1.129       dsl 	}
    512    1.4   mycroft 	argc -= optind;
    513    1.4   mycroft 	argv += optind;
    514    1.1       cgd 
    515   1.75    dyoung 	if (disk_type != NULL && getdiskbyname(disk_type) == NULL)
    516   1.75    dyoung 		errx(EXIT_FAILURE, "bad disktype");
    517   1.75    dyoung 
    518   1.15      phil 	if (sh_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
    519   1.15      phil 		usage();
    520   1.15      phil 
    521   1.62       dsl 	if (B_flag && f_flag) {
    522   1.62       dsl 		warnx("Bootselector may only be configured interactively");
    523   1.34      fvdl 		usage();
    524   1.62       dsl 	}
    525   1.62       dsl 
    526   1.62       dsl 	if (f_flag && u_flag && !s_flag) {
    527   1.62       dsl 		warnx("Partition data not specified");
    528   1.62       dsl 		usage();
    529   1.62       dsl 	}
    530   1.34      fvdl 
    531   1.62       dsl 	if (s_flag && partition == -1) {
    532   1.50  christos 		warnx("-s flag requires a partition selected.");
    533   1.14      phil 		usage();
    534   1.15      phil 	}
    535   1.15      phil 
    536  1.109       dsl 	if (argc > 1)
    537  1.109       dsl 		usage();
    538  1.109       dsl 
    539    1.1       cgd 	if (argc > 0)
    540    1.1       cgd 		disk = argv[0];
    541  1.109       dsl 	else if (!F_flag) {
    542  1.109       dsl 		/* Default to boot device */
    543  1.109       dsl 		initvar_disk(&disk);
    544  1.109       dsl 	}
    545    1.4   mycroft 
    546  1.126     pooka 	if (!F_flag && stat(disk, &sb) == 0 && S_ISREG(sb.st_mode))
    547  1.126     pooka 		F_flag = 1;
    548  1.126     pooka 
    549   1.34      fvdl 	if (open_disk(B_flag || a_flag || i_flag || u_flag) < 0)
    550    1.1       cgd 		exit(1);
    551    1.1       cgd 
    552  1.145  jakllsch 	if (secsize > 512) {
    553  1.145  jakllsch 		if ((iobuf = malloc(secsize)) == NULL)
    554  1.145  jakllsch 			err(EXIT_FAILURE, "Cannot allocate %zd buffer",
    555  1.145  jakllsch 			    secsize);
    556  1.145  jakllsch 	}
    557  1.145  jakllsch 
    558   1.44     lukem 	if (read_s0(0, &mboot))
    559   1.62       dsl 		/* must have been a blank disk */
    560   1.62       dsl 		init_sector0(1);
    561   1.11   ghudson 
    562  1.121  christos 	read_gpt(GPT_HDR_BLKNO, &gpt1);
    563  1.121  christos 	read_gpt(disksectors - 1, &gpt2);
    564  1.121  christos 
    565  1.129       dsl 	if (b_flag) {
    566  1.129       dsl 		dos_cylinders = b_cyl;
    567  1.129       dsl 		dos_heads = b_head;
    568  1.129       dsl 		dos_sectors = b_sec;
    569  1.129       dsl 	} else {
    570  1.129       dsl 		get_bios_geometry();
    571  1.129       dsl 	}
    572  1.129       dsl 
    573  1.129       dsl 	if (ptn_alignment == 0)
    574  1.129       dsl 		get_ptn_alignmemt();
    575  1.129       dsl 
    576   1.62       dsl 	get_extended_ptn();
    577   1.15      phil 
    578   1.62       dsl #ifdef BOOTSEL
    579   1.62       dsl 	default_ptn = get_default_boot();
    580   1.62       dsl #endif
    581   1.62       dsl 
    582   1.62       dsl 	if (E_flag && !u_flag && partition >= ext.num_ptn)
    583   1.62       dsl 		errx(1, "Extended partition %d is not defined.", partition);
    584   1.15      phil 
    585   1.15      phil 	/* Do the update stuff! */
    586   1.15      phil 	if (u_flag) {
    587  1.129       dsl 		if (!f_flag && !b_flag)
    588  1.129       dsl 			change_bios_geometry();
    589  1.129       dsl 
    590   1.62       dsl 		if (s_flag)
    591   1.62       dsl 			change_part(E_flag, partition, csysid, cstart, csize,
    592   1.62       dsl 				cbootmenu);
    593   1.62       dsl 		else {
    594   1.62       dsl 			int part = partition, chg_ext = E_flag, prompt = 1;
    595   1.62       dsl 			do {
    596   1.62       dsl 				if (prompt) {
    597   1.62       dsl 					printf("\n");
    598   1.62       dsl 					print_s0(partition);
    599   1.62       dsl 				}
    600   1.62       dsl 				if (partition == -1)
    601   1.62       dsl 					part = ptn_id(
    602   1.62       dsl 				    "Which partition do you want to change?",
    603   1.62       dsl 							&chg_ext);
    604   1.62       dsl 				if (part < 0)
    605   1.62       dsl 					break;
    606   1.62       dsl 				prompt = change_part(chg_ext, part, 0, 0, 0, 0);
    607   1.62       dsl 			} while (partition == -1);
    608   1.62       dsl 		}
    609  1.129       dsl 	} else {
    610   1.62       dsl 		if (!i_flag && !B_flag) {
    611  1.129       dsl 			print_geometry();
    612   1.15      phil 			print_s0(partition);
    613   1.62       dsl 		}
    614  1.129       dsl 	}
    615    1.1       cgd 
    616   1.62       dsl 	if (a_flag && !E_flag)
    617    1.1       cgd 		change_active(partition);
    618    1.1       cgd 
    619   1.62       dsl #ifdef BOOTSEL
    620   1.62       dsl 	if (B_flag || u_flag || i_flag)
    621   1.62       dsl 		/* Ensure the mbr code supports this configuration */
    622   1.62       dsl 		install_bootsel(0);
    623   1.62       dsl 	if (B_flag)
    624   1.62       dsl 		default_ptn = configure_bootsel(default_ptn);
    625   1.62       dsl 	set_default_boot(default_ptn);
    626   1.62       dsl #else
    627   1.62       dsl 	if (i_flag)
    628   1.62       dsl 		init_sector0(0);
    629   1.34      fvdl #endif
    630   1.34      fvdl 
    631   1.62       dsl 	if (u_flag || a_flag || i_flag || B_flag) {
    632   1.15      phil 		if (!f_flag) {
    633   1.34      fvdl 			printf("\nWe haven't written the MBR back to disk "
    634   1.15      phil 			       "yet.  This is your last chance.\n");
    635   1.62       dsl 			if (u_flag)
    636   1.62       dsl 				print_s0(-1);
    637  1.121  christos 			if (gpt1.hdr_size != 0 || gpt2.hdr_size != 0)
    638  1.121  christos 				printf("\nWARNING: The disk is carrying "
    639  1.121  christos 				       "GUID Partition Tables.\n"
    640  1.121  christos 				       "         If you continue, "
    641  1.121  christos 				       "GPT headers will be deleted.\n\n");
    642  1.121  christos 			if (yesno("Should we write new partition table?")) {
    643  1.121  christos 				delete_gpt(&gpt1);
    644  1.121  christos 				delete_gpt(&gpt2);
    645   1.62       dsl 				write_mbr();
    646  1.121  christos 			}
    647  1.121  christos 		} else {
    648  1.121  christos 			if (delete_gpt(&gpt1) > 0)
    649  1.121  christos 				warnx("Primary GPT header was deleted");
    650  1.121  christos 			if (delete_gpt(&gpt2) > 0)
    651  1.121  christos 				warnx("Secondary GPT header was deleted");
    652   1.62       dsl 			write_mbr();
    653  1.121  christos 		}
    654    1.1       cgd 	}
    655    1.1       cgd 
    656    1.1       cgd 	exit(0);
    657    1.4   mycroft }
    658    1.1       cgd 
    659  1.132     joerg static void
    660   1.43     lukem usage(void)
    661    1.4   mycroft {
    662   1.62       dsl 	int indent = 7 + (int)strlen(getprogname()) + 1;
    663   1.43     lukem 
    664  1.137     enami 	(void)fprintf(stderr, "usage: %s [-aBFfIilSuv] "
    665  1.130       dsl 		"[-A ptn_alignment[/ptn_0_offset]] \\\n"
    666  1.130       dsl 		"%*s[-b cylinders/heads/sectors] \\\n"
    667   1.62       dsl 		"%*s[-0123 | -E num "
    668  1.149  christos 		"[-s [id][/[start][/[size][/bootmenu]]]] \\\n"
    669   1.75    dyoung 		"%*s[-t disktab] [-T disktype] \\\n"
    670   1.91    dyoung 		"%*s[-c bootcode] "
    671  1.155     sevan 		"[-r|-w file] [-z sectorsize] [device]\n"
    672   1.62       dsl 		"\t-a change active partition\n"
    673   1.62       dsl 		"\t-f force - not interactive\n"
    674   1.62       dsl 		"\t-i initialise MBR code\n"
    675  1.138  christos 		"\t-I ignore errors about no space or overlapping partitions\n"
    676   1.62       dsl 		"\t-l list partition types\n"
    677   1.62       dsl 		"\t-u update partition data\n"
    678   1.62       dsl 		"\t-v verbose output, -v -v more verbose still\n"
    679   1.62       dsl 		"\t-B update bootselect options\n"
    680   1.75    dyoung 		"\t-F treat device as a regular file\n"
    681  1.109       dsl 		"\t-S output as shell defines\n"
    682  1.109       dsl 		"\t-r and -w access 'file' for non-destructive testing\n",
    683  1.130       dsl 		getprogname(), indent, "", indent, "", indent, "", indent, "");
    684    1.4   mycroft 	exit(1);
    685    1.1       cgd }
    686    1.1       cgd 
    687   1.62       dsl static daddr_t
    688   1.62       dsl ext_offset(int part)
    689   1.62       dsl {
    690   1.62       dsl 	daddr_t offset = ext.base;
    691   1.62       dsl 
    692   1.62       dsl 	if (part != 0)
    693   1.62       dsl 		offset += le32toh(ext.ptn[part - 1].mbr_parts[1].mbrp_start);
    694   1.62       dsl 	return offset;
    695   1.62       dsl }
    696   1.62       dsl 
    697  1.132     joerg static void
    698   1.43     lukem print_s0(int which)
    699    1.1       cgd {
    700    1.4   mycroft 	int part;
    701    1.1       cgd 
    702    1.4   mycroft 	if (which == -1) {
    703   1.62       dsl 		if (!sh_flag)
    704   1.62       dsl 			printf("Partition table:\n");
    705   1.71     lukem 		for (part = 0; part < MBR_PART_COUNT; part++) {
    706   1.15      phil 			if (!sh_flag)
    707   1.15      phil 				printf("%d: ", part);
    708   1.62       dsl 			print_part(&mboot, part, 0);
    709   1.15      phil 		}
    710   1.62       dsl 		if (!sh_flag) {
    711   1.62       dsl 			if (ext.is_corrupt)
    712   1.87       wiz 				printf("Extended partition table is corrupt\n");
    713   1.62       dsl 			else
    714   1.62       dsl 				if (ext.num_ptn != 0)
    715   1.62       dsl 					printf("Extended partition table:\n");
    716   1.62       dsl 		}
    717   1.62       dsl 		for (part = 0; part < ext.num_ptn; part++) {
    718   1.62       dsl 			if (!sh_flag)
    719   1.62       dsl 				printf("E%d: ", part);
    720   1.62       dsl 			print_part(&ext.ptn[part], 0, ext_offset(part));
    721   1.62       dsl 			if (!sh_flag && v_flag >= 2) {
    722   1.62       dsl 				printf("link: ");
    723   1.62       dsl 				print_mbr_partition(&ext.ptn[part], 1,
    724   1.62       dsl 						ext_offset(part), ext.base, 0);
    725   1.62       dsl 			}
    726   1.62       dsl 		}
    727   1.62       dsl #ifdef BOOTSEL
    728   1.96       dsl 		if (!sh_flag && mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
    729   1.62       dsl 			int tmo;
    730   1.76     lukem 
    731   1.62       dsl 			printf("Bootselector ");
    732   1.71     lukem 			if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ACTIVE) {
    733   1.62       dsl 				printf("enabled");
    734   1.71     lukem 				tmo = le16toh(mboot.mbr_bootsel.mbrbs_timeo);
    735   1.62       dsl 				if (tmo == 0xffff)
    736   1.62       dsl 					printf(", infinite timeout");
    737   1.62       dsl 				else
    738   1.62       dsl 					printf(", timeout %d seconds",
    739   1.62       dsl 						    (10 * tmo + 9) / 182);
    740   1.62       dsl 			} else
    741   1.62       dsl 				printf("disabled");
    742   1.62       dsl 			printf(".\n");
    743   1.62       dsl 		}
    744   1.62       dsl #endif
    745  1.112       apb 		if (!sh_flag) {
    746  1.112       apb 			int active = first_active();
    747  1.112       apb 			if (active == MBR_PART_COUNT)
    748  1.112       apb 				printf("No active partition.\n");
    749  1.112       apb 			else
    750  1.112       apb 				printf("First active partition: %d\n", active);
    751  1.112       apb 		}
    752  1.146  jakllsch 		if (!sh_flag)
    753  1.116       tnn 			printf("Drive serial number: %"PRIu32" (0x%08x)\n",
    754  1.105       dsl 			    le32toh(mboot.mbr_dsn),
    755  1.105       dsl 			    le32toh(mboot.mbr_dsn));
    756   1.62       dsl 		return;
    757   1.62       dsl 	}
    758   1.62       dsl 
    759   1.62       dsl 	if (E_flag) {
    760   1.62       dsl 		if (!sh_flag)
    761   1.62       dsl 			printf("Extended partition E%d:\n", which);
    762   1.62       dsl 		if (which > ext.num_ptn)
    763   1.62       dsl 			printf("Undefined\n");
    764   1.62       dsl 		else
    765   1.62       dsl 			print_part(&ext.ptn[which], 0, ext_offset(which));
    766   1.62       dsl 	} else {
    767   1.62       dsl 		if (!sh_flag)
    768   1.62       dsl 			printf("Partition %d:\n", which);
    769   1.62       dsl 		print_part(&mboot, which, 0);
    770   1.62       dsl 	}
    771    1.1       cgd }
    772    1.1       cgd 
    773  1.132     joerg static void
    774   1.71     lukem print_part(struct mbr_sector *boot, int part, daddr_t offset)
    775   1.12   thorpej {
    776   1.71     lukem 	struct mbr_partition *partp;
    777   1.92  christos 	const char *e;
    778   1.62       dsl 
    779   1.62       dsl 	if (!sh_flag) {
    780   1.62       dsl 		print_mbr_partition(boot, part, offset, 0, 0);
    781   1.62       dsl 		return;
    782   1.62       dsl 	}
    783   1.12   thorpej 
    784   1.62       dsl 	partp = &boot->mbr_parts[part];
    785   1.62       dsl 	if (boot != &mboot) {
    786   1.62       dsl 		part = boot - ext.ptn;
    787   1.62       dsl 		e = "E";
    788   1.62       dsl 	} else
    789   1.62       dsl 		e = "";
    790   1.62       dsl 
    791   1.71     lukem 	if (partp->mbrp_type == 0) {
    792   1.62       dsl 		printf("PART%s%dSIZE=0\n", e, part);
    793   1.62       dsl 		return;
    794   1.62       dsl 	}
    795   1.62       dsl 
    796   1.71     lukem 	printf("PART%s%dID=%d\n", e, part, partp->mbrp_type);
    797   1.62       dsl 	printf("PART%s%dSIZE=%u\n", e, part, le32toh(partp->mbrp_size));
    798   1.69       dsl 	printf("PART%s%dSTART=%"PRIdaddr"\n", e, part,
    799   1.69       dsl 	    offset + le32toh(partp->mbrp_start));
    800   1.62       dsl 	printf("PART%s%dFLAG=0x%x\n", e, part, partp->mbrp_flag);
    801   1.62       dsl 	printf("PART%s%dBCYL=%d\n", e, part,
    802   1.62       dsl 	    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect));
    803   1.62       dsl 	printf("PART%s%dBHEAD=%d\n", e, part, partp->mbrp_shd);
    804   1.62       dsl 	printf("PART%s%dBSEC=%d\n", e, part, MBR_PSECT(partp->mbrp_ssect));
    805   1.62       dsl 	printf("PART%s%dECYL=%d\n", e, part,
    806   1.62       dsl 	    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect));
    807   1.62       dsl 	printf("PART%s%dEHEAD=%d\n", e, part, partp->mbrp_ehd);
    808   1.62       dsl 	printf("PART%s%dESEC=%d\n", e, part, MBR_PSECT(partp->mbrp_esect));
    809   1.12   thorpej }
    810   1.12   thorpej 
    811   1.43     lukem static void
    812  1.102       dsl pr_cyls(daddr_t sector, int is_end)
    813   1.12   thorpej {
    814   1.90    dyoung 	unsigned long cyl, head, sect;
    815   1.62       dsl 	cyl = sector / dos_cylindersectors;
    816   1.62       dsl 	sect = sector - cyl * dos_cylindersectors;
    817   1.62       dsl 	head = sect / dos_sectors;
    818   1.62       dsl 	sect -= head * dos_sectors;
    819   1.12   thorpej 
    820   1.62       dsl 	printf("%lu", cyl);
    821  1.102       dsl 
    822  1.102       dsl 	if (is_end) {
    823  1.102       dsl 		if (head == dos_heads - 1 && sect == dos_sectors - 1)
    824  1.102       dsl 			return;
    825  1.102       dsl 	} else {
    826  1.102       dsl 		if (head == 0 && sect == 0)
    827  1.102       dsl 			return;
    828  1.102       dsl 	}
    829  1.102       dsl 
    830   1.62       dsl 	printf("/%lu/%lu", head, sect + 1);
    831   1.12   thorpej }
    832   1.12   thorpej 
    833  1.132     joerg static void
    834   1.71     lukem print_mbr_partition(struct mbr_sector *boot, int part,
    835   1.62       dsl     daddr_t offset, daddr_t exoffset, int indent)
    836   1.12   thorpej {
    837   1.62       dsl 	daddr_t	start;
    838   1.62       dsl 	daddr_t	size;
    839   1.71     lukem 	struct mbr_partition *partp = &boot->mbr_parts[part];
    840   1.71     lukem 	struct mbr_sector eboot;
    841   1.62       dsl 	int p;
    842   1.62       dsl 	static int dumped = 0;
    843   1.12   thorpej 
    844   1.71     lukem 	if (partp->mbrp_type == 0 && v_flag < 2) {
    845   1.62       dsl 		printf("<UNUSED>\n");
    846   1.62       dsl 		return;
    847   1.62       dsl 	}
    848   1.12   thorpej 
    849   1.62       dsl 	start = le32toh(partp->mbrp_start);
    850   1.62       dsl 	size = le32toh(partp->mbrp_size);
    851   1.71     lukem 	if (MBR_IS_EXTENDED(partp->mbrp_type))
    852   1.62       dsl 		start += exoffset;
    853   1.62       dsl 	else
    854   1.62       dsl 		start += offset;
    855   1.12   thorpej 
    856   1.71     lukem 	printf("%s (sysid %d)\n", get_type(partp->mbrp_type), partp->mbrp_type);
    857   1.62       dsl #ifdef BOOTSEL
    858   1.96       dsl 	if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC &&
    859   1.71     lukem 	    boot->mbr_bootsel.mbrbs_nametab[part][0])
    860   1.62       dsl 		printf("%*s    bootmenu: %s\n", indent, "",
    861   1.71     lukem 		    boot->mbr_bootsel.mbrbs_nametab[part]);
    862   1.62       dsl #endif
    863   1.12   thorpej 
    864   1.69       dsl 	printf("%*s    start %"PRIdaddr", size %"PRIdaddr,
    865   1.69       dsl 	    indent, "", start, size);
    866   1.62       dsl 	if (size != 0) {
    867   1.62       dsl 		printf(" (%u MB, Cyls ", SEC_TO_MB(size));
    868  1.130       dsl 		if (v_flag == 0 && le32toh(partp->mbrp_start) == ptn_0_offset)
    869  1.130       dsl 			pr_cyls(start - ptn_0_offset, 0);
    870   1.62       dsl 		else
    871  1.102       dsl 			pr_cyls(start, 0);
    872   1.62       dsl 		printf("-");
    873  1.102       dsl 		pr_cyls(start + size - 1, 1);
    874   1.62       dsl 		printf(")");
    875   1.62       dsl 	}
    876    1.1       cgd 
    877   1.62       dsl 	switch (partp->mbrp_flag) {
    878   1.62       dsl 	case 0:
    879   1.62       dsl 		break;
    880   1.71     lukem 	case MBR_PFLAG_ACTIVE:
    881   1.62       dsl 		printf(", Active");
    882   1.62       dsl 		break;
    883   1.62       dsl 	default:
    884   1.62       dsl 		printf(", flag 0x%x", partp->mbrp_flag);
    885   1.62       dsl 		break;
    886   1.62       dsl 	}
    887   1.62       dsl 	printf("\n");
    888   1.14      phil 
    889   1.62       dsl 	if (v_flag) {
    890   1.62       dsl 		printf("%*s        beg: cylinder %4d, head %3d, sector %2d\n",
    891   1.62       dsl 		    indent, "",
    892   1.62       dsl 		    MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
    893   1.62       dsl 		    partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
    894   1.62       dsl 		printf("%*s        end: cylinder %4d, head %3d, sector %2d\n",
    895   1.62       dsl 		    indent, "",
    896   1.62       dsl 		    MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
    897   1.62       dsl 		    partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
    898   1.62       dsl 	}
    899   1.14      phil 
    900  1.111       apb 	if (partp->mbrp_type == 0 && start == 0 && v_flag < 3)
    901  1.111       apb 		return;
    902  1.111       apb 
    903  1.103       apb 	if (! MBR_IS_EXTENDED(partp->mbrp_type))
    904  1.103       apb 		print_pbr(start, indent + 8, partp->mbrp_type);
    905  1.103       apb 
    906   1.71     lukem 	if (!MBR_IS_EXTENDED(partp->mbrp_type) ||
    907   1.62       dsl 	    (v_flag <= 2 && !ext.is_corrupt))
    908   1.14      phil 		return;
    909   1.44     lukem 
    910   1.62       dsl 	/*
    911   1.62       dsl 	 * Recursive dump extended table,
    912   1.62       dsl 	 * This is read from the disk - so is wrong during editing.
    913   1.62       dsl 	 * Just ensure we only show it once.
    914   1.62       dsl 	 */
    915   1.62       dsl 	if (dumped)
    916   1.62       dsl 		return;
    917   1.14      phil 
    918   1.62       dsl 	printf("%*s    Extended partition table:\n", indent, "");
    919   1.62       dsl 	indent += 4;
    920   1.62       dsl 	if (read_s0(start, &eboot) == -1)
    921    1.1       cgd 		return;
    922   1.71     lukem 	for (p = 0; p < MBR_PART_COUNT; p++) {
    923   1.62       dsl 		printf("%*s%d: ", indent, "", p);
    924   1.62       dsl 		print_mbr_partition(&eboot, p, start,
    925   1.62       dsl 				    exoffset ? exoffset : start, indent);
    926    1.1       cgd 	}
    927   1.44     lukem 
    928   1.62       dsl 	if (exoffset == 0)
    929   1.62       dsl 		dumped = 1;
    930    1.1       cgd }
    931    1.1       cgd 
    932  1.103       apb /* Print a line with a label and a vis-encoded string */
    933  1.132     joerg static void
    934  1.103       apb printvis(int indent, const char *label, const char *buf, size_t size)
    935  1.103       apb {
    936  1.103       apb 	char *visbuf;
    937  1.103       apb 
    938  1.103       apb 	if ((visbuf = malloc(size * 4 + 1)) == NULL)
    939  1.103       apb 		err(1, "Malloc failed");
    940  1.103       apb 	strsvisx(visbuf, buf, size, VIS_TAB|VIS_NL|VIS_OCTAL, "\"");
    941  1.103       apb 	printf("%*s%s: \"%s\"\n",
    942  1.103       apb 	    indent, "",
    943  1.103       apb 	    label, visbuf);
    944  1.103       apb 	free(visbuf);
    945  1.103       apb }
    946  1.103       apb 
    947  1.103       apb /* Check whether a buffer contains all bytes zero */
    948  1.132     joerg static int
    949  1.110       dsl is_all_zero(const unsigned char *p, size_t size)
    950  1.103       apb {
    951  1.103       apb 
    952  1.103       apb 	while (size-- > 0) {
    953  1.103       apb 		if (*p++ != 0)
    954  1.103       apb 			return 0;
    955  1.103       apb 	}
    956  1.103       apb 	return 1;
    957  1.103       apb }
    958  1.103       apb 
    959  1.103       apb /*
    960  1.103       apb  * Report on the contents of a PBR sector.
    961  1.103       apb  *
    962  1.103       apb  * We first perform several sanity checks.  If vflag >= 2, we report all
    963  1.103       apb  * failing tests, but for smaller values of v_flag we stop after the
    964  1.103       apb  * first failing test.  Tests are ordered in an attempt to get the most
    965  1.103       apb  * useful error message from the first failing test.
    966  1.103       apb  *
    967  1.103       apb  * If v_flag >= 2, we also report some decoded values from the PBR.
    968  1.103       apb  * These results may be meaningless, if the PBR doesn't follow common
    969  1.103       apb  * conventions.
    970  1.103       apb  *
    971  1.103       apb  * Trying to decode anything more than the magic number in the last
    972  1.103       apb  * two bytes is a layering violation, but it can be very useful in
    973  1.103       apb  * diagnosing boot failures.
    974  1.103       apb  */
    975  1.132     joerg static void
    976  1.103       apb print_pbr(daddr_t sector, int indent, uint8_t part_type)
    977  1.103       apb {
    978  1.103       apb 	struct mbr_sector pboot;
    979  1.103       apb 	unsigned char *p, *endp;
    980  1.103       apb 	unsigned char val;
    981  1.103       apb 	int ok;
    982  1.103       apb 	int errcount = 0;
    983  1.103       apb 
    984  1.103       apb #define PBR_ERROR(...)							\
    985  1.103       apb 	do {								\
    986  1.103       apb 		++errcount;						\
    987  1.103       apb 		printf("%*s%s: ", indent, "",				\
    988  1.103       apb 		    (v_flag < 2 ? "PBR is not bootable" : "Not bootable")); \
    989  1.103       apb 		printf(__VA_ARGS__);					\
    990  1.103       apb 		if (v_flag < 2)						\
    991  1.103       apb 			return;						\
    992  1.103       apb 	} while (/*CONSTCOND*/ 0)
    993  1.103       apb 
    994  1.103       apb 	if (v_flag >= 2) {
    995  1.103       apb 		printf("%*sInformation from PBR:\n",
    996  1.103       apb 		    indent, "");
    997  1.103       apb 		indent += 4;
    998  1.103       apb 	}
    999  1.103       apb 
   1000  1.103       apb 	if (read_disk(sector, &pboot) == -1) {
   1001  1.103       apb 		PBR_ERROR("Sector %"PRIdaddr" is unreadable (%s)\n",
   1002  1.103       apb 		    sector, strerror(errno));
   1003  1.103       apb 		return;
   1004  1.103       apb 	}
   1005  1.103       apb 
   1006  1.103       apb 	/* all bytes identical? */
   1007  1.110       dsl 	p = (unsigned char *)&pboot;
   1008  1.103       apb 	endp = p + sizeof(pboot);
   1009  1.103       apb 	val = *p;
   1010  1.103       apb 	ok = 0;
   1011  1.103       apb 	for (; p < endp; p++) {
   1012  1.103       apb 		if (*p != val) {
   1013  1.103       apb 			ok = 1;
   1014  1.103       apb 			break;
   1015  1.103       apb 		}
   1016  1.103       apb 	}
   1017  1.103       apb 	if (! ok)
   1018  1.103       apb 		PBR_ERROR("All bytes are identical (0x%02x)\n", val);
   1019  1.103       apb 
   1020  1.103       apb 	if (pboot.mbr_magic != LE_MBR_MAGIC)
   1021  1.108       apb 		PBR_ERROR("Bad magic number (0x%04x)\n",
   1022  1.103       apb 			le16toh(pboot.mbr_magic));
   1023  1.103       apb 
   1024  1.103       apb #if 0
   1025  1.103       apb 	/* Some i386 OS might fail this test.  All non-i386 will fail. */
   1026  1.103       apb 	if (pboot.mbr_jmpboot[0] != 0xE9
   1027  1.103       apb 	    && pboot.mbr_jmpboot[0] != 0xEB) {
   1028  1.103       apb 		PBR_ERROR("Does not begin with i386 JMP instruction"
   1029  1.103       apb 			" (0x%02x 0x%02x0 0x%02x)\n",
   1030  1.103       apb 		    pboot.mbr_jmpboot[0], pboot.mbr_jmpboot[1],
   1031  1.103       apb 		    pboot.mbr_jmpboot[2]);
   1032  1.103       apb 	}
   1033  1.103       apb #endif
   1034  1.103       apb 
   1035  1.103       apb 	if (v_flag > 0 && errcount == 0)
   1036  1.103       apb 		printf("%*sPBR appears to be bootable\n",
   1037  1.103       apb 		    indent, "");
   1038  1.103       apb 	if (v_flag < 2)
   1039  1.103       apb 		return;
   1040  1.103       apb 
   1041  1.103       apb 	if (! is_all_zero(pboot.mbr_oemname, sizeof(pboot.mbr_oemname))) {
   1042  1.103       apb 		printvis(indent, "OEM name", (char *)pboot.mbr_oemname,
   1043  1.103       apb 			sizeof(pboot.mbr_oemname));
   1044  1.103       apb 	}
   1045  1.103       apb 
   1046  1.103       apb 	if (pboot.mbr_bpb.bpb16.bsBootSig == 0x29)
   1047  1.103       apb 		printf("%*sBPB FAT16 boot signature found\n",
   1048  1.103       apb 		    indent, "");
   1049  1.103       apb 	if (pboot.mbr_bpb.bpb32.bsBootSig == 0x29)
   1050  1.103       apb 		printf("%*sBPB FAT32 boot signature found\n",
   1051  1.103       apb 		    indent, "");
   1052  1.103       apb 
   1053  1.103       apb #undef PBR_ERROR
   1054  1.103       apb }
   1055  1.103       apb 
   1056  1.132     joerg static int
   1057   1.62       dsl read_boot(const char *name, void *buf, size_t len, int err_exit)
   1058   1.30        ws {
   1059   1.34      fvdl 	int bfd, ret;
   1060   1.30        ws 	struct stat st;
   1061   1.30        ws 
   1062   1.62       dsl 	if (boot_path != NULL)
   1063   1.62       dsl 		free(boot_path);
   1064   1.65    itojun 	if (strchr(name, '/') == 0)
   1065   1.65    itojun 		asprintf(&boot_path, "%s/%s", boot_dir, name);
   1066   1.65    itojun 	else
   1067   1.65    itojun 		boot_path = strdup(name);
   1068   1.62       dsl 	if (boot_path == NULL)
   1069   1.62       dsl 		err(1, "Malloc failed");
   1070   1.62       dsl 
   1071   1.62       dsl 	if ((bfd = open(boot_path, O_RDONLY)) < 0 || fstat(bfd, &st) == -1) {
   1072   1.62       dsl 		warn("%s", boot_path);
   1073   1.62       dsl 		goto fail;
   1074   1.62       dsl 	}
   1075   1.62       dsl 
   1076   1.62       dsl 	if (st.st_size > (off_t)len) {
   1077   1.62       dsl 		warnx("%s: bootcode too large", boot_path);
   1078   1.62       dsl 		goto fail;
   1079   1.62       dsl 	}
   1080   1.34      fvdl 	ret = st.st_size;
   1081   1.62       dsl 	if (ret < 0x200) {
   1082   1.62       dsl 		warnx("%s: bootcode too small", boot_path);
   1083   1.62       dsl 		goto fail;
   1084   1.62       dsl 	}
   1085   1.62       dsl 	if (read(bfd, buf, len) != ret) {
   1086   1.62       dsl 		warn("%s", boot_path);
   1087   1.62       dsl 		goto fail;
   1088   1.62       dsl 	}
   1089   1.30        ws 
   1090   1.30        ws 	/*
   1091   1.30        ws 	 * Do some sanity checking here
   1092   1.30        ws 	 */
   1093   1.96       dsl 	if (((struct mbr_sector *)buf)->mbr_magic != LE_MBR_MAGIC) {
   1094   1.62       dsl 		warnx("%s: invalid magic", boot_path);
   1095   1.62       dsl 		goto fail;
   1096   1.62       dsl 	}
   1097   1.62       dsl 
   1098   1.62       dsl 	close(bfd);
   1099   1.62       dsl 	ret = (ret + 0x1ff) & ~0x1ff;
   1100   1.34      fvdl 	return ret;
   1101   1.62       dsl 
   1102   1.62       dsl     fail:
   1103   1.99       dsl 	if (bfd >= 0)
   1104   1.99       dsl 		close(bfd);
   1105   1.62       dsl 	if (err_exit)
   1106   1.62       dsl 		exit(1);
   1107   1.62       dsl 	return 0;
   1108   1.30        ws }
   1109   1.30        ws 
   1110  1.132     joerg static void
   1111   1.76     lukem init_sector0(int zappart)
   1112    1.1       cgd {
   1113   1.15      phil 	int i;
   1114  1.105       dsl 	int copy_size = offsetof(struct mbr_sector, mbr_dsn);
   1115   1.15      phil 
   1116   1.62       dsl #ifdef DEFAULT_BOOTCODE
   1117   1.62       dsl 	if (bootsize == 0)
   1118   1.62       dsl 		bootsize = read_boot(DEFAULT_BOOTCODE, bootcode,
   1119  1.124       dsl 			sizeof bootcode, 0);
   1120   1.62       dsl #endif
   1121   1.62       dsl #ifdef BOOTSEL
   1122   1.96       dsl 	if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
   1123   1.96       dsl 	    && bootcode[0].mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   1124   1.76     lukem 		copy_size = MBR_BS_OFFSET;
   1125   1.30        ws #endif
   1126   1.30        ws 
   1127   1.62       dsl 	if (bootsize != 0) {
   1128   1.62       dsl 		boot_installed = 1;
   1129   1.71     lukem 		memcpy(&mboot, bootcode, copy_size);
   1130  1.105       dsl 		mboot.mbr_bootsel_magic = bootcode[0].mbr_bootsel_magic;
   1131   1.62       dsl 	}
   1132   1.96       dsl 	mboot.mbr_magic = LE_MBR_MAGIC;
   1133   1.15      phil 
   1134   1.76     lukem 	if (!zappart)
   1135   1.62       dsl 		return;
   1136   1.71     lukem 	for (i = 0; i < MBR_PART_COUNT; i++)
   1137   1.62       dsl 		memset(&mboot.mbr_parts[i], 0, sizeof(mboot.mbr_parts[i]));
   1138   1.62       dsl }
   1139   1.34      fvdl 
   1140  1.132     joerg static void
   1141   1.62       dsl get_extended_ptn(void)
   1142   1.62       dsl {
   1143   1.71     lukem 	struct mbr_partition *mp;
   1144   1.71     lukem 	struct mbr_sector *boot;
   1145   1.62       dsl 	daddr_t offset;
   1146   1.71     lukem 	struct mbr_sector *nptn;
   1147   1.62       dsl 
   1148   1.62       dsl 	/* find first (there should only be one) extended partition */
   1149   1.71     lukem 	for (mp = mboot.mbr_parts; !MBR_IS_EXTENDED(mp->mbrp_type); mp++)
   1150   1.71     lukem 		if (mp >= &mboot.mbr_parts[MBR_PART_COUNT])
   1151   1.62       dsl 			return;
   1152   1.62       dsl 
   1153   1.62       dsl 	/*
   1154   1.62       dsl 	 * The extended partition should be structured as a linked list
   1155   1.62       dsl 	 * (even though it appears, at first glance, to be a tree).
   1156   1.62       dsl 	 */
   1157   1.62       dsl 	ext.base = le32toh(mp->mbrp_start);
   1158   1.62       dsl 	ext.limit = ext.base + le32toh(mp->mbrp_size);
   1159   1.62       dsl 	ext.ptn_id = mp - mboot.mbr_parts;
   1160   1.62       dsl 	for (offset = 0;; offset = le32toh(boot->mbr_parts[1].mbrp_start)) {
   1161   1.70    itojun 		nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
   1162   1.70    itojun 		if (nptn == NULL)
   1163   1.62       dsl 			err(1, "Malloc failed");
   1164   1.70    itojun 		ext.ptn = nptn;
   1165   1.62       dsl 		boot = ext.ptn + ext.num_ptn;
   1166   1.62       dsl 		if (read_s0(offset + ext.base, boot) == -1)
   1167   1.62       dsl 			break;
   1168   1.62       dsl 		/* expect p0 to be valid and p1 to be another extended ptn */
   1169   1.71     lukem 		if (MBR_IS_EXTENDED(boot->mbr_parts[0].mbrp_type))
   1170   1.62       dsl 			break;
   1171   1.71     lukem 		if (boot->mbr_parts[1].mbrp_type != 0 &&
   1172   1.71     lukem 		    !MBR_IS_EXTENDED(boot->mbr_parts[1].mbrp_type))
   1173   1.62       dsl 			break;
   1174   1.62       dsl 		/* p2 and p3 should be unallocated */
   1175   1.71     lukem 		if (boot->mbr_parts[2].mbrp_type != 0 ||
   1176   1.71     lukem 		    boot->mbr_parts[3].mbrp_type != 0)
   1177   1.62       dsl 			break;
   1178   1.62       dsl 		/* data ptn inside extended one */
   1179   1.71     lukem 		if (boot->mbr_parts[0].mbrp_type != 0 &&
   1180   1.62       dsl 		    offset + le32toh(boot->mbr_parts[0].mbrp_start)
   1181   1.62       dsl 		    + le32toh(boot->mbr_parts[0].mbrp_size) > ext.limit)
   1182   1.62       dsl 			break;
   1183   1.62       dsl 
   1184   1.62       dsl 		ext.num_ptn++;
   1185   1.62       dsl 
   1186   1.71     lukem 		if (boot->mbr_parts[1].mbrp_type == 0)
   1187   1.62       dsl 			/* end of extended partition chain */
   1188   1.62       dsl 			return;
   1189   1.62       dsl 		/* must be in sector order */
   1190   1.62       dsl 		if (offset >= le32toh(boot->mbr_parts[1].mbrp_start))
   1191   1.62       dsl 			break;
   1192   1.62       dsl 	}
   1193   1.62       dsl 
   1194  1.152  christos 	warnx("Extended partition table is corrupt");
   1195   1.62       dsl 	ext.is_corrupt = 1;
   1196   1.62       dsl 	ext.num_ptn = 0;
   1197   1.34      fvdl }
   1198    1.1       cgd 
   1199  1.130       dsl #if defined(USE_DISKLIST)
   1200  1.132     joerg static void
   1201   1.44     lukem get_diskname(const char *fullname, char *diskname, size_t size)
   1202  1.132     joerg {
   1203   1.44     lukem 	const char *p, *p2;
   1204   1.34      fvdl 	size_t len;
   1205   1.34      fvdl 
   1206   1.34      fvdl 	p = strrchr(fullname, '/');
   1207   1.34      fvdl 	if (p == NULL)
   1208   1.34      fvdl 		p = fullname;
   1209   1.34      fvdl 	else
   1210   1.34      fvdl 		p++;
   1211   1.34      fvdl 
   1212   1.34      fvdl 	if (*p == 0) {
   1213   1.62       dsl 		strlcpy(diskname, fullname, size);
   1214   1.34      fvdl 		return;
   1215   1.34      fvdl 	}
   1216   1.34      fvdl 
   1217   1.34      fvdl 	if (*p == 'r')
   1218   1.34      fvdl 		p++;
   1219   1.34      fvdl 
   1220   1.34      fvdl 	for (p2 = p; *p2 != 0; p2++)
   1221   1.83       dsl 		if (isdigit((unsigned char)*p2))
   1222   1.34      fvdl 			break;
   1223   1.34      fvdl 	if (*p2 == 0) {
   1224   1.34      fvdl 		/* XXX invalid diskname? */
   1225   1.62       dsl 		strlcpy(diskname, fullname, size);
   1226   1.34      fvdl 		return;
   1227   1.34      fvdl 	}
   1228   1.83       dsl 	while (isdigit((unsigned char)*p2))
   1229   1.34      fvdl 		p2++;
   1230   1.34      fvdl 
   1231   1.34      fvdl 	len = p2 - p;
   1232   1.34      fvdl 	if (len > size) {
   1233   1.34      fvdl 		/* XXX */
   1234   1.62       dsl 		strlcpy(diskname, fullname, size);
   1235   1.34      fvdl 		return;
   1236   1.34      fvdl 	}
   1237   1.34      fvdl 
   1238   1.62       dsl 	memcpy(diskname, p, len);
   1239   1.34      fvdl 	diskname[len] = 0;
   1240   1.34      fvdl }
   1241  1.130       dsl #endif
   1242   1.34      fvdl 
   1243  1.129       dsl static void
   1244  1.129       dsl get_ptn_alignmemt(void)
   1245  1.129       dsl {
   1246  1.129       dsl 	struct mbr_partition *partp = &mboot.mbr_parts[0];
   1247  1.129       dsl 	uint32_t ptn_0_base, ptn_0_limit;
   1248  1.129       dsl 
   1249  1.129       dsl 	/* Default to using 'traditional' cylinder alignment */
   1250  1.129       dsl 	ptn_alignment = dos_cylindersectors;
   1251  1.130       dsl 	ptn_0_offset = dos_sectors;
   1252  1.129       dsl 
   1253  1.129       dsl 	if (partp->mbrp_type != 0) {
   1254  1.129       dsl 		/* Try to copy alignment of first partition */
   1255  1.129       dsl 		ptn_0_base = le32toh(partp->mbrp_start);
   1256  1.129       dsl 		ptn_0_limit = ptn_0_base + le32toh(partp->mbrp_size);
   1257  1.129       dsl 		if (!(ptn_0_limit & 2047)) {
   1258  1.129       dsl 			/* Partition ends on a 1MB boundary, align to 1MB */
   1259  1.129       dsl 			ptn_alignment = 2048;
   1260  1.129       dsl 			if (ptn_0_base <= 2048
   1261  1.129       dsl 			    && !(ptn_0_base & (ptn_0_base - 1))) {
   1262  1.129       dsl 				/* ptn_base is a power of 2, use it */
   1263  1.130       dsl 				ptn_0_offset = ptn_0_base;
   1264  1.129       dsl 			}
   1265  1.129       dsl 		}
   1266  1.129       dsl 	} else {
   1267  1.129       dsl 		/* Use 1MB alignment for large disks */
   1268  1.129       dsl 		if (disksectors > 2048 * 1024 * 128) {
   1269  1.129       dsl 			ptn_alignment = 2048;
   1270  1.130       dsl 			ptn_0_offset = 2048;
   1271  1.129       dsl 		}
   1272  1.129       dsl 	}
   1273  1.129       dsl }
   1274  1.129       dsl 
   1275  1.132     joerg static void
   1276  1.129       dsl get_bios_geometry(void)
   1277   1.34      fvdl {
   1278  1.130       dsl #if defined(USE_DISKLIST)
   1279   1.34      fvdl 	int mib[2], i;
   1280   1.34      fvdl 	size_t len;
   1281   1.34      fvdl 	struct biosdisk_info *bip;
   1282   1.34      fvdl 	struct nativedisk_info *nip;
   1283   1.34      fvdl 	char diskname[8];
   1284   1.34      fvdl 
   1285   1.34      fvdl 	mib[0] = CTL_MACHDEP;
   1286   1.34      fvdl 	mib[1] = CPU_DISKINFO;
   1287   1.34      fvdl 	if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
   1288   1.81       dbj 		goto out;
   1289   1.34      fvdl 	}
   1290   1.34      fvdl 	dl = (struct disklist *) malloc(len);
   1291   1.98    rumble 	if (dl == NULL)
   1292   1.98    rumble 		err(1, "Malloc failed");
   1293   1.81       dbj 	if (sysctl(mib, 2, dl, &len, NULL, 0) < 0) {
   1294   1.81       dbj 		free(dl);
   1295   1.81       dbj 		dl = 0;
   1296   1.81       dbj 		goto out;
   1297   1.81       dbj 	}
   1298   1.34      fvdl 
   1299   1.34      fvdl 	get_diskname(disk, diskname, sizeof diskname);
   1300   1.34      fvdl 
   1301   1.34      fvdl 	for (i = 0; i < dl->dl_nnativedisks; i++) {
   1302   1.34      fvdl 		nip = &dl->dl_nativedisks[i];
   1303   1.34      fvdl 		if (strcmp(diskname, nip->ni_devname))
   1304   1.34      fvdl 			continue;
   1305   1.34      fvdl 		/*
   1306   1.62       dsl 		 * XXX listing possible matches is better. This is ok for
   1307   1.62       dsl 		 * now because the user has a chance to change it later.
   1308   1.62       dsl 		 * Also, if all the disks have the same parameters then we can
   1309   1.62       dsl 		 * just use them, we don't need to know which disk is which.
   1310   1.34      fvdl 		 */
   1311   1.34      fvdl 		if (nip->ni_nmatches != 0) {
   1312   1.34      fvdl 			bip = &dl->dl_biosdisks[nip->ni_biosmatches[0]];
   1313   1.34      fvdl 			dos_cylinders = bip->bi_cyl;
   1314   1.34      fvdl 			dos_heads = bip->bi_head;
   1315   1.34      fvdl 			dos_sectors = bip->bi_sec;
   1316   1.62       dsl 			if (bip->bi_lbasecs)
   1317   1.62       dsl 				dos_disksectors = bip->bi_lbasecs;
   1318   1.34      fvdl 			return;
   1319   1.34      fvdl 		}
   1320   1.34      fvdl 	}
   1321   1.81       dbj  out:
   1322  1.129       dsl #endif
   1323   1.34      fvdl 	/* Allright, allright, make a stupid guess.. */
   1324   1.34      fvdl 	intuit_translated_geometry();
   1325   1.11   ghudson }
   1326   1.62       dsl 
   1327   1.62       dsl #ifdef BOOTSEL
   1328  1.132     joerg static daddr_t
   1329   1.62       dsl get_default_boot(void)
   1330   1.62       dsl {
   1331   1.90    dyoung 	unsigned int id;
   1332   1.62       dsl 	int p;
   1333   1.62       dsl 
   1334   1.96       dsl 	if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1335   1.62       dsl 		/* default to first active partition */
   1336   1.62       dsl 		return DEFAULT_ACTIVE;
   1337   1.62       dsl 
   1338   1.71     lukem 	id = mboot.mbr_bootsel.mbrbs_defkey;
   1339   1.62       dsl 
   1340  1.115       dsl 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII) {
   1341  1.115       dsl 		/* Keycode is ascii */
   1342  1.115       dsl 		if (id == '\r')
   1343  1.115       dsl 		    return DEFAULT_ACTIVE;
   1344  1.115       dsl 		/* '1'+ => allocated partition id, 'a'+ => disk 0+ */
   1345  1.115       dsl 		if (id >= 'a' && id < 'a' + MAX_BIOS_DISKS)
   1346  1.115       dsl 			return DEFAULT_DISK(id - 'a');
   1347  1.115       dsl 		id -= '1';
   1348  1.115       dsl 	} else {
   1349  1.115       dsl 		/* keycode is PS/2 keycode */
   1350  1.115       dsl 		if (id == SCAN_ENTER)
   1351  1.115       dsl 			return DEFAULT_ACTIVE;
   1352  1.115       dsl 		/* 1+ => allocated partition id, F1+ => disk 0+ */
   1353  1.115       dsl 		if (id >= SCAN_F1 && id < SCAN_F1 + MAX_BIOS_DISKS)
   1354  1.115       dsl 			return DEFAULT_DISK(id - SCAN_F1);
   1355  1.115       dsl 		id -= SCAN_1;
   1356  1.115       dsl 	}
   1357  1.115       dsl 
   1358  1.115       dsl 	/* Convert partition index to the invariant start sector number */
   1359   1.62       dsl 
   1360   1.71     lukem 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1361   1.71     lukem 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1362   1.62       dsl 			continue;
   1363   1.71     lukem 		if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1364   1.62       dsl 			continue;
   1365   1.62       dsl 		if (id-- == 0)
   1366   1.62       dsl 			return le32toh(mboot.mbr_parts[p].mbrp_start);
   1367   1.62       dsl 	}
   1368   1.62       dsl 
   1369   1.62       dsl 	for (p = 0; p < ext.num_ptn; p++) {
   1370   1.71     lukem 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1371   1.62       dsl 			continue;
   1372   1.71     lukem 		if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1373   1.62       dsl 			continue;
   1374   1.62       dsl 		if (id-- == 0)
   1375   1.62       dsl 			return ext_offset(p)
   1376   1.62       dsl 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start);
   1377   1.62       dsl 	}
   1378   1.62       dsl 
   1379   1.62       dsl 	return DEFAULT_ACTIVE;
   1380   1.62       dsl }
   1381   1.11   ghudson 
   1382  1.132     joerg static void
   1383   1.62       dsl set_default_boot(daddr_t default_ptn)
   1384   1.34      fvdl {
   1385   1.62       dsl 	int p;
   1386  1.115       dsl 	static const unsigned char key_list[] = { SCAN_ENTER, SCAN_F1, SCAN_1,
   1387  1.115       dsl 						'\r', 'a', '1' };
   1388  1.115       dsl 	const unsigned char *key = key_list;
   1389   1.34      fvdl 
   1390   1.96       dsl 	if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1391   1.62       dsl 		/* sanity */
   1392   1.62       dsl 		return;
   1393   1.34      fvdl 
   1394  1.115       dsl 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII)
   1395  1.115       dsl 		/* Use ascii values */
   1396  1.115       dsl 		key += 3;
   1397  1.115       dsl 
   1398   1.62       dsl 	if (default_ptn == DEFAULT_ACTIVE) {
   1399  1.115       dsl 		mboot.mbr_bootsel.mbrbs_defkey = key[0];
   1400   1.34      fvdl 		return;
   1401   1.34      fvdl 	}
   1402   1.34      fvdl 
   1403  1.115       dsl 	if (default_ptn >= DEFAULT_DISK(0)
   1404  1.115       dsl 	    && default_ptn < DEFAULT_DISK(MAX_BIOS_DISKS)) {
   1405  1.115       dsl 		mboot.mbr_bootsel.mbrbs_defkey = key[1]
   1406  1.115       dsl 		    + default_ptn - DEFAULT_DISK(0);
   1407  1.115       dsl 		return;
   1408  1.115       dsl 	}
   1409  1.115       dsl 
   1410  1.115       dsl 	mboot.mbr_bootsel.mbrbs_defkey = key[2];
   1411   1.71     lukem 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1412   1.71     lukem 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1413   1.62       dsl 			continue;
   1414   1.71     lukem 		if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1415   1.62       dsl 			continue;
   1416  1.115       dsl 		if (le32toh(mboot.mbr_parts[p].mbrp_start) == default_ptn)
   1417   1.34      fvdl 			return;
   1418  1.115       dsl 		mboot.mbr_bootsel.mbrbs_defkey++;
   1419   1.62       dsl 	}
   1420   1.62       dsl 
   1421   1.71     lukem 	if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_EXTLBA) {
   1422   1.62       dsl 		for (p = 0; p < ext.num_ptn; p++) {
   1423   1.71     lukem 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1424   1.62       dsl 				continue;
   1425   1.71     lukem 			if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1426   1.62       dsl 				continue;
   1427   1.62       dsl 			if (le32toh(ext.ptn[p].mbr_parts[0].mbrp_start) +
   1428  1.115       dsl 			    ext_offset(p) == default_ptn)
   1429   1.34      fvdl 				return;
   1430  1.115       dsl 			mboot.mbr_bootsel.mbrbs_defkey++;
   1431   1.34      fvdl 		}
   1432   1.34      fvdl 	}
   1433   1.34      fvdl 
   1434   1.62       dsl 	/* Default to first active partition */
   1435  1.115       dsl 	mboot.mbr_bootsel.mbrbs_defkey = key[0];
   1436   1.62       dsl }
   1437   1.34      fvdl 
   1438  1.132     joerg static void
   1439   1.62       dsl install_bootsel(int needed)
   1440   1.62       dsl {
   1441   1.62       dsl 	struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
   1442   1.62       dsl 	int p;
   1443   1.62       dsl 	int ext13 = 0;
   1444   1.92  christos 	const char *code;
   1445   1.62       dsl 
   1446   1.76     lukem 	needed |= MBR_BS_NEWMBR;	/* need new bootsel code */
   1447   1.76     lukem 
   1448   1.62       dsl 	/* Work out which boot code we need for this configuration */
   1449   1.71     lukem 	for (p = 0; p < MBR_PART_COUNT; p++) {
   1450   1.71     lukem 		if (mboot.mbr_parts[p].mbrp_type == 0)
   1451   1.62       dsl 			continue;
   1452   1.96       dsl 		if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1453   1.34      fvdl 			break;
   1454   1.71     lukem 		if (mbs->mbrbs_nametab[p][0] == 0)
   1455   1.62       dsl 			continue;
   1456   1.71     lukem 		needed |= MBR_BS_ACTIVE;
   1457   1.62       dsl 		if (le32toh(mboot.mbr_parts[p].mbrp_start) >= dos_totalsectors)
   1458   1.71     lukem 			ext13 = MBR_BS_EXTINT13;
   1459   1.62       dsl 	}
   1460   1.62       dsl 
   1461   1.62       dsl 	for (p = 0; p < ext.num_ptn; p++) {
   1462   1.96       dsl 		if (ext.ptn[p].mbr_bootsel_magic != LE_MBR_BS_MAGIC)
   1463   1.34      fvdl 			continue;
   1464   1.71     lukem 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1465   1.62       dsl 			continue;
   1466   1.71     lukem 		if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[p][0] == 0)
   1467   1.34      fvdl 			continue;
   1468   1.71     lukem 		needed |= MBR_BS_EXTLBA | MBR_BS_ACTIVE;
   1469   1.62       dsl 	}
   1470   1.34      fvdl 
   1471   1.62       dsl 	if (B_flag)
   1472   1.71     lukem 		needed |= MBR_BS_ACTIVE;
   1473   1.38     soren 
   1474   1.62       dsl 	/* Is the installed code good enough ? */
   1475   1.76     lukem 	if (!i_flag && (needed == 0 ||
   1476   1.96       dsl 	    (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
   1477   1.71     lukem 	    && (mbs->mbrbs_flags & needed) == needed))) {
   1478   1.62       dsl 		/* yes - just set flags */
   1479   1.71     lukem 		mbs->mbrbs_flags |= ext13;
   1480   1.62       dsl 		return;
   1481   1.34      fvdl 	}
   1482   1.34      fvdl 
   1483   1.62       dsl 	/* ok - we need to replace the bootcode */
   1484   1.34      fvdl 
   1485   1.62       dsl 	if (f_flag && !(i_flag || B_flag)) {
   1486   1.62       dsl 		warnx("Installed bootfile doesn't support required options.");
   1487   1.62       dsl 		return;
   1488   1.62       dsl 	}
   1489   1.62       dsl 
   1490   1.78       dsl 	if (!f_flag && bootsize == 0 && !i_flag)
   1491   1.62       dsl 		/* Output an explanation for the 'update bootcode' prompt. */
   1492   1.76     lukem 		printf("\n%s\n",
   1493   1.76     lukem 		    "Installed bootfile doesn't support required options.");
   1494   1.62       dsl 
   1495   1.62       dsl 	/* Were we told a specific file ? (which we have already read) */
   1496   1.62       dsl 	/* If so check that it supports what we need. */
   1497   1.62       dsl 	if (bootsize != 0 && needed != 0
   1498   1.96       dsl 	    && (bootcode[0].mbr_bootsel_magic != LE_MBR_BS_MAGIC
   1499   1.71     lukem 	    || ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed))) {
   1500   1.62       dsl 		/* No it doesn't... */
   1501   1.62       dsl 		if (f_flag)
   1502   1.62       dsl 			warnx("Bootfile %s doesn't support "
   1503   1.62       dsl 				    "required bootsel options", boot_path );
   1504   1.62       dsl 			/* But install it anyway */
   1505   1.62       dsl 		else
   1506   1.62       dsl 			if (yesno("Bootfile %s doesn't support the required "
   1507   1.62       dsl 			    "options,\ninstall default bootfile instead?",
   1508   1.62       dsl 			    boot_path))
   1509   1.62       dsl 				bootsize = 0;
   1510   1.34      fvdl 	}
   1511   1.34      fvdl 
   1512   1.62       dsl 	if (bootsize == 0) {
   1513   1.62       dsl 		/* Get name of bootfile that supports the required facilities */
   1514   1.62       dsl 		code = DEFAULT_BOOTCODE;
   1515   1.71     lukem 		if (needed & MBR_BS_ACTIVE)
   1516   1.62       dsl 			code = DEFAULT_BOOTSELCODE;
   1517   1.62       dsl #ifdef DEFAULT_BOOTEXTCODE
   1518   1.71     lukem 		if (needed & MBR_BS_EXTLBA)
   1519   1.62       dsl 			code = DEFAULT_BOOTEXTCODE;
   1520   1.62       dsl #endif
   1521   1.62       dsl 
   1522   1.62       dsl 		bootsize = read_boot(code, bootcode, sizeof bootcode, 0);
   1523   1.62       dsl 		if (bootsize == 0)
   1524   1.62       dsl 			/* The old bootcode is better than no bootcode at all */
   1525   1.62       dsl 			return;
   1526   1.71     lukem 		if ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed)
   1527   1.62       dsl 			warnx("Default bootfile %s doesn't support required "
   1528   1.62       dsl 				"options.  Got flags 0x%x, wanted 0x%x\n",
   1529   1.71     lukem 				boot_path, bootcode[0].mbr_bootsel.mbrbs_flags,
   1530   1.62       dsl 				needed);
   1531   1.34      fvdl 	}
   1532   1.34      fvdl 
   1533   1.62       dsl 	if (!f_flag && !yesno("Update the bootcode from %s?", boot_path))
   1534   1.62       dsl 		return;
   1535   1.37   thorpej 
   1536   1.62       dsl 	init_sector0(0);
   1537   1.34      fvdl 
   1538   1.96       dsl 	if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   1539   1.71     lukem 		mbs->mbrbs_flags = bootcode[0].mbr_bootsel.mbrbs_flags | ext13;
   1540   1.62       dsl }
   1541   1.34      fvdl 
   1542  1.132     joerg static daddr_t
   1543   1.62       dsl configure_bootsel(daddr_t default_ptn)
   1544   1.62       dsl {
   1545   1.62       dsl 	struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
   1546   1.62       dsl 	int i, item, opt;
   1547   1.62       dsl 	int tmo;
   1548   1.62       dsl 	daddr_t *off;
   1549   1.62       dsl 	int num_bios_disks;
   1550   1.34      fvdl 
   1551  1.130       dsl #if defined(USE_DISKLIST)
   1552   1.62       dsl 	if (dl != NULL) {
   1553   1.62       dsl 		num_bios_disks = dl->dl_nbiosdisks;
   1554  1.115       dsl 		if (num_bios_disks > MAX_BIOS_DISKS)
   1555  1.115       dsl 			num_bios_disks = MAX_BIOS_DISKS;
   1556   1.62       dsl 	} else
   1557   1.91    dyoung #endif
   1558  1.115       dsl 		num_bios_disks = MAX_BIOS_DISKS;
   1559   1.34      fvdl 
   1560   1.62       dsl 	printf("\nBoot selector configuration:\n");
   1561   1.34      fvdl 
   1562   1.62       dsl 	/* The timeout value is in ticks, ~18.2 Hz. Avoid using floats.
   1563   1.62       dsl 	 * Ticks are nearly 64k/3600 - so our long timers are sligtly out!
   1564   1.62       dsl 	 * Newer bootcode always waits for 1 tick, so treats 0xffff
   1565   1.62       dsl 	 * as wait forever.
   1566   1.62       dsl 	 */
   1567   1.71     lukem 	tmo = le16toh(mbs->mbrbs_timeo);
   1568   1.62       dsl 	tmo = tmo == 0xffff ? -1 : (10 * tmo + 9) / 182;
   1569   1.62       dsl 	tmo = decimal("Timeout value (0 to 3600 seconds, -1 => never)",
   1570   1.62       dsl 			tmo, 0, -1, 3600);
   1571   1.71     lukem 	mbs->mbrbs_timeo = htole16(tmo == -1 ? 0xffff : (tmo * 182) / 10);
   1572   1.62       dsl 
   1573   1.71     lukem 	off = calloc(1 + MBR_PART_COUNT + ext.num_ptn + num_bios_disks, sizeof *off);
   1574   1.62       dsl 	if (off == NULL)
   1575   1.62       dsl 		err(1, "Malloc failed");
   1576   1.34      fvdl 
   1577   1.62       dsl 	printf("Select the default boot option. Options are:\n\n");
   1578   1.62       dsl 	item = 0;
   1579   1.62       dsl 	opt = 0;
   1580   1.62       dsl 	off[opt] = DEFAULT_ACTIVE;
   1581   1.62       dsl 	printf("%d: The first active partition\n", opt);
   1582   1.71     lukem 	for (i = 0; i < MBR_PART_COUNT; i++) {
   1583   1.71     lukem 		if (mboot.mbr_parts[i].mbrp_type == 0)
   1584   1.62       dsl 			continue;
   1585   1.71     lukem 		if (mbs->mbrbs_nametab[i][0] == 0)
   1586   1.62       dsl 			continue;
   1587   1.71     lukem 		printf("%d: %s\n", ++opt, &mbs->mbrbs_nametab[i][0]);
   1588   1.62       dsl 		off[opt] = le32toh(mboot.mbr_parts[i].mbrp_start);
   1589   1.62       dsl 		if (off[opt] == default_ptn)
   1590   1.62       dsl 			item = opt;
   1591   1.62       dsl 	}
   1592   1.71     lukem 	if (mbs->mbrbs_flags & MBR_BS_EXTLBA) {
   1593   1.62       dsl 		for (i = 0; i < ext.num_ptn; i++) {
   1594   1.71     lukem 			if (ext.ptn[i].mbr_parts[0].mbrp_type == 0)
   1595   1.62       dsl 				continue;
   1596   1.71     lukem 			if (ext.ptn[i].mbr_bootsel.mbrbs_nametab[0][0] == 0)
   1597   1.62       dsl 				continue;
   1598   1.62       dsl 			printf("%d: %s\n",
   1599   1.71     lukem 			    ++opt, ext.ptn[i].mbr_bootsel.mbrbs_nametab[0]);
   1600   1.62       dsl 			off[opt] = ext_offset(i) +
   1601   1.62       dsl 			    le32toh(ext.ptn[i].mbr_parts[0].mbrp_start);
   1602   1.62       dsl 			if (off[opt] == default_ptn)
   1603   1.62       dsl 				item = opt;
   1604   1.35      fvdl 		}
   1605   1.35      fvdl 	}
   1606   1.62       dsl 	for (i = 0; i < num_bios_disks; i++) {
   1607   1.62       dsl 		printf("%d: Harddisk %d\n", ++opt, i);
   1608  1.115       dsl 		off[opt] = DEFAULT_DISK(i);
   1609  1.115       dsl 		if (DEFAULT_DISK(i) == default_ptn)
   1610   1.62       dsl 			item = opt;
   1611   1.62       dsl 	}
   1612   1.35      fvdl 
   1613   1.62       dsl 	item = decimal("Default boot option", item, 0, 0, opt);
   1614   1.62       dsl 
   1615   1.62       dsl 	default_ptn = off[item];
   1616   1.62       dsl 	free(off);
   1617   1.62       dsl 	return default_ptn;
   1618   1.34      fvdl }
   1619   1.77     lukem #endif /* BOOTSEL */
   1620   1.34      fvdl 
   1621   1.34      fvdl 
   1622   1.11   ghudson /* Prerequisite: the disklabel parameters and master boot record must
   1623   1.11   ghudson  *		 have been read (i.e. dos_* and mboot are meaningful).
   1624   1.11   ghudson  * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
   1625   1.11   ghudson  *		  dos_cylindersectors to be consistent with what the
   1626   1.11   ghudson  *		  partition table is using, if we can find a geometry
   1627   1.11   ghudson  *		  which is consistent with all partition table entries.
   1628   1.11   ghudson  *		  We may get the number of cylinders slightly wrong (in
   1629   1.11   ghudson  *		  the conservative direction).  The idea is to be able
   1630   1.11   ghudson  *		  to create a NetBSD partition on a disk we don't know
   1631   1.11   ghudson  *		  the translated geometry of.
   1632   1.62       dsl  * This routine is only used for non-x86 systems or when we fail to
   1633   1.62       dsl  * get the BIOS geometry from the kernel.
   1634   1.62       dsl  */
   1635  1.132     joerg static void
   1636   1.43     lukem intuit_translated_geometry(void)
   1637   1.11   ghudson {
   1638  1.118     lukem 	uint32_t xcylinders;
   1639  1.118     lukem 	int xheads = -1, xsectors = -1, i, j;
   1640   1.90    dyoung 	unsigned int c1, h1, s1, c2, h2, s2;
   1641   1.90    dyoung 	unsigned long a1, a2;
   1642   1.62       dsl 	uint64_t num, denom;
   1643   1.62       dsl 
   1644   1.62       dsl 	/*
   1645   1.62       dsl 	 * The physical parameters may be invalid as bios geometry.
   1646   1.62       dsl 	 * If we cannot determine the actual bios geometry, we are
   1647   1.62       dsl 	 * better off picking a likely 'faked' geometry than leaving
   1648   1.62       dsl 	 * the invalid physical one.
   1649   1.62       dsl 	 */
   1650   1.15      phil 
   1651   1.62       dsl 	if (dos_cylinders > MAXCYL || dos_heads > MAXHEAD ||
   1652   1.62       dsl 	    dos_sectors > MAXSECTOR) {
   1653   1.62       dsl 		h1 = MAXHEAD - 1;
   1654   1.62       dsl 		c1 = MAXCYL - 1;
   1655  1.130       dsl #if defined(USE_DISKLIST)
   1656   1.62       dsl 		if (dl != NULL) {
   1657   1.62       dsl 			/* BIOS may use 256 heads or 1024 cylinders */
   1658   1.62       dsl 			for (i = 0; i < dl->dl_nbiosdisks; i++) {
   1659  1.118     lukem 				if (h1 < (unsigned int)dl->dl_biosdisks[i].bi_head)
   1660   1.62       dsl 					h1 = dl->dl_biosdisks[i].bi_head;
   1661  1.118     lukem 				if (c1 < (unsigned int)dl->dl_biosdisks[i].bi_cyl)
   1662   1.62       dsl 					c1 = dl->dl_biosdisks[i].bi_cyl;
   1663   1.62       dsl 			}
   1664   1.62       dsl 		}
   1665   1.62       dsl #endif
   1666   1.62       dsl 		dos_sectors = MAXSECTOR;
   1667   1.62       dsl 		dos_heads = h1;
   1668   1.62       dsl 		dos_cylinders = disklabel.d_secperunit / (MAXSECTOR * h1);
   1669   1.62       dsl 		if (dos_cylinders > c1)
   1670   1.62       dsl 			dos_cylinders = c1;
   1671   1.62       dsl 	}
   1672   1.11   ghudson 
   1673   1.11   ghudson 	/* Try to deduce the number of heads from two different mappings. */
   1674   1.71     lukem 	for (i = 0; i < MBR_PART_COUNT * 2 - 1; i++) {
   1675   1.11   ghudson 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
   1676   1.11   ghudson 			continue;
   1677   1.82       dsl 		a1 -= s1;
   1678   1.71     lukem 		for (j = i + 1; j < MBR_PART_COUNT * 2; j++) {
   1679   1.11   ghudson 			if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
   1680   1.11   ghudson 				continue;
   1681   1.62       dsl 			a2 -= s2;
   1682   1.62       dsl 			num = (uint64_t)h1 * a2 - (uint64_t)h2 * a1;
   1683   1.62       dsl 			denom = (uint64_t)c2 * a1 - (uint64_t)c1 * a2;
   1684  1.114   tsutsui 			if (denom != 0 && num != 0 && num % denom == 0) {
   1685   1.44     lukem 				xheads = num / denom;
   1686   1.62       dsl 				xsectors = a1 / (c1 * xheads + h1);
   1687   1.11   ghudson 				break;
   1688   1.11   ghudson 			}
   1689   1.11   ghudson 		}
   1690   1.44     lukem 		if (xheads != -1)
   1691   1.11   ghudson 			break;
   1692   1.11   ghudson 	}
   1693   1.11   ghudson 
   1694  1.101  christos 	if (xheads == -1) {
   1695  1.144  christos 		if (F_flag)
   1696  1.144  christos 			return;
   1697  1.101  christos 		warnx("Cannot determine the number of heads");
   1698  1.101  christos 		return;
   1699  1.101  christos 	}
   1700   1.11   ghudson 
   1701  1.118     lukem 	if (xsectors == -1) {
   1702  1.118     lukem 		warnx("Cannot determine the number of sectors");
   1703  1.118     lukem 		return;
   1704  1.118     lukem 	}
   1705  1.118     lukem 
   1706   1.11   ghudson 	/* Estimate the number of cylinders. */
   1707   1.44     lukem 	xcylinders = disklabel.d_secperunit / xheads / xsectors;
   1708   1.67       dsl 	if (disklabel.d_secperunit > xcylinders * xheads * xsectors)
   1709   1.67       dsl 		xcylinders++;
   1710   1.11   ghudson 
   1711   1.62       dsl 	/*
   1712   1.62       dsl 	 * Now verify consistency with each of the partition table entries.
   1713   1.11   ghudson 	 * Be willing to shove cylinders up a little bit to make things work,
   1714   1.62       dsl 	 * but translation mismatches are fatal.
   1715   1.62       dsl 	 */
   1716   1.71     lukem 	for (i = 0; i < MBR_PART_COUNT * 2; i++) {
   1717   1.11   ghudson 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
   1718   1.11   ghudson 			continue;
   1719   1.67       dsl 		if (c1 >= MAXCYL - 2)
   1720   1.67       dsl 			continue;
   1721   1.44     lukem 		if (xsectors * (c1 * xheads + h1) + s1 != a1)
   1722   1.11   ghudson 			return;
   1723   1.11   ghudson 	}
   1724   1.11   ghudson 
   1725   1.62       dsl 
   1726   1.62       dsl 	/* Everything checks out.
   1727   1.62       dsl 	 * Reset the geometry to use for further calculations.
   1728   1.67       dsl 	 * But cylinders cannot be > 1024.
   1729   1.62       dsl 	 */
   1730   1.67       dsl 	if (xcylinders > MAXCYL)
   1731   1.67       dsl 		dos_cylinders = MAXCYL;
   1732   1.67       dsl 	else
   1733   1.62       dsl 		dos_cylinders = xcylinders;
   1734   1.44     lukem 	dos_heads = xheads;
   1735   1.44     lukem 	dos_sectors = xsectors;
   1736   1.11   ghudson }
   1737   1.11   ghudson 
   1738   1.62       dsl /*
   1739   1.62       dsl  * For the purposes of intuit_translated_geometry(), treat the partition
   1740   1.11   ghudson  * table as a list of eight mapping between (cylinder, head, sector)
   1741   1.11   ghudson  * triplets and absolute sectors.  Get the relevant geometry triplet and
   1742   1.11   ghudson  * absolute sectors for a given entry, or return -1 if it isn't present.
   1743   1.62       dsl  * Note: for simplicity, the returned sector is 0-based.
   1744   1.62       dsl  */
   1745  1.132     joerg static int
   1746   1.90    dyoung get_mapping(int i, unsigned int *cylinder, unsigned int *head, unsigned int *sector,
   1747   1.43     lukem     unsigned long *absolute)
   1748   1.11   ghudson {
   1749   1.71     lukem 	struct mbr_partition *part = &mboot.mbr_parts[i / 2];
   1750   1.11   ghudson 
   1751   1.71     lukem 	if (part->mbrp_type == 0)
   1752   1.11   ghudson 		return -1;
   1753   1.11   ghudson 	if (i % 2 == 0) {
   1754   1.32   thorpej 		*cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
   1755   1.32   thorpej 		*head = part->mbrp_shd;
   1756  1.114   tsutsui 		*sector = MBR_PSECT(part->mbrp_ssect);
   1757   1.62       dsl 		*absolute = le32toh(part->mbrp_start);
   1758   1.11   ghudson 	} else {
   1759   1.32   thorpej 		*cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
   1760   1.32   thorpej 		*head = part->mbrp_ehd;
   1761  1.114   tsutsui 		*sector = MBR_PSECT(part->mbrp_esect);
   1762   1.62       dsl 		*absolute = le32toh(part->mbrp_start)
   1763   1.62       dsl 		    + le32toh(part->mbrp_size) - 1;
   1764   1.11   ghudson 	}
   1765  1.100  christos 	/* Sanity check the data against all zeroes */
   1766  1.100  christos 	if ((*cylinder == 0) && (*sector == 0) && (*head == 0))
   1767  1.100  christos 		return -1;
   1768  1.114   tsutsui 	/* sector numbers in the MBR partition table start at 1 */
   1769  1.114   tsutsui 	*sector = *sector - 1;
   1770   1.62       dsl 	/* Sanity check the data against max values */
   1771   1.62       dsl 	if ((((*cylinder * MAXHEAD) + *head) * MAXSECTOR + *sector) < *absolute)
   1772   1.62       dsl 		/* cannot be a CHS mapping */
   1773   1.62       dsl 		return -1;
   1774   1.11   ghudson 	return 0;
   1775    1.1       cgd }
   1776    1.1       cgd 
   1777   1.62       dsl static void
   1778   1.62       dsl delete_ptn(int part)
   1779   1.62       dsl {
   1780   1.62       dsl 	if (part == ext.ptn_id) {
   1781   1.62       dsl 		/* forget all about the extended partition */
   1782   1.62       dsl 		free(ext.ptn);
   1783   1.62       dsl 		memset(&ext, 0, sizeof ext);
   1784   1.62       dsl 	}
   1785   1.62       dsl 
   1786   1.71     lukem 	mboot.mbr_parts[part].mbrp_type = 0;
   1787   1.62       dsl }
   1788   1.62       dsl 
   1789   1.62       dsl static void
   1790   1.62       dsl delete_ext_ptn(int part)
   1791    1.1       cgd {
   1792    1.1       cgd 
   1793   1.62       dsl 	if (part == 0) {
   1794   1.71     lukem 		ext.ptn[0].mbr_parts[0].mbrp_type = 0;
   1795   1.62       dsl 		return;
   1796   1.62       dsl 	}
   1797   1.62       dsl 	ext.ptn[part - 1].mbr_parts[1] = ext.ptn[part].mbr_parts[1];
   1798   1.62       dsl 	memmove(&ext.ptn[part], &ext.ptn[part + 1],
   1799   1.62       dsl 		(ext.num_ptn - part - 1) * sizeof ext.ptn[0]);
   1800   1.62       dsl 	ext.num_ptn--;
   1801   1.62       dsl }
   1802    1.1       cgd 
   1803   1.62       dsl static int
   1804   1.62       dsl add_ext_ptn(daddr_t start, daddr_t size)
   1805   1.62       dsl {
   1806   1.62       dsl 	int part;
   1807   1.71     lukem 	struct mbr_partition *partp;
   1808   1.71     lukem 	struct mbr_sector *nptn;
   1809   1.62       dsl 
   1810   1.70    itojun 	nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
   1811   1.70    itojun 	if (!nptn)
   1812   1.70    itojun 		err(1, "realloc");
   1813   1.70    itojun 	ext.ptn = nptn;
   1814   1.62       dsl 	for (part = 0; part < ext.num_ptn; part++)
   1815   1.62       dsl 		if (ext_offset(part) > start)
   1816   1.62       dsl 			break;
   1817   1.62       dsl 	/* insert before 'part' - make space... */
   1818   1.62       dsl 	memmove(&ext.ptn[part + 1], &ext.ptn[part],
   1819   1.62       dsl 		(ext.num_ptn - part) * sizeof ext.ptn[0]);
   1820   1.62       dsl 	memset(&ext.ptn[part], 0, sizeof ext.ptn[0]);
   1821   1.96       dsl 	ext.ptn[part].mbr_magic = LE_MBR_MAGIC;
   1822   1.62       dsl 	/* we will be 'part' */
   1823   1.62       dsl 	if (part == 0) {
   1824   1.62       dsl 		/* link us to 'next' */
   1825   1.62       dsl 		partp = &ext.ptn[0].mbr_parts[1];
   1826   1.62       dsl 		/* offset will be fixed by caller */
   1827   1.62       dsl 		partp->mbrp_size = htole32(
   1828   1.62       dsl 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_start) +
   1829   1.62       dsl 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_size));
   1830   1.62       dsl 	} else {
   1831   1.62       dsl 		/* link us to prev's next */
   1832   1.62       dsl 		partp = &ext.ptn[part - 1].mbr_parts[1];
   1833   1.62       dsl 		ext.ptn[part].mbr_parts[1] = *partp;
   1834   1.62       dsl 		/* and prev onto us */
   1835  1.130       dsl 		partp->mbrp_start = htole32(start - ptn_0_offset - ext.base);
   1836  1.130       dsl 		partp->mbrp_size = htole32(size + ptn_0_offset);
   1837   1.62       dsl 	}
   1838   1.71     lukem 	partp->mbrp_type = 5;	/* as used by win98 */
   1839   1.62       dsl 	partp->mbrp_flag = 0;
   1840   1.62       dsl 	/* wallop in some CHS values - win98 doesn't saturate them */
   1841   1.62       dsl 	dos(le32toh(partp->mbrp_start),
   1842   1.62       dsl 	    &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
   1843   1.62       dsl 	dos(le32toh(partp->mbrp_start) + le32toh(partp->mbrp_size) - 1,
   1844   1.62       dsl 	    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
   1845   1.62       dsl 	ext.num_ptn++;
   1846   1.62       dsl 
   1847   1.62       dsl 	return part;
   1848   1.62       dsl }
   1849   1.62       dsl 
   1850   1.62       dsl static const char *
   1851   1.62       dsl check_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
   1852   1.62       dsl {
   1853   1.62       dsl 	int p;
   1854   1.90    dyoung 	unsigned int p_s, p_e;
   1855   1.62       dsl 
   1856   1.62       dsl 	if (sysid != 0) {
   1857  1.113       apb 		if (start == 0)
   1858  1.113       apb 			return "Sector zero is reserved for the MBR";
   1859  1.113       apb #if 0
   1860  1.130       dsl 		if (start < ptn_0_offset)
   1861  1.113       apb 			/* This is just a convention, not a requirement */
   1862   1.62       dsl 			return "Track zero is reserved for the BIOS";
   1863  1.113       apb #endif
   1864  1.148  christos 		if (start + size > disksectors)
   1865   1.62       dsl 			return "Partition exceeds size of disk";
   1866   1.71     lukem 		for (p = 0; p < MBR_PART_COUNT; p++) {
   1867   1.71     lukem 			if (p == part || mboot.mbr_parts[p].mbrp_type == 0)
   1868   1.62       dsl 				continue;
   1869   1.62       dsl 			p_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   1870   1.62       dsl 			p_e = p_s + le32toh(mboot.mbr_parts[p].mbrp_size);
   1871   1.62       dsl 			if (start + size <= p_s || start >= p_e)
   1872   1.62       dsl 				continue;
   1873   1.62       dsl 			if (f_flag) {
   1874   1.62       dsl 				if (fix)
   1875   1.62       dsl 					delete_ptn(p);
   1876   1.62       dsl 				return 0;
   1877   1.62       dsl 			}
   1878   1.62       dsl 			return "Overlaps another partition";
   1879   1.62       dsl 		}
   1880   1.62       dsl 	}
   1881   1.62       dsl 
   1882   1.62       dsl 	/* Are we trying to create an extended partition */
   1883   1.71     lukem 	if (!MBR_IS_EXTENDED(mboot.mbr_parts[part].mbrp_type)) {
   1884   1.62       dsl 		/* this wasn't the extended partition */
   1885   1.62       dsl 		if (!MBR_IS_EXTENDED(sysid))
   1886   1.62       dsl 			return 0;
   1887   1.62       dsl 		/* making an extended partition */
   1888   1.62       dsl 		if (ext.base != 0) {
   1889   1.62       dsl 			if (!f_flag)
   1890   1.62       dsl 				return "There cannot be 2 extended partitions";
   1891   1.62       dsl 			if (fix)
   1892   1.62       dsl 				delete_ptn(ext.ptn_id);
   1893   1.62       dsl 		}
   1894   1.62       dsl 		if (fix) {
   1895   1.62       dsl 			/* allocate a new extended partition */
   1896   1.62       dsl 			ext.ptn = calloc(1, sizeof ext.ptn[0]);
   1897   1.62       dsl 			if (ext.ptn == NULL)
   1898   1.62       dsl 				err(1, "Malloc failed");
   1899   1.96       dsl 			ext.ptn[0].mbr_magic = LE_MBR_MAGIC;
   1900   1.62       dsl 			ext.ptn_id = part;
   1901   1.62       dsl 			ext.base = start;
   1902   1.62       dsl 			ext.limit = start + size;
   1903   1.62       dsl 			ext.num_ptn = 1;
   1904   1.62       dsl 		}
   1905   1.62       dsl 		return 0;
   1906   1.62       dsl 	}
   1907   1.62       dsl 
   1908   1.62       dsl 	/* Check we haven't cut space allocated to an extended ptn */
   1909   1.62       dsl 
   1910   1.62       dsl 	if (!MBR_IS_EXTENDED(sysid)) {
   1911   1.62       dsl 		/* no longer an extended partition */
   1912   1.62       dsl 		if (fix) {
   1913   1.62       dsl 			/* Kill all memory of the extended partitions */
   1914   1.62       dsl 			delete_ptn(part);
   1915   1.62       dsl 			return 0;
   1916   1.29        ws 		}
   1917   1.62       dsl 		if (ext.num_ptn == 0 ||
   1918   1.71     lukem 		    (ext.num_ptn == 1 && ext.ptn[0].mbr_parts[0].mbrp_type == 0))
   1919   1.62       dsl 			/* nothing in extended partition */
   1920   1.62       dsl 			return 0;
   1921   1.15      phil 		if (f_flag)
   1922   1.62       dsl 			return 0;
   1923   1.62       dsl 		if (yesno("Do you really want to delete all the extended partitions?"))
   1924   1.62       dsl 			return 0;
   1925   1.62       dsl 		return "Extended partition busy";
   1926   1.62       dsl 	}
   1927   1.62       dsl 
   1928   1.62       dsl 	if (le32toh(mboot.mbr_parts[part].mbrp_start) != ext.base)
   1929   1.62       dsl 		/* maybe impossible, but an extra sanity check */
   1930   1.62       dsl 		return 0;
   1931   1.62       dsl 
   1932   1.62       dsl 	for (p = ext.num_ptn; --p >= 0;) {
   1933   1.71     lukem 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1934   1.62       dsl 			continue;
   1935   1.62       dsl 		p_s = ext_offset(p);
   1936   1.62       dsl 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   1937   1.62       dsl 			  + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   1938   1.62       dsl 		if (p_s >= start && p_e <= start + size)
   1939   1.62       dsl 			continue;
   1940   1.62       dsl 		if (!f_flag)
   1941   1.62       dsl 			return "Extended partition outside main partition";
   1942   1.62       dsl 		if (fix)
   1943   1.62       dsl 			delete_ext_ptn(p);
   1944   1.62       dsl 	}
   1945   1.62       dsl 
   1946   1.62       dsl 	if (fix && start != ext.base) {
   1947   1.62       dsl 		/* The internal offsets need to be fixed up */
   1948   1.62       dsl 		for (p = 0; p < ext.num_ptn - 1; p++)
   1949   1.62       dsl 			ext.ptn[p].mbr_parts[1].mbrp_start = htole32(
   1950   1.62       dsl 			    le32toh(ext.ptn[p].mbr_parts[1].mbrp_start)
   1951   1.62       dsl 				    + ext.base - start);
   1952   1.62       dsl 		/* and maybe an empty partition at the start */
   1953   1.71     lukem 		if (ext.ptn[0].mbr_parts[0].mbrp_type == 0) {
   1954   1.62       dsl 			if (le32toh(ext.ptn[0].mbr_parts[1].mbrp_start) == 0) {
   1955   1.62       dsl 				/* don't need the empty slot */
   1956   1.62       dsl 				memmove(&ext.ptn[0], &ext.ptn[1],
   1957   1.62       dsl 					(ext.num_ptn - 1) * sizeof ext.ptn[0]);
   1958   1.62       dsl 				ext.num_ptn--;
   1959   1.62       dsl 			}
   1960   1.62       dsl 		} else {
   1961   1.62       dsl 			/* must create an empty slot */
   1962  1.130       dsl 			add_ext_ptn(start, ptn_0_offset);
   1963   1.62       dsl 			ext.ptn[0].mbr_parts[1].mbrp_start = htole32(ext.base
   1964   1.62       dsl 								- start);
   1965   1.62       dsl 		}
   1966   1.62       dsl 	}
   1967   1.62       dsl 	if (fix) {
   1968   1.62       dsl 		ext.base = start;
   1969   1.62       dsl 		ext.limit = start + size;
   1970   1.15      phil 	}
   1971   1.62       dsl 	return 0;
   1972   1.62       dsl }
   1973   1.15      phil 
   1974   1.62       dsl static const char *
   1975   1.62       dsl check_ext_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
   1976   1.62       dsl {
   1977   1.62       dsl 	int p;
   1978   1.90    dyoung 	unsigned int p_s, p_e;
   1979   1.62       dsl 
   1980   1.62       dsl 	if (sysid == 0)
   1981   1.62       dsl 		return 0;
   1982   1.62       dsl 
   1983   1.62       dsl 	if (MBR_IS_EXTENDED(sysid))
   1984   1.62       dsl 		return "Nested extended partitions are not allowed";
   1985   1.62       dsl 
   1986   1.62       dsl 	/* allow one track at start for extended partition header */
   1987  1.130       dsl 	start -= ptn_0_offset;
   1988  1.130       dsl 	size += ptn_0_offset;
   1989   1.62       dsl 	if (start < ext.base || start + size > ext.limit)
   1990   1.62       dsl 		return "Outside bounds of extended partition";
   1991   1.62       dsl 
   1992   1.62       dsl 	if (f_flag && !fix)
   1993   1.62       dsl 		return 0;
   1994   1.62       dsl 
   1995   1.62       dsl 	for (p = ext.num_ptn; --p >= 0;) {
   1996   1.71     lukem 		if (p == part || ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   1997   1.62       dsl 			continue;
   1998   1.62       dsl 		p_s = ext_offset(p);
   1999   1.62       dsl 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2000   1.62       dsl 			+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   2001   1.62       dsl 		if (p == 0)
   2002   1.62       dsl 			p_s += le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2003  1.130       dsl 							- ptn_0_offset;
   2004   1.62       dsl 		if (start < p_e && start + size > p_s) {
   2005   1.62       dsl 			if (!f_flag)
   2006   1.62       dsl 				return "Overlaps another extended partition";
   2007   1.62       dsl 			if (fix) {
   2008   1.62       dsl 				if (part == -1)
   2009   1.62       dsl 					delete_ext_ptn(p);
   2010   1.62       dsl 				else
   2011   1.62       dsl 					/* must not change numbering yet */
   2012   1.71     lukem 					ext.ptn[p].mbr_parts[0].mbrp_type = 0;
   2013   1.62       dsl 			}
   2014   1.62       dsl 		}
   2015   1.62       dsl 	}
   2016   1.62       dsl 	return 0;
   2017   1.62       dsl }
   2018    1.1       cgd 
   2019  1.132     joerg static int
   2020   1.62       dsl change_part(int extended, int part, int sysid, daddr_t start, daddr_t size,
   2021   1.62       dsl 	char *bootmenu)
   2022   1.62       dsl {
   2023   1.71     lukem 	struct mbr_partition *partp;
   2024   1.71     lukem 	struct mbr_sector *boot;
   2025   1.62       dsl 	daddr_t offset;
   2026   1.92  christos 	const char *e;
   2027   1.62       dsl 	int upart = part;
   2028   1.62       dsl 	int p;
   2029   1.62       dsl 	int fl;
   2030   1.62       dsl 	daddr_t n_s, n_e;
   2031   1.62       dsl 	const char *errtext;
   2032   1.62       dsl #ifdef BOOTSEL
   2033   1.71     lukem 	char tmp_bootmenu[MBR_PART_COUNT * (MBR_BS_PARTNAMESIZE + 1)];
   2034   1.71     lukem 	int bootmenu_len = (extended ? MBR_PART_COUNT : 1) * (MBR_BS_PARTNAMESIZE + 1);
   2035   1.62       dsl #endif
   2036    1.5   mycroft 
   2037   1.62       dsl 	if (extended) {
   2038   1.62       dsl 		if (part != -1 && part < ext.num_ptn) {
   2039   1.62       dsl 			boot = &ext.ptn[part];
   2040   1.62       dsl 			partp = &boot->mbr_parts[0];
   2041   1.62       dsl 			offset = ext_offset(part);
   2042    1.1       cgd 		} else {
   2043   1.62       dsl 			part = -1;
   2044   1.62       dsl 			boot = 0;
   2045   1.62       dsl 			partp = 0;
   2046   1.62       dsl 			offset = 0;
   2047   1.62       dsl 		}
   2048   1.62       dsl 		upart = 0;
   2049   1.62       dsl 		e = "E";
   2050   1.62       dsl 	} else {
   2051   1.62       dsl 		boot = &mboot;
   2052   1.62       dsl 		partp = &boot->mbr_parts[part];
   2053   1.62       dsl 		offset = 0;
   2054   1.62       dsl 		e = "";
   2055   1.62       dsl 	}
   2056   1.62       dsl 
   2057   1.62       dsl 	if (!f_flag && part != -1) {
   2058   1.62       dsl 		printf("The data for partition %s%d is:\n", e, part);
   2059   1.62       dsl 		print_part(boot, upart, offset);
   2060   1.62       dsl 	}
   2061   1.28        ws 
   2062   1.62       dsl #ifdef BOOTSEL
   2063   1.62       dsl 	if (bootmenu != NULL)
   2064   1.62       dsl 		strlcpy(tmp_bootmenu, bootmenu, bootmenu_len);
   2065   1.62       dsl 	else
   2066   1.96       dsl 		if (boot != NULL && boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   2067   1.62       dsl 			strlcpy(tmp_bootmenu,
   2068   1.71     lukem 				boot->mbr_bootsel.mbrbs_nametab[upart],
   2069   1.62       dsl 				bootmenu_len);
   2070   1.62       dsl 		else
   2071   1.62       dsl 			tmp_bootmenu[0] = 0;
   2072   1.62       dsl #endif
   2073   1.62       dsl 
   2074  1.147  christos 	if (partp != NULL) {
   2075  1.147  christos 		if (!s_flag) {
   2076  1.147  christos 			/* values not specified, default to current ones */
   2077  1.147  christos 			sysid = partp->mbrp_type;
   2078  1.147  christos 			start = offset + le32toh(partp->mbrp_start);
   2079  1.147  christos 			size = le32toh(partp->mbrp_size);
   2080  1.147  christos 		} else {
   2081  1.147  christos 			if (sysid == -1)
   2082  1.147  christos 				sysid = partp->mbrp_type;
   2083  1.148  christos 			if (start == (daddr_t)0xffffffff) {
   2084  1.147  christos 				start = offset + le32toh(partp->mbrp_start);
   2085  1.148  christos 				if (start == 0)
   2086  1.148  christos 					start = offset = ptn_0_offset;
   2087  1.148  christos 			}
   2088  1.148  christos 			if (size == (daddr_t)0xffffffff) {
   2089  1.147  christos 				size = le32toh(partp->mbrp_size);
   2090  1.148  christos 				if (size == 0)
   2091  1.148  christos 					size = disksectors - start;
   2092  1.148  christos 			}
   2093  1.147  christos 		}
   2094   1.62       dsl 	}
   2095   1.62       dsl 
   2096   1.62       dsl 	/* creating a new partition, default to free space */
   2097   1.62       dsl 	if (!s_flag && sysid == 0 && extended) {
   2098   1.62       dsl 		/* non-extended partition */
   2099   1.62       dsl 		start = ext.base;
   2100   1.62       dsl 		for (p = 0; p < ext.num_ptn; p++) {
   2101   1.71     lukem 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2102   1.62       dsl 				continue;
   2103   1.62       dsl 			n_s = ext_offset(p);
   2104  1.130       dsl 			if (n_s > start + ptn_0_offset)
   2105   1.62       dsl 				break;
   2106   1.62       dsl 			start = ext_offset(p)
   2107   1.62       dsl 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2108   1.62       dsl 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
   2109   1.62       dsl 		}
   2110  1.130       dsl 		if (ext.limit - start <= ptn_0_offset) {
   2111   1.62       dsl 			printf("No space in extended partition\n");
   2112   1.62       dsl 			return 0;
   2113   1.62       dsl 		}
   2114  1.130       dsl 		start += ptn_0_offset;
   2115   1.62       dsl 	}
   2116   1.62       dsl 
   2117   1.62       dsl 	if (!s_flag && sysid == 0 && !extended) {
   2118   1.62       dsl 		/* same for non-extended partition */
   2119   1.62       dsl 		/* first see if old start is free */
   2120  1.130       dsl 		if (start < ptn_0_offset)
   2121   1.62       dsl 			start = 0;
   2122   1.71     lukem 		for (p = 0; start != 0 && p < MBR_PART_COUNT; p++) {
   2123   1.71     lukem 			if (mboot.mbr_parts[p].mbrp_type == 0)
   2124   1.62       dsl 				continue;
   2125   1.62       dsl 			n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2126   1.62       dsl 			if (start >= n_s &&
   2127   1.62       dsl 			    start < n_s + le32toh(mboot.mbr_parts[p].mbrp_size))
   2128   1.62       dsl 				start = 0;
   2129   1.62       dsl 		}
   2130   1.62       dsl 		if (start == 0) {
   2131   1.62       dsl 			/* Look for first gap */
   2132  1.130       dsl 			start = ptn_0_offset;
   2133   1.71     lukem 			for (p = 0; p < MBR_PART_COUNT; p++) {
   2134   1.71     lukem 				if (mboot.mbr_parts[p].mbrp_type == 0)
   2135   1.62       dsl 					continue;
   2136   1.62       dsl 				n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2137   1.62       dsl 				n_e = n_s + le32toh(mboot.mbr_parts[p].mbrp_size);
   2138   1.62       dsl 				if (start >= n_s && start < n_e) {
   2139   1.62       dsl 					start = n_e;
   2140   1.62       dsl 					p = -1;
   2141   1.62       dsl 				}
   2142   1.62       dsl 			}
   2143  1.138  christos 			if (start >= disksectors && !I_flag) {
   2144   1.62       dsl 				printf("No free space\n");
   2145   1.62       dsl 				return 0;
   2146   1.29        ws 			}
   2147    1.1       cgd 		}
   2148   1.62       dsl 	}
   2149    1.4   mycroft 
   2150   1.62       dsl 	if (!f_flag) {
   2151   1.62       dsl 		/* request new values from user */
   2152   1.62       dsl 		if (sysid == 0)
   2153   1.62       dsl 			sysid = 169;
   2154   1.62       dsl 		sysid = decimal("sysid", sysid, 0, 0, 255);
   2155   1.62       dsl 		if (sysid == 0 && !v_flag) {
   2156   1.62       dsl 			start = 0;
   2157   1.62       dsl 			size = 0;
   2158   1.62       dsl #ifdef BOOTSEL
   2159   1.62       dsl 			tmp_bootmenu[0] = 0;
   2160   1.62       dsl #endif
   2161   1.62       dsl 		} else {
   2162   1.62       dsl 			daddr_t old = start;
   2163   1.79       dsl 			daddr_t lim = extended ? ext.limit : disksectors;
   2164   1.62       dsl 			start = decimal("start", start,
   2165   1.62       dsl 				DEC_SEC | DEC_RND_0 | (extended ? DEC_RND : 0),
   2166   1.62       dsl 				extended ? ext.base : 0, lim);
   2167   1.62       dsl 			/* Adjust 'size' so that end doesn't move when 'start'
   2168   1.62       dsl 			 * is only changed slightly.
   2169   1.62       dsl 			 */
   2170   1.62       dsl 			if (size > start - old)
   2171   1.62       dsl 				size -= start - old;
   2172   1.62       dsl 			else
   2173   1.62       dsl 				size = 0;
   2174   1.62       dsl 			/* Find end of available space from this start point */
   2175   1.62       dsl 			if (extended) {
   2176   1.62       dsl 				for (p = 0; p < ext.num_ptn; p++) {
   2177   1.62       dsl 					if (p == part)
   2178   1.62       dsl 						continue;
   2179   1.71     lukem 					if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2180   1.62       dsl 						continue;
   2181   1.62       dsl 					n_s = ext_offset(p);
   2182   1.62       dsl 					if (n_s > start && n_s < lim)
   2183   1.62       dsl 						lim = n_s;
   2184   1.62       dsl 					if (start >= n_s && start < n_s
   2185   1.62       dsl 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
   2186   1.62       dsl 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size)) {
   2187   1.62       dsl 						lim = start;
   2188   1.62       dsl 						break;
   2189   1.62       dsl 					}
   2190   1.62       dsl 				}
   2191   1.62       dsl 			} else {
   2192   1.71     lukem 				for (p = 0; p < MBR_PART_COUNT; p++) {
   2193   1.62       dsl 					if (p == part)
   2194   1.62       dsl 						continue;
   2195   1.71     lukem 					if (mboot.mbr_parts[p].mbrp_type == 0)
   2196   1.62       dsl 						continue;
   2197   1.62       dsl 					n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
   2198   1.62       dsl 					if (n_s > start && n_s < lim)
   2199   1.62       dsl 						lim = n_s;
   2200   1.62       dsl 					if (start >= n_s && start < n_s
   2201   1.62       dsl 				    + le32toh(mboot.mbr_parts[p].mbrp_size)) {
   2202   1.62       dsl 						lim = start;
   2203   1.62       dsl 						break;
   2204   1.62       dsl 					}
   2205   1.62       dsl 				}
   2206   1.62       dsl 			}
   2207   1.62       dsl 			lim -= start;
   2208   1.62       dsl 			if (lim == 0) {
   2209   1.62       dsl 				printf("Start sector already allocated\n");
   2210   1.62       dsl 				return 0;
   2211   1.62       dsl 			}
   2212   1.62       dsl 			if (size == 0 || size > lim)
   2213   1.62       dsl 				size = lim;
   2214   1.62       dsl 			fl = DEC_SEC;
   2215  1.130       dsl 			if (start % ptn_alignment == ptn_0_offset)
   2216   1.62       dsl 				fl |= DEC_RND_DOWN;
   2217  1.130       dsl 			if (start == 2 * ptn_0_offset)
   2218   1.62       dsl 				fl |= DEC_RND_DOWN | DEC_RND_DOWN_2;
   2219   1.62       dsl 			size = decimal("size", size, fl, 0, lim);
   2220   1.62       dsl #ifdef BOOTSEL
   2221   1.62       dsl #ifndef DEFAULT_BOOTEXTCODE
   2222   1.62       dsl 			if (!extended)
   2223   1.62       dsl #endif
   2224   1.62       dsl 				string("bootmenu", bootmenu_len, tmp_bootmenu);
   2225   1.62       dsl #endif
   2226   1.62       dsl 		}
   2227   1.62       dsl 	}
   2228   1.62       dsl 
   2229   1.62       dsl 	/*
   2230   1.62       dsl 	 * Before we write these away, we must verify that nothing
   2231   1.62       dsl 	 * untoward has been requested.
   2232   1.62       dsl 	 */
   2233   1.62       dsl 
   2234   1.62       dsl 	if (extended)
   2235   1.62       dsl 		errtext = check_ext_overlap(part, sysid, start, size, 0);
   2236   1.62       dsl 	else
   2237   1.62       dsl 		errtext = check_overlap(part, sysid, start, size, 0);
   2238  1.135  christos 	if (errtext != NULL && !I_flag) {
   2239   1.62       dsl 		if (f_flag)
   2240  1.151  christos 			errx(2, "%s", errtext);
   2241   1.62       dsl 		printf("%s\n", errtext);
   2242   1.62       dsl 		return 0;
   2243   1.62       dsl 	}
   2244   1.62       dsl 
   2245   1.62       dsl 	/*
   2246   1.62       dsl 	 * Before proceeding, delete any overlapped partitions.
   2247   1.62       dsl 	 * This can only happen if '-f' was supplied on the command line.
   2248   1.62       dsl 	 * Just hope the caller knows what they are doing.
   2249   1.62       dsl 	 * This also fixes the base of each extended partition if the
   2250   1.62       dsl 	 * partition itself has moved.
   2251   1.62       dsl 	 */
   2252  1.135  christos 	if (!I_flag) {
   2253  1.135  christos 		if (extended)
   2254  1.135  christos 			errtext = check_ext_overlap(part, sysid, start, size, 1);
   2255  1.135  christos 		else
   2256  1.135  christos 			errtext = check_overlap(part, sysid, start, size, 1);
   2257  1.136  christos 		if (errtext)
   2258  1.151  christos 			errx(1, "%s", errtext);
   2259  1.135  christos 	}
   2260   1.62       dsl 
   2261   1.62       dsl 
   2262   1.62       dsl 	if (sysid == 0) {
   2263   1.62       dsl 		/* delete this partition - save info though */
   2264   1.62       dsl 		if (partp == NULL)
   2265   1.62       dsl 			/* must have been trying to create an extended ptn */
   2266   1.62       dsl 			return 0;
   2267   1.62       dsl 		if (start == 0 && size == 0)
   2268   1.62       dsl 			memset(partp, 0, sizeof *partp);
   2269   1.62       dsl #ifdef BOOTSEL
   2270   1.96       dsl 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
   2271   1.71     lukem 			memset(boot->mbr_bootsel.mbrbs_nametab[upart], 0,
   2272   1.71     lukem 				sizeof boot->mbr_bootsel.mbrbs_nametab[0]);
   2273   1.62       dsl #endif
   2274   1.62       dsl 		if (extended)
   2275   1.62       dsl 			delete_ext_ptn(part);
   2276   1.62       dsl 		else
   2277   1.62       dsl 			delete_ptn(part);
   2278   1.62       dsl 		return 1;
   2279   1.62       dsl 	}
   2280   1.62       dsl 
   2281   1.62       dsl 
   2282   1.62       dsl 	if (extended) {
   2283   1.62       dsl 		if (part != -1)
   2284   1.62       dsl 			delete_ext_ptn(part);
   2285  1.130       dsl 		if (start == ext.base + ptn_0_offset)
   2286   1.62       dsl 			/* First one must have been free */
   2287   1.62       dsl 			part = 0;
   2288   1.62       dsl 		else
   2289   1.62       dsl 			part = add_ext_ptn(start, size);
   2290   1.62       dsl 
   2291   1.62       dsl 		/* These must be re-calculated because of the realloc */
   2292   1.62       dsl 		boot = &ext.ptn[part];
   2293   1.62       dsl 		partp = &boot->mbr_parts[0];
   2294   1.62       dsl 		offset = ext_offset(part);
   2295   1.62       dsl 	}
   2296   1.62       dsl 
   2297   1.71     lukem 	partp->mbrp_type = sysid;
   2298   1.62       dsl 	partp->mbrp_start = htole32( start - offset);
   2299   1.62       dsl 	partp->mbrp_size = htole32( size);
   2300   1.62       dsl 	dos(start, &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
   2301   1.62       dsl 	dos(start + size - 1,
   2302   1.62       dsl 		    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
   2303   1.62       dsl #ifdef BOOTSEL
   2304   1.62       dsl 	if (extended) {
   2305   1.96       dsl 		boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
   2306   1.71     lukem 		strncpy(boot->mbr_bootsel.mbrbs_nametab[upart], tmp_bootmenu,
   2307   1.62       dsl 			bootmenu_len);
   2308   1.62       dsl 	} else {
   2309   1.62       dsl 		/* We need to bootselect code installed in order to have
   2310   1.62       dsl 		 * somewhere to safely write the menu tag.
   2311   1.62       dsl 		 */
   2312   1.96       dsl 		if (boot->mbr_bootsel_magic != LE_MBR_BS_MAGIC) {
   2313  1.104  christos 			if (f_flag ||
   2314  1.104  christos 			    yesno("The bootselect code is not installed, "
   2315  1.104  christos 				"do you want to install it now?"))
   2316   1.71     lukem 				install_bootsel(MBR_BS_ACTIVE);
   2317   1.62       dsl 		}
   2318   1.96       dsl 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
   2319   1.71     lukem 			strncpy(boot->mbr_bootsel.mbrbs_nametab[upart],
   2320   1.62       dsl 				tmp_bootmenu, bootmenu_len);
   2321   1.62       dsl 		}
   2322   1.62       dsl 	}
   2323   1.62       dsl #endif
   2324   1.62       dsl 
   2325   1.62       dsl 	if (v_flag && !f_flag && yesno("Explicitly specify beg/end address?")) {
   2326   1.62       dsl 		/* this really isn't a good idea.... */
   2327   1.62       dsl 		int tsector, tcylinder, thead;
   2328   1.62       dsl 
   2329   1.62       dsl 		tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
   2330   1.62       dsl 		thead = partp->mbrp_shd;
   2331   1.62       dsl 		tsector = MBR_PSECT(partp->mbrp_ssect);
   2332   1.62       dsl 		tcylinder = decimal("beginning cylinder",
   2333   1.62       dsl 				tcylinder, 0, 0, dos_cylinders - 1);
   2334   1.62       dsl 		thead = decimal("beginning head",
   2335   1.62       dsl 				thead, 0, 0, dos_heads - 1);
   2336   1.62       dsl 		tsector = decimal("beginning sector",
   2337   1.62       dsl 				tsector, 0, 1, dos_sectors);
   2338   1.62       dsl 		partp->mbrp_scyl = DOSCYL(tcylinder);
   2339   1.62       dsl 		partp->mbrp_shd = thead;
   2340   1.62       dsl 		partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
   2341   1.62       dsl 
   2342   1.62       dsl 		tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
   2343   1.62       dsl 		thead = partp->mbrp_ehd;
   2344   1.62       dsl 		tsector = MBR_PSECT(partp->mbrp_esect);
   2345   1.62       dsl 		tcylinder = decimal("ending cylinder",
   2346   1.62       dsl 				tcylinder, 0, 0, dos_cylinders - 1);
   2347   1.62       dsl 		thead = decimal("ending head",
   2348   1.62       dsl 				thead, 0, 0, dos_heads - 1);
   2349   1.62       dsl 		tsector = decimal("ending sector",
   2350   1.62       dsl 				tsector, 0, 1, dos_sectors);
   2351   1.62       dsl 		partp->mbrp_ecyl = DOSCYL(tcylinder);
   2352   1.62       dsl 		partp->mbrp_ehd = thead;
   2353   1.62       dsl 		partp->mbrp_esect = DOSSECT(tsector, tcylinder);
   2354   1.62       dsl 	}
   2355   1.62       dsl 
   2356   1.62       dsl 	/* If we had to mark an extended partition as deleted because
   2357   1.62       dsl 	 * another request would have overlapped it, now is the time
   2358   1.62       dsl 	 * to do the actual delete.
   2359   1.62       dsl 	 */
   2360   1.62       dsl 	if (extended && f_flag) {
   2361   1.62       dsl 		for (p = ext.num_ptn; --p >= 0;)
   2362   1.71     lukem 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
   2363   1.62       dsl 				delete_ext_ptn(p);
   2364   1.62       dsl 	}
   2365   1.62       dsl 	return 1;
   2366    1.1       cgd }
   2367    1.1       cgd 
   2368  1.132     joerg static void
   2369  1.129       dsl print_geometry(void)
   2370    1.1       cgd {
   2371    1.4   mycroft 
   2372   1.15      phil 	if (sh_flag) {
   2373   1.73     lukem 		printf("DISK=%s\n", disk);
   2374   1.69       dsl 		printf("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%"PRIdaddr"\n",
   2375   1.69       dsl 			cylinders, heads, sectors, disksectors);
   2376   1.69       dsl 		printf("BCYL=%d\nBHEAD=%d\nBSEC=%d\nBDLSIZE=%"PRIdaddr"\n",
   2377   1.69       dsl 			dos_cylinders, dos_heads, dos_sectors, dos_disksectors);
   2378   1.62       dsl 		printf("NUMEXTPTN=%d\n", ext.num_ptn);
   2379   1.14      phil 		return;
   2380   1.14      phil 	}
   2381   1.14      phil 
   2382   1.15      phil 	/* Not sh_flag */
   2383   1.48     lukem 	printf("Disk: %s\n", disk);
   2384   1.34      fvdl 	printf("NetBSD disklabel disk geometry:\n");
   2385   1.62       dsl 	printf("cylinders: %d, heads: %d, sectors/track: %d "
   2386  1.145  jakllsch 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr", "
   2387  1.145  jakllsch 	    "bytes/sector: %zd\n\n", cylinders, heads, sectors,
   2388  1.145  jakllsch 	    cylindersectors, disksectors, secsize);
   2389   1.34      fvdl 	printf("BIOS disk geometry:\n");
   2390   1.62       dsl 	printf("cylinders: %d, heads: %d, sectors/track: %d "
   2391   1.69       dsl 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
   2392   1.62       dsl 	    dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors,
   2393   1.69       dsl 	    dos_disksectors);
   2394  1.129       dsl 	printf("Partitions aligned to %d sector boundaries, offset %d\n\n",
   2395  1.130       dsl 	    ptn_alignment, ptn_0_offset);
   2396    1.1       cgd }
   2397    1.1       cgd 
   2398  1.112       apb /* Find the first active partition, else return MBR_PART_COUNT */
   2399  1.132     joerg static int
   2400  1.112       apb first_active(void)
   2401  1.112       apb {
   2402  1.112       apb 	struct mbr_partition *partp = &mboot.mbr_parts[0];
   2403  1.112       apb 	int part;
   2404  1.112       apb 
   2405  1.112       apb 	for (part = 0; part < MBR_PART_COUNT; part++)
   2406  1.112       apb 		if (partp[part].mbrp_flag & MBR_PFLAG_ACTIVE)
   2407  1.112       apb 			return part;
   2408  1.112       apb 	return MBR_PART_COUNT;
   2409  1.112       apb }
   2410  1.112       apb 
   2411  1.132     joerg static void
   2412   1.43     lukem change_active(int which)
   2413    1.1       cgd {
   2414   1.71     lukem 	struct mbr_partition *partp;
   2415    1.4   mycroft 	int part;
   2416   1.71     lukem 	int active = MBR_PART_COUNT;
   2417    1.4   mycroft 
   2418   1.61       dsl 	partp = &mboot.mbr_parts[0];
   2419    1.1       cgd 
   2420    1.1       cgd 	if (a_flag && which != -1)
   2421    1.1       cgd 		active = which;
   2422  1.112       apb 	else
   2423  1.112       apb 		active = first_active();
   2424   1.15      phil 	if (!f_flag) {
   2425   1.15      phil 		if (yesno("Do you want to change the active partition?")) {
   2426   1.71     lukem 			printf ("Choosing %d will make no partition active.\n",
   2427   1.71     lukem 			    MBR_PART_COUNT);
   2428   1.15      phil 			do {
   2429   1.62       dsl 				active = decimal("active partition",
   2430   1.71     lukem 						active, 0, 0, MBR_PART_COUNT);
   2431   1.15      phil 			} while (!yesno("Are you happy with this choice?"));
   2432   1.15      phil 		} else
   2433   1.15      phil 			return;
   2434   1.15      phil 	} else
   2435   1.71     lukem 		if (active != MBR_PART_COUNT)
   2436   1.15      phil 			printf ("Making partition %d active.\n", active);
   2437   1.15      phil 
   2438   1.71     lukem 	for (part = 0; part < MBR_PART_COUNT; part++)
   2439   1.71     lukem 		partp[part].mbrp_flag &= ~MBR_PFLAG_ACTIVE;
   2440   1.71     lukem 	if (active < MBR_PART_COUNT)
   2441   1.71     lukem 		partp[active].mbrp_flag |= MBR_PFLAG_ACTIVE;
   2442    1.1       cgd }
   2443    1.1       cgd 
   2444  1.132     joerg static void
   2445  1.129       dsl change_bios_geometry(void)
   2446    1.1       cgd {
   2447  1.129       dsl 	print_geometry();
   2448   1.62       dsl 	if (!yesno("Do you want to change our idea of what BIOS thinks?"))
   2449   1.62       dsl 		return;
   2450   1.62       dsl 
   2451  1.130       dsl #if defined(USE_DISKLIST)
   2452   1.62       dsl 	if (dl != NULL) {
   2453  1.129       dsl 		struct biosdisk_info *bip;
   2454  1.129       dsl 		int i;
   2455  1.129       dsl 
   2456   1.62       dsl 		for (i = 0; i < dl->dl_nbiosdisks; i++) {
   2457   1.62       dsl 			if (i == 0)
   2458   1.62       dsl 				printf("\nGeometries of known disks:\n");
   2459   1.62       dsl 			bip = &dl->dl_biosdisks[i];
   2460   1.62       dsl 			printf("Disk %d: cylinders %u, heads %u, sectors %u"
   2461   1.69       dsl 				" (%"PRIdaddr" sectors, %dMB)\n",
   2462   1.62       dsl 			    i, bip->bi_cyl, bip->bi_head, bip->bi_sec,
   2463   1.69       dsl 			    bip->bi_lbasecs, SEC_TO_MB(bip->bi_lbasecs));
   2464   1.62       dsl 
   2465   1.62       dsl 		}
   2466   1.62       dsl 		printf("\n");
   2467    1.1       cgd 	}
   2468   1.62       dsl #endif
   2469   1.62       dsl 	do {
   2470   1.62       dsl 		dos_cylinders = decimal("BIOS's idea of #cylinders",
   2471   1.62       dsl 					dos_cylinders, 0, 0, MAXCYL);
   2472   1.62       dsl 		dos_heads = decimal("BIOS's idea of #heads",
   2473   1.62       dsl 					dos_heads, 0, 0, MAXHEAD);
   2474   1.62       dsl 		dos_sectors = decimal("BIOS's idea of #sectors",
   2475   1.62       dsl 					dos_sectors, 0, 1, MAXSECTOR);
   2476  1.129       dsl 		print_geometry();
   2477   1.62       dsl 	} while (!yesno("Are you happy with this choice?"));
   2478    1.1       cgd }
   2479    1.1       cgd 
   2480   1.62       dsl 
   2481    1.1       cgd /***********************************************\
   2482    1.1       cgd * Change real numbers into strange dos numbers	*
   2483    1.1       cgd \***********************************************/
   2484  1.132     joerg static void
   2485   1.43     lukem dos(int sector, unsigned char *cylinderp, unsigned char *headp,
   2486   1.43     lukem     unsigned char *sectorp)
   2487    1.4   mycroft {
   2488    1.5   mycroft 	int cylinder, head;
   2489    1.4   mycroft 
   2490    1.5   mycroft 	cylinder = sector / dos_cylindersectors;
   2491    1.5   mycroft 	sector -= cylinder * dos_cylindersectors;
   2492    1.4   mycroft 
   2493    1.5   mycroft 	head = sector / dos_sectors;
   2494    1.5   mycroft 	sector -= head * dos_sectors;
   2495   1.68       dsl 	if (cylinder > 1023)
   2496   1.68       dsl 		cylinder = 1023;
   2497    1.4   mycroft 
   2498    1.5   mycroft 	*cylinderp = DOSCYL(cylinder);
   2499    1.5   mycroft 	*headp = head;
   2500    1.5   mycroft 	*sectorp = DOSSECT(sector + 1, cylinder);
   2501    1.1       cgd }
   2502    1.1       cgd 
   2503  1.132     joerg static int
   2504   1.44     lukem open_disk(int update)
   2505    1.1       cgd {
   2506   1.18     lukem 	static char namebuf[MAXPATHLEN + 1];
   2507  1.109       dsl 	int flags = update && disk_file == NULL ? O_RDWR : O_RDONLY;
   2508    1.1       cgd 
   2509  1.109       dsl 	if (!F_flag) {
   2510  1.109       dsl 		fd = opendisk(disk, flags, namebuf, sizeof(namebuf), 0);
   2511  1.109       dsl 		if (fd < 0) {
   2512  1.109       dsl 			if (errno == ENODEV)
   2513  1.109       dsl 				warnx("%s is not a character device", namebuf);
   2514  1.109       dsl 			else
   2515  1.109       dsl 				warn("cannot opendisk %s", namebuf);
   2516  1.109       dsl 			return (-1);
   2517  1.109       dsl 		}
   2518  1.109       dsl 		disk = namebuf;
   2519  1.109       dsl 	} else {
   2520  1.109       dsl 		fd = open(disk, flags, 0);
   2521  1.109       dsl 		if (fd == -1) {
   2522  1.109       dsl 			warn("cannot open %s", disk);
   2523  1.109       dsl 			return -1;
   2524  1.109       dsl 		}
   2525   1.91    dyoung 	}
   2526  1.109       dsl 
   2527    1.4   mycroft 	if (get_params() == -1) {
   2528    1.4   mycroft 		close(fd);
   2529   1.62       dsl 		fd = -1;
   2530    1.4   mycroft 		return (-1);
   2531    1.1       cgd 	}
   2532   1.62       dsl 	if (disk_file != NULL) {
   2533   1.62       dsl 		/* for testing: read/write data from a disk file */
   2534   1.62       dsl 		wfd = open(disk_file, update ? O_RDWR|O_CREAT : O_RDONLY, 0777);
   2535   1.62       dsl 		if (wfd == -1) {
   2536   1.62       dsl 			warn("%s", disk_file);
   2537   1.62       dsl 			close(fd);
   2538   1.62       dsl 			fd = -1;
   2539   1.62       dsl 			return -1;
   2540   1.62       dsl 		}
   2541   1.62       dsl 	} else
   2542   1.62       dsl 		wfd = fd;
   2543    1.4   mycroft 	return (0);
   2544    1.1       cgd }
   2545    1.1       cgd 
   2546  1.140  christos static ssize_t
   2547   1.62       dsl read_disk(daddr_t sector, void *buf)
   2548    1.1       cgd {
   2549  1.140  christos 	ssize_t nr;
   2550    1.4   mycroft 
   2551   1.62       dsl 	if (*rfd == -1)
   2552   1.44     lukem 		errx(1, "read_disk(); fd == -1");
   2553    1.1       cgd 
   2554  1.145  jakllsch 	off_t offs = sector * (off_t)secsize;
   2555  1.140  christos 	off_t mod = offs & (secsize - 1);
   2556  1.140  christos 	off_t rnd = offs & ~(secsize - 1);
   2557  1.140  christos 
   2558  1.140  christos 	if (lseek(*rfd, rnd, SEEK_SET) == (off_t)-1)
   2559  1.140  christos 		return -1;
   2560  1.140  christos 
   2561  1.140  christos 	if (secsize == 512)
   2562  1.140  christos 		return read(*rfd, buf, 512);
   2563  1.140  christos 
   2564  1.140  christos 	if ((nr = read(*rfd, iobuf, secsize)) != secsize)
   2565  1.140  christos 		return nr;
   2566  1.140  christos 
   2567  1.140  christos 	memcpy(buf, &iobuf[mod], 512);
   2568  1.140  christos 
   2569  1.140  christos 	return 512;
   2570  1.140  christos }
   2571  1.140  christos 
   2572  1.140  christos static ssize_t
   2573   1.62       dsl write_disk(daddr_t sector, void *buf)
   2574    1.1       cgd {
   2575  1.140  christos 	ssize_t nr;
   2576    1.4   mycroft 
   2577   1.62       dsl 	if (wfd == -1)
   2578   1.62       dsl 		errx(1, "write_disk(); wfd == -1");
   2579  1.140  christos 
   2580  1.145  jakllsch 	off_t offs = sector * (off_t)secsize;
   2581  1.140  christos 	off_t mod = offs & (secsize - 1);
   2582  1.140  christos 	off_t rnd = offs & ~(secsize - 1);
   2583  1.140  christos 
   2584  1.140  christos 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
   2585  1.140  christos 		return -1;
   2586  1.140  christos 
   2587  1.140  christos 	if (secsize == 512)
   2588  1.140  christos 		return write(wfd, buf, 512);
   2589  1.140  christos 
   2590  1.140  christos 	if ((nr = read(wfd, iobuf, secsize)) != secsize)
   2591  1.140  christos 		return nr;
   2592  1.140  christos 
   2593  1.140  christos 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
   2594  1.140  christos 		return -1;
   2595  1.140  christos 
   2596  1.140  christos 	memcpy(&iobuf[mod], buf, 512);
   2597  1.140  christos 
   2598  1.140  christos 	if ((nr = write(wfd, iobuf, secsize)) != secsize)
   2599  1.140  christos 		return nr;
   2600  1.140  christos 
   2601  1.140  christos 	return 512;
   2602    1.1       cgd }
   2603    1.1       cgd 
   2604   1.75    dyoung static void
   2605   1.75    dyoung guess_geometry(daddr_t _sectors)
   2606   1.75    dyoung {
   2607   1.75    dyoung 	dos_sectors = MAXSECTOR;
   2608   1.75    dyoung 	dos_heads = MAXHEAD - 1;	/* some BIOS might use 256 */
   2609   1.75    dyoung 	dos_cylinders = _sectors / (MAXSECTOR * (MAXHEAD - 1));
   2610   1.75    dyoung 	if (dos_cylinders < 1)
   2611   1.75    dyoung 		dos_cylinders = 1;
   2612   1.75    dyoung 	else if (dos_cylinders > MAXCYL - 1)
   2613   1.75    dyoung 		dos_cylinders = MAXCYL - 1;
   2614   1.75    dyoung }
   2615   1.75    dyoung 
   2616  1.132     joerg static int
   2617   1.43     lukem get_params(void)
   2618    1.1       cgd {
   2619   1.75    dyoung 	if (disk_type != NULL) {
   2620   1.75    dyoung 		struct disklabel *tmplabel;
   2621    1.1       cgd 
   2622   1.75    dyoung 		if ((tmplabel = getdiskbyname(disk_type)) == NULL) {
   2623   1.75    dyoung 			warn("bad disktype");
   2624   1.75    dyoung 			return (-1);
   2625   1.75    dyoung 		}
   2626   1.75    dyoung 		disklabel = *tmplabel;
   2627   1.75    dyoung 	} else if (F_flag) {
   2628   1.75    dyoung 		struct stat st;
   2629   1.75    dyoung 		if (fstat(fd, &st) == -1) {
   2630   1.75    dyoung 			warn("fstat");
   2631   1.75    dyoung 			return (-1);
   2632   1.75    dyoung 		}
   2633   1.75    dyoung 		if (st.st_size % 512 != 0) {
   2634   1.75    dyoung 			warnx("%s size (%lld) is not divisible "
   2635   1.75    dyoung 			    "by sector size (%d)", disk, (long long)st.st_size,
   2636   1.75    dyoung 			    512);
   2637   1.75    dyoung 		}
   2638   1.75    dyoung 		disklabel.d_secperunit = st.st_size / 512;
   2639   1.75    dyoung 		guess_geometry(disklabel.d_secperunit);
   2640   1.75    dyoung 		disklabel.d_ncylinders = dos_cylinders;
   2641   1.75    dyoung 		disklabel.d_ntracks = dos_heads;
   2642  1.145  jakllsch 		disklabel.d_secsize = 512;
   2643   1.75    dyoung 		disklabel.d_nsectors = dos_sectors;
   2644  1.154     joerg 	}
   2645  1.154     joerg #if !HAVE_NBTOOL_CONFIG_H
   2646  1.154     joerg 	else if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
   2647   1.42   thorpej 		warn("DIOCGDEFLABEL");
   2648   1.42   thorpej 		if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
   2649   1.42   thorpej 			warn("DIOCGDINFO");
   2650   1.42   thorpej 			return (-1);
   2651   1.42   thorpej 		}
   2652    1.4   mycroft 	}
   2653  1.154     joerg #endif
   2654  1.109       dsl 
   2655   1.75    dyoung 	disksectors = disklabel.d_secperunit;
   2656   1.62       dsl 	cylinders = disklabel.d_ncylinders;
   2657   1.62       dsl 	heads = disklabel.d_ntracks;
   2658  1.145  jakllsch 	secsize = disklabel.d_secsize;
   2659   1.62       dsl 	sectors = disklabel.d_nsectors;
   2660    1.1       cgd 
   2661   1.62       dsl 	/* pick up some defaults for the BIOS sizes */
   2662   1.62       dsl 	if (sectors <= MAXSECTOR) {
   2663   1.62       dsl 		dos_cylinders = cylinders;
   2664   1.62       dsl 		dos_heads = heads;
   2665   1.62       dsl 		dos_sectors = sectors;
   2666   1.62       dsl 	} else {
   2667   1.62       dsl 		/* guess - has to better than the above */
   2668   1.75    dyoung 		guess_geometry(disksectors);
   2669   1.62       dsl 	}
   2670   1.62       dsl 	dos_disksectors = disksectors;
   2671   1.62       dsl 
   2672    1.4   mycroft 	return (0);
   2673    1.1       cgd }
   2674    1.1       cgd 
   2675   1.82       dsl #ifdef BOOTSEL
   2676   1.82       dsl /*
   2677   1.82       dsl  * Rather unfortunately the bootsel 'magic' number is at the end of the
   2678   1.82       dsl  * the structure, and there is no checksum.  So when other operating
   2679   1.82       dsl  * systems install mbr code by only writing the length of their code they
   2680   1.82       dsl  * can overwrite part of the structure but keeping the magic number intact.
   2681   1.82       dsl  * This code attempts to empirically detect this problem.
   2682   1.82       dsl  */
   2683   1.82       dsl static int
   2684   1.82       dsl validate_bootsel(struct mbr_bootsel *mbs)
   2685   1.82       dsl {
   2686   1.90    dyoung 	unsigned int key = mbs->mbrbs_defkey;
   2687   1.90    dyoung 	unsigned int tmo;
   2688  1.118     lukem 	size_t i;
   2689   1.82       dsl 
   2690   1.82       dsl 	if (v_flag)
   2691   1.82       dsl 		return 0;
   2692   1.82       dsl 
   2693   1.82       dsl 	/*
   2694   1.82       dsl 	 * Check default key is sane
   2695   1.82       dsl 	 * - this is the most likely field to be stuffed
   2696  1.115       dsl 	 * 16 disks and 16 bootable partitions seems enough!
   2697   1.82       dsl 	 * (the keymap decode starts falling apart at that point)
   2698   1.82       dsl 	 */
   2699  1.115       dsl 	if (mbs->mbrbs_flags & MBR_BS_ASCII) {
   2700  1.115       dsl 		if (key != 0 && !(key == '\r'
   2701  1.115       dsl 		    || (key >= '1' && key < '1' + MAX_BIOS_DISKS)
   2702  1.115       dsl 		    || (key >= 'a' && key < 'a' + MAX_BIOS_DISKS)))
   2703  1.115       dsl 			return 1;
   2704  1.115       dsl 	} else {
   2705  1.115       dsl 		if (key != 0 && !(key == SCAN_ENTER
   2706  1.115       dsl 		    || (key >= SCAN_1 && key < SCAN_1 + MAX_BIOS_DISKS)
   2707  1.115       dsl 		    || (key >= SCAN_F1 && key < SCAN_F1 + MAX_BIOS_DISKS)))
   2708  1.115       dsl 			return 1;
   2709  1.115       dsl 	}
   2710   1.82       dsl 
   2711   1.82       dsl 	/* Checking the flags will lead to breakage... */
   2712   1.82       dsl 
   2713  1.115       dsl 	/* Timeout value is expected to be a multiple of a second */
   2714   1.82       dsl 	tmo = htole16(mbs->mbrbs_timeo);
   2715   1.82       dsl 	if (tmo != 0 && tmo != 0xffff && tmo != (10 * tmo + 9) / 182 * 182 / 10)
   2716   1.82       dsl 		return 2;
   2717   1.82       dsl 
   2718   1.82       dsl 	/* Check the menu strings are printable */
   2719   1.82       dsl 	/* Unfortunately they aren't zero filled... */
   2720   1.82       dsl 	for (i = 0; i < sizeof(mbs->mbrbs_nametab); i++) {
   2721   1.82       dsl 		int c = (uint8_t)mbs->mbrbs_nametab[0][i];
   2722   1.82       dsl 		if (c == 0 || isprint(c))
   2723   1.82       dsl 			continue;
   2724   1.82       dsl 		return 3;
   2725   1.82       dsl 	}
   2726   1.82       dsl 
   2727   1.82       dsl 	return 0;
   2728   1.82       dsl }
   2729   1.82       dsl #endif
   2730   1.82       dsl 
   2731  1.132     joerg static int
   2732   1.71     lukem read_s0(daddr_t offset, struct mbr_sector *boot)
   2733    1.1       cgd {
   2734   1.76     lukem 	const char *tabletype = offset ? "extended" : "primary";
   2735   1.82       dsl #ifdef BOOTSEL
   2736   1.82       dsl 	static int reported;
   2737   1.82       dsl #endif
   2738    1.4   mycroft 
   2739   1.71     lukem 	if (read_disk(offset, boot) == -1) {
   2740   1.76     lukem 		warn("Can't read %s partition table", tabletype);
   2741   1.62       dsl 		return -1;
   2742    1.1       cgd 	}
   2743   1.96       dsl 	if (boot->mbr_magic != LE_MBR_MAGIC) {
   2744  1.144  christos 		if (F_flag && boot->mbr_magic == 0)
   2745  1.144  christos 			return -1;
   2746   1.80    dyoung 		warnx("%s partition table invalid, "
   2747   1.80    dyoung 		    "no magic in sector %"PRIdaddr, tabletype, offset);
   2748   1.62       dsl 		return -1;
   2749   1.82       dsl 
   2750    1.1       cgd 	}
   2751   1.77     lukem #ifdef BOOTSEL
   2752   1.96       dsl 	if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
   2753   1.82       dsl 		/* mbr_bootsel in new location */
   2754   1.82       dsl 		if (validate_bootsel(&boot->mbr_bootsel)) {
   2755   1.82       dsl 			warnx("removing corrupt bootsel information");
   2756   1.82       dsl 			boot->mbr_bootsel_magic = 0;
   2757   1.82       dsl 		}
   2758   1.82       dsl 		return 0;
   2759   1.82       dsl 	}
   2760   1.96       dsl 	if (boot->mbr_bootsel_magic != LE_MBR_MAGIC)
   2761   1.82       dsl 		return 0;
   2762   1.82       dsl 
   2763   1.82       dsl 	/* mbr_bootsel in old location */
   2764   1.82       dsl 	if (!reported)
   2765   1.76     lukem 		warnx("%s partition table: using old-style bootsel information",
   2766   1.76     lukem 		    tabletype);
   2767   1.82       dsl 	reported = 1;
   2768   1.82       dsl 	if (validate_bootsel((void *)((uint8_t *)boot + MBR_BS_OFFSET + 4))) {
   2769   1.82       dsl 		warnx("%s bootsel information corrupt - ignoring", tabletype);
   2770   1.82       dsl 		return 0;
   2771   1.82       dsl 	}
   2772   1.90    dyoung 	memmove((uint8_t *)boot + MBR_BS_OFFSET,
   2773   1.90    dyoung 		(uint8_t *)boot + MBR_BS_OFFSET + 4,
   2774   1.82       dsl 		sizeof(struct mbr_bootsel));
   2775   1.82       dsl 	if ( ! (boot->mbr_bootsel.mbrbs_flags & MBR_BS_NEWMBR)) {
   2776   1.82       dsl 			/* old style default key */
   2777   1.82       dsl 		int id;
   2778   1.82       dsl 			/* F1..F4 => ptn 0..3, F5+ => disk 0+ */
   2779   1.82       dsl 		id = boot->mbr_bootsel.mbrbs_defkey;
   2780   1.82       dsl 		id -= SCAN_F1;
   2781   1.82       dsl 		if (id >= MBR_PART_COUNT)
   2782   1.82       dsl 			id -= MBR_PART_COUNT; /* Use number of disk */
   2783   1.82       dsl 		else if (mboot.mbr_parts[id].mbrp_type != 0)
   2784   1.82       dsl 			id = le32toh(boot->mbr_parts[id].mbrp_start);
   2785   1.82       dsl 		else
   2786   1.82       dsl 			id = DEFAULT_ACTIVE;
   2787   1.82       dsl 		boot->mbr_bootsel.mbrbs_defkey = id;
   2788   1.76     lukem 	}
   2789   1.96       dsl 	boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
   2790   1.82       dsl 		/* highlight that new bootsel code is necessary */
   2791   1.82       dsl 	boot->mbr_bootsel.mbrbs_flags &= ~MBR_BS_NEWMBR;
   2792   1.77     lukem #endif /* BOOTSEL */
   2793   1.82       dsl 	return 0;
   2794    1.1       cgd }
   2795    1.1       cgd 
   2796  1.132     joerg static int
   2797   1.62       dsl write_mbr(void)
   2798    1.1       cgd {
   2799   1.30        ws 	int flag, i;
   2800   1.62       dsl 	daddr_t offset;
   2801   1.62       dsl 	int rval = -1;
   2802    1.4   mycroft 
   2803    1.1       cgd 	/*
   2804    1.1       cgd 	 * write enable label sector before write (if necessary),
   2805    1.1       cgd 	 * disable after writing.
   2806    1.1       cgd 	 * needed if the disklabel protected area also protects
   2807    1.1       cgd 	 * sector 0. (e.g. empty disk)
   2808    1.1       cgd 	 */
   2809    1.1       cgd 	flag = 1;
   2810  1.154     joerg #if !HAVE_NBTOOL_CONFIG_H
   2811   1.75    dyoung 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
   2812    1.4   mycroft 		warn("DIOCWLABEL");
   2813  1.154     joerg #endif
   2814   1.71     lukem 	if (write_disk(0, &mboot) == -1) {
   2815   1.62       dsl 		warn("Can't write fdisk partition table");
   2816   1.62       dsl 		goto protect_label;
   2817   1.62       dsl 	}
   2818   1.62       dsl 	if (boot_installed)
   2819   1.62       dsl 		for (i = bootsize; (i -= 0x200) > 0;)
   2820   1.62       dsl 			if (write_disk(i / 0x200, &bootcode[i / 0x200]) == -1) {
   2821   1.62       dsl 				warn("Can't write bootcode");
   2822   1.62       dsl 				goto protect_label;
   2823   1.62       dsl 			}
   2824   1.62       dsl 	for (offset = 0, i = 0; i < ext.num_ptn; i++) {
   2825   1.62       dsl 		if (write_disk(ext.base + offset, ext.ptn + i) == -1) {
   2826   1.62       dsl 			warn("Can't write %dth extended partition", i);
   2827   1.62       dsl 			goto protect_label;
   2828   1.62       dsl 		}
   2829   1.62       dsl 		offset = le32toh(ext.ptn[i].mbr_parts[1].mbrp_start);
   2830    1.4   mycroft 	}
   2831   1.62       dsl 	rval = 0;
   2832   1.62       dsl     protect_label:
   2833    1.1       cgd 	flag = 0;
   2834  1.154     joerg #if !HAVE_NBTOOL_CONFIG_H
   2835   1.75    dyoung 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
   2836    1.4   mycroft 		warn("DIOCWLABEL");
   2837  1.154     joerg #endif
   2838   1.62       dsl 	return rval;
   2839    1.1       cgd }
   2840    1.1       cgd 
   2841  1.132     joerg static int
   2842   1.62       dsl yesno(const char *str, ...)
   2843    1.4   mycroft {
   2844    1.4   mycroft 	int ch, first;
   2845   1.62       dsl 	va_list ap;
   2846   1.62       dsl 
   2847   1.62       dsl 	va_start(ap, str);
   2848   1.62       dsl 	vprintf(str, ap);
   2849  1.143  christos 	va_end(ap);
   2850   1.62       dsl 	printf(" [n] ");
   2851    1.1       cgd 
   2852    1.4   mycroft 	first = ch = getchar();
   2853    1.4   mycroft 	while (ch != '\n' && ch != EOF)
   2854    1.4   mycroft 		ch = getchar();
   2855   1.53      yamt 	if (ch == EOF)
   2856   1.53      yamt 		errx(1, "EOF");
   2857    1.4   mycroft 	return (first == 'y' || first == 'Y');
   2858    1.1       cgd }
   2859    1.1       cgd 
   2860  1.132     joerg static int64_t
   2861  1.123       dsl decimal(const char *prompt, int64_t dflt, int flags, int64_t minval, int64_t maxval)
   2862    1.1       cgd {
   2863  1.123       dsl 	int64_t acc = 0;
   2864  1.125       dsl 	int valid;
   2865  1.125       dsl 	int len;
   2866    1.4   mycroft 	char *cp;
   2867    1.1       cgd 
   2868   1.62       dsl 	for (;;) {
   2869   1.62       dsl 		if (flags & DEC_SEC) {
   2870  1.125       dsl 			printf("%s: [%" PRId64 "..%" PRId64 "cyl default: %" PRId64 ", %" PRId64 "cyl, %uMB] ",
   2871   1.62       dsl 			    prompt, SEC_TO_CYL(minval), SEC_TO_CYL(maxval),
   2872   1.62       dsl 			    dflt, SEC_TO_CYL(dflt), SEC_TO_MB(dflt));
   2873   1.62       dsl 		} else
   2874  1.123       dsl 			printf("%s: [%" PRId64 "..%" PRId64 " default: %" PRId64 "] ",
   2875   1.62       dsl 			    prompt, minval, maxval, dflt);
   2876    1.1       cgd 
   2877   1.53      yamt 		if (!fgets(lbuf, LBUF, stdin))
   2878   1.53      yamt 			errx(1, "EOF");
   2879    1.7   mycroft 		cp = lbuf;
   2880    1.7   mycroft 
   2881    1.7   mycroft 		cp += strspn(cp, " \t");
   2882  1.125       dsl 		if (*cp == '\n')
   2883   1.62       dsl 			return dflt;
   2884   1.62       dsl 
   2885  1.125       dsl 		if (cp[0] == '$' && cp[1] == '\n')
   2886   1.62       dsl 			return maxval;
   2887   1.62       dsl 
   2888   1.83       dsl 		if (isdigit((unsigned char)*cp) || *cp == '-') {
   2889  1.123       dsl 			acc = strtoll(lbuf, &cp, 10);
   2890  1.125       dsl 			len = strcspn(cp, " \t\n");
   2891  1.125       dsl 			valid = 0;
   2892  1.125       dsl 			if (len != 0 && (flags & DEC_SEC)) {
   2893  1.125       dsl 				if (!strncasecmp(cp, "gb", len)) {
   2894   1.89       dsl 					acc *= 1024;
   2895  1.125       dsl 					valid = 1;
   2896   1.89       dsl 				}
   2897  1.125       dsl 				if (valid || !strncasecmp(cp, "mb", len)) {
   2898   1.62       dsl 					acc *= SEC_IN_1M;
   2899   1.62       dsl 					/* round to whole number of cylinders */
   2900  1.127       dsl 					acc += ptn_alignment / 2;
   2901  1.127       dsl 					acc /= ptn_alignment;
   2902  1.125       dsl 					valid = 1;
   2903   1.62       dsl 				}
   2904  1.125       dsl 				if (valid || !strncasecmp(cp, "cyl", len)) {
   2905  1.127       dsl 					acc *= ptn_alignment;
   2906   1.62       dsl 					/* adjustments for cylinder boundary */
   2907   1.62       dsl 					if (acc == 0 && flags & DEC_RND_0)
   2908  1.130       dsl 						acc += ptn_0_offset;
   2909   1.62       dsl 					if (flags & DEC_RND)
   2910  1.130       dsl 						acc += ptn_0_offset;
   2911   1.62       dsl 					if (flags & DEC_RND_DOWN)
   2912  1.130       dsl 						acc -= ptn_0_offset;
   2913   1.62       dsl 					if (flags & DEC_RND_DOWN_2)
   2914  1.130       dsl 						acc -= ptn_0_offset;
   2915  1.125       dsl 					cp += len;
   2916   1.62       dsl 				}
   2917   1.62       dsl 			}
   2918   1.62       dsl 		}
   2919    1.1       cgd 
   2920   1.62       dsl 		cp += strspn(cp, " \t");
   2921  1.125       dsl 		if (*cp != '\n') {
   2922  1.125       dsl 			lbuf[strlen(lbuf) - 1] = 0;
   2923   1.62       dsl 			printf("%s is not a valid %s number.\n", lbuf,
   2924   1.62       dsl 			    flags & DEC_SEC ? "sector" : "decimal");
   2925    1.7   mycroft 			continue;
   2926   1.62       dsl 		}
   2927   1.62       dsl 
   2928   1.62       dsl 		if (acc >= minval && acc <= maxval)
   2929   1.62       dsl 			return acc;
   2930  1.123       dsl 		printf("%" PRId64 " is not between %" PRId64 " and %" PRId64 ".\n", acc, minval, maxval);
   2931   1.62       dsl 	}
   2932   1.62       dsl }
   2933   1.62       dsl 
   2934  1.132     joerg static int
   2935   1.62       dsl ptn_id(const char *prompt, int *extended)
   2936   1.62       dsl {
   2937   1.90    dyoung 	unsigned int acc = 0;
   2938   1.62       dsl 	char *cp;
   2939   1.62       dsl 
   2940   1.62       dsl 	for (;; printf("%s is not a valid partition number.\n", lbuf)) {
   2941   1.62       dsl 		printf("%s: [none] ", prompt);
   2942   1.62       dsl 
   2943   1.62       dsl 		if (!fgets(lbuf, LBUF, stdin))
   2944   1.62       dsl 			errx(1, "EOF");
   2945   1.62       dsl 		lbuf[strlen(lbuf)-1] = '\0';
   2946   1.62       dsl 		cp = lbuf;
   2947   1.62       dsl 
   2948   1.62       dsl 		cp += strspn(cp, " \t");
   2949   1.62       dsl 		*extended = 0;
   2950   1.62       dsl 		if (*cp == 0)
   2951   1.62       dsl 			return -1;
   2952   1.62       dsl 
   2953   1.62       dsl 		if (*cp == 'E' || *cp == 'e') {
   2954   1.62       dsl 			cp++;
   2955   1.62       dsl 			*extended = 1;
   2956   1.62       dsl 		}
   2957   1.62       dsl 
   2958   1.62       dsl 		acc = strtoul(cp, &cp, 10);
   2959    1.7   mycroft 
   2960    1.5   mycroft 		cp += strspn(cp, " \t");
   2961    1.5   mycroft 		if (*cp != '\0')
   2962    1.5   mycroft 			continue;
   2963    1.1       cgd 
   2964   1.71     lukem 		if (*extended || acc < MBR_PART_COUNT)
   2965   1.62       dsl 			return acc;
   2966    1.1       cgd 	}
   2967   1.62       dsl }
   2968   1.62       dsl 
   2969   1.62       dsl #ifdef BOOTSEL
   2970  1.132     joerg static void
   2971   1.62       dsl string(const char *prompt, int length, char *buf)
   2972   1.62       dsl {
   2973   1.62       dsl 	int len;
   2974    1.1       cgd 
   2975   1.62       dsl 	for (;;) {
   2976  1.153  christos 		printf("%s: [%.*s] (space to clear)", prompt, length, buf);
   2977   1.62       dsl 
   2978   1.62       dsl 		if (!fgets(lbuf, LBUF, stdin))
   2979   1.62       dsl 			errx(1, "EOF");
   2980   1.62       dsl 		len = strlen(lbuf);
   2981   1.62       dsl 		if (len <= 1)
   2982   1.62       dsl 			/* unchanged if just <enter> */
   2983   1.62       dsl 			return;
   2984   1.62       dsl 		/* now strip trailing spaces, <space><enter> deletes string */
   2985   1.62       dsl 		do
   2986   1.62       dsl 			lbuf[--len] = 0;
   2987   1.62       dsl 		while (len != 0 && lbuf[len - 1] == ' ');
   2988   1.62       dsl 		if (len < length)
   2989   1.62       dsl 			break;
   2990   1.76     lukem 		printf("'%s' is longer than %d characters.\n",
   2991   1.76     lukem 		    lbuf, length - 1);
   2992   1.62       dsl 	}
   2993   1.62       dsl 	strncpy(buf, lbuf, length);
   2994    1.1       cgd }
   2995   1.62       dsl #endif
   2996    1.1       cgd 
   2997  1.132     joerg static int
   2998   1.43     lukem type_match(const void *key, const void *item)
   2999    1.4   mycroft {
   3000   1.85  christos 	const int *idp = key;
   3001   1.85  christos 	const struct mbr_ptype *ptr = item;
   3002    1.4   mycroft 
   3003   1.85  christos 	if (*idp < ptr->id)
   3004    1.4   mycroft 		return (-1);
   3005   1.85  christos 	if (*idp > ptr->id)
   3006    1.4   mycroft 		return (1);
   3007    1.4   mycroft 	return (0);
   3008    1.4   mycroft }
   3009    1.4   mycroft 
   3010  1.132     joerg static const char *
   3011   1.43     lukem get_type(int type)
   3012    1.4   mycroft {
   3013   1.85  christos 	struct mbr_ptype *ptr;
   3014    1.4   mycroft 
   3015   1.85  christos 	ptr = bsearch(&type, mbr_ptypes, KNOWN_SYSIDS,
   3016   1.86  christos 	    sizeof(mbr_ptypes[0]), type_match);
   3017    1.4   mycroft 	if (ptr == 0)
   3018    1.4   mycroft 		return ("unknown");
   3019   1.16      phil 	return (ptr->name);
   3020    1.1       cgd }
   3021  1.121  christos 
   3022  1.132     joerg static int
   3023  1.121  christos read_gpt(daddr_t offset, struct gpt_hdr *gptp)
   3024  1.121  christos {
   3025  1.121  christos 	char buf[512];
   3026  1.121  christos 	struct gpt_hdr *hdr = (void *)buf;
   3027  1.121  christos 	const char *tabletype = GPT_TYPE(offset);
   3028  1.121  christos 
   3029  1.121  christos 	if (read_disk(offset, buf) == -1) {
   3030  1.121  christos 		warn("Can't read %s GPT header", tabletype);
   3031  1.121  christos 		return -1;
   3032  1.121  christos 	}
   3033  1.121  christos 	(void)memcpy(gptp, buf, GPT_HDR_SIZE);
   3034  1.121  christos 
   3035  1.121  christos 	/* GPT CRC should be calculated with CRC field preset to zero */
   3036  1.121  christos 	hdr->hdr_crc_self = 0;
   3037  1.121  christos 
   3038  1.121  christos 	if (memcmp(gptp->hdr_sig, GPT_HDR_SIG, sizeof(gptp->hdr_sig))
   3039  1.121  christos 	    || gptp->hdr_lba_self != (uint64_t)offset
   3040  1.121  christos 	    || crc32(0, (void *)hdr, gptp->hdr_size) != gptp->hdr_crc_self) {
   3041  1.121  christos 		/* not a GPT */
   3042  1.121  christos 		(void)memset(gptp, 0, GPT_HDR_SIZE);
   3043  1.121  christos 	}
   3044  1.121  christos 
   3045  1.121  christos 	if (v_flag && gptp->hdr_size != 0) {
   3046  1.121  christos 		printf("Found %s GPT header CRC %"PRIu32" "
   3047  1.121  christos 		    "at sector %"PRIdaddr", backup at %"PRIdaddr"\n",
   3048  1.121  christos 		    tabletype, gptp->hdr_crc_self, offset, gptp->hdr_lba_alt);
   3049  1.121  christos 	}
   3050  1.121  christos 	return gptp->hdr_size;
   3051  1.121  christos 
   3052  1.121  christos }
   3053  1.121  christos 
   3054  1.132     joerg static int
   3055  1.121  christos delete_gpt(struct gpt_hdr *gptp)
   3056  1.121  christos {
   3057  1.121  christos 	char buf[512];
   3058  1.121  christos 	struct gpt_hdr *hdr = (void *)buf;
   3059  1.121  christos 
   3060  1.121  christos 	if (gptp->hdr_size == 0)
   3061  1.121  christos 		return 0;
   3062  1.121  christos 
   3063  1.121  christos 	/* don't accidently overwrite something important */
   3064  1.121  christos 	if (gptp->hdr_lba_self != GPT_HDR_BLKNO &&
   3065  1.121  christos 	    gptp->hdr_lba_self != (uint64_t)disksectors - 1) {
   3066  1.121  christos 		warnx("given GPT header location doesn't seem correct");
   3067  1.121  christos 		return -1;
   3068  1.121  christos 	}
   3069  1.121  christos 
   3070  1.121  christos 	(void)memcpy(buf, gptp, GPT_HDR_SIZE);
   3071  1.121  christos 	/*
   3072  1.121  christos 	 * Don't really delete GPT, just "disable" it, so it can
   3073  1.121  christos 	 * be recovered later in case of mistake or something
   3074  1.121  christos 	 */
   3075  1.121  christos 	(void)memset(hdr->hdr_sig, 0, sizeof(gptp->hdr_sig));
   3076  1.121  christos 	if (write_disk(gptp->hdr_lba_self, hdr) == -1) {
   3077  1.121  christos 		warn("can't delete %s GPT header",
   3078  1.121  christos 		    GPT_TYPE(gptp->hdr_lba_self));
   3079  1.121  christos 		return -1;
   3080  1.121  christos 	}
   3081  1.121  christos 	(void)memset(gptp, 0, GPT_HDR_SIZE);
   3082  1.121  christos 	return 1;
   3083  1.121  christos }
   3084