Merge from vendor branch NCURSES:
[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.10 2004/12/18 21:43:38 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()
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(partp)
702         struct dos_partition *partp;
703 {
704         int cy, sec;
705         u_int32_t end;
706
707         if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) {
708                 memcpy(partp, &mtpart, sizeof(*partp));
709                 return;
710         }
711
712         /* Start c/h/s. */
713         partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors;
714         cy = partp->dp_start / dos_cylsecs;
715         sec = partp->dp_start % dos_sectors + 1;
716         partp->dp_scyl = DOSCYL(cy);
717         partp->dp_ssect = DOSSECT(sec, cy);
718
719         /* End c/h/s. */
720         end = partp->dp_start + partp->dp_size - 1;
721         partp->dp_ehd = end % dos_cylsecs / dos_sectors;
722         cy = end / dos_cylsecs;
723         sec = end % dos_sectors + 1;
724         partp->dp_ecyl = DOSCYL(cy);
725         partp->dp_esect = DOSSECT(sec, cy);
726 }
727
728 int fd;
729
730         /* Getting device status */
731
732 static int
733 open_disk(int u_flag)
734 {
735         struct stat     st;
736
737         if (stat(disk, &st) == -1) {
738                 if (errno == ENOENT)
739                         return -2;
740                 warnx("can't get file status of %s", disk);
741                 return -1;
742         }
743         if ( !(st.st_mode & S_IFCHR) && p_flag == 0 )
744                 warnx("device %s is not character special", disk);
745         if ((fd = open(disk,
746             a_flag || I_flag || B_flag || u_flag ? O_RDWR : O_RDONLY)) == -1) {
747                 if(errno == ENXIO)
748                         return -2;
749                 warnx("can't open device %s", disk);
750                 return -1;
751         }
752         if (get_params() == -1) {
753                 warnx("can't get disk parameters on %s", disk);
754                 return -1;
755         }
756         return fd;
757 }
758
759 static ssize_t
760 read_disk(off_t sector, void *buf)
761 {
762         lseek(fd,(sector * 512), 0);
763         if( secsize == 0 )
764                 for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 )
765                         {
766                         /* try the read */
767                         int size = read(fd, buf, secsize);
768                         if( size == secsize )
769                                 /* it worked so return */
770                                 return secsize;
771                         }
772         else
773                 return read( fd, buf, secsize );
774
775         /* we failed to read at any of the sizes */
776         return -1;
777 }
778
779 static ssize_t
780 write_disk(off_t sector, void *buf)
781 {
782         lseek(fd,(sector * 512), 0);
783         /* write out in the size that the read_disk found worked */
784         return write(fd, buf, secsize);
785 }
786
787 static int
788 get_params(void)
789 {
790     struct stat st;
791
792     if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
793         if (p_flag && fstat(fd, &st) == 0 && st.st_size) {
794             sectors = 63;
795             heads = 16;
796             cylsecs = heads * sectors;
797             cyls = st.st_size / 512 / cylsecs;
798         } else {
799             warnx("can't get disk parameters on %s; supplying dummy ones", disk);
800             cyls = 1;
801             heads = 1;
802             sectors = 1;
803             cylsecs = heads * sectors;
804         }
805     } else {
806         cyls = disklabel.d_ncylinders;
807         heads = disklabel.d_ntracks;
808         sectors = disklabel.d_nsectors;
809         cylsecs = heads * sectors;
810     }
811     dos_cyls = cyls;
812     dos_heads = heads;
813     dos_sectors = sectors;
814     dos_cylsecs = cylsecs;
815     disksecs = cyls * heads * sectors;
816     return (disksecs);
817 }
818 \f
819
820 static int
821 read_s0(void)
822 {
823         mboot.bootinst_size = secsize;
824         if (mboot.bootinst != NULL)
825                 free(mboot.bootinst);
826         if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) {
827                 warnx("unable to allocate buffer to read fdisk "
828                       "partition table");
829                 return -1;
830         }
831         if (read_disk(0, mboot.bootinst) == -1) {
832                 warnx("can't read fdisk partition table");
833                 return -1;
834         }
835         if (*(uint16_t *)&mboot.bootinst[MBRSIGOFF] != BOOT_MAGIC) {
836                 warnx("invalid fdisk partition table found");
837                 /* So should we initialize things */
838                 return -1;
839         }
840         memcpy(mboot.parts, &mboot.bootinst[DOSPARTOFF], sizeof(mboot.parts));
841         return 0;
842 }
843
844 static int
845 write_s0(void)
846 {
847 #ifdef NOT_NOW
848         int     flag;
849 #endif
850         int     sector;
851
852         if (iotest) {
853                 print_s0(-1);
854                 return 0;
855         }
856         memcpy(&mboot.bootinst[DOSPARTOFF], mboot.parts, sizeof(mboot.parts));
857         /*
858          * write enable label sector before write (if necessary),
859          * disable after writing.
860          * needed if the disklabel protected area also protects
861          * sector 0. (e.g. empty disk)
862          */
863 #ifdef NOT_NOW
864         flag = 1;
865         if (ioctl(fd, DIOCWLABEL, &flag) < 0)
866                 warn("ioctl DIOCWLABEL");
867 #endif
868         for(sector = 0; sector < mboot.bootinst_size / secsize; sector++) 
869                 if (write_disk(sector,
870                                &mboot.bootinst[sector * secsize]) == -1) {
871                         warn("can't write fdisk partition table");
872                         return -1;
873 #ifdef NOT_NOW
874                         flag = 0;
875                         ioctl(fd, DIOCWLABEL, &flag);
876 #endif
877                 }
878 #ifdef NOT_NOW
879         flag = 0;
880         ioctl(fd, DIOCWLABEL, &flag);
881 #endif
882         return(0);
883 }
884
885
886 static int
887 ok(str)
888 char *str;
889 {
890         printf("%s [n] ", str);
891         fflush(stdout);
892         if (fgets(lbuf, LBUF, stdin) == NULL)
893                 exit(1);
894         lbuf[strlen(lbuf)-1] = 0;
895
896         if (*lbuf &&
897                 (!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
898                  !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
899                 return 1;
900         else
901                 return 0;
902 }
903
904 static int
905 decimal(char *str, int *num, int deflt)
906 {
907 int acc = 0, c;
908 char *cp;
909
910         while (1) {
911                 printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
912                 fflush(stdout);
913                 if (fgets(lbuf, LBUF, stdin) == NULL)
914                         exit(1);
915                 lbuf[strlen(lbuf)-1] = 0;
916
917                 if (!*lbuf)
918                         return 0;
919
920                 cp = lbuf;
921                 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
922                 if (!c)
923                         return 0;
924                 while ((c = *cp++)) {
925                         if (c <= '9' && c >= '0')
926                                 acc = acc * 10 + c - '0';
927                         else
928                                 break;
929                 }
930                 if (c == ' ' || c == '\t')
931                         while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
932                 if (!c) {
933                         *num = acc;
934                         return 1;
935                 } else
936                         printf("%s is an invalid decimal number.  Try again.\n",
937                                 lbuf);
938         }
939
940 }
941
942 #if 0
943 static int
944 hex(char *str, int *num, int deflt)
945 {
946 int acc = 0, c;
947 char *cp;
948
949         while (1) {
950                 printf("Supply a hex value for \"%s\" [%x] ", str, deflt);
951                 fgets(lbuf, LBUF, stdin);
952                 lbuf[strlen(lbuf)-1] = 0;
953
954                 if (!*lbuf)
955                         return 0;
956
957                 cp = lbuf;
958                 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
959                 if (!c)
960                         return 0;
961                 while ((c = *cp++)) {
962                         if (c <= '9' && c >= '0')
963                                 acc = (acc << 4) + c - '0';
964                         else if (c <= 'f' && c >= 'a')
965                                 acc = (acc << 4) + c - 'a' + 10;
966                         else if (c <= 'F' && c >= 'A')
967                                 acc = (acc << 4) + c - 'A' + 10;
968                         else
969                                 break;
970                 }
971                 if (c == ' ' || c == '\t')
972                         while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
973                 if (!c) {
974                         *num = acc;
975                         return 1;
976                 } else
977                         printf("%s is an invalid hex number.  Try again.\n",
978                                 lbuf);
979         }
980
981 }
982
983 static int
984 string(char *str, char **ans)
985 {
986 int c;
987 char *cp = lbuf;
988
989         while (1) {
990                 printf("Supply a string value for \"%s\" [%s] ", str, *ans);
991                 fgets(lbuf, LBUF, stdin);
992                 lbuf[strlen(lbuf)-1] = 0;
993
994                 if (!*lbuf)
995                         return 0;
996
997                 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
998                 if (c == '"') {
999                         c = *++cp;
1000                         *ans = cp;
1001                         while ((c = *cp) && c != '"') cp++;
1002                 } else {
1003                         *ans = cp;
1004                         while ((c = *cp) && c != ' ' && c != '\t') cp++;
1005                 }
1006
1007                 if (c)
1008                         *cp = 0;
1009                 return 1;
1010         }
1011 }
1012 #endif
1013
1014 static char *
1015 get_type(int type)
1016 {
1017         int     numentries = (sizeof(part_types)/sizeof(struct part_type));
1018         int     counter = 0;
1019         struct  part_type *ptr = part_types;
1020
1021
1022         while(counter < numentries)
1023         {
1024                 if(ptr->type == type)
1025                 {
1026                         return(ptr->name);
1027                 }
1028                 ptr++;
1029                 counter++;
1030         }
1031         return("unknown");
1032 }
1033
1034
1035 static void
1036 parse_config_line(line, command)
1037     char        *line;
1038     CMD         *command;
1039 {
1040     char        *cp, *end;
1041
1042     cp = line;
1043     while (1)   /* dirty trick used to insure one exit point for this
1044                    function */
1045     {
1046         memset(command, 0, sizeof(*command));
1047
1048         while (isspace(*cp)) ++cp;
1049         if (*cp == '\0' || *cp == '#')
1050         {
1051             break;
1052         }
1053         command->cmd = *cp++;
1054
1055         /*
1056          * Parse args
1057          */
1058         while (1)
1059         {
1060             while (isspace(*cp)) ++cp;
1061             if (*cp == '#')
1062             {
1063                 break;          /* found comment */
1064             }
1065             if (isalpha(*cp))
1066             {
1067                 command->args[command->n_args].argtype = *cp++;
1068             }
1069             if (!isdigit(*cp))
1070             {
1071                 break;          /* assume end of line */
1072             }
1073             end = NULL;
1074             command->args[command->n_args].arg_val = strtol(cp, &end, 0);
1075             if (cp == end)
1076             {
1077                 break;          /* couldn't parse number */
1078             }
1079             cp = end;
1080             command->n_args++;
1081         }
1082         break;
1083     }
1084 }
1085
1086
1087 static int
1088 process_geometry(command)
1089     CMD         *command;
1090 {
1091     int         status = 1, i;
1092
1093     while (1)
1094     {
1095         geom_processed = 1;
1096         if (part_processed)
1097         {
1098             warnx(
1099         "ERROR line %d: the geometry specification line must occur before\n\
1100     all partition specifications",
1101                     current_line_number);
1102             status = 0;
1103             break;
1104         }
1105         if (command->n_args != 3)
1106         {
1107             warnx("ERROR line %d: incorrect number of geometry args",
1108                     current_line_number);
1109             status = 0;
1110             break;
1111         }
1112         dos_cyls = -1;
1113         dos_heads = -1;
1114         dos_sectors = -1;
1115         for (i = 0; i < 3; ++i)
1116         {
1117             switch (command->args[i].argtype)
1118             {
1119             case 'c':
1120                 dos_cyls = command->args[i].arg_val;
1121                 break;
1122             case 'h':
1123                 dos_heads = command->args[i].arg_val;
1124                 break;
1125             case 's':
1126                 dos_sectors = command->args[i].arg_val;
1127                 break;
1128             default:
1129                 warnx(
1130                 "ERROR line %d: unknown geometry arg type: '%c' (0x%02x)",
1131                         current_line_number, command->args[i].argtype,
1132                         command->args[i].argtype);
1133                 status = 0;
1134                 break;
1135             }
1136         }
1137         if (status == 0)
1138         {
1139             break;
1140         }
1141
1142         dos_cylsecs = dos_heads * dos_sectors;
1143
1144         /*
1145          * Do sanity checks on parameter values
1146          */
1147         if (dos_cyls < 0)
1148         {
1149             warnx("ERROR line %d: number of cylinders not specified",
1150                     current_line_number);
1151             status = 0;
1152         }
1153         if (dos_cyls == 0 || dos_cyls > 1024)
1154         {
1155             warnx(
1156         "WARNING line %d: number of cylinders (%d) may be out-of-range\n\
1157     (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\
1158     is dedicated to DragonFly)",
1159                     current_line_number, dos_cyls);
1160         }
1161
1162         if (dos_heads < 0)
1163         {
1164             warnx("ERROR line %d: number of heads not specified",
1165                     current_line_number);
1166             status = 0;
1167         }
1168         else if (dos_heads < 1 || dos_heads > 256)
1169         {
1170             warnx("ERROR line %d: number of heads must be within (1-256)",
1171                     current_line_number);
1172             status = 0;
1173         }
1174
1175         if (dos_sectors < 0)
1176         {
1177             warnx("ERROR line %d: number of sectors not specified",
1178                     current_line_number);
1179             status = 0;
1180         }
1181         else if (dos_sectors < 1 || dos_sectors > 63)
1182         {
1183             warnx("ERROR line %d: number of sectors must be within (1-63)",
1184                     current_line_number);
1185             status = 0;
1186         }
1187
1188         break;
1189     }
1190     return (status);
1191 }
1192
1193
1194 static int
1195 process_partition(command)
1196     CMD         *command;
1197 {
1198     int                         status = 0, partition;
1199     u_int32_t                   prev_head_boundary, prev_cyl_boundary;
1200     u_int32_t                   adj_size, max_end;
1201     struct dos_partition        *partp;
1202
1203     while (1)
1204     {
1205         part_processed = 1;
1206         if (command->n_args != 4)
1207         {
1208             warnx("ERROR line %d: incorrect number of partition args",
1209                     current_line_number);
1210             break;
1211         }
1212         partition = command->args[0].arg_val;
1213         if (partition < 1 || partition > 4)
1214         {
1215             warnx("ERROR line %d: invalid partition number %d",
1216                     current_line_number, partition);
1217             break;
1218         }
1219         partp = ((struct dos_partition *) &mboot.parts) + partition - 1;
1220         bzero((char *)partp, sizeof (struct dos_partition));
1221         partp->dp_typ = command->args[1].arg_val;
1222         partp->dp_start = command->args[2].arg_val;
1223         partp->dp_size = command->args[3].arg_val;
1224         max_end = partp->dp_start + partp->dp_size;
1225
1226         if (partp->dp_typ == 0)
1227         {
1228             /*
1229              * Get out, the partition is marked as unused.
1230              */
1231             /*
1232              * Insure that it's unused.
1233              */
1234             bzero((char *)partp, sizeof (struct dos_partition));
1235             status = 1;
1236             break;
1237         }
1238
1239         /*
1240          * Adjust start upwards, if necessary, to fall on an head boundary.
1241          */
1242         if (partp->dp_start % dos_sectors != 0)
1243         {
1244             prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors;
1245             if (max_end < dos_sectors ||
1246                 prev_head_boundary > max_end - dos_sectors)
1247             {
1248                 /*
1249                  * Can't go past end of partition
1250                  */
1251                 warnx(
1252         "ERROR line %d: unable to adjust start of partition %d to fall on\n\
1253     a head boundary",
1254                         current_line_number, partition);
1255                 break;
1256             }
1257             warnx(
1258         "WARNING: adjusting start offset of partition %d\n\
1259     from %u to %u, to fall on a head boundary",
1260                     partition, (u_int)partp->dp_start,
1261                     (u_int)(prev_head_boundary + dos_sectors));
1262             partp->dp_start = prev_head_boundary + dos_sectors;
1263         }
1264
1265         /*
1266          * Adjust size downwards, if necessary, to fall on a cylinder
1267          * boundary.
1268          */
1269         prev_cyl_boundary =
1270             ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs;
1271         if (prev_cyl_boundary > partp->dp_start)
1272             adj_size = prev_cyl_boundary - partp->dp_start;
1273         else
1274         {
1275             warnx(
1276         "ERROR: could not adjust partition to start on a head boundary\n\
1277     and end on a cylinder boundary.");
1278             return (0);
1279         }
1280         if (adj_size != partp->dp_size)
1281         {
1282             warnx(
1283         "WARNING: adjusting size of partition %d from %u to %u\n\
1284     to end on a cylinder boundary",
1285                     partition, (u_int)partp->dp_size, (u_int)adj_size);
1286             partp->dp_size = adj_size;
1287         }
1288         if (partp->dp_size == 0)
1289         {
1290             warnx("ERROR line %d: size of partition %d is zero",
1291                     current_line_number, partition);
1292             break;
1293         }
1294
1295         dos(partp);
1296         status = 1;
1297         break;
1298     }
1299     return (status);
1300 }
1301
1302
1303 static int
1304 process_active(command)
1305     CMD         *command;
1306 {
1307     int                         status = 0, partition, i;
1308     struct dos_partition        *partp;
1309
1310     while (1)
1311     {
1312         active_processed = 1;
1313         if (command->n_args != 1)
1314         {
1315             warnx("ERROR line %d: incorrect number of active args",
1316                     current_line_number);
1317             status = 0;
1318             break;
1319         }
1320         partition = command->args[0].arg_val;
1321         if (partition < 1 || partition > 4)
1322         {
1323             warnx("ERROR line %d: invalid partition number %d",
1324                     current_line_number, partition);
1325             break;
1326         }
1327         /*
1328          * Reset active partition
1329          */
1330         partp = ((struct dos_partition *) &mboot.parts);
1331         for (i = 0; i < NDOSPART; i++)
1332             partp[i].dp_flag = 0;
1333         partp[partition-1].dp_flag = ACTIVE;
1334
1335         status = 1;
1336         break;
1337     }
1338     return (status);
1339 }
1340
1341
1342 static int
1343 process_line(line)
1344     char        *line;
1345 {
1346     CMD         command;
1347     int         status = 1;
1348
1349     while (1)
1350     {
1351         parse_config_line(line, &command);
1352         switch (command.cmd)
1353         {
1354         case 0:
1355             /*
1356              * Comment or blank line
1357              */
1358             break;
1359         case 'g':
1360             /*
1361              * Set geometry
1362              */
1363             status = process_geometry(&command);
1364             break;
1365         case 'p':
1366             status = process_partition(&command);
1367             break;
1368         case 'a':
1369             status = process_active(&command);
1370             break;
1371         default:
1372             status = 0;
1373             break;
1374         }
1375         break;
1376     }
1377     return (status);
1378 }
1379
1380
1381 static int
1382 read_config(config_file)
1383     char *config_file;
1384 {
1385     FILE        *fp = NULL;
1386     int         status = 1;
1387     char        buf[1010];
1388
1389     while (1)   /* dirty trick used to insure one exit point for this
1390                    function */
1391     {
1392         if (strcmp(config_file, "-") != 0)
1393         {
1394             /*
1395              * We're not reading from stdin
1396              */
1397             if ((fp = fopen(config_file, "r")) == NULL)
1398             {
1399                 status = 0;
1400                 break;
1401             }
1402         }
1403         else
1404         {
1405             fp = stdin;
1406         }
1407         current_line_number = 0;
1408         while (!feof(fp))
1409         {
1410             if (fgets(buf, sizeof(buf), fp) == NULL)
1411             {
1412                 break;
1413             }
1414             ++current_line_number;
1415             status = process_line(buf);
1416             if (status == 0)
1417             {
1418                 break;
1419             }
1420         }
1421         break;
1422     }
1423     if (fp)
1424     {
1425         /*
1426          * It doesn't matter if we're reading from stdin, as we've reached EOF
1427          */
1428         fclose(fp);
1429     }
1430     return (status);
1431 }
1432
1433
1434 static void
1435 reset_boot(void)
1436 {
1437     int                         i;
1438     struct dos_partition        *partp;
1439
1440     init_boot();
1441     for (i = 0; i < 4; ++i)
1442     {
1443         partp = ((struct dos_partition *) &mboot.parts) + i;
1444         bzero((char *)partp, sizeof (struct dos_partition));
1445     }
1446 }
1447
1448 static int
1449 sanitize_partition(partp)
1450     struct dos_partition        *partp;
1451 {
1452     u_int32_t                   prev_head_boundary, prev_cyl_boundary;
1453     u_int32_t                   max_end, size, start;
1454
1455     start = partp->dp_start;
1456     size = partp->dp_size;
1457     max_end = start + size;
1458     /* Only allow a zero size if the partition is being marked unused. */
1459     if (size == 0) {
1460         if (start == 0 && partp->dp_typ == 0)
1461             return (1);
1462         warnx("ERROR: size of partition is zero");
1463         return (0);
1464     }
1465     /* Return if no adjustment is necessary. */
1466     if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0)
1467         return (1);
1468
1469     if (start == 0) {
1470             warnx("WARNING: partition overlaps with partition table");
1471             if (ok("Correct this automatically?"))
1472                     start = dos_sectors;
1473     }
1474     if (start % dos_sectors != 0)
1475         warnx("WARNING: partition does not start on a head boundary");
1476     if ((start  +size) % dos_sectors != 0)
1477         warnx("WARNING: partition does not end on a cylinder boundary");
1478     warnx("WARNING: this may confuse the BIOS or some operating systems");
1479     if (!ok("Correct this automatically?"))
1480         return (1);
1481
1482     /*
1483      * Adjust start upwards, if necessary, to fall on an head boundary.
1484      */
1485     if (start % dos_sectors != 0) {
1486         prev_head_boundary = start / dos_sectors * dos_sectors;
1487         if (max_end < dos_sectors ||
1488             prev_head_boundary >= max_end - dos_sectors) {
1489             /*
1490              * Can't go past end of partition
1491              */
1492             warnx(
1493     "ERROR: unable to adjust start of partition to fall on a head boundary");
1494             return (0);
1495         }
1496         start = prev_head_boundary + dos_sectors;
1497     }
1498
1499     /*
1500      * Adjust size downwards, if necessary, to fall on a cylinder
1501      * boundary.
1502      */
1503     prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs;
1504     if (prev_cyl_boundary > start)
1505         size = prev_cyl_boundary - start;
1506     else {
1507         warnx("ERROR: could not adjust partition to start on a head boundary\n\
1508     and end on a cylinder boundary.");
1509         return (0);
1510     }
1511
1512     /* Finally, commit any changes to partp and return. */
1513     if (start != partp->dp_start) {
1514         warnx("WARNING: adjusting start offset of partition to %u",
1515             (u_int)start);
1516         partp->dp_start = start;
1517     }
1518     if (size != partp->dp_size) {
1519         warnx("WARNING: adjusting size of partition to %u", (u_int)size);
1520         partp->dp_size = size;
1521     }
1522
1523     return (1);
1524 }