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