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