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