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