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