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