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