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