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