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