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