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