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