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