]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/bsdlabel/bsdlabel.c
MFC r302371:
[FreeBSD/stable/8.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 #if 0
44 #ifndef lint
45 static const char copyright[] =
46 "@(#) Copyright (c) 1987, 1993\n\
47         The Regents of the University of California.  All rights reserved.\n";
48 #endif /* not lint */
49
50 #ifndef lint
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 /* not lint */
54 #endif
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57
58 #include <sys/param.h>
59 #include <stdint.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 #define MAXPARTITIONS   20
67 #include <sys/disklabel.h>
68
69 #include <unistd.h>
70 #include <string.h>
71 #include <stdio.h>
72 #include <libgeom.h>
73 #include <stdlib.h>
74 #include <signal.h>
75 #include <stdarg.h>
76 #include <ctype.h>
77 #include <err.h>
78 #include <errno.h>
79
80 #include "pathnames.h"
81
82 static void     makelabel(const char *, struct disklabel *);
83 static int      geom_class_available(const char *);
84 static int      writelabel(void);
85 static int      readlabel(int flag);
86 static void     display(FILE *, const struct disklabel *);
87 static int      edit(void);
88 static int      editit(void);
89 static void     fixlabel(struct disklabel *);
90 static char     *skip(char *);
91 static char     *word(char *);
92 static int      getasciilabel(FILE *, struct disklabel *);
93 static int      getasciipartspec(char *, struct disklabel *, int, int);
94 static int      checklabel(struct disklabel *);
95 static void     usage(void);
96 static struct disklabel *getvirginlabel(void);
97
98 #define DEFEDITOR       _PATH_VI
99 #define DEFPARTITIONS   8
100
101 static char     *specname;
102 static char     *pname;
103 static char     tmpfil[] = PATH_TMPFILE;
104
105 static struct   disklabel lab;
106 static u_char   bootarea[BBSIZE];
107 static off_t    mediasize;
108 static ssize_t  secsize;
109 static char     blank[] = "";
110 static char     unknown[] = "unknown";
111
112 #define MAX_PART ('z')
113 #define MAX_NUM_PARTS (1 + MAX_PART - 'a')
114 static char    part_size_type[MAX_NUM_PARTS];
115 static char    part_offset_type[MAX_NUM_PARTS];
116 static int     part_set[MAX_NUM_PARTS];
117
118 static int      installboot;    /* non-zero if we should install a boot program */
119 static int      allfields;      /* present all fields in edit */
120 static char const *xxboot;      /* primary boot */
121
122 static uint32_t lba_offset;
123 #ifndef LABELSECTOR
124 #define LABELSECTOR -1
125 #endif
126 #ifndef LABELOFFSET
127 #define LABELOFFSET -1
128 #endif
129 static int labelsoffset = LABELSECTOR;
130 static int labeloffset = LABELOFFSET;
131 static int bbsize = BBSIZE;
132
133 enum    {
134         UNSPEC, EDIT, READ, RESTORE, WRITE, WRITEBOOT
135 } op = UNSPEC;
136
137
138 static int      disable_write;   /* set to disable writing to disk label */
139 static int      is_file;        /* work on a file (abs. pathname), "-f" opt. */
140
141 int
142 main(int argc, char *argv[])
143 {
144         FILE *t;
145         int ch, error, fd;
146         const char *name;
147         
148         error = 0;
149         name = NULL;
150
151         while ((ch = getopt(argc, argv, "ABb:efm:nRrw")) != -1)
152                 switch (ch) {
153                         case 'A':
154                                 allfields = 1;
155                                 break;
156                         case 'B':
157                                 ++installboot;
158                                 break;
159                         case 'b':
160                                 xxboot = optarg;
161                                 break;
162                         case 'f':
163                                 is_file=1;
164                                 break;
165                         case 'm':
166                                 if (!strcmp(optarg, "i386") ||
167                                     !strcmp(optarg, "amd64") ||
168                                     !strcmp(optarg, "ia64") ||
169                                     !strcmp(optarg, "pc98")) {
170                                         labelsoffset = 1;
171                                         labeloffset = 0;
172                                         bbsize = 8192;
173                                 } else {
174                                         errx(1, "Unsupported architecture");
175                                 }
176                                 break;
177                         case 'n':
178                                 disable_write = 1;
179                                 break;
180                         case 'R':
181                                 if (op != UNSPEC)
182                                         usage();
183                                 op = RESTORE;
184                                 break;
185                         case 'e':
186                                 if (op != UNSPEC)
187                                         usage();
188                                 op = EDIT;
189                                 break;
190                         case 'r':
191                                 /*
192                                  * We accept and ignode -r for compatibility with
193                                  * historically disklabel usage.
194                                  */
195                                 break;
196                         case 'w':
197                                 if (op != UNSPEC)
198                                         usage();
199                                 op = WRITE;
200                                 break;
201                         case '?':
202                         default:
203                                 usage();
204                 }
205         argc -= optind;
206         argv += optind;
207
208         if (argc < 1)
209                 usage();
210         if (labelsoffset < 0 || labeloffset < 0)
211                 errx(1, "a -m <architecture> option must be specified");
212
213         /* Figure out the names of the thing we're working on */
214         if (is_file) {
215                 specname = argv[0];
216         } else {
217                 specname = g_device_path(argv[0]);
218                 if (specname == NULL) {
219                         warn("unable to get correct path for %s", argv[0]);
220                         return(1);
221                 }
222                 fd = open(specname, O_RDONLY);
223                 if (fd < 0) {
224                         warn("error opening %s", specname);
225                         return(1);
226                 }
227                 pname = g_providername(fd);
228                 if (pname == NULL) {
229                         warn("error getting providername for %s", specname);
230                         close(fd);
231                         return(1);
232                 }
233                 close(fd);
234         }
235
236         if (installboot && op == UNSPEC)
237                 op = WRITEBOOT;
238         else if (op == UNSPEC)
239                 op = READ;
240
241         switch(op) {
242
243         case UNSPEC:
244                 break;
245
246         case EDIT:
247                 if (argc != 1)
248                         usage();
249                 readlabel(1);
250                 fixlabel(&lab);
251                 error = edit();
252                 break;
253
254         case READ:
255                 if (argc != 1)
256                         usage();
257                 readlabel(1);
258                 display(stdout, NULL);
259                 error = checklabel(NULL);
260                 break;
261
262         case RESTORE:
263                 if (argc != 2)
264                         usage();
265                 if (!(t = fopen(argv[1], "r")))
266                         err(4, "fopen %s", argv[1]);
267                 readlabel(0);
268                 if (!getasciilabel(t, &lab))
269                         exit(1);
270                 error = writelabel();
271                 break;
272
273         case WRITE:
274                 if (argc == 2)
275                         name = argv[1];
276                 else if (argc == 1)
277                         name = "auto";
278                 else
279                         usage();
280                 readlabel(0);
281                 makelabel(name, &lab);
282                 fixlabel(&lab);
283                 if (checklabel(NULL) == 0)
284                         error = writelabel();
285                 break;
286
287         case WRITEBOOT:
288
289                 readlabel(1);
290                 fixlabel(&lab);
291                 if (argc == 2)
292                         makelabel(argv[1], &lab);
293                 if (checklabel(NULL) == 0)
294                         error = writelabel();
295                 break;
296         }
297         exit(error);
298 }
299
300 static void
301 fixlabel(struct disklabel *lp)
302 {
303         struct partition *dp;
304         int i;
305
306         for (i = 0; i < lp->d_npartitions; i++) {
307                 if (i == RAW_PART)
308                         continue;
309                 if (lp->d_partitions[i].p_size)
310                         return;
311         }
312
313         dp = &lp->d_partitions[0];
314         dp->p_offset = BBSIZE / secsize;
315         dp->p_size = lp->d_secperunit - dp->p_offset;
316 }
317
318 /*
319  * Construct a prototype disklabel from /etc/disktab.
320  */
321 static void
322 makelabel(const char *type, struct disklabel *lp)
323 {
324         struct disklabel *dp;
325
326         if (strcmp(type, "auto") == 0)
327                 dp = getvirginlabel();
328         else
329                 dp = getdiskbyname(type);
330         if (dp == NULL)
331                 errx(1, "%s: unknown disk type", type);
332         *lp = *dp;
333         bzero(lp->d_packname, sizeof(lp->d_packname));
334 }
335
336 static void
337 readboot(void)
338 {
339         int fd;
340         struct stat st;
341
342         if (xxboot == NULL)
343                 xxboot = "/boot/boot";
344         fd = open(xxboot, O_RDONLY);
345         if (fd < 0)
346                 err(1, "cannot open %s", xxboot);
347         fstat(fd, &st);
348         if (st.st_size <= BBSIZE) {
349                 if (read(fd, bootarea, st.st_size) != st.st_size)
350                         err(1, "read error %s", xxboot);
351                 return;
352         }
353         errx(1, "boot code %s is wrong size", xxboot);
354 }
355
356 static int
357 geom_class_available(const char *name)
358 {
359         struct gclass *class;
360         struct gmesh mesh;
361         int error;
362
363         error = geom_gettree(&mesh);
364         if (error != 0)
365                 errc(1, error, "Cannot get GEOM tree");
366
367         LIST_FOREACH(class, &mesh.lg_class, lg_class) {
368                 if (strcmp(class->lg_name, name) == 0) {
369                         geom_deletetree(&mesh);
370                         return (1);
371                 }
372         }
373
374         geom_deletetree(&mesh);
375
376         return (0);
377 }
378
379 static int
380 writelabel(void)
381 {
382         int i, fd, serrno;
383         struct gctl_req *grq;
384         char const *errstr;
385         struct disklabel *lp = &lab;
386
387         if (disable_write) {
388                 warnx("write to disk label supressed - label was as follows:");
389                 display(stdout, NULL);
390                 return (0);
391         }
392
393         lp->d_magic = DISKMAGIC;
394         lp->d_magic2 = DISKMAGIC;
395         lp->d_checksum = 0;
396         lp->d_checksum = dkcksum(lp);
397         if (installboot)
398                 readboot();
399         for (i = 0; i < lab.d_npartitions; i++)
400                 if (lab.d_partitions[i].p_size)
401                         lab.d_partitions[i].p_offset += lba_offset;
402         bsd_disklabel_le_enc(bootarea + labeloffset + labelsoffset * secsize,
403             lp);
404
405         fd = open(specname, O_RDWR);
406         if (fd < 0) {
407                 if (is_file) {
408                         warn("cannot open file %s for writing label", specname);
409                         return(1);
410                 } else
411                         serrno = errno;
412
413                 if (geom_class_available("PART") != 0) {
414                         /*
415                          * Since we weren't able open provider for
416                          * writing, then recommend user to use gpart(8).
417                          */
418                         warnc(serrno,
419                             "cannot open provider %s for writing label",
420                             specname);
421                         warnx("Try to use gpart(8).");
422                         return (1);
423                 }
424
425                 /* Give up if GEOM_BSD is not available. */
426                 if (geom_class_available("BSD") == 0) {
427                         warnc(serrno, "%s", specname);
428                         return (1);
429                 }
430
431                 grq = gctl_get_handle();
432                 gctl_ro_param(grq, "verb", -1, "write label");
433                 gctl_ro_param(grq, "class", -1, "BSD");
434                 gctl_ro_param(grq, "geom", -1, pname);
435                 gctl_ro_param(grq, "label", 148+16*8,
436                         bootarea + labeloffset + labelsoffset * secsize);
437                 errstr = gctl_issue(grq);
438                 if (errstr != NULL) {
439                         warnx("%s", errstr);
440                         gctl_free(grq);
441                         return(1);
442                 }
443                 gctl_free(grq);
444                 if (installboot) {
445                         grq = gctl_get_handle();
446                         gctl_ro_param(grq, "verb", -1, "write bootcode");
447                         gctl_ro_param(grq, "class", -1, "BSD");
448                         gctl_ro_param(grq, "geom", -1, pname);
449                         gctl_ro_param(grq, "bootcode", BBSIZE, bootarea);
450                         errstr = gctl_issue(grq);
451                         if (errstr != NULL) {
452                                 warnx("%s", errstr);
453                                 gctl_free(grq);
454                                 return (1);
455                         }
456                         gctl_free(grq);
457                 }
458         } else {
459                 if (write(fd, bootarea, bbsize) != bbsize) {
460                         warn("write %s", specname);
461                         close (fd);
462                         return (1);
463                 }
464                 close (fd);
465         }
466         return (0);
467 }
468
469 static void
470 get_file_parms(int f)
471 {
472         int i;
473         struct stat sb;
474
475         if (fstat(f, &sb) != 0)
476                 err(4, "fstat failed");
477         i = sb.st_mode & S_IFMT;
478         if (i != S_IFREG && i != S_IFLNK)
479                 errx(4, "%s is not a valid file or link", specname);
480         secsize = DEV_BSIZE;
481         mediasize = sb.st_size;
482 }
483
484 /*
485  * Fetch disklabel for disk.
486  */
487 static int
488 readlabel(int flag)
489 {
490         ssize_t nbytes;
491         uint32_t lba;
492         int f, i;
493         int error;
494
495         f = open(specname, O_RDONLY);
496         if (f < 0)
497                 err(1, specname);
498         if (is_file)
499                 get_file_parms(f);
500         else {
501                 mediasize = g_mediasize(f);
502                 secsize = g_sectorsize(f);
503                 if (secsize < 0 || mediasize < 0)
504                         err(4, "cannot get disk geometry");
505         }
506         if (mediasize > (off_t)0xffffffff * secsize)
507                 errx(1,
508                     "disks with more than 2^32-1 sectors are not supported");
509         (void)lseek(f, (off_t)0, SEEK_SET);
510         nbytes = read(f, bootarea, BBSIZE);
511         if (nbytes == -1)
512                 err(4, "%s read", specname);
513         if (nbytes != BBSIZE)
514                 errx(4, "couldn't read %d bytes from %s", BBSIZE, specname);
515         close (f);
516         error = bsd_disklabel_le_dec(
517             bootarea + (labeloffset + labelsoffset * secsize),
518             &lab, MAXPARTITIONS);
519         if (flag && error)
520                 errx(1, "%s: no valid label found", specname);
521
522         if (is_file)
523                 return(0);
524
525         /*
526          * Compensate for absolute block addressing by finding the
527          * smallest partition offset and if the offset of the 'c'
528          * partition is equal to that, subtract it from all offsets.
529          */
530         lba = ~0;
531         for (i = 0; i < lab.d_npartitions; i++) {
532                 if (lab.d_partitions[i].p_size)
533                         lba = MIN(lba, lab.d_partitions[i].p_offset);
534         }
535         if (lba != 0 && lab.d_partitions[RAW_PART].p_offset == lba) {
536                 for (i = 0; i < lab.d_npartitions; i++) {
537                         if (lab.d_partitions[i].p_size)
538                                 lab.d_partitions[i].p_offset -= lba;
539                 }
540                 /*
541                  * Save the offset so that we can write the label
542                  * back with absolute block addresses.
543                  */
544                 lba_offset = lba;
545         }
546         return (error);
547 }
548
549
550 static void
551 display(FILE *f, const struct disklabel *lp)
552 {
553         int i, j;
554         const struct partition *pp;
555
556         if (lp == NULL)
557                 lp = &lab;
558
559         fprintf(f, "# %s:\n", specname);
560         if (allfields) {
561                 if (lp->d_type < DKMAXTYPES)
562                         fprintf(f, "type: %s\n", dktypenames[lp->d_type]);
563                 else
564                         fprintf(f, "type: %u\n", lp->d_type);
565                 fprintf(f, "disk: %.*s\n", (int)sizeof(lp->d_typename),
566                         lp->d_typename);
567                 fprintf(f, "label: %.*s\n", (int)sizeof(lp->d_packname),
568                         lp->d_packname);
569                 fprintf(f, "flags:");
570                 if (lp->d_flags & D_REMOVABLE)
571                         fprintf(f, " removeable");
572                 if (lp->d_flags & D_ECC)
573                         fprintf(f, " ecc");
574                 if (lp->d_flags & D_BADSECT)
575                         fprintf(f, " badsect");
576                 fprintf(f, "\n");
577                 fprintf(f, "bytes/sector: %lu\n", (u_long)lp->d_secsize);
578                 fprintf(f, "sectors/track: %lu\n", (u_long)lp->d_nsectors);
579                 fprintf(f, "tracks/cylinder: %lu\n", (u_long)lp->d_ntracks);
580                 fprintf(f, "sectors/cylinder: %lu\n", (u_long)lp->d_secpercyl);
581                 fprintf(f, "cylinders: %lu\n", (u_long)lp->d_ncylinders);
582                 fprintf(f, "sectors/unit: %lu\n", (u_long)lp->d_secperunit);
583                 fprintf(f, "rpm: %u\n", lp->d_rpm);
584                 fprintf(f, "interleave: %u\n", lp->d_interleave);
585                 fprintf(f, "trackskew: %u\n", lp->d_trackskew);
586                 fprintf(f, "cylinderskew: %u\n", lp->d_cylskew);
587                 fprintf(f, "headswitch: %lu\t\t# milliseconds\n",
588                     (u_long)lp->d_headswitch);
589                 fprintf(f, "track-to-track seek: %ld\t# milliseconds\n",
590                     (u_long)lp->d_trkseek);
591                 fprintf(f, "drivedata: ");
592                 for (i = NDDATA - 1; i >= 0; i--)
593                         if (lp->d_drivedata[i])
594                                 break;
595                 if (i < 0)
596                         i = 0;
597                 for (j = 0; j <= i; j++)
598                         fprintf(f, "%lu ", (u_long)lp->d_drivedata[j]);
599                 fprintf(f, "\n\n");
600         }
601         fprintf(f, "%u partitions:\n", lp->d_npartitions);
602         fprintf(f,
603             "#          size     offset    fstype   [fsize bsize bps/cpg]\n");
604         pp = lp->d_partitions;
605         for (i = 0; i < lp->d_npartitions; i++, pp++) {
606                 if (pp->p_size) {
607                         fprintf(f, "  %c: %10lu %10lu  ", 'a' + i,
608                            (u_long)pp->p_size, (u_long)pp->p_offset);
609                         if (pp->p_fstype < FSMAXTYPES)
610                                 fprintf(f, "%8.8s", fstypenames[pp->p_fstype]);
611                         else
612                                 fprintf(f, "%8d", pp->p_fstype);
613                         switch (pp->p_fstype) {
614
615                         case FS_UNUSED:                         /* XXX */
616                                 fprintf(f, "    %5lu %5lu %2s",
617                                     (u_long)pp->p_fsize,
618                                     (u_long)(pp->p_fsize * pp->p_frag), "");
619                                 break;
620
621                         case FS_BSDFFS:
622                                 fprintf(f, "    %5lu %5lu %5u",
623                                     (u_long)pp->p_fsize,
624                                     (u_long)(pp->p_fsize * pp->p_frag),
625                                     pp->p_cpg);
626                                 break;
627
628                         case FS_BSDLFS:
629                                 fprintf(f, "    %5lu %5lu %5d",
630                                     (u_long)pp->p_fsize,
631                                     (u_long)(pp->p_fsize * pp->p_frag),
632                                     pp->p_cpg);
633                                 break;
634
635                         default:
636                                 fprintf(f, "%20.20s", "");
637                                 break;
638                         }
639                         if (i == RAW_PART) {
640                                 fprintf(f, "  # \"raw\" part, don't edit");
641                         }
642                         fprintf(f, "\n");
643                 }
644         }
645         fflush(f);
646 }
647
648 static int
649 edit(void)
650 {
651         int c, fd;
652         struct disklabel label;
653         FILE *fp;
654
655         if ((fd = mkstemp(tmpfil)) == -1 ||
656             (fp = fdopen(fd, "w")) == NULL) {
657                 warnx("can't create %s", tmpfil);
658                 return (1);
659         }
660         display(fp, NULL);
661         fclose(fp);
662         for (;;) {
663                 if (!editit())
664                         break;
665                 fp = fopen(tmpfil, "r");
666                 if (fp == NULL) {
667                         warnx("can't reopen %s for reading", tmpfil);
668                         break;
669                 }
670                 bzero((char *)&label, sizeof(label));
671                 c = getasciilabel(fp, &label);
672                 fclose(fp);
673                 if (c) {
674                         lab = label;
675                         if (writelabel() == 0) {
676                                 (void) unlink(tmpfil);
677                                 return (0);
678                         }
679                 }
680                 printf("re-edit the label? [y]: ");
681                 fflush(stdout);
682                 c = getchar();
683                 if (c != EOF && c != (int)'\n')
684                         while (getchar() != (int)'\n')
685                                 ;
686                 if  (c == (int)'n')
687                         break;
688         }
689         (void) unlink(tmpfil);
690         return (1);
691 }
692
693 static int
694 editit(void)
695 {
696         int pid, xpid;
697         int locstat, omask;
698         const char *ed;
699
700         omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
701         while ((pid = fork()) < 0) {
702                 if (errno == EPROCLIM) {
703                         warnx("you have too many processes");
704                         return(0);
705                 }
706                 if (errno != EAGAIN) {
707                         warn("fork");
708                         return(0);
709                 }
710                 sleep(1);
711         }
712         if (pid == 0) {
713                 sigsetmask(omask);
714                 setgid(getgid());
715                 setuid(getuid());
716                 if ((ed = getenv("EDITOR")) == (char *)0)
717                         ed = DEFEDITOR;
718                 execlp(ed, ed, tmpfil, (char *)0);
719                 err(1, "%s", ed);
720         }
721         while ((xpid = wait(&locstat)) >= 0)
722                 if (xpid == pid)
723                         break;
724         sigsetmask(omask);
725         return(!locstat);
726 }
727
728 static char *
729 skip(char *cp)
730 {
731
732         while (*cp != '\0' && isspace(*cp))
733                 cp++;
734         if (*cp == '\0' || *cp == '#')
735                 return (NULL);
736         return (cp);
737 }
738
739 static char *
740 word(char *cp)
741 {
742         char c;
743
744         while (*cp != '\0' && !isspace(*cp) && *cp != '#')
745                 cp++;
746         if ((c = *cp) != '\0') {
747                 *cp++ = '\0';
748                 if (c != '#')
749                         return (skip(cp));
750         }
751         return (NULL);
752 }
753
754 /*
755  * Read an ascii label in from fd f,
756  * in the same format as that put out by display(),
757  * and fill in lp.
758  */
759 static int
760 getasciilabel(FILE *f, struct disklabel *lp)
761 {
762         char *cp, *endp;
763         const char **cpp;
764         u_int part;
765         char *tp, line[BUFSIZ];
766         u_long v;
767         int lineno = 0, errors = 0;
768         int i;
769
770         makelabel("auto", lp);
771         bzero(&part_set, sizeof(part_set));
772         bzero(&part_size_type, sizeof(part_size_type));
773         bzero(&part_offset_type, sizeof(part_offset_type));
774         lp->d_bbsize = BBSIZE;                          /* XXX */
775         lp->d_sbsize = 0;                               /* XXX */
776         while (fgets(line, sizeof(line) - 1, f)) {
777                 lineno++;
778                 if ((cp = index(line,'\n')) != 0)
779                         *cp = '\0';
780                 cp = skip(line);
781                 if (cp == NULL)
782                         continue;
783                 tp = index(cp, ':');
784                 if (tp == NULL) {
785                         fprintf(stderr, "line %d: syntax error\n", lineno);
786                         errors++;
787                         continue;
788                 }
789                 *tp++ = '\0', tp = skip(tp);
790                 if (!strcmp(cp, "type")) {
791                         if (tp == NULL)
792                                 tp = unknown;
793                         cpp = dktypenames;
794                         for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
795                                 if (*cpp && !strcmp(*cpp, tp)) {
796                                         lp->d_type = cpp - dktypenames;
797                                         break;
798                                 }
799                         if (cpp < &dktypenames[DKMAXTYPES])
800                                 continue;
801                         errno = 0;
802                         v = strtoul(tp, &endp, 10);
803                         if (errno != 0 || *endp != '\0')
804                                 v = DKMAXTYPES;
805                         if (v >= DKMAXTYPES)
806                                 fprintf(stderr, "line %d:%s %lu\n", lineno,
807                                     "Warning, unknown disk type", v);
808                         else
809                                 lp->d_type = v;
810                         continue;
811                 }
812                 if (!strcmp(cp, "flags")) {
813                         for (v = 0; (cp = tp) && *cp != '\0';) {
814                                 tp = word(cp);
815                                 if (!strcmp(cp, "removeable"))
816                                         v |= D_REMOVABLE;
817                                 else if (!strcmp(cp, "ecc"))
818                                         v |= D_ECC;
819                                 else if (!strcmp(cp, "badsect"))
820                                         v |= D_BADSECT;
821                                 else {
822                                         fprintf(stderr,
823                                             "line %d: %s: bad flag\n",
824                                             lineno, cp);
825                                         errors++;
826                                 }
827                         }
828                         lp->d_flags = v;
829                         continue;
830                 }
831                 if (!strcmp(cp, "drivedata")) {
832                         for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
833                                 lp->d_drivedata[i++] = strtoul(cp, NULL, 10);
834                                 tp = word(cp);
835                         }
836                         continue;
837                 }
838                 if (sscanf(cp, "%lu partitions", &v) == 1) {
839                         if (v > MAXPARTITIONS) {
840                                 fprintf(stderr,
841                                     "line %d: bad # of partitions\n", lineno);
842                                 lp->d_npartitions = MAXPARTITIONS;
843                                 errors++;
844                         } else if (v < DEFPARTITIONS) {
845                                 fprintf(stderr,
846                                     "line %d: bad # of partitions\n", lineno);
847                                 lp->d_npartitions = DEFPARTITIONS;
848                                 errors++;
849                         } else
850                                 lp->d_npartitions = v;
851                         continue;
852                 }
853                 if (tp == NULL)
854                         tp = blank;
855                 if (!strcmp(cp, "disk")) {
856                         strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
857                         continue;
858                 }
859                 if (!strcmp(cp, "label")) {
860                         strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
861                         continue;
862                 }
863                 if (!strcmp(cp, "bytes/sector")) {
864                         v = strtoul(tp, NULL, 10);
865                         if (v == 0 || (v % DEV_BSIZE) != 0) {
866                                 fprintf(stderr,
867                                     "line %d: %s: bad sector size\n",
868                                     lineno, tp);
869                                 errors++;
870                         } else
871                                 lp->d_secsize = v;
872                         continue;
873                 }
874                 if (!strcmp(cp, "sectors/track")) {
875                         v = strtoul(tp, NULL, 10);
876 #if (ULONG_MAX != 0xffffffffUL)
877                         if (v == 0 || v > 0xffffffff)
878 #else
879                         if (v == 0)
880 #endif
881                         {
882                                 fprintf(stderr, "line %d: %s: bad %s\n",
883                                     lineno, tp, cp);
884                                 errors++;
885                         } else
886                                 lp->d_nsectors = v;
887                         continue;
888                 }
889                 if (!strcmp(cp, "sectors/cylinder")) {
890                         v = strtoul(tp, NULL, 10);
891                         if (v == 0) {
892                                 fprintf(stderr, "line %d: %s: bad %s\n",
893                                     lineno, tp, cp);
894                                 errors++;
895                         } else
896                                 lp->d_secpercyl = v;
897                         continue;
898                 }
899                 if (!strcmp(cp, "tracks/cylinder")) {
900                         v = strtoul(tp, NULL, 10);
901                         if (v == 0) {
902                                 fprintf(stderr, "line %d: %s: bad %s\n",
903                                     lineno, tp, cp);
904                                 errors++;
905                         } else
906                                 lp->d_ntracks = v;
907                         continue;
908                 }
909                 if (!strcmp(cp, "cylinders")) {
910                         v = strtoul(tp, NULL, 10);
911                         if (v == 0) {
912                                 fprintf(stderr, "line %d: %s: bad %s\n",
913                                     lineno, tp, cp);
914                                 errors++;
915                         } else
916                                 lp->d_ncylinders = v;
917                         continue;
918                 }
919                 if (!strcmp(cp, "sectors/unit")) {
920                         v = strtoul(tp, NULL, 10);
921                         if (v == 0) {
922                                 fprintf(stderr, "line %d: %s: bad %s\n",
923                                     lineno, tp, cp);
924                                 errors++;
925                         } else
926                                 lp->d_secperunit = v;
927                         continue;
928                 }
929                 if (!strcmp(cp, "rpm")) {
930                         v = strtoul(tp, NULL, 10);
931                         if (v == 0 || v > USHRT_MAX) {
932                                 fprintf(stderr, "line %d: %s: bad %s\n",
933                                     lineno, tp, cp);
934                                 errors++;
935                         } else
936                                 lp->d_rpm = v;
937                         continue;
938                 }
939                 if (!strcmp(cp, "interleave")) {
940                         v = strtoul(tp, NULL, 10);
941                         if (v == 0 || v > USHRT_MAX) {
942                                 fprintf(stderr, "line %d: %s: bad %s\n",
943                                     lineno, tp, cp);
944                                 errors++;
945                         } else
946                                 lp->d_interleave = v;
947                         continue;
948                 }
949                 if (!strcmp(cp, "trackskew")) {
950                         v = strtoul(tp, NULL, 10);
951                         if (v > USHRT_MAX) {
952                                 fprintf(stderr, "line %d: %s: bad %s\n",
953                                     lineno, tp, cp);
954                                 errors++;
955                         } else
956                                 lp->d_trackskew = v;
957                         continue;
958                 }
959                 if (!strcmp(cp, "cylinderskew")) {
960                         v = strtoul(tp, NULL, 10);
961                         if (v > USHRT_MAX) {
962                                 fprintf(stderr, "line %d: %s: bad %s\n",
963                                     lineno, tp, cp);
964                                 errors++;
965                         } else
966                                 lp->d_cylskew = v;
967                         continue;
968                 }
969                 if (!strcmp(cp, "headswitch")) {
970                         v = strtoul(tp, NULL, 10);
971                         lp->d_headswitch = v;
972                         continue;
973                 }
974                 if (!strcmp(cp, "track-to-track seek")) {
975                         v = strtoul(tp, NULL, 10);
976                         lp->d_trkseek = v;
977                         continue;
978                 }
979                 /* the ':' was removed above */
980                 if (*cp < 'a' || *cp > MAX_PART || cp[1] != '\0') {
981                         fprintf(stderr,
982                             "line %d: %s: Unknown disklabel field\n", lineno,
983                             cp);
984                         errors++;
985                         continue;
986                 }
987
988                 /* Process a partition specification line. */
989                 part = *cp - 'a';
990                 if (part >= lp->d_npartitions) {
991                         fprintf(stderr,
992                             "line %d: partition name out of range a-%c: %s\n",
993                             lineno, 'a' + lp->d_npartitions - 1, cp);
994                         errors++;
995                         continue;
996                 }
997                 part_set[part] = 1;
998
999                 if (getasciipartspec(tp, lp, part, lineno) != 0) {
1000                         errors++;
1001                         break;
1002                 }
1003         }
1004         errors += checklabel(lp);
1005         return (errors == 0);
1006 }
1007
1008 #define NXTNUM(n) do { \
1009         if (tp == NULL) { \
1010                 fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1011                 return (1); \
1012         } else { \
1013                 cp = tp, tp = word(cp); \
1014                 (n) = strtoul(cp, NULL, 10); \
1015         } \
1016 } while (0)
1017
1018 /* retain 1 character following number */
1019 #define NXTWORD(w,n) do { \
1020         if (tp == NULL) { \
1021                 fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1022                 return (1); \
1023         } else { \
1024                 char *tmp; \
1025                 cp = tp, tp = word(cp); \
1026                 (n) = strtoul(cp, &tmp, 10); \
1027                 if (tmp) (w) = *tmp; \
1028         } \
1029 } while (0)
1030
1031 /*
1032  * Read a partition line into partition `part' in the specified disklabel.
1033  * Return 0 on success, 1 on failure.
1034  */
1035 static int
1036 getasciipartspec(char *tp, struct disklabel *lp, int part, int lineno)
1037 {
1038         struct partition *pp;
1039         char *cp, *endp;
1040         const char **cpp;
1041         u_long v;
1042
1043         pp = &lp->d_partitions[part];
1044         cp = NULL;
1045
1046         v = 0;
1047         NXTWORD(part_size_type[part],v);
1048         if (v == 0 && part_size_type[part] != '*') {
1049                 fprintf(stderr,
1050                     "line %d: %s: bad partition size\n", lineno, cp);
1051                 return (1);
1052         }
1053         pp->p_size = v;
1054
1055         v = 0;
1056         NXTWORD(part_offset_type[part],v);
1057         if (v == 0 && part_offset_type[part] != '*' &&
1058             part_offset_type[part] != '\0') {
1059                 fprintf(stderr,
1060                     "line %d: %s: bad partition offset\n", lineno, cp);
1061                 return (1);
1062         }
1063         pp->p_offset = v;
1064         if (tp == NULL) {
1065                 fprintf(stderr, "line %d: missing file system type\n", lineno);
1066                 return (1);
1067         }
1068         cp = tp, tp = word(cp);
1069         for (cpp = fstypenames; cpp < &fstypenames[FSMAXTYPES]; cpp++)
1070                 if (*cpp && !strcmp(*cpp, cp))
1071                         break;
1072         if (*cpp != NULL) {
1073                 pp->p_fstype = cpp - fstypenames;
1074         } else {
1075                 if (isdigit(*cp)) {
1076                         errno = 0;
1077                         v = strtoul(cp, &endp, 10);
1078                         if (errno != 0 || *endp != '\0')
1079                                 v = FSMAXTYPES;
1080                 } else
1081                         v = FSMAXTYPES;
1082                 if (v >= FSMAXTYPES) {
1083                         fprintf(stderr,
1084                             "line %d: Warning, unknown file system type %s\n",
1085                             lineno, cp);
1086                         v = FS_UNUSED;
1087                 }
1088                 pp->p_fstype = v;
1089         }
1090
1091         switch (pp->p_fstype) {
1092         case FS_UNUSED:
1093         case FS_BSDFFS:
1094         case FS_BSDLFS:
1095                 /* accept defaults for fsize/frag/cpg */
1096                 if (tp) {
1097                         NXTNUM(pp->p_fsize);
1098                         if (pp->p_fsize == 0)
1099                                 break;
1100                         NXTNUM(v);
1101                         pp->p_frag = v / pp->p_fsize;
1102                         if (tp != NULL)
1103                                 NXTNUM(pp->p_cpg);
1104                 }
1105                 /* else default to 0's */
1106                 break;
1107         default:
1108                 break;
1109         }
1110         return (0);
1111 }
1112
1113 /*
1114  * Check disklabel for errors and fill in
1115  * derived fields according to supplied values.
1116  */
1117 static int
1118 checklabel(struct disklabel *lp)
1119 {
1120         struct partition *pp;
1121         int i, errors = 0;
1122         char part;
1123         u_long base_offset, needed, total_size, total_percent, current_offset;
1124         long free_space;
1125         int seen_default_offset;
1126         int hog_part;
1127         int j;
1128         struct partition *pp2;
1129
1130         if (lp == NULL)
1131                 lp = &lab;
1132
1133         if (allfields) {
1134
1135                 if (lp->d_secsize == 0) {
1136                         fprintf(stderr, "sector size 0\n");
1137                         return (1);
1138                 }
1139                 if (lp->d_nsectors == 0) {
1140                         fprintf(stderr, "sectors/track 0\n");
1141                         return (1);
1142                 }
1143                 if (lp->d_ntracks == 0) {
1144                         fprintf(stderr, "tracks/cylinder 0\n");
1145                         return (1);
1146                 }
1147                 if  (lp->d_ncylinders == 0) {
1148                         fprintf(stderr, "cylinders/unit 0\n");
1149                         errors++;
1150                 }
1151                 if (lp->d_rpm == 0)
1152                         warnx("revolutions/minute 0");
1153                 if (lp->d_secpercyl == 0)
1154                         lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1155                 if (lp->d_secperunit == 0)
1156                         lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1157                 if (lp->d_bbsize == 0) {
1158                         fprintf(stderr, "boot block size 0\n");
1159                         errors++;
1160                 } else if (lp->d_bbsize % lp->d_secsize)
1161                         warnx("boot block size %% sector-size != 0");
1162                 if (lp->d_npartitions > MAXPARTITIONS) {
1163                         warnx("number of partitions (%lu) > MAXPARTITIONS (%d)",
1164                             (u_long)lp->d_npartitions, MAXPARTITIONS);
1165                         errors++;
1166                 }
1167                 if (lp->d_npartitions < DEFPARTITIONS) {
1168                         warnx("number of partitions (%lu) < DEFPARTITIONS (%d)",
1169                             (u_long)lp->d_npartitions, DEFPARTITIONS);
1170                         errors++;
1171                 }
1172         } else {
1173                 struct disklabel *vl;
1174
1175                 vl = getvirginlabel();
1176                 if (lp->d_secsize == 0)
1177                         lp->d_secsize = vl->d_secsize;
1178                 if (lp->d_nsectors == 0)
1179                         lp->d_nsectors = vl->d_nsectors;
1180                 if (lp->d_ntracks == 0)
1181                         lp->d_ntracks = vl->d_ntracks;
1182                 if (lp->d_ncylinders == 0)
1183                         lp->d_ncylinders = vl->d_ncylinders;
1184                 if (lp->d_rpm == 0)
1185                         lp->d_rpm = vl->d_rpm;
1186                 if (lp->d_interleave == 0)
1187                         lp->d_interleave = vl->d_interleave;
1188                 if (lp->d_secpercyl == 0)
1189                         lp->d_secpercyl = vl->d_secpercyl;
1190                 if (lp->d_secperunit == 0 ||
1191                     lp->d_secperunit > vl->d_secperunit)
1192                         lp->d_secperunit = vl->d_secperunit;
1193                 if (lp->d_bbsize == 0)
1194                         lp->d_bbsize = vl->d_bbsize;
1195                 if (lp->d_npartitions < DEFPARTITIONS ||
1196                     lp->d_npartitions > MAXPARTITIONS)
1197                         lp->d_npartitions = vl->d_npartitions;
1198         }
1199
1200
1201         /* first allocate space to the partitions, then offsets */
1202         total_size = 0; /* in sectors */
1203         total_percent = 0; /* in percent */
1204         hog_part = -1;
1205         /* find all fixed partitions */
1206         for (i = 0; i < lp->d_npartitions; i++) {
1207                 pp = &lp->d_partitions[i];
1208                 if (part_set[i]) {
1209                         if (part_size_type[i] == '*') {
1210                                 if (i == RAW_PART) {
1211                                         pp->p_size = lp->d_secperunit;
1212                                 } else {
1213                                         if (hog_part != -1)
1214                                                 warnx("Too many '*' partitions (%c and %c)",
1215                                                     hog_part + 'a',i + 'a');
1216                                         else
1217                                                 hog_part = i;
1218                                 }
1219                         } else {
1220                                 off_t size;
1221
1222                                 size = pp->p_size;
1223                                 switch (part_size_type[i]) {
1224                                 case '%':
1225                                         total_percent += size;
1226                                         break;
1227                                 case 't':
1228                                 case 'T':
1229                                         size *= 1024ULL;
1230                                         /* FALLTHROUGH */
1231                                 case 'g':
1232                                 case 'G':
1233                                         size *= 1024ULL;
1234                                         /* FALLTHROUGH */
1235                                 case 'm':
1236                                 case 'M':
1237                                         size *= 1024ULL;
1238                                         /* FALLTHROUGH */
1239                                 case 'k':
1240                                 case 'K':
1241                                         size *= 1024ULL;
1242                                         break;
1243                                 case '\0':
1244                                         break;
1245                                 default:
1246                                         warnx("unknown multiplier suffix '%c' for partition %c (should be K, M, G or T)",
1247                                             part_size_type[i], i + 'a');
1248                                         break;
1249                                 }
1250                                 /* don't count %'s yet */
1251                                 if (part_size_type[i] != '%') {
1252                                         /*
1253                                          * for all not in sectors, convert to
1254                                          * sectors
1255                                          */
1256                                         if (part_size_type[i] != '\0') {
1257                                                 if (size % lp->d_secsize != 0)
1258                                                         warnx("partition %c not an integer number of sectors",
1259                                                             i + 'a');
1260                                                 size /= lp->d_secsize;
1261                                                 pp->p_size = size;
1262                                         }
1263                                         /* else already in sectors */
1264                                         if (i != RAW_PART)
1265                                                 total_size += size;
1266                                 }
1267                         }
1268                 }
1269         }
1270
1271         /* Find out the total free space, excluding the boot block area. */
1272         base_offset = BBSIZE / secsize;
1273         free_space = 0;
1274         for (i = 0; i < lp->d_npartitions; i++) {
1275                 pp = &lp->d_partitions[i];
1276                 if (!part_set[i] || i == RAW_PART ||
1277                     part_size_type[i] == '%' || part_size_type[i] == '*')
1278                         continue;
1279                 if (pp->p_offset > base_offset)
1280                         free_space += pp->p_offset - base_offset;
1281                 if (pp->p_offset + pp->p_size > base_offset)
1282                         base_offset = pp->p_offset + pp->p_size;
1283         }
1284         if (base_offset < lp->d_secperunit)
1285                 free_space += lp->d_secperunit - base_offset;
1286
1287         /* handle % partitions - note %'s don't need to add up to 100! */
1288         if (total_percent != 0) {
1289                 if (total_percent > 100) {
1290                         fprintf(stderr,"total percentage %lu is greater than 100\n",
1291                             total_percent);
1292                         errors++;
1293                 }
1294
1295                 if (free_space > 0) {
1296                         for (i = 0; i < lp->d_npartitions; i++) {
1297                                 pp = &lp->d_partitions[i];
1298                                 if (part_set[i] && part_size_type[i] == '%') {
1299                                         /* careful of overflows! and integer roundoff */
1300                                         pp->p_size = ((double)pp->p_size/100) * free_space;
1301                                         total_size += pp->p_size;
1302
1303                                         /* FIX we can lose a sector or so due to roundoff per
1304                                            partition.  A more complex algorithm could avoid that */
1305                                 }
1306                         }
1307                 } else {
1308                         fprintf(stderr,
1309                             "%ld sectors available to give to '*' and '%%' partitions\n",
1310                             free_space);
1311                         errors++;
1312                         /* fix?  set all % partitions to size 0? */
1313                 }
1314         }
1315         /* give anything remaining to the hog partition */
1316         if (hog_part != -1) {
1317                 /*
1318                  * Find the range of offsets usable by '*' partitions around
1319                  * the hog partition and how much space they need.
1320                  */
1321                 needed = 0;
1322                 base_offset = BBSIZE / secsize;
1323                 for (i = hog_part - 1; i >= 0; i--) {
1324                         pp = &lp->d_partitions[i];
1325                         if (!part_set[i] || i == RAW_PART)
1326                                 continue;
1327                         if (part_offset_type[i] == '*') {
1328                                 needed += pp->p_size;
1329                                 continue;
1330                         }
1331                         base_offset = pp->p_offset + pp->p_size;
1332                         break;
1333                 }
1334                 current_offset = lp->d_secperunit;
1335                 for (i = lp->d_npartitions - 1; i > hog_part; i--) {
1336                         pp = &lp->d_partitions[i];
1337                         if (!part_set[i] || i == RAW_PART)
1338                                 continue;
1339                         if (part_offset_type[i] == '*') {
1340                                 needed += pp->p_size;
1341                                 continue;
1342                         }
1343                         current_offset = pp->p_offset;
1344                 }
1345
1346                 if (current_offset - base_offset <= needed) {
1347                         fprintf(stderr, "Cannot find space for partition %c\n",
1348                             hog_part + 'a');
1349                         fprintf(stderr,
1350                             "Need more than %lu sectors between %lu and %lu\n",
1351                             needed, base_offset, current_offset);
1352                         errors++;
1353                         lp->d_partitions[hog_part].p_size = 0;
1354                 } else {
1355                         lp->d_partitions[hog_part].p_size = current_offset -
1356                             base_offset - needed;
1357                         total_size += lp->d_partitions[hog_part].p_size;
1358                 }
1359         }
1360
1361         /* Now set the offsets for each partition */
1362         current_offset = BBSIZE / secsize; /* in sectors */
1363         seen_default_offset = 0;
1364         for (i = 0; i < lp->d_npartitions; i++) {
1365                 part = 'a' + i;
1366                 pp = &lp->d_partitions[i];
1367                 if (part_set[i]) {
1368                         if (part_offset_type[i] == '*') {
1369                                 if (i == RAW_PART) {
1370                                         pp->p_offset = 0;
1371                                 } else {
1372                                         pp->p_offset = current_offset;
1373                                         seen_default_offset = 1;
1374                                 }
1375                         } else {
1376                                 /* allow them to be out of order for old-style tables */
1377                                 if (pp->p_offset < current_offset &&
1378                                     seen_default_offset && i != RAW_PART &&
1379                                     pp->p_fstype != FS_VINUM) {
1380                                         fprintf(stderr,
1381 "Offset %ld for partition %c overlaps previous partition which ends at %lu\n",
1382                                             (long)pp->p_offset,i+'a',current_offset);
1383                                         fprintf(stderr,
1384 "Labels with any *'s for offset must be in ascending order by sector\n");
1385                                         errors++;
1386                                 } else if (pp->p_offset != current_offset &&
1387                                     i != RAW_PART && seen_default_offset) {
1388                                         /*
1389                                          * this may give unneeded warnings if
1390                                          * partitions are out-of-order
1391                                          */
1392                                         warnx(
1393 "Offset %ld for partition %c doesn't match expected value %ld",
1394                                             (long)pp->p_offset, i + 'a', current_offset);
1395                                 }
1396                         }
1397                         if (i != RAW_PART)
1398                                 current_offset = pp->p_offset + pp->p_size;
1399                 }
1400         }
1401
1402         for (i = 0; i < lp->d_npartitions; i++) {
1403                 part = 'a' + i;
1404                 pp = &lp->d_partitions[i];
1405                 if (pp->p_size == 0 && pp->p_offset != 0)
1406                         warnx("partition %c: size 0, but offset %lu",
1407                             part, (u_long)pp->p_offset);
1408 #ifdef notdef
1409                 if (pp->p_size % lp->d_secpercyl)
1410                         warnx("partition %c: size %% cylinder-size != 0",
1411                             part);
1412                 if (pp->p_offset % lp->d_secpercyl)
1413                         warnx("partition %c: offset %% cylinder-size != 0",
1414                             part);
1415 #endif
1416                 if (pp->p_offset > lp->d_secperunit) {
1417                         fprintf(stderr,
1418                             "partition %c: offset past end of unit\n", part);
1419                         errors++;
1420                 }
1421                 if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1422                         fprintf(stderr,
1423                         "partition %c: partition extends past end of unit\n",
1424                             part);
1425                         errors++;
1426                 }
1427                 if (i == RAW_PART) {
1428                         if (pp->p_fstype != FS_UNUSED)
1429                                 warnx("partition %c is not marked as unused!",part);
1430                         if (pp->p_offset != 0)
1431                                 warnx("partition %c doesn't start at 0!",part);
1432                         if (pp->p_size != lp->d_secperunit)
1433                                 warnx("partition %c doesn't cover the whole unit!",part);
1434
1435                         if ((pp->p_fstype != FS_UNUSED) || (pp->p_offset != 0) ||
1436                             (pp->p_size != lp->d_secperunit)) {
1437                                 warnx("An incorrect partition %c may cause problems for "
1438                                     "standard system utilities",part);
1439                         }
1440                 }
1441
1442                 /* check for overlaps */
1443                 /* this will check for all possible overlaps once and only once */
1444                 for (j = 0; j < i; j++) {
1445                         pp2 = &lp->d_partitions[j];
1446                         if (j != RAW_PART && i != RAW_PART &&
1447                             pp->p_fstype != FS_VINUM &&
1448                             pp2->p_fstype != FS_VINUM &&
1449                             part_set[i] && part_set[j]) {
1450                                 if (pp2->p_offset < pp->p_offset + pp->p_size &&
1451                                     (pp2->p_offset + pp2->p_size > pp->p_offset ||
1452                                         pp2->p_offset >= pp->p_offset)) {
1453                                         fprintf(stderr,"partitions %c and %c overlap!\n",
1454                                             j + 'a', i + 'a');
1455                                         errors++;
1456                                 }
1457                         }
1458                 }
1459         }
1460         for (; i < lp->d_npartitions; i++) {
1461                 part = 'a' + i;
1462                 pp = &lp->d_partitions[i];
1463                 if (pp->p_size || pp->p_offset)
1464                         warnx("unused partition %c: size %d offset %lu",
1465                             'a' + i, pp->p_size, (u_long)pp->p_offset);
1466         }
1467         return (errors);
1468 }
1469
1470 /*
1471  * When operating on a "virgin" disk, try getting an initial label
1472  * from the associated device driver.  This might work for all device
1473  * drivers that are able to fetch some initial device parameters
1474  * without even having access to a (BSD) disklabel, like SCSI disks,
1475  * most IDE drives, or vn devices.
1476  *
1477  * The device name must be given in its "canonical" form.
1478  */
1479 static struct disklabel *
1480 getvirginlabel(void)
1481 {
1482         static struct disklabel loclab;
1483         struct partition *dp;
1484         int f;
1485         u_int u;
1486
1487         if ((f = open(specname, O_RDONLY)) == -1) {
1488                 warn("cannot open %s", specname);
1489                 return (NULL);
1490         }
1491
1492         if (is_file)
1493                 get_file_parms(f);
1494         else {
1495                 mediasize = g_mediasize(f);
1496                 secsize = g_sectorsize(f);
1497                 if (secsize < 0 || mediasize < 0) {
1498                         close (f);
1499                         return (NULL);
1500                 }
1501         }
1502         memset(&loclab, 0, sizeof loclab);
1503         loclab.d_magic = DISKMAGIC;
1504         loclab.d_magic2 = DISKMAGIC;
1505         loclab.d_secsize = secsize;
1506         loclab.d_secperunit = mediasize / secsize;
1507
1508         /*
1509          * Nobody in these enligthened days uses the CHS geometry for
1510          * anything, but nontheless try to get it right.  If we fail
1511          * to get any good ideas from the device, construct something
1512          * which is IBM-PC friendly.
1513          */
1514         if (ioctl(f, DIOCGFWSECTORS, &u) == 0)
1515                 loclab.d_nsectors = u;
1516         else
1517                 loclab.d_nsectors = 63;
1518         if (ioctl(f, DIOCGFWHEADS, &u) == 0)
1519                 loclab.d_ntracks = u;
1520         else if (loclab.d_secperunit <= 63*1*1024)
1521                 loclab.d_ntracks = 1;
1522         else if (loclab.d_secperunit <= 63*16*1024)
1523                 loclab.d_ntracks = 16;
1524         else
1525                 loclab.d_ntracks = 255;
1526         loclab.d_secpercyl = loclab.d_ntracks * loclab.d_nsectors;
1527         loclab.d_ncylinders = loclab.d_secperunit / loclab.d_secpercyl;
1528         loclab.d_npartitions = DEFPARTITIONS;
1529
1530         /* Various (unneeded) compat stuff */
1531         loclab.d_rpm = 3600;
1532         loclab.d_bbsize = BBSIZE;
1533         loclab.d_interleave = 1;
1534         strncpy(loclab.d_typename, "amnesiac",
1535             sizeof(loclab.d_typename));
1536
1537         dp = &loclab.d_partitions[RAW_PART];
1538         dp->p_size = loclab.d_secperunit;
1539         loclab.d_checksum = dkcksum(&loclab);
1540         close (f);
1541         return (&loclab);
1542 }
1543
1544 static void
1545 usage(void)
1546 {
1547
1548         fprintf(stderr,
1549         "%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",
1550         "usage: bsdlabel disk",
1551         "\t\t(to read label)",
1552         "       bsdlabel -w [-n] [-m machine] disk [type]",
1553         "\t\t(to write label with existing boot program)",
1554         "       bsdlabel -e [-n] [-m machine] disk",
1555         "\t\t(to edit label)",
1556         "       bsdlabel -R [-n] [-m machine] disk protofile",
1557         "\t\t(to restore label with existing boot program)",
1558         "       bsdlabel -B [-b boot] [-m machine] disk",
1559         "\t\t(to install boot program with existing on-disk label)",
1560         "       bsdlabel -w -B [-n] [-b boot] [-m machine] disk [type]",
1561         "\t\t(to write label and install boot program)",
1562         "       bsdlabel -R -B [-n] [-b boot] [-m machine] disk protofile",
1563                 "\t\t(to restore label and install boot program)"
1564         );
1565         exit(1);
1566 }