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