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