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