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