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