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