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