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