xref: /netbsd-src/sbin/newfs/newfs.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: newfs.c,v 1.87 2005/11/28 22:35:06 dsl 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.87 2005/11/28 22:35:06 dsl 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, "size %" PRIu64 " exceeds maximum file system size on "
518 		    "`%s' of %u sectors",
519 		    fssize, special, pp->p_size);
520 
521 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
522 	if (Fflag && fso != -1
523 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
524 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
525 
526 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparce) the file */
527 		char	*buf;
528 		int	bufsize, i;
529 		off_t	bufrem;
530 		struct statvfs sfs;
531 
532 		if (fstatvfs(fso, &sfs) == -1) {
533 			warn("can't fstatvfs `%s'", special);
534 			bufsize = 8192;
535 		} else
536 			bufsize = sfs.f_iosize;
537 
538 		if ((buf = calloc(1, bufsize)) == NULL)
539 			err(1, "can't malloc buffer of %d",
540 			bufsize);
541 		bufrem = fssize * sectorsize;
542 		printf(
543     "Creating file system image in `%s', size %lld bytes, in %d byte chunks.\n",
544 		    special, (long long)bufrem, bufsize);
545 		while (bufrem > 0) {
546 			i = write(fso, buf, MIN(bufsize, bufrem));
547 			if (i == -1)
548 				err(1, "writing image");
549 			bufrem -= i;
550 		}
551 		free(buf);
552 	}
553 
554 	/* Sort out fragment and block sizes */
555 	if (fsize == 0) {
556 		fsize = bsize / DFL_FRAG_BLK;
557 		if (fsize == 0)
558 			fsize = oldpartition.p_fsize;
559 		if (fsize <= 0) {
560 			if (isappleufs) {
561 				fsize = APPLEUFS_DFL_FRAGSIZE;
562 			} else {
563 				if (fssize < SMALL_FSSIZE)
564 					fsize = S_DFL_FRAGSIZE;
565 				else if (fssize < MEDIUM_FSSIZE)
566 					fsize = M_DFL_FRAGSIZE;
567 				else
568 					fsize = L_DFL_FRAGSIZE;
569 				if (fsize < sectorsize)
570 					fsize = sectorsize;
571 			}
572 		}
573 	}
574 	if (bsize == 0) {
575 		bsize = oldpartition.p_frag * oldpartition.p_fsize;
576 		if (bsize <= 0) {
577 			if (isappleufs)
578 				bsize = APPLEUFS_DFL_BLKSIZE;
579 			else
580 				bsize = DFL_FRAG_BLK * fsize;
581 		}
582 	}
583 
584 	if (isappleufs && (fsize < APPLEUFS_DFL_FRAGSIZE)) {
585 		warnx("Warning: chosen fsize of %d is less than Apple UFS minimum of %d",
586 			fsize, APPLEUFS_DFL_FRAGSIZE);
587 	}
588 	if (isappleufs && (bsize > APPLEUFS_DFL_BLKSIZE)) {
589 		warnx("Warning: chosen bsize of %d is greater than Apple UFS maximum of %d",
590 			bsize, APPLEUFS_DFL_BLKSIZE);
591 	}
592 
593 	/*
594 	 * Maxcontig sets the default for the maximum number of blocks
595 	 * that may be allocated sequentially. With filesystem clustering
596 	 * it is possible to allocate contiguous blocks up to the maximum
597 	 * transfer size permitted by the controller or buffering.
598 	 */
599 	if (maxcontig == 0)
600 		maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
601 	if (density == 0)
602 		density = NFPI * fsize;
603 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
604 		warnx("%s %s %d%%", "Warning: changing optimization to space",
605 		    "because minfree is less than", MINFREE);
606 		opt = FS_OPTSPACE;
607 	}
608 	if (maxbpg == 0) {
609 		if (Oflag <= 1)
610 			maxbpg = MAXBLKPG_UFS1(bsize);
611 		else
612 			maxbpg = MAXBLKPG_UFS2(bsize);
613 	}
614 	mkfs(pp, special, fsi, fso, mfsmode, mfsuid, mfsgid);
615 	if (!Nflag && pp != NULL
616 	    && memcmp(pp, &oldpartition, sizeof(oldpartition)))
617 		rewritelabel(special, fso, lp);
618 	if (fsi != -1 && fsi != fso)
619 		close(fsi);
620 	if (fso != -1)
621 		close(fso);
622 #ifdef MFS
623 	if (mfs) {
624 
625 		switch (pid = fork()) {
626 		case -1:
627 			perror("mfs");
628 			exit(10);
629 		case 0:
630 			(void)snprintf(mountfromname, sizeof(mountfromname),
631 			    "mfs:%d", getpid());
632 			break;
633 		default:
634 			(void)snprintf(mountfromname, sizeof(mountfromname),
635 			    "mfs:%d", pid);
636 			for (;;) {
637 				/*
638 				 * spin until the mount succeeds
639 				 * or the child exits
640 				 */
641 				usleep(1);
642 
643 				/*
644 				 * XXX Here is a race condition: another process
645 				 * can mount a filesystem which hides our
646 				 * ramdisk before we see the success.
647 				 */
648 				if (statvfs(argv[1], &sf) < 0)
649 					err(88, "statvfs %s", argv[1]);
650 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
651 				    !strncmp(sf.f_mntonname, argv[1],
652 					     MNAMELEN) &&
653 				    !strcmp(sf.f_fstypename, "mfs"))
654 					exit(0);
655 
656 				res = waitpid(pid, &status, WNOHANG);
657 				if (res == -1)
658 					err(11, "waitpid");
659 				if (res != pid)
660 					continue;
661 				if (WIFEXITED(status)) {
662 					if (WEXITSTATUS(status) == 0)
663 						exit(0);
664 					errx(1, "%s: mount: %s", argv[1],
665 					     strerror(WEXITSTATUS(status)));
666 				} else
667 					errx(11, "abnormal termination");
668 			}
669 			/* NOTREACHED */
670 		}
671 
672 		(void) setsid();
673 		(void) close(0);
674 		(void) close(1);
675 		(void) close(2);
676 		(void) chdir("/");
677 
678 		args.base = membase;
679 		args.size = fssize * sectorsize;
680 		if (mount(MOUNT_MFS, argv[1], mntflags, &args) < 0)
681 			exit(errno); /* parent prints message */
682 	}
683 #endif
684 	exit(0);
685 }
686 
687 #ifdef COMPAT
688 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
689 #else
690 const char lmsg[] = "%s: can't read disk label";
691 #endif
692 
693 static struct disklabel *
694 getdisklabel(char *s, int fd)
695 {
696 	static struct disklabel lab;
697 
698 #ifdef COMPAT
699 	if (disktype) {
700 		struct disklabel *lp;
701 
702 		unlabeled++;
703 		lp = getdiskbyname(disktype);
704 		if (lp == NULL)
705 			errx(1, "%s: unknown disk type", disktype);
706 		return (lp);
707 	}
708 #endif
709 	if (ioctl(fd, DIOCGDINFO, &lab) < 0) {
710 		warn("ioctl (GDINFO)");
711 		errx(1, lmsg, s);
712 	}
713 	return (&lab);
714 }
715 
716 static void
717 rewritelabel(char *s, int fd, struct disklabel *lp)
718 {
719 #ifdef COMPAT
720 	if (unlabeled)
721 		return;
722 #endif
723 	lp->d_checksum = 0;
724 	lp->d_checksum = dkcksum(lp);
725 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
726 		if (errno == ESRCH)
727 			return;
728 		warn("ioctl (WDINFO)");
729 		errx(1, "%s: can't rewrite disk label", s);
730 	}
731 #if __vax__
732 	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
733 		int i;
734 		int cfd;
735 		daddr_t alt;
736 		off_t loff;
737 		char specname[64];
738 		char blk[1024];
739 		char *cp;
740 
741 		/*
742 		 * Make name for 'c' partition.
743 		 */
744 		strlcpy(specname, s, sizeof(specname));
745 		cp = specname + strlen(specname) - 1;
746 		if (!isdigit((unsigned char)*cp))
747 			*cp = 'c';
748 		cfd = open(specname, O_WRONLY);
749 		if (cfd < 0)
750 			err(1, "%s: open", specname);
751 		if ((loff = getlabeloffset()) < 0)
752 			err(1, "getlabeloffset()");
753 		memset(blk, 0, sizeof(blk));
754 		*(struct disklabel *)(blk + loff) = *lp;
755 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
756 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
757 			off_t offset;
758 
759 			offset = alt + i;
760 			offset *= lp->d_secsize;
761 			if (lseek(cfd, offset, SEEK_SET) == -1)
762 				err(1, "lseek to badsector area: ");
763 			if (write(cfd, blk, lp->d_secsize) < lp->d_secsize)
764 				warn("alternate label %d write", i/2);
765 		}
766 		close(cfd);
767 	}
768 #endif
769 }
770 
771 static gid_t
772 mfs_group(const char *gname)
773 {
774 	struct group *gp;
775 
776 	if (!(gp = getgrnam(gname)) && !isdigit((unsigned char)*gname))
777 		errx(1, "unknown gname %s", gname);
778 	return gp ? gp->gr_gid : atoi(gname);
779 }
780 
781 static uid_t
782 mfs_user(const char *uname)
783 {
784 	struct passwd *pp;
785 
786 	if (!(pp = getpwnam(uname)) && !isdigit((unsigned char)*uname))
787 		errx(1, "unknown user %s", uname);
788 	return pp ? pp->pw_uid : atoi(uname);
789 }
790 
791 static int64_t
792 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
793 {
794 	int64_t result, r1;
795 	int shift = 0;
796 	char	*ep;
797 
798 	errno = 0;
799 	r1 = strtoll(arg, &ep, 10);
800 	if (ep[0] != '\0' && ep[1] != '\0')
801 		errx(1, "%s `%s' is not a valid number.", desc, arg);
802 	switch (ep[0]) {
803 	case '\0':
804 	case 's': case 'S':
805 		if (num_suffix != NULL)
806 			*num_suffix = 0;
807 		break;
808 	case 'g': case 'G':
809 		shift += 10;
810 		/* FALLTHROUGH */
811 	case 'm': case 'M':
812 		shift += 10;
813 		/* FALLTHROUGH */
814 	case 'k': case 'K':
815 		shift += 10;
816 		/* FALLTHROUGH */
817 	case 'b': case 'B':
818 		if (num_suffix != NULL)
819 			*num_suffix = 1;
820 		break;
821 	default:
822 		errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
823 	}
824 	result = r1 << shift;
825 	if (errno == ERANGE || result >> shift != r1)
826 		errx(1, "%s `%s' is too large to convert.", desc, arg);
827 	if (result < min)
828 		errx(1, "%s `%s' (%" PRId64 ") is less than the minimum (%" PRId64 ").",
829 		    desc, arg, result, min);
830 	if (result > max)
831 		errx(1, "%s `%s' (%" PRId64 ") is greater than the maximum (%" PRId64 ").",
832 		    desc, arg, result, max);
833 	return result;
834 }
835 
836 #define	NEWFS		1
837 #define	MFS_MOUNT	2
838 #define	BOTH		NEWFS | MFS_MOUNT
839 
840 struct help_strings {
841 	int flags;
842 	const char *str;
843 } const help_strings[] = {
844 	{ NEWFS,	"-B byteorder\tbyte order (`be' or `le')" },
845 	{ NEWFS,	"-F \t\tcreate file system image in regular file" },
846 	{ NEWFS,	"-I \t\tdo not check that the file system type is '4.2BSD'" },
847 	{ BOTH,		"-N \t\tdo not create file system, just print out "
848 			    "parameters" },
849 	{ NEWFS,	"-O N\t\tfilesystem format: 0 ==> 4.3BSD, 1 ==> FFS, 2 ==> UFS2" },
850 	{ NEWFS,	"-S secsize\tsector size" },
851 #ifdef COMPAT
852 	{ NEWFS,	"-T disktype\tdisk type" },
853 #endif
854 	{ NEWFS,	"-Z \t\tpre-zero the image file" },
855 	{ BOTH,		"-a maxcontig\tmaximum contiguous blocks" },
856 	{ BOTH,		"-b bsize\tblock size" },
857 	{ BOTH,		"-d maxbsize\tmaximum extent size" },
858 	{ BOTH,		"-e maxbpg\tmaximum blocks per file in a cylinder group"
859 			    },
860 	{ BOTH,		"-f fsize\tfrag size" },
861 	{ NEWFS,	"-g avgfilesize\taverage file size" },
862 	{ MFS_MOUNT,	"-g groupname\tgroup name of mount point" },
863 	{ BOTH,		"-h avgfpdir\taverage files per directory" },
864 	{ BOTH,		"-i density\tnumber of bytes per inode" },
865 	{ BOTH,		"-m minfree\tminimum free space %%" },
866 	{ BOTH,		"-n inodes\tnumber of inodes (overrides -i density)" },
867 	{ BOTH,		"-o optim\toptimization preference (`space' or `time')"
868 			    },
869 	{ MFS_MOUNT,	"-p perm\t\tpermissions (in octal)" },
870 	{ BOTH,		"-s fssize\tfile system size (sectors)" },
871 	{ MFS_MOUNT,	"-u username\tuser name of mount point" },
872 	{ NEWFS,	"-v volname\tApple UFS volume name" },
873 	{ 0, NULL }
874 };
875 
876 static void
877 usage(void)
878 {
879 	int match;
880 	const struct help_strings *hs;
881 
882 	if (mfs) {
883 		fprintf(stderr,
884 		    "usage: %s [ fsoptions ] special-device mount-point\n",
885 			getprogname());
886 	} else
887 		fprintf(stderr,
888 		    "usage: %s [ fsoptions ] special-device%s\n",
889 		    getprogname(),
890 #ifdef COMPAT
891 		    " [disk-type]");
892 #else
893 		    "");
894 #endif
895 	fprintf(stderr, "where fsoptions are:\n");
896 
897 	match = mfs ? MFS_MOUNT : NEWFS;
898 	for (hs = help_strings; hs->flags != 0; hs++)
899 		if (hs->flags & match)
900 			fprintf(stderr, "\t%s\n", hs->str);
901 	exit(1);
902 }
903