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