kernel - Add atomic_readandclear_int()
[dragonfly.git] / sbin / fdisk / fdisk.c
blobfbdad7d6976eb2a895036b012769df8838c226e6
1 /*
2 * Mach Operating System
3 * Copyright (c) 1992 Carnegie Mellon University
4 * All Rights Reserved.
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.
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.
16 * Carnegie Mellon requests users of this software to return to
18 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
19 * School of Computer Science
20 * Carnegie Mellon University
21 * Pittsburgh PA 15213-3890
23 * any improvements or extensions that they make and grant Carnegie Mellon
24 * the rights to redistribute these changes.
26 * $FreeBSD: /repoman/r/ncvs/src/sbin/i386/fdisk/fdisk.c,v 1.36.2.14 2004/01/30 14:40:47 harti Exp $
27 * $DragonFly: src/sbin/i386/fdisk/fdisk.c,v 1.16 2008/04/23 22:09:07 thomas Exp $
30 #include <sys/types.h>
31 #include <sys/diskslice.h>
32 #include <sys/diskmbr.h>
33 #include <sys/stat.h>
34 #include <ctype.h>
35 #include <fcntl.h>
36 #include <err.h>
37 #include <fstab.h>
38 #include <errno.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
44 int iotest;
46 #define LBUF 100
47 static char lbuf[LBUF];
49 #define MBRSIGOFF 510
53 * Ported to 386bsd by Julian Elischer Thu Oct 15 20:26:46 PDT 1992
55 * 14-Dec-89 Robert Baron (rvb) at Carnegie-Mellon University
56 * Copyright (c) 1989 Robert. V. Baron
57 * Created.
60 #define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp
61 #define Hex(str, ans, tmp) if (hex(str, &tmp, ans)) ans = tmp
62 #define String(str, ans, len) {char *z = ans; char **dflt = &z; if (string(str, dflt)) strncpy(ans, *dflt, len); }
64 #define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs)
66 #define MAX_SEC_SIZE 2048 /* maximum section size that is supported */
67 #define MIN_SEC_SIZE 512 /* the sector size to start sensing at */
68 int secsize = 0; /* the sensed sector size */
70 const char *disk;
71 const char *disks[] =
73 "/dev/ad0", "/dev/da0", "/dev/vkd0", 0
76 int cyls, sectors, heads, cylsecs;
77 int64_t disksecs;
79 struct mboot
81 unsigned char padding[2]; /* force the longs to be long aligned */
82 unsigned char *bootinst; /* boot code */
83 off_t bootinst_size;
84 struct dos_partition parts[4];
86 struct mboot mboot = {{0}, NULL, 0};
88 #define ACTIVE 0x80
89 #define BOOT_MAGIC 0xAA55
91 int dos_cyls;
92 int dos_heads;
93 int dos_sectors;
94 int dos_cylsecs;
96 #define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0))
97 #define DOSCYL(c) (c & 0xff)
98 #define MAXCYL 1023
99 static int partition = -1;
102 #define MAX_ARGS 10
104 static int current_line_number;
106 static int geom_processed = 0;
107 static int part_processed = 0;
108 static int active_processed = 0;
111 typedef struct cmd {
112 char cmd;
113 int n_args;
114 struct arg {
115 char argtype;
116 int arg_val;
117 } args[MAX_ARGS];
118 } CMD;
121 static int B_flag = 0; /* replace boot code */
122 static int C_flag = 0; /* use wrapped values for CHS */
123 static int I_flag = 0; /* use entire disk for DragonFly */
124 static int a_flag = 0; /* set active partition */
125 static char *b_flag = NULL; /* path to boot code */
126 static int i_flag = 0; /* replace partition data */
127 static int u_flag = 0; /* update partition data */
128 static int p_flag = 0; /* operate on a disk image file */
129 static int s_flag = 0; /* Print a summary and exit */
130 static int t_flag = 0; /* test only */
131 static char *f_flag = NULL; /* Read config info from file */
132 static int v_flag = 0; /* Be verbose */
134 struct part_type
136 unsigned char type;
137 char *name;
138 }part_types[] =
140 {0x00, "unused"}
141 ,{0x01, "Primary DOS with 12 bit FAT"}
142 ,{0x02, "XENIX / filesystem"}
143 ,{0x03, "XENIX /usr filesystem"}
144 ,{0x04, "Primary DOS with 16 bit FAT (<= 32MB)"}
145 ,{0x05, "Extended DOS"}
146 ,{0x06, "Primary 'big' DOS (> 32MB)"}
147 ,{0x07, "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX"}
148 ,{0x08, "AIX filesystem"}
149 ,{0x09, "AIX boot partition or Coherent"}
150 ,{0x0A, "OS/2 Boot Manager or OPUS"}
151 ,{0x0B, "DOS or Windows 95 with 32 bit FAT"}
152 ,{0x0C, "DOS or Windows 95 with 32 bit FAT, LBA"}
153 ,{0x0E, "Primary 'big' DOS (> 32MB, LBA)"}
154 ,{0x0F, "Extended DOS, LBA"}
155 ,{0x10, "OPUS"}
156 ,{0x11, "OS/2 BM: hidden DOS with 12-bit FAT"}
157 ,{0x12, "Compaq diagnostics"}
158 ,{0x14, "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)"}
159 ,{0x16, "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)"}
160 ,{0x17, "OS/2 BM: hidden IFS (e.g. HPFS)"}
161 ,{0x18, "AST Windows swapfile"}
162 ,{0x24, "NEC DOS"}
163 ,{0x39, "plan9"}
164 ,{0x3C, "PartitionMagic recovery"}
165 ,{0x40, "VENIX 286"}
166 ,{0x41, "Linux/MINIX (sharing disk with DRDOS)"}
167 ,{0x42, "SFS or Linux swap (sharing disk with DRDOS)"}
168 ,{0x43, "Linux native (sharing disk with DRDOS)"}
169 ,{0x4D, "QNX 4.2 Primary"}
170 ,{0x4E, "QNX 4.2 Secondary"}
171 ,{0x4F, "QNX 4.2 Tertiary"}
172 ,{0x50, "DM"}
173 ,{0x51, "DM"}
174 ,{0x52, "CP/M or Microport SysV/AT"}
175 ,{0x53, "DM6 Aux3"}
176 ,{0x54, "DM6"}
177 ,{0x55, "EZ-Drive (disk manager)"}
178 ,{0x56, "GB"}
179 ,{0x5C, "Priam Edisk (disk manager)"} /* according to S. Widlake */
180 ,{0x61, "Speed"}
181 ,{0x63, "ISC UNIX, other System V/386, GNU HURD or Mach"}
182 ,{0x64, "Novell Netware 2.xx"}
183 ,{0x65, "Novell Netware 3.xx"}
184 ,{0x70, "DiskSecure Multi-Boot"}
185 ,{0x75, "PCIX"}
186 ,{0x77, "QNX4.x"}
187 ,{0x78, "QNX4.x 2nd part"}
188 ,{0x79, "QNX4.x 3rd part"}
189 ,{0x80, "Minix 1.1 ... 1.4a"}
190 ,{0x81, "Minix 1.4b ... 1.5.10"}
191 ,{0x82, "Linux swap or Solaris x86"}
192 ,{0x83, "Linux filesystem"}
193 ,{0x84, "OS/2 hidden C: drive"}
194 ,{0x85, "Linux extended"}
195 ,{0x86, "NTFS volume set??"}
196 ,{0x87, "NTFS volume set??"}
197 ,{0x93, "Amoeba filesystem"}
198 ,{0x94, "Amoeba bad block table"}
199 ,{0x9F, "BSD/OS"}
200 ,{0xA0, "Suspend to Disk"}
201 ,{0xA5, "DragonFly/FreeBSD/NetBSD/386BSD"}
202 ,{0xA6, "OpenBSD"}
203 ,{0xA7, "NEXTSTEP"}
204 ,{0xA9, "NetBSD"}
205 ,{0xAC, "IBM JFS"}
206 ,{0xB7, "BSDI BSD/386 filesystem"}
207 ,{0xB8, "BSDI BSD/386 swap"}
208 ,{0xBE, "Solaris x86 boot"}
209 ,{0xC1, "DRDOS/sec with 12-bit FAT"}
210 ,{0xC4, "DRDOS/sec with 16-bit FAT (< 32MB)"}
211 ,{0xC6, "DRDOS/sec with 16-bit FAT (>= 32MB)"}
212 ,{0xC7, "Syrinx"}
213 ,{0xDB, "Concurrent CPM or C.DOS or CTOS"}
214 ,{0xE1, "Speed"}
215 ,{0xE3, "Speed"}
216 ,{0xE4, "Speed"}
217 ,{0xEB, "BeOS file system"}
218 ,{0xEE, "EFI GPT"}
219 ,{0xEF, "EFI System Partition"}
220 ,{0xF1, "Speed"}
221 ,{0xF2, "DOS 3.3+ Secondary"}
222 ,{0xF4, "Speed"}
223 ,{0xFE, "SpeedStor >1024 cyl. or LANstep"}
224 ,{0xFF, "BBT (Bad Blocks Table)"}
227 static void print_s0(int which);
228 static void print_part(int i);
229 static void init_sector0(unsigned long start);
230 static void init_boot(void);
231 static void change_part(int i);
232 static void print_params();
233 static void change_active(int which);
234 static void change_code();
235 static void get_params_to_use();
236 static void dos(struct dos_partition *partp);
237 static int open_disk(int u_flag);
238 static ssize_t read_disk(off_t sector, void *buf);
239 static ssize_t write_disk(off_t sector, void *buf);
240 static int get_params();
241 static int read_s0();
242 static int write_s0();
243 static int ok(char *str);
244 static int decimal(char *str, int *num, int deflt);
245 static char *get_type(int type);
246 static int read_config(char *config_file);
247 static void reset_boot(void);
248 static int sanitize_partition(struct dos_partition *);
249 static void usage(void);
250 #if 0
251 static int hex(char *str, int *num, int deflt);
252 static int string(char *str, char **ans);
253 #endif
257 main(int argc, char *argv[])
259 int c, i;
261 while ((c = getopt(argc, argv, "BCIab:f:p:istuv1234")) != -1)
262 switch (c) {
263 case 'B':
264 B_flag = 1;
265 break;
266 case 'C':
267 C_flag = 1;
268 break;
269 case 'I':
270 I_flag = 1;
271 break;
272 case 'a':
273 a_flag = 1;
274 break;
275 case 'b':
276 b_flag = optarg;
277 break;
278 case 'f':
279 f_flag = optarg;
280 break;
281 case 'p':
282 disk = optarg;
283 p_flag = 1;
284 break;
285 case 'i':
286 i_flag = 1;
287 break;
288 case 's':
289 s_flag = 1;
290 break;
291 case 't':
292 t_flag = 1;
293 break;
294 case 'u':
295 u_flag = 1;
296 break;
297 case 'v':
298 v_flag = 1;
299 break;
300 case '1':
301 case '2':
302 case '3':
303 case '4':
304 partition = c - '0';
305 break;
306 default:
307 usage();
309 if (f_flag || i_flag)
310 u_flag = 1;
311 if (t_flag)
312 v_flag = 1;
313 argc -= optind;
314 argv += optind;
316 if (argc > 0) {
317 disk = getdevpath(argv[0], 0);
318 if (open_disk(u_flag) < 0)
319 err(1, "cannot open disk %s", disk);
320 } else if (disk == NULL) {
321 int rv = 0;
323 for(i = 0; disks[i]; i++)
325 disk = disks[i];
326 rv = open_disk(u_flag);
327 if(rv != -2) break;
329 if(rv < 0)
330 err(1, "cannot open any disk");
331 } else {
332 if (open_disk(u_flag) < 0)
333 err(1, "cannot open disk %s", disk);
336 /* (abu)use mboot.bootinst to probe for the sector size */
337 if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL)
338 err(1, "cannot allocate buffer to determine disk sector size");
339 read_disk(0, mboot.bootinst);
340 free(mboot.bootinst);
341 mboot.bootinst = NULL;
343 if (s_flag)
345 int i;
346 struct dos_partition *partp;
348 if (read_s0())
349 err(1, "read_s0");
350 printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
351 dos_sectors);
352 printf("Part %11s %11s Type Flags\n", "Start", "Size");
353 for (i = 0; i < NDOSPART; i++) {
354 partp = ((struct dos_partition *) &mboot.parts) + i;
355 if (partp->dp_start == 0 && partp->dp_size == 0)
356 continue;
357 printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1,
358 (u_long) partp->dp_start,
359 (u_long) partp->dp_size, partp->dp_typ,
360 partp->dp_flag);
362 exit(0);
365 printf("******* Working on device %s *******\n",disk);
367 if (I_flag)
369 struct dos_partition *partp;
371 read_s0();
372 reset_boot();
373 partp = (struct dos_partition *) (&mboot.parts[0]);
374 partp->dp_typ = DOSPTYP_386BSD;
375 partp->dp_flag = ACTIVE;
376 partp->dp_start = dos_sectors;
377 if (disksecs - dos_sectors > 0xFFFFFFFFU) {
378 printf("Warning: Ending logical block > 2TB, using max value\n");
379 partp->dp_size = 0xFFFFFFFFU;
380 } else {
381 partp->dp_size = (disksecs / dos_cylsecs) *
382 dos_cylsecs - dos_sectors;
384 dos(partp);
385 if (v_flag)
386 print_s0(-1);
387 if (!t_flag)
388 write_s0();
389 exit(0);
391 if (f_flag)
393 if (read_s0() || i_flag)
395 reset_boot();
398 if (!read_config(f_flag))
400 exit(1);
402 if (v_flag)
404 print_s0(-1);
406 if (!t_flag)
408 write_s0();
411 else
413 if(u_flag)
415 get_params_to_use();
417 else
419 print_params();
422 if (read_s0())
423 init_sector0(dos_sectors);
425 printf("Media sector size is %d\n", secsize);
426 printf("Warning: BIOS sector numbering starts with sector 1\n");
427 printf("Information from DOS bootblock is:\n");
428 if (partition == -1)
429 for (i = 1; i <= NDOSPART; i++)
430 change_part(i);
431 else
432 change_part(partition);
434 if (u_flag || a_flag)
435 change_active(partition);
437 if (B_flag)
438 change_code();
440 if (u_flag || a_flag || B_flag) {
441 if (!t_flag) {
442 printf("\nWe haven't changed the partition table yet. ");
443 printf("This is your last chance.\n");
445 print_s0(-1);
446 if (!t_flag) {
447 if (ok("Should we write new partition table?"))
448 write_s0();
450 else
452 printf("\n-t flag specified -- partition table not written.\n");
457 exit(0);
460 static void
461 usage(void)
463 fprintf(stderr, "%s%s",
464 "usage: fdisk [-BCIaistu] [-b bootcode] [-p diskimage] [-1234] [disk]\n",
465 " fdisk -f configfile [-itv] [disk]\n");
466 exit(1);
469 static void
470 print_s0(int which)
472 int i;
474 print_params();
475 printf("Information from DOS bootblock is:\n");
476 if (which == -1)
477 for (i = 1; i <= NDOSPART; i++)
478 printf("%d: ", i), print_part(i);
479 else
480 print_part(which);
483 static struct dos_partition mtpart = { 0 };
485 static void
486 print_part(int i)
488 struct dos_partition *partp;
489 u_int64_t part_mb;
491 partp = ((struct dos_partition *) &mboot.parts) + i - 1;
493 if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) {
494 printf("<UNUSED>\n");
495 return;
498 * Be careful not to overflow.
500 part_mb = partp->dp_size;
501 part_mb *= secsize;
502 part_mb /= (1024 * 1024);
503 printf("sysid %d,(%s)\n", partp->dp_typ, get_type(partp->dp_typ));
504 printf(" start %lu, size %lu (%jd Meg), flag %x%s\n",
505 (u_long)partp->dp_start,
506 (u_long)partp->dp_size,
507 (intmax_t)part_mb,
508 partp->dp_flag,
509 partp->dp_flag == ACTIVE ? " (active)" : "");
510 printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
511 ,DPCYL(partp->dp_scyl, partp->dp_ssect)
512 ,partp->dp_shd
513 ,DPSECT(partp->dp_ssect)
514 ,DPCYL(partp->dp_ecyl, partp->dp_esect)
515 ,partp->dp_ehd
516 ,DPSECT(partp->dp_esect));
520 static void
521 init_boot(void)
523 const char *fname;
524 int fd, n;
525 struct stat sb;
527 fname = b_flag ? b_flag : "/boot/mbr";
528 if ((fd = open(fname, O_RDONLY)) == -1 ||
529 fstat(fd, &sb) == -1)
530 err(1, "%s", fname);
531 if ((mboot.bootinst_size = sb.st_size) % secsize != 0)
532 errx(1, "%s: length must be a multiple of sector size", fname);
533 if (mboot.bootinst != NULL)
534 free(mboot.bootinst);
535 if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL)
536 errx(1, "%s: unable to allocate read buffer", fname);
537 if ((n = read(fd, mboot.bootinst, mboot.bootinst_size)) == -1 ||
538 close(fd))
539 err(1, "%s", fname);
540 if (n != mboot.bootinst_size)
541 errx(1, "%s: short read", fname);
545 static void
546 init_sector0(unsigned long start)
548 struct dos_partition *partp = (struct dos_partition *) (&mboot.parts[3]);
550 init_boot();
552 partp->dp_typ = DOSPTYP_386BSD;
553 partp->dp_flag = ACTIVE;
554 start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors;
555 if(start == 0)
556 start = dos_sectors;
557 partp->dp_start = start;
558 if (disksecs - start > 0xFFFFFFFFU) {
559 printf("Warning: Ending logical block > 2TB, using max value\n");
560 partp->dp_size = 0xFFFFFFFFU;
561 } else {
562 partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start;
565 dos(partp);
568 static void
569 change_part(int i)
571 struct dos_partition *partp = ((struct dos_partition *) &mboot.parts) + i - 1;
573 printf("The data for partition %d is:\n", i);
574 print_part(i);
576 if (u_flag && ok("Do you want to change it?")) {
577 int tmp;
579 if (i_flag) {
580 bzero((char *)partp, sizeof (struct dos_partition));
581 if (i == 4) {
582 init_sector0(1);
583 printf("\nThe static data for the DOS partition 4 has been reinitialized to:\n");
584 print_part(i);
588 do {
589 Decimal("sysid (165=DragonFly)", partp->dp_typ, tmp);
590 Decimal("start", partp->dp_start, tmp);
591 Decimal("size", partp->dp_size, tmp);
592 if (!sanitize_partition(partp)) {
593 warnx("ERROR: failed to adjust; setting sysid to 0");
594 partp->dp_typ = 0;
597 if (ok("Explicitly specify beg/end address ?"))
599 int tsec,tcyl,thd;
600 tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect);
601 thd = partp->dp_shd;
602 tsec = DPSECT(partp->dp_ssect);
603 Decimal("beginning cylinder", tcyl, tmp);
604 Decimal("beginning head", thd, tmp);
605 Decimal("beginning sector", tsec, tmp);
606 if (tcyl > MAXCYL && C_flag == 0) {
607 printf("Warning: starting cylinder wraps, using all 1's\n");
608 partp->dp_scyl = -1;
609 partp->dp_ssect = -1;
610 partp->dp_shd = -1;
611 } else {
612 partp->dp_scyl = DOSCYL(tcyl);
613 partp->dp_ssect = DOSSECT(tsec,tcyl);
614 partp->dp_shd = thd;
617 tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect);
618 thd = partp->dp_ehd;
619 tsec = DPSECT(partp->dp_esect);
620 Decimal("ending cylinder", tcyl, tmp);
621 Decimal("ending head", thd, tmp);
622 Decimal("ending sector", tsec, tmp);
623 if (tcyl > MAXCYL && C_flag == 0) {
624 printf("Warning: ending cylinder wraps, using all 1's\n");
625 partp->dp_ecyl = -1;
626 partp->dp_esect = -1;
627 partp->dp_ehd = -1;
628 } else {
629 partp->dp_ecyl = DOSCYL(tcyl);
630 partp->dp_esect = DOSSECT(tsec,tcyl);
631 partp->dp_ehd = thd;
633 } else
634 dos(partp);
636 print_part(i);
637 } while (!ok("Are we happy with this entry?"));
641 static void
642 print_params(void)
644 printf("parameters extracted from device are:\n");
645 printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
646 ,cyls,heads,sectors,cylsecs);
647 if((dos_sectors > 63) || (dos_cyls > 1023) || (dos_heads > 255))
648 printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
649 printf("parameters to be used for BIOS calculations are:\n");
650 printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
651 ,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
654 static void
655 change_active(int which)
657 struct dos_partition *partp = &mboot.parts[0];
658 int active, i, new, tmp;
660 active = -1;
661 for (i = 0; i < NDOSPART; i++) {
662 if ((partp[i].dp_flag & ACTIVE) == 0)
663 continue;
664 printf("Partition %d is marked active\n", i + 1);
665 if (active == -1)
666 active = i + 1;
668 if (a_flag && which != -1)
669 active = which;
670 else if (active == -1)
671 active = 1;
673 if (!ok("Do you want to change the active partition?"))
674 return;
675 setactive:
676 do {
677 new = active;
678 Decimal("active partition", new, tmp);
679 if (new < 1 || new > 4) {
680 printf("Active partition number must be in range 1-4."
681 " Try again.\n");
682 goto setactive;
684 active = new;
685 } while (!ok("Are you happy with this choice"));
686 for (i = 0; i < NDOSPART; i++)
687 partp[i].dp_flag = 0;
688 if (active > 0 && active <= NDOSPART)
689 partp[active-1].dp_flag = ACTIVE;
692 static void
693 change_code(void)
695 if (ok("Do you want to change the boot code?"))
696 init_boot();
699 void
700 get_params_to_use(void)
702 int tmp;
703 print_params();
704 if (ok("Do you want to change our idea of what BIOS thinks ?"))
708 Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
709 Decimal("BIOS's idea of #heads", dos_heads, tmp);
710 Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
711 dos_cylsecs = dos_heads * dos_sectors;
712 print_params();
714 while(!ok("Are you happy with this choice"));
719 /***********************************************\
720 * Change real numbers into strange dos numbers *
721 \***********************************************/
722 static void
723 dos(struct dos_partition *partp)
725 int cy, sec;
726 u_int32_t end;
728 if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) {
729 memcpy(partp, &mtpart, sizeof(*partp));
730 return;
733 /* Start c/h/s. */
734 cy = partp->dp_start / dos_cylsecs;
735 sec = partp->dp_start % dos_sectors + 1;
736 if (cy > MAXCYL && C_flag == 0) {
737 printf("Warning: starting cylinder wraps, using all 1's\n");
738 partp->dp_shd = -1;
739 partp->dp_scyl = -1;
740 partp->dp_ssect = -1;
741 } else {
742 partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors;
743 partp->dp_scyl = DOSCYL(cy);
744 partp->dp_ssect = DOSSECT(sec, cy);
747 /* End c/h/s. */
748 end = partp->dp_start + partp->dp_size - 1;
749 cy = end / dos_cylsecs;
750 sec = end % dos_sectors + 1;
751 if (cy > MAXCYL && C_flag == 0) {
752 printf("Warning: ending cylinder wraps, using all 1's\n");
753 partp->dp_ehd = -1;
754 partp->dp_ecyl = -1;
755 partp->dp_esect = -1;
756 } else {
757 partp->dp_ehd = end % dos_cylsecs / dos_sectors;
758 partp->dp_ecyl = DOSCYL(cy);
759 partp->dp_esect = DOSSECT(sec, cy);
763 int fd;
765 /* Getting device status */
767 static int
768 open_disk(int u_flag)
770 struct stat st;
772 if (stat(disk, &st) == -1) {
773 if (errno == ENOENT)
774 return -2;
775 warnx("can't get file status of %s", disk);
776 return -1;
778 if ( !(st.st_mode & S_IFCHR) && p_flag == 0 )
779 warnx("device %s is not character special", disk);
780 if ((fd = open(disk,
781 a_flag || I_flag || B_flag || u_flag ? O_RDWR : O_RDONLY)) == -1) {
782 if(errno == ENXIO)
783 return -2;
784 warnx("can't open device %s", disk);
785 return -1;
787 if (get_params() == -1) {
788 warnx("can't get disk parameters on %s", disk);
789 return -1;
791 return fd;
794 static ssize_t
795 read_disk(off_t sector, void *buf)
797 lseek(fd,(sector * 512), 0);
798 if( secsize == 0 )
799 for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
801 /* try the read */
802 int size = read(fd, buf, secsize);
803 if( size == secsize )
804 /* it worked so return */
805 return secsize;
807 else
808 return read( fd, buf, secsize );
810 /* we failed to read at any of the sizes */
811 return -1;
814 static ssize_t
815 write_disk(off_t sector, void *buf)
817 lseek(fd,(sector * 512), 0);
818 /* write out in the size that the read_disk found worked */
819 return write(fd, buf, secsize);
822 static int
823 get_params(void)
825 struct partinfo partinfo; /* disk parameters */
826 struct stat st;
829 * NOTE: When faking up the CHS for a file image (e.g. for USB),
830 * we must use max values. If we do not then an overflowed
831 * cylinder count will, by convention, set the CHS fields to
832 * all 1's. The heads and sectors in the CHS fields will then
833 * exceed the basic geometry which can cause BIOSes to brick.
835 if (ioctl(fd, DIOCGPART, &partinfo) == -1) {
836 if (p_flag && fstat(fd, &st) == 0 && st.st_size) {
837 sectors = 63;
838 heads = 255;
839 cylsecs = heads * sectors;
840 cyls = st.st_size / 512 / cylsecs;
841 } else {
842 warnx("can't get disk parameters on %s; supplying dummy ones",
843 disk);
844 heads = 1;
845 cylsecs = heads * sectors;
847 } else {
848 cyls = partinfo.d_ncylinders;
849 heads = partinfo.d_nheads;
850 sectors = partinfo.d_secpertrack;
851 cylsecs = heads * sectors;
852 secsize = partinfo.media_blksize;
854 dos_cyls = cyls;
855 dos_heads = heads;
856 dos_sectors = sectors;
857 dos_cylsecs = cylsecs;
858 disksecs = (int64_t)cyls * heads * sectors;
859 return (disksecs);
863 static int
864 read_s0(void)
866 mboot.bootinst_size = secsize;
867 if (mboot.bootinst != NULL)
868 free(mboot.bootinst);
869 if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
870 warnx("unable to allocate buffer to read fdisk "
871 "partition table");
872 return -1;
874 if (read_disk(0, mboot.bootinst) == -1) {
875 warnx("can't read fdisk partition table");
876 return -1;
878 if (*(uint16_t *)&mboot.bootinst[MBRSIGOFF] != BOOT_MAGIC) {
879 warnx("invalid fdisk partition table found");
880 /* So should we initialize things */
881 return -1;
883 memcpy(mboot.parts, &mboot.bootinst[DOSPARTOFF], sizeof(mboot.parts));
884 return 0;
887 static int
888 write_s0(void)
890 #ifdef NOT_NOW
891 int flag;
892 #endif
893 int sector;
895 if (iotest) {
896 print_s0(-1);
897 return 0;
899 memcpy(&mboot.bootinst[DOSPARTOFF], mboot.parts, sizeof(mboot.parts));
901 * write enable label sector before write (if necessary),
902 * disable after writing.
903 * needed if the disklabel protected area also protects
904 * sector 0. (e.g. empty disk)
906 #ifdef NOT_NOW
907 flag = 1;
908 if (ioctl(fd, DIOCWLABEL, &flag) < 0)
909 warn("ioctl DIOCWLABEL");
910 #endif
911 for(sector = 0; sector < mboot.bootinst_size / secsize; sector++)
912 if (write_disk(sector,
913 &mboot.bootinst[sector * secsize]) == -1) {
914 warn("can't write fdisk partition table");
915 return -1;
916 #ifdef NOT_NOW
917 flag = 0;
918 ioctl(fd, DIOCWLABEL, &flag);
919 #endif
921 #ifdef NOT_NOW
922 flag = 0;
923 ioctl(fd, DIOCWLABEL, &flag);
924 #endif
925 return(0);
929 static int
930 ok(char *str)
932 printf("%s [n] ", str);
933 fflush(stdout);
934 if (fgets(lbuf, LBUF, stdin) == NULL)
935 exit(1);
936 lbuf[strlen(lbuf)-1] = 0;
938 if (*lbuf &&
939 (!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
940 !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
941 return 1;
942 else
943 return 0;
946 static int
947 decimal(char *str, int *num, int deflt)
949 int acc = 0, c;
950 char *cp;
952 while (1) {
953 printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
954 fflush(stdout);
955 if (fgets(lbuf, LBUF, stdin) == NULL)
956 exit(1);
957 lbuf[strlen(lbuf)-1] = 0;
959 if (!*lbuf)
960 return 0;
962 cp = lbuf;
963 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
964 if (!c)
965 return 0;
966 while ((c = *cp++)) {
967 if (c <= '9' && c >= '0')
968 acc = acc * 10 + c - '0';
969 else
970 break;
972 if (c == ' ' || c == '\t')
973 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
974 if (!c) {
975 *num = acc;
976 return 1;
977 } else
978 printf("%s is an invalid decimal number. Try again.\n",
979 lbuf);
984 #if 0
985 static int
986 hex(char *str, int *num, int deflt)
988 int acc = 0, c;
989 char *cp;
991 while (1) {
992 printf("Supply a hex value for \"%s\" [%x] ", str, deflt);
993 fgets(lbuf, LBUF, stdin);
994 lbuf[strlen(lbuf)-1] = 0;
996 if (!*lbuf)
997 return 0;
999 cp = lbuf;
1000 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
1001 if (!c)
1002 return 0;
1003 while ((c = *cp++)) {
1004 if (c <= '9' && c >= '0')
1005 acc = (acc << 4) + c - '0';
1006 else if (c <= 'f' && c >= 'a')
1007 acc = (acc << 4) + c - 'a' + 10;
1008 else if (c <= 'F' && c >= 'A')
1009 acc = (acc << 4) + c - 'A' + 10;
1010 else
1011 break;
1013 if (c == ' ' || c == '\t')
1014 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
1015 if (!c) {
1016 *num = acc;
1017 return 1;
1018 } else
1019 printf("%s is an invalid hex number. Try again.\n",
1020 lbuf);
1025 static int
1026 string(char *str, char **ans)
1028 int c;
1029 char *cp = lbuf;
1031 while (1) {
1032 printf("Supply a string value for \"%s\" [%s] ", str, *ans);
1033 fgets(lbuf, LBUF, stdin);
1034 lbuf[strlen(lbuf)-1] = 0;
1036 if (!*lbuf)
1037 return 0;
1039 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
1040 if (c == '"') {
1041 c = *++cp;
1042 *ans = cp;
1043 while ((c = *cp) && c != '"') cp++;
1044 } else {
1045 *ans = cp;
1046 while ((c = *cp) && c != ' ' && c != '\t') cp++;
1049 if (c)
1050 *cp = 0;
1051 return 1;
1054 #endif
1056 static char *
1057 get_type(int type)
1059 int numentries = (sizeof(part_types)/sizeof(struct part_type));
1060 int counter = 0;
1061 struct part_type *ptr = part_types;
1064 while(counter < numentries)
1066 if(ptr->type == type)
1068 return(ptr->name);
1070 ptr++;
1071 counter++;
1073 return("unknown");
1077 static void
1078 parse_config_line(char *line, CMD *command)
1080 char *cp, *end;
1082 cp = line;
1083 while (1) /* dirty trick used to insure one exit point for this
1084 function */
1086 memset(command, 0, sizeof(*command));
1088 while (isspace(*cp)) ++cp;
1089 if (*cp == '\0' || *cp == '#')
1091 break;
1093 command->cmd = *cp++;
1096 * Parse args
1098 while (1)
1100 while (isspace(*cp)) ++cp;
1101 if (*cp == '#')
1103 break; /* found comment */
1105 if (isalpha(*cp))
1107 command->args[command->n_args].argtype = *cp++;
1109 if (!isdigit(*cp))
1111 break; /* assume end of line */
1113 end = NULL;
1114 command->args[command->n_args].arg_val = strtol(cp, &end, 0);
1115 if (cp == end)
1117 break; /* couldn't parse number */
1119 cp = end;
1120 command->n_args++;
1122 break;
1127 static int
1128 process_geometry(CMD *command)
1130 int status = 1, i;
1132 while (1)
1134 geom_processed = 1;
1135 if (part_processed)
1137 warnx(
1138 "ERROR line %d: the geometry specification line must occur before\n\
1139 all partition specifications",
1140 current_line_number);
1141 status = 0;
1142 break;
1144 if (command->n_args != 3)
1146 warnx("ERROR line %d: incorrect number of geometry args",
1147 current_line_number);
1148 status = 0;
1149 break;
1151 dos_cyls = -1;
1152 dos_heads = -1;
1153 dos_sectors = -1;
1154 for (i = 0; i < 3; ++i)
1156 switch (command->args[i].argtype)
1158 case 'c':
1159 dos_cyls = command->args[i].arg_val;
1160 break;
1161 case 'h':
1162 dos_heads = command->args[i].arg_val;
1163 break;
1164 case 's':
1165 dos_sectors = command->args[i].arg_val;
1166 break;
1167 default:
1168 warnx(
1169 "ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1170 current_line_number, command->args[i].argtype,
1171 command->args[i].argtype);
1172 status = 0;
1173 break;
1176 if (status == 0)
1178 break;
1181 dos_cylsecs = dos_heads * dos_sectors;
1184 * Do sanity checks on parameter values
1186 if (dos_cyls < 0)
1188 warnx("ERROR line %d: number of cylinders not specified",
1189 current_line_number);
1190 status = 0;
1192 if (dos_cyls == 0 || dos_cyls > 1024)
1194 warnx(
1195 "WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1196 (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1197 is dedicated to DragonFly)",
1198 current_line_number, dos_cyls);
1201 if (dos_heads < 0)
1203 warnx("ERROR line %d: number of heads not specified",
1204 current_line_number);
1205 status = 0;
1207 else if (dos_heads < 1 || dos_heads > 256)
1209 warnx("ERROR line %d: number of heads must be within (1-256)",
1210 current_line_number);
1211 status = 0;
1214 if (dos_sectors < 0)
1216 warnx("ERROR line %d: number of sectors not specified",
1217 current_line_number);
1218 status = 0;
1220 else if (dos_sectors < 1 || dos_sectors > 63)
1222 warnx("ERROR line %d: number of sectors must be within (1-63)",
1223 current_line_number);
1224 status = 0;
1227 break;
1229 return (status);
1233 static int
1234 process_partition(CMD *command)
1236 int status = 0, partition;
1237 u_int32_t prev_head_boundary, prev_cyl_boundary;
1238 u_int32_t adj_size, max_end;
1239 struct dos_partition *partp;
1241 while (1)
1243 part_processed = 1;
1244 if (command->n_args != 4)
1246 warnx("ERROR line %d: incorrect number of partition args",
1247 current_line_number);
1248 break;
1250 partition = command->args[0].arg_val;
1251 if (partition < 1 || partition > 4)
1253 warnx("ERROR line %d: invalid partition number %d",
1254 current_line_number, partition);
1255 break;
1257 partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1258 bzero((char *)partp, sizeof (struct dos_partition));
1259 partp->dp_typ = command->args[1].arg_val;
1260 partp->dp_start = command->args[2].arg_val;
1261 partp->dp_size = command->args[3].arg_val;
1262 max_end = partp->dp_start + partp->dp_size;
1264 if (partp->dp_typ == 0)
1267 * Get out, the partition is marked as unused.
1270 * Insure that it's unused.
1272 bzero((char *)partp, sizeof (struct dos_partition));
1273 status = 1;
1274 break;
1278 * Adjust start upwards, if necessary, to fall on an head boundary.
1280 if (partp->dp_start % dos_sectors != 0)
1282 prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1283 if (max_end < dos_sectors ||
1284 prev_head_boundary > max_end - dos_sectors)
1287 * Can't go past end of partition
1289 warnx(
1290 "ERROR line %d: unable to adjust start of partition %d to fall on\n\
1291 a head boundary",
1292 current_line_number, partition);
1293 break;
1295 warnx(
1296 "WARNING: adjusting start offset of partition %d\n\
1297 from %u to %u, to fall on a head boundary",
1298 partition, (u_int)partp->dp_start,
1299 (u_int)(prev_head_boundary + dos_sectors));
1300 partp->dp_start = prev_head_boundary + dos_sectors;
1304 * Adjust size downwards, if necessary, to fall on a cylinder
1305 * boundary.
1307 prev_cyl_boundary =
1308 ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1309 if (prev_cyl_boundary > partp->dp_start)
1310 adj_size = prev_cyl_boundary - partp->dp_start;
1311 else
1313 warnx(
1314 "ERROR: could not adjust partition to start on a head boundary\n\
1315 and end on a cylinder boundary.");
1316 return (0);
1318 if (adj_size != partp->dp_size)
1320 warnx(
1321 "WARNING: adjusting size of partition %d from %u to %u\n\
1322 to end on a cylinder boundary",
1323 partition, (u_int)partp->dp_size, (u_int)adj_size);
1324 partp->dp_size = adj_size;
1326 if (partp->dp_size == 0)
1328 warnx("ERROR line %d: size of partition %d is zero",
1329 current_line_number, partition);
1330 break;
1333 dos(partp);
1334 status = 1;
1335 break;
1337 return (status);
1341 static int
1342 process_active(CMD *command)
1344 int status = 0, partition, i;
1345 struct dos_partition *partp;
1347 while (1)
1349 active_processed = 1;
1350 if (command->n_args != 1)
1352 warnx("ERROR line %d: incorrect number of active args",
1353 current_line_number);
1354 status = 0;
1355 break;
1357 partition = command->args[0].arg_val;
1358 if (partition < 1 || partition > 4)
1360 warnx("ERROR line %d: invalid partition number %d",
1361 current_line_number, partition);
1362 break;
1365 * Reset active partition
1367 partp = ((struct dos_partition *) &mboot.parts);
1368 for (i = 0; i < NDOSPART; i++)
1369 partp[i].dp_flag = 0;
1370 partp[partition-1].dp_flag = ACTIVE;
1372 status = 1;
1373 break;
1375 return (status);
1379 static int
1380 process_line(char *line)
1382 CMD command;
1383 int status = 1;
1385 while (1)
1387 parse_config_line(line, &command);
1388 switch (command.cmd)
1390 case 0:
1392 * Comment or blank line
1394 break;
1395 case 'g':
1397 * Set geometry
1399 status = process_geometry(&command);
1400 break;
1401 case 'p':
1402 status = process_partition(&command);
1403 break;
1404 case 'a':
1405 status = process_active(&command);
1406 break;
1407 default:
1408 status = 0;
1409 break;
1411 break;
1413 return (status);
1417 static int
1418 read_config(char *config_file)
1420 FILE *fp = NULL;
1421 int status = 1;
1422 char buf[1010];
1424 while (1) /* dirty trick used to insure one exit point for this
1425 function */
1427 if (strcmp(config_file, "-") != 0)
1430 * We're not reading from stdin
1432 if ((fp = fopen(config_file, "r")) == NULL)
1434 status = 0;
1435 break;
1438 else
1440 fp = stdin;
1442 current_line_number = 0;
1443 while (!feof(fp))
1445 if (fgets(buf, sizeof(buf), fp) == NULL)
1447 break;
1449 ++current_line_number;
1450 status = process_line(buf);
1451 if (status == 0)
1453 break;
1456 break;
1458 if (fp)
1461 * It doesn't matter if we're reading from stdin, as we've reached EOF
1463 fclose(fp);
1465 return (status);
1469 static void
1470 reset_boot(void)
1472 int i;
1473 struct dos_partition *partp;
1475 init_boot();
1476 for (i = 0; i < 4; ++i)
1478 partp = ((struct dos_partition *) &mboot.parts) + i;
1479 bzero((char *)partp, sizeof (struct dos_partition));
1483 static int
1484 sanitize_partition(struct dos_partition *partp)
1486 u_int32_t prev_head_boundary, prev_cyl_boundary;
1487 u_int32_t max_end, size, start;
1489 start = partp->dp_start;
1490 size = partp->dp_size;
1491 max_end = start + size;
1492 /* Only allow a zero size if the partition is being marked unused. */
1493 if (size == 0) {
1494 if (start == 0 && partp->dp_typ == 0)
1495 return (1);
1496 warnx("ERROR: size of partition is zero");
1497 return (0);
1499 /* Return if no adjustment is necessary. */
1500 if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0)
1501 return (1);
1503 if (start == 0) {
1504 warnx("WARNING: partition overlaps with partition table");
1505 if (ok("Correct this automatically?"))
1506 start = dos_sectors;
1508 if (start % dos_sectors != 0)
1509 warnx("WARNING: partition does not start on a head boundary");
1510 if ((start +size) % dos_sectors != 0)
1511 warnx("WARNING: partition does not end on a cylinder boundary");
1512 warnx("WARNING: this may confuse the BIOS or some operating systems");
1513 if (!ok("Correct this automatically?"))
1514 return (1);
1517 * Adjust start upwards, if necessary, to fall on an head boundary.
1519 if (start % dos_sectors != 0) {
1520 prev_head_boundary = start / dos_sectors * dos_sectors;
1521 if (max_end < dos_sectors ||
1522 prev_head_boundary >= max_end - dos_sectors) {
1524 * Can't go past end of partition
1526 warnx(
1527 "ERROR: unable to adjust start of partition to fall on a head boundary");
1528 return (0);
1530 start = prev_head_boundary + dos_sectors;
1534 * Adjust size downwards, if necessary, to fall on a cylinder
1535 * boundary.
1537 prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs;
1538 if (prev_cyl_boundary > start)
1539 size = prev_cyl_boundary - start;
1540 else {
1541 warnx("ERROR: could not adjust partition to start on a head boundary\n\
1542 and end on a cylinder boundary.");
1543 return (0);
1546 /* Finally, commit any changes to partp and return. */
1547 if (start != partp->dp_start) {
1548 warnx("WARNING: adjusting start offset of partition to %u",
1549 (u_int)start);
1550 partp->dp_start = start;
1552 if (size != partp->dp_size) {
1553 warnx("WARNING: adjusting size of partition to %u", (u_int)size);
1554 partp->dp_size = size;
1557 return (1);