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