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