Home | History | Annotate | Line # | Download | only in newfs
newfs.c revision 1.49
      1 /*	$NetBSD: newfs.c,v 1.49 2001/11/21 15:23:40 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1983, 1989, 1993, 1994\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)newfs.c	8.13 (Berkeley) 5/1/95";
     45 #else
     46 __RCSID("$NetBSD: newfs.c,v 1.49 2001/11/21 15:23:40 lukem Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 /*
     51  * newfs: friendly front end to mkfs
     52  */
     53 #include <sys/param.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/disklabel.h>
     56 #include <sys/file.h>
     57 #include <sys/mount.h>
     58 #include <sys/sysctl.h>
     59 #include <sys/wait.h>
     60 
     61 #include <ufs/ufs/dir.h>
     62 #include <ufs/ufs/dinode.h>
     63 #include <ufs/ufs/ufsmount.h>
     64 #include <ufs/ffs/fs.h>
     65 
     66 #include <ctype.h>
     67 #include <disktab.h>
     68 #include <errno.h>
     69 #include <paths.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.h>
     73 #include <syslog.h>
     74 #include <unistd.h>
     75 #include <signal.h>
     76 #include <err.h>
     77 #include <util.h>
     78 
     79 #include "mntopts.h"
     80 #include "dkcksum.h"
     81 #include "extern.h"
     82 
     83 struct mntopt mopts[] = {
     84 	MOPT_STDOPTS,
     85 	MOPT_ASYNC,
     86 	MOPT_UPDATE,
     87 	MOPT_NOATIME,
     88 	{ NULL },
     89 };
     90 
     91 static struct disklabel *getdisklabel(char *, int);
     92 static void rewritelabel(char *, int, struct disklabel *);
     93 static int strsuftoi(const char *, const char *, int, int);
     94 static void usage(void);
     95 int main(int, char *[]);
     96 
     97 #define	COMPAT			/* allow non-labeled disks */
     98 
     99 /*
    100  * The following two constants set the default block and fragment sizes.
    101  * Both constants must be a power of 2 and meet the following constraints:
    102  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
    103  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
    104  *	DESBLKSIZE / DESFRAGSIZE <= 8
    105  */
    106 #define	DFL_FRAGSIZE	1024
    107 #define	DFL_BLKSIZE	8192
    108 
    109 /*
    110  * Default sector size.
    111  */
    112 #define DFL_SECSIZE	512
    113 
    114 /*
    115  * Cylinder groups may have up to many cylinders. The actual
    116  * number used depends upon how much information can be stored
    117  * on a single cylinder. The default is to use 16 cylinders
    118  * per group.
    119  */
    120 #define	DESCPG		16	/* desired fs_cpg */
    121 
    122 /*
    123  * ROTDELAY gives the minimum number of milliseconds to initiate
    124  * another disk transfer on the same cylinder. It is used in
    125  * determining the rotationally optimal layout for disk blocks
    126  * within a file; the default of fs_rotdelay is 0ms.
    127  */
    128 #define ROTDELAY	0
    129 
    130 /*
    131  * MAXBLKPG determines the maximum number of data blocks which are
    132  * placed in a single cylinder group. The default is one indirect
    133  * block worth of data blocks.
    134  */
    135 #define MAXBLKPG(bsize)	((bsize) / sizeof(daddr_t))
    136 
    137 /*
    138  * Each file system has a number of inodes statically allocated.
    139  * We allocate one inode slot per NFPI fragments, expecting this
    140  * to be far more than we will ever need.
    141  */
    142 #define	NFPI		4
    143 
    144 /*
    145  * For each cylinder we keep track of the availability of blocks at different
    146  * rotational positions, so that we can lay out the data to be picked
    147  * up with minimum rotational latency.  NRPOS is the default number of
    148  * rotational positions that we distinguish.  With NRPOS of 8 the resolution
    149  * of our summary information is 2ms for a typical 3600 rpm drive.  Caching
    150  * and zoning pretty much defeats rotational optimization, so we now use a
    151  * default of 1.
    152  */
    153 #define	NRPOS		1	/* number distinct rotational positions */
    154 
    155 
    156 int	mfs;			/* run as the memory based filesystem */
    157 int	Nflag;			/* run without writing file system */
    158 int	Oflag;			/* format as an 4.3BSD file system */
    159 int	fssize;			/* file system size */
    160 int	ntracks;		/* # tracks/cylinder */
    161 int	nsectors;		/* # sectors/track */
    162 int	nphyssectors;		/* # sectors/track including spares */
    163 int	secpercyl;		/* sectors per cylinder */
    164 int	trackspares = -1;	/* spare sectors per track */
    165 int	cylspares = -1;		/* spare sectors per cylinder */
    166 int	sectorsize;		/* bytes/sector */
    167 int	rpm;			/* revolutions/minute of drive */
    168 int	interleave;		/* hardware sector interleave */
    169 int	trackskew = -1;		/* sector 0 skew, per track */
    170 int	fsize = 0;		/* fragment size */
    171 int	bsize = 0;		/* block size */
    172 int	cpg = DESCPG;		/* cylinders/cylinder group */
    173 int	cpgflg;			/* cylinders/cylinder group flag was given */
    174 int	minfree = MINFREE;	/* free space threshold */
    175 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
    176 int	density;		/* number of bytes per inode */
    177 int	maxcontig = 0;		/* max contiguous blocks to allocate */
    178 int	rotdelay = ROTDELAY;	/* rotational delay between blocks */
    179 int	maxbpg;			/* maximum blocks per file in a cyl group */
    180 int	nrpos = NRPOS;		/* # of distinguished rotational positions */
    181 int	avgfilesize = AVFILESIZ;/* expected average file size */
    182 int	avgfpdir = AFPDIR;	/* expected number of files per directory */
    183 int	bbsize = BBSIZE;	/* boot block size */
    184 int	sbsize = SBSIZE;	/* superblock size */
    185 int	mntflags = MNT_ASYNC;	/* flags to be passed to mount */
    186 u_long	memleft;		/* virtual memory available */
    187 caddr_t	membase;		/* start address of memory based filesystem */
    188 int	needswap;		/* Filesystem not in native byte order */
    189 #ifdef COMPAT
    190 char	*disktype;
    191 int	unlabeled;
    192 #endif
    193 
    194 char	device[MAXPATHLEN];
    195 
    196 int
    197 main(int argc, char *argv[])
    198 {
    199 	struct partition *pp;
    200 	struct disklabel *lp;
    201 	struct disklabel mfsfakelabel;
    202 	struct partition oldpartition;
    203 	struct statfs *mp;
    204 	int ch, fsi, fso, len, maxpartitions, n, Fflag, Zflag;
    205 	char *cp, *endp, *s1, *s2, *special;
    206 	const char *opstring;
    207 	long long llsize;
    208 #ifdef MFS
    209 	char mountfromname[100];
    210 	pid_t pid, res;
    211 	struct statfs sf;
    212 	int status;
    213 #endif
    214 
    215 	cp = NULL;
    216 	fsi = fso = -1;
    217 	Fflag = Zflag = 0;
    218 	if (strstr(getprogname(), "mfs")) {
    219 		mfs = 1;
    220 		Nflag++;
    221 	}
    222 
    223 	maxpartitions = getmaxpartitions();
    224 	if (maxpartitions > 26)
    225 		errx(1, "insane maxpartitions value %d", maxpartitions);
    226 
    227 	opstring = mfs ?
    228 	    "NT:a:b:c:d:e:f:g:h:i:m:o:s:" :
    229 	    "B:FNOS:T:Za:b:c:d:e:f:g:h:i:k:l:m:n:o:p:r:s:t:u:x:";
    230 	while ((ch = getopt(argc, argv, opstring)) != -1)
    231 		switch (ch) {
    232 		case 'B':
    233 			if (strcmp(optarg, "be") == 0) {
    234 #if BYTE_ORDER == LITTLE_ENDIAN
    235 				needswap = 1;
    236 #endif
    237 			} else if (strcmp(optarg, "le") == 0) {
    238 #if BYTE_ORDER == BIG_ENDIAN
    239 				needswap = 1;
    240 #endif
    241 			} else
    242 				usage();
    243 			break;
    244 		case 'F':
    245 			Fflag = 1;
    246 			break;
    247 		case 'N':
    248 			Nflag = 1;
    249 			break;
    250 		case 'O':
    251 			Oflag = 1;
    252 			break;
    253 		case 'S':
    254 			sectorsize = strsuftoi("sector size",
    255 			    optarg, 1, INT_MAX);
    256 			break;
    257 #ifdef COMPAT
    258 		case 'T':
    259 			disktype = optarg;
    260 			break;
    261 #endif
    262 		case 'Z':
    263 			Zflag = 1;
    264 			break;
    265 		case 'a':
    266 			maxcontig = strsuftoi("maximum contiguous blocks",
    267 			    optarg, 1, INT_MAX);
    268 			break;
    269 		case 'b':
    270 			bsize = strsuftoi("block size",
    271 			    optarg, MINBSIZE, INT_MAX);
    272 			break;
    273 		case 'c':
    274 			cpg = strsuftoi("cylinders per group",
    275 			    optarg, 1, INT_MAX);
    276 			cpgflg++;
    277 			break;
    278 		case 'd':
    279 			rotdelay = strsuftoi("rotational delay",
    280 			    optarg, 0, INT_MAX);
    281 			break;
    282 		case 'e':
    283 			maxbpg = strsuftoi(
    284 			    "blocks per file in a cylinder group",
    285 			    optarg, 1, INT_MAX);
    286 			break;
    287 		case 'f':
    288 			fsize = strsuftoi("fragment size",
    289 			    optarg, 1, INT_MAX);
    290 			break;
    291 		case 'g':
    292 			avgfilesize = strsuftoi("average file size",
    293 			    optarg, 1, INT_MAX);
    294 			break;
    295 		case 'h':
    296 			avgfpdir = strsuftoi("expected files per directory",
    297 			    optarg, 1, INT_MAX);
    298 			break;
    299 		case 'i':
    300 			density = strsuftoi("bytes per inode",
    301 			    optarg, 1, INT_MAX);
    302 			break;
    303 		case 'k':
    304 			trackskew = strsuftoi("track skew",
    305 			    optarg, 0, INT_MAX);
    306 			break;
    307 		case 'l':
    308 			interleave = strsuftoi("interleave",
    309 			    optarg, 1, INT_MAX);
    310 			break;
    311 		case 'm':
    312 			minfree = strsuftoi("free space %",
    313 			    optarg, 0, 99);
    314 			break;
    315 		case 'n':
    316 			nrpos = strsuftoi("rotational layout count",
    317 			    optarg, 1, INT_MAX);
    318 			break;
    319 		case 'o':
    320 			if (mfs)
    321 				getmntopts(optarg, mopts, &mntflags, 0);
    322 			else {
    323 				if (strcmp(optarg, "space") == 0)
    324 					opt = FS_OPTSPACE;
    325 				else if (strcmp(optarg, "time") == 0)
    326 					opt = FS_OPTTIME;
    327 				else
    328 				    errx(1, "%s %s",
    329 					"unknown optimization preference: ",
    330 					"use `space' or `time'.");
    331 			}
    332 			break;
    333 		case 'p':
    334 			trackspares = strsuftoi("spare sectors per track",
    335 			    optarg, 0, INT_MAX);
    336 			break;
    337 		case 'r':
    338 			rpm = strsuftoi("revolutions per minute",
    339 			    optarg, 1, INT_MAX);
    340 			break;
    341 		case 's':
    342 			llsize = strtoll(optarg, &endp, 10);
    343 			if (endp[0] != '\0' && endp[1] != '\0')
    344 				llsize = -1;
    345 			else {
    346 				int	ssiz;
    347 
    348 				ssiz = (sectorsize ? sectorsize : DFL_SECSIZE);
    349 				switch (tolower((unsigned char)endp[0])) {
    350 				case 'b':
    351 					llsize /= ssiz;
    352 					break;
    353 				case 'k':
    354 					llsize *= 1024 / ssiz;
    355 					break;
    356 				case 'm':
    357 					llsize *= 1024 * 1024 / ssiz;
    358 					break;
    359 				case 'g':
    360 					llsize *= 1024 * 1024 * 1024 / ssiz;
    361 					break;
    362 				case '\0':
    363 				case 's':
    364 					break;
    365 				default:
    366 					llsize = -1;
    367 				}
    368 			}
    369 			if (llsize > INT_MAX)
    370 				errx(1, "file system size `%s' is too large.",
    371 				    optarg);
    372 			if (llsize <= 0)
    373 				errx(1,
    374 			    "`%s' is not a valid number for file system size.",
    375 				    optarg);
    376 			fssize = (int)llsize;
    377 			break;
    378 		case 't':
    379 			ntracks = strsuftoi("total tracks",
    380 			    optarg, 1, INT_MAX);
    381 			break;
    382 		case 'u':
    383 			nsectors = strsuftoi("sectors per track",
    384 			    optarg, 1, INT_MAX);
    385 			break;
    386 		case 'x':
    387 			cylspares = strsuftoi("spare sectors per cylinder",
    388 			    optarg, 0, INT_MAX);
    389 			break;
    390 		case '?':
    391 		default:
    392 			usage();
    393 		}
    394 	argc -= optind;
    395 	argv += optind;
    396 
    397 	if (argc != 2 && (mfs || argc != 1))
    398 		usage();
    399 
    400 	special = argv[0];
    401 	if (Fflag || mfs) {
    402 		/*
    403 		 * it's a file system image or an MFS, so fake up a label.
    404 		 * XXX
    405 		 */
    406 		if (!sectorsize)
    407 			sectorsize = DFL_SECSIZE;
    408 
    409 		if (Fflag && !Nflag) {	/* creating image in a regular file */
    410 			if (fssize == 0)
    411 				errx(1, "need to specify size when using -F");
    412 			fso = open(special, O_RDWR | O_CREAT | O_TRUNC, 0777);
    413 			if (fso == -1)
    414 				err(1, "can't open file %s", special);
    415 			if ((fsi = dup(fso)) == -1)
    416 				err(1, "can't dup(2) image fd");
    417 		/* XXXLUKEM: only ftruncate() regular files ? */
    418 			if (ftruncate(fso, (off_t)fssize * sectorsize) == -1)
    419 				err(1, "can't resize %s to %d",
    420 				    special, fssize);
    421 
    422 			if (Zflag) {	/* pre-zero the file */
    423 				char	*buf;
    424 				int	bufsize, i;
    425 				off_t	bufrem;
    426 				struct statfs sfs;
    427 
    428 				if (fstatfs(fso, &sfs) == -1) {
    429 					warn("can't fstatfs `%s'", special);
    430 					bufsize = 8192;
    431 				} else
    432 					bufsize = sfs.f_iosize;
    433 
    434 				if ((buf = calloc(1, bufsize)) == NULL)
    435 					err(1, "can't malloc buffer of %d",
    436 					bufsize);
    437 				bufrem = fssize * sectorsize;
    438 				printf(
    439     "Creating file system image in `%s', size %lld bytes, in %d byte chunks.\n",
    440 				    special, (long long)bufrem, bufsize);
    441 				while (bufrem > 0) {
    442 					i = write(fso, buf,
    443 					    MIN(bufsize, bufrem));
    444 					if (i == -1)
    445 						err(1, "writing image");
    446 					bufrem -= i;
    447 				}
    448 			}
    449 
    450 		}
    451 
    452 		memset(&mfsfakelabel, 0, sizeof(mfsfakelabel));
    453 		mfsfakelabel.d_secsize = sectorsize;
    454 		mfsfakelabel.d_nsectors = 64;	/* these 3 add up to 16MB */
    455 		mfsfakelabel.d_ntracks = 16;
    456 		mfsfakelabel.d_ncylinders = 16;
    457 		mfsfakelabel.d_secpercyl =
    458 		    mfsfakelabel.d_nsectors * mfsfakelabel.d_ntracks;
    459 		mfsfakelabel.d_secperunit =
    460 		    mfsfakelabel.d_ncylinders * mfsfakelabel.d_secpercyl;
    461 		mfsfakelabel.d_rpm = 10000;
    462 		mfsfakelabel.d_interleave = 1;
    463 		mfsfakelabel.d_npartitions = 1;
    464 		mfsfakelabel.d_partitions[0].p_size = mfsfakelabel.d_secperunit;
    465 		mfsfakelabel.d_partitions[0].p_fsize = 1024;
    466 		mfsfakelabel.d_partitions[0].p_frag = 8;
    467 		mfsfakelabel.d_partitions[0].p_cpg = 16;
    468 
    469 		lp = &mfsfakelabel;
    470 		pp = &mfsfakelabel.d_partitions[0];
    471 
    472 	} else {	/* !Fflag && !mfs */
    473 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
    474 		special = device;
    475 		if (fsi < 0)
    476 			err(1, "%s: open for read", special);
    477 
    478 		if (Nflag) {
    479 			fso = -1;
    480 		} else {
    481 			fso = open(special, O_WRONLY);
    482 			if (fso < 0)
    483 				err(1, "%s: open for write", special);
    484 
    485 			/* Bail if target special is mounted */
    486 			n = getmntinfo(&mp, MNT_NOWAIT);
    487 			if (n == 0)
    488 				err(1, "%s: getmntinfo", special);
    489 
    490 			len = sizeof(_PATH_DEV) - 1;
    491 			s1 = special;
    492 			if (strncmp(_PATH_DEV, s1, len) == 0)
    493 				s1 += len;
    494 
    495 			while (--n >= 0) {
    496 				s2 = mp->f_mntfromname;
    497 				if (strncmp(_PATH_DEV, s2, len) == 0) {
    498 					s2 += len - 1;
    499 					*s2 = 'r';
    500 				}
    501 				if (strcmp(s1, s2) == 0 ||
    502 				    strcmp(s1, &s2[1]) == 0)
    503 					errx(1, "%s is mounted on %s",
    504 					    special, mp->f_mntonname);
    505 				++mp;
    506 			}
    507 		}
    508 		cp = strchr(argv[0], '\0') - 1;
    509 		if (cp == 0 || ((*cp < 'a' || *cp > ('a' + maxpartitions - 1))
    510 		    && !isdigit(*cp)))
    511 			errx(1, "can't figure out file system partition");
    512 #ifdef COMPAT
    513 		if (disktype == NULL)
    514 			disktype = argv[1];
    515 #endif
    516 		lp = getdisklabel(special, fsi);
    517 		if (isdigit(*cp))
    518 			pp = &lp->d_partitions[0];
    519 		else
    520 			pp = &lp->d_partitions[*cp - 'a'];
    521 		if (pp->p_size == 0)
    522 			errx(1, "`%c' partition is unavailable", *cp);
    523 		if (pp->p_fstype == FS_BOOT)
    524 			errx(1, "`%c' partition overlaps boot program", *cp);
    525 	}	/* !Fflag && !mfs */
    526 
    527 	if (fssize == 0)
    528 		fssize = pp->p_size;
    529 	if (fssize > pp->p_size && !mfs && !Fflag)
    530 		errx(1, "maximum file system size on the `%c' partition is %d",
    531 		    *cp, pp->p_size);
    532 	if (rpm == 0) {
    533 		rpm = lp->d_rpm;
    534 		if (rpm <= 0)
    535 			rpm = 3600;
    536 	}
    537 	if (ntracks == 0) {
    538 		ntracks = lp->d_ntracks;
    539 		if (ntracks <= 0)
    540 			errx(1, "no default #tracks");
    541 	}
    542 	if (nsectors == 0) {
    543 		nsectors = lp->d_nsectors;
    544 		if (nsectors <= 0)
    545 			errx(1, "no default #sectors/track");
    546 	}
    547 	if (sectorsize == 0) {
    548 		sectorsize = lp->d_secsize;
    549 		if (sectorsize <= 0)
    550 			errx(1, "no default sector size");
    551 	}
    552 	if (trackskew == -1) {
    553 		trackskew = lp->d_trackskew;
    554 		if (trackskew < 0)
    555 			trackskew = 0;
    556 	}
    557 	if (interleave == 0) {
    558 		interleave = lp->d_interleave;
    559 		if (interleave <= 0)
    560 			interleave = 1;
    561 	}
    562 	if (fsize == 0) {
    563 		fsize = pp->p_fsize;
    564 		if (fsize <= 0)
    565 			fsize = MAX(DFL_FRAGSIZE, lp->d_secsize);
    566 	}
    567 	if (bsize == 0) {
    568 		bsize = pp->p_frag * pp->p_fsize;
    569 		if (bsize <= 0)
    570 			bsize = MIN(DFL_BLKSIZE, 8 * fsize);
    571 	}
    572 	if (cpgflg == 0) {
    573 		if (pp->p_cpg != 0)
    574 			cpg = pp->p_cpg;
    575 	}
    576 	/*
    577 	 * Maxcontig sets the default for the maximum number of blocks
    578 	 * that may be allocated sequentially. With filesystem clustering
    579 	 * it is possible to allocate contiguous blocks up to the maximum
    580 	 * transfer size permitted by the controller or buffering.
    581 	 */
    582 	if (maxcontig == 0)
    583 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
    584 	if (density == 0)
    585 		density = NFPI * fsize;
    586 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
    587 		warnx("%s %s %d%%", "Warning: changing optimization to space",
    588 		    "because minfree is less than", MINFREE);
    589 		opt = FS_OPTSPACE;
    590 	}
    591 	if (trackspares == -1) {
    592 		trackspares = lp->d_sparespertrack;
    593 		if (trackspares < 0)
    594 			trackspares = 0;
    595 	}
    596 	nphyssectors = nsectors + trackspares;
    597 	if (cylspares == -1) {
    598 		cylspares = lp->d_sparespercyl;
    599 		if (cylspares < 0)
    600 			cylspares = 0;
    601 	}
    602 	secpercyl = nsectors * ntracks - cylspares;
    603 	if (secpercyl != lp->d_secpercyl)
    604 		warnx("%s (%d) %s (%u)\n",
    605 			"Warning: calculated sectors per cylinder", secpercyl,
    606 			"disagrees with disk label", lp->d_secpercyl);
    607 	if (maxbpg == 0)
    608 		maxbpg = MAXBLKPG(bsize);
    609 #ifdef notdef /* label may be 0 if faked up by kernel */
    610 	bbsize = lp->d_bbsize;
    611 	sbsize = lp->d_sbsize;
    612 #endif
    613 	oldpartition = *pp;
    614 	mkfs(pp, special, fsi, fso);
    615 	if (!Nflag && memcmp(pp, &oldpartition, sizeof(oldpartition)) && !Fflag)
    616 		rewritelabel(special, fso, lp);
    617 	if (!Nflag)
    618 		close(fso);
    619 	close(fsi);
    620 #ifdef MFS
    621 	if (mfs) {
    622 		struct mfs_args args;
    623 
    624 		switch (pid = fork()) {
    625 		case -1:
    626 			perror("mfs");
    627 			exit(10);
    628 		case 0:
    629 			(void)snprintf(mountfromname, sizeof(mountfromname),
    630 			    "mfs:%d", getpid());
    631 			break;
    632 		default:
    633 			(void)snprintf(mountfromname, sizeof(mountfromname),
    634 			    "mfs:%d", pid);
    635 			for (;;) {
    636 				/*
    637 				 * spin until the mount succeeds
    638 				 * or the child exits
    639 				 */
    640 				usleep(1);
    641 
    642 				/*
    643 				 * XXX Here is a race condition: another process
    644 				 * can mount a filesystem which hides our
    645 				 * ramdisk before we see the success.
    646 				 */
    647 				if (statfs(argv[1], &sf) < 0)
    648 					err(88, "statfs %s", argv[1]);
    649 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
    650 				    !strncmp(sf.f_mntonname, argv[1],
    651 					     MNAMELEN) &&
    652 				    !strcmp(sf.f_fstypename, "mfs"))
    653 					exit(0);
    654 
    655 				res = waitpid(pid, &status, WNOHANG);
    656 				if (res == -1)
    657 					err(11, "waitpid");
    658 				if (res != pid)
    659 					continue;
    660 				if (WIFEXITED(status)) {
    661 					if (WEXITSTATUS(status) == 0)
    662 						exit(0);
    663 					errx(1, "%s: mount: %s", argv[1],
    664 					     strerror(WEXITSTATUS(status)));
    665 				} else
    666 					errx(11, "abnormal termination");
    667 			}
    668 			/* NOTREACHED */
    669 		}
    670 
    671 		(void) setsid();
    672 		(void) close(0);
    673 		(void) close(1);
    674 		(void) close(2);
    675 		(void) chdir("/");
    676 
    677 		args.fspec = mountfromname;
    678 		args.export.ex_root = -2;
    679 		if (mntflags & MNT_RDONLY)
    680 			args.export.ex_flags = MNT_EXRDONLY;
    681 		else
    682 			args.export.ex_flags = 0;
    683 		args.base = membase;
    684 		args.size = fssize * sectorsize;
    685 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
    686 			exit(errno); /* parent prints message */
    687 	}
    688 #endif
    689 	exit(0);
    690 }
    691 
    692 #ifdef COMPAT
    693 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
    694 #else
    695 const char lmsg[] = "%s: can't read disk label";
    696 #endif
    697 
    698 static struct disklabel *
    699 getdisklabel(char *s, volatile int fd)
    700 /* XXX why is fs volatile?! */
    701 {
    702 	static struct disklabel lab;
    703 
    704 	if (ioctl(fd, DIOCGDINFO, &lab) < 0) {
    705 #ifdef COMPAT
    706 		if (disktype) {
    707 			struct disklabel *lp;
    708 
    709 			unlabeled++;
    710 			lp = getdiskbyname(disktype);
    711 			if (lp == NULL)
    712 				errx(1, "%s: unknown disk type", disktype);
    713 			return (lp);
    714 		}
    715 #endif
    716 		warn("ioctl (GDINFO)");
    717 		errx(1, lmsg, s);
    718 	}
    719 	return (&lab);
    720 }
    721 
    722 static void
    723 rewritelabel(char *s, volatile int fd, struct disklabel *lp)
    724 /* XXX why is fd volatile?! */
    725 {
    726 #ifdef COMPAT
    727 	if (unlabeled)
    728 		return;
    729 #endif
    730 	lp->d_checksum = 0;
    731 	lp->d_checksum = dkcksum(lp);
    732 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
    733 		warn("ioctl (WDINFO)");
    734 		errx(1, "%s: can't rewrite disk label", s);
    735 	}
    736 #if __vax__
    737 	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
    738 		int i;
    739 		int cfd;
    740 		daddr_t alt;
    741 		char specname[64];
    742 		char blk[1024];
    743 		char *cp;
    744 
    745 		/*
    746 		 * Make name for 'c' partition.
    747 		 */
    748 		strcpy(specname, s);
    749 		cp = specname + strlen(specname) - 1;
    750 		if (!isdigit(*cp))
    751 			*cp = 'c';
    752 		cfd = open(specname, O_WRONLY);
    753 		if (cfd < 0)
    754 			err(1, "%s: open", specname);
    755 		memset(blk, 0, sizeof(blk));
    756 		*(struct disklabel *)(blk + LABELOFFSET) = *lp;
    757 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
    758 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
    759 			off_t offset;
    760 
    761 			offset = alt + i;
    762 			offset *= lp->d_secsize;
    763 			if (lseek(cfd, offset, SEEK_SET) == -1)
    764 				err(1, "lseek to badsector area: ");
    765 			if (write(cfd, blk, lp->d_secsize) < lp->d_secsize)
    766 				warn("alternate label %d write", i/2);
    767 		}
    768 		close(cfd);
    769 	}
    770 #endif
    771 }
    772 
    773 static int
    774 strsuftoi(const char *desc, const char *arg, int min, int max)
    775 {
    776 	long long result;
    777 	char	*ep;
    778 
    779 	errno = 0;
    780 	result = strtoll(arg, &ep, 10);
    781 	if (ep[0] != '\0' && ep[1] != '\0')
    782 		errx(1, "%s `%s' is not a valid number.", desc, arg);
    783 	switch (tolower((unsigned char)ep[0])) {
    784 	case '\0':
    785 	case 'b':
    786 		break;
    787 	case 'k':
    788 		result <<= 10;
    789 		break;
    790 	case 'm':
    791 		result <<= 20;
    792 		break;
    793 	case 'g':
    794 		result <<= 30;
    795 		break;
    796 	default:
    797 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
    798 	}
    799 	if (result < min)
    800 		errx(1, "%s `%s' (%lld) is less than minimum (%d).",
    801 		    desc, arg, result, min);
    802 	if (result > max)
    803 		errx(1, "%s `%s' (%lld) is greater than maximum (%d).",
    804 		    desc, arg, result, max);
    805 	return ((int)result);
    806 }
    807 
    808 static void
    809 usage(void)
    810 {
    811 
    812 	if (mfs) {
    813 		fprintf(stderr,
    814 		    "usage: %s [ fsoptions ] special-device mount-point\n",
    815 			getprogname());
    816 	} else
    817 		fprintf(stderr,
    818 		    "usage: %s [ fsoptions ] special-device%s\n",
    819 		    getprogname(),
    820 #ifdef COMPAT
    821 		    " [device-type]");
    822 #else
    823 		    "");
    824 #endif
    825 	fprintf(stderr, "where fsoptions are:\n");
    826 	if (!mfs) {
    827 		fprintf(stderr,
    828 			"\t-B byteorder\tbyte order (`be' or `le')\n");
    829 		fprintf(stderr,
    830 			"\t-F\t\tcreate file system image in regular file\n");
    831 	}
    832 	fprintf(stderr, "\t-N\t\tdo not create file system, "
    833 			"just print out parameters\n");
    834 	if (!mfs) {
    835 		fprintf(stderr,
    836 			"\t-O\t\tcreate a 4.3BSD format filesystem\n");
    837 		fprintf(stderr,
    838 			"\t-S secsize\tsector size\n");
    839 	}
    840 #ifdef COMPAT
    841 	if (!mfs)
    842 		fprintf(stderr,
    843 			"\t-T disktype\tdisk type\n");
    844 #endif
    845 	if (!mfs)
    846 		fprintf(stderr,
    847 			"\t-Z\t\tpre-zero the image file (with -F)\n");
    848 	fprintf(stderr, "\t-a maxcontig\tmaximum contiguous blocks\n");
    849 	fprintf(stderr, "\t-b bsize\tblock size\n");
    850 	fprintf(stderr, "\t-c cpg\t\tcylinders/group\n");
    851 	fprintf(stderr, "\t-d rotdelay\trotational delay between "
    852 			"contiguous blocks\n");
    853 	fprintf(stderr, "\t-e maxbpg\tmaximum blocks per file "
    854 			"in a cylinder group\n");
    855 	fprintf(stderr, "\t-f fsize\tfragment size\n");
    856 	fprintf(stderr, "\t-g avgfilesize\taverage file size\n");
    857 	fprintf(stderr, "\t-h avgfpdir\taverage files per directory\n");
    858 	fprintf(stderr, "\t-i density\tnumber of bytes per inode\n");
    859 	if (!mfs) {
    860 		fprintf(stderr,
    861 			"\t-k trackskew\tsector 0 skew, per track\n");
    862 		fprintf(stderr,
    863 			"\t-l interleave\thardware sector interleave\n");
    864 	}
    865 	fprintf(stderr, "\t-m minfree\tminimum free space %%\n");
    866 	if (!mfs)
    867 		fprintf(stderr,
    868 			"\t-n nrpos\tnumber of distinguished "
    869 			"rotational positions\n");
    870 	fprintf(stderr, "\t-o optim\toptimization preference "
    871 			"(`space' or `time')\n");
    872 	if (!mfs)
    873 		fprintf(stderr,
    874 			"\t-p trackspares\tspare sectors per track\n");
    875 	fprintf(stderr, "\t-s fssize\tfile system size (sectors)\n");
    876 	if (!mfs) {
    877 		fprintf(stderr,
    878 			"\t-r rpm\t\trevolutions/minute\n");
    879 		fprintf(stderr,
    880 			"\t-t ntracks\ttracks/cylinder\n");
    881 		fprintf(stderr,
    882 			"\t-u nsectors\tsectors/track\n");
    883 		fprintf(stderr,
    884 			"\t-x cylspares\tspare sectors per cylinder\n");
    885 	}
    886 	exit(1);
    887 }
    888