Home | History | Annotate | Line # | Download | only in newfs
newfs.c revision 1.97
      1 /*	$NetBSD: newfs.c,v 1.97 2007/04/28 02:56:32 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.97 2007/04/28 02:56:32 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/disk.h>
     92 #include <sys/file.h>
     93 #include <sys/mount.h>
     94 #include <sys/sysctl.h>
     95 #include <sys/wait.h>
     96 
     97 #include <ufs/ufs/dir.h>
     98 #include <ufs/ufs/dinode.h>
     99 #include <ufs/ufs/ufsmount.h>
    100 #include <ufs/ffs/fs.h>
    101 
    102 #include <ctype.h>
    103 #include <disktab.h>
    104 #include <err.h>
    105 #include <errno.h>
    106 #include <grp.h>
    107 #include <limits.h>
    108 #include <paths.h>
    109 #include <pwd.h>
    110 #include <signal.h>
    111 #include <stdint.h>
    112 #include <stdio.h>
    113 #include <stdlib.h>
    114 #include <string.h>
    115 #include <syslog.h>
    116 #include <unistd.h>
    117 #include <util.h>
    118 #include <mntopts.h>
    119 
    120 #include "dkcksum.h"
    121 #include "extern.h"
    122 #include "partutil.h"
    123 
    124 struct mntopt mopts[] = {
    125 	MOPT_STDOPTS,
    126 	MOPT_ASYNC,
    127 	MOPT_UPDATE,
    128 	MOPT_GETARGS,
    129 	MOPT_NOATIME,
    130 	{ .m_option = NULL },
    131 };
    132 
    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) __attribute__((__noreturn__));
    137 
    138 #define	COMPAT			/* allow non-labeled disks */
    139 
    140 #ifdef COMPAT
    141 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
    142 #else
    143 const char lmsg[] = "%s: can't read disk label";
    144 #endif
    145 
    146 /*
    147  * The following two constants set the default block and fragment sizes.
    148  * Both constants must be a power of 2 and meet the following constraints:
    149  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
    150  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
    151  *	DESBLKSIZE / DESFRAGSIZE <= 8
    152  */
    153 /*
    154  * For file systems smaller than SMALL_FSSIZE we use the S_DFL_* defaults,
    155  * otherwise if less than MEDIUM_FSSIZE use M_DFL_*, otherwise use
    156  * L_DFL_*.
    157  */
    158 #define	SMALL_FSSIZE	(20*1024*2)
    159 #define	S_DFL_FRAGSIZE	512
    160 #define	MEDIUM_FSSIZE	(1000*1024*2)
    161 #define	M_DFL_FRAGSIZE	1024
    162 #define	L_DFL_FRAGSIZE	2048
    163 #define	DFL_FRAG_BLK	8
    164 
    165 /* Apple requires the fragment size to be at least APPLEUFS_DIRBLKSIZ
    166  * but the block size cannot be larger than Darwin's PAGE_SIZE.  See
    167  * the mount check in Darwin's ffs_mountfs for an explanation.
    168  */
    169 #define APPLEUFS_DFL_FRAGSIZE APPLEUFS_DIRBLKSIZ /* 1024 */
    170 #define APPLEUFS_DFL_BLKSIZE 4096 /* default Darwin PAGE_SIZE */
    171 
    172 /*
    173  * Default sector size.
    174  */
    175 #define	DFL_SECSIZE	512
    176 
    177 /*
    178  * Default file system size for "mount_mfs swap /dir" case.
    179  */
    180 #define	DFL_FSSIZE	(8 * 1024 * 1024)
    181 
    182 /*
    183  * MAXBLKPG determines the maximum number of data blocks which are
    184  * placed in a single cylinder group. The default is one indirect
    185  * block worth of data blocks.
    186  */
    187 #define	MAXBLKPG_UFS1(bsize)	((bsize) / sizeof(int32_t))
    188 #define	MAXBLKPG_UFS2(bsize)	((bsize) / sizeof(int64_t))
    189 
    190 /*
    191  * Each file system has a number of inodes statically allocated.
    192  * We allocate one inode slot per NFPI fragments, expecting this
    193  * to be far more than we will ever need.
    194  */
    195 #define	NFPI		4
    196 
    197 
    198 int	mfs;			/* run as the memory based filesystem */
    199 int	Nflag;			/* run without writing file system */
    200 int	Oflag = 1;		/* format as an 4.3BSD file system */
    201 int	verbosity;		/* amount of printf() output */
    202 #define DEFAULT_VERBOSITY 3	/* 4 is traditional behavior */
    203 int64_t	fssize;			/* file system size */
    204 int	sectorsize;		/* bytes/sector */
    205 int	fsize = 0;		/* fragment size */
    206 int	bsize = 0;		/* block size */
    207 int	maxbsize = 0;		/* maximum clustering */
    208 int	minfree = MINFREE;	/* free space threshold */
    209 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
    210 int	density;		/* number of bytes per inode */
    211 int	num_inodes;		/* number of inodes (overrides density) */
    212 int	maxcontig = 0;		/* max contiguous blocks to allocate */
    213 int	maxbpg;			/* maximum blocks per file in a cyl group */
    214 int	avgfilesize = AVFILESIZ;/* expected average file size */
    215 int	avgfpdir = AFPDIR;	/* expected number of files per directory */
    216 int	mntflags = 0;		/* flags to be passed to mount */
    217 u_long	memleft;		/* virtual memory available */
    218 caddr_t	membase;		/* start address of memory based filesystem */
    219 int	needswap;		/* Filesystem not in native byte order */
    220 char	*disktype = NULL;
    221 int	unlabeled;
    222 char *appleufs_volname = 0; /* Apple UFS volume name */
    223 int isappleufs = 0;
    224 
    225 char	device[MAXPATHLEN];
    226 
    227 int
    228 main(int argc, char *argv[])
    229 {
    230 	struct disk_geom geo;
    231 	struct dkwedge_info dkw;
    232 	struct statvfs *mp;
    233 	struct stat sb;
    234 	int ch, fsi, fso, len, n, Fflag, Iflag, Zflag;
    235 	char *cp, *s1, *s2, *special;
    236 	const char *opstring;
    237 	int byte_sized = 0;
    238 #ifdef MFS
    239 	struct mfs_args args;
    240 	char mountfromname[100];
    241 	pid_t pid, res;
    242 	struct statvfs sf;
    243 	int status;
    244 #endif
    245 	mode_t mfsmode = 01777;	/* default mode for a /tmp-type directory */
    246 	uid_t mfsuid = 0;	/* user root */
    247 	gid_t mfsgid = 0;	/* group wheel */
    248 	mntoptparse_t mo;
    249 
    250 	cp = NULL;
    251 	fsi = fso = -1;
    252 	Fflag = Iflag = Zflag = 0;
    253 	verbosity = -1;
    254 	if (strstr(getprogname(), "mfs")) {
    255 		mfs = 1;
    256 	} else {
    257 		/* Undocumented, for ease of testing */
    258 		if (argv[1] != NULL && !strcmp(argv[1], "-mfs")) {
    259 			argv++;
    260 			argc--;
    261 			mfs = 1;
    262 		}
    263 	}
    264 
    265 	opstring = mfs ?
    266 	    "NT:V:a:b:d:e:f:g:h:i:m:n:o:p:s:u:" :
    267 	    "B:FINO:S:T:V:Za:b:d:e:f:g:h:i:l:m:n:o:r:s:v:";
    268 	while ((ch = getopt(argc, argv, opstring)) != -1)
    269 		switch (ch) {
    270 		case 'B':
    271 			if (strcmp(optarg, "be") == 0) {
    272 #if BYTE_ORDER == LITTLE_ENDIAN
    273 				needswap = 1;
    274 #endif
    275 			} else if (strcmp(optarg, "le") == 0) {
    276 #if BYTE_ORDER == BIG_ENDIAN
    277 				needswap = 1;
    278 #endif
    279 			} else
    280 				usage();
    281 			break;
    282 		case 'F':
    283 			Fflag = 1;
    284 			break;
    285 		case 'I':
    286 			Iflag = 1;
    287 			break;
    288 		case 'N':
    289 			Nflag = 1;
    290 			if (verbosity == -1)
    291 				verbosity = DEFAULT_VERBOSITY;
    292 			break;
    293 		case 'O':
    294 			Oflag = strsuftoi64("format", optarg, 0, 2, NULL);
    295 			break;
    296 		case 'S':
    297 			/* XXX: non-512 byte sectors almost certainly don't work. */
    298 			sectorsize = strsuftoi64("sector size",
    299 			    optarg, 512, 65536, NULL);
    300 			if (sectorsize & (sectorsize - 1))
    301 				errx(1, "sector size `%s' is not a power of 2.",
    302 				    optarg);
    303 			break;
    304 #ifdef COMPAT
    305 		case 'T':
    306 			disktype = optarg;
    307 			break;
    308 #endif
    309 		case 'V':
    310 			verbosity = strsuftoi64("verbose", optarg, 0, 4, NULL);
    311 			break;
    312 		case 'Z':
    313 			Zflag = 1;
    314 			break;
    315 		case 'a':
    316 			maxcontig = strsuftoi64("maximum contiguous blocks",
    317 			    optarg, 1, INT_MAX, NULL);
    318 			break;
    319 		case 'b':
    320 			bsize = strsuftoi64("block size",
    321 			    optarg, MINBSIZE, MAXBSIZE, NULL);
    322 			break;
    323 		case 'd':
    324 			maxbsize = strsuftoi64("maximum extent size",
    325 			    optarg, 0, INT_MAX, NULL);
    326 			break;
    327 		case 'e':
    328 			maxbpg = strsuftoi64(
    329 			    "blocks per file in a cylinder group",
    330 			    optarg, 1, INT_MAX, NULL);
    331 			break;
    332 		case 'f':
    333 			fsize = strsuftoi64("fragment size",
    334 			    optarg, 1, MAXBSIZE, NULL);
    335 			break;
    336 		case 'g':
    337 			if (mfs)
    338 				mfsgid = mfs_group(optarg);
    339 			else {
    340 				avgfilesize = strsuftoi64("average file size",
    341 				    optarg, 1, INT_MAX, NULL);
    342 			}
    343 			break;
    344 		case 'h':
    345 			avgfpdir = strsuftoi64("expected files per directory",
    346 			    optarg, 1, INT_MAX, NULL);
    347 			break;
    348 		case 'i':
    349 			density = strsuftoi64("bytes per inode",
    350 			    optarg, 1, INT_MAX, NULL);
    351 			break;
    352 		case 'm':
    353 			minfree = strsuftoi64("free space %",
    354 			    optarg, 0, 99, NULL);
    355 			break;
    356 		case 'n':
    357 			num_inodes = strsuftoi64("number of inodes",
    358 			    optarg, 1, INT_MAX, NULL);
    359 			break;
    360 		case 'o':
    361 			if (mfs) {
    362 				mo = getmntopts(optarg, mopts, &mntflags, 0);
    363 				if (mo == NULL)
    364 					err(1, "getmntopts");
    365 				freemntopts(mo);
    366 			} else {
    367 				if (strcmp(optarg, "space") == 0)
    368 					opt = FS_OPTSPACE;
    369 				else if (strcmp(optarg, "time") == 0)
    370 					opt = FS_OPTTIME;
    371 				else
    372 				    errx(1, "%s %s",
    373 					"unknown optimization preference: ",
    374 					"use `space' or `time'.");
    375 			}
    376 			break;
    377 		case 'p':
    378 			/* mfs only */
    379 			if ((mfsmode = strtol(optarg, NULL, 8)) <= 0)
    380 				errx(1, "bad mode `%s'", optarg);
    381 			break;
    382 		case 's':
    383 			fssize = strsuftoi64("file system size",
    384 			    optarg, INT64_MIN, INT64_MAX, &byte_sized);
    385 			break;
    386 		case 'u':
    387 			/* mfs only */
    388 			mfsuid = mfs_user(optarg);
    389 			break;
    390 		case 'v':
    391 			appleufs_volname = optarg;
    392 			if (strchr(appleufs_volname, ':') || strchr(appleufs_volname, '/'))
    393 				errx(1,"Apple UFS volume name cannot contain ':' or '/'");
    394 			if (appleufs_volname[0] == '\0')
    395 				errx(1,"Apple UFS volume name cannot be zero length");
    396 			isappleufs = 1;
    397 			break;
    398 		case '?':
    399 		default:
    400 			usage();
    401 		}
    402 	argc -= optind;
    403 	argv += optind;
    404 
    405 	if (verbosity == -1)
    406 		/* Default to not showing CG info if mfs */
    407 		verbosity = mfs ? 0 : DEFAULT_VERBOSITY;
    408 
    409 #ifdef MFS
    410 	/* This is enough to get through the correct kernel code paths */
    411 	memset(&args, 0, sizeof args);
    412 	args.fspec = mountfromname;
    413 	if (mntflags & (MNT_GETARGS | MNT_UPDATE)) {
    414 		if ((mntflags & MNT_GETARGS) == 0)
    415 			mntflags |= MNT_ASYNC;
    416 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
    417 			err(1, "mount `%s' failed", argv[1]);
    418 		if (mntflags & MNT_GETARGS)
    419 			printf("base=%p, size=%ld\n", args.base, args.size);
    420 		exit(0);
    421 	}
    422 #endif
    423 
    424 	if (argc != 2 && (mfs || argc != 1))
    425 		usage();
    426 
    427 	memset(&sb, 0, sizeof sb);
    428 	memset(&dkw, 0, sizeof dkw);
    429 	special = argv[0];
    430 	if (Fflag || mfs) {
    431 		/*
    432 		 * It's a file system image or an MFS,
    433 		 * no label, use fixed default for sectorsize.
    434 		 */
    435 		if (sectorsize == 0)
    436 			sectorsize = DFL_SECSIZE;
    437 
    438 		if (mfs) {
    439 			/*
    440 			 * Default filesystem size to that of supplied device,
    441 			 * and fall back to 8M
    442 			 */
    443 			if (fssize == 0)
    444 				if (stat(special, &sb) == -1)
    445 					fssize = DFL_FSSIZE / sectorsize;
    446 		} else {
    447 			/* creating image in a regular file */
    448 			int fl;
    449 			if (Nflag)
    450 				fl = O_RDONLY;
    451 			else {
    452 				if (fssize > 0)
    453 					fl = O_RDWR | O_CREAT;
    454 				else
    455 					fl = O_RDWR;
    456 			}
    457 			fsi = open(special, fl, 0777);
    458 			if (fsi == -1)
    459 				err(1, "can't open file %s", special);
    460 			if (fstat(fsi, &sb) == -1)
    461 				err(1, "can't fstat opened %s", special);
    462 			if (!Nflag)
    463 				fso = fsi;
    464 		}
    465 	} else {	/* !Fflag && !mfs */
    466 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
    467 		special = device;
    468 		if (fsi < 0 || fstat(fsi, &sb) == -1)
    469 			err(1, "%s: open for read", special);
    470 
    471 		if (!Nflag) {
    472 			fso = open(special, O_WRONLY, 0);
    473 			if (fso < 0)
    474 				err(1, "%s: open for write", special);
    475 
    476 			/* Bail if target special is mounted */
    477 			n = getmntinfo(&mp, MNT_NOWAIT);
    478 			if (n == 0)
    479 				err(1, "%s: getmntinfo", special);
    480 
    481 			len = sizeof(_PATH_DEV) - 1;
    482 			s1 = special;
    483 			if (strncmp(_PATH_DEV, s1, len) == 0)
    484 				s1 += len;
    485 
    486 			while (--n >= 0) {
    487 				s2 = mp->f_mntfromname;
    488 				if (strncmp(_PATH_DEV, s2, len) == 0) {
    489 					s2 += len - 1;
    490 					*s2 = 'r';
    491 				}
    492 				if (strcmp(s1, s2) == 0 ||
    493 				    strcmp(s1, &s2[1]) == 0)
    494 					errx(1, "%s is mounted on %s",
    495 					    special, mp->f_mntonname);
    496 				++mp;
    497 			}
    498 		}
    499 
    500 #ifdef COMPAT
    501 		if (disktype == NULL)
    502 			disktype = argv[1];
    503 #endif
    504 		if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
    505 			errx(1, lmsg, special);
    506 		unlabeled = disktype != NULL;
    507 
    508 		if (sectorsize == 0) {
    509 			sectorsize = geo.dg_secsize;
    510 			if (sectorsize <= 0)
    511 				errx(1, "no default sector size");
    512 		}
    513 
    514 		if (dkw.dkw_parent[0]) {
    515 			if (dkw.dkw_size == 0)
    516 				errx(1, "%s partition is unavailable", special);
    517 
    518 			if (strcmp(dkw.dkw_ptype, DKW_PTYPE_APPLEUFS) == 0)
    519 				isappleufs = 1;
    520 
    521 			if (!Iflag) {
    522 				static const char m[] =
    523 				    "%s partition type is not `%s'";
    524 				if (isappleufs) {
    525 					if (strcmp(dkw.dkw_ptype,
    526 					    DKW_PTYPE_APPLEUFS))
    527 						errx(1, m,
    528 						    special, "Apple UFS");
    529 				} else {
    530 					if (strcmp(dkw.dkw_ptype,
    531 					    DKW_PTYPE_FFS))
    532 						errx(1, m, special, "4.2BSD");
    533 				}
    534 			}
    535 		}	/* !Fflag && !mfs */
    536 	}
    537 
    538 	if (byte_sized)
    539 		fssize /= sectorsize;
    540 	if (fssize <= 0) {
    541 		if (sb.st_size != 0)
    542 			fssize += sb.st_size / sectorsize;
    543 		else
    544 			fssize += dkw.dkw_size;
    545 		if (fssize <= 0)
    546 			errx(1, "Unable to determine file system size");
    547 	}
    548 
    549 	if (dkw.dkw_parent[0] && fssize > dkw.dkw_size)
    550 		errx(1, "size %" PRIu64 " exceeds maximum file system size on "
    551 		    "`%s' of %" PRIu64 " sectors",
    552 		    fssize, special, dkw.dkw_size);
    553 
    554 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
    555 	if (Fflag && fso != -1
    556 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
    557 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
    558 
    559 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparce) the file */
    560 		char	*buf;
    561 		int	bufsize, i;
    562 		off_t	bufrem;
    563 		struct statvfs sfs;
    564 
    565 		if (fstatvfs(fso, &sfs) == -1) {
    566 			warn("can't fstatvfs `%s'", special);
    567 			bufsize = 8192;
    568 		} else
    569 			bufsize = sfs.f_iosize;
    570 
    571 		if ((buf = calloc(1, bufsize)) == NULL)
    572 			err(1, "can't malloc buffer of %d",
    573 			bufsize);
    574 		bufrem = fssize * sectorsize;
    575 		if (verbosity > 0)
    576 			printf( "Creating file system image in `%s', "
    577 			    "size %lld bytes, in %d byte chunks.\n",
    578 			    special, (long long)bufrem, bufsize);
    579 		while (bufrem > 0) {
    580 			i = write(fso, buf, MIN(bufsize, bufrem));
    581 			if (i == -1)
    582 				err(1, "writing image");
    583 			bufrem -= i;
    584 		}
    585 		free(buf);
    586 	}
    587 
    588 	/* Sort out fragment and block sizes */
    589 	if (fsize == 0) {
    590 		fsize = bsize / DFL_FRAG_BLK;
    591 		if (fsize <= 0) {
    592 			if (isappleufs) {
    593 				fsize = APPLEUFS_DFL_FRAGSIZE;
    594 			} else {
    595 				if (fssize < SMALL_FSSIZE)
    596 					fsize = S_DFL_FRAGSIZE;
    597 				else if (fssize < MEDIUM_FSSIZE)
    598 					fsize = M_DFL_FRAGSIZE;
    599 				else
    600 					fsize = L_DFL_FRAGSIZE;
    601 				if (fsize < sectorsize)
    602 					fsize = sectorsize;
    603 			}
    604 		}
    605 	}
    606 	if (bsize <= 0) {
    607 		if (isappleufs)
    608 			bsize = APPLEUFS_DFL_BLKSIZE;
    609 		else
    610 			bsize = DFL_FRAG_BLK * fsize;
    611 	}
    612 
    613 	if (isappleufs && (fsize < APPLEUFS_DFL_FRAGSIZE)) {
    614 		warnx("Warning: chosen fsize of %d is less than Apple UFS minimum of %d",
    615 			fsize, APPLEUFS_DFL_FRAGSIZE);
    616 	}
    617 	if (isappleufs && (bsize > APPLEUFS_DFL_BLKSIZE)) {
    618 		warnx("Warning: chosen bsize of %d is greater than Apple UFS maximum of %d",
    619 			bsize, APPLEUFS_DFL_BLKSIZE);
    620 	}
    621 
    622 	/*
    623 	 * Maxcontig sets the default for the maximum number of blocks
    624 	 * that may be allocated sequentially. With filesystem clustering
    625 	 * it is possible to allocate contiguous blocks up to the maximum
    626 	 * transfer size permitted by the controller or buffering.
    627 	 */
    628 	if (maxcontig == 0)
    629 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
    630 	if (density == 0)
    631 		density = NFPI * fsize;
    632 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
    633 		warnx("%s %s %d%%", "Warning: changing optimization to space",
    634 		    "because minfree is less than", MINFREE);
    635 		opt = FS_OPTSPACE;
    636 	}
    637 	if (maxbpg == 0) {
    638 		if (Oflag <= 1)
    639 			maxbpg = MAXBLKPG_UFS1(bsize);
    640 		else
    641 			maxbpg = MAXBLKPG_UFS2(bsize);
    642 	}
    643 	mkfs(special, fsi, fso, mfsmode, mfsuid, mfsgid);
    644 	if (fsi != -1 && fsi != fso)
    645 		close(fsi);
    646 	if (fso != -1)
    647 		close(fso);
    648 #ifdef MFS
    649 	if (mfs) {
    650 
    651 		switch (pid = fork()) {
    652 		case -1:
    653 			perror("mfs");
    654 			exit(10);
    655 		case 0:
    656 			(void)snprintf(mountfromname, sizeof(mountfromname),
    657 			    "mfs:%d", getpid());
    658 			break;
    659 		default:
    660 			(void)snprintf(mountfromname, sizeof(mountfromname),
    661 			    "mfs:%d", pid);
    662 			for (;;) {
    663 				/*
    664 				 * spin until the mount succeeds
    665 				 * or the child exits
    666 				 */
    667 				usleep(1);
    668 
    669 				/*
    670 				 * XXX Here is a race condition: another process
    671 				 * can mount a filesystem which hides our
    672 				 * ramdisk before we see the success.
    673 				 */
    674 				if (statvfs(argv[1], &sf) < 0)
    675 					err(88, "statvfs %s", argv[1]);
    676 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
    677 				    !strncmp(sf.f_mntonname, argv[1],
    678 					     MNAMELEN) &&
    679 				    !strcmp(sf.f_fstypename, "mfs"))
    680 					exit(0);
    681 
    682 				res = waitpid(pid, &status, WNOHANG);
    683 				if (res == -1)
    684 					err(11, "waitpid");
    685 				if (res != pid)
    686 					continue;
    687 				if (WIFEXITED(status)) {
    688 					if (WEXITSTATUS(status) == 0)
    689 						exit(0);
    690 					errx(1, "%s: mount: %s", argv[1],
    691 					     strerror(WEXITSTATUS(status)));
    692 				} else
    693 					errx(11, "abnormal termination");
    694 			}
    695 			/* NOTREACHED */
    696 		}
    697 
    698 		(void) setsid();
    699 		(void) close(0);
    700 		(void) close(1);
    701 		(void) close(2);
    702 		(void) chdir("/");
    703 
    704 		args.base = membase;
    705 		args.size = fssize * sectorsize;
    706 		if (mount(MOUNT_MFS, argv[1], mntflags | MNT_ASYNC, &args) < 0)
    707 			exit(errno); /* parent prints message */
    708 	}
    709 #endif
    710 	exit(0);
    711 }
    712 
    713 static gid_t
    714 mfs_group(const char *gname)
    715 {
    716 	struct group *gp;
    717 
    718 	if (!(gp = getgrnam(gname)) && !isdigit((unsigned char)*gname))
    719 		errx(1, "unknown gname %s", gname);
    720 	return gp ? gp->gr_gid : atoi(gname);
    721 }
    722 
    723 static uid_t
    724 mfs_user(const char *uname)
    725 {
    726 	struct passwd *pp;
    727 
    728 	if (!(pp = getpwnam(uname)) && !isdigit((unsigned char)*uname))
    729 		errx(1, "unknown user %s", uname);
    730 	return pp ? pp->pw_uid : atoi(uname);
    731 }
    732 
    733 static int64_t
    734 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
    735 {
    736 	int64_t result, r1;
    737 	int shift = 0;
    738 	char	*ep;
    739 
    740 	errno = 0;
    741 	r1 = strtoll(arg, &ep, 10);
    742 	if (ep[0] != '\0' && ep[1] != '\0')
    743 		errx(1, "%s `%s' is not a valid number.", desc, arg);
    744 	switch (ep[0]) {
    745 	case '\0':
    746 	case 's': case 'S':
    747 		if (num_suffix != NULL)
    748 			*num_suffix = 0;
    749 		break;
    750 	case 'g': case 'G':
    751 		shift += 10;
    752 		/* FALLTHROUGH */
    753 	case 'm': case 'M':
    754 		shift += 10;
    755 		/* FALLTHROUGH */
    756 	case 'k': case 'K':
    757 		shift += 10;
    758 		/* FALLTHROUGH */
    759 	case 'b': case 'B':
    760 		if (num_suffix != NULL)
    761 			*num_suffix = 1;
    762 		break;
    763 	default:
    764 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
    765 	}
    766 	result = r1 << shift;
    767 	if (errno == ERANGE || result >> shift != r1)
    768 		errx(1, "%s `%s' is too large to convert.", desc, arg);
    769 	if (result < min)
    770 		errx(1, "%s `%s' (%" PRId64 ") is less than the minimum (%" PRId64 ").",
    771 		    desc, arg, result, min);
    772 	if (result > max)
    773 		errx(1, "%s `%s' (%" PRId64 ") is greater than the maximum (%" PRId64 ").",
    774 		    desc, arg, result, max);
    775 	return result;
    776 }
    777 
    778 #define	NEWFS		1
    779 #define	MFS_MOUNT	2
    780 #define	BOTH		NEWFS | MFS_MOUNT
    781 
    782 struct help_strings {
    783 	int flags;
    784 	const char *str;
    785 } const help_strings[] = {
    786 	{ NEWFS,	"-B byteorder\tbyte order (`be' or `le')" },
    787 	{ NEWFS,	"-F \t\tcreate file system image in regular file" },
    788 	{ NEWFS,	"-I \t\tdo not check that the file system type is '4.2BSD'" },
    789 	{ BOTH,		"-N \t\tdo not create file system, just print out "
    790 			    "parameters" },
    791 	{ NEWFS,	"-O N\t\tfilesystem format: 0 ==> 4.3BSD, 1 ==> FFS, 2 ==> UFS2" },
    792 	{ NEWFS,	"-S secsize\tsector size" },
    793 #ifdef COMPAT
    794 	{ NEWFS,	"-T disktype\tdisk type" },
    795 #endif
    796 	{ BOTH,		"-V verbose\toutput verbosity: 0 ==> none, 4 ==> max" },
    797 	{ NEWFS,	"-Z \t\tpre-zero the image file" },
    798 	{ BOTH,		"-a maxcontig\tmaximum contiguous blocks" },
    799 	{ BOTH,		"-b bsize\tblock size" },
    800 	{ BOTH,		"-d maxbsize\tmaximum extent size" },
    801 	{ BOTH,		"-e maxbpg\tmaximum blocks per file in a cylinder group"
    802 			    },
    803 	{ BOTH,		"-f fsize\tfrag size" },
    804 	{ NEWFS,	"-g avgfilesize\taverage file size" },
    805 	{ MFS_MOUNT,	"-g groupname\tgroup name of mount point" },
    806 	{ BOTH,		"-h avgfpdir\taverage files per directory" },
    807 	{ BOTH,		"-i density\tnumber of bytes per inode" },
    808 	{ BOTH,		"-m minfree\tminimum free space %%" },
    809 	{ BOTH,		"-n inodes\tnumber of inodes (overrides -i density)" },
    810 	{ BOTH,		"-o optim\toptimization preference (`space' or `time')"
    811 			    },
    812 	{ MFS_MOUNT,	"-p perm\t\tpermissions (in octal)" },
    813 	{ BOTH,		"-s fssize\tfile system size (sectors)" },
    814 	{ MFS_MOUNT,	"-u username\tuser name of mount point" },
    815 	{ NEWFS,	"-v volname\tApple UFS volume name" },
    816 	{ 0, NULL }
    817 };
    818 
    819 static void
    820 usage(void)
    821 {
    822 	int match;
    823 	const struct help_strings *hs;
    824 
    825 	if (mfs) {
    826 		fprintf(stderr,
    827 		    "usage: %s [ fsoptions ] special-device mount-point\n",
    828 			getprogname());
    829 	} else
    830 		fprintf(stderr,
    831 		    "usage: %s [ fsoptions ] special-device%s\n",
    832 		    getprogname(),
    833 #ifdef COMPAT
    834 		    " [disk-type]");
    835 #else
    836 		    "");
    837 #endif
    838 	fprintf(stderr, "where fsoptions are:\n");
    839 
    840 	match = mfs ? MFS_MOUNT : NEWFS;
    841 	for (hs = help_strings; hs->flags != 0; hs++)
    842 		if (hs->flags & match)
    843 			fprintf(stderr, "\t%s\n", hs->str);
    844 	exit(1);
    845 }
    846