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