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