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