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