Start untangling the disklabel from various bits of code with the goal of
[dragonfly.git] / sbin / disklabel / disklabel.c
1 /*
2  * Copyright (c) 1987, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Symmetric Computer Systems.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#) Copyright (c) 1987, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)disklabel.c      1.2 (Symmetric) 11/28/85
38  * @(#)disklabel.c      8.2 (Berkeley) 1/7/94
39  * $FreeBSD: src/sbin/disklabel/disklabel.c,v 1.28.2.15 2003/01/24 16:18:16 des Exp $
40  * $DragonFly: src/sbin/disklabel/disklabel.c,v 1.13 2007/05/14 20:02:43 dillon Exp $
41  */
42
43 #include <sys/param.h>
44 #include <sys/file.h>
45 #include <sys/stat.h>
46 #include <sys/wait.h>
47 #define DKTYPENAMES
48 #include <sys/disklabel.h>
49 #include <sys/diskmbr.h>
50
51 #include <vfs/ufs/dinode.h>
52 #include <vfs/ufs/fs.h>
53
54 #include <unistd.h>
55 #include <string.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <signal.h>
59 #include <stdarg.h>
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include "pathnames.h"
64
65 /*
66  * Disklabel: read and write disklabels.
67  * The label is usually placed on one of the first sectors of the disk.
68  * Many machines also place a bootstrap in the same area,
69  * in which case the label is embedded in the bootstrap.
70  * The bootstrap source must leave space at the proper offset
71  * for the label on such machines.
72  */
73
74 #ifndef BBSIZE
75 #define BBSIZE  8192                    /* size of boot area, with label */
76 #endif
77
78 /* FIX!  These are too low, but are traditional */
79 #define DEFAULT_NEWFS_BLOCK  8192U
80 #define DEFAULT_NEWFS_FRAG   1024U
81 #define DEFAULT_NEWFS_CPG    16U
82
83 #define BIG_NEWFS_BLOCK  16384U
84 #define BIG_NEWFS_FRAG   2048U
85 #define BIG_NEWFS_CPG    64U
86
87 #define NUMBOOT 2
88
89 void    makelabel(const char *, const char *, struct disklabel *);
90 int     writelabel(int, const char *, struct disklabel *);
91 void    l_perror(const char *);
92 struct disklabel *readlabel(int);
93 struct disklabel *makebootarea(char *, struct disklabel *, int);
94 void    display(FILE *, const struct disklabel *);
95 int     edit(struct disklabel *, int);
96 int     editit(void);
97 char    *skip(char *);
98 char    *word(char *);
99 int     getasciilabel(FILE *, struct disklabel *);
100 int     getasciipartspec(char *, struct disklabel *, int, int);
101 int     checklabel(struct disklabel *);
102 void    setbootflag(struct disklabel *);
103 void    Warning(const char *, ...) __printflike(1, 2);
104 void    usage(void);
105 int     checkoldboot(int, const char *);
106 struct disklabel *getvirginlabel(void);
107
108 #define DEFEDITOR       _PATH_VI
109 #define streq(a,b)      (strcmp(a,b) == 0)
110
111 char    *dkname;
112 char    *specname;
113 char    tmpfil[] = PATH_TMPFILE;
114
115 char    namebuf[BBSIZE], *np = namebuf;
116 struct  disklabel lab;
117 char    bootarea[BBSIZE];
118
119 #define MAX_PART ('z')
120 #define MAX_NUM_PARTS (1 + MAX_PART - 'a')
121 char    part_size_type[MAX_NUM_PARTS];
122 char    part_offset_type[MAX_NUM_PARTS];
123 int     part_set[MAX_NUM_PARTS];
124
125 #if NUMBOOT > 0
126 int     installboot;    /* non-zero if we should install a boot program */
127 char    *bootbuf;       /* pointer to buffer with remainder of boot prog */
128 int     bootsize;       /* size of remaining boot program */
129 char    *xxboot;        /* primary boot */
130 char    *bootxx;        /* secondary boot */
131 char    boot0[MAXPATHLEN];
132 char    boot1[MAXPATHLEN];
133 #endif
134
135 enum    {
136         UNSPEC, EDIT, NOWRITE, READ, RESTORE, WRITE, WRITEABLE, WRITEBOOT
137 } op = UNSPEC;
138
139 int     rflag;
140 int     disable_write;   /* set to disable writing to disk label */
141
142 #ifdef DEBUG
143 int     debug;
144 #define OPTIONS "BNRWb:denrs:w"
145 #else
146 #define OPTIONS "BNRWb:enrs:w"
147 #endif
148
149 int
150 main(int argc, char *argv[])
151 {
152         struct disklabel *lp;
153         FILE *t;
154         int ch, f = 0, flag, error = 0;
155         char *name = 0;
156
157         while ((ch = getopt(argc, argv, OPTIONS)) != -1)
158                 switch (ch) {
159 #if NUMBOOT > 0
160                         case 'B':
161                                 ++installboot;
162                                 break;
163                         case 'b':
164                                 xxboot = optarg;
165                                 break;
166 #if NUMBOOT > 1
167                         case 's':
168                                 bootxx = optarg;
169                                 break;
170 #endif
171 #endif
172                         case 'N':
173                                 if (op != UNSPEC)
174                                         usage();
175                                 op = NOWRITE;
176                                 break;
177                         case 'n':
178                                 disable_write = 1;
179                                 break;
180                         case 'R':
181                                 if (op != UNSPEC)
182                                         usage();
183                                 op = RESTORE;
184                                 break;
185                         case 'W':
186                                 if (op != UNSPEC)
187                                         usage();
188                                 op = WRITEABLE;
189                                 break;
190                         case 'e':
191                                 if (op != UNSPEC)
192                                         usage();
193                                 op = EDIT;
194                                 break;
195                         case 'r':
196                                 ++rflag;
197                                 break;
198                         case 'w':
199                                 if (op != UNSPEC)
200                                         usage();
201                                 op = WRITE;
202                                 break;
203 #ifdef DEBUG
204                         case 'd':
205                                 debug++;
206                                 break;
207 #endif
208                         case '?':
209                         default:
210                                 usage();
211                 }
212         argc -= optind;
213         argv += optind;
214 #if NUMBOOT > 0
215         if (installboot) {
216                 rflag++;
217                 if (op == UNSPEC)
218                         op = WRITEBOOT;
219         } else {
220                 if (op == UNSPEC)
221                         op = READ;
222                 xxboot = bootxx = 0;
223         }
224 #else
225         if (op == UNSPEC)
226                 op = READ;
227 #endif
228         if (argc < 1)
229                 usage();
230
231         dkname = argv[0];
232         if (dkname[0] != '/') {
233                 sprintf(np, "%s%s%c", _PATH_DEV, dkname, 'a' + RAW_PART);
234                 specname = np;
235                 np += strlen(specname) + 1;
236         } else
237                 specname = dkname;
238         f = open(specname, op == READ ? O_RDONLY : O_RDWR);
239         if (f < 0 && errno == ENOENT && dkname[0] != '/') {
240                 sprintf(specname, "%s%s", _PATH_DEV, dkname);
241                 np = namebuf + strlen(specname) + 1;
242                 f = open(specname, op == READ ? O_RDONLY : O_RDWR);
243         }
244         if (f < 0)
245                 err(4, "%s", specname);
246
247         switch(op) {
248
249         case UNSPEC:
250                 break;
251
252         case EDIT:
253                 if (argc != 1)
254                         usage();
255                 lp = readlabel(f);
256                 error = edit(lp, f);
257                 break;
258
259         case NOWRITE:
260                 flag = 0;
261                 if (ioctl(f, DIOCWLABEL, (char *)&flag) < 0)
262                         err(4, "ioctl DIOCWLABEL");
263                 break;
264
265         case READ:
266                 if (argc != 1)
267                         usage();
268                 lp = readlabel(f);
269                 display(stdout, lp);
270                 error = checklabel(lp);
271                 if (checkoldboot(f, NULL))
272                         warnx("Warning, old bootblocks detected, install new bootblocks & reinstall the disklabel");
273                 break;
274
275         case RESTORE:
276 #if NUMBOOT > 0
277                 if (installboot && argc == 3) {
278                         makelabel(argv[2], 0, &lab);
279                         argc--;
280
281                         /*
282                          * We only called makelabel() for its side effect
283                          * of setting the bootstrap file names.  Discard
284                          * all changes to `lab' so that all values in the
285                          * final label come from the ASCII label.
286                          */
287                         bzero((char *)&lab, sizeof(lab));
288                 }
289 #endif
290                 if (argc != 2)
291                         usage();
292                 if (!(t = fopen(argv[1], "r")))
293                         err(4, "%s", argv[1]);
294                 if (!getasciilabel(t, &lab))
295                         exit(1);
296                 lp = makebootarea(bootarea, &lab, f);
297                 *lp = lab;
298                 error = writelabel(f, bootarea, lp);
299                 break;
300
301         case WRITE:
302                 if (argc == 3) {
303                         name = argv[2];
304                         argc--;
305                 }
306                 if (argc != 2)
307                         usage();
308                 makelabel(argv[1], name, &lab);
309                 lp = makebootarea(bootarea, &lab, f);
310                 *lp = lab;
311                 if (checklabel(lp) == 0)
312                         error = writelabel(f, bootarea, lp);
313                 break;
314
315         case WRITEABLE:
316                 flag = 1;
317                 if (ioctl(f, DIOCWLABEL, (char *)&flag) < 0)
318                         err(4, "ioctl DIOCWLABEL");
319                 break;
320
321 #if NUMBOOT > 0
322         case WRITEBOOT:
323         {
324                 struct disklabel tlab;
325
326                 lp = readlabel(f);
327                 tlab = *lp;
328                 if (argc == 2)
329                         makelabel(argv[1], 0, &lab);
330                 lp = makebootarea(bootarea, &lab, f);
331                 *lp = tlab;
332                 if (checklabel(lp) == 0)
333                         error = writelabel(f, bootarea, lp);
334                 break;
335         }
336 #endif
337         }
338         exit(error);
339 }
340
341 /*
342  * Construct a prototype disklabel from /etc/disktab.  As a side
343  * effect, set the names of the primary and secondary boot files
344  * if specified.
345  */
346 void
347 makelabel(const char *type, const char *name, struct disklabel *lp)
348 {
349         struct disklabel *dp;
350
351         if (strcmp(type, "auto") == 0)
352                 dp = getvirginlabel();
353         else
354                 dp = getdiskbyname(type);
355         if (dp == NULL)
356                 errx(1, "%s: unknown disk type", type);
357         *lp = *dp;
358 #if NUMBOOT > 0
359         /*
360          * Set bootstrap name(s).
361          * 1. If set from command line, use those,
362          * 2. otherwise, check if disktab specifies them (b0 or b1),
363          * 3. otherwise, makebootarea() will choose ones based on the name
364          *    of the disk special file. E.g. /dev/ra0 -> raboot, bootra
365          */
366         if (!xxboot && lp->d_boot0) {
367                 if (*lp->d_boot0 != '/')
368                         sprintf(boot0, "%s/%s", _PATH_BOOTDIR, lp->d_boot0);
369                 else
370                         strcpy(boot0, lp->d_boot0);
371                 xxboot = boot0;
372         }
373 #if NUMBOOT > 1
374         if (!bootxx && lp->d_boot1) {
375                 if (*lp->d_boot1 != '/')
376                         sprintf(boot1, "%s/%s", _PATH_BOOTDIR, lp->d_boot1);
377                 else
378                         strcpy(boot1, lp->d_boot1);
379                 bootxx = boot1;
380         }
381 #endif
382 #endif
383         /* d_packname is union d_boot[01], so zero */
384         bzero(lp->d_packname, sizeof(lp->d_packname));
385         if (name)
386                 strncpy(lp->d_packname, name, sizeof(lp->d_packname));
387 }
388
389 int
390 writelabel(int f, const char *boot, struct disklabel *lp)
391 {
392         int flag;
393
394         if (disable_write) {
395                 Warning("write to disk label supressed - label was as follows:");
396                 display(stdout, lp);
397                 return (0);
398         } else {
399                 /* make sure we are not overwriting our boot code */
400                 if (checkoldboot(f, boot))
401                         errx(4, "Will not overwrite old bootblocks w/ label, install new boot blocks first!");
402                 setbootflag(lp);
403                 lp->d_magic = DISKMAGIC;
404                 lp->d_magic2 = DISKMAGIC;
405                 lp->d_checksum = 0;
406                 lp->d_checksum = dkcksum(lp);
407                 if (rflag) {
408                         /*
409                          * First set the kernel disk label,
410                          * then write a label to the raw disk.
411                          * If the SDINFO ioctl fails because it is unimplemented,
412                          * keep going; otherwise, the kernel consistency checks
413                          * may prevent us from changing the current (in-core)
414                          * label.
415                          */
416                         if (ioctl(f, DIOCSDINFO, lp) < 0 &&
417                                 errno != ENODEV && errno != ENOTTY) {
418                                 l_perror("ioctl DIOCSDINFO");
419                                 return (1);
420                         }
421                         lseek(f, (off_t)0, SEEK_SET);
422                         
423                         /*
424                          * write enable label sector before write (if necessary),
425                          * disable after writing.
426                          */
427                         flag = 1;
428                         if (ioctl(f, DIOCWLABEL, &flag) < 0)
429                                 warn("ioctl DIOCWLABEL");
430                         if (write(f, boot, lp->d_bbsize) != (ssize_t)lp->d_bbsize) {
431                                 warn("write");
432                                 return (1);
433                         }
434 #if NUMBOOT > 0
435                         /*
436                          * Output the remainder of the disklabel
437                          */
438                         if (bootbuf && write(f, bootbuf, bootsize) != bootsize) {
439                                 warn("write");
440                                 return(1);
441                         }
442 #endif
443                         flag = 0;
444                         ioctl(f, DIOCWLABEL, &flag);
445                 } else if (ioctl(f, DIOCWDINFO, lp) < 0) {
446                         l_perror("ioctl DIOCWDINFO");
447                         return (1);
448                 }
449         }
450         return (0);
451 }
452
453 void
454 l_perror(const char *s)
455 {
456         switch (errno) {
457
458         case ESRCH:
459                 warnx("%s: no disk label on disk;", s);
460                 fprintf(stderr, "add \"-r\" to install initial label\n");
461                 break;
462
463         case EINVAL:
464                 warnx("%s: label magic number or checksum is wrong!", s);
465                 fprintf(stderr, "(disklabel or kernel is out of date?)\n");
466                 break;
467
468         case EBUSY:
469                 warnx("%s: open partition would move or shrink", s);
470                 break;
471
472         case EXDEV:
473                 warnx("%s: '%c' partition must start at beginning of disk",
474                     s, 'a' + RAW_PART);
475                 break;
476
477         default:
478                 warn((char *)NULL);
479                 break;
480         }
481 }
482
483 /*
484  * Fetch disklabel for disk.
485  * Use ioctl to get label unless -r flag is given.
486  */
487 struct disklabel *
488 readlabel(int f)
489 {
490         struct disklabel *lp;
491
492         if (rflag) {
493                 if (read(f, bootarea, BBSIZE) < BBSIZE)
494                         err(4, "%s", specname);
495                 for (lp = (struct disklabel *)bootarea;
496                     lp <= (struct disklabel *)(bootarea + BBSIZE - sizeof(*lp));
497                     lp = (struct disklabel *)((char *)lp + 16))
498                         if (lp->d_magic == DISKMAGIC &&
499                             lp->d_magic2 == DISKMAGIC)
500                                 break;
501                 if (lp > (struct disklabel *)(bootarea+BBSIZE-sizeof(*lp)) ||
502                     lp->d_magic != DISKMAGIC || lp->d_magic2 != DISKMAGIC ||
503                     dkcksum(lp) != 0)
504                         errx(1,
505             "bad pack magic number (label is damaged, or pack is unlabeled)");
506         } else {
507                 lp = &lab;
508                 if (ioctl(f, DIOCGDINFO, lp) < 0)
509                         err(4, "ioctl DIOCGDINFO");
510         }
511         return (lp);
512 }
513
514 /*
515  * Construct a bootarea (d_bbsize bytes) in the specified buffer ``boot''
516  * Returns a pointer to the disklabel portion of the bootarea.
517  */
518 struct disklabel *
519 makebootarea(char *boot, struct disklabel *dp, int f)
520 {
521         struct disklabel *lp;
522         char *p;
523         int b;
524 #if NUMBOOT > 0
525         char *dkbasename;
526         struct stat sb;
527 #endif
528 #ifdef __i386__
529         char *tmpbuf;
530         unsigned int i, found;
531 #endif
532
533         /* XXX */
534         if (dp->d_secsize == 0) {
535                 dp->d_secsize = DEV_BSIZE;
536                 dp->d_bbsize = BBSIZE;
537         }
538         lp = (struct disklabel *)
539                 (boot + (LABELSECTOR * dp->d_secsize) + LABELOFFSET);
540         bzero((char *)lp, sizeof *lp);
541 #if NUMBOOT > 0
542         /*
543          * If we are not installing a boot program but we are installing a
544          * label on disk then we must read the current bootarea so we don't
545          * clobber the existing boot.
546          */
547         if (!installboot) {
548                 if (rflag) {
549                         if (read(f, boot, BBSIZE) < BBSIZE)
550                                 err(4, "%s", specname);
551                         bzero((char *)lp, sizeof *lp);
552                 }
553                 return (lp);
554         }
555         /*
556          * We are installing a boot program.  Determine the name(s) and
557          * read them into the appropriate places in the boot area.
558          */
559         if (!xxboot || !bootxx) {
560                 dkbasename = np;
561                 if ((p = strrchr(dkname, '/')) == NULL)
562                         p = dkname;
563                 else
564                         p++;
565                 while (*p && !isdigit(*p))
566                         *np++ = *p++;
567                 *np++ = '\0';
568
569                 if (!xxboot) {
570                         sprintf(boot0, "%s/boot1", _PATH_BOOTDIR);
571                         xxboot = boot0;
572                 }
573 #if NUMBOOT > 1
574                 if (!bootxx) {
575                         sprintf(boot1, "%s/boot2", _PATH_BOOTDIR);
576                         bootxx = boot1;
577                 }
578 #endif
579         }
580 #ifdef DEBUG
581         if (debug)
582                 fprintf(stderr, "bootstraps: xxboot = %s, bootxx = %s\n",
583                         xxboot, bootxx ? bootxx : "NONE");
584 #endif
585
586         /*
587          * Strange rules:
588          * 1. One-piece bootstrap (hp300/hp800)
589          *      up to d_bbsize bytes of ``xxboot'' go in bootarea, the rest
590          *      is remembered and written later following the bootarea.
591          * 2. Two-piece bootstraps (vax/i386?/mips?)
592          *      up to d_secsize bytes of ``xxboot'' go in first d_secsize
593          *      bytes of bootarea, remaining d_bbsize-d_secsize filled
594          *      from ``bootxx''.
595          */
596         b = open(xxboot, O_RDONLY);
597         if (b < 0)
598                 err(4, "%s", xxboot);
599 #if NUMBOOT > 1
600 #ifdef __i386__
601         /*
602          * XXX Botch alert.
603          * The i386 has the so-called fdisk table embedded into the
604          * primary bootstrap.  We take care to not clobber it, but
605          * only if it does already contain some data.  (Otherwise,
606          * the xxboot provides a template.)
607          */
608         if ((tmpbuf = (char *)malloc((int)dp->d_secsize)) == 0)
609                 err(4, "%s", xxboot);
610         memcpy((void *)tmpbuf, (void *)boot, (int)dp->d_secsize);
611 #endif /* i386 */
612         if (read(b, boot, (int)dp->d_secsize) < 0)
613                 err(4, "%s", xxboot);
614         close(b);
615 #ifdef __i386__
616         for (i = DOSPARTOFF, found = 0;
617              !found && i < DOSPARTOFF + NDOSPART*sizeof(struct dos_partition);
618              i++)
619                 found = tmpbuf[i] != 0;
620         if (found)
621                 memcpy((void *)&boot[DOSPARTOFF],
622                        (void *)&tmpbuf[DOSPARTOFF],
623                        NDOSPART * sizeof(struct dos_partition));
624         free(tmpbuf);
625 #endif /* i386 */
626         b = open(bootxx, O_RDONLY);
627         if (b < 0)
628                 err(4, "%s", bootxx);
629         if (fstat(b, &sb) != 0)
630                 err(4, "%s", bootxx);
631         if (dp->d_secsize + sb.st_size > dp->d_bbsize)
632                 errx(4, "%s too large", bootxx);
633         if (read(b, &boot[dp->d_secsize],
634                  (int)(dp->d_bbsize-dp->d_secsize)) < 0)
635                 err(4, "%s", bootxx);
636 #else /* !(NUMBOOT > 1) */
637         if (read(b, boot, (int)dp->d_bbsize) < 0)
638                 err(4, "%s", xxboot);
639         if (fstat(b, &sb) != 0)
640                 err(4, "%s", xxboot);
641         bootsize = (int)sb.st_size - dp->d_bbsize;
642         if (bootsize > 0) {
643                 /* XXX assume d_secsize is a power of two */
644                 bootsize = (bootsize + dp->d_secsize-1) & ~(dp->d_secsize-1);
645                 bootbuf = (char *)malloc((size_t)bootsize);
646                 if (bootbuf == 0)
647                         err(4, "%s", xxboot);
648                 if (read(b, bootbuf, bootsize) < 0) {
649                         free(bootbuf);
650                         err(4, "%s", xxboot);
651                 }
652         }
653 #endif /* NUMBOOT > 1 */
654         close(b);
655 #endif /* NUMBOOT > 0 */
656         /*
657          * Make sure no part of the bootstrap is written in the area
658          * reserved for the label.
659          */
660         for (p = (char *)lp; p < (char *)lp + sizeof(struct disklabel); p++)
661                 if (*p)
662                         errx(2, "bootstrap doesn't leave room for disk label");
663         return (lp);
664 }
665
666 void
667 display(FILE *f, const struct disklabel *lp)
668 {
669         int i, j;
670         const struct partition *pp;
671
672         fprintf(f, "# %s:\n", specname);
673         if (lp->d_type < DKMAXTYPES)
674                 fprintf(f, "type: %s\n", dktypenames[lp->d_type]);
675         else
676                 fprintf(f, "type: %u\n", lp->d_type);
677         fprintf(f, "disk: %.*s\n", (int)sizeof(lp->d_typename),
678                 lp->d_typename);
679         fprintf(f, "label: %.*s\n", (int)sizeof(lp->d_packname),
680                 lp->d_packname);
681         fprintf(f, "flags:");
682         fprintf(f, "\n");
683         fprintf(f, "bytes/sector: %lu\n", (u_long)lp->d_secsize);
684         fprintf(f, "sectors/track: %lu\n", (u_long)lp->d_nsectors);
685         fprintf(f, "tracks/cylinder: %lu\n", (u_long)lp->d_ntracks);
686         fprintf(f, "sectors/cylinder: %lu\n", (u_long)lp->d_secpercyl);
687         fprintf(f, "cylinders: %lu\n", (u_long)lp->d_ncylinders);
688         fprintf(f, "sectors/unit: %lu\n", (u_long)lp->d_secperunit);
689         fprintf(f, "rpm: %u\n", lp->d_rpm);
690         fprintf(f, "interleave: %u\n", lp->d_interleave);
691         fprintf(f, "trackskew: %u\n", lp->d_trackskew);
692         fprintf(f, "cylinderskew: %u\n", lp->d_cylskew);
693         fprintf(f, "headswitch: %lu\t\t# milliseconds\n",
694             (u_long)lp->d_headswitch);
695         fprintf(f, "track-to-track seek: %ld\t# milliseconds\n",
696             (u_long)lp->d_trkseek);
697         fprintf(f, "drivedata: ");
698         for (i = NDDATA - 1; i >= 0; i--)
699                 if (lp->d_drivedata[i])
700                         break;
701         if (i < 0)
702                 i = 0;
703         for (j = 0; j <= i; j++)
704                 fprintf(f, "%lu ", (u_long)lp->d_drivedata[j]);
705         fprintf(f, "\n\n%u partitions:\n", lp->d_npartitions);
706         fprintf(f,
707             "#        size   offset    fstype   [fsize bsize bps/cpg]\n");
708         pp = lp->d_partitions;
709         for (i = 0; i < lp->d_npartitions; i++, pp++) {
710                 if (pp->p_size) {
711                         fprintf(f, "  %c: %8lu %8lu  ", 'a' + i,
712                            (u_long)pp->p_size, (u_long)pp->p_offset);
713                         if (pp->p_fstype < FSMAXTYPES)
714                                 fprintf(f, "%8.8s", fstypenames[pp->p_fstype]);
715                         else
716                                 fprintf(f, "%8d", pp->p_fstype);
717                         switch (pp->p_fstype) {
718
719                         case FS_UNUSED:                         /* XXX */
720                                 fprintf(f, "    %5lu %5lu %5.5s ",
721                                     (u_long)pp->p_fsize,
722                                     (u_long)(pp->p_fsize * pp->p_frag), "");
723                                 break;
724
725                         case FS_BSDFFS:
726                                 fprintf(f, "    %5lu %5lu %5u ",
727                                     (u_long)pp->p_fsize,
728                                     (u_long)(pp->p_fsize * pp->p_frag),
729                                     pp->p_cpg);
730                                 break;
731
732                         case FS_BSDLFS:
733                                 fprintf(f, "    %5lu %5lu %5d",
734                                     (u_long)pp->p_fsize,
735                                     (u_long)(pp->p_fsize * pp->p_frag),
736                                     pp->p_cpg);
737                                 break;
738
739                         default:
740                                 fprintf(f, "%20.20s", "");
741                                 break;
742                         }
743                         fprintf(f, "\t# (Cyl. %4lu",
744                             (u_long)(pp->p_offset / lp->d_secpercyl));
745                         if (pp->p_offset % lp->d_secpercyl)
746                             putc('*', f);
747                         else
748                             putc(' ', f);
749                         fprintf(f, "- %lu",
750                             (u_long)((pp->p_offset + pp->p_size +
751                             lp->d_secpercyl - 1) /
752                             lp->d_secpercyl - 1));
753                         if (pp->p_size % lp->d_secpercyl)
754                             putc('*', f);
755                         fprintf(f, ")\n");
756                 }
757         }
758         fflush(f);
759 }
760
761 int
762 edit(struct disklabel *lp, int f)
763 {
764         int c, fd;
765         struct disklabel label;
766         FILE *fp;
767
768         if ((fd = mkstemp(tmpfil)) == -1 ||
769             (fp = fdopen(fd, "w")) == NULL) {
770                 warnx("can't create %s", tmpfil);
771                 return (1);
772         }
773         display(fp, lp);
774         fclose(fp);
775         for (;;) {
776                 if (!editit())
777                         break;
778                 fp = fopen(tmpfil, "r");
779                 if (fp == NULL) {
780                         warnx("can't reopen %s for reading", tmpfil);
781                         break;
782                 }
783                 bzero((char *)&label, sizeof(label));
784                 if (getasciilabel(fp, &label)) {
785                         *lp = label;
786                         if (writelabel(f, bootarea, lp) == 0) {
787                                 fclose(fp);
788                                 unlink(tmpfil);
789                                 return (0);
790                         }
791                 }
792                 fclose(fp);
793                 printf("re-edit the label? [y]: "); fflush(stdout);
794                 c = getchar();
795                 if (c != EOF && c != (int)'\n')
796                         while (getchar() != (int)'\n')
797                                 ;
798                 if  (c == (int)'n')
799                         break;
800         }
801         unlink(tmpfil);
802         return (1);
803 }
804
805 int
806 editit(void)
807 {
808         int pid, xpid;
809         int status, omask;
810         const char *ed;
811
812         omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
813         while ((pid = fork()) < 0) {
814                 if (errno == EPROCLIM) {
815                         warnx("you have too many processes");
816                         return(0);
817                 }
818                 if (errno != EAGAIN) {
819                         warn("fork");
820                         return(0);
821                 }
822                 sleep(1);
823         }
824         if (pid == 0) {
825                 sigsetmask(omask);
826                 setgid(getgid());
827                 setuid(getuid());
828                 if ((ed = getenv("EDITOR")) == (char *)0)
829                         ed = DEFEDITOR;
830                 execlp(ed, ed, tmpfil, (char *)0);
831                 err(1, "%s", ed);
832         }
833         while ((xpid = wait(&status)) >= 0)
834                 if (xpid == pid)
835                         break;
836         sigsetmask(omask);
837         return(!status);
838 }
839
840 char *
841 skip(char *cp)
842 {
843
844         while (*cp != '\0' && isspace(*cp))
845                 cp++;
846         if (*cp == '\0' || *cp == '#')
847                 return (NULL);
848         return (cp);
849 }
850
851 char *
852 word(char *cp)
853 {
854         char c;
855
856         while (*cp != '\0' && !isspace(*cp) && *cp != '#')
857                 cp++;
858         if ((c = *cp) != '\0') {
859                 *cp++ = '\0';
860                 if (c != '#')
861                         return (skip(cp));
862         }
863         return (NULL);
864 }
865
866 /*
867  * Read an ascii label in from fd f,
868  * in the same format as that put out by display(),
869  * and fill in lp.
870  */
871 int
872 getasciilabel(FILE *f, struct disklabel *lp)
873 {
874         char *cp;
875         const char **cpp;
876         u_int part;
877         char *tp, line[BUFSIZ];
878         u_long v;
879         int lineno = 0, errors = 0;
880         int i;
881         char empty[] = "";
882         char unknown[] = "unknown";
883
884         bzero(&part_set, sizeof(part_set));
885         bzero(&part_size_type, sizeof(part_size_type));
886         bzero(&part_offset_type, sizeof(part_offset_type));
887         lp->d_bbsize = BBSIZE;                          /* XXX */
888         lp->d_sbsize = SBSIZE;                          /* XXX */
889         while (fgets(line, sizeof(line) - 1, f)) {
890                 lineno++;
891                 if ((cp = strchr(line,'\n')) != 0)
892                         *cp = '\0';
893                 cp = skip(line);
894                 if (cp == NULL)
895                         continue;
896                 tp = strchr(cp, ':');
897                 if (tp == NULL) {
898                         fprintf(stderr, "line %d: syntax error\n", lineno);
899                         errors++;
900                         continue;
901                 }
902                 *tp++ = '\0', tp = skip(tp);
903                 if (streq(cp, "type")) {
904                         if (tp == NULL)
905                                 tp = unknown;
906                         cpp = dktypenames;
907                         for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
908                                 if (*cpp && streq(*cpp, tp)) {
909                                         lp->d_type = cpp - dktypenames;
910                                         break;
911                                 }
912                         if (cpp < &dktypenames[DKMAXTYPES])
913                                 continue;
914                         v = strtoul(tp, NULL, 10);
915                         if (v >= DKMAXTYPES)
916                                 fprintf(stderr, "line %d:%s %lu\n", lineno,
917                                     "Warning, unknown disk type", v);
918                         lp->d_type = v;
919                         continue;
920                 }
921                 if (streq(cp, "flags")) {
922                         for (v = 0; (cp = tp) && *cp != '\0';) {
923                                 tp = word(cp);
924                                 if (streq(cp, "removeable"))
925                                         v |= 0; /* obsolete */
926                                 else if (streq(cp, "ecc"))
927                                         v |= 0; /* obsolete */
928                                 else if (streq(cp, "badsect"))
929                                         v |= 0; /* obsolete */
930                                 else {
931                                         fprintf(stderr,
932                                             "line %d: %s: bad flag\n",
933                                             lineno, cp);
934                                         errors++;
935                                 }
936                         }
937                         lp->d_flags = v;
938                         continue;
939                 }
940                 if (streq(cp, "drivedata")) {
941                         for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
942                                 lp->d_drivedata[i++] = strtoul(cp, NULL, 10);
943                                 tp = word(cp);
944                         }
945                         continue;
946                 }
947                 if (sscanf(cp, "%lu partitions", &v) == 1) {
948                         if (v == 0 || v > MAXPARTITIONS) {
949                                 fprintf(stderr,
950                                     "line %d: bad # of partitions\n", lineno);
951                                 lp->d_npartitions = MAXPARTITIONS;
952                                 errors++;
953                         } else
954                                 lp->d_npartitions = v;
955                         continue;
956                 }
957                 if (tp == NULL)
958                         tp = empty;
959                 if (streq(cp, "disk")) {
960                         strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
961                         continue;
962                 }
963                 if (streq(cp, "label")) {
964                         strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
965                         continue;
966                 }
967                 if (streq(cp, "bytes/sector")) {
968                         v = strtoul(tp, NULL, 10);
969                         if (v == 0 || (v % DEV_BSIZE) != 0) {
970                                 fprintf(stderr,
971                                     "line %d: %s: bad sector size\n",
972                                     lineno, tp);
973                                 errors++;
974                         } else
975                                 lp->d_secsize = v;
976                         continue;
977                 }
978                 if (streq(cp, "sectors/track")) {
979                         v = strtoul(tp, NULL, 10);
980 #if (ULONG_MAX != 0xffffffffUL)
981                         if (v == 0 || v > 0xffffffff) {
982 #else
983                         if (v == 0) {
984 #endif
985                                 fprintf(stderr, "line %d: %s: bad %s\n",
986                                     lineno, tp, cp);
987                                 errors++;
988                         } else
989                                 lp->d_nsectors = v;
990                         continue;
991                 }
992                 if (streq(cp, "sectors/cylinder")) {
993                         v = strtoul(tp, NULL, 10);
994                         if (v == 0) {
995                                 fprintf(stderr, "line %d: %s: bad %s\n",
996                                     lineno, tp, cp);
997                                 errors++;
998                         } else
999                                 lp->d_secpercyl = v;
1000                         continue;
1001                 }
1002                 if (streq(cp, "tracks/cylinder")) {
1003                         v = strtoul(tp, NULL, 10);
1004                         if (v == 0) {
1005                                 fprintf(stderr, "line %d: %s: bad %s\n",
1006                                     lineno, tp, cp);
1007                                 errors++;
1008                         } else
1009                                 lp->d_ntracks = v;
1010                         continue;
1011                 }
1012                 if (streq(cp, "cylinders")) {
1013                         v = strtoul(tp, NULL, 10);
1014                         if (v == 0) {
1015                                 fprintf(stderr, "line %d: %s: bad %s\n",
1016                                     lineno, tp, cp);
1017                                 errors++;
1018                         } else
1019                                 lp->d_ncylinders = v;
1020                         continue;
1021                 }
1022                 if (streq(cp, "sectors/unit")) {
1023                         v = strtoul(tp, NULL, 10);
1024                         if (v == 0) {
1025                                 fprintf(stderr, "line %d: %s: bad %s\n",
1026                                     lineno, tp, cp);
1027                                 errors++;
1028                         } else
1029                                 lp->d_secperunit = v;
1030                         continue;
1031                 }
1032                 if (streq(cp, "rpm")) {
1033                         v = strtoul(tp, NULL, 10);
1034                         if (v == 0 || v > USHRT_MAX) {
1035                                 fprintf(stderr, "line %d: %s: bad %s\n",
1036                                     lineno, tp, cp);
1037                                 errors++;
1038                         } else
1039                                 lp->d_rpm = v;
1040                         continue;
1041                 }
1042                 if (streq(cp, "interleave")) {
1043                         v = strtoul(tp, NULL, 10);
1044                         if (v == 0 || v > USHRT_MAX) {
1045                                 fprintf(stderr, "line %d: %s: bad %s\n",
1046                                     lineno, tp, cp);
1047                                 errors++;
1048                         } else
1049                                 lp->d_interleave = v;
1050                         continue;
1051                 }
1052                 if (streq(cp, "trackskew")) {
1053                         v = strtoul(tp, NULL, 10);
1054                         if (v > USHRT_MAX) {
1055                                 fprintf(stderr, "line %d: %s: bad %s\n",
1056                                     lineno, tp, cp);
1057                                 errors++;
1058                         } else
1059                                 lp->d_trackskew = v;
1060                         continue;
1061                 }
1062                 if (streq(cp, "cylinderskew")) {
1063                         v = strtoul(tp, NULL, 10);
1064                         if (v > USHRT_MAX) {
1065                                 fprintf(stderr, "line %d: %s: bad %s\n",
1066                                     lineno, tp, cp);
1067                                 errors++;
1068                         } else
1069                                 lp->d_cylskew = v;
1070                         continue;
1071                 }
1072                 if (streq(cp, "headswitch")) {
1073                         v = strtoul(tp, NULL, 10);
1074                         lp->d_headswitch = v;
1075                         continue;
1076                 }
1077                 if (streq(cp, "track-to-track seek")) {
1078                         v = strtoul(tp, NULL, 10);
1079                         lp->d_trkseek = v;
1080                         continue;
1081                 }
1082                 /* the ':' was removed above */
1083                 if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') {
1084                         fprintf(stderr,
1085                             "line %d: %s: Unknown disklabel field\n", lineno,
1086                             cp);
1087                         errors++;
1088                         continue;
1089                 }
1090
1091                 /* Process a partition specification line. */
1092                 part = *cp - 'a';
1093                 if (part >= lp->d_npartitions) {
1094                         fprintf(stderr,
1095                             "line %d: partition name out of range a-%c: %s\n",
1096                             lineno, 'a' + lp->d_npartitions - 1, cp);
1097                         errors++;
1098                         continue;
1099                 }
1100                 part_set[part] = 1;
1101
1102                 if (getasciipartspec(tp, lp, part, lineno) != 0) {
1103                         errors++;
1104                         break;
1105                 }
1106         }
1107         errors += checklabel(lp);
1108         return (errors == 0);
1109 }
1110
1111 #define NXTNUM(n) do { \
1112         if (tp == NULL) { \
1113                 fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1114                 return (1); \
1115         } else { \
1116                 cp = tp, tp = word(cp); \
1117                 (n) = strtoul(cp, NULL, 10); \
1118         } \
1119 } while (0)
1120
1121 /* retain 1 character following number */
1122 #define NXTWORD(w,n) do { \
1123         if (tp == NULL) { \
1124                 fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1125                 return (1); \
1126         } else { \
1127                 char *tmp; \
1128                 cp = tp, tp = word(cp); \
1129                 (n) = strtoul(cp, &tmp, 10); \
1130                 if (tmp) (w) = *tmp; \
1131         } \
1132 } while (0)
1133
1134 /*
1135  * Read a partition line into partition `part' in the specified disklabel.
1136  * Return 0 on success, 1 on failure.
1137  */
1138 int
1139 getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno)
1140 {
1141         struct partition *pp;
1142         char *cp;
1143         const char **cpp;
1144         u_long v;
1145
1146         pp = &lp->d_partitions[part];
1147         cp = NULL;
1148
1149         v = 0;
1150         NXTWORD(part_size_type[part],v);
1151         if (v == 0 && part_size_type[part] != '*') {
1152                 fprintf(stderr,
1153                     "line %d: %s: bad partition size\n", lineno, cp);
1154                 return (1);
1155         }
1156         pp->p_size = v;
1157
1158         v = 0;
1159         NXTWORD(part_offset_type[part],v);
1160         if (v == 0 && part_offset_type[part] != '*' &&
1161             part_offset_type[part] != '\0') {
1162                 fprintf(stderr,
1163                     "line %d: %s: bad partition offset\n", lineno, cp);
1164                 return (1);
1165         }
1166         pp->p_offset = v;
1167         cp = tp, tp = word(cp);
1168         for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++)
1169                 if (*cpp && streq(*cpp, cp))
1170                         break;
1171         if (*cpp != NULL) {
1172                 pp->p_fstype = cpp - fstypenames;
1173         } else {
1174                 if (isdigit(*cp))
1175                         v = strtoul(cp, NULL, 10);
1176                 else
1177                         v = FSMAXTYPES;
1178                 if (v >= FSMAXTYPES) {
1179                         fprintf(stderr,
1180                             "line %d: Warning, unknown filesystem type %s\n",
1181                             lineno, cp);
1182                         v = FS_UNUSED;
1183                 }
1184                 pp->p_fstype = v;
1185         }
1186
1187         switch (pp->p_fstype) {
1188         case FS_UNUSED:
1189                 /*
1190                  * allow us to accept defaults for
1191                  * fsize/frag/cpg
1192                  */
1193                 if (tp) {
1194                         NXTNUM(pp->p_fsize);
1195                         if (pp->p_fsize == 0)
1196                                 break;
1197                         NXTNUM(v);
1198                         pp->p_frag = v / pp->p_fsize;
1199                 }
1200                 /* else default to 0's */
1201                 break;
1202
1203         /* These happen to be the same */
1204         case FS_BSDFFS:
1205         case FS_BSDLFS:
1206                 if (tp) {
1207                         NXTNUM(pp->p_fsize);
1208                         if (pp->p_fsize == 0)
1209                                 break;
1210                         NXTNUM(v);
1211                         pp->p_frag = v / pp->p_fsize;
1212                         NXTNUM(pp->p_cpg);
1213                 } else {
1214                         /*
1215                          * FIX! poor attempt at adaptive
1216                          */
1217                         /* 1 GB */
1218                         if (pp->p_size < 1024*1024*1024 / lp->d_secsize) {
1219                                 /*
1220                                  * FIX! These are too low, but are traditional
1221                                  */
1222                                 pp->p_fsize = DEFAULT_NEWFS_FRAG;
1223                                 pp->p_frag = DEFAULT_NEWFS_BLOCK /
1224                                     DEFAULT_NEWFS_FRAG;
1225                                 pp->p_cpg = DEFAULT_NEWFS_CPG;
1226                         } else {
1227                                 pp->p_fsize = BIG_NEWFS_FRAG;
1228                                 pp->p_frag = BIG_NEWFS_BLOCK /
1229                                     BIG_NEWFS_FRAG;
1230                                 pp->p_cpg = BIG_NEWFS_CPG;
1231                         }
1232                 }
1233         default:
1234                 break;
1235         }
1236         return (0);
1237 }
1238
1239 /*
1240  * Check disklabel for errors and fill in
1241  * derived fields according to supplied values.
1242  */
1243 int
1244 checklabel(struct disklabel *lp)
1245 {
1246         struct partition *pp;
1247         int i, errors = 0;
1248         char part;
1249         u_long total_size, total_percent, current_offset;
1250         int seen_default_offset;
1251         int hog_part;
1252         int j;
1253         struct partition *pp2;
1254
1255         if (lp->d_secsize == 0) {
1256                 fprintf(stderr, "sector size 0\n");
1257                 return (1);
1258         }
1259         if (lp->d_nsectors == 0) {
1260                 fprintf(stderr, "sectors/track 0\n");
1261                 return (1);
1262         }
1263         if (lp->d_ntracks == 0) {
1264                 fprintf(stderr, "tracks/cylinder 0\n");
1265                 return (1);
1266         }
1267         if  (lp->d_ncylinders == 0) {
1268                 fprintf(stderr, "cylinders/unit 0\n");
1269                 errors++;
1270         }
1271         if (lp->d_rpm == 0)
1272                 Warning("revolutions/minute 0");
1273         if (lp->d_secpercyl == 0)
1274                 lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1275         if (lp->d_secperunit == 0)
1276                 lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1277         if (lp->d_bbsize == 0) {
1278                 fprintf(stderr, "boot block size 0\n");
1279                 errors++;
1280         } else if (lp->d_bbsize % lp->d_secsize)
1281                 Warning("boot block size %% sector-size != 0");
1282         if (lp->d_sbsize == 0) {
1283                 fprintf(stderr, "super block size 0\n");
1284                 errors++;
1285         } else if (lp->d_sbsize % lp->d_secsize)
1286                 Warning("super block size %% sector-size != 0");
1287         if (lp->d_npartitions > MAXPARTITIONS)
1288                 Warning("number of partitions (%lu) > MAXPARTITIONS (%d)",
1289                     (u_long)lp->d_npartitions, MAXPARTITIONS);
1290
1291         /* first allocate space to the partitions, then offsets */
1292         total_size = 0; /* in sectors */
1293         total_percent = 0; /* in percent */
1294         hog_part = -1;
1295         /* find all fixed partitions */
1296         for (i = 0; i < lp->d_npartitions; i++) {
1297                 pp = &lp->d_partitions[i];
1298                 if (part_set[i]) {
1299                         if (part_size_type[i] == '*') {
1300                                 if (i == RAW_PART) {
1301                                         pp->p_size = lp->d_secperunit;
1302                                 } else {
1303                                         if (hog_part != -1)
1304                                                 Warning("Too many '*' partitions (%c and %c)",
1305                                                     hog_part + 'a',i + 'a');
1306                                         else
1307                                                 hog_part = i;
1308                                 }
1309                         } else {
1310                                 off_t size;
1311
1312                                 size = pp->p_size;
1313                                 switch (part_size_type[i]) {
1314                                 case '%':
1315                                         total_percent += size;
1316                                         break;
1317                                 case 'k':
1318                                 case 'K':
1319                                         size *= 1024ULL;
1320                                         break;
1321                                 case 'm':
1322                                 case 'M':
1323                                         size *= 1024ULL * 1024ULL;
1324                                         break;
1325                                 case 'g':
1326                                 case 'G':
1327                                         size *= 1024ULL * 1024ULL * 1024ULL;
1328                                         break;
1329                                 case '\0':
1330                                         break;
1331                                 default:
1332                                         Warning("unknown size specifier '%c' (K/M/G are valid)",part_size_type[i]);
1333                                         break;
1334                                 }
1335                                 /* don't count %'s yet */
1336                                 if (part_size_type[i] != '%') {
1337                                         /*
1338                                          * for all not in sectors, convert to
1339                                          * sectors
1340                                          */
1341                                         if (part_size_type[i] != '\0') {
1342                                                 if (size % lp->d_secsize != 0)
1343                                                         Warning("partition %c not an integer number of sectors",
1344                                                             i + 'a');
1345                                                 size /= lp->d_secsize;
1346                                                 pp->p_size = size;
1347                                         }
1348                                         /* else already in sectors */
1349                                         if (i != RAW_PART)
1350                                                 total_size += size;
1351                                 }
1352                         }
1353                 }
1354         }
1355         /* handle % partitions - note %'s don't need to add up to 100! */
1356         if (total_percent != 0) {
1357                 long free_space = lp->d_secperunit - total_size;
1358                 if (total_percent > 100) {
1359                         fprintf(stderr,"total percentage %lu is greater than 100\n",
1360                             total_percent);
1361                         errors++;
1362                 }
1363
1364                 if (free_space > 0) {
1365                         for (i = 0; i < lp->d_npartitions; i++) {
1366                                 pp = &lp->d_partitions[i];
1367                                 if (part_set[i] && part_size_type[i] == '%') {
1368                                         /* careful of overflows! and integer roundoff */
1369                                         pp->p_size = ((double)pp->p_size/100) * free_space;
1370                                         total_size += pp->p_size;
1371
1372                                         /* FIX we can lose a sector or so due to roundoff per
1373                                            partition.  A more complex algorithm could avoid that */
1374                                 }
1375                         }
1376                 } else {
1377                         fprintf(stderr,
1378                             "%ld sectors available to give to '*' and '%%' partitions\n",
1379                             free_space);
1380                         errors++;
1381                         /* fix?  set all % partitions to size 0? */
1382                 }
1383         }
1384         /* give anything remaining to the hog partition */
1385         if (hog_part != -1) {
1386                 lp->d_partitions[hog_part].p_size = lp->d_secperunit - total_size;
1387                 total_size = lp->d_secperunit;
1388         }
1389
1390         /* Now set the offsets for each partition */
1391         current_offset = 0; /* in sectors */
1392         seen_default_offset = 0;
1393         for (i = 0; i < lp->d_npartitions; i++) {
1394                 part = 'a' + i;
1395                 pp = &lp->d_partitions[i];
1396                 if (part_set[i]) {
1397                         if (part_offset_type[i] == '*') {
1398                                 if (i == RAW_PART) {
1399                                         pp->p_offset = 0;
1400                                 } else {
1401                                         pp->p_offset = current_offset;
1402                                         seen_default_offset = 1;
1403                                 }
1404                         } else {
1405                                 /* allow them to be out of order for old-style tables */
1406                                 if (pp->p_offset < current_offset && 
1407                                     seen_default_offset && i != RAW_PART &&
1408                                     pp->p_fstype != FS_VINUM) {
1409                                         fprintf(stderr,
1410 "Offset %ld for partition %c overlaps previous partition which ends at %lu\n",
1411                                             (long)pp->p_offset,i+'a',current_offset);
1412                                         fprintf(stderr,
1413 "Labels with any *'s for offset must be in ascending order by sector\n");
1414                                         errors++;
1415                                 } else if (pp->p_offset != current_offset &&
1416                                     i != RAW_PART && seen_default_offset) {
1417                                         /* 
1418                                          * this may give unneeded warnings if 
1419                                          * partitions are out-of-order
1420                                          */
1421                                         Warning(
1422 "Offset %ld for partition %c doesn't match expected value %ld",
1423                                             (long)pp->p_offset, i + 'a', current_offset);
1424                                 }
1425                         }
1426                         if (i != RAW_PART)
1427                                 current_offset = pp->p_offset + pp->p_size; 
1428                 }
1429         }
1430
1431         for (i = 0; i < lp->d_npartitions; i++) {
1432                 part = 'a' + i;
1433                 pp = &lp->d_partitions[i];
1434                 if (pp->p_size == 0 && pp->p_offset != 0)
1435                         Warning("partition %c: size 0, but offset %lu",
1436                             part, (u_long)pp->p_offset);
1437 #ifdef notdef
1438                 if (pp->p_size % lp->d_secpercyl)
1439                         Warning("partition %c: size %% cylinder-size != 0",
1440                             part);
1441                 if (pp->p_offset % lp->d_secpercyl)
1442                         Warning("partition %c: offset %% cylinder-size != 0",
1443                             part);
1444 #endif
1445                 if (pp->p_offset > lp->d_secperunit) {
1446                         fprintf(stderr,
1447                             "partition %c: offset past end of unit\n", part);
1448                         errors++;
1449                 }
1450                 if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1451                         fprintf(stderr,
1452                         "partition %c: partition extends past end of unit\n",
1453                             part);
1454                         errors++;
1455                 }
1456                 if (i == RAW_PART)
1457                 {
1458                         if (pp->p_fstype != FS_UNUSED)
1459                                 Warning("partition %c is not marked as unused!",part);
1460                         if (pp->p_offset != 0)
1461                                 Warning("partition %c doesn't start at 0!",part);
1462                         if (pp->p_size != lp->d_secperunit)
1463                                 Warning("partition %c doesn't cover the whole unit!",part);
1464
1465                         if ((pp->p_fstype != FS_UNUSED) || (pp->p_offset != 0) ||
1466                             (pp->p_size != lp->d_secperunit)) {
1467                                 Warning("An incorrect partition %c may cause problems for "
1468                                     "standard system utilities",part);
1469                         }
1470                 }
1471
1472                 /* check for overlaps */
1473                 /* this will check for all possible overlaps once and only once */
1474                 for (j = 0; j < i; j++) {
1475                         pp2 = &lp->d_partitions[j];
1476                         if (j != RAW_PART && i != RAW_PART &&   
1477                             pp->p_fstype != FS_VINUM &&
1478                             pp2->p_fstype != FS_VINUM &&
1479                             part_set[i] && part_set[j]) {
1480                                 if (pp2->p_offset < pp->p_offset + pp->p_size &&
1481                                     (pp2->p_offset + pp2->p_size > pp->p_offset ||
1482                                         pp2->p_offset >= pp->p_offset)) {
1483                                         fprintf(stderr,"partitions %c and %c overlap!\n",
1484                                             j + 'a', i + 'a');
1485                                         errors++;
1486                                 }
1487                         }
1488                 }
1489         }
1490         for (; i < 8 || i < lp->d_npartitions; i++) {
1491                 part = 'a' + i;
1492                 pp = &lp->d_partitions[i];
1493                 if (pp->p_size || pp->p_offset)
1494                         Warning("unused partition %c: size %d offset %lu",
1495                             'a' + i, pp->p_size, (u_long)pp->p_offset);
1496         }
1497         return (errors);
1498 }
1499
1500 /*
1501  * When operating on a "virgin" disk, try getting an initial label
1502  * from the associated device driver.  This might work for all device
1503  * drivers that are able to fetch some initial device parameters
1504  * without even having access to a (BSD) disklabel, like SCSI disks,
1505  * most IDE drives, or vn devices.
1506  *
1507  * The device name must be given in its "canonical" form.
1508  */
1509 struct disklabel *
1510 getvirginlabel(void)
1511 {
1512         static struct disklabel dlab;
1513         char nambuf[BBSIZE];
1514         int f;
1515
1516         if (dkname[0] == '/') {
1517                 warnx("\"auto\" requires the usage of a canonical disk name");
1518                 return (NULL);
1519         }
1520         snprintf(nambuf, BBSIZE, "%s%s", _PATH_DEV, dkname);
1521         if ((f = open(nambuf, O_RDONLY)) == -1) {
1522                 warn("cannot open %s", nambuf);
1523                 return (NULL);
1524         }
1525
1526         /*
1527          * Try to use the new get-virgin-label ioctl.  If it fails,
1528          * fallback to the old get-disdk-info ioctl.
1529          */
1530         if (ioctl(f, DIOCGDVIRGIN, &dlab) < 0) {
1531                 if (ioctl(f, DIOCGDINFO, &dlab) < 0) {
1532                         warn("ioctl DIOCGDINFO");
1533                         close(f);
1534                         return (NULL);
1535                 }
1536         }
1537         close(f);
1538         dlab.d_boot0 = NULL;
1539         dlab.d_boot1 = NULL;
1540         return (&dlab);
1541 }
1542
1543 /*
1544  * If we are installing a boot program that doesn't fit in d_bbsize
1545  * we need to mark those partitions that the boot overflows into.
1546  * This allows newfs to prevent creation of a filesystem where it might
1547  * clobber bootstrap code.
1548  */
1549 void
1550 setbootflag(struct disklabel *lp)
1551 {
1552         struct partition *pp;
1553         int i, errors = 0;
1554         char part;
1555         u_long boffset;
1556
1557         if (bootbuf == 0)
1558                 return;
1559         boffset = bootsize / lp->d_secsize;
1560         for (i = 0; i < lp->d_npartitions; i++) {
1561                 part = 'a' + i;
1562                 pp = &lp->d_partitions[i];
1563                 if (pp->p_size == 0)
1564                         continue;
1565                 if (boffset <= pp->p_offset) {
1566                         if (pp->p_fstype == FS_BOOT)
1567                                 pp->p_fstype = FS_UNUSED;
1568                 } else if (pp->p_fstype != FS_BOOT) {
1569                         if (pp->p_fstype != FS_UNUSED) {
1570                                 fprintf(stderr,
1571                                         "boot overlaps used partition %c\n",
1572                                         part);
1573                                 errors++;
1574                         } else {
1575                                 pp->p_fstype = FS_BOOT;
1576                                 Warning("boot overlaps partition %c, %s",
1577                                         part, "marked as FS_BOOT");
1578                         }
1579                 }
1580         }
1581         if (errors)
1582                 errx(4, "cannot install boot program");
1583 }
1584
1585 /*VARARGS1*/
1586 void
1587 Warning(const char *fmt, ...)
1588 {
1589         va_list ap;
1590
1591         fprintf(stderr, "Warning, ");
1592         va_start(ap, fmt);
1593         vfprintf(stderr, fmt, ap);
1594         fprintf(stderr, "\n");
1595         va_end(ap);
1596 }
1597
1598 /*
1599  * Check to see if the bootblocks are in the wrong place.  FBsd5 bootblocks
1600  * and earlier DFly bb's are packed against the old disklabel and a new
1601  * disklabel would blow them up.  This is a hack that should be removed
1602  * in 2006 sometime (if ever).
1603  */
1604
1605 int
1606 checkoldboot(int f, const char *bootbuffer)
1607 {
1608         char buf[BBSIZE];
1609
1610         if (bootbuffer && strncmp(bootbuffer + 0x402, "BTX", 3) == 0)
1611                 return(0);
1612         lseek(f, (off_t)0, SEEK_SET);
1613         if (read(f, buf, sizeof(buf)) != sizeof(buf))
1614                 return(0);
1615         if (strncmp(buf + 0x402, "BTX", 3) == 0)  /* new location */
1616                 return(0);
1617         if (strncmp(buf + 0x316, "BTX", 3) == 0)  /* old location */
1618                 return(1);
1619         return(0);
1620 }
1621
1622 void
1623 usage(void)
1624 {
1625 #if NUMBOOT > 0
1626         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1627                 "usage: disklabel [-r] disk",
1628                 "\t\t(to read label)",
1629                 "       disklabel -w [-r] [-n] disk type [ packid ]",
1630                 "\t\t(to write label with existing boot program)",
1631                 "       disklabel -e [-r] [-n] disk",
1632                 "\t\t(to edit label)",
1633                 "       disklabel -R [-r] [-n] disk protofile",
1634                 "\t\t(to restore label with existing boot program)",
1635 #if NUMBOOT > 1
1636                 "       disklabel -B [-n] [ -b boot1 [ -s boot2 ] ] disk [ type ]",
1637                 "\t\t(to install boot program with existing label)",
1638                 "       disklabel -w -B [-n] [ -b boot1 [ -s boot2 ] ] disk type [ packid ]",
1639                 "\t\t(to write label and boot program)",
1640                 "       disklabel -R -B [-n] [ -b boot1 [ -s boot2 ] ] disk protofile [ type ]",
1641                 "\t\t(to restore label and boot program)",
1642 #else
1643                 "       disklabel -B [-n] [ -b bootprog ] disk [ type ]",
1644                 "\t\t(to install boot program with existing on-disk label)",
1645                 "       disklabel -w -B [-n] [ -b bootprog ] disk type [ packid ]",
1646                 "\t\t(to write label and install boot program)",
1647                 "       disklabel -R -B [-n] [ -b bootprog ] disk protofile [ type ]",
1648                 "\t\t(to restore label and install boot program)",
1649 #endif
1650                 "       disklabel [-NW] disk",
1651                 "\t\t(to write disable/enable label)");
1652 #else
1653         fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1654                 "usage: disklabel [-r] disk", "(to read label)",
1655                 "       disklabel -w [-r] [-n] disk type [ packid ]",
1656                 "\t\t(to write label)",
1657                 "       disklabel -e [-r] [-n] disk",
1658                 "\t\t(to edit label)",
1659                 "       disklabel -R [-r] [-n] disk protofile",
1660                 "\t\t(to restore label)",
1661                 "       disklabel [-NW] disk",
1662                 "\t\t(to write disable/enable label)");
1663 #endif
1664         exit(1);
1665 }