bsdlabel.c revision 36632
1/*
2 * Copyright (c) 1987, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Symmetric Computer Systems.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1987, 1993\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44#if 0
45static char sccsid[] = "@(#)disklabel.c	8.2 (Berkeley) 1/7/94";
46/* from static char sccsid[] = "@(#)disklabel.c	1.2 (Symmetric) 11/28/85"; */
47#endif
48static const char rcsid[] =
49	"$Id$";
50#endif /* not lint */
51
52#include <sys/param.h>
53#include <sys/errno.h>
54#include <sys/file.h>
55#include <sys/stat.h>
56#include <sys/wait.h>
57#define DKTYPENAMES
58#include <sys/disklabel.h>
59#include <ufs/ffs/fs.h>
60#include <unistd.h>
61#include <string.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <signal.h>
65#include <stdarg.h>
66#include <ctype.h>
67#include <err.h>
68#include "pathnames.h"
69
70/*
71 * Disklabel: read and write disklabels.
72 * The label is usually placed on one of the first sectors of the disk.
73 * Many machines also place a bootstrap in the same area,
74 * in which case the label is embedded in the bootstrap.
75 * The bootstrap source must leave space at the proper offset
76 * for the label on such machines.
77 */
78
79#ifdef tahoe
80#define RAWPARTITION	'a'
81#else
82#define RAWPARTITION	'c'
83#endif
84
85#ifndef BBSIZE
86#define	BBSIZE	8192			/* size of boot area, with label */
87#endif
88
89#ifdef tahoe
90#define	NUMBOOT	0
91#else
92#if defined(hp300) || defined(hp800)
93#define	NUMBOOT	1
94#else
95#define	NUMBOOT	2
96#endif
97#endif
98
99void	makelabel	__P((char *, char *, struct disklabel *));
100int	writelabel	__P((int, char *, struct disklabel *));
101void	l_perror	__P((char *));
102struct disklabel * readlabel __P((int));
103struct disklabel * makebootarea __P((char *, struct disklabel *, int));
104void	display		__P((FILE *, struct disklabel *));
105int	edit		__P((struct disklabel *, int));
106int	editit		__P((void));
107char *	skip		__P((char *));
108char *	word		__P((char *));
109int	getasciilabel	__P((FILE *, struct disklabel *));
110int	checklabel	__P((struct disklabel *));
111void	setbootflag	__P((struct disklabel *));
112void	Warning		(char *, ...);
113void	usage		__P((void));
114extern	u_short dkcksum __P((struct disklabel *));
115struct disklabel * getvirginlabel __P((void));
116
117#define	DEFEDITOR	_PATH_VI
118#define	streq(a,b)	(strcmp(a,b) == 0)
119
120char	*dkname;
121char	*specname;
122char	tmpfil[] = _PATH_TMP;
123
124char	namebuf[BBSIZE], *np = namebuf;
125struct	disklabel lab;
126struct	disklabel *readlabel(), *makebootarea();
127char	bootarea[BBSIZE];
128
129#if NUMBOOT > 0
130int	installboot;	/* non-zero if we should install a boot program */
131char	*bootbuf;	/* pointer to buffer with remainder of boot prog */
132int	bootsize;	/* size of remaining boot program */
133char	*xxboot;	/* primary boot */
134char	*bootxx;	/* secondary boot */
135char	boot0[MAXPATHLEN];
136char	boot1[MAXPATHLEN];
137#endif
138
139enum	{
140	UNSPEC, EDIT, NOWRITE, READ, RESTORE, WRITE, WRITEABLE, WRITEBOOT
141} op = UNSPEC;
142
143int	rflag;
144
145#ifdef DEBUG
146int	debug;
147#define OPTIONS	"BNRWb:ders:w"
148#else
149#define OPTIONS	"BNRWb:ers:w"
150#endif
151
152int
153main(argc, argv)
154	int argc;
155	char *argv[];
156{
157	register struct disklabel *lp;
158	FILE *t;
159	int ch, f, flag, error = 0;
160	char *name = 0;
161
162	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
163		switch (ch) {
164#if NUMBOOT > 0
165			case 'B':
166				++installboot;
167				break;
168			case 'b':
169				xxboot = optarg;
170				break;
171#if NUMBOOT > 1
172			case 's':
173				bootxx = optarg;
174				break;
175#endif
176#endif
177			case 'N':
178				if (op != UNSPEC)
179					usage();
180				op = NOWRITE;
181				break;
182			case 'R':
183				if (op != UNSPEC)
184					usage();
185				op = RESTORE;
186				break;
187			case 'W':
188				if (op != UNSPEC)
189					usage();
190				op = WRITEABLE;
191				break;
192			case 'e':
193				if (op != UNSPEC)
194					usage();
195				op = EDIT;
196				break;
197			case 'r':
198				++rflag;
199				break;
200			case 'w':
201				if (op != UNSPEC)
202					usage();
203				op = WRITE;
204				break;
205#ifdef DEBUG
206			case 'd':
207				debug++;
208				break;
209#endif
210			case '?':
211			default:
212				usage();
213		}
214	argc -= optind;
215	argv += optind;
216#if NUMBOOT > 0
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#else
227	if (op == UNSPEC)
228		op = READ;
229#endif
230	if (argc < 1)
231		usage();
232
233	dkname = argv[0];
234	if (dkname[0] != '/') {
235		(void)sprintf(np, "%sr%s%c", _PATH_DEV, dkname, RAWPARTITION);
236		specname = np;
237		np += strlen(specname) + 1;
238	} else
239		specname = dkname;
240	f = open(specname, op == READ ? O_RDONLY : O_RDWR);
241	if (f < 0 && errno == ENOENT && dkname[0] != '/') {
242		(void)sprintf(specname, "%sr%s", _PATH_DEV, dkname);
243		np = namebuf + strlen(specname) + 1;
244		f = open(specname, op == READ ? O_RDONLY : O_RDWR);
245	}
246	if (f < 0)
247		err(4, "%s", specname);
248
249	switch(op) {
250
251	case UNSPEC:
252		break;
253
254	case EDIT:
255		if (argc != 1)
256			usage();
257		lp = readlabel(f);
258		error = edit(lp, f);
259		break;
260
261	case NOWRITE:
262		flag = 0;
263		if (ioctl(f, DIOCWLABEL, (char *)&flag) < 0)
264			err(4, "ioctl DIOCWLABEL");
265		break;
266
267	case READ:
268		if (argc != 1)
269			usage();
270		lp = readlabel(f);
271		display(stdout, lp);
272		error = checklabel(lp);
273		break;
274
275	case RESTORE:
276#if NUMBOOT > 0
277		if (installboot && argc == 3) {
278			makelabel(argv[2], 0, &lab);
279			argc--;
280		}
281#endif
282		if (argc != 2)
283			usage();
284		lp = makebootarea(bootarea, &lab, f);
285		if (!(t = fopen(argv[1], "r")))
286			err(4, "%s", argv[1]);
287		if (getasciilabel(t, lp))
288			error = writelabel(f, bootarea, lp);
289		break;
290
291	case WRITE:
292		if (argc == 3) {
293			name = argv[2];
294			argc--;
295		}
296		if (argc != 2)
297			usage();
298		makelabel(argv[1], name, &lab);
299		lp = makebootarea(bootarea, &lab, f);
300		*lp = lab;
301		if (checklabel(lp) == 0)
302			error = writelabel(f, bootarea, lp);
303		break;
304
305	case WRITEABLE:
306		flag = 1;
307		if (ioctl(f, DIOCWLABEL, (char *)&flag) < 0)
308			err(4, "ioctl DIOCWLABEL");
309		break;
310
311#if NUMBOOT > 0
312	case WRITEBOOT:
313	{
314		struct disklabel tlab;
315
316		lp = readlabel(f);
317		tlab = *lp;
318		if (argc == 2)
319			makelabel(argv[1], 0, &lab);
320		lp = makebootarea(bootarea, &lab, f);
321		*lp = tlab;
322		if (checklabel(lp) == 0)
323			error = writelabel(f, bootarea, lp);
324		break;
325	}
326#endif
327	}
328	exit(error);
329}
330
331/*
332 * Construct a prototype disklabel from /etc/disktab.  As a side
333 * effect, set the names of the primary and secondary boot files
334 * if specified.
335 */
336void
337makelabel(type, name, lp)
338	char *type, *name;
339	register struct disklabel *lp;
340{
341	register struct disklabel *dp;
342
343	if (strcmp(type, "auto") == 0)
344		dp = getvirginlabel();
345	else
346		dp = getdiskbyname(type);
347	if (dp == NULL)
348		errx(1, "%s: unknown disk type", type);
349	*lp = *dp;
350#if NUMBOOT > 0
351	/*
352	 * Set bootstrap name(s).
353	 * 1. If set from command line, use those,
354	 * 2. otherwise, check if disktab specifies them (b0 or b1),
355	 * 3. otherwise, makebootarea() will choose ones based on the name
356	 *    of the disk special file. E.g. /dev/ra0 -> raboot, bootra
357	 */
358	if (!xxboot && lp->d_boot0) {
359		if (*lp->d_boot0 != '/')
360			(void)sprintf(boot0, "%s/%s",
361				      _PATH_BOOTDIR, lp->d_boot0);
362		else
363			(void)strcpy(boot0, lp->d_boot0);
364		xxboot = boot0;
365	}
366#if NUMBOOT > 1
367	if (!bootxx && lp->d_boot1) {
368		if (*lp->d_boot1 != '/')
369			(void)sprintf(boot1, "%s/%s",
370				      _PATH_BOOTDIR, lp->d_boot1);
371		else
372			(void)strcpy(boot1, lp->d_boot1);
373		bootxx = boot1;
374	}
375#endif
376#endif
377	/* d_packname is union d_boot[01], so zero */
378	bzero(lp->d_packname, sizeof(lp->d_packname));
379	if (name)
380		(void)strncpy(lp->d_packname, name, sizeof(lp->d_packname));
381}
382
383int
384writelabel(f, boot, lp)
385	int f;
386	char *boot;
387	register struct disklabel *lp;
388{
389#ifdef vax
390	register int i;
391#endif
392	int flag;
393
394	setbootflag(lp);
395	lp->d_magic = DISKMAGIC;
396	lp->d_magic2 = DISKMAGIC;
397	lp->d_checksum = 0;
398	lp->d_checksum = dkcksum(lp);
399	if (rflag) {
400		/*
401		 * First set the kernel disk label,
402		 * then write a label to the raw disk.
403		 * If the SDINFO ioctl fails because it is unimplemented,
404		 * keep going; otherwise, the kernel consistency checks
405		 * may prevent us from changing the current (in-core)
406		 * label.
407		 */
408		if (ioctl(f, DIOCSDINFO, lp) < 0 &&
409		    errno != ENODEV && errno != ENOTTY) {
410			l_perror("ioctl DIOCSDINFO");
411			return (1);
412		}
413		(void)lseek(f, (off_t)0, SEEK_SET);
414		/*
415		 * write enable label sector before write (if necessary),
416		 * disable after writing.
417		 */
418		flag = 1;
419		if (ioctl(f, DIOCWLABEL, &flag) < 0)
420			warn("ioctl DIOCWLABEL");
421		if (write(f, boot, lp->d_bbsize) != lp->d_bbsize) {
422			warn("write");
423			return (1);
424		}
425#if NUMBOOT > 0
426		/*
427		 * Output the remainder of the disklabel
428		 */
429		if (bootbuf && write(f, bootbuf, bootsize) != bootsize) {
430			warn("write");
431			return(1);
432		}
433#endif
434		flag = 0;
435		(void) ioctl(f, DIOCWLABEL, &flag);
436	} else if (ioctl(f, DIOCWDINFO, lp) < 0) {
437		l_perror("ioctl DIOCWDINFO");
438		return (1);
439	}
440#ifdef vax
441	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
442		daddr_t alt;
443
444		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
445		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
446			(void)lseek(f, (off_t)((alt + i) * lp->d_secsize),
447			    SEEK_SET);
448			if (write(f, boot, lp->d_secsize) < lp->d_secsize)
449				warn("alternate label %d write", i/2);
450		}
451	}
452#endif
453	return (0);
454}
455
456void
457l_perror(s)
458	char *s;
459{
460	switch (errno) {
461
462	case ESRCH:
463		warnx("%s: no disk label on disk;\n"
464		      "use \"disklabel -r\" to install initial label", s);
465		break;
466
467	case EINVAL:
468		warnx("%s: label magic number or checksum is wrong!\n"
469		      "(disklabel or kernel is out of date?)", s);
470		break;
471
472	case EBUSY:
473		warnx("%s: open partition would move or shrink", s);
474		break;
475
476	case EXDEV:
477		warnx(
478  "%s: labeled partition or 'a' partition must start at beginning of disk", s);
479		break;
480
481	default:
482		warn((char *)NULL);
483		break;
484	}
485}
486
487/*
488 * Fetch disklabel for disk.
489 * Use ioctl to get label unless -r flag is given.
490 */
491struct disklabel *
492readlabel(f)
493	int f;
494{
495	register struct disklabel *lp;
496
497	if (rflag) {
498		if (read(f, bootarea, BBSIZE) < BBSIZE)
499			err(4, "%s", specname);
500		for (lp = (struct disklabel *)bootarea;
501		    lp <= (struct disklabel *)(bootarea + BBSIZE - sizeof(*lp));
502		    lp = (struct disklabel *)((char *)lp + 16))
503			if (lp->d_magic == DISKMAGIC &&
504			    lp->d_magic2 == DISKMAGIC)
505				break;
506		if (lp > (struct disklabel *)(bootarea+BBSIZE-sizeof(*lp)) ||
507		    lp->d_magic != DISKMAGIC || lp->d_magic2 != DISKMAGIC ||
508		    dkcksum(lp) != 0) {
509     errx(1, "bad pack magic number (label is damaged, or pack is unlabeled)");
510		}
511	} else {
512		lp = &lab;
513		if (ioctl(f, DIOCGDINFO, lp) < 0)
514			err(4, "ioctl DIOCGDINFO");
515	}
516	return (lp);
517}
518
519/*
520 * Construct a bootarea (d_bbsize bytes) in the specified buffer ``boot''
521 * Returns a pointer to the disklabel portion of the bootarea.
522 */
523struct disklabel *
524makebootarea(boot, dp, f)
525	char *boot;
526	register struct disklabel *dp;
527	int f;
528{
529	struct disklabel *lp;
530	register char *p;
531	int b;
532#if NUMBOOT > 0
533	char *dkbasename;
534#if NUMBOOT == 1
535	struct stat sb;
536#endif
537#ifdef __i386__
538	char *tmpbuf;
539	int i, found;
540#endif /* i386 */
541#endif
542
543	/* XXX */
544	if (dp->d_secsize == 0) {
545		dp->d_secsize = DEV_BSIZE;
546		dp->d_bbsize = BBSIZE;
547	}
548	lp = (struct disklabel *)
549		(boot + (LABELSECTOR * dp->d_secsize) + LABELOFFSET);
550	bzero((char *)lp, sizeof *lp);
551#if NUMBOOT > 0
552	/*
553	 * If we are not installing a boot program but we are installing a
554	 * label on disk then we must read the current bootarea so we don't
555	 * clobber the existing boot.
556	 */
557	if (!installboot) {
558		if (rflag) {
559			if (read(f, boot, BBSIZE) < BBSIZE)
560				err(4, "%s", specname);
561			bzero((char *)lp, sizeof *lp);
562		}
563		return (lp);
564	}
565	/*
566	 * We are installing a boot program.  Determine the name(s) and
567	 * read them into the appropriate places in the boot area.
568	 */
569	if (!xxboot || !bootxx) {
570		dkbasename = np;
571		if ((p = rindex(dkname, '/')) == NULL)
572			p = dkname;
573		else
574			p++;
575		while (*p && !isdigit(*p))
576			*np++ = *p++;
577		*np++ = '\0';
578
579		if (!xxboot) {
580			(void)sprintf(np, "%s/%sboot",
581				      _PATH_BOOTDIR, dkbasename);
582			if (access(np, F_OK) < 0 && dkbasename[0] == 'r')
583				dkbasename++;
584			xxboot = np;
585			(void)sprintf(xxboot, "%s/%sboot",
586				      _PATH_BOOTDIR, dkbasename);
587			np += strlen(xxboot) + 1;
588		}
589#if NUMBOOT > 1
590		if (!bootxx) {
591			(void)sprintf(np, "%s/boot%s",
592				      _PATH_BOOTDIR, dkbasename);
593			if (access(np, F_OK) < 0 && dkbasename[0] == 'r')
594				dkbasename++;
595			bootxx = np;
596			(void)sprintf(bootxx, "%s/boot%s",
597				      _PATH_BOOTDIR, dkbasename);
598			np += strlen(bootxx) + 1;
599		}
600#endif
601	}
602#ifdef DEBUG
603	if (debug)
604		fprintf(stderr, "bootstraps: xxboot = %s, bootxx = %s\n",
605			xxboot, bootxx ? bootxx : "NONE");
606#endif
607
608	/*
609	 * Strange rules:
610	 * 1. One-piece bootstrap (hp300/hp800)
611	 *	up to d_bbsize bytes of ``xxboot'' go in bootarea, the rest
612	 *	is remembered and written later following the bootarea.
613	 * 2. Two-piece bootstraps (vax/i386?/mips?)
614	 *	up to d_secsize bytes of ``xxboot'' go in first d_secsize
615	 *	bytes of bootarea, remaining d_bbsize-d_secsize filled
616	 *	from ``bootxx''.
617	 */
618	b = open(xxboot, O_RDONLY);
619	if (b < 0)
620		err(4, "%s", xxboot);
621#if NUMBOOT > 1
622#ifdef __i386__
623	/*
624	 * XXX Botch alert.
625	 * The i386 has the so-called fdisk table embedded into the
626	 * primary bootstrap.  We take care to not clobber it, but
627	 * only if it does already contain some data.  (Otherwise,
628	 * the xxboot provides a template.)
629	 */
630	if ((tmpbuf = (char *)malloc((int)dp->d_secsize)) == 0)
631		err(4, "%s", xxboot);
632	memcpy((void *)tmpbuf, (void *)boot, (int)dp->d_secsize);
633#endif /* i386 */
634	if (read(b, boot, (int)dp->d_secsize) < 0)
635		err(4, "%s", xxboot);
636	(void)close(b);
637#ifdef __i386__
638	for (i = DOSPARTOFF, found = 0;
639	     !found && i < DOSPARTOFF + NDOSPART*sizeof(struct dos_partition);
640	     i++)
641		found = tmpbuf[i] != 0;
642	if (found)
643		memcpy((void *)&boot[DOSPARTOFF],
644		       (void *)&tmpbuf[DOSPARTOFF],
645		       NDOSPART * sizeof(struct dos_partition));
646	free(tmpbuf);
647#endif /* i386 */
648	b = open(bootxx, O_RDONLY);
649	if (b < 0)
650		err(4, "%s", bootxx);
651	if (read(b, &boot[dp->d_secsize],
652		 (int)(dp->d_bbsize-dp->d_secsize)) < 0)
653		err(4, "%s", bootxx);
654#else
655	if (read(b, boot, (int)dp->d_bbsize) < 0)
656		err(4, "%s", xxboot);
657	(void)fstat(b, &sb);
658	bootsize = (int)sb.st_size - dp->d_bbsize;
659	if (bootsize > 0) {
660		/* XXX assume d_secsize is a power of two */
661		bootsize = (bootsize + dp->d_secsize-1) & ~(dp->d_secsize-1);
662		bootbuf = (char *)malloc((size_t)bootsize);
663		if (bootbuf == 0)
664			err(4, "%s", xxboot);
665		if (read(b, bootbuf, bootsize) < 0) {
666			free(bootbuf);
667			err(4, "%s", xxboot);
668		}
669	}
670#endif
671	(void)close(b);
672#endif
673	/*
674	 * Make sure no part of the bootstrap is written in the area
675	 * reserved for the label.
676	 */
677	for (p = (char *)lp; p < (char *)lp + sizeof(struct disklabel); p++)
678		if (*p)
679			errx(2, "bootstrap doesn't leave room for disk label");
680	return (lp);
681}
682
683void
684display(f, lp)
685	FILE *f;
686	register struct disklabel *lp;
687{
688	register int i, j;
689	register struct partition *pp;
690
691	fprintf(f, "# %s:\n", specname);
692	if ((unsigned) lp->d_type < DKMAXTYPES)
693		fprintf(f, "type: %s\n", dktypenames[lp->d_type]);
694	else
695		fprintf(f, "type: %d\n", lp->d_type);
696	fprintf(f, "disk: %.*s\n", (int)sizeof(lp->d_typename),
697		lp->d_typename);
698	fprintf(f, "label: %.*s\n", (int)sizeof(lp->d_packname),
699		lp->d_packname);
700	fprintf(f, "flags:");
701	if (lp->d_flags & D_REMOVABLE)
702		fprintf(f, " removeable");
703	if (lp->d_flags & D_ECC)
704		fprintf(f, " ecc");
705	if (lp->d_flags & D_BADSECT)
706		fprintf(f, " badsect");
707	fprintf(f, "\n");
708	fprintf(f, "bytes/sector: %ld\n", lp->d_secsize);
709	fprintf(f, "sectors/track: %ld\n", lp->d_nsectors);
710	fprintf(f, "tracks/cylinder: %ld\n", lp->d_ntracks);
711	fprintf(f, "sectors/cylinder: %ld\n", lp->d_secpercyl);
712	fprintf(f, "cylinders: %ld\n", lp->d_ncylinders);
713	fprintf(f, "sectors/unit: %ld\n", lp->d_secperunit);
714	fprintf(f, "rpm: %d\n", lp->d_rpm);
715	fprintf(f, "interleave: %d\n", lp->d_interleave);
716	fprintf(f, "trackskew: %d\n", lp->d_trackskew);
717	fprintf(f, "cylinderskew: %d\n", lp->d_cylskew);
718	fprintf(f, "headswitch: %ld\t\t# milliseconds\n", lp->d_headswitch);
719	fprintf(f, "track-to-track seek: %ld\t# milliseconds\n",
720		lp->d_trkseek);
721	fprintf(f, "drivedata: ");
722	for (i = NDDATA - 1; i >= 0; i--)
723		if (lp->d_drivedata[i])
724			break;
725	if (i < 0)
726		i = 0;
727	for (j = 0; j <= i; j++)
728		fprintf(f, "%ld ", lp->d_drivedata[j]);
729	fprintf(f, "\n\n%d partitions:\n", lp->d_npartitions);
730	fprintf(f,
731	    "#        size   offset    fstype   [fsize bsize bps/cpg]\n");
732	pp = lp->d_partitions;
733	for (i = 0; i < lp->d_npartitions; i++, pp++) {
734		if (pp->p_size) {
735			fprintf(f, "  %c: %8ld %8ld  ", 'a' + i,
736			   pp->p_size, pp->p_offset);
737			if ((unsigned) pp->p_fstype < FSMAXTYPES)
738				fprintf(f, "%8.8s", fstypenames[pp->p_fstype]);
739			else
740				fprintf(f, "%8d", pp->p_fstype);
741			switch (pp->p_fstype) {
742
743			case FS_UNUSED:				/* XXX */
744				fprintf(f, "    %5ld %5ld %5.5s ",
745				    pp->p_fsize, pp->p_fsize * pp->p_frag, "");
746				break;
747
748			case FS_BSDFFS:
749				fprintf(f, "    %5ld %5ld %5d ",
750				    pp->p_fsize, pp->p_fsize * pp->p_frag,
751				    pp->p_cpg);
752				break;
753
754			case FS_BSDLFS:
755				fprintf(f, "    %5ld %5ld %5d",
756				    pp->p_fsize, pp->p_fsize * pp->p_frag,
757				    pp->p_cpg);
758				break;
759
760			default:
761				fprintf(f, "%20.20s", "");
762				break;
763			}
764			fprintf(f, "\t# (Cyl. %4ld",
765			    pp->p_offset / lp->d_secpercyl);
766			if (pp->p_offset % lp->d_secpercyl)
767			    putc('*', f);
768			else
769			    putc(' ', f);
770			fprintf(f, "- %ld",
771			    (pp->p_offset +
772			    pp->p_size + lp->d_secpercyl - 1) /
773			    lp->d_secpercyl - 1);
774			if (pp->p_size % lp->d_secpercyl)
775			    putc('*', f);
776			fprintf(f, ")\n");
777		}
778	}
779	fflush(f);
780}
781
782int
783edit(lp, f)
784	struct disklabel *lp;
785	int f;
786{
787	register int c, fd;
788	struct disklabel label;
789	FILE *fp;
790
791	if ((fd = mkstemp(tmpfil)) == -1 ||
792	    (fp = fdopen(fd, "w")) == NULL) {
793		warnx("can't create %s", tmpfil);
794		return (1);
795	}
796	display(fp, lp);
797	fclose(fp);
798	for (;;) {
799		if (!editit())
800			break;
801		fp = fopen(tmpfil, "r");
802		if (fp == NULL) {
803			warnx("can't reopen %s for reading", tmpfil);
804			break;
805		}
806		bzero((char *)&label, sizeof(label));
807		if (getasciilabel(fp, &label)) {
808			*lp = label;
809			if (writelabel(f, bootarea, lp) == 0) {
810				fclose(fp);
811				(void) unlink(tmpfil);
812				return (0);
813			}
814		}
815		fclose(fp);
816		printf("re-edit the label? [y]: "); fflush(stdout);
817		c = getchar();
818		if (c != EOF && c != (int)'\n')
819			while (getchar() != (int)'\n')
820				;
821		if  (c == (int)'n')
822			break;
823	}
824	(void) unlink(tmpfil);
825	return (1);
826}
827
828int
829editit()
830{
831	register int pid, xpid;
832	int stat, omask;
833	extern char *getenv();
834
835	omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
836	while ((pid = fork()) < 0) {
837		extern int errno;
838
839		if (errno == EPROCLIM) {
840			warnx("you have too many processes");
841			return(0);
842		}
843		if (errno != EAGAIN) {
844			warn("fork");
845			return(0);
846		}
847		sleep(1);
848	}
849	if (pid == 0) {
850		register char *ed;
851
852		sigsetmask(omask);
853		setgid(getgid());
854		setuid(getuid());
855		if ((ed = getenv("EDITOR")) == (char *)0)
856			ed = DEFEDITOR;
857		execlp(ed, ed, tmpfil, 0);
858		err(1, "%s", ed);
859	}
860	while ((xpid = wait(&stat)) >= 0)
861		if (xpid == pid)
862			break;
863	sigsetmask(omask);
864	return(!stat);
865}
866
867char *
868skip(cp)
869	register char *cp;
870{
871
872	while (*cp != '\0' && isspace(*cp))
873		cp++;
874	if (*cp == '\0' || *cp == '#')
875		return ((char *)NULL);
876	return (cp);
877}
878
879char *
880word(cp)
881	register char *cp;
882{
883	register char c;
884
885	while (*cp != '\0' && !isspace(*cp) && *cp != '#')
886		cp++;
887	if ((c = *cp) != '\0') {
888		*cp++ = '\0';
889		if (c != '#')
890			return (skip(cp));
891	}
892	return ((char *)NULL);
893}
894
895/*
896 * Read an ascii label in from fd f,
897 * in the same format as that put out by display(),
898 * and fill in lp.
899 */
900int
901getasciilabel(f, lp)
902	FILE	*f;
903	register struct disklabel *lp;
904{
905	register char **cpp, *cp;
906	register struct partition *pp;
907	char *tp, *s, line[BUFSIZ];
908	int v, lineno = 0, errors = 0;
909
910	lp->d_bbsize = BBSIZE;				/* XXX */
911	lp->d_sbsize = SBSIZE;				/* XXX */
912	while (fgets(line, sizeof(line) - 1, f)) {
913		lineno++;
914		if ((cp = index(line,'\n')) != 0)
915			*cp = '\0';
916		cp = skip(line);
917		if (cp == NULL)
918			continue;
919		tp = index(cp, ':');
920		if (tp == NULL) {
921			fprintf(stderr, "line %d: syntax error\n", lineno);
922			errors++;
923			continue;
924		}
925		*tp++ = '\0', tp = skip(tp);
926		if (streq(cp, "type")) {
927			if (tp == NULL)
928				tp = "unknown";
929			cpp = dktypenames;
930			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
931				if ((s = *cpp) && streq(s, tp)) {
932					lp->d_type = cpp - dktypenames;
933					goto next;
934				}
935			v = atoi(tp);
936			if ((unsigned)v >= DKMAXTYPES)
937				fprintf(stderr, "line %d:%s %d\n", lineno,
938				    "Warning, unknown disk type", v);
939			lp->d_type = v;
940			continue;
941		}
942		if (streq(cp, "flags")) {
943			for (v = 0; (cp = tp) && *cp != '\0';) {
944				tp = word(cp);
945				if (streq(cp, "removeable"))
946					v |= D_REMOVABLE;
947				else if (streq(cp, "ecc"))
948					v |= D_ECC;
949				else if (streq(cp, "badsect"))
950					v |= D_BADSECT;
951				else {
952					fprintf(stderr,
953					    "line %d: %s: bad flag\n",
954					    lineno, cp);
955					errors++;
956				}
957			}
958			lp->d_flags = v;
959			continue;
960		}
961		if (streq(cp, "drivedata")) {
962			register int i;
963
964			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
965				lp->d_drivedata[i++] = atoi(cp);
966				tp = word(cp);
967			}
968			continue;
969		}
970		if (sscanf(cp, "%d partitions", &v) == 1) {
971			if (v == 0 || (unsigned)v > MAXPARTITIONS) {
972				fprintf(stderr,
973				    "line %d: bad # of partitions\n", lineno);
974				lp->d_npartitions = MAXPARTITIONS;
975				errors++;
976			} else
977				lp->d_npartitions = v;
978			continue;
979		}
980		if (tp == NULL)
981			tp = "";
982		if (streq(cp, "disk")) {
983			strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
984			continue;
985		}
986		if (streq(cp, "label")) {
987			strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
988			continue;
989		}
990		if (streq(cp, "bytes/sector")) {
991			v = atoi(tp);
992			if (v <= 0 || (v % 512) != 0) {
993				fprintf(stderr,
994				    "line %d: %s: bad sector size\n",
995				    lineno, tp);
996				errors++;
997			} else
998				lp->d_secsize = v;
999			continue;
1000		}
1001		if (streq(cp, "sectors/track")) {
1002			v = atoi(tp);
1003			if (v <= 0) {
1004				fprintf(stderr, "line %d: %s: bad %s\n",
1005				    lineno, tp, cp);
1006				errors++;
1007			} else
1008				lp->d_nsectors = v;
1009			continue;
1010		}
1011		if (streq(cp, "sectors/cylinder")) {
1012			v = atoi(tp);
1013			if (v <= 0) {
1014				fprintf(stderr, "line %d: %s: bad %s\n",
1015				    lineno, tp, cp);
1016				errors++;
1017			} else
1018				lp->d_secpercyl = v;
1019			continue;
1020		}
1021		if (streq(cp, "tracks/cylinder")) {
1022			v = atoi(tp);
1023			if (v <= 0) {
1024				fprintf(stderr, "line %d: %s: bad %s\n",
1025				    lineno, tp, cp);
1026				errors++;
1027			} else
1028				lp->d_ntracks = v;
1029			continue;
1030		}
1031		if (streq(cp, "cylinders")) {
1032			v = atoi(tp);
1033			if (v <= 0) {
1034				fprintf(stderr, "line %d: %s: bad %s\n",
1035				    lineno, tp, cp);
1036				errors++;
1037			} else
1038				lp->d_ncylinders = v;
1039			continue;
1040		}
1041		if (streq(cp, "sectors/unit")) {
1042			v = atoi(tp);
1043			if (v <= 0) {
1044				fprintf(stderr, "line %d: %s: bad %s\n",
1045				    lineno, tp, cp);
1046				errors++;
1047			} else
1048				lp->d_secperunit = v;
1049			continue;
1050		}
1051		if (streq(cp, "rpm")) {
1052			v = atoi(tp);
1053			if (v <= 0) {
1054				fprintf(stderr, "line %d: %s: bad %s\n",
1055				    lineno, tp, cp);
1056				errors++;
1057			} else
1058				lp->d_rpm = v;
1059			continue;
1060		}
1061		if (streq(cp, "interleave")) {
1062			v = atoi(tp);
1063			if (v <= 0) {
1064				fprintf(stderr, "line %d: %s: bad %s\n",
1065				    lineno, tp, cp);
1066				errors++;
1067			} else
1068				lp->d_interleave = v;
1069			continue;
1070		}
1071		if (streq(cp, "trackskew")) {
1072			v = atoi(tp);
1073			if (v < 0) {
1074				fprintf(stderr, "line %d: %s: bad %s\n",
1075				    lineno, tp, cp);
1076				errors++;
1077			} else
1078				lp->d_trackskew = v;
1079			continue;
1080		}
1081		if (streq(cp, "cylinderskew")) {
1082			v = atoi(tp);
1083			if (v < 0) {
1084				fprintf(stderr, "line %d: %s: bad %s\n",
1085				    lineno, tp, cp);
1086				errors++;
1087			} else
1088				lp->d_cylskew = v;
1089			continue;
1090		}
1091		if (streq(cp, "headswitch")) {
1092			v = atoi(tp);
1093			if (v < 0) {
1094				fprintf(stderr, "line %d: %s: bad %s\n",
1095				    lineno, tp, cp);
1096				errors++;
1097			} else
1098				lp->d_headswitch = v;
1099			continue;
1100		}
1101		if (streq(cp, "track-to-track seek")) {
1102			v = atoi(tp);
1103			if (v < 0) {
1104				fprintf(stderr, "line %d: %s: bad %s\n",
1105				    lineno, tp, cp);
1106				errors++;
1107			} else
1108				lp->d_trkseek = v;
1109			continue;
1110		}
1111		if ('a' <= *cp && *cp <= 'z' && cp[1] == '\0') {
1112			unsigned part = *cp - 'a';
1113
1114			if (part > lp->d_npartitions) {
1115				fprintf(stderr,
1116				    "line %d: bad partition name\n", lineno);
1117				errors++;
1118				continue;
1119			}
1120			pp = &lp->d_partitions[part];
1121#define NXTNUM(n) { \
1122	if (tp == NULL) { \
1123		fprintf(stderr, "line %d: too few numeric fields\n", lineno); \
1124		errors++; \
1125		break; \
1126	} else { \
1127		cp = tp, tp = word(cp); \
1128		if (tp == NULL) \
1129			tp = cp; \
1130		(n) = atoi(cp); \
1131	} \
1132     }
1133
1134			NXTNUM(v);
1135			if (v < 0) {
1136				fprintf(stderr,
1137				    "line %d: %s: bad partition size\n",
1138				    lineno, cp);
1139				errors++;
1140			} else
1141				pp->p_size = v;
1142			NXTNUM(v);
1143			if (v < 0) {
1144				fprintf(stderr,
1145				    "line %d: %s: bad partition offset\n",
1146				    lineno, cp);
1147				errors++;
1148			} else
1149				pp->p_offset = v;
1150			cp = tp, tp = word(cp);
1151			cpp = fstypenames;
1152			for (; cpp < &fstypenames[FSMAXTYPES]; cpp++)
1153				if ((s = *cpp) && streq(s, cp)) {
1154					pp->p_fstype = cpp - fstypenames;
1155					goto gottype;
1156				}
1157			if (isdigit(*cp))
1158				v = atoi(cp);
1159			else
1160				v = FSMAXTYPES;
1161			if ((unsigned)v >= FSMAXTYPES) {
1162				fprintf(stderr, "line %d: %s %s\n", lineno,
1163				    "Warning, unknown filesystem type", cp);
1164				v = FS_UNUSED;
1165			}
1166			pp->p_fstype = v;
1167	gottype:
1168
1169			switch (pp->p_fstype) {
1170
1171			case FS_UNUSED:				/* XXX */
1172				NXTNUM(pp->p_fsize);
1173				if (pp->p_fsize == 0)
1174					break;
1175				NXTNUM(v);
1176				pp->p_frag = v / pp->p_fsize;
1177				break;
1178
1179			case FS_BSDFFS:
1180				NXTNUM(pp->p_fsize);
1181				if (pp->p_fsize == 0)
1182					break;
1183				NXTNUM(v);
1184				pp->p_frag = v / pp->p_fsize;
1185				NXTNUM(pp->p_cpg);
1186				break;
1187
1188			case FS_BSDLFS:
1189				NXTNUM(pp->p_fsize);
1190				if (pp->p_fsize == 0)
1191					break;
1192				NXTNUM(v);
1193				pp->p_frag = v / pp->p_fsize;
1194				NXTNUM(pp->p_cpg);
1195				break;
1196
1197			default:
1198				break;
1199			}
1200			continue;
1201		}
1202		fprintf(stderr, "line %d: %s: Unknown disklabel field\n",
1203		    lineno, cp);
1204		errors++;
1205	next:
1206		;
1207	}
1208	errors += checklabel(lp);
1209	return (errors == 0);
1210}
1211
1212/*
1213 * Check disklabel for errors and fill in
1214 * derived fields according to supplied values.
1215 */
1216int
1217checklabel(lp)
1218	register struct disklabel *lp;
1219{
1220	register struct partition *pp;
1221	int i, errors = 0;
1222	char part;
1223
1224	if (lp->d_secsize == 0) {
1225		fprintf(stderr, "sector size %ld\n", lp->d_secsize);
1226		return (1);
1227	}
1228	if (lp->d_nsectors == 0) {
1229		fprintf(stderr, "sectors/track %ld\n", lp->d_nsectors);
1230		return (1);
1231	}
1232	if (lp->d_ntracks == 0) {
1233		fprintf(stderr, "tracks/cylinder %ld\n", lp->d_ntracks);
1234		return (1);
1235	}
1236	if  (lp->d_ncylinders == 0) {
1237		fprintf(stderr, "cylinders/unit %ld\n", lp->d_ncylinders);
1238		errors++;
1239	}
1240	if (lp->d_rpm == 0)
1241		Warning("revolutions/minute %d", lp->d_rpm);
1242	if (lp->d_secpercyl == 0)
1243		lp->d_secpercyl = lp->d_nsectors * lp->d_ntracks;
1244	if (lp->d_secperunit == 0)
1245		lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
1246	if (lp->d_bbsize == 0) {
1247		fprintf(stderr, "boot block size %ld\n", lp->d_bbsize);
1248		errors++;
1249	} else if (lp->d_bbsize % lp->d_secsize)
1250		Warning("boot block size %% sector-size != 0");
1251	if (lp->d_sbsize == 0) {
1252		fprintf(stderr, "super block size %ld\n", lp->d_sbsize);
1253		errors++;
1254	} else if (lp->d_sbsize % lp->d_secsize)
1255		Warning("super block size %% sector-size != 0");
1256	if (lp->d_npartitions > MAXPARTITIONS)
1257		Warning("number of partitions (%d) > MAXPARTITIONS (%d)",
1258		    lp->d_npartitions, MAXPARTITIONS);
1259	for (i = 0; i < lp->d_npartitions; i++) {
1260		part = 'a' + i;
1261		pp = &lp->d_partitions[i];
1262		if (pp->p_size == 0 && pp->p_offset != 0)
1263			Warning("partition %c: size 0, but offset %d",
1264			    part, pp->p_offset);
1265#ifdef notdef
1266		if (pp->p_size % lp->d_secpercyl)
1267			Warning("partition %c: size %% cylinder-size != 0",
1268			    part);
1269		if (pp->p_offset % lp->d_secpercyl)
1270			Warning("partition %c: offset %% cylinder-size != 0",
1271			    part);
1272#endif
1273		if (pp->p_offset > lp->d_secperunit) {
1274			fprintf(stderr,
1275			    "partition %c: offset past end of unit\n", part);
1276			errors++;
1277		}
1278		if (pp->p_offset + pp->p_size > lp->d_secperunit) {
1279			fprintf(stderr,
1280			"partition %c: partition extends past end of unit\n",
1281			    part);
1282			errors++;
1283		}
1284	}
1285	for (; i < MAXPARTITIONS; i++) {
1286		part = 'a' + i;
1287		pp = &lp->d_partitions[i];
1288		if (pp->p_size || pp->p_offset)
1289			Warning("unused partition %c: size %d offset %d",
1290			    'a' + i, pp->p_size, pp->p_offset);
1291	}
1292	return (errors);
1293}
1294
1295/*
1296 * When operating on a "virgin" disk, try getting an initial label
1297 * from the associated device driver.  This might work for all device
1298 * drivers that are able to fetch some initial device parameters
1299 * without even having access to a (BSD) disklabel, like SCSI disks,
1300 * most IDE drives, or vn devices.
1301 *
1302 * The device name must be given in its "canonical" form.
1303 */
1304struct disklabel *
1305getvirginlabel(void)
1306{
1307	static struct disklabel lab;
1308	char namebuf[BBSIZE];
1309	int f;
1310
1311	if (dkname[0] == '/') {
1312		fprintf(stderr,
1313		"\"auto\" requires the usage of a canonical disk name.\n");
1314		return (NULL);
1315	}
1316	(void)snprintf(namebuf, BBSIZE, "%sr%s", _PATH_DEV, dkname);
1317	if ((f = open(namebuf, O_RDONLY, 0)) == -1) {
1318		err(4, "open()");
1319		return (NULL);
1320	}
1321	if (ioctl(f, DIOCGDINFO, &lab) < 0) {
1322		err(4, "ioctl DIOCGDINFO");
1323		close(f);
1324		return (NULL);
1325	}
1326	close(f);
1327	return (&lab);
1328}
1329
1330
1331/*
1332 * If we are installing a boot program that doesn't fit in d_bbsize
1333 * we need to mark those partitions that the boot overflows into.
1334 * This allows newfs to prevent creation of a filesystem where it might
1335 * clobber bootstrap code.
1336 */
1337void
1338setbootflag(lp)
1339	register struct disklabel *lp;
1340{
1341	register struct partition *pp;
1342	int i, errors = 0;
1343	char part;
1344	u_long boffset;
1345
1346	if (bootbuf == 0)
1347		return;
1348	boffset = bootsize / lp->d_secsize;
1349	for (i = 0; i < lp->d_npartitions; i++) {
1350		part = 'a' + i;
1351		pp = &lp->d_partitions[i];
1352		if (pp->p_size == 0)
1353			continue;
1354		if (boffset <= pp->p_offset) {
1355			if (pp->p_fstype == FS_BOOT)
1356				pp->p_fstype = FS_UNUSED;
1357		} else if (pp->p_fstype != FS_BOOT) {
1358			if (pp->p_fstype != FS_UNUSED) {
1359				fprintf(stderr,
1360					"boot overlaps used partition %c\n",
1361					part);
1362				errors++;
1363			} else {
1364				pp->p_fstype = FS_BOOT;
1365				Warning("boot overlaps partition %c, %s",
1366					part, "marked as FS_BOOT");
1367			}
1368		}
1369	}
1370	if (errors)
1371		errx(4, "cannot install boot program");
1372}
1373
1374/*VARARGS1*/
1375void
1376Warning(char *fmt, ...)
1377{
1378	va_list ap;
1379
1380	fprintf(stderr, "Warning, ");
1381	va_start(ap, fmt);
1382	vfprintf(stderr, fmt, ap);
1383	fprintf(stderr, "\n");
1384	va_end(ap);
1385}
1386
1387void
1388usage()
1389{
1390#if NUMBOOT > 0
1391	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%s\n%s\n",
1392		"usage: disklabel [-r] disk",
1393		"\t\t(to read label)",
1394		"       disklabel -w [-r] disk type [ packid ]",
1395		"\t\t(to write label with existing boot program)",
1396		"       disklabel -e [-r] disk",
1397		"\t\t(to edit label)",
1398		"       disklabel -R [-r] disk protofile",
1399		"\t\t(to restore label with existing boot program)",
1400#if NUMBOOT > 1
1401		"       disklabel -B [ -b boot1 [ -s boot2 ] ] disk [ type ]",
1402		"\t\t(to install boot program with existing label)",
1403		"       disklabel -w -B [ -b boot1 [ -s boot2 ] ] disk type [ packid ]",
1404		"\t\t(to write label and boot program)",
1405		"       disklabel -R -B [ -b boot1 [ -s boot2 ] ] disk protofile [ type ]",
1406		"\t\t(to restore label and boot program)",
1407#else
1408		"       disklabel -B [ -b bootprog ] disk [ type ]",
1409		"\t\t(to install boot program with existing on-disk label)",
1410		"       disklabel -w -B [ -b bootprog ] disk type [ packid ]",
1411		"\t\t(to write label and install boot program)",
1412		"       disklabel -R -B [ -b bootprog ] disk protofile [ type ]",
1413		"\t\t(to restore label and install boot program)",
1414#endif
1415		"       disklabel [-NW] disk",
1416		"\t\t(to write disable/enable label)");
1417#else
1418	fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
1419		"usage: disklabel [-r] disk", "(to read label)",
1420		"       disklabel -w [-r] disk type [ packid ]",
1421		"\t\t(to write label)",
1422		"       disklabel -e [-r] disk",
1423		"\t\t(to edit label)",
1424		"       disklabel -R [-r] disk protofile",
1425		"\t\t(to restore label)",
1426		"       disklabel [-NW] disk",
1427		"\t\t(to write disable/enable label)");
1428#endif
1429	exit(1);
1430}
1431