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