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