xref: /netbsd-src/sbin/newfs/newfs.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: newfs.c,v 1.114 2016/04/01 05:23:56 ryo 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\
74  The Regents of the University of California.  All rights reserved.");
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.114 2016/04/01 05:23:56 ryo 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/disk.h>
92 #include <sys/file.h>
93 #include <sys/mount.h>
94 #include <sys/sysctl.h>
95 #include <sys/wait.h>
96 
97 #include <ufs/ufs/dir.h>
98 #include <ufs/ufs/dinode.h>
99 #include <ufs/ufs/ufsmount.h>
100 #include <ufs/ufs/quota2.h>
101 #include <ufs/ffs/fs.h>
102 
103 #include <ctype.h>
104 #include <disktab.h>
105 #include <err.h>
106 #include <errno.h>
107 #include <grp.h>
108 #include <limits.h>
109 #include <paths.h>
110 #include <pwd.h>
111 #include <signal.h>
112 #include <stdint.h>
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <syslog.h>
117 #include <unistd.h>
118 #include <util.h>
119 #include <mntopts.h>
120 
121 #ifdef MFS
122 #include <mountprog.h>
123 #endif
124 
125 #include "dkcksum.h"
126 #include "extern.h"
127 #include "partutil.h"
128 
129 struct mntopt mopts[] = {
130 	MOPT_STDOPTS,
131 	MOPT_ASYNC,
132 	MOPT_UPDATE,
133 	MOPT_GETARGS,
134 	MOPT_NOATIME,
135 	{ .m_option = NULL },
136 };
137 
138 static gid_t mfs_group(const char *);
139 static uid_t mfs_user(const char *);
140 static int64_t strsuftoi64(const char *, const char *, int64_t, int64_t, int *);
141 static void usage(void) __dead;
142 
143 #define	COMPAT			/* allow non-labeled disks */
144 
145 #ifdef COMPAT
146 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
147 #else
148 const char lmsg[] = "%s: can't read disk label";
149 #endif
150 
151 /*
152  * The following two constants set the default block and fragment sizes.
153  * Both constants must be a power of 2 and meet the following constraints:
154  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
155  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
156  *	DESBLKSIZE / DESFRAGSIZE <= 8
157  */
158 /*
159  * For file systems smaller than SMALL_FSSIZE we use the S_DFL_* defaults,
160  * otherwise if less than MEDIUM_FSSIZE use M_DFL_*,
161  * otherwise if less than LARGE_FSSIZE use L_DFL_*,
162  * otherwise use LL_DFL_* especially for modern AFT disks.
163  */
164 #define	SMALL_FSSIZE	(20*1024*2)
165 #define	S_DFL_FRAGSIZE	512
166 #define	MEDIUM_FSSIZE	(1000*1024*2)
167 #define	M_DFL_FRAGSIZE	1024
168 #define	LARGE_FSSIZE	(128*1024*1024*2)
169 #define	L_DFL_FRAGSIZE	2048
170 #define	LL_DFL_FRAGSIZE	4096
171 #define	DFL_FRAG_BLK	8
172 
173 /* Apple requires the fragment size to be at least APPLEUFS_DIRBLKSIZ
174  * but the block size cannot be larger than Darwin's PAGE_SIZE.  See
175  * the mount check in Darwin's ffs_mountfs for an explanation.
176  */
177 #define APPLEUFS_DFL_FRAGSIZE APPLEUFS_DIRBLKSIZ /* 1024 */
178 #define APPLEUFS_DFL_BLKSIZE 4096 /* default Darwin PAGE_SIZE */
179 
180 /*
181  * Default sector size.
182  */
183 #define	DFL_SECSIZE	512
184 
185 /*
186  * Default file system size for "mount_mfs swap /dir" case.
187  */
188 #define	DFL_FSSIZE	(8 * 1024 * 1024)
189 
190 /*
191  * MAXBLKPG determines the maximum number of data blocks which are
192  * placed in a single cylinder group. The default is one indirect
193  * block worth of data blocks.
194  */
195 #define	MAXBLKPG_UFS1(bsize)	((bsize) / sizeof(int32_t))
196 #define	MAXBLKPG_UFS2(bsize)	((bsize) / sizeof(int64_t))
197 
198 /*
199  * Each file system has a number of inodes statically allocated.
200  * We allocate one inode slot per NFPI fragments, expecting this
201  * to be far more than we will ever need.
202  */
203 #define	NFPI		4
204 
205 
206 int	mfs;			/* run as the memory based filesystem */
207 int	Gflag;			/* allow garbage parameters (for testing) */
208 int	Nflag;			/* run without writing file system */
209 int	Oflag = 1;		/* format as an 4.3BSD file system */
210 int	verbosity;		/* amount of printf() output */
211 #define DEFAULT_VERBOSITY 3	/* 4 is traditional behavior */
212 int64_t	fssize;			/* file system size */
213 int	sectorsize;		/* bytes/sector */
214 int	fsize = 0;		/* fragment size */
215 int	bsize = 0;		/* block size */
216 int	maxbsize = 0;		/* maximum clustering */
217 int	minfree = MINFREE;	/* free space threshold */
218 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
219 int	density;		/* number of bytes per inode */
220 int	num_inodes;		/* number of inodes (overrides density) */
221 int	maxcontig = 0;		/* max contiguous blocks to allocate */
222 int	maxbpg;			/* maximum blocks per file in a cyl group */
223 int	avgfilesize = AVFILESIZ;/* expected average file size */
224 int	avgfpdir = AFPDIR;	/* expected number of files per directory */
225 int	mntflags = 0;		/* flags to be passed to mount */
226 u_long	memleft;		/* virtual memory available */
227 caddr_t	membase;		/* start address of memory based filesystem */
228 int	needswap;		/* Filesystem not in native byte order */
229 char	*disktype = NULL;
230 int	unlabeled;
231 char *appleufs_volname = 0; /* Apple UFS volume name */
232 int isappleufs = 0;
233 int quotas = 0;
234 
235 char	device[MAXPATHLEN];
236 
237 int
238 main(int argc, char *argv[])
239 {
240 	struct disk_geom geo;
241 	struct dkwedge_info dkw;
242 	struct statvfs *mp;
243 	struct stat sb;
244 	int ch, fsi, fso, len, n, Fflag, Iflag, Zflag;
245 	const char *s1, *special, *raw;
246 	char *s2;
247 	char specname[MAXPATHLEN];
248 	char rawname[MAXPATHLEN];
249 	const char *opstring;
250 	int byte_sized = 0;
251 #ifdef MFS
252 	struct mfs_args args;
253 	char mountfromname[100];
254 	char mounttoname[MAXPATHLEN];
255 	pid_t pid, res;
256 	struct statvfs sf;
257 	int status;
258 #endif
259 	mode_t mfsmode = 01777;	/* default mode for a /tmp-type directory */
260 	uid_t mfsuid = 0;	/* user root */
261 	gid_t mfsgid = 0;	/* group wheel */
262 	mntoptparse_t mo;
263 
264 	fsi = fso = -1;
265 	Fflag = Iflag = Zflag = 0;
266 	verbosity = -1;
267 	if (strstr(getprogname(), "mfs")) {
268 		mfs = 1;
269 	} else {
270 		/* Undocumented, for ease of testing */
271 		if (argv[1] != NULL && !strcmp(argv[1], "-mfs")) {
272 			argv++;
273 			argc--;
274 			mfs = 1;
275 		}
276 	}
277 
278 	opstring = mfs ?
279 	    "NT:V:a:b:d:e:f:g:h:i:m:n:o:p:q:s:u:" :
280 	    "B:FGINO:S:T:V:Za:b:d:e:f:g:h:i:l:m:n:o:q:r:s:v:";
281 	while ((ch = getopt(argc, argv, opstring)) != -1)
282 		switch (ch) {
283 		case 'B':
284 			if (strcmp(optarg, "be") == 0) {
285 #if BYTE_ORDER == LITTLE_ENDIAN
286 				needswap = 1;
287 #endif
288 			} else if (strcmp(optarg, "le") == 0) {
289 #if BYTE_ORDER == BIG_ENDIAN
290 				needswap = 1;
291 #endif
292 			} else
293 				usage();
294 			break;
295 		case 'F':
296 			Fflag = 1;
297 			break;
298 		case 'G':
299 			fprintf(stderr, "WARNING: -G may create file systems "
300 			    "which cause kernel panics\n");
301 			Gflag = 1;
302 			break;
303 		case 'I':
304 			Iflag = 1;
305 			break;
306 		case 'N':
307 			Nflag = 1;
308 			if (verbosity == -1)
309 				verbosity = DEFAULT_VERBOSITY;
310 			break;
311 		case 'O':
312 			Oflag = strsuftoi64("format", optarg, 0, 2, NULL);
313 			break;
314 		case 'S':
315 			/* XXX: non-512 byte sectors almost certainly don't work. */
316 			sectorsize = strsuftoi64("sector size",
317 			    optarg, 512, 65536, NULL);
318 			if (sectorsize & (sectorsize - 1))
319 				errx(1, "sector size `%s' is not a power of 2.",
320 				    optarg);
321 			break;
322 #ifdef COMPAT
323 		case 'T':
324 			disktype = optarg;
325 			break;
326 #endif
327 		case 'V':
328 			verbosity = strsuftoi64("verbose", optarg, 0, 4, NULL);
329 			break;
330 		case 'Z':
331 			Zflag = 1;
332 			break;
333 		case 'a':
334 			maxcontig = strsuftoi64("maximum contiguous blocks",
335 			    optarg, 1, INT_MAX, NULL);
336 			break;
337 		case 'b':
338 			bsize = strsuftoi64("block size",
339 			    optarg, MINBSIZE, MAXBSIZE, NULL);
340 			break;
341 		case 'd':
342 			maxbsize = strsuftoi64("maximum extent size",
343 			    optarg, 0, INT_MAX, NULL);
344 			break;
345 		case 'e':
346 			maxbpg = strsuftoi64(
347 			    "blocks per file in a cylinder group",
348 			    optarg, 1, INT_MAX, NULL);
349 			break;
350 		case 'f':
351 			fsize = strsuftoi64("fragment size",
352 			    optarg, 1, MAXBSIZE, NULL);
353 			break;
354 		case 'g':
355 			if (mfs)
356 				mfsgid = mfs_group(optarg);
357 			else {
358 				avgfilesize = strsuftoi64("average file size",
359 				    optarg, 1, INT_MAX, NULL);
360 			}
361 			break;
362 		case 'h':
363 			avgfpdir = strsuftoi64("expected files per directory",
364 			    optarg, 1, INT_MAX, NULL);
365 			break;
366 		case 'i':
367 			density = strsuftoi64("bytes per inode",
368 			    optarg, 1, INT_MAX, NULL);
369 			break;
370 		case 'm':
371 			minfree = strsuftoi64("free space %",
372 			    optarg, 0, 99, NULL);
373 			break;
374 		case 'n':
375 			num_inodes = strsuftoi64("number of inodes",
376 			    optarg, 1, INT_MAX, NULL);
377 			break;
378 		case 'o':
379 			if (mfs) {
380 				mo = getmntopts(optarg, mopts, &mntflags, 0);
381 				if (mo == NULL)
382 					err(1, "getmntopts");
383 				freemntopts(mo);
384 			} else {
385 				if (strcmp(optarg, "space") == 0)
386 					opt = FS_OPTSPACE;
387 				else if (strcmp(optarg, "time") == 0)
388 					opt = FS_OPTTIME;
389 				else
390 				    errx(1, "%s %s",
391 					"unknown optimization preference: ",
392 					"use `space' or `time'.");
393 			}
394 			break;
395 		case 'q':
396 			if      (strcmp(optarg, "user") == 0)
397 				quotas |= FS_Q2_DO_TYPE(USRQUOTA);
398 			else if (strcmp(optarg, "group") == 0)
399 				quotas |= FS_Q2_DO_TYPE(GRPQUOTA);
400 			else
401 				errx(1, "invalid quota type %s", optarg);
402 			break;
403 		case 'p':
404 			/* mfs only */
405 			if ((mfsmode = strtol(optarg, NULL, 8)) <= 0)
406 				errx(1, "bad mode `%s'", optarg);
407 			break;
408 		case 's':
409 			fssize = strsuftoi64("file system size",
410 			    optarg, INT64_MIN, INT64_MAX, &byte_sized);
411 			break;
412 		case 'u':
413 			/* mfs only */
414 			mfsuid = mfs_user(optarg);
415 			break;
416 		case 'v':
417 			appleufs_volname = optarg;
418 			if (strchr(appleufs_volname, ':') || strchr(appleufs_volname, '/'))
419 				errx(1,"Apple UFS volume name cannot contain ':' or '/'");
420 			if (appleufs_volname[0] == '\0')
421 				errx(1,"Apple UFS volume name cannot be zero length");
422 			isappleufs = 1;
423 			break;
424 		case '?':
425 		default:
426 			usage();
427 		}
428 	argc -= optind;
429 	argv += optind;
430 
431 	if (Oflag < 1 && quotas != 0)
432 		errx(1, "in-filesystem quota is incompatible with -O0");
433 
434 	if (verbosity == -1)
435 		/* Default to not showing CG info if mfs */
436 		verbosity = mfs ? 0 : DEFAULT_VERBOSITY;
437 
438 #ifdef MFS
439 	/* This is enough to get through the correct kernel code paths */
440 	memset(&args, 0, sizeof args);
441 	args.fspec = mountfromname;
442 	if (mntflags & (MNT_GETARGS | MNT_UPDATE)) {
443 		if ((mntflags & MNT_GETARGS) == 0)
444 			mntflags |= MNT_ASYNC;
445 		if (mount(MOUNT_MFS, argv[1], mntflags,
446 		    &args, sizeof args) == -1)
447 			err(1, "mount `%s' failed", argv[1]);
448 		if (mntflags & MNT_GETARGS)
449 			printf("base=%p, size=%ld\n", args.base, args.size);
450 		exit(0);
451 	}
452 #endif
453 
454 	if (argc != 2 && (mfs || argc != 1))
455 		usage();
456 
457 	memset(&sb, 0, sizeof sb);
458 	memset(&dkw, 0, sizeof dkw);
459 	special = argv[0];
460 	if (Fflag || mfs) {
461 		/*
462 		 * It's a file system image or an MFS,
463 		 * no label, use fixed default for sectorsize.
464 		 */
465 		if (sectorsize == 0)
466 			sectorsize = DFL_SECSIZE;
467 
468 		if (mfs) {
469 			/*
470 			 * Default filesystem size to that of supplied device,
471 			 * and fall back to 8M
472 			 */
473 			if (fssize == 0)
474 				if (stat(special, &sb) == -1)
475 					fssize = DFL_FSSIZE / sectorsize;
476 		} else {
477 			/* creating image in a regular file */
478 			int fl;
479 			if (Nflag)
480 				fl = O_RDONLY;
481 			else {
482 				if (fssize > 0)
483 					fl = O_RDWR | O_CREAT;
484 				else
485 					fl = O_RDWR;
486 			}
487 			fsi = open(special, fl, 0777);
488 			if (fsi == -1)
489 				err(1, "can't open file %s", special);
490 			if (fstat(fsi, &sb) == -1)
491 				err(1, "can't fstat opened %s", special);
492 			if (!Nflag)
493 				fso = fsi;
494 		}
495 	} else {	/* !Fflag && !mfs */
496 		raw = getfsspecname(specname, sizeof(specname), special);
497 		if (raw == NULL)
498 			err(1, "%s: %s", special, specname);
499 		special = getdiskrawname(rawname, sizeof(rawname), raw);
500 		if (special == NULL)
501 			special = raw;
502 
503 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
504 		special = device;
505 		if (fsi < 0 || fstat(fsi, &sb) == -1)
506 			err(1, "%s: open for read", special);
507 		if (S_ISBLK(sb.st_mode)) {
508 			errx(1, "%s is a block device. use raw device",
509 			    special);
510 		}
511 
512 		if (!Nflag) {
513 			fso = open(special, O_WRONLY, 0);
514 			if (fso < 0)
515 				err(1, "%s: open for write", special);
516 
517 			/* Bail if target special is mounted */
518 			n = getmntinfo(&mp, MNT_NOWAIT);
519 			if (n == 0)
520 				err(1, "%s: getmntinfo", special);
521 
522 			len = sizeof(_PATH_DEV) - 1;
523 			s1 = special;
524 			if (strncmp(_PATH_DEV, s1, len) == 0)
525 				s1 += len;
526 
527 			while (--n >= 0) {
528 				s2 = mp->f_mntfromname;
529 				if (strncmp(_PATH_DEV, s2, len) == 0) {
530 					s2 += len - 1;
531 					*s2 = 'r';
532 				}
533 				if (strcmp(s1, s2) == 0 ||
534 				    strcmp(s1, &s2[1]) == 0)
535 					errx(1, "%s is mounted on %s",
536 					    special, mp->f_mntonname);
537 				++mp;
538 			}
539 		}
540 
541 #ifdef COMPAT
542 		if (disktype == NULL)
543 			disktype = argv[1];
544 #endif
545 		if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
546 			errx(1, lmsg, special);
547 		unlabeled = disktype != NULL;
548 
549 		if (sectorsize == 0) {
550 			sectorsize = geo.dg_secsize;
551 			if (sectorsize <= 0)
552 				errx(1, "no default sector size");
553 		}
554 
555 		if (dkw.dkw_parent[0]) {
556 			if (dkw.dkw_size == 0)
557 				errx(1, "%s partition is unavailable", special);
558 
559 			if (strcmp(dkw.dkw_ptype, DKW_PTYPE_APPLEUFS) == 0)
560 				isappleufs = 1;
561 
562 			if (!Iflag) {
563 				static const char m[] =
564 				    "%s partition type is not `%s'";
565 				if (isappleufs) {
566 					if (strcmp(dkw.dkw_ptype,
567 					    DKW_PTYPE_APPLEUFS))
568 						errx(1, m,
569 						    special, "Apple UFS");
570 				} else {
571 					if (strcmp(dkw.dkw_ptype,
572 					    DKW_PTYPE_FFS))
573 						errx(1, m, special, "4.2BSD");
574 				}
575 			}
576 		}	/* !Fflag && !mfs */
577 	}
578 
579 	if (byte_sized)
580 		fssize /= sectorsize;
581 	if (fssize <= 0) {
582 		if (sb.st_size != 0)
583 			fssize += sb.st_size / sectorsize;
584 		else
585 			fssize += dkw.dkw_size;
586 		if (fssize <= 0)
587 			errx(1, "Unable to determine file system size");
588 	}
589 
590 	if (dkw.dkw_parent[0] && (uint64_t)fssize > dkw.dkw_size)
591 		errx(1, "size %" PRIu64 " exceeds maximum file system size on "
592 		    "`%s' of %" PRIu64 " sectors",
593 		    fssize, special, dkw.dkw_size);
594 
595 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
596 	if (Fflag && fso != -1
597 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
598 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
599 
600 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparce) the file */
601 		char	*buf;
602 		int	bufsize, i;
603 		off_t	bufrem;
604 		struct statvfs sfs;
605 
606 		if (fstatvfs(fso, &sfs) == -1) {
607 			warn("can't fstatvfs `%s'", special);
608 			bufsize = 8192;
609 		} else
610 			bufsize = sfs.f_iosize;
611 
612 		if ((buf = calloc(1, bufsize)) == NULL)
613 			err(1, "can't malloc buffer of %d",
614 			bufsize);
615 		bufrem = fssize * sectorsize;
616 		if (verbosity > 0)
617 			printf( "Creating file system image in `%s', "
618 			    "size %lld bytes, in %d byte chunks.\n",
619 			    special, (long long)bufrem, bufsize);
620 		while (bufrem > 0) {
621 			i = write(fso, buf, MIN(bufsize, bufrem));
622 			if (i == -1)
623 				err(1, "writing image");
624 			bufrem -= i;
625 		}
626 		free(buf);
627 	}
628 
629 	/* Sort out fragment and block sizes */
630 	if (fsize == 0) {
631 		fsize = bsize / DFL_FRAG_BLK;
632 		if (fsize <= 0) {
633 			if (isappleufs) {
634 				fsize = APPLEUFS_DFL_FRAGSIZE;
635 			} else {
636 				if (fssize < SMALL_FSSIZE)
637 					fsize = S_DFL_FRAGSIZE;
638 				else if (fssize < MEDIUM_FSSIZE)
639 					fsize = M_DFL_FRAGSIZE;
640 				else if (fssize < LARGE_FSSIZE)
641 					fsize = L_DFL_FRAGSIZE;
642 				else
643 					fsize = LL_DFL_FRAGSIZE;
644 				if (fsize < sectorsize)
645 					fsize = sectorsize;
646 			}
647 		}
648 	}
649 	if (bsize <= 0) {
650 		if (isappleufs)
651 			bsize = APPLEUFS_DFL_BLKSIZE;
652 		else
653 			bsize = DFL_FRAG_BLK * fsize;
654 	}
655 
656 	if (isappleufs && (fsize < APPLEUFS_DFL_FRAGSIZE)) {
657 		warnx("Warning: chosen fsize of %d is less than Apple UFS minimum of %d",
658 			fsize, APPLEUFS_DFL_FRAGSIZE);
659 	}
660 	if (isappleufs && (bsize > APPLEUFS_DFL_BLKSIZE)) {
661 		warnx("Warning: chosen bsize of %d is greater than Apple UFS maximum of %d",
662 			bsize, APPLEUFS_DFL_BLKSIZE);
663 	}
664 
665 	/*
666 	 * Maxcontig sets the default for the maximum number of blocks
667 	 * that may be allocated sequentially. With filesystem clustering
668 	 * it is possible to allocate contiguous blocks up to the maximum
669 	 * transfer size permitted by the controller or buffering.
670 	 */
671 	if (maxcontig == 0)
672 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
673 	if (density == 0)
674 		density = NFPI * fsize;
675 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
676 		warnx("%s %s %d%%", "Warning: changing optimization to space",
677 		    "because minfree is less than", MINFREE);
678 		opt = FS_OPTSPACE;
679 	}
680 	if (maxbpg == 0) {
681 		if (Oflag <= 1)
682 			maxbpg = MAXBLKPG_UFS1(bsize);
683 		else
684 			maxbpg = MAXBLKPG_UFS2(bsize);
685 	}
686 	mkfs(special, fsi, fso, mfsmode, mfsuid, mfsgid);
687 	if (fsi != -1 && fsi != fso)
688 		close(fsi);
689 	if (fso != -1)
690 		close(fso);
691 #ifdef MFS
692 	if (mfs) {
693 
694 		pathadj(argv[1], mounttoname);
695 		switch (pid = fork()) {
696 		case -1:
697 			perror("mfs");
698 			exit(10);
699 		case 0:
700 			(void)snprintf(mountfromname, sizeof(mountfromname),
701 			    "mfs:%d", getpid());
702 			break;
703 		default:
704 			(void)snprintf(mountfromname, sizeof(mountfromname),
705 			    "mfs:%d", pid);
706 			for (;;) {
707 				/*
708 				 * spin until the mount succeeds
709 				 * or the child exits
710 				 */
711 				usleep(1);
712 
713 				/*
714 				 * XXX Here is a race condition: another process
715 				 * can mount a filesystem which hides our
716 				 * ramdisk before we see the success.
717 				 */
718 				if (statvfs(mounttoname, &sf) < 0)
719 					err(88, "statvfs %s", mounttoname);
720 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
721 				    !strncmp(sf.f_mntonname, mounttoname,
722 					     MNAMELEN) &&
723 				    !strcmp(sf.f_fstypename, "mfs"))
724 					exit(0);
725 
726 				res = waitpid(pid, &status, WNOHANG);
727 				if (res == -1)
728 					err(11, "waitpid");
729 				if (res != pid)
730 					continue;
731 				if (WIFEXITED(status)) {
732 					if (WEXITSTATUS(status) == 0)
733 						exit(0);
734 					errx(1, "%s: mount: %s", mounttoname,
735 					     strerror(WEXITSTATUS(status)));
736 				} else
737 					errx(11, "abnormal termination");
738 			}
739 			/* NOTREACHED */
740 		}
741 
742 		(void) setsid();
743 		(void) close(0);
744 		(void) close(1);
745 		(void) close(2);
746 		(void) chdir("/");
747 
748 		args.base = membase;
749 		args.size = fssize * sectorsize;
750 		if (mount(MOUNT_MFS, mounttoname, mntflags | MNT_ASYNC,
751 		    &args, sizeof args) == -1)
752 			exit(errno); /* parent prints message */
753 	}
754 #endif
755 	exit(0);
756 }
757 
758 static gid_t
759 mfs_group(const char *gname)
760 {
761 	struct group *gp;
762 
763 	if (!(gp = getgrnam(gname)) && !isdigit((unsigned char)*gname))
764 		errx(1, "unknown gname %s", gname);
765 	return gp ? gp->gr_gid : (gid_t)atoi(gname);
766 }
767 
768 static uid_t
769 mfs_user(const char *uname)
770 {
771 	struct passwd *pp;
772 
773 	if (!(pp = getpwnam(uname)) && !isdigit((unsigned char)*uname))
774 		errx(1, "unknown user %s", uname);
775 	return pp ? pp->pw_uid : (uid_t)atoi(uname);
776 }
777 
778 static int64_t
779 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
780 {
781 	int64_t result, r1;
782 	int shift = 0;
783 	char	*ep;
784 
785 	errno = 0;
786 	r1 = strtoll(arg, &ep, 10);
787 	if (ep[0] != '\0' && ep[1] != '\0')
788 		errx(1, "%s `%s' is not a valid number.", desc, arg);
789 	switch (ep[0]) {
790 	case '\0':
791 	case 's': case 'S':
792 		if (num_suffix != NULL)
793 			*num_suffix = 0;
794 		break;
795 	case 't': case 'T':
796 		shift += 10;
797 		/* FALLTHROUGH */
798 	case 'g': case 'G':
799 		shift += 10;
800 		/* FALLTHROUGH */
801 	case 'm': case 'M':
802 		shift += 10;
803 		/* FALLTHROUGH */
804 	case 'k': case 'K':
805 		shift += 10;
806 		/* FALLTHROUGH */
807 	case 'b': case 'B':
808 		if (num_suffix != NULL)
809 			*num_suffix = 1;
810 		break;
811 	default:
812 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
813 	}
814 	result = r1 << shift;
815 	if (errno == ERANGE || result >> shift != r1)
816 		errx(1, "%s `%s' is too large to convert.", desc, arg);
817 	if (result < min) {
818 		if (Gflag) {
819 			warnx("%s `%s' (%" PRId64 ") is less than the "
820 			    "minimum (%" PRId64 ").", desc, arg, result, min);
821 		} else {
822 			errx(1, "%s `%s' (%" PRId64 ") is less than the "
823 			    "minimum (%" PRId64 ").", desc, arg, result, min);
824 		}
825 	}
826 	if (result > max) {
827 		if (Gflag) {
828 			warnx("%s `%s' (%" PRId64 ") is greater than the "
829 			    "maximum (%" PRId64 ").", desc, arg, result, max);
830 		} else {
831 			errx(1, "%s `%s' (%" PRId64 ") is greater than the "
832 			    "maximum (%" PRId64 ").", desc, arg, result, max);
833 		}
834 	}
835 	return result;
836 }
837 
838 #define	NEWFS		1
839 #define	MFS_MOUNT	2
840 #define	BOTH		NEWFS | MFS_MOUNT
841 
842 struct help_strings {
843 	int flags;
844 	const char *str;
845 } const help_strings[] = {
846 	{ NEWFS,	"-B byteorder\tbyte order (`be' or `le')" },
847 	{ NEWFS,	"-F \t\tcreate file system image in regular file" },
848 	{ NEWFS,	"-G \t\tmake sanity calculations non-fatal (testing only!)" },
849 	{ NEWFS,	"-I \t\tdo not check that the file system type is '4.2BSD'" },
850 	{ BOTH,		"-N \t\tdo not create file system, just print out "
851 			    "parameters" },
852 	{ NEWFS,	"-O N\t\tfilesystem format: 0 => 4.3BSD, 1 => FFSv1, 2 => FFSv2" },
853 	{ NEWFS,	"-S secsize\tsector size" },
854 #ifdef COMPAT
855 	{ NEWFS,	"-T disktype\tdisk type" },
856 #endif
857 	{ BOTH,		"-V verbose\toutput verbosity: 0 ==> none, 4 ==> max" },
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 	{ BOTH,		"-q (user|group) enable specified quota" },
874 	{ MFS_MOUNT,	"-p perm\t\tpermissions (in octal)" },
875 	{ BOTH,		"-s fssize\tfile system size (sectors)" },
876 	{ MFS_MOUNT,	"-u username\tuser name of mount point" },
877 	{ NEWFS,	"-v volname\tApple UFS volume name" },
878 	{ 0, NULL }
879 };
880 
881 static void
882 usage(void)
883 {
884 	int match;
885 	const struct help_strings *hs;
886 
887 	if (mfs) {
888 		fprintf(stderr,
889 		    "usage: %s [ fsoptions ] special-device mount-point\n",
890 			getprogname());
891 	} else
892 		fprintf(stderr,
893 		    "usage: %s [ fsoptions ] special-device%s\n",
894 		    getprogname(),
895 #ifdef COMPAT
896 		    " [disk-type]");
897 #else
898 		    "");
899 #endif
900 	fprintf(stderr, "where fsoptions are:\n");
901 
902 	match = mfs ? MFS_MOUNT : NEWFS;
903 	for (hs = help_strings; hs->flags != 0; hs++)
904 		if (hs->flags & match)
905 			fprintf(stderr, "\t%s\n", hs->str);
906 	exit(1);
907 }
908