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