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