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