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