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