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