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