fdisk.c revision 187246
1/* 2 * Mach Operating System 3 * Copyright (c) 1992 Carnegie Mellon University 4 * All Rights Reserved. 5 * 6 * Permission to use, copy, modify and distribute this software and its 7 * documentation is hereby granted, provided that both the copyright 8 * notice and this permission notice appear in all copies of the 9 * software, derivative works or modified versions, and any portions 10 * thereof, and that both notices appear in supporting documentation. 11 * 12 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 13 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR 14 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. 15 * 16 * Carnegie Mellon requests users of this software to return to 17 * 18 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU 19 * School of Computer Science 20 * Carnegie Mellon University 21 * Pittsburgh PA 15213-3890 22 * 23 * any improvements or extensions that they make and grant Carnegie Mellon 24 * the rights to redistribute these changes. 25 */ 26 27#include <sys/cdefs.h> 28__FBSDID("$FreeBSD: head/sbin/fdisk/fdisk.c 187246 2009-01-14 21:31:09Z luigi $"); 29 30#include <sys/disk.h> 31#include <sys/disklabel.h> 32#include <sys/diskmbr.h> 33#include <sys/endian.h> 34#include <sys/param.h> 35#include <sys/stat.h> 36#include <sys/mount.h> 37#include <ctype.h> 38#include <fcntl.h> 39#include <err.h> 40#include <errno.h> 41#include <libgeom.h> 42#include <paths.h> 43#include <regex.h> 44#include <stdint.h> 45#include <stdio.h> 46#include <stdlib.h> 47#include <string.h> 48#include <unistd.h> 49 50int iotest; 51 52#define LBUF 100 53static char lbuf[LBUF]; 54 55/* 56 * 57 * Ported to 386bsd by Julian Elischer Thu Oct 15 20:26:46 PDT 1992 58 * 59 * 14-Dec-89 Robert Baron (rvb) at Carnegie-Mellon University 60 * Copyright (c) 1989 Robert. V. Baron 61 * Created. 62 */ 63 64#define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp 65 66#define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs) 67 68#define MAX_SEC_SIZE 2048 /* maximum section size that is supported */ 69#define MIN_SEC_SIZE 512 /* the sector size to start sensing at */ 70static int secsize = 0; /* the sensed sector size */ 71 72static char *disk; 73 74static int cyls, sectors, heads, cylsecs, disksecs; 75 76struct mboot { 77 unsigned char *bootinst; /* boot code */ 78 off_t bootinst_size; 79 struct dos_partition parts[NDOSPART]; 80}; 81 82static struct mboot mboot; 83static int fd; 84 85#define ACTIVE 0x80 86 87static uint dos_cyls; 88static uint dos_heads; 89static uint dos_sectors; 90static uint dos_cylsecs; 91 92#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0)) 93#define DOSCYL(c) (c & 0xff) 94 95#define MAX_ARGS 10 96 97static int current_line_number; 98 99static int geom_processed = 0; 100static int part_processed = 0; 101static int active_processed = 0; 102 103typedef struct cmd { 104 char cmd; 105 int n_args; 106 struct arg { 107 char argtype; 108 int arg_val; 109 } args[MAX_ARGS]; 110} CMD; 111 112static int B_flag = 0; /* replace boot code */ 113static int I_flag = 0; /* use entire disk for FreeBSD */ 114static int a_flag = 0; /* set active partition */ 115static char *b_flag = NULL; /* path to boot code */ 116static int i_flag = 0; /* replace partition data */ 117static int q_flag = 0; /* Be quiet */ 118static int u_flag = 0; /* update partition data */ 119static int s_flag = 0; /* Print a summary and exit */ 120static int t_flag = 0; /* test only */ 121static char *f_flag = NULL; /* Read config info from file */ 122static int v_flag = 0; /* Be verbose */ 123static int print_config_flag = 0; 124 125/* 126 * A list of partition types, probably outdated. 127 */ 128static const char *const part_types[256] = { 129 [0x00] = "unused", 130 [0x01] = "Primary DOS with 12 bit FAT", 131 [0x02] = "XENIX / file system", 132 [0x03] = "XENIX /usr file system", 133 [0x04] = "Primary DOS with 16 bit FAT (< 32MB)", 134 [0x05] = "Extended DOS", 135 [0x06] = "Primary 'big' DOS (>= 32MB)", 136 [0x07] = "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX", 137 [0x08] = "AIX file system or SplitDrive", 138 [0x09] = "AIX boot partition or Coherent", 139 [0x0A] = "OS/2 Boot Manager, OPUS or Coherent swap", 140 [0x0B] = "DOS or Windows 95 with 32 bit FAT", 141 [0x0C] = "DOS or Windows 95 with 32 bit FAT (LBA)", 142 [0x0E] = "Primary 'big' DOS (>= 32MB, LBA)", 143 [0x0F] = "Extended DOS (LBA)", 144 [0x10] = "OPUS", 145 [0x11] = "OS/2 BM: hidden DOS with 12-bit FAT", 146 [0x12] = "Compaq diagnostics", 147 [0x14] = "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)", 148 [0x16] = "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)", 149 [0x17] = "OS/2 BM: hidden IFS (e.g. HPFS)", 150 [0x18] = "AST Windows swapfile", 151 [0x24] = "NEC DOS", 152 [0x3C] = "PartitionMagic recovery", 153 [0x39] = "plan9", 154 [0x40] = "VENIX 286", 155 [0x41] = "Linux/MINIX (sharing disk with DRDOS)", 156 [0x42] = "SFS or Linux swap (sharing disk with DRDOS)", 157 [0x43] = "Linux native (sharing disk with DRDOS)", 158 [0x4D] = "QNX 4.2 Primary", 159 [0x4E] = "QNX 4.2 Secondary", 160 [0x4F] = "QNX 4.2 Tertiary", 161 [0x50] = "DM (disk manager)", 162 [0x51] = "DM6 Aux1 (or Novell)", 163 [0x52] = "CP/M or Microport SysV/AT", 164 [0x53] = "DM6 Aux3", 165 [0x54] = "DM6", 166 [0x55] = "EZ-Drive (disk manager)", 167 [0x56] = "Golden Bow (disk manager)", 168 [0x5c] = "Priam Edisk (disk manager)", /* according to S. Widlake */ 169 [0x61] = "SpeedStor", 170 [0x63] = "System V/386 (such as ISC UNIX), GNU HURD or Mach", 171 [0x64] = "Novell Netware/286 2.xx", 172 [0x65] = "Novell Netware/386 3.xx", 173 [0x70] = "DiskSecure Multi-Boot", 174 [0x75] = "PCIX", 175 [0x77] = "QNX4.x", 176 [0x78] = "QNX4.x 2nd part", 177 [0x79] = "QNX4.x 3rd part", 178 [0x80] = "Minix until 1.4a", 179 [0x81] = "Minix since 1.4b, early Linux partition or Mitac disk manager", 180 [0x82] = "Linux swap or Solaris x86", 181 [0x83] = "Linux native", 182 [0x84] = "OS/2 hidden C: drive", 183 [0x85] = "Linux extended", 184 [0x86] = "NTFS volume set??", 185 [0x87] = "NTFS volume set??", 186 [0x93] = "Amoeba file system", 187 [0x94] = "Amoeba bad block table", 188 [0x9F] = "BSD/OS", 189 [0xA0] = "Suspend to Disk", 190 [0xA5] = "FreeBSD/NetBSD/386BSD", 191 [0xA6] = "OpenBSD", 192 [0xA7] = "NeXTSTEP", 193 [0xA9] = "NetBSD", 194 [0xAC] = "IBM JFS", 195 [0xAF] = "HFS+", 196 [0xB7] = "BSDI BSD/386 file system", 197 [0xB8] = "BSDI BSD/386 swap", 198 [0xBE] = "Solaris x86 boot", 199 [0xBF] = "Solaris x86 (new)", 200 [0xC1] = "DRDOS/sec with 12-bit FAT", 201 [0xC4] = "DRDOS/sec with 16-bit FAT (< 32MB)", 202 [0xC6] = "DRDOS/sec with 16-bit FAT (>= 32MB)", 203 [0xC7] = "Syrinx", 204 [0xDB] = "CP/M, Concurrent CP/M, Concurrent DOS or CTOS", 205 [0xE1] = "DOS access or SpeedStor with 12-bit FAT extended partition", 206 [0xE3] = "DOS R/O or SpeedStor", 207 [0xE4] = "SpeedStor with 16-bit FAT extended partition < 1024 cyl.", 208 [0xEB] = "BeOS file system", 209 [0xEE] = "EFI GPT", 210 [0xEF] = "EFI System Partition", 211 [0xF1] = "SpeedStor", 212 [0xF2] = "DOS 3.3+ Secondary", 213 [0xF4] = "SpeedStor large partition", 214 [0xFE] = "SpeedStor >1024 cyl. or LANstep", 215 [0xFF] = "Xenix bad blocks table", 216}; 217 218static const char * 219get_type(int t) 220{ 221 const char *ret; 222 223 ret = (t >= 0 && t <= 255) ? part_types[t] : NULL; 224 return ret ? ret : "unknown"; 225} 226 227 228static void print_s0(void); 229static void print_part(const struct dos_partition *); 230static void init_sector0(unsigned long start); 231static void init_boot(void); 232static void change_part(int i); 233static void print_params(void); 234static void change_active(int which); 235static void change_code(void); 236static void get_params_to_use(void); 237static char *get_rootdisk(void); 238static void dos(struct dos_partition *partp); 239static int open_disk(int flag); 240static ssize_t read_disk(off_t sector, void *buf); 241static int write_disk(off_t sector, void *buf); 242static int get_params(void); 243static int read_s0(void); 244static int write_s0(void); 245static int ok(const char *str); 246static int decimal(const char *str, int *num, int deflt); 247static int read_config(char *config_file); 248static void reset_boot(void); 249static int sanitize_partition(struct dos_partition *); 250static void usage(void); 251 252int 253main(int argc, char *argv[]) 254{ 255 int c, i; 256 int partition = -1; 257 struct dos_partition *partp; 258 259 while ((c = getopt(argc, argv, "BIab:f:ipqstuv1234")) != -1) 260 switch (c) { 261 case 'B': 262 B_flag = 1; 263 break; 264 case 'I': 265 I_flag = 1; 266 break; 267 case 'a': 268 a_flag = 1; 269 break; 270 case 'b': 271 b_flag = optarg; 272 break; 273 case 'f': 274 f_flag = optarg; 275 break; 276 case 'i': 277 i_flag = 1; 278 break; 279 case 'p': 280 print_config_flag = 1; 281 break; 282 case 'q': 283 q_flag = 1; 284 break; 285 case 's': 286 s_flag = 1; 287 break; 288 case 't': 289 t_flag = 1; 290 break; 291 case 'u': 292 u_flag = 1; 293 break; 294 case 'v': 295 v_flag = 1; 296 break; 297 case '1': 298 case '2': 299 case '3': 300 case '4': 301 partition = c - '0'; 302 break; 303 default: 304 usage(); 305 } 306 if (f_flag || i_flag) 307 u_flag = 1; 308 if (t_flag) 309 v_flag = 1; 310 argc -= optind; 311 argv += optind; 312 313 if (argc == 0) { 314 disk = get_rootdisk(); 315 } else { 316 disk = g_device_path(argv[0]); 317 if (disk == NULL) 318 err(1, "unable to get correct path for %s", argv[0]); 319 } 320 if (open_disk(u_flag) < 0) 321 err(1, "cannot open disk %s", disk); 322 323 /* (abu)use mboot.bootinst to probe for the sector size */ 324 if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL) 325 err(1, "cannot allocate buffer to determine disk sector size"); 326 if (read_disk(0, mboot.bootinst) == -1) 327 errx(1, "could not detect sector size"); 328 free(mboot.bootinst); 329 mboot.bootinst = NULL; 330 331 if (print_config_flag) { 332 if (read_s0()) 333 err(1, "read_s0"); 334 335 printf("# %s\n", disk); 336 printf("g c%d h%d s%d\n", dos_cyls, dos_heads, dos_sectors); 337 338 for (i = 0; i < NDOSPART; i++) { 339 partp = &mboot.parts[i]; 340 341 if (partp->dp_start == 0 && partp->dp_size == 0) 342 continue; 343 344 printf("p %d 0x%02x %lu %lu\n", i + 1, partp->dp_typ, 345 (u_long)partp->dp_start, (u_long)partp->dp_size); 346 347 /* Fill flags for the partition. */ 348 if (partp->dp_flag & 0x80) 349 printf("a %d\n", i + 1); 350 } 351 exit(0); 352 } 353 if (s_flag) { 354 if (read_s0()) 355 err(1, "read_s0"); 356 printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads, 357 dos_sectors); 358 printf("Part %11s %11s Type Flags\n", "Start", "Size"); 359 for (i = 0; i < NDOSPART; i++) { 360 partp = &mboot.parts[i]; 361 if (partp->dp_start == 0 && partp->dp_size == 0) 362 continue; 363 printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1, 364 (u_long) partp->dp_start, 365 (u_long) partp->dp_size, partp->dp_typ, 366 partp->dp_flag); 367 } 368 exit(0); 369 } 370 371 printf("******* Working on device %s *******\n",disk); 372 373 if (I_flag) { 374 read_s0(); 375 reset_boot(); 376 partp = &mboot.parts[0]; 377 partp->dp_typ = DOSPTYP_386BSD; 378 partp->dp_flag = ACTIVE; 379 partp->dp_start = dos_sectors; 380 partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - 381 dos_sectors; 382 dos(partp); 383 if (v_flag) 384 print_s0(); 385 if (!t_flag) 386 write_s0(); 387 exit(0); 388 } 389 if (f_flag) { 390 if (read_s0() || i_flag) 391 reset_boot(); 392 if (!read_config(f_flag)) 393 exit(1); 394 if (v_flag) 395 print_s0(); 396 if (!t_flag) 397 write_s0(); 398 } else { 399 if(u_flag) 400 get_params_to_use(); 401 else 402 print_params(); 403 404 if (read_s0()) 405 init_sector0(dos_sectors); 406 407 printf("Media sector size is %d\n", secsize); 408 printf("Warning: BIOS sector numbering starts with sector 1\n"); 409 printf("Information from DOS bootblock is:\n"); 410 if (partition == -1) 411 for (i = 1; i <= NDOSPART; i++) 412 change_part(i); 413 else 414 change_part(partition); 415 416 if (u_flag || a_flag) 417 change_active(partition); 418 419 if (B_flag) 420 change_code(); 421 422 if (u_flag || a_flag || B_flag) { 423 if (!t_flag) { 424 printf("\nWe haven't changed the partition table yet. "); 425 printf("This is your last chance.\n"); 426 } 427 print_s0(); 428 if (!t_flag) { 429 if (ok("Should we write new partition table?")) 430 write_s0(); 431 } else { 432 printf("\n-t flag specified -- partition table not written.\n"); 433 } 434 } 435 } 436 437 exit(0); 438} 439 440static void 441usage() 442{ 443 fprintf(stderr, "%s%s", 444 "usage: fdisk [-BIaipqstu] [-b bootcode] [-1234] [disk]\n", 445 " fdisk -f configfile [-itv] [disk]\n"); 446 exit(1); 447} 448 449static void 450print_s0(void) 451{ 452 int i; 453 454 print_params(); 455 printf("Information from DOS bootblock is:\n"); 456 for (i = 1; i <= NDOSPART; i++) { 457 printf("%d: ", i); 458 print_part(&mboot.parts[i - 1]); 459 } 460} 461 462static struct dos_partition mtpart; 463 464static void 465print_part(const struct dos_partition *partp) 466{ 467 u_int64_t part_mb; 468 469 if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) { 470 printf("<UNUSED>\n"); 471 return; 472 } 473 /* 474 * Be careful not to overflow. 475 */ 476 part_mb = partp->dp_size; 477 part_mb *= secsize; 478 part_mb /= (1024 * 1024); 479 printf("sysid %d (%#04x),(%s)\n", partp->dp_typ, partp->dp_typ, 480 get_type(partp->dp_typ)); 481 printf(" start %lu, size %lu (%ju Meg), flag %x%s\n", 482 (u_long)partp->dp_start, 483 (u_long)partp->dp_size, 484 (uintmax_t)part_mb, 485 partp->dp_flag, 486 partp->dp_flag == ACTIVE ? " (active)" : ""); 487 printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n" 488 ,DPCYL(partp->dp_scyl, partp->dp_ssect) 489 ,partp->dp_shd 490 ,DPSECT(partp->dp_ssect) 491 ,DPCYL(partp->dp_ecyl, partp->dp_esect) 492 ,partp->dp_ehd 493 ,DPSECT(partp->dp_esect)); 494} 495 496 497static void 498init_boot(void) 499{ 500#ifndef __ia64__ 501 const char *fname; 502 int fdesc, n; 503 struct stat sb; 504 505 fname = b_flag ? b_flag : "/boot/mbr"; 506 if ((fdesc = open(fname, O_RDONLY)) == -1 || 507 fstat(fdesc, &sb) == -1) 508 err(1, "%s", fname); 509 if ((mboot.bootinst_size = sb.st_size) % secsize != 0) 510 errx(1, "%s: length must be a multiple of sector size", fname); 511 if (mboot.bootinst != NULL) 512 free(mboot.bootinst); 513 if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL) 514 errx(1, "%s: unable to allocate read buffer", fname); 515 if ((n = read(fdesc, mboot.bootinst, mboot.bootinst_size)) == -1 || 516 close(fdesc)) 517 err(1, "%s", fname); 518 if (n != mboot.bootinst_size) 519 errx(1, "%s: short read", fname); 520#else 521 if (mboot.bootinst != NULL) 522 free(mboot.bootinst); 523 mboot.bootinst_size = secsize; 524 if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) 525 errx(1, "unable to allocate boot block buffer"); 526 memset(mboot.bootinst, 0, mboot.bootinst_size); 527 le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC); 528#endif 529} 530 531 532static void 533init_sector0(unsigned long start) 534{ 535 struct dos_partition *partp = &mboot.parts[0]; 536 537 init_boot(); 538 539 partp->dp_typ = DOSPTYP_386BSD; 540 partp->dp_flag = ACTIVE; 541 start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors; 542 if(start == 0) 543 start = dos_sectors; 544 partp->dp_start = start; 545 partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start; 546 547 dos(partp); 548} 549 550static void 551change_part(int i) 552{ 553 struct dos_partition *partp = &mboot.parts[i - 1]; 554 555 printf("The data for partition %d is:\n", i); 556 print_part(partp); 557 558 if (u_flag && ok("Do you want to change it?")) { 559 int tmp; 560 561 if (i_flag) { 562 bzero(partp, sizeof (*partp)); 563 if (i == 1) { 564 init_sector0(1); 565 printf("\nThe static data for the slice 1 has been reinitialized to:\n"); 566 print_part(partp); 567 } 568 } 569 570 do { 571 Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp); 572 Decimal("start", partp->dp_start, tmp); 573 Decimal("size", partp->dp_size, tmp); 574 if (!sanitize_partition(partp)) { 575 warnx("ERROR: failed to adjust; setting sysid to 0"); 576 partp->dp_typ = 0; 577 } 578 579 if (ok("Explicitly specify beg/end address ?")) 580 { 581 int tsec,tcyl,thd; 582 tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect); 583 thd = partp->dp_shd; 584 tsec = DPSECT(partp->dp_ssect); 585 Decimal("beginning cylinder", tcyl, tmp); 586 Decimal("beginning head", thd, tmp); 587 Decimal("beginning sector", tsec, tmp); 588 partp->dp_scyl = DOSCYL(tcyl); 589 partp->dp_ssect = DOSSECT(tsec,tcyl); 590 partp->dp_shd = thd; 591 592 tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect); 593 thd = partp->dp_ehd; 594 tsec = DPSECT(partp->dp_esect); 595 Decimal("ending cylinder", tcyl, tmp); 596 Decimal("ending head", thd, tmp); 597 Decimal("ending sector", tsec, tmp); 598 partp->dp_ecyl = DOSCYL(tcyl); 599 partp->dp_esect = DOSSECT(tsec,tcyl); 600 partp->dp_ehd = thd; 601 } else 602 dos(partp); 603 604 print_part(partp); 605 } while (!ok("Are we happy with this entry?")); 606 } 607} 608 609static void 610print_params() 611{ 612 printf("parameters extracted from in-core disklabel are:\n"); 613 printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n" 614 ,cyls,heads,sectors,cylsecs); 615 if (dos_cyls > 1023 || dos_heads > 255 || dos_sectors > 63) 616 printf("Figures below won't work with BIOS for partitions not in cyl 1\n"); 617 printf("parameters to be used for BIOS calculations are:\n"); 618 printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n" 619 ,dos_cyls,dos_heads,dos_sectors,dos_cylsecs); 620} 621 622static void 623change_active(int which) 624{ 625 struct dos_partition *partp = &mboot.parts[0]; 626 int active, i, new, tmp; 627 628 active = -1; 629 for (i = 0; i < NDOSPART; i++) { 630 if ((partp[i].dp_flag & ACTIVE) == 0) 631 continue; 632 printf("Partition %d is marked active\n", i + 1); 633 if (active == -1) 634 active = i + 1; 635 } 636 if (a_flag && which != -1) 637 active = which; 638 else if (active == -1) 639 active = 1; 640 641 if (!ok("Do you want to change the active partition?")) 642 return; 643setactive: 644 do { 645 new = active; 646 Decimal("active partition", new, tmp); 647 if (new < 1 || new > 4) { 648 printf("Active partition number must be in range 1-4." 649 " Try again.\n"); 650 goto setactive; 651 } 652 active = new; 653 } while (!ok("Are you happy with this choice")); 654 for (i = 0; i < NDOSPART; i++) 655 partp[i].dp_flag = 0; 656 if (active > 0 && active <= NDOSPART) 657 partp[active-1].dp_flag = ACTIVE; 658} 659 660static void 661change_code() 662{ 663 if (ok("Do you want to change the boot code?")) 664 init_boot(); 665} 666 667void 668get_params_to_use() 669{ 670 int tmp; 671 print_params(); 672 if (ok("Do you want to change our idea of what BIOS thinks ?")) 673 { 674 do 675 { 676 Decimal("BIOS's idea of #cylinders", dos_cyls, tmp); 677 Decimal("BIOS's idea of #heads", dos_heads, tmp); 678 Decimal("BIOS's idea of #sectors", dos_sectors, tmp); 679 dos_cylsecs = dos_heads * dos_sectors; 680 print_params(); 681 } 682 while(!ok("Are you happy with this choice")); 683 } 684} 685 686 687/***********************************************\ 688* Change real numbers into strange dos numbers * 689\***********************************************/ 690static void 691dos(struct dos_partition *partp) 692{ 693 int cy, sec; 694 u_int32_t end; 695 696 if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) { 697 memcpy(partp, &mtpart, sizeof(*partp)); 698 return; 699 } 700 701 /* Start c/h/s. */ 702 partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors; 703 cy = partp->dp_start / dos_cylsecs; 704 sec = partp->dp_start % dos_sectors + 1; 705 partp->dp_scyl = DOSCYL(cy); 706 partp->dp_ssect = DOSSECT(sec, cy); 707 708 /* End c/h/s. */ 709 end = partp->dp_start + partp->dp_size - 1; 710 partp->dp_ehd = end % dos_cylsecs / dos_sectors; 711 cy = end / dos_cylsecs; 712 sec = end % dos_sectors + 1; 713 partp->dp_ecyl = DOSCYL(cy); 714 partp->dp_esect = DOSSECT(sec, cy); 715} 716 717static int 718open_disk(int flag) 719{ 720 int rwmode; 721 722 /* Write mode if one of these flags are set. */ 723 rwmode = (a_flag || I_flag || B_flag || flag); 724 fd = g_open(disk, rwmode); 725 /* If the mode fails, try read-only if we didn't. */ 726 if (fd == -1 && errno == EPERM && rwmode) 727 fd = g_open(disk, 0); 728 if (fd == -1 && errno == ENXIO) 729 return -2; 730 if (fd == -1) { 731 warnx("can't open device %s", disk); 732 return -1; 733 } 734 if (get_params() == -1) { 735 warnx("can't get disk parameters on %s", disk); 736 return -1; 737 } 738 return fd; 739} 740 741static ssize_t 742read_disk(off_t sector, void *buf) 743{ 744 745 lseek(fd, (sector * 512), 0); 746 if (secsize == 0) 747 for (secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; 748 secsize *= 2) { 749 /* try the read */ 750 int size = read(fd, buf, secsize); 751 if (size == secsize) 752 /* it worked so return */ 753 return secsize; 754 } 755 else 756 return read(fd, buf, secsize); 757 758 /* we failed to read at any of the sizes */ 759 return -1; 760} 761 762static int 763write_disk(off_t sector, void *buf) 764{ 765 int error; 766 struct gctl_req *grq; 767 const char *errmsg; 768 char fbuf[BUFSIZ], *pname; 769 int i, fdw; 770 771 grq = gctl_get_handle(); 772 gctl_ro_param(grq, "verb", -1, "write MBR"); 773 gctl_ro_param(grq, "class", -1, "MBR"); 774 pname = g_providername(fd); 775 if (pname == NULL) { 776 warn("Error getting providername for %s", disk); 777 return (-1); 778 } 779 gctl_ro_param(grq, "geom", -1, pname); 780 gctl_ro_param(grq, "data", secsize, buf); 781 errmsg = gctl_issue(grq); 782 free(pname); 783 if (errmsg == NULL) { 784 gctl_free(grq); 785 return(0); 786 } 787 if (!q_flag) /* GEOM errors are benign, not all devices supported */ 788 warnx("%s", errmsg); 789 gctl_free(grq); 790 791 error = pwrite(fd, buf, secsize, (sector * 512)); 792 if (error == secsize) 793 return (0); 794 795 for (i = 1; i < 5; i++) { 796 sprintf(fbuf, "%ss%d", disk, i); 797 fdw = open(fbuf, O_RDWR, 0); 798 if (fdw < 0) 799 continue; 800 error = ioctl(fdw, DIOCSMBR, buf); 801 close(fdw); 802 if (error == 0) 803 return (0); 804 } 805 warnx("Failed to write sector zero"); 806 return(EINVAL); 807} 808 809static int 810get_params() 811{ 812 int error; 813 u_int u; 814 off_t o; 815 816 error = ioctl(fd, DIOCGFWSECTORS, &u); 817 if (error == 0) 818 sectors = dos_sectors = u; 819 else 820 sectors = dos_sectors = 63; 821 822 error = ioctl(fd, DIOCGFWHEADS, &u); 823 if (error == 0) 824 heads = dos_heads = u; 825 else 826 heads = dos_heads = 255; 827 828 dos_cylsecs = cylsecs = heads * sectors; 829 disksecs = cyls * heads * sectors; 830 831 u = g_sectorsize(fd); 832 if (u <= 0) 833 return (-1); 834 835 o = g_mediasize(fd); 836 if (o < 0) 837 return (-1); 838 disksecs = o / u; 839 cyls = dos_cyls = o / (u * dos_heads * dos_sectors); 840 841 return (disksecs); 842} 843 844static int 845read_s0() 846{ 847 int i; 848 849 mboot.bootinst_size = secsize; 850 if (mboot.bootinst != NULL) 851 free(mboot.bootinst); 852 if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) { 853 warnx("unable to allocate buffer to read fdisk " 854 "partition table"); 855 return -1; 856 } 857 if (read_disk(0, mboot.bootinst) == -1) { 858 warnx("can't read fdisk partition table"); 859 return -1; 860 } 861 if (le16dec(&mboot.bootinst[DOSMAGICOFFSET]) != DOSMAGIC) { 862 warnx("invalid fdisk partition table found"); 863 /* So should we initialize things */ 864 return -1; 865 } 866 for (i = 0; i < NDOSPART; i++) 867 dos_partition_dec( 868 &mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE], 869 &mboot.parts[i]); 870 return 0; 871} 872 873static int 874write_s0() 875{ 876 int sector, i; 877 878 if (iotest) { 879 print_s0(); 880 return 0; 881 } 882 for(i = 0; i < NDOSPART; i++) 883 dos_partition_enc(&mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE], 884 &mboot.parts[i]); 885 le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC); 886 for(sector = 0; sector < mboot.bootinst_size / secsize; sector++) 887 if (write_disk(sector, 888 &mboot.bootinst[sector * secsize]) == -1) { 889 warn("can't write fdisk partition table"); 890 return -1; 891 } 892 return(0); 893} 894 895 896static int 897ok(const char *str) 898{ 899 printf("%s [n] ", str); 900 fflush(stdout); 901 if (fgets(lbuf, LBUF, stdin) == NULL) 902 exit(1); 903 lbuf[strlen(lbuf)-1] = 0; 904 905 if (*lbuf && 906 (!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") || 907 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y"))) 908 return 1; 909 else 910 return 0; 911} 912 913static int 914decimal(const char *str, int *num, int deflt) 915{ 916 int acc = 0, c; 917 char *cp; 918 919 while (1) { 920 printf("Supply a decimal value for \"%s\" [%d] ", str, deflt); 921 fflush(stdout); 922 if (fgets(lbuf, LBUF, stdin) == NULL) 923 exit(1); 924 lbuf[strlen(lbuf)-1] = 0; 925 926 if (!*lbuf) 927 return 0; 928 929 cp = lbuf; 930 while ((c = *cp) && (c == ' ' || c == '\t')) cp++; 931 if (!c) 932 return 0; 933 while ((c = *cp++)) { 934 if (c <= '9' && c >= '0') 935 acc = acc * 10 + c - '0'; 936 else 937 break; 938 } 939 if (c == ' ' || c == '\t') 940 while ((c = *cp) && (c == ' ' || c == '\t')) cp++; 941 if (!c) { 942 *num = acc; 943 return 1; 944 } else 945 printf("%s is an invalid decimal number. Try again.\n", 946 lbuf); 947 } 948 949} 950 951 952static void 953parse_config_line(char *line, CMD *command) 954{ 955 char *cp, *end; 956 957 cp = line; 958 while (1) { 959 memset(command, 0, sizeof(*command)); 960 961 while (isspace(*cp)) ++cp; 962 if (*cp == '\0' || *cp == '#') 963 break; 964 command->cmd = *cp++; 965 966 /* 967 * Parse args 968 */ 969 while (1) { 970 while (isspace(*cp)) ++cp; 971 if (*cp == '#') 972 break; /* found comment */ 973 if (isalpha(*cp)) 974 command->args[command->n_args].argtype = *cp++; 975 if (!isdigit(*cp)) 976 break; /* assume end of line */ 977 end = NULL; 978 command->args[command->n_args].arg_val = strtol(cp, &end, 0); 979 if (cp == end) 980 break; /* couldn't parse number */ 981 cp = end; 982 command->n_args++; 983 } 984 break; 985 } 986} 987 988 989static int 990process_geometry(CMD *command) 991{ 992 int status = 1, i; 993 994 while (1) { 995 geom_processed = 1; 996 if (part_processed) { 997 warnx( 998 "ERROR line %d: the geometry specification line must occur before\n\ 999 all partition specifications", 1000 current_line_number); 1001 status = 0; 1002 break; 1003 } 1004 if (command->n_args != 3) { 1005 warnx("ERROR line %d: incorrect number of geometry args", 1006 current_line_number); 1007 status = 0; 1008 break; 1009 } 1010 dos_cyls = 0; 1011 dos_heads = 0; 1012 dos_sectors = 0; 1013 for (i = 0; i < 3; ++i) { 1014 switch (command->args[i].argtype) { 1015 case 'c': 1016 dos_cyls = command->args[i].arg_val; 1017 break; 1018 case 'h': 1019 dos_heads = command->args[i].arg_val; 1020 break; 1021 case 's': 1022 dos_sectors = command->args[i].arg_val; 1023 break; 1024 default: 1025 warnx( 1026 "ERROR line %d: unknown geometry arg type: '%c' (0x%02x)", 1027 current_line_number, command->args[i].argtype, 1028 command->args[i].argtype); 1029 status = 0; 1030 break; 1031 } 1032 } 1033 if (status == 0) 1034 break; 1035 1036 dos_cylsecs = dos_heads * dos_sectors; 1037 1038 /* 1039 * Do sanity checks on parameter values 1040 */ 1041 if (dos_cyls == 0) { 1042 warnx("ERROR line %d: number of cylinders not specified", 1043 current_line_number); 1044 status = 0; 1045 } 1046 if (dos_cyls > 1024) { 1047 warnx( 1048 "WARNING line %d: number of cylinders (%d) may be out-of-range\n\ 1049 (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\ 1050 is dedicated to FreeBSD)", 1051 current_line_number, dos_cyls); 1052 } 1053 1054 if (dos_heads == 0) { 1055 warnx("ERROR line %d: number of heads not specified", 1056 current_line_number); 1057 status = 0; 1058 } else if (dos_heads > 256) { 1059 warnx("ERROR line %d: number of heads must be within (1-256)", 1060 current_line_number); 1061 status = 0; 1062 } 1063 1064 if (dos_sectors == 0) { 1065 warnx("ERROR line %d: number of sectors not specified", 1066 current_line_number); 1067 status = 0; 1068 } else if (dos_sectors > 63) { 1069 warnx("ERROR line %d: number of sectors must be within (1-63)", 1070 current_line_number); 1071 status = 0; 1072 } 1073 1074 break; 1075 } 1076 return (status); 1077} 1078 1079 1080static int 1081process_partition(CMD *command) 1082{ 1083 int status = 0, partition; 1084 u_int32_t prev_head_boundary, prev_cyl_boundary; 1085 u_int32_t adj_size, max_end; 1086 struct dos_partition *partp; 1087 1088 while (1) { 1089 part_processed = 1; 1090 if (command->n_args != 4) { 1091 warnx("ERROR line %d: incorrect number of partition args", 1092 current_line_number); 1093 break; 1094 } 1095 partition = command->args[0].arg_val; 1096 if (partition < 1 || partition > 4) { 1097 warnx("ERROR line %d: invalid partition number %d", 1098 current_line_number, partition); 1099 break; 1100 } 1101 partp = &mboot.parts[partition - 1]; 1102 bzero(partp, sizeof (*partp)); 1103 partp->dp_typ = command->args[1].arg_val; 1104 partp->dp_start = command->args[2].arg_val; 1105 partp->dp_size = command->args[3].arg_val; 1106 max_end = partp->dp_start + partp->dp_size; 1107 1108 if (partp->dp_typ == 0) { 1109 /* 1110 * Get out, the partition is marked as unused. 1111 */ 1112 /* 1113 * Insure that it's unused. 1114 */ 1115 bzero(partp, sizeof(*partp)); 1116 status = 1; 1117 break; 1118 } 1119 1120 /* 1121 * Adjust start upwards, if necessary, to fall on a head boundary. 1122 */ 1123 if (partp->dp_start % dos_sectors != 0) { 1124 prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors; 1125 if (max_end < dos_sectors || 1126 prev_head_boundary > max_end - dos_sectors) { 1127 /* 1128 * Can't go past end of partition 1129 */ 1130 warnx( 1131 "ERROR line %d: unable to adjust start of partition %d to fall on\n\ 1132 a head boundary", 1133 current_line_number, partition); 1134 break; 1135 } 1136 warnx( 1137 "WARNING: adjusting start offset of partition %d\n\ 1138 from %u to %u, to fall on a head boundary", 1139 partition, (u_int)partp->dp_start, 1140 (u_int)(prev_head_boundary + dos_sectors)); 1141 partp->dp_start = prev_head_boundary + dos_sectors; 1142 } 1143 1144 /* 1145 * Adjust size downwards, if necessary, to fall on a cylinder 1146 * boundary. 1147 */ 1148 prev_cyl_boundary = 1149 ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs; 1150 if (prev_cyl_boundary > partp->dp_start) 1151 adj_size = prev_cyl_boundary - partp->dp_start; 1152 else { 1153 warnx( 1154 "ERROR: could not adjust partition to start on a head boundary\n\ 1155 and end on a cylinder boundary."); 1156 return (0); 1157 } 1158 if (adj_size != partp->dp_size) { 1159 warnx( 1160 "WARNING: adjusting size of partition %d from %u to %u\n\ 1161 to end on a cylinder boundary", 1162 partition, (u_int)partp->dp_size, (u_int)adj_size); 1163 partp->dp_size = adj_size; 1164 } 1165 if (partp->dp_size == 0) { 1166 warnx("ERROR line %d: size of partition %d is zero", 1167 current_line_number, partition); 1168 break; 1169 } 1170 1171 dos(partp); 1172 status = 1; 1173 break; 1174 } 1175 return (status); 1176} 1177 1178 1179static int 1180process_active(CMD *command) 1181{ 1182 int status = 0, partition, i; 1183 struct dos_partition *partp; 1184 1185 while (1) { 1186 active_processed = 1; 1187 if (command->n_args != 1) { 1188 warnx("ERROR line %d: incorrect number of active args", 1189 current_line_number); 1190 status = 0; 1191 break; 1192 } 1193 partition = command->args[0].arg_val; 1194 if (partition < 1 || partition > 4) { 1195 warnx("ERROR line %d: invalid partition number %d", 1196 current_line_number, partition); 1197 break; 1198 } 1199 /* 1200 * Reset active partition 1201 */ 1202 partp = mboot.parts; 1203 for (i = 0; i < NDOSPART; i++) 1204 partp[i].dp_flag = 0; 1205 partp[partition-1].dp_flag = ACTIVE; 1206 1207 status = 1; 1208 break; 1209 } 1210 return (status); 1211} 1212 1213 1214static int 1215process_line(char *line) 1216{ 1217 CMD command; 1218 int status = 1; 1219 1220 while (1) { 1221 parse_config_line(line, &command); 1222 switch (command.cmd) { 1223 case 0: 1224 /* 1225 * Comment or blank line 1226 */ 1227 break; 1228 case 'g': 1229 /* 1230 * Set geometry 1231 */ 1232 status = process_geometry(&command); 1233 break; 1234 case 'p': 1235 status = process_partition(&command); 1236 break; 1237 case 'a': 1238 status = process_active(&command); 1239 break; 1240 default: 1241 status = 0; 1242 break; 1243 } 1244 break; 1245 } 1246 return (status); 1247} 1248 1249 1250static int 1251read_config(char *config_file) 1252{ 1253 FILE *fp = NULL; 1254 int status = 1; 1255 char buf[1010]; 1256 1257 while (1) { 1258 if (strcmp(config_file, "-") != 0) { 1259 /* 1260 * We're not reading from stdin 1261 */ 1262 if ((fp = fopen(config_file, "r")) == NULL) { 1263 status = 0; 1264 break; 1265 } 1266 } else { 1267 fp = stdin; 1268 } 1269 current_line_number = 0; 1270 while (!feof(fp)) { 1271 if (fgets(buf, sizeof(buf), fp) == NULL) 1272 break; 1273 ++current_line_number; 1274 status = process_line(buf); 1275 if (status == 0) 1276 break; 1277 } 1278 break; 1279 } 1280 if (fp) { 1281 /* 1282 * It doesn't matter if we're reading from stdin, as we've reached EOF 1283 */ 1284 fclose(fp); 1285 } 1286 return (status); 1287} 1288 1289 1290static void 1291reset_boot(void) 1292{ 1293 int i; 1294 struct dos_partition *partp; 1295 1296 init_boot(); 1297 for (i = 0; i < 4; ++i) { 1298 partp = &mboot.parts[i]; 1299 bzero(partp, sizeof(*partp)); 1300 } 1301} 1302 1303static int 1304sanitize_partition(struct dos_partition *partp) 1305{ 1306 u_int32_t prev_head_boundary, prev_cyl_boundary; 1307 u_int32_t max_end, size, start; 1308 1309 start = partp->dp_start; 1310 size = partp->dp_size; 1311 max_end = start + size; 1312 /* Only allow a zero size if the partition is being marked unused. */ 1313 if (size == 0) { 1314 if (start == 0 && partp->dp_typ == 0) 1315 return (1); 1316 warnx("ERROR: size of partition is zero"); 1317 return (0); 1318 } 1319 /* Return if no adjustment is necessary. */ 1320 if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0) 1321 return (1); 1322 1323 if (start == 0) { 1324 warnx("WARNING: partition overlaps with partition table"); 1325 if (ok("Correct this automatically?")) 1326 start = dos_sectors; 1327 } 1328 if (start % dos_sectors != 0) 1329 warnx("WARNING: partition does not start on a head boundary"); 1330 if ((start +size) % dos_sectors != 0) 1331 warnx("WARNING: partition does not end on a cylinder boundary"); 1332 warnx("WARNING: this may confuse the BIOS or some operating systems"); 1333 if (!ok("Correct this automatically?")) 1334 return (1); 1335 1336 /* 1337 * Adjust start upwards, if necessary, to fall on a head boundary. 1338 */ 1339 if (start % dos_sectors != 0) { 1340 prev_head_boundary = start / dos_sectors * dos_sectors; 1341 if (max_end < dos_sectors || 1342 prev_head_boundary >= max_end - dos_sectors) { 1343 /* 1344 * Can't go past end of partition 1345 */ 1346 warnx( 1347 "ERROR: unable to adjust start of partition to fall on a head boundary"); 1348 return (0); 1349 } 1350 start = prev_head_boundary + dos_sectors; 1351 } 1352 1353 /* 1354 * Adjust size downwards, if necessary, to fall on a cylinder 1355 * boundary. 1356 */ 1357 prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs; 1358 if (prev_cyl_boundary > start) 1359 size = prev_cyl_boundary - start; 1360 else { 1361 warnx("ERROR: could not adjust partition to start on a head boundary\n\ 1362 and end on a cylinder boundary."); 1363 return (0); 1364 } 1365 1366 /* Finally, commit any changes to partp and return. */ 1367 if (start != partp->dp_start) { 1368 warnx("WARNING: adjusting start offset of partition to %u", 1369 (u_int)start); 1370 partp->dp_start = start; 1371 } 1372 if (size != partp->dp_size) { 1373 warnx("WARNING: adjusting size of partition to %u", (u_int)size); 1374 partp->dp_size = size; 1375 } 1376 1377 return (1); 1378} 1379 1380/* 1381 * Try figuring out the root device's canonical disk name. 1382 * The following choices are considered: 1383 * /dev/ad0s1a => /dev/ad0 1384 * /dev/da0a => /dev/da0 1385 * /dev/vinum/root => /dev/vinum/root 1386 */ 1387static char * 1388get_rootdisk(void) 1389{ 1390 struct statfs rootfs; 1391 regex_t re; 1392#define NMATCHES 2 1393 regmatch_t rm[NMATCHES]; 1394 char *s; 1395 int rv; 1396 1397 if (statfs("/", &rootfs) == -1) 1398 err(1, "statfs(\"/\")"); 1399 1400 if ((rv = regcomp(&re, "^(/dev/[a-z/]+[0-9]+)([sp][0-9]+)?[a-h]?$", 1401 REG_EXTENDED)) != 0) 1402 errx(1, "regcomp() failed (%d)", rv); 1403 if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0) 1404 errx(1, 1405"mounted root fs resource doesn't match expectations (regexec returned %d)", 1406 rv); 1407 if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL) 1408 errx(1, "out of memory"); 1409 memcpy(s, rootfs.f_mntfromname + rm[1].rm_so, 1410 rm[1].rm_eo - rm[1].rm_so); 1411 s[rm[1].rm_eo - rm[1].rm_so] = 0; 1412 1413 return s; 1414} 1415