Home | History | Annotate | Line # | Download | only in newfs
newfs.c revision 1.48
      1 /*	$NetBSD: newfs.c,v 1.48 2001/11/16 09:58:17 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.48 2001/11/16 09:58:17 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 && strcmp(special, "swap") == 0)) {
    402 		/*
    403 		 * it's a file system image, or an MFS mounted on "swap";
    404 		 * fake up a label.		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 = 3600;
    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 		goto havelabel;
    473 	}
    474 
    475 	fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
    476 	special = device;
    477 	if (fsi < 0)
    478 		err(1, "%s: open for read", special);
    479 
    480 	if (Nflag) {
    481 		fso = -1;
    482 	} else {
    483 		fso = open(special, O_WRONLY);
    484 		if (fso < 0)
    485 			err(1, "%s: open for write", special);
    486 
    487 		/* Bail if target special is mounted */
    488 		n = getmntinfo(&mp, MNT_NOWAIT);
    489 		if (n == 0)
    490 			err(1, "%s: getmntinfo", special);
    491 
    492 		len = sizeof(_PATH_DEV) - 1;
    493 		s1 = special;
    494 		if (strncmp(_PATH_DEV, s1, len) == 0)
    495 			s1 += len;
    496 
    497 		while (--n >= 0) {
    498 			s2 = mp->f_mntfromname;
    499 			if (strncmp(_PATH_DEV, s2, len) == 0) {
    500 				s2 += len - 1;
    501 				*s2 = 'r';
    502 			}
    503 			if (strcmp(s1, s2) == 0 || strcmp(s1, &s2[1]) == 0)
    504 				errx(1, "%s is mounted on %s",
    505 				    special, mp->f_mntonname);
    506 			++mp;
    507 		}
    508 	}
    509 	if (mfs && disktype != NULL) {
    510 		lp = (struct disklabel *)getdiskbyname(disktype);
    511 		if (lp == NULL)
    512 			errx(1, "%s: unknown disk type", disktype);
    513 		pp = &lp->d_partitions[1];
    514 	} else {
    515 		cp = strchr(argv[0], '\0') - 1;
    516 		if (cp == 0 || ((*cp < 'a' || *cp > ('a' + maxpartitions - 1))
    517 		    && !isdigit(*cp)))
    518 			errx(1, "can't figure out file system partition");
    519 #ifdef COMPAT
    520 		if (!mfs && disktype == NULL)
    521 			disktype = argv[1];
    522 #endif
    523 		lp = getdisklabel(special, fsi);
    524 		if (isdigit(*cp))
    525 			pp = &lp->d_partitions[0];
    526 		else
    527 			pp = &lp->d_partitions[*cp - 'a'];
    528 		if (pp->p_size == 0)
    529 			errx(1, "`%c' partition is unavailable", *cp);
    530 		if (pp->p_fstype == FS_BOOT)
    531 			errx(1, "`%c' partition overlaps boot program", *cp);
    532 	}
    533 
    534  havelabel:
    535 	if (fssize == 0)
    536 		fssize = pp->p_size;
    537 	if (fssize > pp->p_size && !mfs && !Fflag)
    538 		errx(1, "maximum file system size on the `%c' partition is %d",
    539 		    *cp, pp->p_size);
    540 	if (rpm == 0) {
    541 		rpm = lp->d_rpm;
    542 		if (rpm <= 0)
    543 			rpm = 3600;
    544 	}
    545 	if (ntracks == 0) {
    546 		ntracks = lp->d_ntracks;
    547 		if (ntracks <= 0)
    548 			errx(1, "no default #tracks");
    549 	}
    550 	if (nsectors == 0) {
    551 		nsectors = lp->d_nsectors;
    552 		if (nsectors <= 0)
    553 			errx(1, "no default #sectors/track");
    554 	}
    555 	if (sectorsize == 0) {
    556 		sectorsize = lp->d_secsize;
    557 		if (sectorsize <= 0)
    558 			errx(1, "no default sector size");
    559 	}
    560 	if (trackskew == -1) {
    561 		trackskew = lp->d_trackskew;
    562 		if (trackskew < 0)
    563 			trackskew = 0;
    564 	}
    565 	if (interleave == 0) {
    566 		interleave = lp->d_interleave;
    567 		if (interleave <= 0)
    568 			interleave = 1;
    569 	}
    570 	if (fsize == 0) {
    571 		fsize = pp->p_fsize;
    572 		if (fsize <= 0)
    573 			fsize = MAX(DFL_FRAGSIZE, lp->d_secsize);
    574 	}
    575 	if (bsize == 0) {
    576 		bsize = pp->p_frag * pp->p_fsize;
    577 		if (bsize <= 0)
    578 			bsize = MIN(DFL_BLKSIZE, 8 * fsize);
    579 	}
    580 	if (cpgflg == 0) {
    581 		if (pp->p_cpg != 0)
    582 			cpg = pp->p_cpg;
    583 	}
    584 	/*
    585 	 * Maxcontig sets the default for the maximum number of blocks
    586 	 * that may be allocated sequentially. With filesystem clustering
    587 	 * it is possible to allocate contiguous blocks up to the maximum
    588 	 * transfer size permitted by the controller or buffering.
    589 	 */
    590 	if (maxcontig == 0)
    591 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
    592 	if (density == 0)
    593 		density = NFPI * fsize;
    594 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
    595 		warnx("%s %s %d%%", "Warning: changing optimization to space",
    596 		    "because minfree is less than", MINFREE);
    597 		opt = FS_OPTSPACE;
    598 	}
    599 	if (trackspares == -1) {
    600 		trackspares = lp->d_sparespertrack;
    601 		if (trackspares < 0)
    602 			trackspares = 0;
    603 	}
    604 	nphyssectors = nsectors + trackspares;
    605 	if (cylspares == -1) {
    606 		cylspares = lp->d_sparespercyl;
    607 		if (cylspares < 0)
    608 			cylspares = 0;
    609 	}
    610 	secpercyl = nsectors * ntracks - cylspares;
    611 	if (secpercyl != lp->d_secpercyl)
    612 		warnx("%s (%d) %s (%u)\n",
    613 			"Warning: calculated sectors per cylinder", secpercyl,
    614 			"disagrees with disk label", lp->d_secpercyl);
    615 	if (maxbpg == 0)
    616 		maxbpg = MAXBLKPG(bsize);
    617 #ifdef notdef /* label may be 0 if faked up by kernel */
    618 	bbsize = lp->d_bbsize;
    619 	sbsize = lp->d_sbsize;
    620 #endif
    621 	oldpartition = *pp;
    622 	mkfs(pp, special, fsi, fso);
    623 	if (!Nflag && memcmp(pp, &oldpartition, sizeof(oldpartition)) && !Fflag)
    624 		rewritelabel(special, fso, lp);
    625 	if (!Nflag)
    626 		close(fso);
    627 	close(fsi);
    628 #ifdef MFS
    629 	if (mfs) {
    630 		struct mfs_args args;
    631 
    632 		switch (pid = fork()) {
    633 		case -1:
    634 			perror("mfs");
    635 			exit(10);
    636 		case 0:
    637 			(void)snprintf(mountfromname, sizeof(mountfromname),
    638 			    "mfs:%d", getpid());
    639 			break;
    640 		default:
    641 			(void)snprintf(mountfromname, sizeof(mountfromname),
    642 			    "mfs:%d", pid);
    643 			for (;;) {
    644 				/*
    645 				 * spin until the mount succeeds
    646 				 * or the child exits
    647 				 */
    648 				usleep(1);
    649 
    650 				/*
    651 				 * XXX Here is a race condition: another process
    652 				 * can mount a filesystem which hides our
    653 				 * ramdisk before we see the success.
    654 				 */
    655 				if (statfs(argv[1], &sf) < 0)
    656 					err(88, "statfs %s", argv[1]);
    657 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
    658 				    !strncmp(sf.f_mntonname, argv[1],
    659 					     MNAMELEN) &&
    660 				    !strcmp(sf.f_fstypename, "mfs"))
    661 					exit(0);
    662 
    663 				res = waitpid(pid, &status, WNOHANG);
    664 				if (res == -1)
    665 					err(11, "waitpid");
    666 				if (res != pid)
    667 					continue;
    668 				if (WIFEXITED(status)) {
    669 					if (WEXITSTATUS(status) == 0)
    670 						exit(0);
    671 					errx(1, "%s: mount: %s", argv[1],
    672 					     strerror(WEXITSTATUS(status)));
    673 				} else
    674 					errx(11, "abnormal termination");
    675 			}
    676 			/* NOTREACHED */
    677 		}
    678 
    679 		(void) setsid();
    680 		(void) close(0);
    681 		(void) close(1);
    682 		(void) close(2);
    683 		(void) chdir("/");
    684 
    685 		args.fspec = mountfromname;
    686 		args.export.ex_root = -2;
    687 		if (mntflags & MNT_RDONLY)
    688 			args.export.ex_flags = MNT_EXRDONLY;
    689 		else
    690 			args.export.ex_flags = 0;
    691 		args.base = membase;
    692 		args.size = fssize * sectorsize;
    693 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
    694 			exit(errno); /* parent prints message */
    695 	}
    696 #endif
    697 	exit(0);
    698 }
    699 
    700 #ifdef COMPAT
    701 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
    702 #else
    703 const char lmsg[] = "%s: can't read disk label";
    704 #endif
    705 
    706 static struct disklabel *
    707 getdisklabel(char *s, volatile int fd)
    708 /* XXX why is fs volatile?! */
    709 {
    710 	static struct disklabel lab;
    711 
    712 	if (ioctl(fd, DIOCGDINFO, &lab) < 0) {
    713 #ifdef COMPAT
    714 		if (disktype) {
    715 			struct disklabel *lp;
    716 
    717 			unlabeled++;
    718 			lp = getdiskbyname(disktype);
    719 			if (lp == NULL)
    720 				errx(1, "%s: unknown disk type", disktype);
    721 			return (lp);
    722 		}
    723 #endif
    724 		warn("ioctl (GDINFO)");
    725 		errx(1, lmsg, s);
    726 	}
    727 	return (&lab);
    728 }
    729 
    730 static void
    731 rewritelabel(char *s, volatile int fd, struct disklabel *lp)
    732 /* XXX why is fd volatile?! */
    733 {
    734 #ifdef COMPAT
    735 	if (unlabeled)
    736 		return;
    737 #endif
    738 	lp->d_checksum = 0;
    739 	lp->d_checksum = dkcksum(lp);
    740 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
    741 		warn("ioctl (WDINFO)");
    742 		errx(1, "%s: can't rewrite disk label", s);
    743 	}
    744 #if __vax__
    745 	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
    746 		int i;
    747 		int cfd;
    748 		daddr_t alt;
    749 		char specname[64];
    750 		char blk[1024];
    751 		char *cp;
    752 
    753 		/*
    754 		 * Make name for 'c' partition.
    755 		 */
    756 		strcpy(specname, s);
    757 		cp = specname + strlen(specname) - 1;
    758 		if (!isdigit(*cp))
    759 			*cp = 'c';
    760 		cfd = open(specname, O_WRONLY);
    761 		if (cfd < 0)
    762 			err(1, "%s: open", specname);
    763 		memset(blk, 0, sizeof(blk));
    764 		*(struct disklabel *)(blk + LABELOFFSET) = *lp;
    765 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
    766 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
    767 			off_t offset;
    768 
    769 			offset = alt + i;
    770 			offset *= lp->d_secsize;
    771 			if (lseek(cfd, offset, SEEK_SET) == -1)
    772 				err(1, "lseek to badsector area: ");
    773 			if (write(cfd, blk, lp->d_secsize) < lp->d_secsize)
    774 				warn("alternate label %d write", i/2);
    775 		}
    776 		close(cfd);
    777 	}
    778 #endif
    779 }
    780 
    781 static int
    782 strsuftoi(const char *desc, const char *arg, int min, int max)
    783 {
    784 	long long result;
    785 	char	*ep;
    786 
    787 	errno = 0;
    788 	result = strtoll(arg, &ep, 10);
    789 	if (ep[0] != '\0' && ep[1] != '\0')
    790 		errx(1, "%s `%s' is not a valid number.", desc, arg);
    791 	switch (tolower((unsigned char)ep[0])) {
    792 	case '\0':
    793 	case 'b':
    794 		break;
    795 	case 'k':
    796 		result <<= 10;
    797 		break;
    798 	case 'm':
    799 		result <<= 20;
    800 		break;
    801 	case 'g':
    802 		result <<= 30;
    803 		break;
    804 	default:
    805 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
    806 	}
    807 	if (result < min)
    808 		errx(1, "%s `%s' (%lld) is less than minimum (%d).",
    809 		    desc, arg, result, min);
    810 	if (result > max)
    811 		errx(1, "%s `%s' (%lld) is greater than maximum (%d).",
    812 		    desc, arg, result, max);
    813 	return ((int)result);
    814 }
    815 
    816 static void
    817 usage(void)
    818 {
    819 
    820 	if (mfs) {
    821 		fprintf(stderr,
    822 		    "usage: %s [ fsoptions ] special-device mount-point\n",
    823 			getprogname());
    824 	} else
    825 		fprintf(stderr,
    826 		    "usage: %s [ fsoptions ] special-device%s\n",
    827 		    getprogname(),
    828 #ifdef COMPAT
    829 		    " [device-type]");
    830 #else
    831 		    "");
    832 #endif
    833 	fprintf(stderr, "where fsoptions are:\n");
    834 	if (!mfs) {
    835 		fprintf(stderr,
    836 			"\t-B byteorder\tbyte order (`be' or `le')\n");
    837 		fprintf(stderr,
    838 			"\t-F\t\tcreate file system image in regular file\n");
    839 	}
    840 	fprintf(stderr, "\t-N\t\tdo not create file system, "
    841 			"just print out parameters\n");
    842 	if (!mfs) {
    843 		fprintf(stderr,
    844 			"\t-O\t\tcreate a 4.3BSD format filesystem\n");
    845 		fprintf(stderr,
    846 			"\t-S secsize\tsector size\n");
    847 	}
    848 #ifdef COMPAT
    849 	fprintf(stderr, "\t-T disktype\tdisk type\n");
    850 #endif
    851 	if (!mfs)
    852 		fprintf(stderr,
    853 			"\t-Z\t\tpre-zero the image file (with -F)\n");
    854 	fprintf(stderr, "\t-a maxcontig\tmaximum contiguous blocks\n");
    855 	fprintf(stderr, "\t-b bsize\tblock size\n");
    856 	fprintf(stderr, "\t-c cpg\t\tcylinders/group\n");
    857 	fprintf(stderr, "\t-d rotdelay\trotational delay between "
    858 			"contiguous blocks\n");
    859 	fprintf(stderr, "\t-e maxbpg\tmaximum blocks per file "
    860 			"in a cylinder group\n");
    861 	fprintf(stderr, "\t-f fsize\tfragment size\n");
    862 	fprintf(stderr, "\t-g average file size\n");
    863 	fprintf(stderr, "\t-h average files per directory\n");
    864 	fprintf(stderr, "\t-i density\tnumber of bytes per inode\n");
    865 	if (!mfs) {
    866 		fprintf(stderr,
    867 			"\t-k trackskew\tsector 0 skew, per track\n");
    868 		fprintf(stderr,
    869 			"\t-l interleave\thardware sector interleave\n");
    870 	}
    871 	fprintf(stderr, "\t-m minfree\tminimum free space %%\n");
    872 	if (!mfs)
    873 		fprintf(stderr,
    874 			"\t-n nrpos\tnumber of distinguished "
    875 			"rotational positions\n");
    876 	fprintf(stderr, "\t-o optim\toptimization preference "
    877 			"(`space' or `time')\n");
    878 	if (!mfs)
    879 		fprintf(stderr,
    880 			"\t-p trackspares\tspare sectors per track\n");
    881 	fprintf(stderr, "\t-s fssize\tfile system size (sectors)\n");
    882 	if (!mfs) {
    883 		fprintf(stderr,
    884 			"\t-r rpm\t\trevolutions/minute\n");
    885 		fprintf(stderr,
    886 			"\t-t ntracks\ttracks/cylinder\n");
    887 		fprintf(stderr,
    888 			"\t-u nsectors\tsectors/track\n");
    889 		fprintf(stderr,
    890 			"\t-x cylspares\tspare sectors per cylinder\n");
    891 	}
    892 	exit(1);
    893 }
    894