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