fdisk.c revision 1.98 1 /* $NetBSD: fdisk.c,v 1.98 2006/03/17 15:53:46 rumble 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.98 2006/03/17 15:53:46 rumble 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)
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 if (head == 0 && sect == 0)
653 return;
654 printf("/%lu/%lu", head, sect + 1);
655 }
656
657 void
658 print_mbr_partition(struct mbr_sector *boot, int part,
659 daddr_t offset, daddr_t exoffset, int indent)
660 {
661 daddr_t start;
662 daddr_t size;
663 struct mbr_partition *partp = &boot->mbr_parts[part];
664 struct mbr_sector eboot;
665 int p;
666 static int dumped = 0;
667
668 if (partp->mbrp_type == 0 && v_flag < 2) {
669 printf("<UNUSED>\n");
670 return;
671 }
672
673 start = le32toh(partp->mbrp_start);
674 size = le32toh(partp->mbrp_size);
675 if (MBR_IS_EXTENDED(partp->mbrp_type))
676 start += exoffset;
677 else
678 start += offset;
679
680 printf("%s (sysid %d)\n", get_type(partp->mbrp_type), partp->mbrp_type);
681 #ifdef BOOTSEL
682 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC &&
683 boot->mbr_bootsel.mbrbs_nametab[part][0])
684 printf("%*s bootmenu: %s\n", indent, "",
685 boot->mbr_bootsel.mbrbs_nametab[part]);
686 #endif
687
688 printf("%*s start %"PRIdaddr", size %"PRIdaddr,
689 indent, "", start, size);
690 if (size != 0) {
691 printf(" (%u MB, Cyls ", SEC_TO_MB(size));
692 if (v_flag == 0 && le32toh(partp->mbrp_start) == dos_sectors)
693 pr_cyls(start - dos_sectors);
694 else
695 pr_cyls(start);
696 printf("-");
697 pr_cyls(start + size);
698 printf(")");
699 }
700
701 switch (partp->mbrp_flag) {
702 case 0:
703 break;
704 case MBR_PFLAG_ACTIVE:
705 printf(", Active");
706 break;
707 default:
708 printf(", flag 0x%x", partp->mbrp_flag);
709 break;
710 }
711 printf("\n");
712
713 if (v_flag) {
714 printf("%*s beg: cylinder %4d, head %3d, sector %2d\n",
715 indent, "",
716 MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
717 partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
718 printf("%*s end: cylinder %4d, head %3d, sector %2d\n",
719 indent, "",
720 MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
721 partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
722 }
723
724 if (!MBR_IS_EXTENDED(partp->mbrp_type) ||
725 (v_flag <= 2 && !ext.is_corrupt))
726 return;
727
728 /*
729 * Recursive dump extended table,
730 * This is read from the disk - so is wrong during editing.
731 * Just ensure we only show it once.
732 */
733 if (dumped)
734 return;
735
736 printf("%*s Extended partition table:\n", indent, "");
737 indent += 4;
738 if (read_s0(start, &eboot) == -1)
739 return;
740 for (p = 0; p < MBR_PART_COUNT; p++) {
741 printf("%*s%d: ", indent, "", p);
742 print_mbr_partition(&eboot, p, start,
743 exoffset ? exoffset : start, indent);
744 }
745
746 if (exoffset == 0)
747 dumped = 1;
748 }
749
750 int
751 read_boot(const char *name, void *buf, size_t len, int err_exit)
752 {
753 int bfd, ret;
754 struct stat st;
755
756 if (boot_path != NULL)
757 free(boot_path);
758 if (strchr(name, '/') == 0)
759 asprintf(&boot_path, "%s/%s", boot_dir, name);
760 else
761 boot_path = strdup(name);
762 if (boot_path == NULL)
763 err(1, "Malloc failed");
764
765 if ((bfd = open(boot_path, O_RDONLY)) < 0 || fstat(bfd, &st) == -1) {
766 warn("%s", boot_path);
767 goto fail;
768 }
769
770 if (st.st_size > (off_t)len) {
771 warnx("%s: bootcode too large", boot_path);
772 goto fail;
773 }
774 ret = st.st_size;
775 if (ret < 0x200) {
776 warnx("%s: bootcode too small", boot_path);
777 goto fail;
778 }
779 if (read(bfd, buf, len) != ret) {
780 warn("%s", boot_path);
781 goto fail;
782 }
783
784 /*
785 * Do some sanity checking here
786 */
787 if (((struct mbr_sector *)buf)->mbr_magic != LE_MBR_MAGIC) {
788 warnx("%s: invalid magic", boot_path);
789 goto fail;
790 }
791
792 close(bfd);
793 ret = (ret + 0x1ff) & ~0x1ff;
794 return ret;
795
796 fail:
797 close(bfd);
798 if (err_exit)
799 exit(1);
800 return 0;
801 }
802
803 void
804 init_sector0(int zappart)
805 {
806 int i;
807 int copy_size = MBR_PART_OFFSET;
808
809 #ifdef DEFAULT_BOOTCODE
810 if (bootsize == 0)
811 bootsize = read_boot(DEFAULT_BOOTCODE, bootcode,
812 sizeof bootcode, 1);
813 #endif
814 #ifdef BOOTSEL
815 if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
816 && bootcode[0].mbr_bootsel_magic == LE_MBR_BS_MAGIC)
817 copy_size = MBR_BS_OFFSET;
818 #endif
819
820 if (bootsize != 0) {
821 boot_installed = 1;
822 memcpy(&mboot, bootcode, copy_size);
823 }
824 mboot.mbr_magic = LE_MBR_MAGIC;
825
826 if (!zappart)
827 return;
828 for (i = 0; i < MBR_PART_COUNT; i++)
829 memset(&mboot.mbr_parts[i], 0, sizeof(mboot.mbr_parts[i]));
830 }
831
832 void
833 get_extended_ptn(void)
834 {
835 struct mbr_partition *mp;
836 struct mbr_sector *boot;
837 daddr_t offset;
838 struct mbr_sector *nptn;
839
840 /* find first (there should only be one) extended partition */
841 for (mp = mboot.mbr_parts; !MBR_IS_EXTENDED(mp->mbrp_type); mp++)
842 if (mp >= &mboot.mbr_parts[MBR_PART_COUNT])
843 return;
844
845 /*
846 * The extended partition should be structured as a linked list
847 * (even though it appears, at first glance, to be a tree).
848 */
849 ext.base = le32toh(mp->mbrp_start);
850 ext.limit = ext.base + le32toh(mp->mbrp_size);
851 ext.ptn_id = mp - mboot.mbr_parts;
852 for (offset = 0;; offset = le32toh(boot->mbr_parts[1].mbrp_start)) {
853 nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
854 if (nptn == NULL)
855 err(1, "Malloc failed");
856 ext.ptn = nptn;
857 boot = ext.ptn + ext.num_ptn;
858 if (read_s0(offset + ext.base, boot) == -1)
859 break;
860 /* expect p0 to be valid and p1 to be another extended ptn */
861 if (MBR_IS_EXTENDED(boot->mbr_parts[0].mbrp_type))
862 break;
863 if (boot->mbr_parts[1].mbrp_type != 0 &&
864 !MBR_IS_EXTENDED(boot->mbr_parts[1].mbrp_type))
865 break;
866 /* p2 and p3 should be unallocated */
867 if (boot->mbr_parts[2].mbrp_type != 0 ||
868 boot->mbr_parts[3].mbrp_type != 0)
869 break;
870 /* data ptn inside extended one */
871 if (boot->mbr_parts[0].mbrp_type != 0 &&
872 offset + le32toh(boot->mbr_parts[0].mbrp_start)
873 + le32toh(boot->mbr_parts[0].mbrp_size) > ext.limit)
874 break;
875
876 ext.num_ptn++;
877
878 if (boot->mbr_parts[1].mbrp_type == 0)
879 /* end of extended partition chain */
880 return;
881 /* must be in sector order */
882 if (offset >= le32toh(boot->mbr_parts[1].mbrp_start))
883 break;
884 }
885
886 warnx("Extended partition table is corrupt\n");
887 ext.is_corrupt = 1;
888 ext.num_ptn = 0;
889 }
890
891 #if (defined(__i386__) || defined(__x86_64__)) && !HAVE_NBTOOL_CONFIG_H
892 void
893 get_diskname(const char *fullname, char *diskname, size_t size)
894 {
895 const char *p, *p2;
896 size_t len;
897
898 p = strrchr(fullname, '/');
899 if (p == NULL)
900 p = fullname;
901 else
902 p++;
903
904 if (*p == 0) {
905 strlcpy(diskname, fullname, size);
906 return;
907 }
908
909 if (*p == 'r')
910 p++;
911
912 for (p2 = p; *p2 != 0; p2++)
913 if (isdigit((unsigned char)*p2))
914 break;
915 if (*p2 == 0) {
916 /* XXX invalid diskname? */
917 strlcpy(diskname, fullname, size);
918 return;
919 }
920 while (isdigit((unsigned char)*p2))
921 p2++;
922
923 len = p2 - p;
924 if (len > size) {
925 /* XXX */
926 strlcpy(diskname, fullname, size);
927 return;
928 }
929
930 memcpy(diskname, p, len);
931 diskname[len] = 0;
932 }
933
934 void
935 get_geometry(void)
936 {
937 int mib[2], i;
938 size_t len;
939 struct biosdisk_info *bip;
940 struct nativedisk_info *nip;
941 char diskname[8];
942
943 mib[0] = CTL_MACHDEP;
944 mib[1] = CPU_DISKINFO;
945 if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
946 goto out;
947 }
948 dl = (struct disklist *) malloc(len);
949 if (dl == NULL)
950 err(1, "Malloc failed");
951 if (sysctl(mib, 2, dl, &len, NULL, 0) < 0) {
952 free(dl);
953 dl = 0;
954 goto out;
955 }
956
957 get_diskname(disk, diskname, sizeof diskname);
958
959 for (i = 0; i < dl->dl_nnativedisks; i++) {
960 nip = &dl->dl_nativedisks[i];
961 if (strcmp(diskname, nip->ni_devname))
962 continue;
963 /*
964 * XXX listing possible matches is better. This is ok for
965 * now because the user has a chance to change it later.
966 * Also, if all the disks have the same parameters then we can
967 * just use them, we don't need to know which disk is which.
968 */
969 if (nip->ni_nmatches != 0) {
970 bip = &dl->dl_biosdisks[nip->ni_biosmatches[0]];
971 dos_cylinders = bip->bi_cyl;
972 dos_heads = bip->bi_head;
973 dos_sectors = bip->bi_sec;
974 if (bip->bi_lbasecs)
975 dos_disksectors = bip->bi_lbasecs;
976 return;
977 }
978 }
979 out:
980 /* Allright, allright, make a stupid guess.. */
981 intuit_translated_geometry();
982 }
983 #endif /* (defined(__i386__) || defined(__x86_64__)) && !HAVE_NBTOOL_CONFIG_H */
984
985 #ifdef BOOTSEL
986 daddr_t
987 get_default_boot(void)
988 {
989 unsigned int id;
990 int p;
991
992 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
993 /* default to first active partition */
994 return DEFAULT_ACTIVE;
995
996 if (mboot.mbr_bootsel.mbrbs_defkey == SCAN_ENTER)
997 return DEFAULT_ACTIVE;
998
999 id = mboot.mbr_bootsel.mbrbs_defkey;
1000
1001 /* 1+ => allocated partition id, F1+ => disk 0+ */
1002 if (id >= SCAN_F1)
1003 return id - SCAN_F1;
1004 id -= SCAN_1;
1005
1006 for (p = 0; p < MBR_PART_COUNT; p++) {
1007 if (mboot.mbr_parts[p].mbrp_type == 0)
1008 continue;
1009 if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
1010 continue;
1011 if (id-- == 0)
1012 return le32toh(mboot.mbr_parts[p].mbrp_start);
1013 }
1014
1015 for (p = 0; p < ext.num_ptn; p++) {
1016 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1017 continue;
1018 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1019 continue;
1020 if (id-- == 0)
1021 return ext_offset(p)
1022 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start);
1023 }
1024
1025 return DEFAULT_ACTIVE;
1026 }
1027
1028 void
1029 set_default_boot(daddr_t default_ptn)
1030 {
1031 int p;
1032 int key = SCAN_1;
1033
1034 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1035 /* sanity */
1036 return;
1037
1038 if (default_ptn == DEFAULT_ACTIVE) {
1039 mboot.mbr_bootsel.mbrbs_defkey = SCAN_ENTER;
1040 return;
1041 }
1042
1043 for (p = 0; p < MBR_PART_COUNT; p++) {
1044 if (mboot.mbr_parts[p].mbrp_type == 0)
1045 continue;
1046 if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
1047 continue;
1048 if (le32toh(mboot.mbr_parts[p].mbrp_start) == default_ptn) {
1049 mboot.mbr_bootsel.mbrbs_defkey = key;
1050 return;
1051 }
1052 key++;
1053 }
1054
1055 if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_EXTLBA) {
1056 for (p = 0; p < ext.num_ptn; p++) {
1057 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1058 continue;
1059 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1060 continue;
1061 if (le32toh(ext.ptn[p].mbr_parts[0].mbrp_start) +
1062 ext_offset(p) == default_ptn) {
1063 mboot.mbr_bootsel.mbrbs_defkey = key;
1064 return;
1065 }
1066 key++;
1067 }
1068 }
1069
1070 if (default_ptn < 8) {
1071 key = SCAN_F1;
1072 mboot.mbr_bootsel.mbrbs_defkey = key + default_ptn;
1073 return;
1074 }
1075
1076 /* Default to first active partition */
1077 mboot.mbr_bootsel.mbrbs_defkey = SCAN_ENTER;
1078 }
1079
1080 void
1081 install_bootsel(int needed)
1082 {
1083 struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
1084 int p;
1085 int ext13 = 0;
1086 const char *code;
1087
1088 needed |= MBR_BS_NEWMBR; /* need new bootsel code */
1089
1090 /* Work out which boot code we need for this configuration */
1091 for (p = 0; p < MBR_PART_COUNT; p++) {
1092 if (mboot.mbr_parts[p].mbrp_type == 0)
1093 continue;
1094 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1095 break;
1096 if (mbs->mbrbs_nametab[p][0] == 0)
1097 continue;
1098 needed |= MBR_BS_ACTIVE;
1099 if (le32toh(mboot.mbr_parts[p].mbrp_start) >= dos_totalsectors)
1100 ext13 = MBR_BS_EXTINT13;
1101 }
1102
1103 for (p = 0; p < ext.num_ptn; p++) {
1104 if (ext.ptn[p].mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1105 continue;
1106 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1107 continue;
1108 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[p][0] == 0)
1109 continue;
1110 needed |= MBR_BS_EXTLBA | MBR_BS_ACTIVE;
1111 }
1112
1113 if (B_flag)
1114 needed |= MBR_BS_ACTIVE;
1115
1116 /* Is the installed code good enough ? */
1117 if (!i_flag && (needed == 0 ||
1118 (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
1119 && (mbs->mbrbs_flags & needed) == needed))) {
1120 /* yes - just set flags */
1121 mbs->mbrbs_flags |= ext13;
1122 return;
1123 }
1124
1125 /* ok - we need to replace the bootcode */
1126
1127 if (f_flag && !(i_flag || B_flag)) {
1128 warnx("Installed bootfile doesn't support required options.");
1129 return;
1130 }
1131
1132 if (!f_flag && bootsize == 0 && !i_flag)
1133 /* Output an explanation for the 'update bootcode' prompt. */
1134 printf("\n%s\n",
1135 "Installed bootfile doesn't support required options.");
1136
1137 /* Were we told a specific file ? (which we have already read) */
1138 /* If so check that it supports what we need. */
1139 if (bootsize != 0 && needed != 0
1140 && (bootcode[0].mbr_bootsel_magic != LE_MBR_BS_MAGIC
1141 || ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed))) {
1142 /* No it doesn't... */
1143 if (f_flag)
1144 warnx("Bootfile %s doesn't support "
1145 "required bootsel options", boot_path );
1146 /* But install it anyway */
1147 else
1148 if (yesno("Bootfile %s doesn't support the required "
1149 "options,\ninstall default bootfile instead?",
1150 boot_path))
1151 bootsize = 0;
1152 }
1153
1154 if (bootsize == 0) {
1155 /* Get name of bootfile that supports the required facilities */
1156 code = DEFAULT_BOOTCODE;
1157 if (needed & MBR_BS_ACTIVE)
1158 code = DEFAULT_BOOTSELCODE;
1159 #ifdef DEFAULT_BOOTEXTCODE
1160 if (needed & MBR_BS_EXTLBA)
1161 code = DEFAULT_BOOTEXTCODE;
1162 #endif
1163
1164 bootsize = read_boot(code, bootcode, sizeof bootcode, 0);
1165 if (bootsize == 0)
1166 /* The old bootcode is better than no bootcode at all */
1167 return;
1168 if ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed)
1169 warnx("Default bootfile %s doesn't support required "
1170 "options. Got flags 0x%x, wanted 0x%x\n",
1171 boot_path, bootcode[0].mbr_bootsel.mbrbs_flags,
1172 needed);
1173 }
1174
1175 if (!f_flag && !yesno("Update the bootcode from %s?", boot_path))
1176 return;
1177
1178 init_sector0(0);
1179
1180 if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC)
1181 mbs->mbrbs_flags = bootcode[0].mbr_bootsel.mbrbs_flags | ext13;
1182 }
1183
1184 daddr_t
1185 configure_bootsel(daddr_t default_ptn)
1186 {
1187 struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
1188 int i, item, opt;
1189 int tmo;
1190 daddr_t *off;
1191 int num_bios_disks;
1192
1193 #if (defined(__i386__) || defined(__x86_64__)) && !HAVE_NBTOOL_CONFIG_H
1194 if (dl != NULL) {
1195 num_bios_disks = dl->dl_nbiosdisks;
1196 if (num_bios_disks > 8)
1197 num_bios_disks = 8;
1198 } else
1199 #endif
1200 num_bios_disks = 8;
1201
1202 printf("\nBoot selector configuration:\n");
1203
1204 /* The timeout value is in ticks, ~18.2 Hz. Avoid using floats.
1205 * Ticks are nearly 64k/3600 - so our long timers are sligtly out!
1206 * Newer bootcode always waits for 1 tick, so treats 0xffff
1207 * as wait forever.
1208 */
1209 tmo = le16toh(mbs->mbrbs_timeo);
1210 tmo = tmo == 0xffff ? -1 : (10 * tmo + 9) / 182;
1211 tmo = decimal("Timeout value (0 to 3600 seconds, -1 => never)",
1212 tmo, 0, -1, 3600);
1213 mbs->mbrbs_timeo = htole16(tmo == -1 ? 0xffff : (tmo * 182) / 10);
1214
1215 off = calloc(1 + MBR_PART_COUNT + ext.num_ptn + num_bios_disks, sizeof *off);
1216 if (off == NULL)
1217 err(1, "Malloc failed");
1218
1219 printf("Select the default boot option. Options are:\n\n");
1220 item = 0;
1221 opt = 0;
1222 off[opt] = DEFAULT_ACTIVE;
1223 printf("%d: The first active partition\n", opt);
1224 for (i = 0; i < MBR_PART_COUNT; i++) {
1225 if (mboot.mbr_parts[i].mbrp_type == 0)
1226 continue;
1227 if (mbs->mbrbs_nametab[i][0] == 0)
1228 continue;
1229 printf("%d: %s\n", ++opt, &mbs->mbrbs_nametab[i][0]);
1230 off[opt] = le32toh(mboot.mbr_parts[i].mbrp_start);
1231 if (off[opt] == default_ptn)
1232 item = opt;
1233 }
1234 if (mbs->mbrbs_flags & MBR_BS_EXTLBA) {
1235 for (i = 0; i < ext.num_ptn; i++) {
1236 if (ext.ptn[i].mbr_parts[0].mbrp_type == 0)
1237 continue;
1238 if (ext.ptn[i].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1239 continue;
1240 printf("%d: %s\n",
1241 ++opt, ext.ptn[i].mbr_bootsel.mbrbs_nametab[0]);
1242 off[opt] = ext_offset(i) +
1243 le32toh(ext.ptn[i].mbr_parts[0].mbrp_start);
1244 if (off[opt] == default_ptn)
1245 item = opt;
1246 }
1247 }
1248 for (i = 0; i < num_bios_disks; i++) {
1249 printf("%d: Harddisk %d\n", ++opt, i);
1250 off[opt] = i;
1251 if (i == default_ptn)
1252 item = opt;
1253 }
1254
1255 item = decimal("Default boot option", item, 0, 0, opt);
1256
1257 default_ptn = off[item];
1258 free(off);
1259 return default_ptn;
1260 }
1261 #endif /* BOOTSEL */
1262
1263
1264 /* Prerequisite: the disklabel parameters and master boot record must
1265 * have been read (i.e. dos_* and mboot are meaningful).
1266 * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
1267 * dos_cylindersectors to be consistent with what the
1268 * partition table is using, if we can find a geometry
1269 * which is consistent with all partition table entries.
1270 * We may get the number of cylinders slightly wrong (in
1271 * the conservative direction). The idea is to be able
1272 * to create a NetBSD partition on a disk we don't know
1273 * the translated geometry of.
1274 * This routine is only used for non-x86 systems or when we fail to
1275 * get the BIOS geometry from the kernel.
1276 */
1277 void
1278 intuit_translated_geometry(void)
1279 {
1280 int xcylinders = -1, xheads = -1, xsectors = -1, i, j;
1281 unsigned int c1, h1, s1, c2, h2, s2;
1282 unsigned long a1, a2;
1283 uint64_t num, denom;
1284
1285 /*
1286 * The physical parameters may be invalid as bios geometry.
1287 * If we cannot determine the actual bios geometry, we are
1288 * better off picking a likely 'faked' geometry than leaving
1289 * the invalid physical one.
1290 */
1291
1292 if (dos_cylinders > MAXCYL || dos_heads > MAXHEAD ||
1293 dos_sectors > MAXSECTOR) {
1294 h1 = MAXHEAD - 1;
1295 c1 = MAXCYL - 1;
1296 #if (defined(__i386__) || defined(__x86_64__)) && !HAVE_NBTOOL_CONFIG_H
1297 if (dl != NULL) {
1298 /* BIOS may use 256 heads or 1024 cylinders */
1299 for (i = 0; i < dl->dl_nbiosdisks; i++) {
1300 if (h1 < dl->dl_biosdisks[i].bi_head)
1301 h1 = dl->dl_biosdisks[i].bi_head;
1302 if (c1 < dl->dl_biosdisks[i].bi_cyl)
1303 c1 = dl->dl_biosdisks[i].bi_cyl;
1304 }
1305 }
1306 #endif
1307 dos_sectors = MAXSECTOR;
1308 dos_heads = h1;
1309 dos_cylinders = disklabel.d_secperunit / (MAXSECTOR * h1);
1310 if (dos_cylinders > c1)
1311 dos_cylinders = c1;
1312 }
1313
1314 /* Try to deduce the number of heads from two different mappings. */
1315 for (i = 0; i < MBR_PART_COUNT * 2 - 1; i++) {
1316 if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
1317 continue;
1318 a1 -= s1;
1319 for (j = i + 1; j < MBR_PART_COUNT * 2; j++) {
1320 if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
1321 continue;
1322 a2 -= s2;
1323 num = (uint64_t)h1 * a2 - (uint64_t)h2 * a1;
1324 denom = (uint64_t)c2 * a1 - (uint64_t)c1 * a2;
1325 if (denom != 0 && num % denom == 0) {
1326 xheads = num / denom;
1327 xsectors = a1 / (c1 * xheads + h1);
1328 break;
1329 }
1330 }
1331 if (xheads != -1)
1332 break;
1333 }
1334
1335 if (xheads == -1)
1336 return;
1337
1338 /* Estimate the number of cylinders. */
1339 xcylinders = disklabel.d_secperunit / xheads / xsectors;
1340 if (disklabel.d_secperunit > xcylinders * xheads * xsectors)
1341 xcylinders++;
1342
1343 /*
1344 * Now verify consistency with each of the partition table entries.
1345 * Be willing to shove cylinders up a little bit to make things work,
1346 * but translation mismatches are fatal.
1347 */
1348 for (i = 0; i < MBR_PART_COUNT * 2; i++) {
1349 if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
1350 continue;
1351 if (c1 >= MAXCYL - 2)
1352 continue;
1353 if (xsectors * (c1 * xheads + h1) + s1 != a1)
1354 return;
1355 }
1356
1357
1358 /* Everything checks out.
1359 * Reset the geometry to use for further calculations.
1360 * But cylinders cannot be > 1024.
1361 */
1362 if (xcylinders > MAXCYL)
1363 dos_cylinders = MAXCYL;
1364 else
1365 dos_cylinders = xcylinders;
1366 dos_heads = xheads;
1367 dos_sectors = xsectors;
1368 }
1369
1370 /*
1371 * For the purposes of intuit_translated_geometry(), treat the partition
1372 * table as a list of eight mapping between (cylinder, head, sector)
1373 * triplets and absolute sectors. Get the relevant geometry triplet and
1374 * absolute sectors for a given entry, or return -1 if it isn't present.
1375 * Note: for simplicity, the returned sector is 0-based.
1376 */
1377 int
1378 get_mapping(int i, unsigned int *cylinder, unsigned int *head, unsigned int *sector,
1379 unsigned long *absolute)
1380 {
1381 struct mbr_partition *part = &mboot.mbr_parts[i / 2];
1382
1383 if (part->mbrp_type == 0)
1384 return -1;
1385 if (i % 2 == 0) {
1386 *cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
1387 *head = part->mbrp_shd;
1388 *sector = MBR_PSECT(part->mbrp_ssect) - 1;
1389 *absolute = le32toh(part->mbrp_start);
1390 } else {
1391 *cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
1392 *head = part->mbrp_ehd;
1393 *sector = MBR_PSECT(part->mbrp_esect) - 1;
1394 *absolute = le32toh(part->mbrp_start)
1395 + le32toh(part->mbrp_size) - 1;
1396 }
1397 /* Sanity check the data against max values */
1398 if ((((*cylinder * MAXHEAD) + *head) * MAXSECTOR + *sector) < *absolute)
1399 /* cannot be a CHS mapping */
1400 return -1;
1401 return 0;
1402 }
1403
1404 static void
1405 delete_ptn(int part)
1406 {
1407 if (part == ext.ptn_id) {
1408 /* forget all about the extended partition */
1409 free(ext.ptn);
1410 memset(&ext, 0, sizeof ext);
1411 }
1412
1413 mboot.mbr_parts[part].mbrp_type = 0;
1414 }
1415
1416 static void
1417 delete_ext_ptn(int part)
1418 {
1419
1420 if (part == 0) {
1421 ext.ptn[0].mbr_parts[0].mbrp_type = 0;
1422 return;
1423 }
1424 ext.ptn[part - 1].mbr_parts[1] = ext.ptn[part].mbr_parts[1];
1425 memmove(&ext.ptn[part], &ext.ptn[part + 1],
1426 (ext.num_ptn - part - 1) * sizeof ext.ptn[0]);
1427 ext.num_ptn--;
1428 }
1429
1430 static int
1431 add_ext_ptn(daddr_t start, daddr_t size)
1432 {
1433 int part;
1434 struct mbr_partition *partp;
1435 struct mbr_sector *nptn;
1436
1437 nptn = realloc(ext.ptn, (ext.num_ptn + 1) * sizeof *ext.ptn);
1438 if (!nptn)
1439 err(1, "realloc");
1440 ext.ptn = nptn;
1441 for (part = 0; part < ext.num_ptn; part++)
1442 if (ext_offset(part) > start)
1443 break;
1444 /* insert before 'part' - make space... */
1445 memmove(&ext.ptn[part + 1], &ext.ptn[part],
1446 (ext.num_ptn - part) * sizeof ext.ptn[0]);
1447 memset(&ext.ptn[part], 0, sizeof ext.ptn[0]);
1448 ext.ptn[part].mbr_magic = LE_MBR_MAGIC;
1449 /* we will be 'part' */
1450 if (part == 0) {
1451 /* link us to 'next' */
1452 partp = &ext.ptn[0].mbr_parts[1];
1453 /* offset will be fixed by caller */
1454 partp->mbrp_size = htole32(
1455 le32toh(ext.ptn[1].mbr_parts[0].mbrp_start) +
1456 le32toh(ext.ptn[1].mbr_parts[0].mbrp_size));
1457 } else {
1458 /* link us to prev's next */
1459 partp = &ext.ptn[part - 1].mbr_parts[1];
1460 ext.ptn[part].mbr_parts[1] = *partp;
1461 /* and prev onto us */
1462 partp->mbrp_start = htole32(start - dos_sectors - ext.base);
1463 partp->mbrp_size = htole32(size + dos_sectors);
1464 }
1465 partp->mbrp_type = 5; /* as used by win98 */
1466 partp->mbrp_flag = 0;
1467 /* wallop in some CHS values - win98 doesn't saturate them */
1468 dos(le32toh(partp->mbrp_start),
1469 &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
1470 dos(le32toh(partp->mbrp_start) + le32toh(partp->mbrp_size) - 1,
1471 &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
1472 ext.num_ptn++;
1473
1474 return part;
1475 }
1476
1477 static const char *
1478 check_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1479 {
1480 int p;
1481 unsigned int p_s, p_e;
1482
1483 if (sysid != 0) {
1484 if (start < dos_sectors)
1485 return "Track zero is reserved for the BIOS";
1486 if (start + size > disksectors)
1487 return "Partition exceeds size of disk";
1488 for (p = 0; p < MBR_PART_COUNT; p++) {
1489 if (p == part || mboot.mbr_parts[p].mbrp_type == 0)
1490 continue;
1491 p_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1492 p_e = p_s + le32toh(mboot.mbr_parts[p].mbrp_size);
1493 if (start + size <= p_s || start >= p_e)
1494 continue;
1495 if (f_flag) {
1496 if (fix)
1497 delete_ptn(p);
1498 return 0;
1499 }
1500 return "Overlaps another partition";
1501 }
1502 }
1503
1504 /* Are we trying to create an extended partition */
1505 if (!MBR_IS_EXTENDED(mboot.mbr_parts[part].mbrp_type)) {
1506 /* this wasn't the extended partition */
1507 if (!MBR_IS_EXTENDED(sysid))
1508 return 0;
1509 /* making an extended partition */
1510 if (ext.base != 0) {
1511 if (!f_flag)
1512 return "There cannot be 2 extended partitions";
1513 if (fix)
1514 delete_ptn(ext.ptn_id);
1515 }
1516 if (fix) {
1517 /* allocate a new extended partition */
1518 ext.ptn = calloc(1, sizeof ext.ptn[0]);
1519 if (ext.ptn == NULL)
1520 err(1, "Malloc failed");
1521 ext.ptn[0].mbr_magic = LE_MBR_MAGIC;
1522 ext.ptn_id = part;
1523 ext.base = start;
1524 ext.limit = start + size;
1525 ext.num_ptn = 1;
1526 }
1527 return 0;
1528 }
1529
1530 /* Check we haven't cut space allocated to an extended ptn */
1531
1532 if (!MBR_IS_EXTENDED(sysid)) {
1533 /* no longer an extended partition */
1534 if (fix) {
1535 /* Kill all memory of the extended partitions */
1536 delete_ptn(part);
1537 return 0;
1538 }
1539 if (ext.num_ptn == 0 ||
1540 (ext.num_ptn == 1 && ext.ptn[0].mbr_parts[0].mbrp_type == 0))
1541 /* nothing in extended partition */
1542 return 0;
1543 if (f_flag)
1544 return 0;
1545 if (yesno("Do you really want to delete all the extended partitions?"))
1546 return 0;
1547 return "Extended partition busy";
1548 }
1549
1550 if (le32toh(mboot.mbr_parts[part].mbrp_start) != ext.base)
1551 /* maybe impossible, but an extra sanity check */
1552 return 0;
1553
1554 for (p = ext.num_ptn; --p >= 0;) {
1555 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1556 continue;
1557 p_s = ext_offset(p);
1558 p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1559 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1560 if (p_s >= start && p_e <= start + size)
1561 continue;
1562 if (!f_flag)
1563 return "Extended partition outside main partition";
1564 if (fix)
1565 delete_ext_ptn(p);
1566 }
1567
1568 if (fix && start != ext.base) {
1569 /* The internal offsets need to be fixed up */
1570 for (p = 0; p < ext.num_ptn - 1; p++)
1571 ext.ptn[p].mbr_parts[1].mbrp_start = htole32(
1572 le32toh(ext.ptn[p].mbr_parts[1].mbrp_start)
1573 + ext.base - start);
1574 /* and maybe an empty partition at the start */
1575 if (ext.ptn[0].mbr_parts[0].mbrp_type == 0) {
1576 if (le32toh(ext.ptn[0].mbr_parts[1].mbrp_start) == 0) {
1577 /* don't need the empty slot */
1578 memmove(&ext.ptn[0], &ext.ptn[1],
1579 (ext.num_ptn - 1) * sizeof ext.ptn[0]);
1580 ext.num_ptn--;
1581 }
1582 } else {
1583 /* must create an empty slot */
1584 add_ext_ptn(start, dos_sectors);
1585 ext.ptn[0].mbr_parts[1].mbrp_start = htole32(ext.base
1586 - start);
1587 }
1588 }
1589 if (fix) {
1590 ext.base = start;
1591 ext.limit = start + size;
1592 }
1593 return 0;
1594 }
1595
1596 static const char *
1597 check_ext_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1598 {
1599 int p;
1600 unsigned int p_s, p_e;
1601
1602 if (sysid == 0)
1603 return 0;
1604
1605 if (MBR_IS_EXTENDED(sysid))
1606 return "Nested extended partitions are not allowed";
1607
1608 /* allow one track at start for extended partition header */
1609 start -= dos_sectors;
1610 size += dos_sectors;
1611 if (start < ext.base || start + size > ext.limit)
1612 return "Outside bounds of extended partition";
1613
1614 if (f_flag && !fix)
1615 return 0;
1616
1617 for (p = ext.num_ptn; --p >= 0;) {
1618 if (p == part || ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1619 continue;
1620 p_s = ext_offset(p);
1621 p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1622 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1623 if (p == 0)
1624 p_s += le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1625 - dos_sectors;
1626 if (start < p_e && start + size > p_s) {
1627 if (!f_flag)
1628 return "Overlaps another extended partition";
1629 if (fix) {
1630 if (part == -1)
1631 delete_ext_ptn(p);
1632 else
1633 /* must not change numbering yet */
1634 ext.ptn[p].mbr_parts[0].mbrp_type = 0;
1635 }
1636 }
1637 }
1638 return 0;
1639 }
1640
1641 int
1642 change_part(int extended, int part, int sysid, daddr_t start, daddr_t size,
1643 char *bootmenu)
1644 {
1645 struct mbr_partition *partp;
1646 struct mbr_sector *boot;
1647 daddr_t offset;
1648 const char *e;
1649 int upart = part;
1650 int p;
1651 int fl;
1652 daddr_t n_s, n_e;
1653 const char *errtext;
1654 #ifdef BOOTSEL
1655 char tmp_bootmenu[MBR_PART_COUNT * (MBR_BS_PARTNAMESIZE + 1)];
1656 int bootmenu_len = (extended ? MBR_PART_COUNT : 1) * (MBR_BS_PARTNAMESIZE + 1);
1657 #endif
1658
1659 if (extended) {
1660 if (part != -1 && part < ext.num_ptn) {
1661 boot = &ext.ptn[part];
1662 partp = &boot->mbr_parts[0];
1663 offset = ext_offset(part);
1664 } else {
1665 part = -1;
1666 boot = 0;
1667 partp = 0;
1668 offset = 0;
1669 }
1670 upart = 0;
1671 e = "E";
1672 } else {
1673 boot = &mboot;
1674 partp = &boot->mbr_parts[part];
1675 offset = 0;
1676 e = "";
1677 }
1678
1679 if (!f_flag && part != -1) {
1680 printf("The data for partition %s%d is:\n", e, part);
1681 print_part(boot, upart, offset);
1682 }
1683
1684 #ifdef BOOTSEL
1685 if (bootmenu != NULL)
1686 strlcpy(tmp_bootmenu, bootmenu, bootmenu_len);
1687 else
1688 if (boot != NULL && boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
1689 strlcpy(tmp_bootmenu,
1690 boot->mbr_bootsel.mbrbs_nametab[upart],
1691 bootmenu_len);
1692 else
1693 tmp_bootmenu[0] = 0;
1694 #endif
1695
1696 if (!s_flag && partp != NULL) {
1697 /* values not specified, default to current ones */
1698 sysid = partp->mbrp_type;
1699 start = offset + le32toh(partp->mbrp_start);
1700 size = le32toh(partp->mbrp_size);
1701 }
1702
1703 /* creating a new partition, default to free space */
1704 if (!s_flag && sysid == 0 && extended) {
1705 /* non-extended partition */
1706 start = ext.base;
1707 for (p = 0; p < ext.num_ptn; p++) {
1708 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1709 continue;
1710 n_s = ext_offset(p);
1711 if (n_s > start + dos_sectors)
1712 break;
1713 start = ext_offset(p)
1714 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1715 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1716 }
1717 if (ext.limit - start <= dos_sectors) {
1718 printf("No space in extended partition\n");
1719 return 0;
1720 }
1721 start += dos_sectors;
1722 }
1723
1724 if (!s_flag && sysid == 0 && !extended) {
1725 /* same for non-extended partition */
1726 /* first see if old start is free */
1727 if (start < dos_sectors)
1728 start = 0;
1729 for (p = 0; start != 0 && p < MBR_PART_COUNT; p++) {
1730 if (mboot.mbr_parts[p].mbrp_type == 0)
1731 continue;
1732 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1733 if (start >= n_s &&
1734 start < n_s + le32toh(mboot.mbr_parts[p].mbrp_size))
1735 start = 0;
1736 }
1737 if (start == 0) {
1738 /* Look for first gap */
1739 start = dos_sectors;
1740 for (p = 0; p < MBR_PART_COUNT; p++) {
1741 if (mboot.mbr_parts[p].mbrp_type == 0)
1742 continue;
1743 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1744 n_e = n_s + le32toh(mboot.mbr_parts[p].mbrp_size);
1745 if (start >= n_s && start < n_e) {
1746 start = n_e;
1747 p = -1;
1748 }
1749 }
1750 if (start >= disksectors) {
1751 printf("No free space\n");
1752 return 0;
1753 }
1754 }
1755 }
1756
1757 if (!f_flag) {
1758 /* request new values from user */
1759 if (sysid == 0)
1760 sysid = 169;
1761 sysid = decimal("sysid", sysid, 0, 0, 255);
1762 if (sysid == 0 && !v_flag) {
1763 start = 0;
1764 size = 0;
1765 #ifdef BOOTSEL
1766 tmp_bootmenu[0] = 0;
1767 #endif
1768 } else {
1769 daddr_t old = start;
1770 daddr_t lim = extended ? ext.limit : disksectors;
1771 start = decimal("start", start,
1772 DEC_SEC | DEC_RND_0 | (extended ? DEC_RND : 0),
1773 extended ? ext.base : 0, lim);
1774 /* Adjust 'size' so that end doesn't move when 'start'
1775 * is only changed slightly.
1776 */
1777 if (size > start - old)
1778 size -= start - old;
1779 else
1780 size = 0;
1781 /* Find end of available space from this start point */
1782 if (extended) {
1783 for (p = 0; p < ext.num_ptn; p++) {
1784 if (p == part)
1785 continue;
1786 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1787 continue;
1788 n_s = ext_offset(p);
1789 if (n_s > start && n_s < lim)
1790 lim = n_s;
1791 if (start >= n_s && start < n_s
1792 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1793 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size)) {
1794 lim = start;
1795 break;
1796 }
1797 }
1798 } else {
1799 for (p = 0; p < MBR_PART_COUNT; p++) {
1800 if (p == part)
1801 continue;
1802 if (mboot.mbr_parts[p].mbrp_type == 0)
1803 continue;
1804 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1805 if (n_s > start && n_s < lim)
1806 lim = n_s;
1807 if (start >= n_s && start < n_s
1808 + le32toh(mboot.mbr_parts[p].mbrp_size)) {
1809 lim = start;
1810 break;
1811 }
1812 }
1813 }
1814 lim -= start;
1815 if (lim == 0) {
1816 printf("Start sector already allocated\n");
1817 return 0;
1818 }
1819 if (size == 0 || size > lim)
1820 size = lim;
1821 fl = DEC_SEC;
1822 if (start % dos_cylindersectors == dos_sectors)
1823 fl |= DEC_RND_DOWN;
1824 if (start == 2 * dos_sectors)
1825 fl |= DEC_RND_DOWN | DEC_RND_DOWN_2;
1826 size = decimal("size", size, fl, 0, lim);
1827 #ifdef BOOTSEL
1828 #ifndef DEFAULT_BOOTEXTCODE
1829 if (!extended)
1830 #endif
1831 string("bootmenu", bootmenu_len, tmp_bootmenu);
1832 #endif
1833 }
1834 }
1835
1836 /*
1837 * Before we write these away, we must verify that nothing
1838 * untoward has been requested.
1839 */
1840
1841 if (extended)
1842 errtext = check_ext_overlap(part, sysid, start, size, 0);
1843 else
1844 errtext = check_overlap(part, sysid, start, size, 0);
1845 if (errtext != NULL) {
1846 if (f_flag)
1847 errx(2, "%s\n", errtext);
1848 printf("%s\n", errtext);
1849 return 0;
1850 }
1851
1852 /*
1853 * Before proceeding, delete any overlapped partitions.
1854 * This can only happen if '-f' was supplied on the command line.
1855 * Just hope the caller knows what they are doing.
1856 * This also fixes the base of each extended partition if the
1857 * partition itself has moved.
1858 */
1859
1860 if (extended)
1861 errtext = check_ext_overlap(part, sysid, start, size, 1);
1862 else
1863 errtext = check_overlap(part, sysid, start, size, 1);
1864
1865 if (errtext)
1866 errx(1, "%s\n", errtext);
1867
1868 if (sysid == 0) {
1869 /* delete this partition - save info though */
1870 if (partp == NULL)
1871 /* must have been trying to create an extended ptn */
1872 return 0;
1873 if (start == 0 && size == 0)
1874 memset(partp, 0, sizeof *partp);
1875 #ifdef BOOTSEL
1876 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
1877 memset(boot->mbr_bootsel.mbrbs_nametab[upart], 0,
1878 sizeof boot->mbr_bootsel.mbrbs_nametab[0]);
1879 #endif
1880 if (extended)
1881 delete_ext_ptn(part);
1882 else
1883 delete_ptn(part);
1884 return 1;
1885 }
1886
1887
1888 if (extended) {
1889 if (part != -1)
1890 delete_ext_ptn(part);
1891 if (start == ext.base + dos_sectors)
1892 /* First one must have been free */
1893 part = 0;
1894 else
1895 part = add_ext_ptn(start, size);
1896
1897 /* These must be re-calculated because of the realloc */
1898 boot = &ext.ptn[part];
1899 partp = &boot->mbr_parts[0];
1900 offset = ext_offset(part);
1901 }
1902
1903 partp->mbrp_type = sysid;
1904 partp->mbrp_start = htole32( start - offset);
1905 partp->mbrp_size = htole32( size);
1906 dos(start, &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
1907 dos(start + size - 1,
1908 &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
1909 #ifdef BOOTSEL
1910 if (extended) {
1911 boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
1912 strncpy(boot->mbr_bootsel.mbrbs_nametab[upart], tmp_bootmenu,
1913 bootmenu_len);
1914 } else {
1915 /* We need to bootselect code installed in order to have
1916 * somewhere to safely write the menu tag.
1917 */
1918 if (boot->mbr_bootsel_magic != LE_MBR_BS_MAGIC) {
1919 if (yesno("The bootselect code is not installed, "
1920 "do you want to install it now?"))
1921 install_bootsel(MBR_BS_ACTIVE);
1922 }
1923 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
1924 strncpy(boot->mbr_bootsel.mbrbs_nametab[upart],
1925 tmp_bootmenu, bootmenu_len);
1926 }
1927 }
1928 #endif
1929
1930 if (v_flag && !f_flag && yesno("Explicitly specify beg/end address?")) {
1931 /* this really isn't a good idea.... */
1932 int tsector, tcylinder, thead;
1933
1934 tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
1935 thead = partp->mbrp_shd;
1936 tsector = MBR_PSECT(partp->mbrp_ssect);
1937 tcylinder = decimal("beginning cylinder",
1938 tcylinder, 0, 0, dos_cylinders - 1);
1939 thead = decimal("beginning head",
1940 thead, 0, 0, dos_heads - 1);
1941 tsector = decimal("beginning sector",
1942 tsector, 0, 1, dos_sectors);
1943 partp->mbrp_scyl = DOSCYL(tcylinder);
1944 partp->mbrp_shd = thead;
1945 partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
1946
1947 tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
1948 thead = partp->mbrp_ehd;
1949 tsector = MBR_PSECT(partp->mbrp_esect);
1950 tcylinder = decimal("ending cylinder",
1951 tcylinder, 0, 0, dos_cylinders - 1);
1952 thead = decimal("ending head",
1953 thead, 0, 0, dos_heads - 1);
1954 tsector = decimal("ending sector",
1955 tsector, 0, 1, dos_sectors);
1956 partp->mbrp_ecyl = DOSCYL(tcylinder);
1957 partp->mbrp_ehd = thead;
1958 partp->mbrp_esect = DOSSECT(tsector, tcylinder);
1959 }
1960
1961 /* If we had to mark an extended partition as deleted because
1962 * another request would have overlapped it, now is the time
1963 * to do the actual delete.
1964 */
1965 if (extended && f_flag) {
1966 for (p = ext.num_ptn; --p >= 0;)
1967 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1968 delete_ext_ptn(p);
1969 }
1970 return 1;
1971 }
1972
1973 void
1974 print_params(void)
1975 {
1976
1977 if (sh_flag) {
1978 printf("DISK=%s\n", disk);
1979 printf("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%"PRIdaddr"\n",
1980 cylinders, heads, sectors, disksectors);
1981 printf("BCYL=%d\nBHEAD=%d\nBSEC=%d\nBDLSIZE=%"PRIdaddr"\n",
1982 dos_cylinders, dos_heads, dos_sectors, dos_disksectors);
1983 printf("NUMEXTPTN=%d\n", ext.num_ptn);
1984 return;
1985 }
1986
1987 /* Not sh_flag */
1988 printf("Disk: %s\n", disk);
1989 printf("NetBSD disklabel disk geometry:\n");
1990 printf("cylinders: %d, heads: %d, sectors/track: %d "
1991 "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
1992 cylinders, heads, sectors, cylindersectors, disksectors);
1993 printf("BIOS disk geometry:\n");
1994 printf("cylinders: %d, heads: %d, sectors/track: %d "
1995 "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
1996 dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors,
1997 dos_disksectors);
1998 }
1999
2000 void
2001 change_active(int which)
2002 {
2003 struct mbr_partition *partp;
2004 int part;
2005 int active = MBR_PART_COUNT;
2006
2007 partp = &mboot.mbr_parts[0];
2008
2009 if (a_flag && which != -1)
2010 active = which;
2011 else {
2012 for (part = 0; part < MBR_PART_COUNT; part++)
2013 if (partp[part].mbrp_flag & MBR_PFLAG_ACTIVE)
2014 active = part;
2015 }
2016 if (!f_flag) {
2017 if (yesno("Do you want to change the active partition?")) {
2018 printf ("Choosing %d will make no partition active.\n",
2019 MBR_PART_COUNT);
2020 do {
2021 active = decimal("active partition",
2022 active, 0, 0, MBR_PART_COUNT);
2023 } while (!yesno("Are you happy with this choice?"));
2024 } else
2025 return;
2026 } else
2027 if (active != MBR_PART_COUNT)
2028 printf ("Making partition %d active.\n", active);
2029
2030 for (part = 0; part < MBR_PART_COUNT; part++)
2031 partp[part].mbrp_flag &= ~MBR_PFLAG_ACTIVE;
2032 if (active < MBR_PART_COUNT)
2033 partp[active].mbrp_flag |= MBR_PFLAG_ACTIVE;
2034 }
2035
2036 void
2037 get_params_to_use(void)
2038 {
2039 #if defined(__i386__) || defined(__x86_64__)
2040 struct biosdisk_info *bip;
2041 int i;
2042 #endif
2043
2044 if (b_flag) {
2045 dos_cylinders = b_cyl;
2046 dos_heads = b_head;
2047 dos_sectors = b_sec;
2048 return;
2049 }
2050
2051 print_params();
2052 if (!yesno("Do you want to change our idea of what BIOS thinks?"))
2053 return;
2054
2055 #if (defined(__i386__) || defined(__x86_64__)) && !HAVE_NBTOOL_CONFIG_H
2056 if (dl != NULL) {
2057 for (i = 0; i < dl->dl_nbiosdisks; i++) {
2058 if (i == 0)
2059 printf("\nGeometries of known disks:\n");
2060 bip = &dl->dl_biosdisks[i];
2061 printf("Disk %d: cylinders %u, heads %u, sectors %u"
2062 " (%"PRIdaddr" sectors, %dMB)\n",
2063 i, bip->bi_cyl, bip->bi_head, bip->bi_sec,
2064 bip->bi_lbasecs, SEC_TO_MB(bip->bi_lbasecs));
2065
2066 }
2067 printf("\n");
2068 }
2069 #endif
2070 do {
2071 dos_cylinders = decimal("BIOS's idea of #cylinders",
2072 dos_cylinders, 0, 0, MAXCYL);
2073 dos_heads = decimal("BIOS's idea of #heads",
2074 dos_heads, 0, 0, MAXHEAD);
2075 dos_sectors = decimal("BIOS's idea of #sectors",
2076 dos_sectors, 0, 1, MAXSECTOR);
2077 print_params();
2078 } while (!yesno("Are you happy with this choice?"));
2079 }
2080
2081
2082 /***********************************************\
2083 * Change real numbers into strange dos numbers *
2084 \***********************************************/
2085 void
2086 dos(int sector, unsigned char *cylinderp, unsigned char *headp,
2087 unsigned char *sectorp)
2088 {
2089 int cylinder, head;
2090
2091 cylinder = sector / dos_cylindersectors;
2092 sector -= cylinder * dos_cylindersectors;
2093
2094 head = sector / dos_sectors;
2095 sector -= head * dos_sectors;
2096 if (cylinder > 1023)
2097 cylinder = 1023;
2098
2099 *cylinderp = DOSCYL(cylinder);
2100 *headp = head;
2101 *sectorp = DOSSECT(sector + 1, cylinder);
2102 }
2103
2104 int
2105 open_disk(int update)
2106 {
2107 static char namebuf[MAXPATHLEN + 1];
2108
2109 #if HAVE_NBTOOL_CONFIG_H
2110 strlcpy(namebuf, disk_file, sizeof(namebuf));
2111 if ((fd = open(disk_file, update ? O_RDWR : O_RDONLY, 0)) == -1) {
2112 warn("%s", disk_file);
2113 return -1;
2114 }
2115 #else
2116 fd = opendisk(disk, update && disk_file == NULL ? O_RDWR : O_RDONLY,
2117 namebuf, sizeof(namebuf), 0);
2118 if (fd < 0) {
2119 if (errno == ENODEV)
2120 warnx("%s is not a character device", namebuf);
2121 else
2122 warn("%s", namebuf);
2123 return (-1);
2124 }
2125 #endif /* HAVE_NBTOOL_CONFIG_H */
2126 disk = namebuf;
2127 if (get_params() == -1) {
2128 close(fd);
2129 fd = -1;
2130 return (-1);
2131 }
2132 if (disk_file != NULL) {
2133 /* for testing: read/write data from a disk file */
2134 wfd = open(disk_file, update ? O_RDWR|O_CREAT : O_RDONLY, 0777);
2135 if (wfd == -1) {
2136 warn("%s", disk_file);
2137 close(fd);
2138 fd = -1;
2139 return -1;
2140 }
2141 } else
2142 wfd = fd;
2143 return (0);
2144 }
2145
2146 int
2147 read_disk(daddr_t sector, void *buf)
2148 {
2149
2150 if (*rfd == -1)
2151 errx(1, "read_disk(); fd == -1");
2152 if (lseek(*rfd, sector * (off_t)512, 0) == -1)
2153 return (-1);
2154 return (read(*rfd, buf, 512));
2155 }
2156
2157 int
2158 write_disk(daddr_t sector, void *buf)
2159 {
2160
2161 if (wfd == -1)
2162 errx(1, "write_disk(); wfd == -1");
2163 if (lseek(wfd, sector * (off_t)512, 0) == -1)
2164 return (-1);
2165 return (write(wfd, buf, 512));
2166 }
2167
2168 static void
2169 guess_geometry(daddr_t _sectors)
2170 {
2171 dos_sectors = MAXSECTOR;
2172 dos_heads = MAXHEAD - 1; /* some BIOS might use 256 */
2173 dos_cylinders = _sectors / (MAXSECTOR * (MAXHEAD - 1));
2174 if (dos_cylinders < 1)
2175 dos_cylinders = 1;
2176 else if (dos_cylinders > MAXCYL - 1)
2177 dos_cylinders = MAXCYL - 1;
2178 }
2179
2180 int
2181 get_params(void)
2182 {
2183 if (disk_type != NULL) {
2184 struct disklabel *tmplabel;
2185
2186 if ((tmplabel = getdiskbyname(disk_type)) == NULL) {
2187 warn("bad disktype");
2188 return (-1);
2189 }
2190 disklabel = *tmplabel;
2191 } else if (F_flag) {
2192 struct stat st;
2193 if (fstat(fd, &st) == -1) {
2194 warn("fstat");
2195 return (-1);
2196 }
2197 if (st.st_size % 512 != 0) {
2198 warnx("%s size (%lld) is not divisible "
2199 "by sector size (%d)", disk, (long long)st.st_size,
2200 512);
2201 }
2202 disklabel.d_secperunit = st.st_size / 512;
2203 guess_geometry(disklabel.d_secperunit);
2204 disklabel.d_ncylinders = dos_cylinders;
2205 disklabel.d_ntracks = dos_heads;
2206 disklabel.d_nsectors = dos_sectors;
2207 #if HAVE_NBTOOL_CONFIG_H
2208 } else {
2209 warnx("no disklabel specified");
2210 return -1;
2211 }
2212 #else
2213 } else if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
2214 warn("DIOCGDEFLABEL");
2215 if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
2216 warn("DIOCGDINFO");
2217 return (-1);
2218 }
2219 }
2220 #endif /* HAVE_NBTOOL_CONFIG_H */
2221 disksectors = disklabel.d_secperunit;
2222 cylinders = disklabel.d_ncylinders;
2223 heads = disklabel.d_ntracks;
2224 sectors = disklabel.d_nsectors;
2225
2226 /* pick up some defaults for the BIOS sizes */
2227 if (sectors <= MAXSECTOR) {
2228 dos_cylinders = cylinders;
2229 dos_heads = heads;
2230 dos_sectors = sectors;
2231 } else {
2232 /* guess - has to better than the above */
2233 guess_geometry(disksectors);
2234 }
2235 dos_disksectors = disksectors;
2236
2237 return (0);
2238 }
2239
2240 #ifdef BOOTSEL
2241 /*
2242 * Rather unfortunately the bootsel 'magic' number is at the end of the
2243 * the structure, and there is no checksum. So when other operating
2244 * systems install mbr code by only writing the length of their code they
2245 * can overwrite part of the structure but keeping the magic number intact.
2246 * This code attempts to empirically detect this problem.
2247 */
2248 static int
2249 validate_bootsel(struct mbr_bootsel *mbs)
2250 {
2251 unsigned int key = mbs->mbrbs_defkey;
2252 unsigned int tmo;
2253 int i;
2254
2255 if (v_flag)
2256 return 0;
2257
2258 /*
2259 * Check default key is sane
2260 * - this is the most likely field to be stuffed
2261 * 12 disks and 12 bootable partitions seems enough!
2262 * (the keymap decode starts falling apart at that point)
2263 */
2264 if (key != 0 && !(key == SCAN_ENTER
2265 || (key >= SCAN_1 && key < SCAN_1 + 12)
2266 || (key >= SCAN_F1 && key < SCAN_F1 + 12)))
2267 return 1;
2268
2269 /* Checking the flags will lead to breakage... */
2270
2271 /* Timeout value is expecyed to be a multiple of a second */
2272 tmo = htole16(mbs->mbrbs_timeo);
2273 if (tmo != 0 && tmo != 0xffff && tmo != (10 * tmo + 9) / 182 * 182 / 10)
2274 return 2;
2275
2276 /* Check the menu strings are printable */
2277 /* Unfortunately they aren't zero filled... */
2278 for (i = 0; i < sizeof(mbs->mbrbs_nametab); i++) {
2279 int c = (uint8_t)mbs->mbrbs_nametab[0][i];
2280 if (c == 0 || isprint(c))
2281 continue;
2282 return 3;
2283 }
2284
2285 return 0;
2286 }
2287 #endif
2288
2289 int
2290 read_s0(daddr_t offset, struct mbr_sector *boot)
2291 {
2292 const char *tabletype = offset ? "extended" : "primary";
2293 #ifdef BOOTSEL
2294 static int reported;
2295 #endif
2296
2297 if (read_disk(offset, boot) == -1) {
2298 warn("Can't read %s partition table", tabletype);
2299 return -1;
2300 }
2301 if (boot->mbr_magic != LE_MBR_MAGIC) {
2302 warnx("%s partition table invalid, "
2303 "no magic in sector %"PRIdaddr, tabletype, offset);
2304 return -1;
2305
2306 }
2307 #ifdef BOOTSEL
2308 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
2309 /* mbr_bootsel in new location */
2310 if (validate_bootsel(&boot->mbr_bootsel)) {
2311 warnx("removing corrupt bootsel information");
2312 boot->mbr_bootsel_magic = 0;
2313 }
2314 return 0;
2315 }
2316 if (boot->mbr_bootsel_magic != LE_MBR_MAGIC)
2317 return 0;
2318
2319 /* mbr_bootsel in old location */
2320 if (!reported)
2321 warnx("%s partition table: using old-style bootsel information",
2322 tabletype);
2323 reported = 1;
2324 if (validate_bootsel((void *)((uint8_t *)boot + MBR_BS_OFFSET + 4))) {
2325 warnx("%s bootsel information corrupt - ignoring", tabletype);
2326 return 0;
2327 }
2328 memmove((uint8_t *)boot + MBR_BS_OFFSET,
2329 (uint8_t *)boot + MBR_BS_OFFSET + 4,
2330 sizeof(struct mbr_bootsel));
2331 if ( ! (boot->mbr_bootsel.mbrbs_flags & MBR_BS_NEWMBR)) {
2332 /* old style default key */
2333 int id;
2334 /* F1..F4 => ptn 0..3, F5+ => disk 0+ */
2335 id = boot->mbr_bootsel.mbrbs_defkey;
2336 id -= SCAN_F1;
2337 if (id >= MBR_PART_COUNT)
2338 id -= MBR_PART_COUNT; /* Use number of disk */
2339 else if (mboot.mbr_parts[id].mbrp_type != 0)
2340 id = le32toh(boot->mbr_parts[id].mbrp_start);
2341 else
2342 id = DEFAULT_ACTIVE;
2343 boot->mbr_bootsel.mbrbs_defkey = id;
2344 }
2345 boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
2346 /* highlight that new bootsel code is necessary */
2347 boot->mbr_bootsel.mbrbs_flags &= ~MBR_BS_NEWMBR;
2348 #endif /* BOOTSEL */
2349 return 0;
2350 }
2351
2352 int
2353 write_mbr(void)
2354 {
2355 int flag, i;
2356 daddr_t offset;
2357 int rval = -1;
2358
2359 /*
2360 * write enable label sector before write (if necessary),
2361 * disable after writing.
2362 * needed if the disklabel protected area also protects
2363 * sector 0. (e.g. empty disk)
2364 */
2365 flag = 1;
2366 #if !HAVE_NBTOOL_CONFIG_H
2367 if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2368 warn("DIOCWLABEL");
2369 #endif /* HAVE_NBTOOL_CONFIG_H */
2370 if (write_disk(0, &mboot) == -1) {
2371 warn("Can't write fdisk partition table");
2372 goto protect_label;
2373 }
2374 if (boot_installed)
2375 for (i = bootsize; (i -= 0x200) > 0;)
2376 if (write_disk(i / 0x200, &bootcode[i / 0x200]) == -1) {
2377 warn("Can't write bootcode");
2378 goto protect_label;
2379 }
2380 for (offset = 0, i = 0; i < ext.num_ptn; i++) {
2381 if (write_disk(ext.base + offset, ext.ptn + i) == -1) {
2382 warn("Can't write %dth extended partition", i);
2383 goto protect_label;
2384 }
2385 offset = le32toh(ext.ptn[i].mbr_parts[1].mbrp_start);
2386 }
2387 rval = 0;
2388 protect_label:
2389 #if !HAVE_NBTOOL_CONFIG_H
2390 flag = 0;
2391 if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2392 warn("DIOCWLABEL");
2393 #endif /* HAVE_NBTOOL_CONFIG_H */
2394 return rval;
2395 }
2396
2397 int
2398 yesno(const char *str, ...)
2399 {
2400 int ch, first;
2401 va_list ap;
2402
2403 va_start(ap, str);
2404
2405 vprintf(str, ap);
2406 printf(" [n] ");
2407
2408 first = ch = getchar();
2409 while (ch != '\n' && ch != EOF)
2410 ch = getchar();
2411 if (ch == EOF)
2412 errx(1, "EOF");
2413 return (first == 'y' || first == 'Y');
2414 }
2415
2416 int
2417 decimal(const char *prompt, int dflt, int flags, int minval, int maxval)
2418 {
2419 int acc = 0;
2420 char *cp;
2421 char ch;
2422
2423 for (;;) {
2424 if (flags & DEC_SEC) {
2425 printf("%s: [%d..%dcyl default: %d, %dcyl, %uMB] ",
2426 prompt, SEC_TO_CYL(minval), SEC_TO_CYL(maxval),
2427 dflt, SEC_TO_CYL(dflt), SEC_TO_MB(dflt));
2428 } else
2429 printf("%s: [%d..%d default: %d] ",
2430 prompt, minval, maxval, dflt);
2431
2432 if (!fgets(lbuf, LBUF, stdin))
2433 errx(1, "EOF");
2434 lbuf[strlen(lbuf)-1] = '\0';
2435 cp = lbuf;
2436
2437 cp += strspn(cp, " \t");
2438 if (*cp == '\0')
2439 return dflt;
2440
2441 if (cp[0] == '$' && cp[1] == 0)
2442 return maxval;
2443
2444 if (isdigit((unsigned char)*cp) || *cp == '-') {
2445 acc = strtol(lbuf, &cp, 10);
2446 if (flags & DEC_SEC) {
2447 ch = *cp;
2448 if (ch == 'g' || ch == 'G') {
2449 acc *= 1024;
2450 ch = 'm';
2451 }
2452 if (ch == 'm' || ch == 'M') {
2453 acc *= SEC_IN_1M;
2454 /* round to whole number of cylinders */
2455 acc += dos_cylindersectors / 2;
2456 acc /= dos_cylindersectors;
2457 ch = 'c';
2458 }
2459 if (ch == 'c' || ch == 'C') {
2460 cp++;
2461 acc *= dos_cylindersectors;
2462 /* adjustments for cylinder boundary */
2463 if (acc == 0 && flags & DEC_RND_0)
2464 acc += dos_sectors;
2465 if (flags & DEC_RND)
2466 acc += dos_sectors;
2467 if (flags & DEC_RND_DOWN)
2468 acc -= dos_sectors;
2469 if (flags & DEC_RND_DOWN_2)
2470 acc -= dos_sectors;
2471 }
2472 }
2473 }
2474
2475 cp += strspn(cp, " \t");
2476 if (*cp != '\0') {
2477 printf("%s is not a valid %s number.\n", lbuf,
2478 flags & DEC_SEC ? "sector" : "decimal");
2479 continue;
2480 }
2481
2482 if (acc >= minval && acc <= maxval)
2483 return acc;
2484 printf("%d is not between %d and %d.\n", acc, minval, maxval);
2485 }
2486 }
2487
2488 int
2489 ptn_id(const char *prompt, int *extended)
2490 {
2491 unsigned int acc = 0;
2492 char *cp;
2493
2494 for (;; printf("%s is not a valid partition number.\n", lbuf)) {
2495 printf("%s: [none] ", prompt);
2496
2497 if (!fgets(lbuf, LBUF, stdin))
2498 errx(1, "EOF");
2499 lbuf[strlen(lbuf)-1] = '\0';
2500 cp = lbuf;
2501
2502 cp += strspn(cp, " \t");
2503 *extended = 0;
2504 if (*cp == 0)
2505 return -1;
2506
2507 if (*cp == 'E' || *cp == 'e') {
2508 cp++;
2509 *extended = 1;
2510 }
2511
2512 acc = strtoul(cp, &cp, 10);
2513
2514 cp += strspn(cp, " \t");
2515 if (*cp != '\0')
2516 continue;
2517
2518 if (*extended || acc < MBR_PART_COUNT)
2519 return acc;
2520 }
2521 }
2522
2523 #ifdef BOOTSEL
2524 void
2525 string(const char *prompt, int length, char *buf)
2526 {
2527 int len;
2528
2529 for (;;) {
2530 printf("%s: [%.*s] ", prompt, length, buf);
2531
2532 if (!fgets(lbuf, LBUF, stdin))
2533 errx(1, "EOF");
2534 len = strlen(lbuf);
2535 if (len <= 1)
2536 /* unchanged if just <enter> */
2537 return;
2538 /* now strip trailing spaces, <space><enter> deletes string */
2539 do
2540 lbuf[--len] = 0;
2541 while (len != 0 && lbuf[len - 1] == ' ');
2542 if (len < length)
2543 break;
2544 printf("'%s' is longer than %d characters.\n",
2545 lbuf, length - 1);
2546 }
2547 strncpy(buf, lbuf, length);
2548 }
2549 #endif
2550
2551 int
2552 type_match(const void *key, const void *item)
2553 {
2554 const int *idp = key;
2555 const struct mbr_ptype *ptr = item;
2556
2557 if (*idp < ptr->id)
2558 return (-1);
2559 if (*idp > ptr->id)
2560 return (1);
2561 return (0);
2562 }
2563
2564 const char *
2565 get_type(int type)
2566 {
2567 struct mbr_ptype *ptr;
2568
2569 ptr = bsearch(&type, mbr_ptypes, KNOWN_SYSIDS,
2570 sizeof(mbr_ptypes[0]), type_match);
2571 if (ptr == 0)
2572 return ("unknown");
2573 return (ptr->name);
2574 }
2575