Sync usage with man page.
[netbsd-mini2440.git] / sbin / disklabel / main.c
blobbf8de7f7cf56c264f18b40f2309f9fcf79115c8b
1 /* $NetBSD: main.c,v 1.21 2009/11/28 12:14:53 tsutsui Exp $ */
3 /*
4 * Copyright (c) 2006 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Julio M. Merino Vidal.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
33 * Copyright (c) 1987, 1993
34 * The Regents of the University of California. All rights reserved.
36 * This code is derived from software contributed to Berkeley by
37 * Symmetric Computer Systems.
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. Neither the name of the University nor the names of its contributors
48 * may be used to endorse or promote products derived from this software
49 * without specific prior written permission.
51 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * SUCH DAMAGE.
64 #if HAVE_NBTOOL_CONFIG_H
65 #include "nbtool_config.h"
66 #endif
68 #include <sys/cdefs.h>
69 #ifndef lint
70 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\
71 The Regents of the University of California. All rights reserved.");
72 #endif /* not lint */
74 #ifndef lint
75 #if 0
76 static char sccsid[] = "@(#)disklabel.c 8.4 (Berkeley) 5/4/95";
77 /* from static char sccsid[] = "@(#)disklabel.c 1.2 (Symmetric) 11/28/85"; */
78 #else
79 __RCSID("$NetBSD: main.c,v 1.21 2009/11/28 12:14:53 tsutsui Exp $");
80 #endif
81 #endif /* not lint */
83 #include <sys/param.h>
84 #include <sys/file.h>
85 #include <sys/stat.h>
86 #include <sys/wait.h>
87 #define DKTYPENAMES
88 #define FSTYPENAMES
90 #include <ctype.h>
91 #include <err.h>
92 #include <errno.h>
93 #include <signal.h>
94 #include <string.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <limits.h>
98 #include <unistd.h>
100 #include <ufs/ufs/dinode.h>
101 #include <ufs/ffs/fs.h>
103 #if HAVE_NBTOOL_CONFIG_H
104 #include <nbinclude/sys/disklabel.h>
105 #include <nbinclude/sys/disklabel_acorn.h>
106 #include <nbinclude/sys/bootblock.h>
107 #include "../../include/disktab.h"
108 #else
109 #include <sys/ioctl.h>
110 #include <sys/disklabel.h>
111 #include <sys/disklabel_acorn.h>
112 #include <sys/bootblock.h>
113 #include <util.h>
114 #include <disktab.h>
115 #endif /* HAVE_NBTOOL_CONFIG_H */
117 #include "pathnames.h"
118 #include "extern.h"
119 #include "dkcksum.h"
120 #include "bswap.h"
123 * Disklabel: read and write disklabels.
124 * The label is usually placed on one of the first sectors of the disk.
125 * Many machines also place a bootstrap in the same area,
126 * in which case the label is embedded in the bootstrap.
127 * The bootstrap source must leave space at the proper offset
128 * for the label on such machines.
131 #ifndef BBSIZE
132 #define BBSIZE 8192 /* size of boot area, with label */
133 #endif
135 #define DISKMAGIC_REV bswap32(DISKMAGIC)
136 /* To delete a label, we just invert the magic numbers */
137 #define DISKMAGIC_DELETED (~DISKMAGIC)
138 #define DISKMAGIC_DELETED_REV bswap32(~DISKMAGIC)
140 #define DEFEDITOR _PATH_VI
142 char specname[MAXPATHLEN];
144 /* Some global data, all too hard to pass about */
145 char bootarea[BBSIZE]; /* Buffer matching part of disk */
146 int bootarea_len; /* Number of bytes we actually read */
147 static struct disklabel lab; /* The label we have updated */
149 static int Aflag; /* Action all labels */
150 static int Fflag; /* Read/write from file */
151 static int rflag; /* Read/write direct from disk */
152 static int tflag; /* Format output as disktab */
153 int Cflag; /* CHS format output */
154 static int Dflag; /* Delete old labels (use with write) */
155 static int Iflag; /* Read/write direct, but default if absent */
156 static int lflag; /* List all known file system types and exit */
157 static int mflag; /* Expect disk to contain an MBR */
158 static int verbose;
159 static int read_all; /* set if op = READ && Aflag */
161 static int write_label(int);
162 static int readlabel_direct(int);
163 static void writelabel_direct(int);
164 static int update_label(int, u_int, u_int);
165 static struct disklabel *find_label(int, u_int);
167 static void makedisktab(FILE *, struct disklabel *);
168 static void makelabel(const char *, const char *);
169 static void l_perror(const char *);
170 static void readlabel(int);
171 static int edit(int);
172 static int editit(const char *);
173 static char *skip(char *);
174 static char *word(char *);
175 static int getasciilabel(FILE *, struct disklabel *);
176 static void usage(void);
177 static int qsort_strcmp(const void *, const void *);
178 static int getulong(const char *, char, char **,
179 unsigned long *, unsigned long);
180 #define GETNUM32(a, v) getulong(a, '\0', NULL, v, UINT32_MAX)
181 #define GETNUM16(a, v) getulong(a, '\0', NULL, v, UINT16_MAX)
182 #define GETNUM8(a, v) getulong(a, '\0', NULL, v, UINT8_MAX)
184 static int set_writable_fd = -1;
186 #if HAVE_NBTOOL_CONFIG_H
187 #define GETLABELOFFSET() LABELOFFSET
188 #define GETLABELSECTOR() LABELSECTOR
189 #else /* HAVE_NBTOOL_CONFIG_H */
190 #define GETLABELOFFSET() getlabeloffset()
191 #define GETLABELSECTOR() getlabelsector()
192 #endif
194 /* Default location for label - only used if we don't find one to update */
195 #define LABEL_OFFSET (dklabel_getlabelsector() * DEV_BSIZE + dklabel_getlabeloffset())
198 * For portability it doesn't make sense to use any other value....
199 * Except, maybe, the size of a physical sector.
200 * This value is used if we have to write a label to the start of an mbr ptn.
202 #ifndef LABELOFFSET_MBR
203 #define LABELOFFSET_MBR 512
204 #endif
206 #if HAVE_NBTOOL_CONFIG_H
207 static int
208 opendisk(const char *path, int flags, char *buf, int buflen, int cooked)
210 int f;
211 f = open(path, flags, 0);
212 strlcpy(buf, path, buflen);
213 return f;
216 static int
217 dk_ioctl(int f, void *arg)
219 errno = ENOTTY;
220 return -1;
222 #define dk_ioctl(f, cmd, arg) dk_ioctl(f, arg)
223 #else
224 #define dk_ioctl(f, cmd, arg) ioctl(f, cmd, arg)
225 #endif /* HAVE_NBTOOL_CONFIG_H */
227 static daddr_t
228 dklabel_getlabelsector(void)
230 unsigned long int nval;
231 char *end;
232 const char *val;
234 if ((val = getenv("DISKLABELSECTOR")) == NULL)
235 return GETLABELSECTOR();
236 if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
237 err(EXIT_FAILURE, "DISKLABELSECTOR in environment");
238 return nval;
241 static off_t
242 dklabel_getlabeloffset(void)
244 unsigned long int nval;
245 char *end;
246 const char *val;
248 if ((val = getenv("DISKLABELOFFSET")) == NULL)
249 return GETLABELOFFSET();
250 if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
251 err(EXIT_FAILURE, "DISKLABELOFFSET in environment");
252 return nval;
255 static void
256 clear_writable(void)
258 static int zero = 0;
259 dk_ioctl(set_writable_fd, DIOCWLABEL, &zero);
263 main(int argc, char *argv[])
265 FILE *t;
266 int ch, f, error;
267 char *dkname;
268 struct stat sb;
269 int writable;
270 enum {
271 UNSPEC, EDIT, READ, RESTORE, SETWRITABLE, SETREADONLY,
272 WRITE, INTERACT, DELETE
273 } op = UNSPEC, old_op;
275 #ifdef USE_MBR
276 mflag = 1;
277 #endif
278 #if HAVE_NBTOOL_CONFIG_H
279 /* We must avoid doing any ioctl requests */
280 Fflag = rflag = 1;
281 #endif
283 error = 0;
284 while ((ch = getopt(argc, argv, "ACDFINRWb:ef:ilmrs:tvw")) != -1) {
285 old_op = op;
286 switch (ch) {
287 case 'A': /* Action all labels */
288 Aflag = 1;
289 rflag = 1;
290 break;
291 case 'C': /* Display in CHS format */
292 Cflag = 1;
293 break;
294 case 'D': /* Delete all existing labels */
295 Dflag = 1;
296 rflag = 1;
297 break;
298 case 'F': /* Treat 'disk' as a regular file */
299 Fflag = 1;
300 rflag = 1; /* Force direct access */
301 break;
302 case 'I': /* Use default label if none found */
303 Iflag = 1;
304 rflag = 1; /* Implies direct access */
305 break;
306 case 'R': /* Restore label from text file */
307 op = RESTORE;
308 break;
309 case 'N': /* Disallow writes to label sector */
310 op = SETREADONLY;
311 break;
312 case 'W': /* Allow writes to label sector */
313 op = SETWRITABLE;
314 break;
315 case 'e': /* Edit label with $EDITOR */
316 op = EDIT;
317 break;
318 case 'f': /* Name of disktab file */
319 if (setdisktab(optarg) == -1)
320 usage();
321 break;
322 case 'i': /* Edit using built-in editor */
323 op = INTERACT;
324 break;
325 case 'l': /* List all known file system types and exit */
326 lflag = 1;
327 break;
328 case 'm': /* Expect disk to have an MBR */
329 mflag ^= 1;
330 break;
331 case 'r': /* Read/write label directly from disk */
332 rflag = 1;
333 break;
334 case 't': /* Format output as a disktab entry */
335 tflag = 1;
336 break;
337 case 'v': /* verbose/diag output */
338 verbose++;
339 break;
340 case 'w': /* Write label based on disktab entry */
341 op = WRITE;
342 break;
343 case '?':
344 default:
345 usage();
347 if (old_op != UNSPEC && old_op != op)
348 usage();
350 argc -= optind;
351 argv += optind;
353 if (lflag)
354 exit(list_fs_types() ? EXIT_SUCCESS : EXIT_FAILURE);
356 if (op == UNSPEC)
357 op = Dflag ? DELETE : READ;
359 if (argc < 1)
360 usage();
362 if (Iflag && op != EDIT && op != INTERACT)
363 usage();
365 dkname = argv[0];
366 f = opendisk(dkname, op == READ ? O_RDONLY : O_RDWR,
367 specname, sizeof specname, 0);
368 if (f < 0)
369 err(4, "%s", specname);
371 if (!Fflag && fstat(f, &sb) == 0 && S_ISREG(sb.st_mode))
372 Fflag = rflag = 1;
374 switch (op) {
376 case DELETE: /* Remove all existing labels */
377 if (argc != 1)
378 usage();
379 Dflag = 2;
380 writelabel_direct(f);
381 break;
383 case EDIT:
384 if (argc != 1)
385 usage();
386 readlabel(f);
387 error = edit(f);
388 break;
390 case INTERACT:
391 if (argc != 1)
392 usage();
393 readlabel(f);
395 * XXX: Fill some default values so checklabel does not fail
397 if (lab.d_bbsize == 0)
398 lab.d_bbsize = BBSIZE;
399 if (lab.d_sbsize == 0)
400 lab.d_sbsize = SBLOCKSIZE;
401 interact(&lab, f);
402 break;
404 case READ:
405 if (argc != 1)
406 usage();
407 read_all = Aflag;
408 readlabel(f);
409 if (read_all)
410 /* Label got printed in the bowels of readlabel */
411 break;
412 if (tflag)
413 makedisktab(stdout, &lab);
414 else {
415 showinfo(stdout, &lab, specname);
416 showpartitions(stdout, &lab, Cflag);
418 error = checklabel(&lab);
419 if (error)
420 error += 100;
421 break;
423 case RESTORE:
424 if (argc != 2)
425 usage();
426 if (!(t = fopen(argv[1], "r")))
427 err(4, "%s", argv[1]);
428 if (getasciilabel(t, &lab))
429 error = write_label(f);
430 else
431 error = 1;
432 break;
434 case SETREADONLY:
435 writable = 0;
436 goto do_diocwlabel;
437 case SETWRITABLE:
438 writable = 1;
439 do_diocwlabel:
440 if (argc != 1)
441 usage();
442 if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
443 err(4, "ioctl DIOCWLABEL");
444 break;
446 case WRITE: /* Create label from /etc/disktab entry & write */
447 if (argc < 2 || argc > 3)
448 usage();
449 makelabel(argv[1], argv[2]);
450 if (checklabel(&lab) == 0)
451 error = write_label(f);
452 else
453 error = 1;
454 break;
456 case UNSPEC:
457 usage();
460 exit(error);
464 * Construct a prototype disklabel from /etc/disktab.
466 static void
467 makelabel(const char *type, const char *name)
469 struct disklabel *dp;
471 dp = getdiskbyname(type);
472 if (dp == NULL)
473 errx(1, "unknown disk type: %s", type);
474 lab = *dp;
476 /* d_packname is union d_boot[01], so zero */
477 (void)memset(lab.d_packname, 0, sizeof(lab.d_packname));
478 if (name)
479 (void)strncpy(lab.d_packname, name, sizeof(lab.d_packname));
482 static int
483 write_label(int f)
485 int writable;
487 lab.d_magic = DISKMAGIC;
488 lab.d_magic2 = DISKMAGIC;
489 lab.d_checksum = 0;
490 lab.d_checksum = dkcksum(&lab);
492 if (rflag) {
493 /* Write the label directly to the disk */
496 * First set the kernel disk label,
497 * then write a label to the raw disk.
498 * If the SDINFO ioctl fails because it is unimplemented,
499 * keep going; otherwise, the kernel consistency checks
500 * may prevent us from changing the current (in-core)
501 * label.
503 if (!Fflag && dk_ioctl(f, DIOCSDINFO, &lab) < 0 &&
504 errno != ENODEV && errno != ENOTTY) {
505 l_perror("ioctl DIOCSDINFO");
506 return (1);
509 * write enable label sector before write (if necessary),
510 * disable after writing.
512 writable = 1;
513 if (!Fflag) {
514 if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
515 perror("ioctl DIOCWLABEL");
516 set_writable_fd = f;
517 atexit(clear_writable);
520 writelabel_direct(f);
523 * Now issue a DIOCWDINFO. This will let the kernel convert the
524 * disklabel to some machdep format if needed.
526 /* XXX: This is stupid! */
527 if (!Fflag && dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
528 l_perror("ioctl DIOCWDINFO");
529 return (1);
531 } else {
532 /* Get the kernel to write the label */
533 if (dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
534 l_perror("ioctl DIOCWDINFO");
535 return (1);
539 #ifdef VAX_ALTLABELS
540 if (lab.d_type == DTYPE_SMD && lab.d_flags & D_BADSECT &&
541 lab.d_secsize == 512) {
542 /* Write the label to the odd sectors of the last track! */
543 daddr_t alt;
544 int i;
545 uint8_t sec0[512];
547 if (pread(f, sec0, 512, 0) < 512) {
548 warn("read master label to write alternates");
549 return 0;
552 alt = lab.d_ncylinders * lab.d_secpercyl - lab.d_nsectors;
553 for (i = 1; i < 11 && (uint32_t)i < lab.d_nsectors; i += 2) {
554 if (pwrite(f, sec0, 512, (off_t)(alt + i) * 512) < 512)
555 warn("alternate label %d write", i/2);
558 #endif /* VAX_ALTLABELS */
560 return 0;
564 writelabel(int f, struct disklabel *lp)
566 if (lp != &lab)
567 lab = *lp;
568 return write_label(f);
571 static void
572 l_perror(const char *s)
575 switch (errno) {
577 case ESRCH:
578 warnx("%s: No disk label on disk;\n"
579 "use \"disklabel -I\" to install initial label", s);
580 break;
582 case EINVAL:
583 warnx("%s: Label magic number or checksum is wrong!\n"
584 "(disklabel or kernel is out of date?)", s);
585 break;
587 case EBUSY:
588 warnx("%s: Open partition would move or shrink", s);
589 break;
591 case EXDEV:
592 warnx("%s: Labeled partition or 'a' partition must start"
593 " at beginning of disk", s);
594 break;
596 default:
597 warn("%s", s);
598 break;
602 #ifdef NO_MBR_SUPPORT
603 #define process_mbr(f, action) 1
604 #else
606 * Scan DOS/MBR partition table and extended partition list for NetBSD ptns.
608 static int
609 process_mbr(int f, int (*action)(int, u_int))
611 struct mbr_partition *dp;
612 struct mbr_sector mbr;
613 int rval = 1, res;
614 int part;
615 u_int ext_base, next_ext, this_ext, start;
617 ext_base = 0;
618 next_ext = 0;
619 for (;;) {
620 this_ext = next_ext;
621 next_ext = 0;
622 if (verbose > 1)
623 warnx("reading mbr sector %u", this_ext);
624 if (pread(f, &mbr, sizeof mbr, this_ext * (off_t)DEV_BSIZE)
625 != sizeof(mbr)) {
626 if (verbose)
627 warn("Can't read master boot record %d",
628 this_ext);
629 break;
632 /* Check if table is valid. */
633 if (mbr.mbr_magic != htole16(MBR_MAGIC)) {
634 if (verbose)
635 warnx("Invalid signature in mbr record %d",
636 this_ext);
637 break;
640 dp = &mbr.mbr_parts[0];
642 /* Find NetBSD partition(s). */
643 for (part = 0; part < MBR_PART_COUNT; dp++, part++) {
644 start = le32toh(dp->mbrp_start);
645 switch (dp->mbrp_type) {
646 #ifdef COMPAT_386BSD_MBRPART
647 case MBR_PTYPE_386BSD:
648 if (ext_base != 0)
649 break;
650 /* FALLTHROUGH */
651 #endif
652 case MBR_PTYPE_NETBSD:
653 res = action(f, this_ext + start);
654 if (res <= 0)
655 /* Found or failure */
656 return res;
657 if (res > rval)
658 /* Keep largest value */
659 rval = res;
660 break;
661 case MBR_PTYPE_EXT:
662 case MBR_PTYPE_EXT_LBA:
663 case MBR_PTYPE_EXT_LNX:
664 next_ext = start;
665 break;
666 default:
667 break;
670 if (next_ext == 0)
671 /* No more extended partitions */
672 break;
673 next_ext += ext_base;
674 if (ext_base == 0)
675 ext_base = next_ext;
677 if (next_ext <= this_ext) {
678 if (verbose)
679 warnx("Invalid extended chain %x <= %x",
680 next_ext, this_ext);
681 break;
683 /* Maybe we should check against the disk size... */
686 return rval;
689 static int
690 readlabel_mbr(int f, u_int sector)
692 struct disklabel *disk_lp;
694 disk_lp = find_label(f, sector);
695 if (disk_lp == NULL)
696 return 1;
697 targettohlabel(&lab, disk_lp);
698 return 0;
701 static int
702 writelabel_mbr(int f, u_int sector)
704 return update_label(f, sector, mflag ? LABELOFFSET_MBR : ~0U) ? 2 : 0;
707 #endif /* !NO_MBR_SUPPORT */
709 #ifndef USE_ACORN
710 #define get_filecore_partition(f) 0
711 #else
713 * static int filecore_checksum(u_char *bootblock)
715 * Calculates the filecore boot block checksum. This is used to validate
716 * a filecore boot block on the disk. If a boot block is validated then
717 * it is used to locate the partition table. If the boot block is not
718 * validated, it is assumed that the whole disk is NetBSD.
720 * The basic algorithm is:
722 * for (each byte in block, excluding checksum) {
723 * sum += byte;
724 * if (sum > 255)
725 * sum -= 255;
728 * That's equivalent to summing all of the bytes in the block
729 * (excluding the checksum byte, of course), then calculating the
730 * checksum as "cksum = sum - ((sum - 1) / 255) * 255)". That
731 * expression may or may not yield a faster checksum function,
732 * but it's easier to reason about.
734 * Note that if you have a block filled with bytes of a single
735 * value "X" (regardless of that value!) and calculate the cksum
736 * of the block (excluding the checksum byte), you will _always_
737 * end up with a checksum of X. (Do the math; that can be derived
738 * from the checksum calculation function!) That means that
739 * blocks which contain bytes which all have the same value will
740 * always checksum properly. That's a _very_ unlikely occurence
741 * (probably impossible, actually) for a valid filecore boot block,
742 * so we treat such blocks as invalid.
744 static int
745 filecore_checksum(u_char *bootblock)
747 u_char byte0, accum_diff;
748 u_int sum;
749 int i;
751 sum = 0;
752 accum_diff = 0;
753 byte0 = bootblock[0];
756 * Sum the contents of the block, keeping track of whether
757 * or not all bytes are the same. If 'accum_diff' ends up
758 * being zero, all of the bytes are, in fact, the same.
760 for (i = 0; i < 511; ++i) {
761 sum += bootblock[i];
762 accum_diff |= bootblock[i] ^ byte0;
766 * Check to see if the checksum byte is the same as the
767 * rest of the bytes, too. (Note that if all of the bytes
768 * are the same except the checksum, a checksum compare
769 * won't succeed, but that's not our problem.)
771 accum_diff |= bootblock[i] ^ byte0;
773 /* All bytes in block are the same; call it invalid. */
774 if (accum_diff == 0)
775 return (-1);
777 return (sum - ((sum - 1) / 255) * 255);
781 * Check for the presence of a RiscOS filecore boot block
782 * indicating an ADFS file system on the disc.
783 * Return the offset to the NetBSD part of the disc if
784 * this can be determined.
785 * This routine will terminate disklabel if the disc
786 * is found to be ADFS only.
788 static u_int
789 get_filecore_partition(int f)
791 struct filecore_bootblock *fcbb;
792 static u_char bb[DEV_BSIZE];
793 u_int offset;
794 struct riscix_partition_table *riscix_part;
795 int loop;
797 if (pread(f, bb, sizeof(bb), (off_t)FILECORE_BOOT_SECTOR * DEV_BSIZE) != sizeof(bb))
798 err(4, "can't read filecore boot block");
799 fcbb = (struct filecore_bootblock *)bb;
801 /* Check if table is valid. */
802 if (filecore_checksum(bb) != fcbb->checksum)
803 return (0);
806 * Check for NetBSD/arm32 (RiscBSD) partition marker.
807 * If found the NetBSD disklabel location is easy.
809 offset = (fcbb->partition_cyl_low + (fcbb->partition_cyl_high << 8))
810 * fcbb->heads * fcbb->secspertrack;
812 switch (fcbb->partition_type) {
814 case PARTITION_FORMAT_RISCBSD:
815 return (offset);
817 case PARTITION_FORMAT_RISCIX:
819 * Read the RISCiX partition table and search for the
820 * first partition named "RiscBSD", "NetBSD", or "Empty:"
822 * XXX is use of 'Empty:' really desirable?! -- cgd
825 if (pread(f, bb, sizeof(bb), (off_t)offset * DEV_BSIZE) != sizeof(bb))
826 err(4, "can't read riscix partition table");
827 riscix_part = (struct riscix_partition_table *)bb;
829 for (loop = 0; loop < NRISCIX_PARTITIONS; ++loop) {
830 if (strcmp((char *)riscix_part->partitions[loop].rp_name,
831 "RiscBSD") == 0 ||
832 strcmp((char *)riscix_part->partitions[loop].rp_name,
833 "NetBSD") == 0 ||
834 strcmp((char *)riscix_part->partitions[loop].rp_name,
835 "Empty:") == 0) {
836 return riscix_part->partitions[loop].rp_start;
837 break;
841 * Valid filecore boot block, RISCiX partition table
842 * but no NetBSD partition. We should leave this
843 * disc alone.
845 errx(4, "cannot label: no NetBSD partition found"
846 " in RISCiX partition table");
848 default:
850 * Valid filecore boot block and no non-ADFS partition.
851 * This means that the whole disc is allocated for ADFS
852 * so do not trash ! If the user really wants to put a
853 * NetBSD disklabel on the disc then they should remove
854 * the filecore boot block first with dd.
856 errx(4, "cannot label: filecore-only disk"
857 " (no non-ADFS partition)");
859 return (0);
861 #endif /* USE_ACORN */
864 * Fetch disklabel for disk to 'lab'.
865 * Use ioctl to get label unless -r flag is given.
867 static void
868 readlabel(int f)
870 if (rflag) {
871 /* Get label directly from disk */
872 if (readlabel_direct(f) == 0)
873 return;
875 * There was no label on the disk. Get the fictious one
876 * as a basis for initialisation.
878 if (!Fflag && Iflag && (dk_ioctl(f, DIOCGDINFO, &lab) == 0 ||
879 dk_ioctl(f, DIOCGDEFLABEL, &lab) == 0))
880 return;
881 } else {
882 /* Get label from kernel. */
883 if (dk_ioctl(f, DIOCGDINFO, &lab) < 0)
884 err(4, "ioctl DIOCGDINFO");
885 return;
888 if (read_all == 2)
889 /* We actually found one, and printed it... */
890 exit(0);
891 errx(1, "could not read existing label");
895 * Reading the label from the disk is largely a case of 'hunt the label'.
896 * and since different architectures default to different places there
897 * could even be more than one label that contradict each other!
898 * For now we look in the expected place, then search through likely
899 * other locations.
901 static struct disklabel *
902 find_label(int f, u_int sector)
904 struct disklabel *disk_lp, hlp;
905 int i, offset;
906 const char *is_deleted;
908 bootarea_len = pread(f, bootarea, sizeof bootarea,
909 sector * (off_t)DEV_BSIZE);
910 if (bootarea_len <= 0) {
911 if (verbose)
912 warn("failed to read bootarea from sector %u", sector);
913 return NULL;
916 if (verbose > 2)
917 warnx("read sector %u len %u looking for label",
918 sector, bootarea_len);
920 /* Check expected offset first */
921 for (offset = LABEL_OFFSET, i = -4;; offset = i += 4) {
922 is_deleted = "";
923 disk_lp = (void *)(bootarea + offset);
924 if (i == LABEL_OFFSET)
925 continue;
926 if ((char *)(disk_lp + 1) > bootarea + bootarea_len)
927 break;
928 if (disk_lp->d_magic2 != disk_lp->d_magic)
929 continue;
930 if (read_all && (disk_lp->d_magic == DISKMAGIC_DELETED ||
931 disk_lp->d_magic == DISKMAGIC_DELETED_REV)) {
932 disk_lp->d_magic ^= ~0u;
933 disk_lp->d_magic2 ^= ~0u;
934 is_deleted = "deleted ";
936 if (target32toh(disk_lp->d_magic) != DISKMAGIC) {
937 /* XXX: Do something about byte-swapped labels ? */
938 if (target32toh(disk_lp->d_magic) == DISKMAGIC_REV &&
939 target32toh(disk_lp->d_magic2) == DISKMAGIC_REV)
940 warnx("ignoring %sbyteswapped label"
941 " at offset %u from sector %u",
942 is_deleted, offset, sector);
943 continue;
945 if (target16toh(disk_lp->d_npartitions) > MAXPARTITIONS ||
946 dkcksum_target(disk_lp) != 0) {
947 if (verbose > 0)
948 warnx("corrupt label found at offset %u in "
949 "sector %u", offset, sector);
950 continue;
952 if (verbose > 1)
953 warnx("%slabel found at offset %u from sector %u",
954 is_deleted, offset, sector);
955 if (!read_all)
956 return disk_lp;
958 /* To print all the labels we have to do it here */
959 /* XXX: maybe we should compare them? */
960 targettohlabel(&hlp, disk_lp);
961 printf("# %ssector %u offset %u bytes\n",
962 is_deleted, sector, offset);
963 if (tflag)
964 makedisktab(stdout, &hlp);
965 else {
966 showinfo(stdout, &hlp, specname);
967 showpartitions(stdout, &hlp, Cflag);
969 checklabel(&hlp);
970 htotargetlabel(disk_lp, &hlp);
971 /* Remember we've found a label */
972 read_all = 2;
974 return NULL;
977 static void
978 write_bootarea(int f, u_int sector)
980 int wlen;
982 if (bootarea_len <= 0)
983 errx(1, "attempting to write after failed read");
985 #ifdef ALPHA_BOOTBLOCK_CKSUM
987 * The Alpha requires that the boot block be checksummed.
988 * <sys/bootblock.h> provides a macro to do it.
990 if (sector == 0) {
991 struct alpha_boot_block *bb;
993 bb = (struct alpha_boot_block *)(void *)bootarea;
994 bb->bb_cksum = 0;
995 ALPHA_BOOT_BLOCK_CKSUM(bb, &bb->bb_cksum);
997 #endif /* ALPHA_BOOTBLOCK_CKSUM */
999 wlen = pwrite(f, bootarea, bootarea_len, sector * (off_t)DEV_BSIZE);
1000 if (wlen == bootarea_len)
1001 return;
1002 if (wlen == -1)
1003 err(1, "disklabel write (sector %u) size %u failed",
1004 sector, bootarea_len);
1005 errx(1, "disklabel write (sector %u) size %u truncated to %d",
1006 sector, bootarea_len, wlen);
1009 static int
1010 update_label(int f, u_int label_sector, u_int label_offset)
1012 struct disklabel *disk_lp;
1014 disk_lp = find_label(f, label_sector);
1016 if (disk_lp && Dflag) {
1017 /* Invalidate the existing label */
1018 disk_lp->d_magic ^= ~0u;
1019 disk_lp->d_magic2 ^= ~0u;
1020 if (Dflag == 2)
1021 write_bootarea(f, label_sector);
1022 /* Force label to default location */
1023 disk_lp = NULL;
1026 if (Dflag == 2)
1027 /* We are just deleting the label */
1028 return 0;
1030 if (disk_lp == NULL) {
1031 if (label_offset == ~0u)
1032 return 0;
1033 /* Nothing on the disk - we need to add it */
1034 disk_lp = (void *)(bootarea + label_offset);
1035 if ((char *)(disk_lp + 1) > bootarea + bootarea_len)
1036 errx(1, "no space in bootarea (sector %u) "
1037 "to create label", label_sector);
1040 htotargetlabel(disk_lp, &lab);
1041 write_bootarea(f, label_sector);
1042 return 1;
1045 static void
1046 writelabel_direct(int f)
1048 u_int label_sector;
1049 int written = 0;
1050 int rval;
1052 label_sector = get_filecore_partition(f);
1053 if (label_sector != 0)
1054 /* The offset needs to be that from the acorn ports... */
1055 written = update_label(f, label_sector, DEV_BSIZE);
1057 rval = process_mbr(f, writelabel_mbr);
1059 if (rval == 2 || written)
1060 /* Don't add a label to sector 0, but update one if there */
1061 update_label(f, 0, ~0u);
1062 else
1063 update_label(f, 0, LABEL_OFFSET);
1066 static int
1067 readlabel_direct(int f)
1069 struct disklabel *disk_lp;
1070 u_int filecore_partition_offset;
1072 filecore_partition_offset = get_filecore_partition(f);
1073 if (filecore_partition_offset != 0) {
1074 disk_lp = find_label(f, filecore_partition_offset);
1075 if (disk_lp != NULL) {
1076 targettohlabel(&lab, disk_lp);
1077 return 0;
1081 if (mflag && process_mbr(f, readlabel_mbr) == 0)
1082 return 0;
1084 disk_lp = find_label(f, 0);
1085 if (disk_lp != NULL) {
1086 targettohlabel(&lab, disk_lp);
1087 return 0;
1090 if (!mflag && process_mbr(f, readlabel_mbr) == 0)
1091 return 0;
1093 return 1;
1096 static void
1097 makedisktab(FILE *f, struct disklabel *lp)
1099 int i;
1100 const char *did;
1101 struct partition *pp;
1103 did = "\\\n\t:";
1104 (void) fprintf(f, "%.*s|Automatically generated label:\\\n\t:dt=",
1105 (int) sizeof(lp->d_typename), lp->d_typename);
1106 if ((unsigned) lp->d_type < DKMAXTYPES)
1107 (void) fprintf(f, "%s:", dktypenames[lp->d_type]);
1108 else
1109 (void) fprintf(f, "unknown%d:", lp->d_type);
1111 (void) fprintf(f, "se#%d:", lp->d_secsize);
1112 (void) fprintf(f, "ns#%d:", lp->d_nsectors);
1113 (void) fprintf(f, "nt#%d:", lp->d_ntracks);
1114 (void) fprintf(f, "sc#%d:", lp->d_secpercyl);
1115 (void) fprintf(f, "nc#%d:", lp->d_ncylinders);
1117 if ((lp->d_secpercyl * lp->d_ncylinders) != lp->d_secperunit) {
1118 (void) fprintf(f, "%ssu#%d:", did, lp->d_secperunit);
1119 did = "";
1121 if (lp->d_rpm != 3600) {
1122 (void) fprintf(f, "%srm#%d:", did, lp->d_rpm);
1123 did = "";
1125 if (lp->d_interleave != 1) {
1126 (void) fprintf(f, "%sil#%d:", did, lp->d_interleave);
1127 did = "";
1129 if (lp->d_trackskew != 0) {
1130 (void) fprintf(f, "%ssk#%d:", did, lp->d_trackskew);
1131 did = "";
1133 if (lp->d_cylskew != 0) {
1134 (void) fprintf(f, "%scs#%d:", did, lp->d_cylskew);
1135 did = "";
1137 if (lp->d_headswitch != 0) {
1138 (void) fprintf(f, "%shs#%d:", did, lp->d_headswitch);
1139 did = "";
1141 if (lp->d_trkseek != 0) {
1142 (void) fprintf(f, "%sts#%d:", did, lp->d_trkseek);
1143 did = "";
1145 #ifdef notyet
1146 (void) fprintf(f, "drivedata: ");
1147 for (i = NDDATA - 1; i >= 0; i--)
1148 if (lp->d_drivedata[i])
1149 break;
1150 if (i < 0)
1151 i = 0;
1152 for (j = 0; j <= i; j++)
1153 (void) fprintf(f, "%d ", lp->d_drivedata[j]);
1154 #endif /* notyet */
1155 pp = lp->d_partitions;
1156 for (i = 0; i < lp->d_npartitions; i++, pp++) {
1157 if (pp->p_size) {
1158 char c = 'a' + i;
1159 (void) fprintf(f, "\\\n\t:");
1160 (void) fprintf(f, "p%c#%d:", c, pp->p_size);
1161 (void) fprintf(f, "o%c#%d:", c, pp->p_offset);
1162 if (pp->p_fstype != FS_UNUSED) {
1163 if ((unsigned) pp->p_fstype < FSMAXTYPES)
1164 (void) fprintf(f, "t%c=%s:", c,
1165 fstypenames[pp->p_fstype]);
1166 else
1167 (void) fprintf(f, "t%c=unknown%d:",
1168 c, pp->p_fstype);
1170 switch (pp->p_fstype) {
1172 case FS_UNUSED:
1173 break;
1175 case FS_BSDFFS:
1176 case FS_BSDLFS:
1177 case FS_EX2FS:
1178 case FS_ADOS:
1179 case FS_APPLEUFS:
1180 (void) fprintf(f, "b%c#%d:", c,
1181 pp->p_fsize * pp->p_frag);
1182 (void) fprintf(f, "f%c#%d:", c, pp->p_fsize);
1183 break;
1184 default:
1185 break;
1189 (void) fprintf(f, "\n");
1190 (void) fflush(f);
1193 static int
1194 edit(int f)
1196 const char *tmpdir;
1197 char tmpfil[MAXPATHLEN];
1198 int first, ch, fd;
1199 int get_ok;
1200 FILE *fp;
1202 if ((tmpdir = getenv("TMPDIR")) == NULL)
1203 tmpdir = _PATH_TMP;
1204 (void)snprintf(tmpfil, sizeof(tmpfil), "%s/%s", tmpdir, TMPFILE);
1205 if ((fd = mkstemp(tmpfil)) == -1 || (fp = fdopen(fd, "w")) == NULL) {
1206 warn("%s", tmpfil);
1207 return (1);
1209 (void)fchmod(fd, 0600);
1210 showinfo(fp, &lab, specname);
1211 showpartitions(fp, &lab, Cflag);
1212 (void) fclose(fp);
1213 for (;;) {
1214 if (!editit(tmpfil))
1215 break;
1216 fp = fopen(tmpfil, "r");
1217 if (fp == NULL) {
1218 warn("%s", tmpfil);
1219 break;
1221 (void) memset(&lab, 0, sizeof(lab));
1222 get_ok = getasciilabel(fp, &lab);
1223 fclose(fp);
1224 if (get_ok && write_label(f) == 0) {
1225 (void) unlink(tmpfil);
1226 return (0);
1228 (void) printf("re-edit the label? [y]: ");
1229 (void) fflush(stdout);
1230 first = ch = getchar();
1231 while (ch != '\n' && ch != EOF)
1232 ch = getchar();
1233 if (first == 'n' || first == 'N')
1234 break;
1236 (void)unlink(tmpfil);
1237 return (1);
1240 static int
1241 editit(const char *tmpfil)
1243 int pid, xpid;
1244 int status;
1245 sigset_t nsigset, osigset;
1247 sigemptyset(&nsigset);
1248 sigaddset(&nsigset, SIGINT);
1249 sigaddset(&nsigset, SIGQUIT);
1250 sigaddset(&nsigset, SIGHUP);
1251 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1252 while ((pid = fork()) < 0) {
1253 if (errno != EAGAIN) {
1254 sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1255 warn("fork");
1256 return (0);
1258 sleep(1);
1260 if (pid == 0) {
1261 const char *ed;
1262 char *buf;
1263 int retval;
1265 sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1266 setgid(getgid());
1267 setuid(getuid());
1268 if ((ed = getenv("EDITOR")) == (char *)0)
1269 ed = DEFEDITOR;
1271 * Jump through a few extra hoops in case someone's editor
1272 * is "editor arg1 arg2".
1274 asprintf(&buf, "%s %s", ed, tmpfil);
1275 if (!buf)
1276 err(1, "malloc");
1277 retval = execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", buf, NULL);
1278 if (retval == -1)
1279 perror(ed);
1280 exit(retval);
1282 while ((xpid = wait(&status)) >= 0)
1283 if (xpid == pid)
1284 break;
1285 sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1286 return (!status);
1289 static char *
1290 skip(char *cp)
1293 cp += strspn(cp, " \t");
1294 if (*cp == '\0')
1295 return (NULL);
1296 return (cp);
1299 static char *
1300 word(char *cp)
1303 if (cp == NULL || *cp == '\0')
1304 return (NULL);
1306 cp += strcspn(cp, " \t");
1307 if (*cp == '\0')
1308 return (NULL);
1309 *cp++ = '\0';
1310 cp += strspn(cp, " \t");
1311 if (*cp == '\0')
1312 return (NULL);
1313 return (cp);
1316 #define _CHECKLINE \
1317 if (tp == NULL || *tp == '\0') { \
1318 warnx("line %d: too few fields", lineno); \
1319 errors++; \
1320 break; \
1323 #define __CHECKLINE \
1324 if (*tp == NULL || **tp == '\0') { \
1325 warnx("line %d: too few fields", lineno); \
1326 *tp = _error_; \
1327 return 0; \
1330 static char _error_[] = "";
1331 #define NXTNUM(n) if ((n = nxtnum(&tp, lineno),0) + tp != _error_) \
1332 ; else goto error
1333 #define NXTXNUM(n) if ((n = nxtxnum(&tp, lp, lineno),0) + tp != _error_) \
1334 ; else goto error
1336 static unsigned long
1337 nxtnum(char **tp, int lineno)
1339 char *cp;
1340 unsigned long v;
1342 __CHECKLINE
1343 if (getulong(*tp, '\0', &cp, &v, UINT32_MAX) != 0) {
1344 warnx("line %d: syntax error", lineno);
1345 *tp = _error_;
1346 return 0;
1348 *tp = cp;
1349 return v;
1352 static unsigned long
1353 nxtxnum(char **tp, struct disklabel *lp, int lineno)
1355 char *cp, *ncp;
1356 unsigned long n, v;
1358 __CHECKLINE
1359 cp = *tp;
1360 if (getulong(cp, '/', &ncp, &n, UINT32_MAX) != 0)
1361 goto bad;
1363 if (*ncp == '/') {
1364 n *= lp->d_secpercyl;
1365 cp = ncp + 1;
1366 if (getulong(cp, '/', &ncp, &v, UINT32_MAX) != 0)
1367 goto bad;
1368 n += v * lp->d_nsectors;
1369 cp = ncp + 1;
1370 if (getulong(cp, '\0', &ncp, &v, UINT32_MAX) != 0)
1371 goto bad;
1372 n += v;
1374 *tp = ncp;
1375 return n;
1376 bad:
1377 warnx("line %d: invalid format", lineno);
1378 *tp = _error_;
1379 return 0;
1383 * Read an ascii label in from fd f,
1384 * in the same format as that put out by showinfo() and showpartitions(),
1385 * and fill in lp.
1387 static int
1388 getasciilabel(FILE *f, struct disklabel *lp)
1390 const char *const *cpp, *s;
1391 struct partition *pp;
1392 char *cp, *tp, line[BUFSIZ], tbuf[15];
1393 int lineno, errors;
1394 unsigned long v;
1395 unsigned int part;
1397 lineno = 0;
1398 errors = 0;
1399 lp->d_bbsize = BBSIZE; /* XXX */
1400 lp->d_sbsize = SBLOCKSIZE; /* XXX */
1401 while (fgets(line, sizeof(line) - 1, f)) {
1402 lineno++;
1403 if ((cp = strpbrk(line, "#\r\n")) != NULL)
1404 *cp = '\0';
1405 cp = skip(line);
1406 if (cp == NULL) /* blank line or comment line */
1407 continue;
1408 tp = strchr(cp, ':'); /* everything has a colon in it */
1409 if (tp == NULL) {
1410 warnx("line %d: syntax error", lineno);
1411 errors++;
1412 continue;
1414 *tp++ = '\0', tp = skip(tp);
1415 if (!strcmp(cp, "type")) {
1416 if (tp == NULL) {
1417 strlcpy(tbuf, "unknown", sizeof(tbuf));
1418 tp = tbuf;
1420 cpp = dktypenames;
1421 for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
1422 if ((s = *cpp) && !strcasecmp(s, tp)) {
1423 lp->d_type = cpp - dktypenames;
1424 goto next;
1426 if (GETNUM16(tp, &v) != 0) {
1427 warnx("line %d: syntax error", lineno);
1428 errors++;
1429 continue;
1431 if (v >= DKMAXTYPES)
1432 warnx("line %d: warning, unknown disk type: %s",
1433 lineno, tp);
1434 lp->d_type = v;
1435 continue;
1437 if (!strcmp(cp, "flags")) {
1438 for (v = 0; (cp = tp) && *cp != '\0';) {
1439 tp = word(cp);
1440 if (!strcasecmp(cp, "removable"))
1441 v |= D_REMOVABLE;
1442 else if (!strcasecmp(cp, "ecc"))
1443 v |= D_ECC;
1444 else if (!strcasecmp(cp, "badsect"))
1445 v |= D_BADSECT;
1446 else {
1447 warnx("line %d: bad flag: %s",
1448 lineno, cp);
1449 errors++;
1452 lp->d_flags = v;
1453 continue;
1455 if (!strcmp(cp, "drivedata")) {
1456 int i;
1458 for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
1459 if (GETNUM32(cp, &v) != 0) {
1460 warnx("line %d: bad drive data",
1461 lineno);
1462 errors++;
1463 } else
1464 lp->d_drivedata[i] = v;
1465 i++;
1466 tp = word(cp);
1468 continue;
1470 if (sscanf(cp, "%lu partitions", &v) == 1) {
1471 if (v == 0 || v > MAXPARTITIONS) {
1472 warnx("line %d: bad # of partitions", lineno);
1473 lp->d_npartitions = MAXPARTITIONS;
1474 errors++;
1475 } else
1476 lp->d_npartitions = v;
1477 continue;
1479 if (tp == NULL) {
1480 tbuf[0] = '\0';
1481 tp = tbuf;
1483 if (!strcmp(cp, "disk")) {
1484 strncpy(lp->d_typename, tp, sizeof(lp->d_typename));
1485 continue;
1487 if (!strcmp(cp, "label")) {
1488 strncpy(lp->d_packname, tp, sizeof(lp->d_packname));
1489 continue;
1491 if (!strcmp(cp, "bytes/sector")) {
1492 if (GETNUM32(tp, &v) != 0 || v <= 0 || (v % 512) != 0) {
1493 warnx("line %d: bad %s: %s", lineno, cp, tp);
1494 errors++;
1495 } else
1496 lp->d_secsize = v;
1497 continue;
1499 if (!strcmp(cp, "sectors/track")) {
1500 if (GETNUM32(tp, &v) != 0) {
1501 warnx("line %d: bad %s: %s", lineno, cp, tp);
1502 errors++;
1503 } else
1504 lp->d_nsectors = v;
1505 continue;
1507 if (!strcmp(cp, "sectors/cylinder")) {
1508 if (GETNUM32(tp, &v) != 0) {
1509 warnx("line %d: bad %s: %s", lineno, cp, tp);
1510 errors++;
1511 } else
1512 lp->d_secpercyl = v;
1513 continue;
1515 if (!strcmp(cp, "tracks/cylinder")) {
1516 if (GETNUM32(tp, &v) != 0) {
1517 warnx("line %d: bad %s: %s", lineno, cp, tp);
1518 errors++;
1519 } else
1520 lp->d_ntracks = v;
1521 continue;
1523 if (!strcmp(cp, "cylinders")) {
1524 if (GETNUM32(tp, &v) != 0) {
1525 warnx("line %d: bad %s: %s", lineno, cp, tp);
1526 errors++;
1527 } else
1528 lp->d_ncylinders = v;
1529 continue;
1531 if (!strcmp(cp, "total sectors") ||
1532 !strcmp(cp, "sectors/unit")) {
1533 if (GETNUM32(tp, &v) != 0) {
1534 warnx("line %d: bad %s: %s", lineno, cp, tp);
1535 errors++;
1536 } else
1537 lp->d_secperunit = v;
1538 continue;
1540 if (!strcmp(cp, "rpm")) {
1541 if (GETNUM16(tp, &v) != 0) {
1542 warnx("line %d: bad %s: %s", lineno, cp, tp);
1543 errors++;
1544 } else
1545 lp->d_rpm = v;
1546 continue;
1548 if (!strcmp(cp, "interleave")) {
1549 if (GETNUM16(tp, &v) != 0) {
1550 warnx("line %d: bad %s: %s", lineno, cp, tp);
1551 errors++;
1552 } else
1553 lp->d_interleave = v;
1554 continue;
1556 if (!strcmp(cp, "trackskew")) {
1557 if (GETNUM16(tp, &v) != 0) {
1558 warnx("line %d: bad %s: %s", lineno, cp, tp);
1559 errors++;
1560 } else
1561 lp->d_trackskew = v;
1562 continue;
1564 if (!strcmp(cp, "cylinderskew")) {
1565 if (GETNUM16(tp, &v) != 0) {
1566 warnx("line %d: bad %s: %s", lineno, cp, tp);
1567 errors++;
1568 } else
1569 lp->d_cylskew = v;
1570 continue;
1572 if (!strcmp(cp, "headswitch")) {
1573 if (GETNUM32(tp, &v) != 0) {
1574 warnx("line %d: bad %s: %s", lineno, cp, tp);
1575 errors++;
1576 } else
1577 lp->d_headswitch = v;
1578 continue;
1580 if (!strcmp(cp, "track-to-track seek")) {
1581 if (GETNUM32(tp, &v) != 0) {
1582 warnx("line %d: bad %s: %s", lineno, cp, tp);
1583 errors++;
1584 } else
1585 lp->d_trkseek = v;
1586 continue;
1588 if ('a' > *cp || *cp > 'z' || cp[1] != '\0') {
1589 warnx("line %d: unknown field: %s", lineno, cp);
1590 errors++;
1591 continue;
1594 /* We have a partition entry */
1595 part = *cp - 'a';
1597 if (part >= MAXPARTITIONS) {
1598 warnx("line %d: bad partition name: %s", lineno, cp);
1599 errors++;
1600 continue;
1602 pp = &lp->d_partitions[part];
1604 NXTXNUM(pp->p_size);
1605 NXTXNUM(pp->p_offset);
1606 /* can't use word() here because of blanks in fstypenames[] */
1607 tp += strspn(tp, " \t");
1608 _CHECKLINE
1609 cp = tp;
1610 cpp = fstypenames;
1611 for (; cpp < &fstypenames[FSMAXTYPES]; cpp++) {
1612 s = *cpp;
1613 if (s == NULL ||
1614 (cp[strlen(s)] != ' ' &&
1615 cp[strlen(s)] != '\t' &&
1616 cp[strlen(s)] != '\0'))
1617 continue;
1618 if (!memcmp(s, cp, strlen(s))) {
1619 pp->p_fstype = cpp - fstypenames;
1620 tp += strlen(s);
1621 if (*tp == '\0')
1622 tp = NULL;
1623 else {
1624 tp += strspn(tp, " \t");
1625 if (*tp == '\0')
1626 tp = NULL;
1628 goto gottype;
1631 tp = word(cp);
1632 if (isdigit(*cp & 0xff)) {
1633 if (GETNUM8(cp, &v) != 0) {
1634 warnx("line %d: syntax error", lineno);
1635 errors++;
1637 } else
1638 v = FSMAXTYPES;
1639 if ((unsigned)v >= FSMAXTYPES) {
1640 warnx("line %d: warning, unknown file system type: %s",
1641 lineno, cp);
1642 warnx("tip: use -l to see all valid file system "
1643 "types");
1644 v = FS_UNUSED;
1646 pp->p_fstype = v;
1647 gottype:
1648 switch (pp->p_fstype) {
1650 case FS_UNUSED: /* XXX */
1651 NXTNUM(pp->p_fsize);
1652 if (pp->p_fsize == 0)
1653 break;
1654 NXTNUM(v);
1655 pp->p_frag = v / pp->p_fsize;
1656 break;
1658 case FS_BSDFFS:
1659 case FS_ADOS:
1660 case FS_APPLEUFS:
1661 NXTNUM(pp->p_fsize);
1662 if (pp->p_fsize == 0)
1663 break;
1664 NXTNUM(v);
1665 pp->p_frag = v / pp->p_fsize;
1666 NXTNUM(pp->p_cpg);
1667 break;
1668 case FS_BSDLFS:
1669 NXTNUM(pp->p_fsize);
1670 if (pp->p_fsize == 0)
1671 break;
1672 NXTNUM(v);
1673 pp->p_frag = v / pp->p_fsize;
1674 NXTNUM(pp->p_sgs);
1675 break;
1676 case FS_EX2FS:
1677 NXTNUM(pp->p_fsize);
1678 if (pp->p_fsize == 0)
1679 break;
1680 NXTNUM(v);
1681 pp->p_frag = v / pp->p_fsize;
1682 break;
1683 case FS_ISO9660:
1684 NXTNUM(pp->p_cdsession);
1685 break;
1686 default:
1687 break;
1689 continue;
1690 error:
1691 errors++;
1692 next:
1695 errors += checklabel(lp);
1696 return (errors == 0);
1700 * Check disklabel for errors and fill in
1701 * derived fields according to supplied values.
1704 checklabel(struct disklabel *lp)
1706 struct partition *pp, *qp;
1707 int i, j, errors;
1708 char part;
1710 errors = 0;
1711 if (lp->d_secsize == 0) {
1712 warnx("sector size %d", lp->d_secsize);
1713 return (1);
1715 if (lp->d_nsectors == 0) {
1716 warnx("sectors/track %d", lp->d_nsectors);
1717 return (1);
1719 if (lp->d_ntracks == 0) {
1720 warnx("tracks/cylinder %d", lp->d_ntracks);
1721 return (1);
1723 if (lp->d_ncylinders == 0) {
1724 warnx("cylinders/unit %d", lp->d_ncylinders);
1725 errors++;
1727 if (lp->d_rpm == 0)
1728 warnx("warning, revolutions/minute %d", lp->d_rpm);
1729 if (lp->d_secpercyl == 0)
1730 lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1731 if (lp->d_secperunit == 0)
1732 lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1733 if (lp->d_bbsize == 0) {
1734 warnx("boot block size %d", lp->d_bbsize);
1735 errors++;
1736 } else if (lp->d_bbsize % lp->d_secsize)
1737 warnx("warning, boot block size %% sector-size != 0");
1738 if (lp->d_sbsize == 0) {
1739 warnx("super block size %d", lp->d_sbsize);
1740 errors++;
1741 } else if (lp->d_sbsize % lp->d_secsize)
1742 warnx("warning, super block size %% sector-size != 0");
1743 if (lp->d_npartitions > MAXPARTITIONS)
1744 warnx("warning, number of partitions (%d) > MAXPARTITIONS (%d)",
1745 lp->d_npartitions, MAXPARTITIONS);
1746 else
1747 for (i = MAXPARTITIONS - 1; i >= lp->d_npartitions; i--) {
1748 part = 'a' + i;
1749 pp = &lp->d_partitions[i];
1750 if (pp->p_size || pp->p_offset) {
1751 warnx("warning, partition %c increased "
1752 "number of partitions from %d to %d",
1753 part, lp->d_npartitions, i + 1);
1754 lp->d_npartitions = i + 1;
1755 break;
1758 for (i = 0; i < lp->d_npartitions; i++) {
1759 part = 'a' + i;
1760 pp = &lp->d_partitions[i];
1761 if (pp->p_size == 0 && pp->p_offset != 0)
1762 warnx("warning, partition %c: size 0, but offset %d",
1763 part, pp->p_offset);
1764 #ifdef STRICT_CYLINDER_ALIGNMENT
1765 if (pp->p_offset % lp->d_secpercyl) {
1766 warnx("warning, partition %c:"
1767 " not starting on cylinder boundary",
1768 part);
1769 errors++;
1771 #endif /* STRICT_CYLINDER_ALIGNMENT */
1772 if (pp->p_offset > lp->d_secperunit) {
1773 warnx("partition %c: offset past end of unit", part);
1774 errors++;
1776 if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1777 warnx("partition %c: partition extends"
1778 " past end of unit",
1779 part);
1780 errors++;
1782 if (pp->p_fstype != FS_UNUSED)
1783 for (j = i + 1; j < lp->d_npartitions; j++) {
1784 qp = &lp->d_partitions[j];
1785 if (qp->p_fstype == FS_UNUSED)
1786 continue;
1787 if (pp->p_offset < qp->p_offset + qp->p_size &&
1788 qp->p_offset < pp->p_offset + pp->p_size)
1789 warnx("partitions %c and %c overlap",
1790 part, 'a' + j);
1793 return (errors);
1796 static void
1797 usage(void)
1799 static const struct {
1800 const char *name;
1801 const char *expn;
1802 } usages[] = {
1803 { "[-ACFrtv] disk", "(to read label)" },
1804 { "-w [-DFrv] [-f disktab] disk disktype [packid]", "(to write label)" },
1805 { "-e [-CDFIrv] disk", "(to edit label)" },
1806 { "-i [-DFIrv] disk", "(to create a label interactively)" },
1807 { "-D [-v] disk", "(to delete existing label(s))" },
1808 { "-R [-DFrv] disk protofile", "(to restore label)" },
1809 { "[-NW] disk", "(to write disable/enable label)" },
1810 { "-l", "(to show all known file system types)" },
1811 { NULL, NULL }
1813 int i;
1814 const char *pn = getprogname();
1815 const char *t = "usage:";
1817 for (i = 0; usages[i].name != NULL; i++) {
1818 (void)fprintf(stderr, "%s %s %s\n\t%s\n",
1819 t, pn, usages[i].name, usages[i].expn);
1820 t = "or";
1822 exit(1);
1825 static int
1826 getulong(const char *str, char sep, char **epp, unsigned long *ul,
1827 unsigned long max)
1829 char *ep;
1831 if (epp == NULL)
1832 epp = &ep;
1834 *ul = strtoul(str, epp, 10);
1836 if ((*ul == ULONG_MAX && errno == ERANGE) || *ul > max)
1837 return ERANGE;
1839 if (*str == '\0' || (**epp != '\0' && **epp != sep &&
1840 !isspace((unsigned char)**epp)))
1841 return EFTYPE;
1843 return 0;
1847 * This is a wrapper over the standard strcmp function to be used with
1848 * qsort on an array of pointers to strings.
1850 static int
1851 qsort_strcmp(const void *v1, const void *v2)
1853 const char *const *sp1 = (const char *const *)v1;
1854 const char *const *sp2 = (const char *const *)v2;
1856 return strcmp(*sp1, *sp2);
1860 * Prints all know file system types for a partition.
1861 * Returns 1 on success, 0 on failure.
1864 list_fs_types(void)
1866 int ret;
1867 size_t nelems;
1869 nelems = 0;
1871 const char *const *namep;
1873 namep = fstypenames;
1874 while (*namep++ != NULL)
1875 nelems++;
1878 ret = 1;
1879 if (nelems > 0) {
1880 const char **list;
1881 size_t i;
1883 list = (const char **)malloc(sizeof(char *) * nelems);
1884 if (list == NULL) {
1885 warnx("sorry, could not allocate memory for list");
1886 ret = 0;
1887 } else {
1888 for (i = 0; i < nelems; i++)
1889 list[i] = fstypenames[i];
1891 qsort(list, nelems, sizeof(char *), qsort_strcmp);
1893 for (i = 0; i < nelems; i++)
1894 (void)printf("%s\n", list[i]);
1896 free(list);
1900 return ret;