xref: /netbsd-src/sbin/fdisk/fdisk.c (revision a4ddc2c8fb9af816efe3b1c375a5530aef0e89e9)
1 /*	$NetBSD: fdisk.c,v 1.144 2013/02/13 00:40:28 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.144 2013/02/13 00:40:28 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 #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 		if (F_flag)
1649 			return;
1650 		warnx("Cannot determine the number of heads");
1651 		return;
1652 	}
1653 
1654 	if (xsectors == -1) {
1655 		warnx("Cannot determine the number of sectors");
1656 		return;
1657 	}
1658 
1659 	/* Estimate the number of cylinders. */
1660 	xcylinders = disklabel.d_secperunit / xheads / xsectors;
1661 	if (disklabel.d_secperunit > xcylinders * xheads * xsectors)
1662 		xcylinders++;
1663 
1664 	/*
1665 	 * Now verify consistency with each of the partition table entries.
1666 	 * Be willing to shove cylinders up a little bit to make things work,
1667 	 * but translation mismatches are fatal.
1668 	 */
1669 	for (i = 0; i < MBR_PART_COUNT * 2; i++) {
1670 		if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
1671 			continue;
1672 		if (c1 >= MAXCYL - 2)
1673 			continue;
1674 		if (xsectors * (c1 * xheads + h1) + s1 != a1)
1675 			return;
1676 	}
1677 
1678 
1679 	/* Everything checks out.
1680 	 * Reset the geometry to use for further calculations.
1681 	 * But cylinders cannot be > 1024.
1682 	 */
1683 	if (xcylinders > MAXCYL)
1684 		dos_cylinders = MAXCYL;
1685 	else
1686 		dos_cylinders = xcylinders;
1687 	dos_heads = xheads;
1688 	dos_sectors = xsectors;
1689 }
1690 
1691 /*
1692  * For the purposes of intuit_translated_geometry(), treat the partition
1693  * table as a list of eight mapping between (cylinder, head, sector)
1694  * triplets and absolute sectors.  Get the relevant geometry triplet and
1695  * absolute sectors for a given entry, or return -1 if it isn't present.
1696  * Note: for simplicity, the returned sector is 0-based.
1697  */
1698 static int
1699 get_mapping(int i, unsigned int *cylinder, unsigned int *head, unsigned int *sector,
1700     unsigned long *absolute)
1701 {
1702 	struct mbr_partition *part = &mboot.mbr_parts[i / 2];
1703 
1704 	if (part->mbrp_type == 0)
1705 		return -1;
1706 	if (i % 2 == 0) {
1707 		*cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
1708 		*head = part->mbrp_shd;
1709 		*sector = MBR_PSECT(part->mbrp_ssect);
1710 		*absolute = le32toh(part->mbrp_start);
1711 	} else {
1712 		*cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
1713 		*head = part->mbrp_ehd;
1714 		*sector = MBR_PSECT(part->mbrp_esect);
1715 		*absolute = le32toh(part->mbrp_start)
1716 		    + le32toh(part->mbrp_size) - 1;
1717 	}
1718 	/* Sanity check the data against all zeroes */
1719 	if ((*cylinder == 0) && (*sector == 0) && (*head == 0))
1720 		return -1;
1721 	/* sector numbers in the MBR partition table start at 1 */
1722 	*sector = *sector - 1;
1723 	/* Sanity check the data against max values */
1724 	if ((((*cylinder * MAXHEAD) + *head) * MAXSECTOR + *sector) < *absolute)
1725 		/* cannot be a CHS mapping */
1726 		return -1;
1727 	return 0;
1728 }
1729 
1730 static void
1731 delete_ptn(int part)
1732 {
1733 	if (part == ext.ptn_id) {
1734 		/* forget all about the extended partition */
1735 		free(ext.ptn);
1736 		memset(&ext, 0, sizeof ext);
1737 	}
1738 
1739 	mboot.mbr_parts[part].mbrp_type = 0;
1740 }
1741 
1742 static void
1743 delete_ext_ptn(int part)
1744 {
1745 
1746 	if (part == 0) {
1747 		ext.ptn[0].mbr_parts[0].mbrp_type = 0;
1748 		return;
1749 	}
1750 	ext.ptn[part - 1].mbr_parts[1] = ext.ptn[part].mbr_parts[1];
1751 	memmove(&ext.ptn[part], &ext.ptn[part + 1],
1752 		(ext.num_ptn - part - 1) * sizeof ext.ptn[0]);
1753 	ext.num_ptn--;
1754 }
1755 
1756 static int
1757 add_ext_ptn(daddr_t start, daddr_t size)
1758 {
1759 	int part;
1760 	struct mbr_partition *partp;
1761 	struct mbr_sector *nptn;
1762 
1763 	nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
1764 	if (!nptn)
1765 		err(1, "realloc");
1766 	ext.ptn = nptn;
1767 	for (part = 0; part < ext.num_ptn; part++)
1768 		if (ext_offset(part) > start)
1769 			break;
1770 	/* insert before 'part' - make space... */
1771 	memmove(&ext.ptn[part + 1], &ext.ptn[part],
1772 		(ext.num_ptn - part) * sizeof ext.ptn[0]);
1773 	memset(&ext.ptn[part], 0, sizeof ext.ptn[0]);
1774 	ext.ptn[part].mbr_magic = LE_MBR_MAGIC;
1775 	/* we will be 'part' */
1776 	if (part == 0) {
1777 		/* link us to 'next' */
1778 		partp = &ext.ptn[0].mbr_parts[1];
1779 		/* offset will be fixed by caller */
1780 		partp->mbrp_size = htole32(
1781 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_start) +
1782 		    le32toh(ext.ptn[1].mbr_parts[0].mbrp_size));
1783 	} else {
1784 		/* link us to prev's next */
1785 		partp = &ext.ptn[part - 1].mbr_parts[1];
1786 		ext.ptn[part].mbr_parts[1] = *partp;
1787 		/* and prev onto us */
1788 		partp->mbrp_start = htole32(start - ptn_0_offset - ext.base);
1789 		partp->mbrp_size = htole32(size + ptn_0_offset);
1790 	}
1791 	partp->mbrp_type = 5;	/* as used by win98 */
1792 	partp->mbrp_flag = 0;
1793 	/* wallop in some CHS values - win98 doesn't saturate them */
1794 	dos(le32toh(partp->mbrp_start),
1795 	    &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
1796 	dos(le32toh(partp->mbrp_start) + le32toh(partp->mbrp_size) - 1,
1797 	    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
1798 	ext.num_ptn++;
1799 
1800 	return part;
1801 }
1802 
1803 static const char *
1804 check_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1805 {
1806 	int p;
1807 	unsigned int p_s, p_e;
1808 
1809 	if (sysid != 0) {
1810 		if (start == 0)
1811 			return "Sector zero is reserved for the MBR";
1812 #if 0
1813 		if (start < ptn_0_offset)
1814 			/* This is just a convention, not a requirement */
1815 			return "Track zero is reserved for the BIOS";
1816 #endif
1817 		if (start + size > disksectors)
1818 			return "Partition exceeds size of disk";
1819 		for (p = 0; p < MBR_PART_COUNT; p++) {
1820 			if (p == part || mboot.mbr_parts[p].mbrp_type == 0)
1821 				continue;
1822 			p_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1823 			p_e = p_s + le32toh(mboot.mbr_parts[p].mbrp_size);
1824 			if (start + size <= p_s || start >= p_e)
1825 				continue;
1826 			if (f_flag) {
1827 				if (fix)
1828 					delete_ptn(p);
1829 				return 0;
1830 			}
1831 			return "Overlaps another partition";
1832 		}
1833 	}
1834 
1835 	/* Are we trying to create an extended partition */
1836 	if (!MBR_IS_EXTENDED(mboot.mbr_parts[part].mbrp_type)) {
1837 		/* this wasn't the extended partition */
1838 		if (!MBR_IS_EXTENDED(sysid))
1839 			return 0;
1840 		/* making an extended partition */
1841 		if (ext.base != 0) {
1842 			if (!f_flag)
1843 				return "There cannot be 2 extended partitions";
1844 			if (fix)
1845 				delete_ptn(ext.ptn_id);
1846 		}
1847 		if (fix) {
1848 			/* allocate a new extended partition */
1849 			ext.ptn = calloc(1, sizeof ext.ptn[0]);
1850 			if (ext.ptn == NULL)
1851 				err(1, "Malloc failed");
1852 			ext.ptn[0].mbr_magic = LE_MBR_MAGIC;
1853 			ext.ptn_id = part;
1854 			ext.base = start;
1855 			ext.limit = start + size;
1856 			ext.num_ptn = 1;
1857 		}
1858 		return 0;
1859 	}
1860 
1861 	/* Check we haven't cut space allocated to an extended ptn */
1862 
1863 	if (!MBR_IS_EXTENDED(sysid)) {
1864 		/* no longer an extended partition */
1865 		if (fix) {
1866 			/* Kill all memory of the extended partitions */
1867 			delete_ptn(part);
1868 			return 0;
1869 		}
1870 		if (ext.num_ptn == 0 ||
1871 		    (ext.num_ptn == 1 && ext.ptn[0].mbr_parts[0].mbrp_type == 0))
1872 			/* nothing in extended partition */
1873 			return 0;
1874 		if (f_flag)
1875 			return 0;
1876 		if (yesno("Do you really want to delete all the extended partitions?"))
1877 			return 0;
1878 		return "Extended partition busy";
1879 	}
1880 
1881 	if (le32toh(mboot.mbr_parts[part].mbrp_start) != ext.base)
1882 		/* maybe impossible, but an extra sanity check */
1883 		return 0;
1884 
1885 	for (p = ext.num_ptn; --p >= 0;) {
1886 		if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1887 			continue;
1888 		p_s = ext_offset(p);
1889 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1890 			  + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1891 		if (p_s >= start && p_e <= start + size)
1892 			continue;
1893 		if (!f_flag)
1894 			return "Extended partition outside main partition";
1895 		if (fix)
1896 			delete_ext_ptn(p);
1897 	}
1898 
1899 	if (fix && start != ext.base) {
1900 		/* The internal offsets need to be fixed up */
1901 		for (p = 0; p < ext.num_ptn - 1; p++)
1902 			ext.ptn[p].mbr_parts[1].mbrp_start = htole32(
1903 			    le32toh(ext.ptn[p].mbr_parts[1].mbrp_start)
1904 				    + ext.base - start);
1905 		/* and maybe an empty partition at the start */
1906 		if (ext.ptn[0].mbr_parts[0].mbrp_type == 0) {
1907 			if (le32toh(ext.ptn[0].mbr_parts[1].mbrp_start) == 0) {
1908 				/* don't need the empty slot */
1909 				memmove(&ext.ptn[0], &ext.ptn[1],
1910 					(ext.num_ptn - 1) * sizeof ext.ptn[0]);
1911 				ext.num_ptn--;
1912 			}
1913 		} else {
1914 			/* must create an empty slot */
1915 			add_ext_ptn(start, ptn_0_offset);
1916 			ext.ptn[0].mbr_parts[1].mbrp_start = htole32(ext.base
1917 								- start);
1918 		}
1919 	}
1920 	if (fix) {
1921 		ext.base = start;
1922 		ext.limit = start + size;
1923 	}
1924 	return 0;
1925 }
1926 
1927 static const char *
1928 check_ext_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1929 {
1930 	int p;
1931 	unsigned int p_s, p_e;
1932 
1933 	if (sysid == 0)
1934 		return 0;
1935 
1936 	if (MBR_IS_EXTENDED(sysid))
1937 		return "Nested extended partitions are not allowed";
1938 
1939 	/* allow one track at start for extended partition header */
1940 	start -= ptn_0_offset;
1941 	size += ptn_0_offset;
1942 	if (start < ext.base || start + size > ext.limit)
1943 		return "Outside bounds of extended partition";
1944 
1945 	if (f_flag && !fix)
1946 		return 0;
1947 
1948 	for (p = ext.num_ptn; --p >= 0;) {
1949 		if (p == part || ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1950 			continue;
1951 		p_s = ext_offset(p);
1952 		p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1953 			+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1954 		if (p == 0)
1955 			p_s += le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1956 							- ptn_0_offset;
1957 		if (start < p_e && start + size > p_s) {
1958 			if (!f_flag)
1959 				return "Overlaps another extended partition";
1960 			if (fix) {
1961 				if (part == -1)
1962 					delete_ext_ptn(p);
1963 				else
1964 					/* must not change numbering yet */
1965 					ext.ptn[p].mbr_parts[0].mbrp_type = 0;
1966 			}
1967 		}
1968 	}
1969 	return 0;
1970 }
1971 
1972 static int
1973 change_part(int extended, int part, int sysid, daddr_t start, daddr_t size,
1974 	char *bootmenu)
1975 {
1976 	struct mbr_partition *partp;
1977 	struct mbr_sector *boot;
1978 	daddr_t offset;
1979 	const char *e;
1980 	int upart = part;
1981 	int p;
1982 	int fl;
1983 	daddr_t n_s, n_e;
1984 	const char *errtext;
1985 #ifdef BOOTSEL
1986 	char tmp_bootmenu[MBR_PART_COUNT * (MBR_BS_PARTNAMESIZE + 1)];
1987 	int bootmenu_len = (extended ? MBR_PART_COUNT : 1) * (MBR_BS_PARTNAMESIZE + 1);
1988 #endif
1989 
1990 	if (extended) {
1991 		if (part != -1 && part < ext.num_ptn) {
1992 			boot = &ext.ptn[part];
1993 			partp = &boot->mbr_parts[0];
1994 			offset = ext_offset(part);
1995 		} else {
1996 			part = -1;
1997 			boot = 0;
1998 			partp = 0;
1999 			offset = 0;
2000 		}
2001 		upart = 0;
2002 		e = "E";
2003 	} else {
2004 		boot = &mboot;
2005 		partp = &boot->mbr_parts[part];
2006 		offset = 0;
2007 		e = "";
2008 	}
2009 
2010 	if (!f_flag && part != -1) {
2011 		printf("The data for partition %s%d is:\n", e, part);
2012 		print_part(boot, upart, offset);
2013 	}
2014 
2015 #ifdef BOOTSEL
2016 	if (bootmenu != NULL)
2017 		strlcpy(tmp_bootmenu, bootmenu, bootmenu_len);
2018 	else
2019 		if (boot != NULL && boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
2020 			strlcpy(tmp_bootmenu,
2021 				boot->mbr_bootsel.mbrbs_nametab[upart],
2022 				bootmenu_len);
2023 		else
2024 			tmp_bootmenu[0] = 0;
2025 #endif
2026 
2027 	if (!s_flag && partp != NULL) {
2028 		/* values not specified, default to current ones */
2029 		sysid = partp->mbrp_type;
2030 		start = offset + le32toh(partp->mbrp_start);
2031 		size = le32toh(partp->mbrp_size);
2032 	}
2033 
2034 	/* creating a new partition, default to free space */
2035 	if (!s_flag && sysid == 0 && extended) {
2036 		/* non-extended partition */
2037 		start = ext.base;
2038 		for (p = 0; p < ext.num_ptn; p++) {
2039 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2040 				continue;
2041 			n_s = ext_offset(p);
2042 			if (n_s > start + ptn_0_offset)
2043 				break;
2044 			start = ext_offset(p)
2045 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2046 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
2047 		}
2048 		if (ext.limit - start <= ptn_0_offset) {
2049 			printf("No space in extended partition\n");
2050 			return 0;
2051 		}
2052 		start += ptn_0_offset;
2053 	}
2054 
2055 	if (!s_flag && sysid == 0 && !extended) {
2056 		/* same for non-extended partition */
2057 		/* first see if old start is free */
2058 		if (start < ptn_0_offset)
2059 			start = 0;
2060 		for (p = 0; start != 0 && p < MBR_PART_COUNT; p++) {
2061 			if (mboot.mbr_parts[p].mbrp_type == 0)
2062 				continue;
2063 			n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2064 			if (start >= n_s &&
2065 			    start < n_s + le32toh(mboot.mbr_parts[p].mbrp_size))
2066 				start = 0;
2067 		}
2068 		if (start == 0) {
2069 			/* Look for first gap */
2070 			start = ptn_0_offset;
2071 			for (p = 0; p < MBR_PART_COUNT; p++) {
2072 				if (mboot.mbr_parts[p].mbrp_type == 0)
2073 					continue;
2074 				n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2075 				n_e = n_s + le32toh(mboot.mbr_parts[p].mbrp_size);
2076 				if (start >= n_s && start < n_e) {
2077 					start = n_e;
2078 					p = -1;
2079 				}
2080 			}
2081 			if (start >= disksectors && !I_flag) {
2082 				printf("No free space\n");
2083 				return 0;
2084 			}
2085 		}
2086 	}
2087 
2088 	if (!f_flag) {
2089 		/* request new values from user */
2090 		if (sysid == 0)
2091 			sysid = 169;
2092 		sysid = decimal("sysid", sysid, 0, 0, 255);
2093 		if (sysid == 0 && !v_flag) {
2094 			start = 0;
2095 			size = 0;
2096 #ifdef BOOTSEL
2097 			tmp_bootmenu[0] = 0;
2098 #endif
2099 		} else {
2100 			daddr_t old = start;
2101 			daddr_t lim = extended ? ext.limit : disksectors;
2102 			start = decimal("start", start,
2103 				DEC_SEC | DEC_RND_0 | (extended ? DEC_RND : 0),
2104 				extended ? ext.base : 0, lim);
2105 			/* Adjust 'size' so that end doesn't move when 'start'
2106 			 * is only changed slightly.
2107 			 */
2108 			if (size > start - old)
2109 				size -= start - old;
2110 			else
2111 				size = 0;
2112 			/* Find end of available space from this start point */
2113 			if (extended) {
2114 				for (p = 0; p < ext.num_ptn; p++) {
2115 					if (p == part)
2116 						continue;
2117 					if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2118 						continue;
2119 					n_s = ext_offset(p);
2120 					if (n_s > start && n_s < lim)
2121 						lim = n_s;
2122 					if (start >= n_s && start < n_s
2123 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2124 				+ le32toh(ext.ptn[p].mbr_parts[0].mbrp_size)) {
2125 						lim = start;
2126 						break;
2127 					}
2128 				}
2129 			} else {
2130 				for (p = 0; p < MBR_PART_COUNT; p++) {
2131 					if (p == part)
2132 						continue;
2133 					if (mboot.mbr_parts[p].mbrp_type == 0)
2134 						continue;
2135 					n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2136 					if (n_s > start && n_s < lim)
2137 						lim = n_s;
2138 					if (start >= n_s && start < n_s
2139 				    + le32toh(mboot.mbr_parts[p].mbrp_size)) {
2140 						lim = start;
2141 						break;
2142 					}
2143 				}
2144 			}
2145 			lim -= start;
2146 			if (lim == 0) {
2147 				printf("Start sector already allocated\n");
2148 				return 0;
2149 			}
2150 			if (size == 0 || size > lim)
2151 				size = lim;
2152 			fl = DEC_SEC;
2153 			if (start % ptn_alignment == ptn_0_offset)
2154 				fl |= DEC_RND_DOWN;
2155 			if (start == 2 * ptn_0_offset)
2156 				fl |= DEC_RND_DOWN | DEC_RND_DOWN_2;
2157 			size = decimal("size", size, fl, 0, lim);
2158 #ifdef BOOTSEL
2159 #ifndef DEFAULT_BOOTEXTCODE
2160 			if (!extended)
2161 #endif
2162 				string("bootmenu", bootmenu_len, tmp_bootmenu);
2163 #endif
2164 		}
2165 	}
2166 
2167 	/*
2168 	 * Before we write these away, we must verify that nothing
2169 	 * untoward has been requested.
2170 	 */
2171 
2172 	if (extended)
2173 		errtext = check_ext_overlap(part, sysid, start, size, 0);
2174 	else
2175 		errtext = check_overlap(part, sysid, start, size, 0);
2176 	if (errtext != NULL && !I_flag) {
2177 		if (f_flag)
2178 			errx(2, "%s\n", errtext);
2179 		printf("%s\n", errtext);
2180 		return 0;
2181 	}
2182 
2183 	/*
2184 	 * Before proceeding, delete any overlapped partitions.
2185 	 * This can only happen if '-f' was supplied on the command line.
2186 	 * Just hope the caller knows what they are doing.
2187 	 * This also fixes the base of each extended partition if the
2188 	 * partition itself has moved.
2189 	 */
2190 	if (!I_flag) {
2191 		if (extended)
2192 			errtext = check_ext_overlap(part, sysid, start, size, 1);
2193 		else
2194 			errtext = check_overlap(part, sysid, start, size, 1);
2195 		if (errtext)
2196 			errx(1, "%s\n", errtext);
2197 	}
2198 
2199 
2200 	if (sysid == 0) {
2201 		/* delete this partition - save info though */
2202 		if (partp == NULL)
2203 			/* must have been trying to create an extended ptn */
2204 			return 0;
2205 		if (start == 0 && size == 0)
2206 			memset(partp, 0, sizeof *partp);
2207 #ifdef BOOTSEL
2208 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
2209 			memset(boot->mbr_bootsel.mbrbs_nametab[upart], 0,
2210 				sizeof boot->mbr_bootsel.mbrbs_nametab[0]);
2211 #endif
2212 		if (extended)
2213 			delete_ext_ptn(part);
2214 		else
2215 			delete_ptn(part);
2216 		return 1;
2217 	}
2218 
2219 
2220 	if (extended) {
2221 		if (part != -1)
2222 			delete_ext_ptn(part);
2223 		if (start == ext.base + ptn_0_offset)
2224 			/* First one must have been free */
2225 			part = 0;
2226 		else
2227 			part = add_ext_ptn(start, size);
2228 
2229 		/* These must be re-calculated because of the realloc */
2230 		boot = &ext.ptn[part];
2231 		partp = &boot->mbr_parts[0];
2232 		offset = ext_offset(part);
2233 	}
2234 
2235 	partp->mbrp_type = sysid;
2236 	partp->mbrp_start = htole32( start - offset);
2237 	partp->mbrp_size = htole32( size);
2238 	dos(start, &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
2239 	dos(start + size - 1,
2240 		    &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
2241 #ifdef BOOTSEL
2242 	if (extended) {
2243 		boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
2244 		strncpy(boot->mbr_bootsel.mbrbs_nametab[upart], tmp_bootmenu,
2245 			bootmenu_len);
2246 	} else {
2247 		/* We need to bootselect code installed in order to have
2248 		 * somewhere to safely write the menu tag.
2249 		 */
2250 		if (boot->mbr_bootsel_magic != LE_MBR_BS_MAGIC) {
2251 			if (f_flag ||
2252 			    yesno("The bootselect code is not installed, "
2253 				"do you want to install it now?"))
2254 				install_bootsel(MBR_BS_ACTIVE);
2255 		}
2256 		if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
2257 			strncpy(boot->mbr_bootsel.mbrbs_nametab[upart],
2258 				tmp_bootmenu, bootmenu_len);
2259 		}
2260 	}
2261 #endif
2262 
2263 	if (v_flag && !f_flag && yesno("Explicitly specify beg/end address?")) {
2264 		/* this really isn't a good idea.... */
2265 		int tsector, tcylinder, thead;
2266 
2267 		tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
2268 		thead = partp->mbrp_shd;
2269 		tsector = MBR_PSECT(partp->mbrp_ssect);
2270 		tcylinder = decimal("beginning cylinder",
2271 				tcylinder, 0, 0, dos_cylinders - 1);
2272 		thead = decimal("beginning head",
2273 				thead, 0, 0, dos_heads - 1);
2274 		tsector = decimal("beginning sector",
2275 				tsector, 0, 1, dos_sectors);
2276 		partp->mbrp_scyl = DOSCYL(tcylinder);
2277 		partp->mbrp_shd = thead;
2278 		partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
2279 
2280 		tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
2281 		thead = partp->mbrp_ehd;
2282 		tsector = MBR_PSECT(partp->mbrp_esect);
2283 		tcylinder = decimal("ending cylinder",
2284 				tcylinder, 0, 0, dos_cylinders - 1);
2285 		thead = decimal("ending head",
2286 				thead, 0, 0, dos_heads - 1);
2287 		tsector = decimal("ending sector",
2288 				tsector, 0, 1, dos_sectors);
2289 		partp->mbrp_ecyl = DOSCYL(tcylinder);
2290 		partp->mbrp_ehd = thead;
2291 		partp->mbrp_esect = DOSSECT(tsector, tcylinder);
2292 	}
2293 
2294 	/* If we had to mark an extended partition as deleted because
2295 	 * another request would have overlapped it, now is the time
2296 	 * to do the actual delete.
2297 	 */
2298 	if (extended && f_flag) {
2299 		for (p = ext.num_ptn; --p >= 0;)
2300 			if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2301 				delete_ext_ptn(p);
2302 	}
2303 	return 1;
2304 }
2305 
2306 static void
2307 print_geometry(void)
2308 {
2309 
2310 	if (sh_flag) {
2311 		printf("DISK=%s\n", disk);
2312 		printf("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%"PRIdaddr"\n",
2313 			cylinders, heads, sectors, disksectors);
2314 		printf("BCYL=%d\nBHEAD=%d\nBSEC=%d\nBDLSIZE=%"PRIdaddr"\n",
2315 			dos_cylinders, dos_heads, dos_sectors, dos_disksectors);
2316 		printf("NUMEXTPTN=%d\n", ext.num_ptn);
2317 		return;
2318 	}
2319 
2320 	/* Not sh_flag */
2321 	printf("Disk: %s\n", disk);
2322 	printf("NetBSD disklabel disk geometry:\n");
2323 	printf("cylinders: %d, heads: %d, sectors/track: %d "
2324 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
2325 	    cylinders, heads, sectors, cylindersectors, disksectors);
2326 	printf("BIOS disk geometry:\n");
2327 	printf("cylinders: %d, heads: %d, sectors/track: %d "
2328 	    "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
2329 	    dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors,
2330 	    dos_disksectors);
2331 	printf("Partitions aligned to %d sector boundaries, offset %d\n\n",
2332 	    ptn_alignment, ptn_0_offset);
2333 }
2334 
2335 /* Find the first active partition, else return MBR_PART_COUNT */
2336 static int
2337 first_active(void)
2338 {
2339 	struct mbr_partition *partp = &mboot.mbr_parts[0];
2340 	int part;
2341 
2342 	for (part = 0; part < MBR_PART_COUNT; part++)
2343 		if (partp[part].mbrp_flag & MBR_PFLAG_ACTIVE)
2344 			return part;
2345 	return MBR_PART_COUNT;
2346 }
2347 
2348 static void
2349 change_active(int which)
2350 {
2351 	struct mbr_partition *partp;
2352 	int part;
2353 	int active = MBR_PART_COUNT;
2354 
2355 	partp = &mboot.mbr_parts[0];
2356 
2357 	if (a_flag && which != -1)
2358 		active = which;
2359 	else
2360 		active = first_active();
2361 	if (!f_flag) {
2362 		if (yesno("Do you want to change the active partition?")) {
2363 			printf ("Choosing %d will make no partition active.\n",
2364 			    MBR_PART_COUNT);
2365 			do {
2366 				active = decimal("active partition",
2367 						active, 0, 0, MBR_PART_COUNT);
2368 			} while (!yesno("Are you happy with this choice?"));
2369 		} else
2370 			return;
2371 	} else
2372 		if (active != MBR_PART_COUNT)
2373 			printf ("Making partition %d active.\n", active);
2374 
2375 	for (part = 0; part < MBR_PART_COUNT; part++)
2376 		partp[part].mbrp_flag &= ~MBR_PFLAG_ACTIVE;
2377 	if (active < MBR_PART_COUNT)
2378 		partp[active].mbrp_flag |= MBR_PFLAG_ACTIVE;
2379 }
2380 
2381 static void
2382 change_bios_geometry(void)
2383 {
2384 	print_geometry();
2385 	if (!yesno("Do you want to change our idea of what BIOS thinks?"))
2386 		return;
2387 
2388 #if defined(USE_DISKLIST)
2389 	if (dl != NULL) {
2390 		struct biosdisk_info *bip;
2391 		int i;
2392 
2393 		for (i = 0; i < dl->dl_nbiosdisks; i++) {
2394 			if (i == 0)
2395 				printf("\nGeometries of known disks:\n");
2396 			bip = &dl->dl_biosdisks[i];
2397 			printf("Disk %d: cylinders %u, heads %u, sectors %u"
2398 				" (%"PRIdaddr" sectors, %dMB)\n",
2399 			    i, bip->bi_cyl, bip->bi_head, bip->bi_sec,
2400 			    bip->bi_lbasecs, SEC_TO_MB(bip->bi_lbasecs));
2401 
2402 		}
2403 		printf("\n");
2404 	}
2405 #endif
2406 	do {
2407 		dos_cylinders = decimal("BIOS's idea of #cylinders",
2408 					dos_cylinders, 0, 0, MAXCYL);
2409 		dos_heads = decimal("BIOS's idea of #heads",
2410 					dos_heads, 0, 0, MAXHEAD);
2411 		dos_sectors = decimal("BIOS's idea of #sectors",
2412 					dos_sectors, 0, 1, MAXSECTOR);
2413 		print_geometry();
2414 	} while (!yesno("Are you happy with this choice?"));
2415 }
2416 
2417 
2418 /***********************************************\
2419 * Change real numbers into strange dos numbers	*
2420 \***********************************************/
2421 static void
2422 dos(int sector, unsigned char *cylinderp, unsigned char *headp,
2423     unsigned char *sectorp)
2424 {
2425 	int cylinder, head;
2426 
2427 	cylinder = sector / dos_cylindersectors;
2428 	sector -= cylinder * dos_cylindersectors;
2429 
2430 	head = sector / dos_sectors;
2431 	sector -= head * dos_sectors;
2432 	if (cylinder > 1023)
2433 		cylinder = 1023;
2434 
2435 	*cylinderp = DOSCYL(cylinder);
2436 	*headp = head;
2437 	*sectorp = DOSSECT(sector + 1, cylinder);
2438 }
2439 
2440 static int
2441 open_disk(int update)
2442 {
2443 	static char namebuf[MAXPATHLEN + 1];
2444 	int flags = update && disk_file == NULL ? O_RDWR : O_RDONLY;
2445 
2446 	if (!F_flag) {
2447 		fd = opendisk(disk, flags, namebuf, sizeof(namebuf), 0);
2448 		if (fd < 0) {
2449 			if (errno == ENODEV)
2450 				warnx("%s is not a character device", namebuf);
2451 			else
2452 				warn("cannot opendisk %s", namebuf);
2453 			return (-1);
2454 		}
2455 		disk = namebuf;
2456 	} else {
2457 		fd = open(disk, flags, 0);
2458 		if (fd == -1) {
2459 			warn("cannot open %s", disk);
2460 			return -1;
2461 		}
2462 	}
2463 
2464 	if (get_params() == -1) {
2465 		close(fd);
2466 		fd = -1;
2467 		return (-1);
2468 	}
2469 	if (disk_file != NULL) {
2470 		/* for testing: read/write data from a disk file */
2471 		wfd = open(disk_file, update ? O_RDWR|O_CREAT : O_RDONLY, 0777);
2472 		if (wfd == -1) {
2473 			warn("%s", disk_file);
2474 			close(fd);
2475 			fd = -1;
2476 			return -1;
2477 		}
2478 	} else
2479 		wfd = fd;
2480 	return (0);
2481 }
2482 
2483 static ssize_t
2484 read_disk(daddr_t sector, void *buf)
2485 {
2486 	ssize_t nr;
2487 
2488 	if (*rfd == -1)
2489 		errx(1, "read_disk(); fd == -1");
2490 
2491 	off_t offs = sector * (off_t)512;
2492 	off_t mod = offs & (secsize - 1);
2493 	off_t rnd = offs & ~(secsize - 1);
2494 
2495 	if (lseek(*rfd, rnd, SEEK_SET) == (off_t)-1)
2496 		return -1;
2497 
2498 	if (secsize == 512)
2499 		return read(*rfd, buf, 512);
2500 
2501 	if ((nr = read(*rfd, iobuf, secsize)) != secsize)
2502 		return nr;
2503 
2504 	memcpy(buf, &iobuf[mod], 512);
2505 
2506 	return 512;
2507 }
2508 
2509 static ssize_t
2510 write_disk(daddr_t sector, void *buf)
2511 {
2512 	ssize_t nr;
2513 
2514 	if (wfd == -1)
2515 		errx(1, "write_disk(); wfd == -1");
2516 
2517 	off_t offs = sector * (off_t)512;
2518 	off_t mod = offs & (secsize - 1);
2519 	off_t rnd = offs & ~(secsize - 1);
2520 
2521 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
2522 		return -1;
2523 
2524 	if (secsize == 512)
2525 		return write(wfd, buf, 512);
2526 
2527 	if ((nr = read(wfd, iobuf, secsize)) != secsize)
2528 		return nr;
2529 
2530 	if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
2531 		return -1;
2532 
2533 	memcpy(&iobuf[mod], buf, 512);
2534 
2535 	if ((nr = write(wfd, iobuf, secsize)) != secsize)
2536 		return nr;
2537 
2538 	return 512;
2539 }
2540 
2541 static void
2542 guess_geometry(daddr_t _sectors)
2543 {
2544 	dos_sectors = MAXSECTOR;
2545 	dos_heads = MAXHEAD - 1;	/* some BIOS might use 256 */
2546 	dos_cylinders = _sectors / (MAXSECTOR * (MAXHEAD - 1));
2547 	if (dos_cylinders < 1)
2548 		dos_cylinders = 1;
2549 	else if (dos_cylinders > MAXCYL - 1)
2550 		dos_cylinders = MAXCYL - 1;
2551 }
2552 
2553 static int
2554 get_params(void)
2555 {
2556 	if (disk_type != NULL) {
2557 		struct disklabel *tmplabel;
2558 
2559 		if ((tmplabel = getdiskbyname(disk_type)) == NULL) {
2560 			warn("bad disktype");
2561 			return (-1);
2562 		}
2563 		disklabel = *tmplabel;
2564 	} else if (F_flag) {
2565 		struct stat st;
2566 		if (fstat(fd, &st) == -1) {
2567 			warn("fstat");
2568 			return (-1);
2569 		}
2570 		if (st.st_size % 512 != 0) {
2571 			warnx("%s size (%lld) is not divisible "
2572 			    "by sector size (%d)", disk, (long long)st.st_size,
2573 			    512);
2574 		}
2575 		disklabel.d_secperunit = st.st_size / 512;
2576 		guess_geometry(disklabel.d_secperunit);
2577 		disklabel.d_ncylinders = dos_cylinders;
2578 		disklabel.d_ntracks = dos_heads;
2579 		disklabel.d_nsectors = dos_sectors;
2580 	} else if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
2581 		warn("DIOCGDEFLABEL");
2582 		if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
2583 			warn("DIOCGDINFO");
2584 			return (-1);
2585 		}
2586 	}
2587 
2588 	disksectors = disklabel.d_secperunit;
2589 	cylinders = disklabel.d_ncylinders;
2590 	heads = disklabel.d_ntracks;
2591 	sectors = disklabel.d_nsectors;
2592 
2593 	/* pick up some defaults for the BIOS sizes */
2594 	if (sectors <= MAXSECTOR) {
2595 		dos_cylinders = cylinders;
2596 		dos_heads = heads;
2597 		dos_sectors = sectors;
2598 	} else {
2599 		/* guess - has to better than the above */
2600 		guess_geometry(disksectors);
2601 	}
2602 	dos_disksectors = disksectors;
2603 
2604 	return (0);
2605 }
2606 
2607 #ifdef BOOTSEL
2608 /*
2609  * Rather unfortunately the bootsel 'magic' number is at the end of the
2610  * the structure, and there is no checksum.  So when other operating
2611  * systems install mbr code by only writing the length of their code they
2612  * can overwrite part of the structure but keeping the magic number intact.
2613  * This code attempts to empirically detect this problem.
2614  */
2615 static int
2616 validate_bootsel(struct mbr_bootsel *mbs)
2617 {
2618 	unsigned int key = mbs->mbrbs_defkey;
2619 	unsigned int tmo;
2620 	size_t i;
2621 
2622 	if (v_flag)
2623 		return 0;
2624 
2625 	/*
2626 	 * Check default key is sane
2627 	 * - this is the most likely field to be stuffed
2628 	 * 16 disks and 16 bootable partitions seems enough!
2629 	 * (the keymap decode starts falling apart at that point)
2630 	 */
2631 	if (mbs->mbrbs_flags & MBR_BS_ASCII) {
2632 		if (key != 0 && !(key == '\r'
2633 		    || (key >= '1' && key < '1' + MAX_BIOS_DISKS)
2634 		    || (key >= 'a' && key < 'a' + MAX_BIOS_DISKS)))
2635 			return 1;
2636 	} else {
2637 		if (key != 0 && !(key == SCAN_ENTER
2638 		    || (key >= SCAN_1 && key < SCAN_1 + MAX_BIOS_DISKS)
2639 		    || (key >= SCAN_F1 && key < SCAN_F1 + MAX_BIOS_DISKS)))
2640 			return 1;
2641 	}
2642 
2643 	/* Checking the flags will lead to breakage... */
2644 
2645 	/* Timeout value is expected to be a multiple of a second */
2646 	tmo = htole16(mbs->mbrbs_timeo);
2647 	if (tmo != 0 && tmo != 0xffff && tmo != (10 * tmo + 9) / 182 * 182 / 10)
2648 		return 2;
2649 
2650 	/* Check the menu strings are printable */
2651 	/* Unfortunately they aren't zero filled... */
2652 	for (i = 0; i < sizeof(mbs->mbrbs_nametab); i++) {
2653 		int c = (uint8_t)mbs->mbrbs_nametab[0][i];
2654 		if (c == 0 || isprint(c))
2655 			continue;
2656 		return 3;
2657 	}
2658 
2659 	return 0;
2660 }
2661 #endif
2662 
2663 static int
2664 read_s0(daddr_t offset, struct mbr_sector *boot)
2665 {
2666 	const char *tabletype = offset ? "extended" : "primary";
2667 #ifdef BOOTSEL
2668 	static int reported;
2669 #endif
2670 
2671 	if (read_disk(offset, boot) == -1) {
2672 		warn("Can't read %s partition table", tabletype);
2673 		return -1;
2674 	}
2675 	if (boot->mbr_magic != LE_MBR_MAGIC) {
2676 		if (F_flag && boot->mbr_magic == 0)
2677 			return -1;
2678 		warnx("%s partition table invalid, "
2679 		    "no magic in sector %"PRIdaddr, tabletype, offset);
2680 		return -1;
2681 
2682 	}
2683 #ifdef BOOTSEL
2684 	if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
2685 		/* mbr_bootsel in new location */
2686 		if (validate_bootsel(&boot->mbr_bootsel)) {
2687 			warnx("removing corrupt bootsel information");
2688 			boot->mbr_bootsel_magic = 0;
2689 		}
2690 		return 0;
2691 	}
2692 	if (boot->mbr_bootsel_magic != LE_MBR_MAGIC)
2693 		return 0;
2694 
2695 	/* mbr_bootsel in old location */
2696 	if (!reported)
2697 		warnx("%s partition table: using old-style bootsel information",
2698 		    tabletype);
2699 	reported = 1;
2700 	if (validate_bootsel((void *)((uint8_t *)boot + MBR_BS_OFFSET + 4))) {
2701 		warnx("%s bootsel information corrupt - ignoring", tabletype);
2702 		return 0;
2703 	}
2704 	memmove((uint8_t *)boot + MBR_BS_OFFSET,
2705 		(uint8_t *)boot + MBR_BS_OFFSET + 4,
2706 		sizeof(struct mbr_bootsel));
2707 	if ( ! (boot->mbr_bootsel.mbrbs_flags & MBR_BS_NEWMBR)) {
2708 			/* old style default key */
2709 		int id;
2710 			/* F1..F4 => ptn 0..3, F5+ => disk 0+ */
2711 		id = boot->mbr_bootsel.mbrbs_defkey;
2712 		id -= SCAN_F1;
2713 		if (id >= MBR_PART_COUNT)
2714 			id -= MBR_PART_COUNT; /* Use number of disk */
2715 		else if (mboot.mbr_parts[id].mbrp_type != 0)
2716 			id = le32toh(boot->mbr_parts[id].mbrp_start);
2717 		else
2718 			id = DEFAULT_ACTIVE;
2719 		boot->mbr_bootsel.mbrbs_defkey = id;
2720 	}
2721 	boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
2722 		/* highlight that new bootsel code is necessary */
2723 	boot->mbr_bootsel.mbrbs_flags &= ~MBR_BS_NEWMBR;
2724 #endif /* BOOTSEL */
2725 	return 0;
2726 }
2727 
2728 static int
2729 write_mbr(void)
2730 {
2731 	int flag, i;
2732 	daddr_t offset;
2733 	int rval = -1;
2734 
2735 	/*
2736 	 * write enable label sector before write (if necessary),
2737 	 * disable after writing.
2738 	 * needed if the disklabel protected area also protects
2739 	 * sector 0. (e.g. empty disk)
2740 	 */
2741 	flag = 1;
2742 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2743 		warn("DIOCWLABEL");
2744 	if (write_disk(0, &mboot) == -1) {
2745 		warn("Can't write fdisk partition table");
2746 		goto protect_label;
2747 	}
2748 	if (boot_installed)
2749 		for (i = bootsize; (i -= 0x200) > 0;)
2750 			if (write_disk(i / 0x200, &bootcode[i / 0x200]) == -1) {
2751 				warn("Can't write bootcode");
2752 				goto protect_label;
2753 			}
2754 	for (offset = 0, i = 0; i < ext.num_ptn; i++) {
2755 		if (write_disk(ext.base + offset, ext.ptn + i) == -1) {
2756 			warn("Can't write %dth extended partition", i);
2757 			goto protect_label;
2758 		}
2759 		offset = le32toh(ext.ptn[i].mbr_parts[1].mbrp_start);
2760 	}
2761 	rval = 0;
2762     protect_label:
2763 	flag = 0;
2764 	if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2765 		warn("DIOCWLABEL");
2766 	return rval;
2767 }
2768 
2769 static int
2770 yesno(const char *str, ...)
2771 {
2772 	int ch, first;
2773 	va_list ap;
2774 
2775 	va_start(ap, str);
2776 	vprintf(str, ap);
2777 	va_end(ap);
2778 	printf(" [n] ");
2779 
2780 	first = ch = getchar();
2781 	while (ch != '\n' && ch != EOF)
2782 		ch = getchar();
2783 	if (ch == EOF)
2784 		errx(1, "EOF");
2785 	return (first == 'y' || first == 'Y');
2786 }
2787 
2788 static int64_t
2789 decimal(const char *prompt, int64_t dflt, int flags, int64_t minval, int64_t maxval)
2790 {
2791 	int64_t acc = 0;
2792 	int valid;
2793 	int len;
2794 	char *cp;
2795 
2796 	for (;;) {
2797 		if (flags & DEC_SEC) {
2798 			printf("%s: [%" PRId64 "..%" PRId64 "cyl default: %" PRId64 ", %" PRId64 "cyl, %uMB] ",
2799 			    prompt, SEC_TO_CYL(minval), SEC_TO_CYL(maxval),
2800 			    dflt, SEC_TO_CYL(dflt), SEC_TO_MB(dflt));
2801 		} else
2802 			printf("%s: [%" PRId64 "..%" PRId64 " default: %" PRId64 "] ",
2803 			    prompt, minval, maxval, dflt);
2804 
2805 		if (!fgets(lbuf, LBUF, stdin))
2806 			errx(1, "EOF");
2807 		cp = lbuf;
2808 
2809 		cp += strspn(cp, " \t");
2810 		if (*cp == '\n')
2811 			return dflt;
2812 
2813 		if (cp[0] == '$' && cp[1] == '\n')
2814 			return maxval;
2815 
2816 		if (isdigit((unsigned char)*cp) || *cp == '-') {
2817 			acc = strtoll(lbuf, &cp, 10);
2818 			len = strcspn(cp, " \t\n");
2819 			valid = 0;
2820 			if (len != 0 && (flags & DEC_SEC)) {
2821 				if (!strncasecmp(cp, "gb", len)) {
2822 					acc *= 1024;
2823 					valid = 1;
2824 				}
2825 				if (valid || !strncasecmp(cp, "mb", len)) {
2826 					acc *= SEC_IN_1M;
2827 					/* round to whole number of cylinders */
2828 					acc += ptn_alignment / 2;
2829 					acc /= ptn_alignment;
2830 					valid = 1;
2831 				}
2832 				if (valid || !strncasecmp(cp, "cyl", len)) {
2833 					acc *= ptn_alignment;
2834 					/* adjustments for cylinder boundary */
2835 					if (acc == 0 && flags & DEC_RND_0)
2836 						acc += ptn_0_offset;
2837 					if (flags & DEC_RND)
2838 						acc += ptn_0_offset;
2839 					if (flags & DEC_RND_DOWN)
2840 						acc -= ptn_0_offset;
2841 					if (flags & DEC_RND_DOWN_2)
2842 						acc -= ptn_0_offset;
2843 					cp += len;
2844 				}
2845 			}
2846 		}
2847 
2848 		cp += strspn(cp, " \t");
2849 		if (*cp != '\n') {
2850 			lbuf[strlen(lbuf) - 1] = 0;
2851 			printf("%s is not a valid %s number.\n", lbuf,
2852 			    flags & DEC_SEC ? "sector" : "decimal");
2853 			continue;
2854 		}
2855 
2856 		if (acc >= minval && acc <= maxval)
2857 			return acc;
2858 		printf("%" PRId64 " is not between %" PRId64 " and %" PRId64 ".\n", acc, minval, maxval);
2859 	}
2860 }
2861 
2862 static int
2863 ptn_id(const char *prompt, int *extended)
2864 {
2865 	unsigned int acc = 0;
2866 	char *cp;
2867 
2868 	for (;; printf("%s is not a valid partition number.\n", lbuf)) {
2869 		printf("%s: [none] ", prompt);
2870 
2871 		if (!fgets(lbuf, LBUF, stdin))
2872 			errx(1, "EOF");
2873 		lbuf[strlen(lbuf)-1] = '\0';
2874 		cp = lbuf;
2875 
2876 		cp += strspn(cp, " \t");
2877 		*extended = 0;
2878 		if (*cp == 0)
2879 			return -1;
2880 
2881 		if (*cp == 'E' || *cp == 'e') {
2882 			cp++;
2883 			*extended = 1;
2884 		}
2885 
2886 		acc = strtoul(cp, &cp, 10);
2887 
2888 		cp += strspn(cp, " \t");
2889 		if (*cp != '\0')
2890 			continue;
2891 
2892 		if (*extended || acc < MBR_PART_COUNT)
2893 			return acc;
2894 	}
2895 }
2896 
2897 #ifdef BOOTSEL
2898 static void
2899 string(const char *prompt, int length, char *buf)
2900 {
2901 	int len;
2902 
2903 	for (;;) {
2904 		printf("%s: [%.*s] ", prompt, length, buf);
2905 
2906 		if (!fgets(lbuf, LBUF, stdin))
2907 			errx(1, "EOF");
2908 		len = strlen(lbuf);
2909 		if (len <= 1)
2910 			/* unchanged if just <enter> */
2911 			return;
2912 		/* now strip trailing spaces, <space><enter> deletes string */
2913 		do
2914 			lbuf[--len] = 0;
2915 		while (len != 0 && lbuf[len - 1] == ' ');
2916 		if (len < length)
2917 			break;
2918 		printf("'%s' is longer than %d characters.\n",
2919 		    lbuf, length - 1);
2920 	}
2921 	strncpy(buf, lbuf, length);
2922 }
2923 #endif
2924 
2925 static int
2926 type_match(const void *key, const void *item)
2927 {
2928 	const int *idp = key;
2929 	const struct mbr_ptype *ptr = item;
2930 
2931 	if (*idp < ptr->id)
2932 		return (-1);
2933 	if (*idp > ptr->id)
2934 		return (1);
2935 	return (0);
2936 }
2937 
2938 static const char *
2939 get_type(int type)
2940 {
2941 	struct mbr_ptype *ptr;
2942 
2943 	ptr = bsearch(&type, mbr_ptypes, KNOWN_SYSIDS,
2944 	    sizeof(mbr_ptypes[0]), type_match);
2945 	if (ptr == 0)
2946 		return ("unknown");
2947 	return (ptr->name);
2948 }
2949 
2950 static int
2951 read_gpt(daddr_t offset, struct gpt_hdr *gptp)
2952 {
2953 	char buf[512];
2954 	struct gpt_hdr *hdr = (void *)buf;
2955 	const char *tabletype = GPT_TYPE(offset);
2956 
2957 	if (read_disk(offset, buf) == -1) {
2958 		warn("Can't read %s GPT header", tabletype);
2959 		return -1;
2960 	}
2961 	(void)memcpy(gptp, buf, GPT_HDR_SIZE);
2962 
2963 	/* GPT CRC should be calculated with CRC field preset to zero */
2964 	hdr->hdr_crc_self = 0;
2965 
2966 	if (memcmp(gptp->hdr_sig, GPT_HDR_SIG, sizeof(gptp->hdr_sig))
2967 	    || gptp->hdr_lba_self != (uint64_t)offset
2968 	    || crc32(0, (void *)hdr, gptp->hdr_size) != gptp->hdr_crc_self) {
2969 		/* not a GPT */
2970 		(void)memset(gptp, 0, GPT_HDR_SIZE);
2971 	}
2972 
2973 	if (v_flag && gptp->hdr_size != 0) {
2974 		printf("Found %s GPT header CRC %"PRIu32" "
2975 		    "at sector %"PRIdaddr", backup at %"PRIdaddr"\n",
2976 		    tabletype, gptp->hdr_crc_self, offset, gptp->hdr_lba_alt);
2977 	}
2978 	return gptp->hdr_size;
2979 
2980 }
2981 
2982 static int
2983 delete_gpt(struct gpt_hdr *gptp)
2984 {
2985 	char buf[512];
2986 	struct gpt_hdr *hdr = (void *)buf;
2987 
2988 	if (gptp->hdr_size == 0)
2989 		return 0;
2990 
2991 	/* don't accidently overwrite something important */
2992 	if (gptp->hdr_lba_self != GPT_HDR_BLKNO &&
2993 	    gptp->hdr_lba_self != (uint64_t)disksectors - 1) {
2994 		warnx("given GPT header location doesn't seem correct");
2995 		return -1;
2996 	}
2997 
2998 	(void)memcpy(buf, gptp, GPT_HDR_SIZE);
2999 	/*
3000 	 * Don't really delete GPT, just "disable" it, so it can
3001 	 * be recovered later in case of mistake or something
3002 	 */
3003 	(void)memset(hdr->hdr_sig, 0, sizeof(gptp->hdr_sig));
3004 	if (write_disk(gptp->hdr_lba_self, hdr) == -1) {
3005 		warn("can't delete %s GPT header",
3006 		    GPT_TYPE(gptp->hdr_lba_self));
3007 		return -1;
3008 	}
3009 	(void)memset(gptp, 0, GPT_HDR_SIZE);
3010 	return 1;
3011 }
3012