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