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