xref: /netbsd-src/sbin/disklabel/main.c (revision aad9773e38ed2370a628a6416e098f9008fc10a7)
1 /*	$NetBSD: main.c,v 1.42 2014/09/19 17:45:03 matt 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  *
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.
30  */
31 
32 /*
33  * Copyright (c) 1987, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * This code is derived from software contributed to Berkeley by
37  * Symmetric Computer Systems.
38  *
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.
50  *
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.
62  */
63 
64 #if HAVE_NBTOOL_CONFIG_H
65 #include "nbtool_config.h"
66 #endif
67 
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 */
73 
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.42 2014/09/19 17:45:03 matt Exp $");
80 #endif
81 #endif	/* not lint */
82 
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
89 
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>
99 
100 #include <ufs/ufs/dinode.h>
101 #include <ufs/ffs/fs.h>
102 
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 */
116 
117 #include "pathnames.h"
118 #include "extern.h"
119 #include "dkcksum.h"
120 #include "bswap.h"
121 
122 /*
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.
129  */
130 
131 #ifndef BBSIZE
132 #define	BBSIZE	8192			/* size of boot area, with label */
133 #endif
134 
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)
139 
140 #define	DEFEDITOR	_PATH_VI
141 
142 char	specname[MAXPATHLEN];
143 
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 */
148 
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 */
160 
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);
166 static void getmachineparams(const char *);
167 
168 static void		 makedisktab(FILE *, struct disklabel *);
169 static void		 makelabel(const char *, const char *);
170 static void		 l_perror(const char *);
171 static void		 readlabel(int);
172 static int		 edit(int);
173 static int		 editit(const char *);
174 static char		*skip(char *);
175 static char		*word(char *);
176 static int		 getasciilabel(FILE *, struct disklabel *);
177 __dead static void	 usage(void);
178 static int		 qsort_strcmp(const void *, const void *);
179 static int		 getulong(const char *, char, char **,
180     unsigned long *, unsigned long);
181 #define GETNUM32(a, v)	getulong(a, '\0', NULL, v, UINT32_MAX)
182 #define GETNUM16(a, v)	getulong(a, '\0', NULL, v, UINT16_MAX)
183 #define GETNUM8(a, v)	getulong(a, '\0', NULL, v, UINT8_MAX)
184 
185 static int set_writable_fd = -1;
186 
187 static u_int labeloffset;
188 static u_int labelsector;
189 static int labelusesmbr;
190 u_int maxpartitions;
191 static int byteorder;
192 
193 static int biendian_p;
194 #ifndef HAVE_NBTOOL_CONFIG_H
195 static int native_p = 1;
196 #endif
197 int bswap_p;
198 
199 static const struct disklabel_params {
200 	const char *machine;
201 	int labelusesmbr;
202 	u_int labelsector;
203 	u_int labeloffset;
204 	u_int maxpartitions;
205 	u_int raw_part;
206 	u_int oldmaxpartitions;
207 	int byteorder;
208 } disklabel_params[] = {
209 	{ "mvme68k",	0, 0,   0,  8, 2, 0, BIG_ENDIAN },	/* m68k */
210 	{ "next68k",	0, 0,   0,  8, 2, 0, BIG_ENDIAN },	/* m68k */
211 
212 	{ "algor",	0, 0,  64,  8, 2, 0, LITTLE_ENDIAN },	/* mips */
213 	{ "alpha",	0, 0,  64,  8, 2, 0, LITTLE_ENDIAN },	/* alpha */
214 	{ "luna68k",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68k */
215 	{ "mac68k",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68k */
216 	{ "news68k",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68k */
217 	{ "newsmips",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* mips */
218 	{ "pmax",	0, 0,  64,  8, 2, 0, LITTLE_ENDIAN },	/* mips */
219 	{ "sun2",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68k */
220 	{ "sun68k",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68010 */
221 	{ "x68k",	0, 0,  64,  8, 2, 0, BIG_ENDIAN },	/* m68010 */
222 
223 	{ "vax",	0, 0,  64, 12, 2, 8, LITTLE_ENDIAN },	/* vax */
224 
225 	{ "amiga",	0, 0,  64, 16, 2, 0, BIG_ENDIAN },	/* m68k */
226 	{ "amigappc",	0, 0,  64, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
227 	{ "evbmips",	0, 0,  64, 16, 2, 0, 0 },		/* mips */
228 	{ "evbppc",	0, 0,  64, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
229 
230 	{ "sparc",	0, 0, 128,  8, 2, 0, BIG_ENDIAN },	/* sun */
231 	{ "sparc64",	0, 0, 128,  8, 2, 0, BIG_ENDIAN },	/* sun */
232 	{ "sun3",	0, 0, 128,  8, 2, 0, BIG_ENDIAN },	/* sun */
233 
234 	{ "atari",	0, 0, 516, 16, 2, 0, BIG_ENDIAN },	/* m68k */
235 
236 	{ "mipsco",	0, 1,   0,  8, 2, 0, BIG_ENDIAN },	/* mips */
237 	{ "mvmeppc",	0, 1,   0,  8, 3, 0, BIG_ENDIAN },	/* powerpc */
238 
239 	{ "bebox",	0, 1,   0,  8, 3, 0, BIG_ENDIAN },	/* powerpc */
240 
241 	{ "emips",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* mips */
242 	{ "hppa",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* hppa */
243 	{ "ibmnws",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
244 	{ "ofppc",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
245 	{ "rs6000",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
246 	{ "sandpoint",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
247 	{ "sgimips",	0, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* mips */
248 
249 	{ "sbmips",	0, 1,   0, 16, 3, 0, 0 },		/* mips */
250 
251 	{ "cesfic",	0, 2,   0,  8, 2, 0, BIG_ENDIAN },	/* m68k */
252 	{ "hp300",	0, 2,   0,  8, 2, 0, BIG_ENDIAN },	/* m68k */
253 
254 	{ "ews4800mips",0, 9,   0, 16, 15, 0, BIG_ENDIAN },	/* mips */
255 
256 	{ "macppc",	1, 0,  64, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
257 	{ "pmon",	1, 0,  64, 16, 2, 0, 0 },		/* evbmips */
258 
259 	{ "prep",	1, 1,   0,  8, 2, 0, BIG_ENDIAN },	/* powerpc */
260 
261 	{ "dreamcast",	1, 1,   0, 16, 2, 0, LITTLE_ENDIAN },	/* sh3 */
262 	{ "evbarm64",	1, 1,   0, 16, 2, 0, 0 },		/* aarch64 */
263 	{ "evbcf",	1, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* coldfire */
264 	{ "evbppc-mbr",	1, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* powerpc */
265 	{ "evbsh3",	1, 1,   0, 16, 2, 0, 0 },		/* sh3 */
266 	{ "hpcsh",	1, 1,   0, 16, 2, 0, LITTLE_ENDIAN },	/* sh3 */
267 	{ "mmeye",	1, 1,   0, 16, 2, 0, 0 },		/* sh3 */
268 	{ "or1k",	1, 1,   0, 16, 2, 0, BIG_ENDIAN },	/* or1k */
269 	{ "riscv",	1, 1,   0, 16, 2, 0, LITTLE_ENDIAN },	/* riscv */
270 
271 	{ "acorn26",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
272 	{ "acorn32",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
273 	{ "cats",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
274 	{ "evbarm",	1, 1,   0, 16, 2, 8, 0 },		/* arm */
275 	{ "iyonix",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
276 	{ "netwinder",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
277 	{ "shark",	1, 1,   0, 16, 2, 8, LITTLE_ENDIAN },	/* arm */
278 
279 	{ "amd64",	1, 1,   0, 16, 3, 0, LITTLE_ENDIAN },	/* x86 */
280 	{ "arc",	1, 1,   0, 16, 3, 0, LITTLE_ENDIAN },	/* mips */
281 	{ "cobalt",	1, 1,   0, 16, 3, 0, LITTLE_ENDIAN },	/* mips */
282 	{ "landisk",	1, 1,   0, 16, 3, 0, LITTLE_ENDIAN },	/* sh3 */
283 
284 	{ "epoc32",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* arm */
285 	{ "hpcarm",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* arm */
286 	{ "hpcmips",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* mips */
287 	{ "i386",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* x86 */
288 	{ "ia64",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* x86 */
289 	{ "zaurus",	1, 1,   0, 16, 3, 8, LITTLE_ENDIAN },	/* arm */
290 
291 	{ NULL,		0, 0,   0,  0, 0, 0, 0 },	/* must be last */
292 };
293 
294 #ifndef HAVE_NBTOOL_CONFIG_H
295 static struct disklabel_params native_params;
296 #endif
297 
298 static const struct arch_endian {
299 	int byteorder;
300 	const char *arch;
301 } arch_endians[] = {
302 	{ LITTLE_ENDIAN, "aarch64" },
303 	{ LITTLE_ENDIAN, "alpha" },
304 	{ LITTLE_ENDIAN, "arm" },
305 	{ LITTLE_ENDIAN, "earm" },
306 	{ LITTLE_ENDIAN, "earmhf" },
307 	{ LITTLE_ENDIAN, "earmv4" },
308 	{ LITTLE_ENDIAN, "earmv5" },
309 	{ LITTLE_ENDIAN, "earmv6" },
310 	{ LITTLE_ENDIAN, "earmv6hf" },
311 	{ LITTLE_ENDIAN, "earmv7" },
312 	{ LITTLE_ENDIAN, "earmv7hf" },
313 	{ LITTLE_ENDIAN, "i386" },
314 	{ LITTLE_ENDIAN, "ia64" },
315 	{ LITTLE_ENDIAN, "mipsel" },
316 	{ LITTLE_ENDIAN, "mips64el" },
317 	{ LITTLE_ENDIAN, "riscv32" },
318 	{ LITTLE_ENDIAN, "riscv64" },
319 	{ LITTLE_ENDIAN, "sh3el" },
320 	{ LITTLE_ENDIAN, "vax" },
321 	{ LITTLE_ENDIAN, "x86_64" },
322 
323 	{ BIG_ENDIAN, "aarch64eb" },
324 	{ BIG_ENDIAN, "armeb" },
325 	{ BIG_ENDIAN, "coldfire" },
326 	{ BIG_ENDIAN, "earmeb" },
327 	{ BIG_ENDIAN, "earmhfeb" },
328 	{ BIG_ENDIAN, "earmv4eb" },
329 	{ BIG_ENDIAN, "earmv5eb" },
330 	{ BIG_ENDIAN, "earmv6eb" },
331 	{ BIG_ENDIAN, "earmv6hfeb" },
332 	{ BIG_ENDIAN, "earmv7eb" },
333 	{ BIG_ENDIAN, "earmv7hfeb" },
334 	{ BIG_ENDIAN, "hppa" },
335 	{ BIG_ENDIAN, "m68000" },
336 	{ BIG_ENDIAN, "m68k" },
337 	{ BIG_ENDIAN, "mipseb" },
338 	{ BIG_ENDIAN, "mips64eb" },
339 	{ BIG_ENDIAN, "or1k" },
340 	{ BIG_ENDIAN, "powerpc" },
341 	{ BIG_ENDIAN, "sh3eb" },
342 	{ BIG_ENDIAN, "sparc" },
343 	{ BIG_ENDIAN, "sparc64" },
344 
345 	{ 0, NULL },
346 };
347 
348 /* Default location for label - only used if we don't find one to update */
349 #define LABEL_OFFSET (dklabel_getlabelsector() * DEV_BSIZE + dklabel_getlabeloffset())
350 
351 /*
352  * For portability it doesn't make sense to use any other value....
353  * Except, maybe, the size of a physical sector.
354  * This value is used if we have to write a label to the start of an mbr ptn.
355  */
356 #ifndef	LABELOFFSET_MBR
357 #define	LABELOFFSET_MBR	512
358 #endif
359 
360 #if HAVE_NBTOOL_CONFIG_H
361 static int
362 opendisk(const char *path, int flags, char *buf, int buflen, int cooked)
363 {
364 	int f;
365 	f = open(path, flags, 0);
366 	strlcpy(buf, path, buflen);
367 	return f;
368 }
369 #endif /* HAVE_NBTOOL_CONFIG_H */
370 
371 static void
372 setbyteorder(int new_byteorder)
373 {
374 	static int set_p;
375 
376 	if ((!biendian_p || set_p)
377 	    && byteorder != 0
378 	    && byteorder != new_byteorder) {
379 		warn("changing %s byteorder to %s",
380 		    byteorder == LITTLE_ENDIAN ? "le" : "be",
381 		    new_byteorder == LITTLE_ENDIAN ? "le" : "be");
382 	}
383 	byteorder = new_byteorder;
384 	biendian_p = 0;
385 	set_p = 1;
386 }
387 
388 static void
389 getmachineparams(const char *mach)
390 {
391 	const struct disklabel_params *dp = disklabel_params;
392 	for (; dp->machine != NULL; dp++) {
393 		if (!strcmp(mach, dp->machine)) {
394 			labelusesmbr = dp->labelusesmbr;
395 			labelsector = dp->labelsector;
396 			labeloffset = dp->labeloffset;
397 			maxpartitions = dp->maxpartitions;
398 			biendian_p = (dp->byteorder == 0);
399 			if (!biendian_p)
400 				setbyteorder(dp->byteorder);
401 			return;
402 		}
403 	}
404 	errx(1, "%s: unknown machine type", mach);
405 }
406 
407 static void
408 getarchbyteorder(const char *arch)
409 {
410 	const struct arch_endian *p = arch_endians;
411 	for (; p->arch != NULL; p++) {
412 		if (!strcmp(arch, p->arch)) {
413 			setbyteorder(p->byteorder);
414 			return;
415 		}
416 	}
417 	errx(1, "%s: unknown arch", arch);
418 }
419 
420 static daddr_t
421 dklabel_getlabelsector(void)
422 {
423 	unsigned long int nval;
424 	char *end;
425 	const char *val;
426 
427 	if ((val = getenv("DISKLABELSECTOR")) == NULL)
428 		return labelsector;
429 	if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
430 		err(EXIT_FAILURE, "DISKLABELSECTOR in environment");
431 	return nval;
432 }
433 
434 static off_t
435 dklabel_getlabeloffset(void)
436 {
437 	unsigned long int nval;
438 	char *end;
439 	const char *val;
440 
441 	if ((val = getenv("DISKLABELOFFSET")) == NULL)
442 		return labeloffset;
443 	if ((nval = strtoul(val, &end, 10)) == ULONG_MAX && errno == ERANGE)
444 		err(EXIT_FAILURE, "DISKLABELOFFSET in environment");
445 	return nval;
446 }
447 
448 static void
449 clear_writable(void)
450 {
451 	static int zero = 0;
452 	dk_ioctl(set_writable_fd, DIOCWLABEL, &zero);
453 }
454 
455 int
456 main(int argc, char *argv[])
457 {
458 	FILE	*t;
459 	int	 ch, f, error;
460 	char	*dkname;
461 	char	*cp;
462 	struct stat sb;
463 	int	 writable;
464 	enum {
465 		UNSPEC, EDIT, READ, RESTORE, SETWRITABLE, SETREADONLY,
466 		WRITE, INTERACT, DELETE
467 	} op = UNSPEC, old_op;
468 
469 #ifndef HAVE_NBTOOL_CONFIG_H
470 	labeloffset = native_params.labeloffset = getlabeloffset();
471 	labelsector = native_params.labelsector = getlabelsector();
472 	labelusesmbr = native_params.labelusesmbr = getlabelusesmbr();
473 	maxpartitions = native_params.maxpartitions = getmaxpartitions();
474 	byteorder = native_params.byteorder = BYTE_ORDER;
475 #endif
476 
477 	if ((cp = getenv("MACHINE")) != NULL) {
478 		getmachineparams(cp);
479 	}
480 
481 	if ((cp = getenv("MACHINE_ARCH")) != NULL) {
482 		getarchbyteorder(cp);
483 	}
484 
485 	mflag = labelusesmbr;
486 	if (mflag < 0) {
487 #if HAVE_NBTOOL_CONFIG_H
488 		warn("getlabelusesmbr() failed");
489 #else
490 		warn("getlabelusesmbr() failed");
491 		mflag = LABELUSESMBR;
492 #endif
493 	}
494 #if HAVE_NBTOOL_CONFIG_H
495 	/* We must avoid doing any ioctl requests */
496 	Fflag = rflag = 1;
497 #endif
498 
499 	error = 0;
500 	while ((ch = getopt(argc, argv, "AB:CDFIM:NRWef:ilmrtvw")) != -1) {
501 		old_op = op;
502 		switch (ch) {
503 		case 'A':	/* Action all labels */
504 			Aflag = 1;
505 			rflag = 1;
506 			break;
507 		case 'C':	/* Display in CHS format */
508 			Cflag = 1;
509 			break;
510 		case 'D':	/* Delete all existing labels */
511 			Dflag = 1;
512 			rflag = 1;
513 			break;
514 		case 'F':	/* Treat 'disk' as a regular file */
515 			Fflag = 1;
516 			rflag = 1;	/* Force direct access */
517 			break;
518 		case 'I':	/* Use default label if none found */
519 			Iflag = 1;
520 			rflag = 1;	/* Implies direct access */
521 			break;
522 		case 'R':	/* Restore label from text file */
523 			op = RESTORE;
524 			break;
525 		case 'B':	/* byteorder */
526 			if (!strcmp(optarg, "be")) {
527 				setbyteorder(BIG_ENDIAN);
528 			} else if (!strcmp(optarg, "le")) {
529 				setbyteorder(LITTLE_ENDIAN);
530 			} else {
531 				errx(1, "%s: not be or le", optarg);
532 			}
533 			break;
534 		case 'M':	/* machine type */
535 			getmachineparams(optarg);
536 			break;
537 		case 'N':	/* Disallow writes to label sector */
538 			op = SETREADONLY;
539 			break;
540 		case 'W':	/* Allow writes to label sector */
541 			op = SETWRITABLE;
542 			break;
543 		case 'e':	/* Edit label with $EDITOR */
544 			op = EDIT;
545 			break;
546 		case 'f':	/* Name of disktab file */
547 			if (setdisktab(optarg) == -1)
548 				usage();
549 			break;
550 		case 'i':	/* Edit using built-in editor */
551 			op = INTERACT;
552 			break;
553 		case 'l':	/* List all known file system types and exit */
554 			lflag = 1;
555 			break;
556 		case 'm':	/* Expect disk to have an MBR */
557 			mflag ^= 1;
558 			break;
559 		case 'r':	/* Read/write label directly from disk */
560 			rflag = 1;
561 			break;
562 		case 't':	/* Format output as a disktab entry */
563 			tflag = 1;
564 			break;
565 		case 'v':	/* verbose/diag output */
566 			verbose++;
567 			break;
568 		case 'w':	/* Write label based on disktab entry */
569 			op = WRITE;
570 			break;
571 		case '?':
572 		default:
573 			usage();
574 		}
575 		if (old_op != UNSPEC && old_op != op)
576 			usage();
577 	}
578 
579 	if (maxpartitions == 0) {
580 		errx(1, "unknown label: use -M/-B and $MACHINE/$MACHINE_ARCH");
581 	}
582 	if (byteorder != BIG_ENDIAN && byteorder != LITTLE_ENDIAN) {
583 		errx(1, "unknown byteorder");
584 	}
585 	bswap_p = (byteorder != BYTE_ORDER);
586 #ifdef DEBUG
587 	printf("labelusesmbr=%d labelsector=%u labeloffset=%u maxpartitions=%u\n",
588 	    labelusesmbr, labelsector, labeloffset, maxpartitions);
589 	printf("byteorder=%d bswap_p=%d\n", byteorder, bswap_p);
590 #endif
591 #ifndef HAVE_NBTOOL_CONFIG_H
592 	/*
593 	 * If the disklabel has the same location as the native disklabel and
594 	 * fewer or equal paritions, we can use the native ioctls.  Otherwise
595 	 * force file/raw access.
596 	 */
597 	native_p = native_params.labelusesmbr == labelusesmbr
598 	    && native_params.labelsector == labelsector
599 	    && native_params.labeloffset == labeloffset
600 	    && maxpartitions <= native_params.maxpartitions
601 	    && !bswap_p;
602 	if (!native_p)
603 		Fflag = rflag = 1;
604 #endif
605 
606 	argc -= optind;
607 	argv += optind;
608 
609 	if (lflag)
610 		exit(list_fs_types() ? EXIT_SUCCESS : EXIT_FAILURE);
611 
612 	if (op == UNSPEC)
613 		op = Dflag ? DELETE : READ;
614 
615 	if (argc < 1)
616 		usage();
617 
618 	if (Iflag && op != EDIT && op != INTERACT)
619 		usage();
620 
621 	dkname = argv[0];
622 	f = opendisk(dkname, op == READ ? O_RDONLY : O_RDWR,
623 		    specname, sizeof specname, 0);
624 	if (f < 0)
625 		err(4, "%s", specname);
626 
627 	if (!Fflag && fstat(f, &sb) == 0 && S_ISREG(sb.st_mode))
628 		Fflag = rflag = 1;
629 
630 	switch (op) {
631 
632 	case DELETE:	/* Remove all existing labels */
633 		if (argc != 1)
634 			usage();
635 		Dflag = 2;
636 		writelabel_direct(f);
637 		break;
638 
639 	case EDIT:
640 		if (argc != 1)
641 			usage();
642 		readlabel(f);
643 		error = edit(f);
644 		break;
645 
646 	case INTERACT:
647 		if (argc != 1)
648 			usage();
649 		readlabel(f);
650 		/*
651 		 * XXX: Fill some default values so checklabel does not fail
652 		 */
653 		if (lab.d_bbsize == 0)
654 			lab.d_bbsize = BBSIZE;
655 		if (lab.d_sbsize == 0)
656 			lab.d_sbsize = SBLOCKSIZE;
657 		interact(&lab, f);
658 		break;
659 
660 	case READ:
661 		if (argc != 1)
662 			usage();
663 		read_all = Aflag;
664 		readlabel(f);
665 		if (read_all)
666 			/* Label got printed in the bowels of readlabel */
667 			break;
668 		if (tflag)
669 			makedisktab(stdout, &lab);
670 		else {
671 			showinfo(stdout, &lab, specname);
672 			showpartitions(stdout, &lab, Cflag);
673 		}
674 		error = checklabel(&lab);
675 		if (error)
676 			error += 100;
677 		break;
678 
679 	case RESTORE:
680 		if (argc != 2)
681 			usage();
682 		if (!(t = fopen(argv[1], "r")))
683 			err(4, "%s", argv[1]);
684 		if (getasciilabel(t, &lab))
685 			error = write_label(f);
686 		else
687 			error = 1;
688 		break;
689 
690 	case SETREADONLY:
691 		writable = 0;
692 		goto do_diocwlabel;
693 	case SETWRITABLE:
694 		writable = 1;
695 	    do_diocwlabel:
696 		if (argc != 1)
697 			usage();
698 		if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
699 			err(4, "ioctl DIOCWLABEL");
700 		break;
701 
702 	case WRITE:	/* Create label from /etc/disktab entry & write */
703 		if (argc < 2 || argc > 3)
704 			usage();
705 		makelabel(argv[1], argv[2]);
706 		if (checklabel(&lab) == 0)
707 			error = write_label(f);
708 		else
709 			error = 1;
710 		break;
711 
712 	case UNSPEC:
713 		usage();
714 
715 	}
716 	exit(error);
717 }
718 
719 /*
720  * Construct a prototype disklabel from /etc/disktab.
721  */
722 static void
723 makelabel(const char *type, const char *name)
724 {
725 	struct disklabel *dp;
726 
727 	dp = getdiskbyname(type);
728 	if (dp == NULL)
729 		errx(1, "unknown disk type: %s", type);
730 	lab = *dp;
731 
732 	/* d_packname is union d_boot[01], so zero */
733 	(void)memset(lab.d_packname, 0, sizeof(lab.d_packname));
734 	if (name)
735 		(void)strncpy(lab.d_packname, name, sizeof(lab.d_packname));
736 }
737 
738 static int
739 write_label(int f)
740 {
741 	int writable;
742 
743 	lab.d_magic = DISKMAGIC;
744 	lab.d_magic2 = DISKMAGIC;
745 	lab.d_checksum = 0;
746 	lab.d_checksum = dkcksum(&lab);
747 
748 	if (rflag) {
749 		/* Write the label directly to the disk */
750 
751 		/*
752 		 * First set the kernel disk label,
753 		 * then write a label to the raw disk.
754 		 * If the SDINFO ioctl fails because it is unimplemented,
755 		 * keep going; otherwise, the kernel consistency checks
756 		 * may prevent us from changing the current (in-core)
757 		 * label.
758 		 */
759 		if (!Fflag && dk_ioctl(f, DIOCSDINFO, &lab) < 0 &&
760 		    errno != ENODEV && errno != ENOTTY) {
761 			l_perror("ioctl DIOCSDINFO");
762 			return (1);
763 		}
764 		/*
765 		 * write enable label sector before write (if necessary),
766 		 * disable after writing.
767 		 */
768 		writable = 1;
769 		if (!Fflag) {
770 			if (dk_ioctl(f, DIOCWLABEL, &writable) < 0)
771 				perror("ioctl DIOCWLABEL");
772 			set_writable_fd = f;
773 			atexit(clear_writable);
774 		}
775 
776 		writelabel_direct(f);
777 
778 		/*
779 		 * Now issue a DIOCWDINFO. This will let the kernel convert the
780 		 * disklabel to some machdep format if needed.
781 		 */
782 		/* XXX: This is stupid! */
783 		if (!Fflag && dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
784 			l_perror("ioctl DIOCWDINFO");
785 			return (1);
786 		}
787 	} else {
788 		/* Get the kernel to write the label */
789 		if (dk_ioctl(f, DIOCWDINFO, &lab) < 0) {
790 			l_perror("ioctl DIOCWDINFO");
791 			return (1);
792 		}
793 	}
794 
795 #ifdef VAX_ALTLABELS
796 	if (lab.d_type == DTYPE_SMD && lab.d_flags & D_BADSECT &&
797 	    lab.d_secsize == 512) {
798 		/* Write the label to the odd sectors of the last track! */
799 		daddr_t	alt;
800 		int	i;
801 		uint8_t sec0[512];
802 
803 		if (pread(f, sec0, 512, 0) < 512) {
804 			warn("read master label to write alternates");
805 			return 0;
806 		}
807 
808 		alt = lab.d_ncylinders * lab.d_secpercyl - lab.d_nsectors;
809 		for (i = 1; i < 11 && (uint32_t)i < lab.d_nsectors; i += 2) {
810 			if (pwrite(f, sec0, 512, (off_t)(alt + i) * 512) < 512)
811 				warn("alternate label %d write", i/2);
812 		}
813 	}
814 #endif	/* VAX_ALTLABELS */
815 
816 	return 0;
817 }
818 
819 int
820 writelabel(int f, struct disklabel *lp)
821 {
822 	if (lp != &lab)
823 		lab = *lp;
824 	return write_label(f);
825 }
826 
827 static void
828 l_perror(const char *s)
829 {
830 
831 	switch (errno) {
832 
833 	case ESRCH:
834 		warnx("%s: No disk label on disk;\n"
835 		    "use \"disklabel -I\" to install initial label", s);
836 		break;
837 
838 	case EINVAL:
839 		warnx("%s: Label magic number or checksum is wrong!\n"
840 		    "(disklabel or kernel is out of date?)", s);
841 		break;
842 
843 	case EBUSY:
844 		warnx("%s: Open partition would move or shrink", s);
845 		break;
846 
847 	case EXDEV:
848 		warnx("%s: Labeled partition or 'a' partition must start"
849 		      " at beginning of disk", s);
850 		break;
851 
852 	default:
853 		warn("%s", s);
854 		break;
855 	}
856 }
857 
858 #ifdef NO_MBR_SUPPORT
859 #define process_mbr(f, action) 1
860 #else
861 /*
862  * Scan DOS/MBR partition table and extended partition list for NetBSD ptns.
863  */
864 static int
865 process_mbr(int f, int (*action)(int, u_int))
866 {
867 	struct mbr_partition *dp;
868 	struct mbr_sector mbr;
869 	int rval = 1, res;
870 	int part;
871 	u_int ext_base, next_ext, this_ext, start;
872 
873 	ext_base = 0;
874 	next_ext = 0;
875 	for (;;) {
876 		this_ext = next_ext;
877 		next_ext = 0;
878 		if (verbose > 1)
879 			warnx("reading mbr sector %u", this_ext);
880 		if (pread(f, &mbr, sizeof mbr, this_ext * (off_t)DEV_BSIZE)
881 		    != sizeof(mbr)) {
882 			if (verbose)
883 				warn("Can't read master boot record %u",
884 				    this_ext);
885 			break;
886 		}
887 
888 		/* Check if table is valid. */
889 		if (mbr.mbr_magic != htole16(MBR_MAGIC)) {
890 			if (verbose)
891 				warnx("Invalid signature in mbr record %u",
892 				    this_ext);
893 			break;
894 		}
895 
896 		dp = &mbr.mbr_parts[0];
897 
898 		/* Find NetBSD partition(s). */
899 		for (part = 0; part < MBR_PART_COUNT; dp++, part++) {
900 			start = le32toh(dp->mbrp_start);
901 			switch (dp->mbrp_type) {
902 #ifdef COMPAT_386BSD_MBRPART
903 			case MBR_PTYPE_386BSD:
904 				if (ext_base != 0)
905 					break;
906 				/* FALLTHROUGH */
907 #endif
908 			case MBR_PTYPE_NETBSD:
909 				res = action(f, this_ext + start);
910 				if (res <= 0)
911 					/* Found or failure */
912 					return res;
913 				if (res > rval)
914 					/* Keep largest value */
915 					rval = res;
916 				break;
917 			case MBR_PTYPE_EXT:
918 			case MBR_PTYPE_EXT_LBA:
919 			case MBR_PTYPE_EXT_LNX:
920 				next_ext = start;
921 				break;
922 			default:
923 				break;
924 			}
925 		}
926 		if (next_ext == 0)
927 			/* No more extended partitions */
928 			break;
929 		next_ext += ext_base;
930 		if (ext_base == 0)
931 			ext_base = next_ext;
932 
933 		if (next_ext <= this_ext) {
934 			if (verbose)
935 				warnx("Invalid extended chain %x <= %x",
936 					next_ext, this_ext);
937 			break;
938 		}
939 		/* Maybe we should check against the disk size... */
940 	}
941 
942 	return rval;
943 }
944 
945 static int
946 readlabel_mbr(int f, u_int sector)
947 {
948 	struct disklabel *disk_lp;
949 
950 	disk_lp = find_label(f, sector);
951 	if (disk_lp == NULL)
952 		return 1;
953 	targettohlabel(&lab, disk_lp);
954 	return 0;
955 }
956 
957 static int
958 writelabel_mbr(int f, u_int sector)
959 {
960 	return update_label(f, sector, mflag ? LABELOFFSET_MBR : ~0U) ? 2 : 0;
961 }
962 
963 #endif	/* !NO_MBR_SUPPORT */
964 
965 #ifndef USE_ACORN
966 #define get_filecore_partition(f) 0
967 #else
968 /*
969  * static int filecore_checksum(u_char *bootblock)
970  *
971  * Calculates the filecore boot block checksum. This is used to validate
972  * a filecore boot block on the disk.  If a boot block is validated then
973  * it is used to locate the partition table. If the boot block is not
974  * validated, it is assumed that the whole disk is NetBSD.
975  *
976  * The basic algorithm is:
977  *
978  *	for (each byte in block, excluding checksum) {
979  *		sum += byte;
980  *		if (sum > 255)
981  *			sum -= 255;
982  *	}
983  *
984  * That's equivalent to summing all of the bytes in the block
985  * (excluding the checksum byte, of course), then calculating the
986  * checksum as "cksum = sum - ((sum - 1) / 255) * 255)".  That
987  * expression may or may not yield a faster checksum function,
988  * but it's easier to reason about.
989  *
990  * Note that if you have a block filled with bytes of a single
991  * value "X" (regardless of that value!) and calculate the cksum
992  * of the block (excluding the checksum byte), you will _always_
993  * end up with a checksum of X.  (Do the math; that can be derived
994  * from the checksum calculation function!)  That means that
995  * blocks which contain bytes which all have the same value will
996  * always checksum properly.  That's a _very_ unlikely occurence
997  * (probably impossible, actually) for a valid filecore boot block,
998  * so we treat such blocks as invalid.
999  */
1000 static int
1001 filecore_checksum(u_char *bootblock)
1002 {
1003 	u_char	byte0, accum_diff;
1004 	u_int	sum;
1005 	int	i;
1006 
1007 	sum = 0;
1008 	accum_diff = 0;
1009 	byte0 = bootblock[0];
1010 
1011 	/*
1012 	 * Sum the contents of the block, keeping track of whether
1013 	 * or not all bytes are the same.  If 'accum_diff' ends up
1014 	 * being zero, all of the bytes are, in fact, the same.
1015 	 */
1016 	for (i = 0; i < 511; ++i) {
1017 		sum += bootblock[i];
1018 		accum_diff |= bootblock[i] ^ byte0;
1019 	}
1020 
1021 	/*
1022 	 * Check to see if the checksum byte is the same as the
1023 	 * rest of the bytes, too.  (Note that if all of the bytes
1024 	 * are the same except the checksum, a checksum compare
1025 	 * won't succeed, but that's not our problem.)
1026 	 */
1027 	accum_diff |= bootblock[i] ^ byte0;
1028 
1029 	/* All bytes in block are the same; call it invalid. */
1030 	if (accum_diff == 0)
1031 		return (-1);
1032 
1033 	return (sum - ((sum - 1) / 255) * 255);
1034 }
1035 
1036 /*
1037  * Check for the presence of a RiscOS filecore boot block
1038  * indicating an ADFS file system on the disc.
1039  * Return the offset to the NetBSD part of the disc if
1040  * this can be determined.
1041  * This routine will terminate disklabel if the disc
1042  * is found to be ADFS only.
1043  */
1044 static u_int
1045 get_filecore_partition(int f)
1046 {
1047 	struct filecore_bootblock	*fcbb;
1048 	static u_char	bb[DEV_BSIZE];
1049 	u_int		offset;
1050 	struct riscix_partition_table	*riscix_part;
1051 	int		loop;
1052 
1053 	if (pread(f, bb, sizeof(bb), (off_t)FILECORE_BOOT_SECTOR * DEV_BSIZE) != sizeof(bb))
1054 		err(4, "can't read filecore boot block");
1055 	fcbb = (struct filecore_bootblock *)bb;
1056 
1057 	/* Check if table is valid. */
1058 	if (filecore_checksum(bb) != fcbb->checksum)
1059 		return (0);
1060 
1061 	/*
1062 	 * Check for NetBSD/arm32 (RiscBSD) partition marker.
1063 	 * If found the NetBSD disklabel location is easy.
1064 	 */
1065 	offset = (fcbb->partition_cyl_low + (fcbb->partition_cyl_high << 8))
1066 	    * fcbb->heads * fcbb->secspertrack;
1067 
1068 	switch (fcbb->partition_type) {
1069 
1070 	case PARTITION_FORMAT_RISCBSD:
1071 		return (offset);
1072 
1073 	case PARTITION_FORMAT_RISCIX:
1074 		/*
1075 		 * Read the RISCiX partition table and search for the
1076 		 * first partition named "RiscBSD", "NetBSD", or "Empty:"
1077 		 *
1078 		 * XXX is use of 'Empty:' really desirable?! -- cgd
1079 		 */
1080 
1081 		if (pread(f, bb, sizeof(bb), (off_t)offset * DEV_BSIZE) != sizeof(bb))
1082 			err(4, "can't read riscix partition table");
1083 		riscix_part = (struct riscix_partition_table *)bb;
1084 
1085 		for (loop = 0; loop < NRISCIX_PARTITIONS; ++loop) {
1086 			if (strcmp((char *)riscix_part->partitions[loop].rp_name,
1087 				    "RiscBSD") == 0 ||
1088 			    strcmp((char *)riscix_part->partitions[loop].rp_name,
1089 				    "NetBSD") == 0 ||
1090 			    strcmp((char *)riscix_part->partitions[loop].rp_name,
1091 				    "Empty:") == 0) {
1092 				return riscix_part->partitions[loop].rp_start;
1093 				break;
1094 			}
1095 		}
1096 		/*
1097 		 * Valid filecore boot block, RISCiX partition table
1098 		 * but no NetBSD partition. We should leave this
1099 		 * disc alone.
1100 		 */
1101 		errx(4, "cannot label: no NetBSD partition found"
1102 			" in RISCiX partition table");
1103 
1104 	default:
1105 		/*
1106 		 * Valid filecore boot block and no non-ADFS partition.
1107 		 * This means that the whole disc is allocated for ADFS
1108 		 * so do not trash ! If the user really wants to put a
1109 		 * NetBSD disklabel on the disc then they should remove
1110 		 * the filecore boot block first with dd.
1111 		 */
1112 		errx(4, "cannot label: filecore-only disk"
1113 			" (no non-ADFS partition)");
1114 	}
1115 	return (0);
1116 }
1117 #endif	/* USE_ACORN */
1118 
1119 /*
1120  * Fetch disklabel for disk to 'lab'.
1121  * Use ioctl to get label unless -r flag is given.
1122  */
1123 static void
1124 readlabel(int f)
1125 {
1126 	if (rflag) {
1127 		/* Get label directly from disk */
1128 		if (readlabel_direct(f) == 0)
1129 			return;
1130 		/*
1131 		 * There was no label on the disk. Get the fictious one
1132 		 * as a basis for initialisation.
1133 		 */
1134 		if (!Fflag && Iflag && (dk_ioctl(f, DIOCGDINFO, &lab) == 0 ||
1135 		    dk_ioctl(f, DIOCGDEFLABEL, &lab) == 0))
1136 			return;
1137 	} else {
1138 		/* Get label from kernel. */
1139 		if (dk_ioctl(f, DIOCGDINFO, &lab) < 0)
1140 			err(4, "ioctl DIOCGDINFO");
1141 		return;
1142 	}
1143 
1144 	if (read_all == 2)
1145 		/* We actually found one, and printed it... */
1146 		exit(0);
1147 	errx(1, "could not read existing label");
1148 }
1149 
1150 /*
1151  * Reading the label from the disk is largely a case of 'hunt the label'.
1152  * and since different architectures default to different places there
1153  * could even be more than one label that contradict each other!
1154  * For now we look in the expected place, then search through likely
1155  * other locations.
1156  */
1157 static struct disklabel *
1158 find_label(int f, u_int sector)
1159 {
1160 	struct disklabel *disk_lp, hlp;
1161 	int i;
1162 	off_t offset;
1163 	const char *is_deleted;
1164 
1165 	bootarea_len = pread(f, bootarea, sizeof bootarea,
1166 	    sector * (off_t)DEV_BSIZE);
1167 	if (bootarea_len <= 0) {
1168 		if (verbose)
1169 			warn("failed to read bootarea from sector %u", sector);
1170 		return NULL;
1171 	}
1172 
1173 	if (verbose > 2)
1174 		warnx("read sector %u len %d looking for label",
1175 		    sector, bootarea_len);
1176 
1177 	/* Check expected offset first */
1178 	for (offset = LABEL_OFFSET, i = -4;; offset = i += 4) {
1179 		is_deleted = "";
1180 		disk_lp = (void *)(bootarea + offset);
1181 		if (i == LABEL_OFFSET)
1182 			continue;
1183 		if ((char *)(disk_lp + 1) > bootarea + bootarea_len)
1184 			break;
1185 		if (disk_lp->d_magic2 != disk_lp->d_magic)
1186 			continue;
1187 		if (read_all && (disk_lp->d_magic == DISKMAGIC_DELETED ||
1188 		    disk_lp->d_magic == DISKMAGIC_DELETED_REV)) {
1189 			disk_lp->d_magic ^= ~0u;
1190 			disk_lp->d_magic2 ^= ~0u;
1191 			is_deleted = "deleted ";
1192 		}
1193 		if (target32toh(disk_lp->d_magic) != DISKMAGIC) {
1194 			/* XXX: Do something about byte-swapped labels ? */
1195 			if (target32toh(disk_lp->d_magic) == DISKMAGIC_REV &&
1196 			    target32toh(disk_lp->d_magic2) == DISKMAGIC_REV)
1197 				warnx("ignoring %sbyteswapped label"
1198 				    " at offset %jd from sector %u",
1199 				    is_deleted, (intmax_t)offset, sector);
1200 			continue;
1201 		}
1202 		if (target16toh(disk_lp->d_npartitions) > maxpartitions ||
1203 		    dkcksum_target(disk_lp) != 0) {
1204 			if (verbose > 0)
1205 				warnx("corrupt label found at offset %jd in "
1206 				    "sector %u", (intmax_t)offset, sector);
1207 			continue;
1208 		}
1209 		if (verbose > 1)
1210 			warnx("%slabel found at offset %jd from sector %u",
1211 			    is_deleted, (intmax_t)offset, sector);
1212 		if (!read_all)
1213 			return disk_lp;
1214 
1215 		/* To print all the labels we have to do it here */
1216 		/* XXX: maybe we should compare them? */
1217 		targettohlabel(&hlp, disk_lp);
1218 		printf("# %ssector %u offset %jd bytes\n",
1219 		    is_deleted, sector, (intmax_t)offset);
1220 		if (tflag)
1221 			makedisktab(stdout, &hlp);
1222 		else {
1223 			showinfo(stdout, &hlp, specname);
1224 			showpartitions(stdout, &hlp, Cflag);
1225 		}
1226 		checklabel(&hlp);
1227 		htotargetlabel(disk_lp, &hlp);
1228 		/* Remember we've found a label */
1229 		read_all = 2;
1230 	}
1231 	return NULL;
1232 }
1233 
1234 static void
1235 write_bootarea(int f, u_int sector)
1236 {
1237 	int wlen;
1238 
1239 	if (bootarea_len <= 0)
1240 		errx(1, "attempting to write after failed read");
1241 
1242 #ifdef ALPHA_BOOTBLOCK_CKSUM
1243 	/*
1244 	 * The Alpha requires that the boot block be checksummed.
1245 	 * <sys/bootblock.h> provides a macro to do it.
1246 	 */
1247 	if (sector == 0) {
1248 		struct alpha_boot_block *bb;
1249 
1250 		bb = (struct alpha_boot_block *)(void *)bootarea;
1251 		bb->bb_cksum = 0;
1252 		ALPHA_BOOT_BLOCK_CKSUM(bb, &bb->bb_cksum);
1253 	}
1254 #endif	/* ALPHA_BOOTBLOCK_CKSUM */
1255 
1256 	wlen = pwrite(f, bootarea, bootarea_len, sector * (off_t)DEV_BSIZE);
1257 	if (wlen == bootarea_len)
1258 		return;
1259 	if (wlen == -1)
1260 		err(1, "disklabel write (sector %u) size %d failed",
1261 		    sector, bootarea_len);
1262 	errx(1, "disklabel write (sector %u) size %d truncated to %d",
1263 		    sector, bootarea_len, wlen);
1264 }
1265 
1266 static int
1267 update_label(int f, u_int label_sector, u_int label_offset)
1268 {
1269 	struct disklabel *disk_lp;
1270 
1271 	disk_lp = find_label(f, label_sector);
1272 
1273 	if (disk_lp && Dflag) {
1274 		/* Invalidate the existing label */
1275 		disk_lp->d_magic ^= ~0u;
1276 		disk_lp->d_magic2 ^= ~0u;
1277 		if (Dflag == 2)
1278 			write_bootarea(f, label_sector);
1279 		/* Force label to default location */
1280 		disk_lp = NULL;
1281 	}
1282 
1283 	if (Dflag == 2)
1284 		/* We are just deleting the label */
1285 		return 0;
1286 
1287 	if (disk_lp == NULL) {
1288 		if (label_offset == ~0u)
1289 			return 0;
1290 		/* Nothing on the disk - we need to add it */
1291 		disk_lp = (void *)(bootarea + label_offset);
1292 		if ((char *)(disk_lp + 1) > bootarea + bootarea_len)
1293 			errx(1, "no space in bootarea (sector %u) "
1294 			    "to create label", label_sector);
1295 	}
1296 
1297 	htotargetlabel(disk_lp, &lab);
1298 	write_bootarea(f, label_sector);
1299 	return 1;
1300 }
1301 
1302 static void
1303 writelabel_direct(int f)
1304 {
1305 	u_int label_sector;
1306 	int written = 0;
1307 	int rval;
1308 
1309 	label_sector = get_filecore_partition(f);
1310 	if (label_sector != 0)
1311 		/* The offset needs to be that from the acorn ports... */
1312 		written = update_label(f, label_sector, DEV_BSIZE);
1313 
1314 	rval = process_mbr(f, writelabel_mbr);
1315 
1316 	if (rval == 2 || written)
1317 		/* Don't add a label to sector 0, but update one if there */
1318 		update_label(f, 0, ~0u);
1319 	else
1320 		update_label(f, 0, LABEL_OFFSET);
1321 }
1322 
1323 static int
1324 readlabel_direct(int f)
1325 {
1326 	struct disklabel *disk_lp;
1327 	u_int filecore_partition_offset;
1328 
1329 	filecore_partition_offset = get_filecore_partition(f);
1330 	if (filecore_partition_offset != 0) {
1331 		disk_lp = find_label(f, filecore_partition_offset);
1332 		if (disk_lp != NULL) {
1333 			targettohlabel(&lab, disk_lp);
1334 			return 0;
1335 		}
1336 	}
1337 
1338 	if (mflag && process_mbr(f, readlabel_mbr) == 0)
1339 		return 0;
1340 
1341 	disk_lp = find_label(f, 0);
1342 	if (disk_lp != NULL) {
1343 		targettohlabel(&lab, disk_lp);
1344 		return 0;
1345 	}
1346 
1347 	if (!mflag && process_mbr(f, readlabel_mbr) == 0)
1348 		return 0;
1349 
1350 	return 1;
1351 }
1352 
1353 static void
1354 makedisktab(FILE *f, struct disklabel *lp)
1355 {
1356 	int	 i;
1357 	const char *did;
1358 	struct partition *pp;
1359 
1360 	did = "\\\n\t:";
1361 	(void) fprintf(f, "%.*s|Automatically generated label:\\\n\t:dt=",
1362 	    (int) sizeof(lp->d_typename), lp->d_typename);
1363 	if ((unsigned) lp->d_type < DKMAXTYPES)
1364 		(void) fprintf(f, "%s:", dktypenames[lp->d_type]);
1365 	else
1366 		(void) fprintf(f, "unknown%" PRIu16 ":", lp->d_type);
1367 
1368 	(void) fprintf(f, "se#%" PRIu32 ":", lp->d_secsize);
1369 	(void) fprintf(f, "ns#%" PRIu32 ":", lp->d_nsectors);
1370 	(void) fprintf(f, "nt#%" PRIu32 ":", lp->d_ntracks);
1371 	(void) fprintf(f, "sc#%" PRIu32 ":", lp->d_secpercyl);
1372 	(void) fprintf(f, "nc#%" PRIu32 ":", lp->d_ncylinders);
1373 
1374 	if ((lp->d_secpercyl * lp->d_ncylinders) != lp->d_secperunit) {
1375 		(void) fprintf(f, "%ssu#%" PRIu32 ":", did, lp->d_secperunit);
1376 		did = "";
1377 	}
1378 	if (lp->d_rpm != 3600) {
1379 		(void) fprintf(f, "%srm#%" PRIu16 ":", did, lp->d_rpm);
1380 		did = "";
1381 	}
1382 	if (lp->d_interleave != 1) {
1383 		(void) fprintf(f, "%sil#%" PRIu16 ":", did, lp->d_interleave);
1384 		did = "";
1385 	}
1386 	if (lp->d_trackskew != 0) {
1387 		(void) fprintf(f, "%ssk#%" PRIu16 ":", did, lp->d_trackskew);
1388 		did = "";
1389 	}
1390 	if (lp->d_cylskew != 0) {
1391 		(void) fprintf(f, "%scs#%" PRIu16 ":", did, lp->d_cylskew);
1392 		did = "";
1393 	}
1394 	if (lp->d_headswitch != 0) {
1395 		(void) fprintf(f, "%shs#%" PRIu32 ":", did, lp->d_headswitch);
1396 		did = "";
1397 	}
1398 	if (lp->d_trkseek != 0) {
1399 		(void) fprintf(f, "%sts#%" PRIu32 ":", did, lp->d_trkseek);
1400 		did = "";
1401 	}
1402 #ifdef notyet
1403 	(void) fprintf(f, "drivedata: ");
1404 	for (i = NDDATA - 1; i >= 0; i--)
1405 		if (lp->d_drivedata[i])
1406 			break;
1407 	if (i < 0)
1408 		i = 0;
1409 	for (j = 0; j <= i; j++)
1410 		(void) fprintf(f, "%" PRIu32 " ", lp->d_drivedata[j]);
1411 #endif	/* notyet */
1412 	pp = lp->d_partitions;
1413 	for (i = 0; i < lp->d_npartitions; i++, pp++) {
1414 		if (pp->p_size) {
1415 			char c = 'a' + i;
1416 			(void) fprintf(f, "\\\n\t:");
1417 			(void) fprintf(f, "p%c#%" PRIu32 ":", c, pp->p_size);
1418 			(void) fprintf(f, "o%c#%" PRIu32 ":", c, pp->p_offset);
1419 			if (pp->p_fstype != FS_UNUSED) {
1420 				if ((unsigned) pp->p_fstype < FSMAXTYPES)
1421 					(void) fprintf(f, "t%c=%s:", c,
1422 					    fstypenames[pp->p_fstype]);
1423 				else
1424 					(void) fprintf(f,
1425 					    "t%c=unknown%" PRIu8 ":",
1426 					    c, pp->p_fstype);
1427 			}
1428 			switch (pp->p_fstype) {
1429 
1430 			case FS_UNUSED:
1431 				break;
1432 
1433 			case FS_BSDFFS:
1434 			case FS_BSDLFS:
1435 			case FS_EX2FS:
1436 			case FS_ADOS:
1437 			case FS_APPLEUFS:
1438 				(void) fprintf(f, "b%c#%" PRIu64 ":", c,
1439 				    (uint64_t)pp->p_fsize * pp->p_frag);
1440 				(void) fprintf(f, "f%c#%" PRIu32 ":", c,
1441 				    pp->p_fsize);
1442 				break;
1443 			default:
1444 				break;
1445 			}
1446 		}
1447 	}
1448 	(void) fprintf(f, "\n");
1449 	(void) fflush(f);
1450 }
1451 
1452 static int
1453 edit(int f)
1454 {
1455 	const char *tmpdir;
1456 	char	tmpfil[MAXPATHLEN];
1457 	int	 first, ch, fd;
1458 	int	get_ok;
1459 	FILE	*fp;
1460 
1461 	if ((tmpdir = getenv("TMPDIR")) == NULL)
1462 		tmpdir = _PATH_TMP;
1463 	(void)snprintf(tmpfil, sizeof(tmpfil), "%s/%s", tmpdir, TMPFILE);
1464 	if ((fd = mkstemp(tmpfil)) == -1 || (fp = fdopen(fd, "w")) == NULL) {
1465 		warn("%s", tmpfil);
1466 		return (1);
1467 	}
1468 	(void)fchmod(fd, 0600);
1469 	showinfo(fp, &lab, specname);
1470 	showpartitions(fp, &lab, Cflag);
1471 	(void) fclose(fp);
1472 	for (;;) {
1473 		if (!editit(tmpfil))
1474 			break;
1475 		fp = fopen(tmpfil, "r");
1476 		if (fp == NULL) {
1477 			warn("%s", tmpfil);
1478 			break;
1479 		}
1480 		(void) memset(&lab, 0, sizeof(lab));
1481 		get_ok = getasciilabel(fp, &lab);
1482 		fclose(fp);
1483 		if (get_ok && write_label(f) == 0) {
1484 			(void) unlink(tmpfil);
1485 			return (0);
1486 		}
1487 		(void) printf("re-edit the label? [y]: ");
1488 		(void) fflush(stdout);
1489 		first = ch = getchar();
1490 		while (ch != '\n' && ch != EOF)
1491 			ch = getchar();
1492 		if (first == 'n' || first == 'N')
1493 			break;
1494 	}
1495 	(void)unlink(tmpfil);
1496 	return (1);
1497 }
1498 
1499 static int
1500 editit(const char *tmpfil)
1501 {
1502 	int pid, xpid;
1503 	int status;
1504 	sigset_t nsigset, osigset;
1505 
1506 	sigemptyset(&nsigset);
1507 	sigaddset(&nsigset, SIGINT);
1508 	sigaddset(&nsigset, SIGQUIT);
1509 	sigaddset(&nsigset, SIGHUP);
1510 	sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1511 	while ((pid = fork()) < 0) {
1512 		if (errno != EAGAIN) {
1513 			sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1514 			warn("fork");
1515 			return (0);
1516 		}
1517 		sleep(1);
1518 	}
1519 	if (pid == 0) {
1520 		const char *ed;
1521 		char *buf;
1522 		int retval;
1523 
1524 		sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1525 		setgid(getgid());
1526 		setuid(getuid());
1527 		if ((ed = getenv("EDITOR")) == (char *)0)
1528 			ed = DEFEDITOR;
1529 		/*
1530 		 * Jump through a few extra hoops in case someone's editor
1531 		 * is "editor arg1 arg2".
1532 		 */
1533 		asprintf(&buf, "%s %s", ed, tmpfil);
1534 		if (!buf)
1535 			err(1, "malloc");
1536 		retval = execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", buf, NULL);
1537 		if (retval == -1)
1538 			perror(ed);
1539 		exit(retval);
1540 	}
1541 	while ((xpid = wait(&status)) >= 0)
1542 		if (xpid == pid)
1543 			break;
1544 	sigprocmask(SIG_SETMASK, &osigset, (sigset_t *)0);
1545 	return (!status);
1546 }
1547 
1548 static char *
1549 skip(char *cp)
1550 {
1551 
1552 	cp += strspn(cp, " \t");
1553 	if (*cp == '\0')
1554 		return (NULL);
1555 	return (cp);
1556 }
1557 
1558 static char *
1559 word(char *cp)
1560 {
1561 
1562 	if (cp == NULL || *cp == '\0')
1563 		return (NULL);
1564 
1565 	cp += strcspn(cp, " \t");
1566 	if (*cp == '\0')
1567 		return (NULL);
1568 	*cp++ = '\0';
1569 	cp += strspn(cp, " \t");
1570 	if (*cp == '\0')
1571 		return (NULL);
1572 	return (cp);
1573 }
1574 
1575 #define _CHECKLINE \
1576 	if (tp == NULL || *tp == '\0') {			\
1577 		warnx("line %d: too few fields", lineno);	\
1578 		errors++;					\
1579 		break;						\
1580 	}
1581 
1582 #define __CHECKLINE \
1583 	if (*tp == NULL || **tp == '\0') {			\
1584 		warnx("line %d: too few fields", lineno);	\
1585 		*tp = _error_;					\
1586 		return 0;					\
1587 	}
1588 
1589 static char _error_[] = "";
1590 #define NXTNUM(n)	if ((n = nxtnum(&tp, lineno),0) + tp != _error_) \
1591 			; else goto error
1592 #define NXTXNUM(n)	if ((n = nxtxnum(&tp, lp, lineno),0) + tp != _error_) \
1593 			; else goto error
1594 
1595 static unsigned long
1596 nxtnum(char **tp, int lineno)
1597 {
1598 	char *cp;
1599 	unsigned long v;
1600 
1601 	__CHECKLINE
1602 	if (getulong(*tp, '\0', &cp, &v, UINT32_MAX) != 0) {
1603 		warnx("line %d: syntax error", lineno);
1604 		*tp = _error_;
1605 		return 0;
1606 	}
1607 	*tp = cp;
1608 	return v;
1609 }
1610 
1611 static unsigned long
1612 nxtxnum(char **tp, struct disklabel *lp, int lineno)
1613 {
1614 	char	*cp, *ncp;
1615 	unsigned long n, v;
1616 
1617 	__CHECKLINE
1618 	cp = *tp;
1619 	if (getulong(cp, '/', &ncp, &n, UINT32_MAX) != 0)
1620 		goto bad;
1621 
1622 	if (*ncp == '/') {
1623 		n *= lp->d_secpercyl;
1624 		cp = ncp + 1;
1625 		if (getulong(cp, '/', &ncp, &v, UINT32_MAX) != 0)
1626 			goto bad;
1627 		n += v * lp->d_nsectors;
1628 		cp = ncp + 1;
1629 		if (getulong(cp, '\0', &ncp, &v, UINT32_MAX) != 0)
1630 			goto bad;
1631 		n += v;
1632 	}
1633 	*tp = ncp;
1634 	return n;
1635 bad:
1636 	warnx("line %d: invalid format", lineno);
1637 	*tp = _error_;
1638 	return 0;
1639 }
1640 
1641 /*
1642  * Read an ascii label in from fd f,
1643  * in the same format as that put out by showinfo() and showpartitions(),
1644  * and fill in lp.
1645  */
1646 static int
1647 getasciilabel(FILE *f, struct disklabel *lp)
1648 {
1649 	const char *const *cpp, *s;
1650 	struct partition *pp;
1651 	char	*cp, *tp, line[BUFSIZ], tbuf[15];
1652 	int	 lineno, errors;
1653 	unsigned long v;
1654 	unsigned int part;
1655 
1656 	lineno = 0;
1657 	errors = 0;
1658 	lp->d_bbsize = BBSIZE;				/* XXX */
1659 	lp->d_sbsize = SBLOCKSIZE;			/* XXX */
1660 	while (fgets(line, sizeof(line) - 1, f)) {
1661 		lineno++;
1662 		if ((cp = strpbrk(line, "#\r\n")) != NULL)
1663 			*cp = '\0';
1664 		cp = skip(line);
1665 		if (cp == NULL)     /* blank line or comment line */
1666 			continue;
1667 		tp = strchr(cp, ':'); /* everything has a colon in it */
1668 		if (tp == NULL) {
1669 			warnx("line %d: syntax error", lineno);
1670 			errors++;
1671 			continue;
1672 		}
1673 		*tp++ = '\0', tp = skip(tp);
1674 		if (!strcmp(cp, "type")) {
1675 			if (tp == NULL) {
1676 				strlcpy(tbuf, "unknown", sizeof(tbuf));
1677 				tp = tbuf;
1678 			}
1679 			cpp = dktypenames;
1680 			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
1681 				if ((s = *cpp) && !strcasecmp(s, tp)) {
1682 					lp->d_type = cpp - dktypenames;
1683 					goto next;
1684 				}
1685 			if (GETNUM16(tp, &v) != 0) {
1686 				warnx("line %d: syntax error", lineno);
1687 				errors++;
1688 				continue;
1689 			}
1690 			if (v >= DKMAXTYPES)
1691 				warnx("line %d: warning, unknown disk type: %s",
1692 				    lineno, tp);
1693 			lp->d_type = v;
1694 			continue;
1695 		}
1696 		if (!strcmp(cp, "flags")) {
1697 			for (v = 0; (cp = tp) && *cp != '\0';) {
1698 				tp = word(cp);
1699 				if (!strcasecmp(cp, "removable"))
1700 					v |= D_REMOVABLE;
1701 				else if (!strcasecmp(cp, "ecc"))
1702 					v |= D_ECC;
1703 				else if (!strcasecmp(cp, "badsect"))
1704 					v |= D_BADSECT;
1705 				else {
1706 					warnx("line %d: bad flag: %s",
1707 					    lineno, cp);
1708 					errors++;
1709 				}
1710 			}
1711 			lp->d_flags = v;
1712 			continue;
1713 		}
1714 		if (!strcmp(cp, "drivedata")) {
1715 			int i;
1716 
1717 			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
1718 				if (GETNUM32(cp, &v) != 0) {
1719 					warnx("line %d: bad drive data",
1720 					    lineno);
1721 					errors++;
1722 				} else
1723 					lp->d_drivedata[i] = v;
1724 				i++;
1725 				tp = word(cp);
1726 			}
1727 			continue;
1728 		}
1729 		if (sscanf(cp, "%lu partitions", &v) == 1) {
1730 			if (v == 0 || v > maxpartitions) {
1731 				warnx("line %d: bad # of partitions", lineno);
1732 				lp->d_npartitions = maxpartitions;
1733 				errors++;
1734 			} else
1735 				lp->d_npartitions = v;
1736 			continue;
1737 		}
1738 		if (tp == NULL) {
1739 			tbuf[0] = '\0';
1740 			tp = tbuf;
1741 		}
1742 		if (!strcmp(cp, "disk")) {
1743 			strncpy(lp->d_typename, tp, sizeof(lp->d_typename));
1744 			continue;
1745 		}
1746 		if (!strcmp(cp, "label")) {
1747 			strncpy(lp->d_packname, tp, sizeof(lp->d_packname));
1748 			continue;
1749 		}
1750 		if (!strcmp(cp, "bytes/sector")) {
1751 			if (GETNUM32(tp, &v) != 0 || v <= 0 || (v % 512) != 0) {
1752 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1753 				errors++;
1754 			} else
1755 				lp->d_secsize = v;
1756 			continue;
1757 		}
1758 		if (!strcmp(cp, "sectors/track")) {
1759 			if (GETNUM32(tp, &v) != 0) {
1760 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1761 				errors++;
1762 			} else
1763 				lp->d_nsectors = v;
1764 			continue;
1765 		}
1766 		if (!strcmp(cp, "sectors/cylinder")) {
1767 			if (GETNUM32(tp, &v) != 0) {
1768 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1769 				errors++;
1770 			} else
1771 				lp->d_secpercyl = v;
1772 			continue;
1773 		}
1774 		if (!strcmp(cp, "tracks/cylinder")) {
1775 			if (GETNUM32(tp, &v) != 0) {
1776 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1777 				errors++;
1778 			} else
1779 				lp->d_ntracks = v;
1780 			continue;
1781 		}
1782 		if (!strcmp(cp, "cylinders")) {
1783 			if (GETNUM32(tp, &v) != 0) {
1784 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1785 				errors++;
1786 			} else
1787 				lp->d_ncylinders = v;
1788 			continue;
1789 		}
1790 		if (!strcmp(cp, "total sectors") ||
1791 		    !strcmp(cp, "sectors/unit")) {
1792 			if (GETNUM32(tp, &v) != 0) {
1793 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1794 				errors++;
1795 			} else
1796 				lp->d_secperunit = v;
1797 			continue;
1798 		}
1799 		if (!strcmp(cp, "rpm")) {
1800 			if (GETNUM16(tp, &v) != 0) {
1801 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1802 				errors++;
1803 			} else
1804 				lp->d_rpm = v;
1805 			continue;
1806 		}
1807 		if (!strcmp(cp, "interleave")) {
1808 			if (GETNUM16(tp, &v) != 0) {
1809 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1810 				errors++;
1811 			} else
1812 				lp->d_interleave = v;
1813 			continue;
1814 		}
1815 		if (!strcmp(cp, "trackskew")) {
1816 			if (GETNUM16(tp, &v) != 0) {
1817 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1818 				errors++;
1819 			} else
1820 				lp->d_trackskew = v;
1821 			continue;
1822 		}
1823 		if (!strcmp(cp, "cylinderskew")) {
1824 			if (GETNUM16(tp, &v) != 0) {
1825 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1826 				errors++;
1827 			} else
1828 				lp->d_cylskew = v;
1829 			continue;
1830 		}
1831 		if (!strcmp(cp, "headswitch")) {
1832 			if (GETNUM32(tp, &v) != 0) {
1833 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1834 				errors++;
1835 			} else
1836 				lp->d_headswitch = v;
1837 			continue;
1838 		}
1839 		if (!strcmp(cp, "track-to-track seek")) {
1840 			if (GETNUM32(tp, &v) != 0) {
1841 				warnx("line %d: bad %s: %s", lineno, cp, tp);
1842 				errors++;
1843 			} else
1844 				lp->d_trkseek = v;
1845 			continue;
1846 		}
1847 		if ('a' > *cp || *cp > 'z' || cp[1] != '\0') {
1848 			warnx("line %d: unknown field: %s", lineno, cp);
1849 			errors++;
1850 			continue;
1851 		}
1852 
1853 		/* We have a partition entry */
1854 		part = *cp - 'a';
1855 
1856 		if (part >= maxpartitions) {
1857 			warnx("line %d: bad partition name: %s", lineno, cp);
1858 			errors++;
1859 			continue;
1860 		}
1861 		if (part >= __arraycount(lp->d_partitions)) {
1862 			warnx("line %d: partition id %s, >= %zu", lineno,
1863 			    cp, __arraycount(lp->d_partitions));
1864 			errors++;
1865 			continue;
1866 		}
1867 		pp = &lp->d_partitions[part];
1868 
1869 		NXTXNUM(pp->p_size);
1870 		NXTXNUM(pp->p_offset);
1871 		/* can't use word() here because of blanks in fstypenames[] */
1872 		tp += strspn(tp, " \t");
1873 		_CHECKLINE
1874 		cp = tp;
1875 		cpp = fstypenames;
1876 		for (; cpp < &fstypenames[FSMAXTYPES]; cpp++) {
1877 			s = *cpp;
1878 			if (s == NULL ||
1879 				(cp[strlen(s)] != ' ' &&
1880 				 cp[strlen(s)] != '\t' &&
1881 				 cp[strlen(s)] != '\0'))
1882 				continue;
1883 			if (!memcmp(s, cp, strlen(s))) {
1884 				pp->p_fstype = cpp - fstypenames;
1885 				tp += strlen(s);
1886 				if (*tp == '\0')
1887 					tp = NULL;
1888 				else {
1889 					tp += strspn(tp, " \t");
1890 					if (*tp == '\0')
1891 						tp = NULL;
1892 				}
1893 				goto gottype;
1894 			}
1895 		}
1896 		tp = word(cp);
1897 		if (isdigit(*cp & 0xff)) {
1898 			if (GETNUM8(cp, &v) != 0) {
1899 				warnx("line %d: syntax error", lineno);
1900 				errors++;
1901 			}
1902 		} else
1903 			v = FSMAXTYPES;
1904 		if ((unsigned)v >= FSMAXTYPES) {
1905 			warnx("line %d: warning, unknown file system type: %s",
1906 			    lineno, cp);
1907 			warnx("tip: use -l to see all valid file system "
1908 			    "types");
1909 			v = FS_UNUSED;
1910 		}
1911 		pp->p_fstype = v;
1912 gottype:
1913 		switch (pp->p_fstype) {
1914 
1915 		case FS_UNUSED:				/* XXX */
1916 			NXTNUM(pp->p_fsize);
1917 			if (pp->p_fsize == 0)
1918 				break;
1919 			NXTNUM(v);
1920 			pp->p_frag = v / pp->p_fsize;
1921 			break;
1922 
1923 		case FS_BSDFFS:
1924 		case FS_ADOS:
1925 		case FS_APPLEUFS:
1926 			NXTNUM(pp->p_fsize);
1927 			if (pp->p_fsize == 0)
1928 				break;
1929 			NXTNUM(v);
1930 			pp->p_frag = v / pp->p_fsize;
1931 			NXTNUM(pp->p_cpg);
1932 			break;
1933 		case FS_BSDLFS:
1934 			NXTNUM(pp->p_fsize);
1935 			if (pp->p_fsize == 0)
1936 				break;
1937 			NXTNUM(v);
1938 			pp->p_frag = v / pp->p_fsize;
1939 			NXTNUM(pp->p_sgs);
1940 			break;
1941 		case FS_EX2FS:
1942 			NXTNUM(pp->p_fsize);
1943 			if (pp->p_fsize == 0)
1944 				break;
1945 			NXTNUM(v);
1946 			pp->p_frag = v / pp->p_fsize;
1947 			break;
1948 		case FS_ISO9660:
1949 			NXTNUM(pp->p_cdsession);
1950 			break;
1951 		default:
1952 			break;
1953 		}
1954 		continue;
1955  error:
1956 		errors++;
1957  next:
1958 		;
1959 	}
1960 	errors += checklabel(lp);
1961 	return (errors == 0);
1962 }
1963 
1964 /*
1965  * Check disklabel for errors and fill in
1966  * derived fields according to supplied values.
1967  */
1968 int
1969 checklabel(struct disklabel *lp)
1970 {
1971 	struct partition *pp, *qp;
1972 	int	i, j, errors;
1973 	char	part;
1974 
1975 	errors = 0;
1976 	if (lp->d_secsize == 0) {
1977 		warnx("sector size %" PRIu32, lp->d_secsize);
1978 		return (1);
1979 	}
1980 	if (lp->d_nsectors == 0) {
1981 		warnx("sectors/track %" PRIu32, lp->d_nsectors);
1982 		return (1);
1983 	}
1984 	if (lp->d_ntracks == 0) {
1985 		warnx("tracks/cylinder %" PRIu32, lp->d_ntracks);
1986 		return (1);
1987 	}
1988 	if  (lp->d_ncylinders == 0) {
1989 		warnx("cylinders/unit %" PRIu32, lp->d_ncylinders);
1990 		errors++;
1991 	}
1992 	if (lp->d_rpm == 0)
1993 		warnx("warning, revolutions/minute %" PRIu16, lp->d_rpm);
1994 	if (lp->d_secpercyl == 0)
1995 		lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1996 	if (lp->d_secperunit == 0)
1997 		lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1998 	if (lp->d_bbsize == 0) {
1999 		warnx("boot block size %" PRIu32, lp->d_bbsize);
2000 		errors++;
2001 	} else if (lp->d_bbsize % lp->d_secsize)
2002 		warnx("warning, boot block size %% sector-size != 0");
2003 	if (lp->d_sbsize == 0) {
2004 		warnx("super block size %" PRIu32, lp->d_sbsize);
2005 		errors++;
2006 	} else if (lp->d_sbsize % lp->d_secsize)
2007 		warnx("warning, super block size %% sector-size != 0");
2008 	if (lp->d_npartitions > maxpartitions)
2009 		warnx("warning, number of partitions (%" PRIu16 ") > "
2010 		    "MAXPARTITIONS (%d)",
2011 		    lp->d_npartitions, maxpartitions);
2012 	else
2013 		for (i = maxpartitions - 1; i >= lp->d_npartitions; i--) {
2014 			part = 'a' + i;
2015 			pp = &lp->d_partitions[i];
2016 			if (pp->p_size || pp->p_offset) {
2017 				warnx("warning, partition %c increased "
2018 				    "number of partitions from %" PRIu16
2019 				    " to %d",
2020 				    part, lp->d_npartitions, i + 1);
2021 				lp->d_npartitions = i + 1;
2022 				break;
2023 			}
2024 		}
2025 	for (i = 0; i < lp->d_npartitions; i++) {
2026 		part = 'a' + i;
2027 		pp = &lp->d_partitions[i];
2028 		if (pp->p_size == 0 && pp->p_offset != 0)
2029 			warnx("warning, partition %c: size 0, but "
2030 			    "offset %" PRIu32,
2031 			    part, pp->p_offset);
2032 #ifdef STRICT_CYLINDER_ALIGNMENT
2033 		if (pp->p_offset % lp->d_secpercyl) {
2034 			warnx("warning, partition %c:"
2035 			    " not starting on cylinder boundary",
2036 			    part);
2037 			errors++;
2038 		}
2039 #endif	/* STRICT_CYLINDER_ALIGNMENT */
2040 		if (pp->p_offset > lp->d_secperunit) {
2041 			warnx("partition %c: offset past end of unit", part);
2042 			errors++;
2043 		}
2044 		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
2045 			warnx("partition %c: partition extends"
2046 			    " past end of unit",
2047 			    part);
2048 			errors++;
2049 		}
2050 		if (pp->p_fstype != FS_UNUSED)
2051 			for (j = i + 1; j < lp->d_npartitions; j++) {
2052 				qp = &lp->d_partitions[j];
2053 				if (qp->p_fstype == FS_UNUSED)
2054 					continue;
2055 				if (pp->p_offset < qp->p_offset + qp->p_size &&
2056 				    qp->p_offset < pp->p_offset + pp->p_size)
2057 					warnx("partitions %c and %c overlap",
2058 					    part, 'a' + j);
2059 			}
2060 	}
2061 	return (errors);
2062 }
2063 
2064 static void
2065 usage(void)
2066 {
2067 	static const struct {
2068 		const char *name;
2069 		const char *expn;
2070 	} usages[] = {
2071 	{ "[-ABCFMrtv] disk", "(to read label)" },
2072 	{ "-w [-BDFMrv] [-f disktab] disk disktype [packid]", "(to write label)" },
2073 	{ "-e [-BCDFMIrv] disk", "(to edit label)" },
2074 	{ "-i [-BDFMIrv] disk", "(to create a label interactively)" },
2075 	{ "-D [-v] disk", "(to delete existing label(s))" },
2076 	{ "-R [-BDFMrv] disk protofile", "(to restore label)" },
2077 	{ "[-NW] disk", "(to write disable/enable label)" },
2078 	{ "-l", "(to show all known file system types)" },
2079 	{ NULL, NULL }
2080 	};
2081 	int i;
2082 	const char *pn = getprogname();
2083 	const char *t = "usage:";
2084 
2085 	for (i = 0; usages[i].name != NULL; i++) {
2086 		(void)fprintf(stderr, "%s %s %s\n\t%s\n",
2087 		    t, pn, usages[i].name, usages[i].expn);
2088 		t = "or";
2089 	}
2090 	exit(1);
2091 }
2092 
2093 static int
2094 getulong(const char *str, char sep, char **epp, unsigned long *ul,
2095     unsigned long max)
2096 {
2097 	char *ep;
2098 
2099 	if (epp == NULL)
2100 		epp = &ep;
2101 
2102 	*ul = strtoul(str, epp, 10);
2103 
2104 	if ((*ul ==  ULONG_MAX && errno == ERANGE) || *ul > max)
2105 		return ERANGE;
2106 
2107 	if (*str == '\0' || (**epp != '\0' && **epp != sep &&
2108 	    !isspace((unsigned char)**epp)))
2109 		return EFTYPE;
2110 
2111 	return 0;
2112 }
2113 
2114 /*
2115  * This is a wrapper over the standard strcmp function to be used with
2116  * qsort on an array of pointers to strings.
2117  */
2118 static int
2119 qsort_strcmp(const void *v1, const void *v2)
2120 {
2121 	const char *const *sp1 = (const char *const *)v1;
2122 	const char *const *sp2 = (const char *const *)v2;
2123 
2124 	return strcmp(*sp1, *sp2);
2125 }
2126 
2127 /*
2128  * Prints all know file system types for a partition.
2129  * Returns 1 on success, 0 on failure.
2130  */
2131 int
2132 list_fs_types(void)
2133 {
2134 	int ret;
2135 	size_t nelems;
2136 
2137 	nelems = 0;
2138 	{
2139 		const char *const *namep;
2140 
2141 		namep = fstypenames;
2142 		while (*namep++ != NULL)
2143 			nelems++;
2144 	}
2145 
2146 	ret = 1;
2147 	if (nelems > 0) {
2148 		const char **list;
2149 		size_t i;
2150 
2151 		list = (const char **)malloc(sizeof(char *) * nelems);
2152 		if (list == NULL) {
2153 			warnx("sorry, could not allocate memory for list");
2154 			ret = 0;
2155 		} else {
2156 			for (i = 0; i < nelems; i++)
2157 				list[i] = fstypenames[i];
2158 
2159 			qsort(list, nelems, sizeof(char *), qsort_strcmp);
2160 
2161 			for (i = 0; i < nelems; i++)
2162 				(void)printf("%s\n", list[i]);
2163 
2164 			free(list);
2165 		}
2166 	}
2167 
2168 	return ret;
2169 }
2170 
2171 #ifndef HAVE_NBTOOL_CONFIG_H
2172 int
2173 dk_ioctl(int f, u_long cmd, void *arg)
2174 {
2175 	if (!native_p) {
2176 		errno = ENOTTY;
2177 		return -1;
2178 	}
2179 	return ioctl(f, cmd, arg);
2180 }
2181 #endif
2182