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