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