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