Home | History | Annotate | Line # | Download | only in newfs
newfs.c revision 1.43
      1 /*	$NetBSD: newfs.c,v 1.43 2001/07/29 09:55:22 lukem 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.43 2001/07/29 09:55:22 lukem 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/stat.h>
     55 #include <sys/ioctl.h>
     56 #include <sys/disklabel.h>
     57 #include <sys/file.h>
     58 #include <sys/mount.h>
     59 #include <sys/sysctl.h>
     60 #include <sys/wait.h>
     61 
     62 #include <ufs/ufs/dir.h>
     63 #include <ufs/ufs/dinode.h>
     64 #include <ufs/ufs/ufsmount.h>
     65 #include <ufs/ffs/fs.h>
     66 
     67 #include <ctype.h>
     68 #include <disktab.h>
     69 #include <errno.h>
     70 #include <paths.h>
     71 #include <stdio.h>
     72 #include <stdlib.h>
     73 #include <string.h>
     74 #include <syslog.h>
     75 #include <unistd.h>
     76 #include <signal.h>
     77 #include <err.h>
     78 #include <util.h>
     79 
     80 #include "mntopts.h"
     81 #include "dkcksum.h"
     82 #include "extern.h"
     83 
     84 struct mntopt mopts[] = {
     85 	MOPT_STDOPTS,
     86 	MOPT_ASYNC,
     87 	MOPT_UPDATE,
     88 	MOPT_NOATIME,
     89 	{ NULL },
     90 };
     91 
     92 static struct disklabel *getdisklabel(char *, int);
     93 static void rewritelabel(char *, int, struct disklabel *);
     94 static int strsuftoi(const char *, const char *, int, int);
     95 static void usage(void);
     96 int main(int, char *[]);
     97 
     98 #define	COMPAT			/* allow non-labeled disks */
     99 
    100 /*
    101  * The following two constants set the default block and fragment sizes.
    102  * Both constants must be a power of 2 and meet the following constraints:
    103  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
    104  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
    105  *	DESBLKSIZE / DESFRAGSIZE <= 8
    106  */
    107 #define	DFL_FRAGSIZE	1024
    108 #define	DFL_BLKSIZE	8192
    109 
    110 /*
    111  * Default sector size.
    112  */
    113 #define DFL_SECSIZE	512
    114 
    115 /*
    116  * Cylinder groups may have up to many cylinders. The actual
    117  * number used depends upon how much information can be stored
    118  * on a single cylinder. The default is to use 16 cylinders
    119  * per group.
    120  */
    121 #define	DESCPG		16	/* desired fs_cpg */
    122 
    123 /*
    124  * ROTDELAY gives the minimum number of milliseconds to initiate
    125  * another disk transfer on the same cylinder. It is used in
    126  * determining the rotationally optimal layout for disk blocks
    127  * within a file; the default of fs_rotdelay is 0ms.
    128  */
    129 #define ROTDELAY	0
    130 
    131 /*
    132  * MAXBLKPG determines the maximum number of data blocks which are
    133  * placed in a single cylinder group. The default is one indirect
    134  * block worth of data blocks.
    135  */
    136 #define MAXBLKPG(bsize)	((bsize) / sizeof(daddr_t))
    137 
    138 /*
    139  * Each file system has a number of inodes statically allocated.
    140  * We allocate one inode slot per NFPI fragments, expecting this
    141  * to be far more than we will ever need.
    142  */
    143 #define	NFPI		4
    144 
    145 /*
    146  * For each cylinder we keep track of the availability of blocks at different
    147  * rotational positions, so that we can lay out the data to be picked
    148  * up with minimum rotational latency.  NRPOS is the default number of
    149  * rotational positions that we distinguish.  With NRPOS of 8 the resolution
    150  * of our summary information is 2ms for a typical 3600 rpm drive.  Caching
    151  * and zoning pretty much defeats rotational optimization, so we now use a
    152  * default of 1.
    153  */
    154 #define	NRPOS		1	/* number distinct rotational positions */
    155 
    156 
    157 int	mfs;			/* run as the memory based filesystem */
    158 int	Nflag;			/* run without writing file system */
    159 int	Oflag;			/* format as an 4.3BSD file system */
    160 int	fssize;			/* file system size */
    161 int	ntracks;		/* # tracks/cylinder */
    162 int	nsectors;		/* # sectors/track */
    163 int	nphyssectors;		/* # sectors/track including spares */
    164 int	secpercyl;		/* sectors per cylinder */
    165 int	trackspares = -1;	/* spare sectors per track */
    166 int	cylspares = -1;		/* spare sectors per cylinder */
    167 int	sectorsize;		/* bytes/sector */
    168 int	rpm;			/* revolutions/minute of drive */
    169 int	interleave;		/* hardware sector interleave */
    170 int	trackskew = -1;		/* sector 0 skew, per track */
    171 int	headswitch;		/* head switch time, usec */
    172 int	trackseek;		/* track-to-track seek, usec */
    173 int	fsize = 0;		/* fragment size */
    174 int	bsize = 0;		/* block size */
    175 int	cpg = DESCPG;		/* cylinders/cylinder group */
    176 int	cpgflg;			/* cylinders/cylinder group flag was given */
    177 int	minfree = MINFREE;	/* free space threshold */
    178 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
    179 int	density;		/* number of bytes per inode */
    180 int	maxcontig = 0;		/* max contiguous blocks to allocate */
    181 int	rotdelay = ROTDELAY;	/* rotational delay between blocks */
    182 int	maxbpg;			/* maximum blocks per file in a cyl group */
    183 int	nrpos = NRPOS;		/* # of distinguished rotational positions */
    184 int	bbsize = BBSIZE;	/* boot block size */
    185 int	sbsize = SBSIZE;	/* superblock size */
    186 int	mntflags = MNT_ASYNC;	/* flags to be passed to mount */
    187 u_long	memleft;		/* virtual memory available */
    188 caddr_t	membase;		/* start address of memory based filesystem */
    189 int	needswap;		/* Filesystem not in native byte order */
    190 #ifdef COMPAT
    191 char	*disktype;
    192 int	unlabeled;
    193 #endif
    194 
    195 char	device[MAXPATHLEN];
    196 
    197 int
    198 main(int argc, char *argv[])
    199 {
    200 	struct partition *pp;
    201 	struct disklabel *lp;
    202 	struct disklabel mfsfakelabel;
    203 	struct partition oldpartition;
    204 	struct stat st;
    205 	struct statfs *mp;
    206 	int ch, fsi, fso, len, maxpartitions, n, Fflag, Zflag;
    207 	char *cp, *endp, *s1, *s2, *special;
    208 	const char *opstring;
    209 	long long llsize;
    210 #ifdef MFS
    211 	char mountfromname[100];
    212 	pid_t pid, res;
    213 	struct statfs sf;
    214 	int status;
    215 #endif
    216 
    217 	cp = NULL;
    218 	fsi = fso = -1;
    219 	Fflag = Zflag = 0;
    220 	if (strstr(getprogname(), "mfs")) {
    221 		mfs = 1;
    222 		Nflag++;
    223 	}
    224 
    225 	maxpartitions = getmaxpartitions();
    226 	if (maxpartitions > 26)
    227 		errx(1, "insane maxpartitions value %d", maxpartitions);
    228 
    229 	opstring = mfs ?
    230 	    "NT:a:b:c:d:e:f:i:m:o:s:" :
    231 	    "B:FNOS:T:Za:b:c:d:e:f:i:k:l:m:n:o:p:r:s:t:u:x:";
    232 	while ((ch = getopt(argc, argv, opstring)) != -1)
    233 		switch (ch) {
    234 		case 'B':
    235 			if (strcmp(optarg, "be") == 0) {
    236 #if BYTE_ORDER == LITTLE_ENDIAN
    237 				needswap = 1;
    238 #endif
    239 			} else if (strcmp(optarg, "le") == 0) {
    240 #if BYTE_ORDER == BIG_ENDIAN
    241 				needswap = 1;
    242 #endif
    243 			} else
    244 				usage();
    245 			break;
    246 		case 'F':
    247 			Fflag = 1;
    248 			break;
    249 		case 'N':
    250 			Nflag = 1;
    251 			break;
    252 		case 'O':
    253 			Oflag = 1;
    254 			break;
    255 		case 'S':
    256 			sectorsize = strsuftoi("sector size",
    257 			    optarg, 1, INT_MAX);
    258 			break;
    259 #ifdef COMPAT
    260 		case 'T':
    261 			disktype = optarg;
    262 			break;
    263 #endif
    264 		case 'Z':
    265 			Zflag = 1;
    266 			break;
    267 		case 'a':
    268 			maxcontig = strsuftoi("maximum contiguous blocks",
    269 			    optarg, 1, INT_MAX);
    270 			break;
    271 		case 'b':
    272 			bsize = strsuftoi("block size",
    273 			    optarg, MINBSIZE, INT_MAX);
    274 			break;
    275 		case 'c':
    276 			cpg = strsuftoi("cylinders per group",
    277 			    optarg, 1, INT_MAX);
    278 			cpgflg++;
    279 			break;
    280 		case 'd':
    281 			rotdelay = strsuftoi("rotational delay",
    282 			    optarg, 0, INT_MAX);
    283 			break;
    284 		case 'e':
    285 			maxbpg = strsuftoi(
    286 			    "blocks per file in a cylinder group",
    287 			    optarg, 1, INT_MAX);
    288 			break;
    289 		case 'f':
    290 			fsize = strsuftoi("fragment size",
    291 			    optarg, 1, INT_MAX);
    292 			break;
    293 		case 'i':
    294 			density = strsuftoi("bytes per inode",
    295 			    optarg, 1, INT_MAX);
    296 			break;
    297 		case 'k':
    298 			trackskew = strsuftoi("track skew",
    299 			    optarg, 0, INT_MAX);
    300 			break;
    301 		case 'l':
    302 			interleave = strsuftoi("interleave",
    303 			    optarg, 1, INT_MAX);
    304 			break;
    305 		case 'm':
    306 			minfree = strsuftoi("free space %",
    307 			    optarg, 0, 99);
    308 			break;
    309 		case 'n':
    310 			nrpos = strsuftoi("rotational layout count",
    311 			    optarg, 1, INT_MAX);
    312 			break;
    313 		case 'o':
    314 			if (mfs)
    315 				getmntopts(optarg, mopts, &mntflags, 0);
    316 			else {
    317 				if (strcmp(optarg, "space") == 0)
    318 					opt = FS_OPTSPACE;
    319 				else if (strcmp(optarg, "time") == 0)
    320 					opt = FS_OPTTIME;
    321 				else
    322 				    errx(1, "%s %s",
    323 					"unknown optimization preference: ",
    324 					"use `space' or `time'.");
    325 			}
    326 			break;
    327 		case 'p':
    328 			trackspares = strsuftoi("spare sectors per track",
    329 			    optarg, 0, INT_MAX);
    330 			break;
    331 		case 'r':
    332 			rpm = strsuftoi("revolutions per minute",
    333 			    optarg, 1, INT_MAX);
    334 			break;
    335 		case 's':
    336 			llsize = strtoll(optarg, &endp, 10);
    337 			if (endp[0] != '\0' && endp[1] != '\0')
    338 				llsize = -1;
    339 			else {
    340 				int	ssiz;
    341 
    342 				ssiz = (sectorsize ? sectorsize : DFL_SECSIZE);
    343 				switch (tolower((unsigned char)endp[0])) {
    344 				case 'b':
    345 					llsize /= ssiz;
    346 					break;
    347 				case 'k':
    348 					llsize *= 1024 / ssiz;
    349 					break;
    350 				case 'm':
    351 					llsize *= 1024 * 1024 / ssiz;
    352 					break;
    353 				case 'g':
    354 					llsize *= 1024 * 1024 * 1024 / ssiz;
    355 					break;
    356 				case '\0':
    357 				case 's':
    358 					break;
    359 				default:
    360 					llsize = -1;
    361 				}
    362 			}
    363 			if (llsize > INT_MAX)
    364 				errx(1, "file system size `%s' is too large.",
    365 				    optarg);
    366 			if (llsize <= 0)
    367 				errx(1,
    368 			    "`%s' is not a valid number for file system size.",
    369 				    optarg);
    370 			fssize = (int)llsize;
    371 			break;
    372 		case 't':
    373 			ntracks = strsuftoi("total tracks",
    374 			    optarg, 1, INT_MAX);
    375 			break;
    376 		case 'u':
    377 			nsectors = strsuftoi("sectors per track",
    378 			    optarg, 1, INT_MAX);
    379 			break;
    380 		case 'x':
    381 			cylspares = strsuftoi("spare sectors per cylinder",
    382 			    optarg, 0, INT_MAX);
    383 			break;
    384 		case '?':
    385 		default:
    386 			usage();
    387 		}
    388 	argc -= optind;
    389 	argv += optind;
    390 
    391 	if (argc != 2 && (mfs || argc != 1))
    392 		usage();
    393 
    394 	special = argv[0];
    395 	if ((mfs && !strcmp(special, "swap")) || Fflag) {
    396 		/*
    397 		 * it's an MFS mounted on "swap" or a file system image;
    398 		 * fake up a label.		XXX
    399 		 */
    400 		if (!sectorsize)
    401 			sectorsize = DFL_SECSIZE;
    402 
    403 		if (Fflag && (stat(special, &st) != -1 && !S_ISREG(st.st_mode)))
    404 			errx(1, "%s is not a regular file", special);
    405 		if (Fflag && !Nflag) {	/* creating image in a regular file */
    406 			fso = open(special, O_RDWR | O_CREAT | O_TRUNC, 0777);
    407 			if (fso == -1)
    408 				err(1, "can't open file %s", special);
    409 			fsi = dup(fso);
    410 			if (fssize == 0)
    411 				errx(1, "need to specify size when using -F");
    412 			if (ftruncate(fso, (off_t)fssize * sectorsize) == -1)
    413 				err(1, "can't resize %s to %d",
    414 				    special, fssize);
    415 
    416 			if (Zflag) {	/* pre-zero the file */
    417 				char	*buf;
    418 				int	i;
    419 
    420 				if ((buf = calloc(1, sectorsize)) == NULL)
    421 					err(1, "can't malloc buffer of %d",
    422 					sectorsize);
    423 				printf(
    424 		    "Creating file system image in `%s', size %lld bytes.\n",
    425 				    special, (long long)(fssize * sectorsize));
    426 				for (i = 0; i < fssize; i++) {
    427 					if (write(fso, buf, sectorsize) !=
    428 					    sectorsize)
    429 						err(1,
    430 						    "writing image sector %d",
    431 						    i);
    432 				}
    433 			}
    434 
    435 		}
    436 
    437 		memset(&mfsfakelabel, 0, sizeof(mfsfakelabel));
    438 		mfsfakelabel.d_secsize = sectorsize;
    439 		mfsfakelabel.d_nsectors = 64;	/* these 3 add up to 16MB */
    440 		mfsfakelabel.d_ntracks = 16;
    441 		mfsfakelabel.d_ncylinders = 16;
    442 		mfsfakelabel.d_secpercyl =
    443 		    mfsfakelabel.d_nsectors * mfsfakelabel.d_ntracks;
    444 		mfsfakelabel.d_secperunit =
    445 		    mfsfakelabel.d_ncylinders * mfsfakelabel.d_secpercyl;
    446 		mfsfakelabel.d_rpm = 3600;
    447 		mfsfakelabel.d_interleave = 1;
    448 		mfsfakelabel.d_npartitions = 1;
    449 		mfsfakelabel.d_partitions[0].p_size = mfsfakelabel.d_secperunit;
    450 		mfsfakelabel.d_partitions[0].p_fsize = 1024;
    451 		mfsfakelabel.d_partitions[0].p_frag = 8;
    452 		mfsfakelabel.d_partitions[0].p_cpg = 16;
    453 
    454 		lp = &mfsfakelabel;
    455 		pp = &mfsfakelabel.d_partitions[0];
    456 
    457 		goto havelabel;
    458 	}
    459 	cp = strrchr(special, '/');
    460 	if (cp == NULL) {
    461 		/*
    462 		 * No path prefix; try /dev/r%s then /dev/%s.
    463 		 */
    464 		(void)snprintf(device, sizeof(device), "%sr%s",
    465 		    _PATH_DEV, special);
    466 		if (stat(device, &st) == -1)
    467 			(void)snprintf(device, sizeof(device), "%s%s",
    468 			    _PATH_DEV, special);
    469 		special = device;
    470 	}
    471 	if (Nflag) {
    472 		fso = -1;
    473 	} else {
    474 		fso = open(special, O_WRONLY);
    475 		if (fso < 0)
    476 			err(1, "%s: open", special);
    477 
    478 		/* Bail if target special is mounted */
    479 		n = getmntinfo(&mp, MNT_NOWAIT);
    480 		if (n == 0)
    481 			err(1, "%s: getmntinfo", special);
    482 
    483 		len = sizeof(_PATH_DEV) - 1;
    484 		s1 = special;
    485 		if (strncmp(_PATH_DEV, s1, len) == 0)
    486 			s1 += len;
    487 
    488 		while (--n >= 0) {
    489 			s2 = mp->f_mntfromname;
    490 			if (strncmp(_PATH_DEV, s2, len) == 0) {
    491 				s2 += len - 1;
    492 				*s2 = 'r';
    493 			}
    494 			if (strcmp(s1, s2) == 0 || strcmp(s1, &s2[1]) == 0)
    495 				errx(1, "%s is mounted on %s",
    496 				    special, mp->f_mntonname);
    497 			++mp;
    498 		}
    499 	}
    500 	if (mfs && disktype != NULL) {
    501 		lp = (struct disklabel *)getdiskbyname(disktype);
    502 		if (lp == NULL)
    503 			errx(1, "%s: unknown disk type", disktype);
    504 		pp = &lp->d_partitions[1];
    505 	} else {
    506 		fsi = open(special, O_RDONLY);
    507 		if (fsi < 0)
    508 			err(1, "%s: open", special);
    509 		if (fstat(fsi, &st) < 0)
    510 			err(1, "%s: fstat", special);
    511 		if (!S_ISCHR(st.st_mode) && !mfs)
    512 			warnx("%s: not a character-special device", special);
    513 		cp = strchr(argv[0], '\0') - 1;
    514 		if (cp == 0 || ((*cp < 'a' || *cp > ('a' + maxpartitions - 1))
    515 		    && !isdigit(*cp)))
    516 			errx(1, "can't figure out file system partition");
    517 #ifdef COMPAT
    518 		if (!mfs && disktype == NULL)
    519 			disktype = argv[1];
    520 #endif
    521 		lp = getdisklabel(special, fsi);
    522 		if (isdigit(*cp))
    523 			pp = &lp->d_partitions[0];
    524 		else
    525 			pp = &lp->d_partitions[*cp - 'a'];
    526 		if (pp->p_size == 0)
    527 			errx(1, "`%c' partition is unavailable", *cp);
    528 		if (pp->p_fstype == FS_BOOT)
    529 			errx(1, "`%c' partition overlaps boot program", *cp);
    530 	}
    531 
    532  havelabel:
    533 	if (fssize == 0)
    534 		fssize = pp->p_size;
    535 	if (fssize > pp->p_size && !mfs && !Fflag)
    536 		errx(1, "maximum file system size on the `%c' partition is %d",
    537 		    *cp, pp->p_size);
    538 	if (rpm == 0) {
    539 		rpm = lp->d_rpm;
    540 		if (rpm <= 0)
    541 			rpm = 3600;
    542 	}
    543 	if (ntracks == 0) {
    544 		ntracks = lp->d_ntracks;
    545 		if (ntracks <= 0)
    546 			errx(1, "no default #tracks");
    547 	}
    548 	if (nsectors == 0) {
    549 		nsectors = lp->d_nsectors;
    550 		if (nsectors <= 0)
    551 			errx(1, "no default #sectors/track");
    552 	}
    553 	if (sectorsize == 0) {
    554 		sectorsize = lp->d_secsize;
    555 		if (sectorsize <= 0)
    556 			errx(1, "no default sector size");
    557 	}
    558 	if (trackskew == -1) {
    559 		trackskew = lp->d_trackskew;
    560 		if (trackskew < 0)
    561 			trackskew = 0;
    562 	}
    563 	if (interleave == 0) {
    564 		interleave = lp->d_interleave;
    565 		if (interleave <= 0)
    566 			interleave = 1;
    567 	}
    568 	if (fsize == 0) {
    569 		fsize = pp->p_fsize;
    570 		if (fsize <= 0)
    571 			fsize = MAX(DFL_FRAGSIZE, lp->d_secsize);
    572 	}
    573 	if (bsize == 0) {
    574 		bsize = pp->p_frag * pp->p_fsize;
    575 		if (bsize <= 0)
    576 			bsize = MIN(DFL_BLKSIZE, 8 * fsize);
    577 	}
    578 	if (cpgflg == 0) {
    579 		if (pp->p_cpg != 0)
    580 			cpg = pp->p_cpg;
    581 	}
    582 	/*
    583 	 * Maxcontig sets the default for the maximum number of blocks
    584 	 * that may be allocated sequentially. With filesystem clustering
    585 	 * it is possible to allocate contiguous blocks up to the maximum
    586 	 * transfer size permitted by the controller or buffering.
    587 	 */
    588 	if (maxcontig == 0)
    589 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
    590 	if (density == 0)
    591 		density = NFPI * fsize;
    592 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
    593 		warnx("%s %s %d%%", "Warning: changing optimization to space",
    594 		    "because minfree is less than", MINFREE);
    595 		opt = FS_OPTSPACE;
    596 	}
    597 	if (trackspares == -1) {
    598 		trackspares = lp->d_sparespertrack;
    599 		if (trackspares < 0)
    600 			trackspares = 0;
    601 	}
    602 	nphyssectors = nsectors + trackspares;
    603 	if (cylspares == -1) {
    604 		cylspares = lp->d_sparespercyl;
    605 		if (cylspares < 0)
    606 			cylspares = 0;
    607 	}
    608 	secpercyl = nsectors * ntracks - cylspares;
    609 	if (secpercyl != lp->d_secpercyl)
    610 		warnx("%s (%d) %s (%u)\n",
    611 			"Warning: calculated sectors per cylinder", secpercyl,
    612 			"disagrees with disk label", lp->d_secpercyl);
    613 	if (maxbpg == 0)
    614 		maxbpg = MAXBLKPG(bsize);
    615 	headswitch = lp->d_headswitch;
    616 	trackseek = lp->d_trkseek;
    617 #ifdef notdef /* label may be 0 if faked up by kernel */
    618 	bbsize = lp->d_bbsize;
    619 	sbsize = lp->d_sbsize;
    620 #endif
    621 	oldpartition = *pp;
    622 	mkfs(pp, special, fsi, fso);
    623 	if (!Nflag && memcmp(pp, &oldpartition, sizeof(oldpartition)) && !Fflag)
    624 		rewritelabel(special, fso, lp);
    625 	if (!Nflag)
    626 		close(fso);
    627 	close(fsi);
    628 #ifdef MFS
    629 	if (mfs) {
    630 		struct mfs_args args;
    631 
    632 		switch (pid = fork()) {
    633 		case -1:
    634 			perror("mfs");
    635 			exit(10);
    636 		case 0:
    637 			(void)snprintf(mountfromname, sizeof(mountfromname),
    638 			    "mfs:%d", getpid());
    639 			break;
    640 		default:
    641 			(void)snprintf(mountfromname, sizeof(mountfromname),
    642 			    "mfs:%d", pid);
    643 			for (;;) {
    644 				/*
    645 				 * spin until the mount succeeds
    646 				 * or the child exits
    647 				 */
    648 				usleep(1);
    649 
    650 				/*
    651 				 * XXX Here is a race condition: another process
    652 				 * can mount a filesystem which hides our
    653 				 * ramdisk before we see the success.
    654 				 */
    655 				if (statfs(argv[1], &sf) < 0)
    656 					err(88, "statfs %s", argv[1]);
    657 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
    658 				    !strncmp(sf.f_mntonname, argv[1],
    659 					     MNAMELEN) &&
    660 				    !strcmp(sf.f_fstypename, "mfs"))
    661 					exit(0);
    662 
    663 				res = waitpid(pid, &status, WNOHANG);
    664 				if (res == -1)
    665 					err(11, "waitpid");
    666 				if (res != pid)
    667 					continue;
    668 				if (WIFEXITED(status)) {
    669 					if (WEXITSTATUS(status) == 0)
    670 						exit(0);
    671 					errx(1, "%s: mount: %s", argv[1],
    672 					     strerror(WEXITSTATUS(status)));
    673 				} else
    674 					errx(11, "abnormal termination");
    675 			}
    676 			/* NOTREACHED */
    677 		}
    678 
    679 		(void) setsid();
    680 		(void) close(0);
    681 		(void) close(1);
    682 		(void) close(2);
    683 		(void) chdir("/");
    684 
    685 		args.fspec = mountfromname;
    686 		args.export.ex_root = -2;
    687 		if (mntflags & MNT_RDONLY)
    688 			args.export.ex_flags = MNT_EXRDONLY;
    689 		else
    690 			args.export.ex_flags = 0;
    691 		args.base = membase;
    692 		args.size = fssize * sectorsize;
    693 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
    694 			exit(errno); /* parent prints message */
    695 	}
    696 #endif
    697 	exit(0);
    698 }
    699 
    700 #ifdef COMPAT
    701 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
    702 #else
    703 const char lmsg[] = "%s: can't read disk label";
    704 #endif
    705 
    706 static struct disklabel *
    707 getdisklabel(char *s, volatile int fd)
    708 /* XXX why is fs volatile?! */
    709 {
    710 	static struct disklabel lab;
    711 
    712 	if (ioctl(fd, DIOCGDINFO, &lab) < 0) {
    713 #ifdef COMPAT
    714 		if (disktype) {
    715 			struct disklabel *lp;
    716 
    717 			unlabeled++;
    718 			lp = getdiskbyname(disktype);
    719 			if (lp == NULL)
    720 				errx(1, "%s: unknown disk type", disktype);
    721 			return (lp);
    722 		}
    723 #endif
    724 		warn("ioctl (GDINFO)");
    725 		errx(1, lmsg, s);
    726 	}
    727 	return (&lab);
    728 }
    729 
    730 static void
    731 rewritelabel(char *s, volatile int fd, struct disklabel *lp)
    732 /* XXX why is fd volatile?! */
    733 {
    734 #ifdef COMPAT
    735 	if (unlabeled)
    736 		return;
    737 #endif
    738 	lp->d_checksum = 0;
    739 	lp->d_checksum = dkcksum(lp);
    740 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
    741 		warn("ioctl (WDINFO)");
    742 		errx(1, "%s: can't rewrite disk label", s);
    743 	}
    744 #if __vax__
    745 	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
    746 		int i;
    747 		int cfd;
    748 		daddr_t alt;
    749 		char specname[64];
    750 		char blk[1024];
    751 		char *cp;
    752 
    753 		/*
    754 		 * Make name for 'c' partition.
    755 		 */
    756 		strcpy(specname, s);
    757 		cp = specname + strlen(specname) - 1;
    758 		if (!isdigit(*cp))
    759 			*cp = 'c';
    760 		cfd = open(specname, O_WRONLY);
    761 		if (cfd < 0)
    762 			err(1, "%s: open", specname);
    763 		memset(blk, 0, sizeof(blk));
    764 		*(struct disklabel *)(blk + LABELOFFSET) = *lp;
    765 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
    766 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
    767 			off_t offset;
    768 
    769 			offset = alt + i;
    770 			offset *= lp->d_secsize;
    771 			if (lseek(cfd, offset, SEEK_SET) == -1)
    772 				err(1, "lseek to badsector area: ");
    773 			if (write(cfd, blk, lp->d_secsize) < lp->d_secsize)
    774 				warn("alternate label %d write", i/2);
    775 		}
    776 		close(cfd);
    777 	}
    778 #endif
    779 }
    780 
    781 static int
    782 strsuftoi(const char *desc, const char *arg, int min, int max)
    783 {
    784 	long long result;
    785 	char	*ep;
    786 
    787 	errno = 0;
    788 	result = strtoll(arg, &ep, 10);
    789 	if (ep[0] != '\0' && ep[1] != '\0')
    790 		errx(1, "%s `%s' is not a valid number.", desc, arg);
    791 	switch (tolower((unsigned char)ep[0])) {
    792 	case '\0':
    793 	case 'b':
    794 		break;
    795 	case 'k':
    796 		result <<= 10;
    797 		break;
    798 	case 'm':
    799 		result <<= 20;
    800 		break;
    801 	case 'g':
    802 		result <<= 30;
    803 		break;
    804 	default:
    805 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
    806 	}
    807 	if (result < min)
    808 		errx(1, "%s `%s' (%lld) is less than minimum (%d).",
    809 		    desc, arg, result, min);
    810 	if (result > max)
    811 		errx(1, "%s `%s' (%lld) is greater than maximum (%d).",
    812 		    desc, arg, result, max);
    813 	return ((int)result);
    814 }
    815 
    816 static void
    817 usage(void)
    818 {
    819 
    820 	if (mfs) {
    821 		fprintf(stderr,
    822 		    "usage: %s [ fsoptions ] special-device mount-point\n",
    823 			getprogname());
    824 	} else
    825 		fprintf(stderr,
    826 		    "usage: %s [ fsoptions ] special-device%s\n",
    827 		    getprogname(),
    828 #ifdef COMPAT
    829 		    " [device-type]");
    830 #else
    831 		    "");
    832 #endif
    833 	fprintf(stderr, "where fsoptions are:\n");
    834 	if (!mfs) {
    835 		fprintf(stderr,
    836 			"\t-B byteorder\tbyte order (`be' or `le')\n");
    837 		fprintf(stderr,
    838 			"\t-F\t\tcreate file system image in regular file\n");
    839 	}
    840 	fprintf(stderr, "\t-N\t\tdo not create file system, "
    841 			"just print out parameters\n");
    842 	if (!mfs) {
    843 		fprintf(stderr,
    844 			"\t-O\t\tcreate a 4.3BSD format filesystem\n");
    845 		fprintf(stderr,
    846 			"\t-S secsize\tsector size\n");
    847 	}
    848 #ifdef COMPAT
    849 	fprintf(stderr, "\t-T disktype\tdisk type\n");
    850 #endif
    851 	if (!mfs)
    852 		fprintf(stderr,
    853 			"\t-Z\t\tpre-zero the image file (with -F)\n");
    854 	fprintf(stderr, "\t-a maxcontig\tmaximum contiguous blocks\n");
    855 	fprintf(stderr, "\t-b bsize\tblock size\n");
    856 	fprintf(stderr, "\t-c cpg\t\tcylinders/group\n");
    857 	fprintf(stderr, "\t-d rotdelay\trotational delay between "
    858 			"contiguous blocks\n");
    859 	fprintf(stderr, "\t-e maxbpg\tmaximum blocks per file "
    860 			"in a cylinder group\n");
    861 	fprintf(stderr, "\t-f fsize\tfragment size\n");
    862 	fprintf(stderr, "\t-i density\tnumber of bytes per inode\n");
    863 	if (!mfs) {
    864 		fprintf(stderr,
    865 			"\t-k trackskew\tsector 0 skew, per track\n");
    866 		fprintf(stderr,
    867 			"\t-l interleave\thardware sector interleave\n");
    868 	}
    869 	fprintf(stderr, "\t-m minfree\tminimum free space %%\n");
    870 	if (!mfs)
    871 		fprintf(stderr,
    872 			"\t-n nrpos\tnumber of distinguished "
    873 			"rotational positions\n");
    874 	fprintf(stderr, "\t-o optim\toptimization preference "
    875 			"(`space' or `time')\n");
    876 	if (!mfs)
    877 		fprintf(stderr,
    878 			"\t-p trackspares\tspare sectors per track\n");
    879 	fprintf(stderr, "\t-s fssize\tfile system size (sectors)\n");
    880 	if (!mfs) {
    881 		fprintf(stderr,
    882 			"\t-r rpm\t\trevolutions/minute\n");
    883 		fprintf(stderr,
    884 			"\t-t ntracks\ttracks/cylinder\n");
    885 		fprintf(stderr,
    886 			"\t-u nsectors\tsectors/track\n");
    887 		fprintf(stderr,
    888 			"\t-x cylspares\tspare sectors per cylinder\n");
    889 	}
    890 	exit(1);
    891 }
    892