Home | History | Annotate | Line # | Download | only in newfs
newfs.c revision 1.85.2.1
      1 /*	$NetBSD: newfs.c,v 1.85.2.1 2007/03/03 23:06:16 bouyer 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.85.2.1 2007/03/03 23:06:16 bouyer 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  * Default file system size for "mount_mfs swap /dir" case.
    174  */
    175 #define	DFL_FSSIZE	(8 * 1024 * 1024)
    176 
    177 /*
    178  * MAXBLKPG determines the maximum number of data blocks which are
    179  * placed in a single cylinder group. The default is one indirect
    180  * block worth of data blocks.
    181  */
    182 #define	MAXBLKPG_UFS1(bsize)	((bsize) / sizeof(int32_t))
    183 #define	MAXBLKPG_UFS2(bsize)	((bsize) / sizeof(int64_t))
    184 
    185 /*
    186  * Each file system has a number of inodes statically allocated.
    187  * We allocate one inode slot per NFPI fragments, expecting this
    188  * to be far more than we will ever need.
    189  */
    190 #define	NFPI		4
    191 
    192 
    193 int	mfs;			/* run as the memory based filesystem */
    194 int	Nflag;			/* run without writing file system */
    195 int	Oflag = 1;		/* format as an 4.3BSD file system */
    196 int64_t	fssize;			/* file system size */
    197 int	sectorsize;		/* bytes/sector */
    198 int	fsize = 0;		/* fragment size */
    199 int	bsize = 0;		/* block size */
    200 int	maxbsize = 0;		/* maximum clustering */
    201 int	minfree = MINFREE;	/* free space threshold */
    202 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
    203 int	density;		/* number of bytes per inode */
    204 int	num_inodes;		/* number of inodes (overrides density) */
    205 int	maxcontig = 0;		/* max contiguous blocks to allocate */
    206 int	maxbpg;			/* maximum blocks per file in a cyl group */
    207 int	avgfilesize = AVFILESIZ;/* expected average file size */
    208 int	avgfpdir = AFPDIR;	/* expected number of files per directory */
    209 int	mntflags = MNT_ASYNC;	/* flags to be passed to mount */
    210 u_long	memleft;		/* virtual memory available */
    211 caddr_t	membase;		/* start address of memory based filesystem */
    212 int	needswap;		/* Filesystem not in native byte order */
    213 #ifdef COMPAT
    214 char	*disktype;
    215 int	unlabeled;
    216 #endif
    217 char *appleufs_volname = 0; /* Apple UFS volume name */
    218 int isappleufs = 0;
    219 
    220 char	device[MAXPATHLEN];
    221 
    222 int
    223 main(int argc, char *argv[])
    224 {
    225 	struct partition *pp = NULL;
    226 	struct disklabel *lp = NULL;
    227 	struct partition oldpartition;
    228 	struct statvfs *mp;
    229 	struct stat sb;
    230 	int ch, fsi, fso, len, n, Fflag, Iflag, Zflag;
    231 	uint ptn = 0;	/* gcc -Wuninitialised */
    232 	char *cp, *s1, *s2, *special;
    233 	const char *opstring;
    234 	int byte_sized = 0;
    235 #ifdef MFS
    236 	struct mfs_args args;
    237 	char mountfromname[100];
    238 	pid_t pid, res;
    239 	struct statvfs sf;
    240 	int status;
    241 #endif
    242 	mode_t mfsmode = 01777;	/* default mode for a /tmp-type directory */
    243 	uid_t mfsuid = 0;	/* user root */
    244 	gid_t mfsgid = 0;	/* group wheel */
    245 
    246 	cp = NULL;
    247 	fsi = fso = -1;
    248 	Fflag = Iflag = Zflag = 0;
    249 	if (strstr(getprogname(), "mfs")) {
    250 		mfs = 1;
    251 	} else {
    252 		/* Undocumented, for ease of testing */
    253 		if (argv[1] != NULL && !strcmp(argv[1], "-mfs")) {
    254 			argv++;
    255 			argc--;
    256 			mfs = 1;
    257 		}
    258 	}
    259 
    260 	opstring = mfs ?
    261 	    "NT:a:b:d:e:f:g:h:i:m:n:o:p:s:u:" :
    262 	    "B:FINO:S:T:Za:b:d:e:f:g:h:i:l:m:n:o:p:r:s:u:v:";
    263 	while ((ch = getopt(argc, argv, opstring)) != -1)
    264 		switch (ch) {
    265 		case 'B':
    266 			if (strcmp(optarg, "be") == 0) {
    267 #if BYTE_ORDER == LITTLE_ENDIAN
    268 				needswap = 1;
    269 #endif
    270 			} else if (strcmp(optarg, "le") == 0) {
    271 #if BYTE_ORDER == BIG_ENDIAN
    272 				needswap = 1;
    273 #endif
    274 			} else
    275 				usage();
    276 			break;
    277 		case 'F':
    278 			Fflag = 1;
    279 			break;
    280 		case 'I':
    281 			Iflag = 1;
    282 			break;
    283 		case 'N':
    284 			Nflag = 1;
    285 			break;
    286 		case 'O':
    287 			Oflag = strsuftoi64("format", optarg, 0, 2, NULL);
    288 			break;
    289 		case 'S':
    290 			sectorsize = strsuftoi64("sector size",
    291 			    optarg, 1, INT_MAX, NULL);
    292 			break;
    293 #ifdef COMPAT
    294 		case 'T':
    295 			disktype = optarg;
    296 			break;
    297 #endif
    298 		case 'Z':
    299 			Zflag = 1;
    300 			break;
    301 		case 'a':
    302 			maxcontig = strsuftoi64("maximum contiguous blocks",
    303 			    optarg, 1, INT_MAX, NULL);
    304 			break;
    305 		case 'b':
    306 			bsize = strsuftoi64("block size",
    307 			    optarg, MINBSIZE, MAXBSIZE, NULL);
    308 			break;
    309 		case 'd':
    310 			maxbsize = strsuftoi64("maximum extent size",
    311 			    optarg, 0, INT_MAX, NULL);
    312 			break;
    313 		case 'e':
    314 			maxbpg = strsuftoi64(
    315 			    "blocks per file in a cylinder group",
    316 			    optarg, 1, INT_MAX, NULL);
    317 			break;
    318 		case 'f':
    319 			fsize = strsuftoi64("fragment size",
    320 			    optarg, 1, MAXBSIZE, NULL);
    321 			break;
    322 		case 'g':
    323 			if (mfs)
    324 				mfsgid = mfs_group(optarg);
    325 			else {
    326 				avgfilesize = strsuftoi64("average file size",
    327 				    optarg, 1, INT_MAX, NULL);
    328 			}
    329 			break;
    330 		case 'h':
    331 			avgfpdir = strsuftoi64("expected files per directory",
    332 			    optarg, 1, INT_MAX, NULL);
    333 			break;
    334 		case 'i':
    335 			density = strsuftoi64("bytes per inode",
    336 			    optarg, 1, INT_MAX, NULL);
    337 			break;
    338 		case 'm':
    339 			minfree = strsuftoi64("free space %",
    340 			    optarg, 0, 99, NULL);
    341 			break;
    342 		case 'n':
    343 			num_inodes = strsuftoi64("number of inodes",
    344 			    optarg, 1, INT_MAX, NULL);
    345 			break;
    346 		case 'o':
    347 			if (mfs)
    348 				getmntopts(optarg, mopts, &mntflags, 0);
    349 			else {
    350 				if (strcmp(optarg, "space") == 0)
    351 					opt = FS_OPTSPACE;
    352 				else if (strcmp(optarg, "time") == 0)
    353 					opt = FS_OPTTIME;
    354 				else
    355 				    errx(1, "%s %s",
    356 					"unknown optimization preference: ",
    357 					"use `space' or `time'.");
    358 			}
    359 			break;
    360 		case 'p':
    361 			if (mfs) {
    362 				if ((mfsmode = strtol(optarg, NULL, 8)) <= 0)
    363 					errx(1, "bad mode `%s'", optarg);
    364 			} else
    365 				errx(1, "unknown option 'p'");
    366 			break;
    367 		case 's':
    368 			fssize = strsuftoi64("file system size",
    369 			    optarg, INT64_MIN, INT64_MAX, &byte_sized);
    370 			break;
    371 		case 'u':
    372 			if (mfs)
    373 				mfsuid = mfs_user(optarg);
    374 			else
    375 				errx(1, "deprecated option 'u'");
    376 			break;
    377 		case 'v':
    378 			appleufs_volname = optarg;
    379 			if (strchr(appleufs_volname, ':') || strchr(appleufs_volname, '/'))
    380 				errx(1,"Apple UFS volume name cannot contain ':' or '/'");
    381 			if (appleufs_volname[0] == '\0')
    382 				errx(1,"Apple UFS volume name cannot be zero length");
    383 			isappleufs = 1;
    384 			break;
    385 		case '?':
    386 		default:
    387 			usage();
    388 		}
    389 	argc -= optind;
    390 	argv += optind;
    391 
    392 #ifdef MFS
    393 	/* This is enough to get through the correct kernel code paths */
    394 	memset(&args, 0, sizeof args);
    395 	args.fspec = mountfromname;
    396 	if (mntflags & (MNT_GETARGS | MNT_UPDATE)) {
    397 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
    398 			err(1, "mount `%s' failed", argv[1]);
    399 		if (mntflags & MNT_GETARGS)
    400 			printf("base=%p, size=%ld\n", args.base, args.size);
    401 		exit(0);
    402 	}
    403 #endif
    404 
    405 	if (argc != 2 && (mfs || argc != 1))
    406 		usage();
    407 
    408 	memset(&oldpartition, 0, sizeof oldpartition);
    409 	memset(&sb, 0, sizeof sb);
    410 	special = argv[0];
    411 	if (Fflag || mfs) {
    412 		/*
    413 		 * It's a file system image or an MFS,
    414 		 * no label, use fixed default for sectorsize.
    415 		 */
    416 		if (sectorsize == 0)
    417 			sectorsize = DFL_SECSIZE;
    418 
    419 		if (mfs) {
    420 			/*
    421 			 * Default filesystem size to that of supplied device,
    422 			 * and fall back to 8M
    423 			 */
    424 			if (fssize == 0)
    425 				if (stat(special, &sb) == -1)
    426 					fssize = DFL_FSSIZE / sectorsize;
    427 		} else {
    428 			/* creating image in a regular file */
    429 			int fl;
    430 			if (Nflag)
    431 				fl = O_RDONLY;
    432 			else {
    433 				if (fssize > 0)
    434 					fl = O_RDWR | O_CREAT;
    435 				else
    436 					fl = O_RDWR;
    437 			}
    438 			fsi = open(special, fl, 0777);
    439 			if (fsi == -1)
    440 				err(1, "can't open file %s", special);
    441 			if (fstat(fsi, &sb) == -1)
    442 				err(1, "can't fstat opened %s", special);
    443 			if (!Nflag)
    444 				fso = fsi;
    445 		}
    446 	} else {	/* !Fflag && !mfs */
    447 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
    448 		special = device;
    449 		if (fsi < 0 || fstat(fsi, &sb) == -1)
    450 			err(1, "%s: open for read", special);
    451 
    452 		if (!Nflag) {
    453 			fso = open(special, O_WRONLY, 0);
    454 			if (fso < 0)
    455 				err(1, "%s: open for write", special);
    456 
    457 			/* Bail if target special is mounted */
    458 			n = getmntinfo(&mp, MNT_NOWAIT);
    459 			if (n == 0)
    460 				err(1, "%s: getmntinfo", special);
    461 
    462 			len = sizeof(_PATH_DEV) - 1;
    463 			s1 = special;
    464 			if (strncmp(_PATH_DEV, s1, len) == 0)
    465 				s1 += len;
    466 
    467 			while (--n >= 0) {
    468 				s2 = mp->f_mntfromname;
    469 				if (strncmp(_PATH_DEV, s2, len) == 0) {
    470 					s2 += len - 1;
    471 					*s2 = 'r';
    472 				}
    473 				if (strcmp(s1, s2) == 0 ||
    474 				    strcmp(s1, &s2[1]) == 0)
    475 					errx(1, "%s is mounted on %s",
    476 					    special, mp->f_mntonname);
    477 				++mp;
    478 			}
    479 		}
    480 
    481 #ifdef COMPAT
    482 		if (disktype == NULL)
    483 			disktype = argv[1];
    484 #endif
    485 		lp = getdisklabel(special, fsi);
    486 		if (sectorsize == 0) {
    487 			sectorsize = lp->d_secsize;
    488 			if (sectorsize <= 0)
    489 				errx(1, "no default sector size");
    490 		}
    491 
    492 		ptn = strchr(special, '\0')[-1] - 'a';
    493 		if (ptn < lp->d_npartitions && ptn == DISKPART(sb.st_rdev)) {
    494 			/* Assume partition really does match the label */
    495 			pp = &lp->d_partitions[ptn];
    496 			oldpartition = *pp;
    497 			if (pp->p_size == 0)
    498 				errx(1, "`%c' partition is unavailable",
    499 					'a' + ptn);
    500 			if (pp->p_fstype == FS_APPLEUFS)
    501 				isappleufs = 1;
    502 			if (!Iflag) {
    503 				if (isappleufs) {
    504 					if (pp->p_fstype != FS_APPLEUFS)
    505 						errx(1, "`%c' partition type is not `Apple UFS'", 'a' + ptn);
    506 				} else {
    507 					if (pp->p_fstype != FS_BSDFFS)
    508 						errx(1, "`%c' partition type is not `4.2BSD'", 'a' + ptn);
    509 				}
    510 			}
    511 		}
    512 	}	/* !Fflag && !mfs */
    513 
    514 	if (byte_sized)
    515 		fssize /= sectorsize;
    516 	if (fssize <= 0) {
    517 		if (sb.st_size != 0)
    518 			fssize += sb.st_size / sectorsize;
    519 		else
    520 			fssize += oldpartition.p_size;
    521 		if (fssize <= 0)
    522 			errx(1, "Unable to determine file system size");
    523 	}
    524 
    525 	if (pp != NULL && fssize > pp->p_size)
    526 		errx(1, "maximum file system size on `%s' is %d sectors",
    527 		    special, pp->p_size);
    528 
    529 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
    530 	if (Fflag && fso != -1
    531 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
    532 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
    533 
    534 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparce) the file */
    535 		char	*buf;
    536 		int	bufsize, i;
    537 		off_t	bufrem;
    538 		struct statvfs sfs;
    539 
    540 		if (fstatvfs(fso, &sfs) == -1) {
    541 			warn("can't fstatvfs `%s'", special);
    542 			bufsize = 8192;
    543 		} else
    544 			bufsize = sfs.f_iosize;
    545 
    546 		if ((buf = calloc(1, bufsize)) == NULL)
    547 			err(1, "can't malloc buffer of %d",
    548 			bufsize);
    549 		bufrem = fssize * sectorsize;
    550 		printf(
    551     "Creating file system image in `%s', size %lld bytes, in %d byte chunks.\n",
    552 		    special, (long long)bufrem, bufsize);
    553 		while (bufrem > 0) {
    554 			i = write(fso, buf, MIN(bufsize, bufrem));
    555 			if (i == -1)
    556 				err(1, "writing image");
    557 			bufrem -= i;
    558 		}
    559 		free(buf);
    560 	}
    561 
    562 	/* Sort out fragment and block sizes */
    563 	if (fsize == 0) {
    564 		fsize = bsize / DFL_FRAG_BLK;
    565 		if (fsize == 0)
    566 			fsize = oldpartition.p_fsize;
    567 		if (fsize <= 0) {
    568 			if (isappleufs) {
    569 				fsize = APPLEUFS_DFL_FRAGSIZE;
    570 			} else {
    571 				if (fssize < SMALL_FSSIZE)
    572 					fsize = S_DFL_FRAGSIZE;
    573 				else if (fssize < MEDIUM_FSSIZE)
    574 					fsize = M_DFL_FRAGSIZE;
    575 				else
    576 					fsize = L_DFL_FRAGSIZE;
    577 				if (fsize < sectorsize)
    578 					fsize = sectorsize;
    579 			}
    580 		}
    581 	}
    582 	if (bsize == 0) {
    583 		bsize = oldpartition.p_frag * oldpartition.p_fsize;
    584 		if (bsize <= 0) {
    585 			if (isappleufs)
    586 				bsize = APPLEUFS_DFL_BLKSIZE;
    587 			else
    588 				bsize = DFL_FRAG_BLK * fsize;
    589 		}
    590 	}
    591 
    592 	if (isappleufs && (fsize < APPLEUFS_DFL_FRAGSIZE)) {
    593 		warnx("Warning: chosen fsize of %d is less than Apple UFS minimum of %d",
    594 			fsize, APPLEUFS_DFL_FRAGSIZE);
    595 	}
    596 	if (isappleufs && (bsize > APPLEUFS_DFL_BLKSIZE)) {
    597 		warnx("Warning: chosen bsize of %d is greater than Apple UFS maximum of %d",
    598 			bsize, APPLEUFS_DFL_BLKSIZE);
    599 	}
    600 
    601 	/*
    602 	 * Maxcontig sets the default for the maximum number of blocks
    603 	 * that may be allocated sequentially. With filesystem clustering
    604 	 * it is possible to allocate contiguous blocks up to the maximum
    605 	 * transfer size permitted by the controller or buffering.
    606 	 */
    607 	if (maxcontig == 0)
    608 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
    609 	if (density == 0)
    610 		density = NFPI * fsize;
    611 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
    612 		warnx("%s %s %d%%", "Warning: changing optimization to space",
    613 		    "because minfree is less than", MINFREE);
    614 		opt = FS_OPTSPACE;
    615 	}
    616 	if (maxbpg == 0) {
    617 		if (Oflag <= 1)
    618 			maxbpg = MAXBLKPG_UFS1(bsize);
    619 		else
    620 			maxbpg = MAXBLKPG_UFS2(bsize);
    621 	}
    622 	mkfs(pp, special, fsi, fso, mfsmode, mfsuid, mfsgid);
    623 	if (!Nflag && pp != NULL
    624 	    && memcmp(pp, &oldpartition, sizeof(oldpartition)))
    625 		rewritelabel(special, fso, lp);
    626 	if (fsi != -1 && fsi != fso)
    627 		close(fsi);
    628 	if (fso != -1)
    629 		close(fso);
    630 #ifdef MFS
    631 	if (mfs) {
    632 
    633 		switch (pid = fork()) {
    634 		case -1:
    635 			perror("mfs");
    636 			exit(10);
    637 		case 0:
    638 			(void)snprintf(mountfromname, sizeof(mountfromname),
    639 			    "mfs:%d", getpid());
    640 			break;
    641 		default:
    642 			(void)snprintf(mountfromname, sizeof(mountfromname),
    643 			    "mfs:%d", pid);
    644 			for (;;) {
    645 				/*
    646 				 * spin until the mount succeeds
    647 				 * or the child exits
    648 				 */
    649 				usleep(1);
    650 
    651 				/*
    652 				 * XXX Here is a race condition: another process
    653 				 * can mount a filesystem which hides our
    654 				 * ramdisk before we see the success.
    655 				 */
    656 				if (statvfs(argv[1], &sf) < 0)
    657 					err(88, "statvfs %s", argv[1]);
    658 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
    659 				    !strncmp(sf.f_mntonname, argv[1],
    660 					     MNAMELEN) &&
    661 				    !strcmp(sf.f_fstypename, "mfs"))
    662 					exit(0);
    663 
    664 				res = waitpid(pid, &status, WNOHANG);
    665 				if (res == -1)
    666 					err(11, "waitpid");
    667 				if (res != pid)
    668 					continue;
    669 				if (WIFEXITED(status)) {
    670 					if (WEXITSTATUS(status) == 0)
    671 						exit(0);
    672 					errx(1, "%s: mount: %s", argv[1],
    673 					     strerror(WEXITSTATUS(status)));
    674 				} else
    675 					errx(11, "abnormal termination");
    676 			}
    677 			/* NOTREACHED */
    678 		}
    679 
    680 		(void) setsid();
    681 		(void) close(0);
    682 		(void) close(1);
    683 		(void) close(2);
    684 		(void) chdir("/");
    685 
    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, int fd)
    708 {
    709 	static struct disklabel lab;
    710 
    711 #ifdef COMPAT
    712 	if (disktype) {
    713 		struct disklabel *lp;
    714 
    715 		unlabeled++;
    716 		lp = getdiskbyname(disktype);
    717 		if (lp == NULL)
    718 			errx(1, "%s: unknown disk type", disktype);
    719 		return (lp);
    720 	}
    721 #endif
    722 	if (ioctl(fd, DIOCGDINFO, &lab) < 0) {
    723 		warn("ioctl (GDINFO)");
    724 		errx(1, lmsg, s);
    725 	}
    726 	return (&lab);
    727 }
    728 
    729 static void
    730 rewritelabel(char *s, int fd, struct disklabel *lp)
    731 {
    732 #ifdef COMPAT
    733 	if (unlabeled)
    734 		return;
    735 #endif
    736 	lp->d_checksum = 0;
    737 	lp->d_checksum = dkcksum(lp);
    738 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
    739 		if (errno == ESRCH)
    740 			return;
    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 		off_t loff;
    750 		char specname[64];
    751 		char blk[1024];
    752 		char *cp;
    753 
    754 		/*
    755 		 * Make name for 'c' partition.
    756 		 */
    757 		strlcpy(specname, s, sizeof(specname));
    758 		cp = specname + strlen(specname) - 1;
    759 		if (!isdigit((unsigned char)*cp))
    760 			*cp = 'c';
    761 		cfd = open(specname, O_WRONLY);
    762 		if (cfd < 0)
    763 			err(1, "%s: open", specname);
    764 		if ((loff = getlabeloffset()) < 0)
    765 			err(1, "getlabeloffset()");
    766 		memset(blk, 0, sizeof(blk));
    767 		*(struct disklabel *)(blk + loff) = *lp;
    768 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
    769 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
    770 			off_t offset;
    771 
    772 			offset = alt + i;
    773 			offset *= lp->d_secsize;
    774 			if (lseek(cfd, offset, SEEK_SET) == -1)
    775 				err(1, "lseek to badsector area: ");
    776 			if (write(cfd, blk, lp->d_secsize) < lp->d_secsize)
    777 				warn("alternate label %d write", i/2);
    778 		}
    779 		close(cfd);
    780 	}
    781 #endif
    782 }
    783 
    784 static gid_t
    785 mfs_group(const char *gname)
    786 {
    787 	struct group *gp;
    788 
    789 	if (!(gp = getgrnam(gname)) && !isdigit((unsigned char)*gname))
    790 		errx(1, "unknown gname %s", gname);
    791 	return gp ? gp->gr_gid : atoi(gname);
    792 }
    793 
    794 static uid_t
    795 mfs_user(const char *uname)
    796 {
    797 	struct passwd *pp;
    798 
    799 	if (!(pp = getpwnam(uname)) && !isdigit((unsigned char)*uname))
    800 		errx(1, "unknown user %s", uname);
    801 	return pp ? pp->pw_uid : atoi(uname);
    802 }
    803 
    804 static int64_t
    805 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
    806 {
    807 	int64_t result, r1;
    808 	int shift = 0;
    809 	char	*ep;
    810 
    811 	errno = 0;
    812 	r1 = strtoll(arg, &ep, 10);
    813 	if (ep[0] != '\0' && ep[1] != '\0')
    814 		errx(1, "%s `%s' is not a valid number.", desc, arg);
    815 	switch (ep[0]) {
    816 	case '\0':
    817 	case 's': case 'S':
    818 		if (num_suffix != NULL)
    819 			*num_suffix = 0;
    820 		break;
    821 	case 'g': case 'G':
    822 		shift += 10;
    823 		/* FALLTHROUGH */
    824 	case 'm': case 'M':
    825 		shift += 10;
    826 		/* FALLTHROUGH */
    827 	case 'k': case 'K':
    828 		shift += 10;
    829 		/* FALLTHROUGH */
    830 	case 'b': case 'B':
    831 		if (num_suffix != NULL)
    832 			*num_suffix = 1;
    833 		break;
    834 	default:
    835 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
    836 	}
    837 	result = r1 << shift;
    838 	if (errno == ERANGE || result >> shift != r1)
    839 		errx(1, "%s `%s' is too large to convert.", desc, arg);
    840 	if (result < min)
    841 		errx(1, "%s `%s' (%" PRId64 ") is less than the minimum (%" PRId64 ").",
    842 		    desc, arg, result, min);
    843 	if (result > max)
    844 		errx(1, "%s `%s' (%" PRId64 ") is greater than the maximum (%" PRId64 ").",
    845 		    desc, arg, result, max);
    846 	return result;
    847 }
    848 
    849 #define	NEWFS		1
    850 #define	MFS_MOUNT	2
    851 #define	BOTH		NEWFS | MFS_MOUNT
    852 
    853 struct help_strings {
    854 	int flags;
    855 	const char *str;
    856 } const help_strings[] = {
    857 	{ NEWFS,	"-B byteorder\tbyte order (`be' or `le')" },
    858 	{ NEWFS,	"-F \t\tcreate file system image in regular file" },
    859 	{ NEWFS,	"-I \t\tdo not check that the file system type is '4.2BSD'" },
    860 	{ BOTH,		"-N \t\tdo not create file system, just print out "
    861 			    "parameters" },
    862 	{ NEWFS,	"-O N\t\tfilesystem format: 0 ==> 4.3BSD, 1 ==> FFS, 2 ==> UFS2" },
    863 	{ NEWFS,	"-S secsize\tsector size" },
    864 #ifdef COMPAT
    865 	{ NEWFS,	"-T disktype\tdisk type" },
    866 #endif
    867 	{ NEWFS,	"-Z \t\tpre-zero the image file" },
    868 	{ BOTH,		"-a maxcontig\tmaximum contiguous blocks" },
    869 	{ BOTH,		"-b bsize\tblock size" },
    870 	{ BOTH,		"-d maxbsize\tmaximum extent size" },
    871 	{ BOTH,		"-e maxbpg\tmaximum blocks per file in a cylinder group"
    872 			    },
    873 	{ BOTH,		"-f fsize\tfrag size" },
    874 	{ NEWFS,	"-g avgfilesize\taverage file size" },
    875 	{ MFS_MOUNT,	"-g groupname\tgroup name of mount point" },
    876 	{ BOTH,		"-h avgfpdir\taverage files per directory" },
    877 	{ BOTH,		"-i density\tnumber of bytes per inode" },
    878 	{ BOTH,		"-m minfree\tminimum free space %%" },
    879 	{ BOTH,		"-n inodes\tnumber of inodes (overrides -i density)" },
    880 	{ BOTH,		"-o optim\toptimization preference (`space' or `time')"
    881 			    },
    882 	{ MFS_MOUNT,	"-p perm\t\tpermissions (in octal)" },
    883 	{ BOTH,		"-s fssize\tfile system size (sectors)" },
    884 	{ MFS_MOUNT,	"-u username\tuser name of mount point" },
    885 	{ NEWFS,	"-v volname\tApple UFS volume name" },
    886 	{ 0, NULL }
    887 };
    888 
    889 static void
    890 usage(void)
    891 {
    892 	int match;
    893 	const struct help_strings *hs;
    894 
    895 	if (mfs) {
    896 		fprintf(stderr,
    897 		    "usage: %s [ fsoptions ] special-device mount-point\n",
    898 			getprogname());
    899 	} else
    900 		fprintf(stderr,
    901 		    "usage: %s [ fsoptions ] special-device%s\n",
    902 		    getprogname(),
    903 #ifdef COMPAT
    904 		    " [disk-type]");
    905 #else
    906 		    "");
    907 #endif
    908 	fprintf(stderr, "where fsoptions are:\n");
    909 
    910 	match = mfs ? MFS_MOUNT : NEWFS;
    911 	for (hs = help_strings; hs->flags != 0; hs++)
    912 		if (hs->flags & match)
    913 			fprintf(stderr, "\t%s\n", hs->str);
    914 	exit(1);
    915 }
    916