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