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