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