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