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