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