newfs.c revision 1.116 1 /* $NetBSD: newfs.c,v 1.116 2020/04/17 09:33:37 jdolecek 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.116 2020/04/17 09:33:37 jdolecek 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 #ifndef NO_FFS_EI
229 int needswap; /* Filesystem not in native byte order */
230 #endif
231 char *disktype = NULL;
232 int unlabeled;
233 #ifndef NO_APPLE_UFS
234 char *appleufs_volname = 0; /* Apple UFS volume name */
235 int isappleufs = 0;
236 #endif
237 int quotas = 0;
238
239 char device[MAXPATHLEN];
240
241 int
242 main(int argc, char *argv[])
243 {
244 struct disk_geom geo;
245 struct dkwedge_info dkw;
246 struct statvfs *mp;
247 struct stat sb;
248 int ch, fsi, fso, len, n, Fflag, Iflag, Zflag;
249 const char *s1, *special, *raw;
250 char *s2;
251 char specname[MAXPATHLEN];
252 char rawname[MAXPATHLEN];
253 const char *opstring;
254 int byte_sized = 0;
255 #ifdef MFS
256 struct mfs_args args;
257 char mountfromname[100];
258 char mounttoname[MAXPATHLEN];
259 pid_t pid, res;
260 struct statvfs sf;
261 int status;
262 #endif
263 mode_t mfsmode = 01777; /* default mode for a /tmp-type directory */
264 uid_t mfsuid = 0; /* user root */
265 gid_t mfsgid = 0; /* group wheel */
266 mntoptparse_t mo;
267
268 fsi = fso = -1;
269 Fflag = Iflag = Zflag = 0;
270 verbosity = -1;
271 if (strstr(getprogname(), "mfs")) {
272 mfs = 1;
273 } else {
274 /* Undocumented, for ease of testing */
275 if (argv[1] != NULL && !strcmp(argv[1], "-mfs")) {
276 argv++;
277 argc--;
278 mfs = 1;
279 }
280 }
281
282 opstring = mfs ?
283 "NT:V:a:b:d:e:f:g:h:i:m:n:o:p:q:s:u:" :
284 "B:FGINO:S:T:V:Za:b:d:e:f:g:h:i:l:m:n:o:q:r:s:v:";
285 while ((ch = getopt(argc, argv, opstring)) != -1)
286 switch (ch) {
287 #ifndef NO_FFS_EI
288 case 'B':
289 if (strcmp(optarg, "be") == 0) {
290 # if BYTE_ORDER == LITTLE_ENDIAN
291 needswap = 1;
292 # endif
293 } else if (strcmp(optarg, "le") == 0) {
294 # if BYTE_ORDER == BIG_ENDIAN
295 needswap = 1;
296 # endif
297 } else
298 usage();
299 break;
300 #endif
301 case 'F':
302 Fflag = 1;
303 break;
304 case 'G':
305 fprintf(stderr, "WARNING: -G may create file systems "
306 "which cause kernel panics\n");
307 Gflag = 1;
308 break;
309 case 'I':
310 Iflag = 1;
311 break;
312 case 'N':
313 Nflag = 1;
314 if (verbosity == -1)
315 verbosity = DEFAULT_VERBOSITY;
316 break;
317 case 'O':
318 Oflag = strsuftoi64("format", optarg, 0, 2, NULL);
319 break;
320 case 'S':
321 /* XXX: non-512 byte sectors almost certainly don't work. */
322 sectorsize = strsuftoi64("sector size",
323 optarg, 512, 65536, NULL);
324 if (sectorsize & (sectorsize - 1))
325 errx(1, "sector size `%s' is not a power of 2.",
326 optarg);
327 break;
328 #ifdef COMPAT
329 case 'T':
330 disktype = optarg;
331 break;
332 #endif
333 case 'V':
334 verbosity = strsuftoi64("verbose", optarg, 0, 4, NULL);
335 break;
336 case 'Z':
337 Zflag = 1;
338 break;
339 case 'a':
340 maxcontig = strsuftoi64("maximum contiguous blocks",
341 optarg, 1, INT_MAX, NULL);
342 break;
343 case 'b':
344 bsize = strsuftoi64("block size",
345 optarg, MINBSIZE, MAXBSIZE, NULL);
346 break;
347 case 'd':
348 maxbsize = strsuftoi64("maximum extent size",
349 optarg, 0, INT_MAX, NULL);
350 break;
351 case 'e':
352 maxbpg = strsuftoi64(
353 "blocks per file in a cylinder group",
354 optarg, 1, INT_MAX, NULL);
355 break;
356 case 'f':
357 fsize = strsuftoi64("fragment size",
358 optarg, 1, MAXBSIZE, NULL);
359 break;
360 case 'g':
361 if (mfs)
362 mfsgid = mfs_group(optarg);
363 else {
364 avgfilesize = strsuftoi64("average file size",
365 optarg, 1, INT_MAX, NULL);
366 }
367 break;
368 case 'h':
369 avgfpdir = strsuftoi64("expected files per directory",
370 optarg, 1, INT_MAX, NULL);
371 break;
372 case 'i':
373 density = strsuftoi64("bytes per inode",
374 optarg, 1, INT_MAX, NULL);
375 break;
376 case 'm':
377 minfree = strsuftoi64("free space %",
378 optarg, 0, 99, NULL);
379 break;
380 case 'n':
381 num_inodes = strsuftoi64("number of inodes",
382 optarg, 1, INT_MAX, NULL);
383 break;
384 case 'o':
385 if (mfs) {
386 mo = getmntopts(optarg, mopts, &mntflags, 0);
387 if (mo == NULL)
388 err(1, "getmntopts");
389 freemntopts(mo);
390 } else {
391 if (strcmp(optarg, "space") == 0)
392 opt = FS_OPTSPACE;
393 else if (strcmp(optarg, "time") == 0)
394 opt = FS_OPTTIME;
395 else
396 errx(1, "%s %s",
397 "unknown optimization preference: ",
398 "use `space' or `time'.");
399 }
400 break;
401 case 'q':
402 if (strcmp(optarg, "user") == 0)
403 quotas |= FS_Q2_DO_TYPE(USRQUOTA);
404 else if (strcmp(optarg, "group") == 0)
405 quotas |= FS_Q2_DO_TYPE(GRPQUOTA);
406 else
407 errx(1, "invalid quota type %s", optarg);
408 break;
409 case 'p':
410 /* mfs only */
411 if ((mfsmode = strtol(optarg, NULL, 8)) <= 0)
412 errx(1, "bad mode `%s'", optarg);
413 break;
414 case 's':
415 fssize = strsuftoi64("file system size",
416 optarg, INT64_MIN, INT64_MAX, &byte_sized);
417 break;
418 case 'u':
419 /* mfs only */
420 mfsuid = mfs_user(optarg);
421 break;
422 #ifndef NO_APPLE_UFS
423 case 'v':
424 appleufs_volname = optarg;
425 if (strchr(appleufs_volname, ':') || strchr(appleufs_volname, '/'))
426 errx(1,"Apple UFS volume name cannot contain ':' or '/'");
427 if (appleufs_volname[0] == '\0')
428 errx(1,"Apple UFS volume name cannot be zero length");
429 isappleufs = 1;
430 break;
431 #endif
432 case '?':
433 default:
434 usage();
435 }
436 argc -= optind;
437 argv += optind;
438
439 if (Oflag < 1 && quotas != 0)
440 errx(1, "in-filesystem quota is incompatible with -O0");
441
442 if (verbosity == -1)
443 /* Default to not showing CG info if mfs */
444 verbosity = mfs ? 0 : DEFAULT_VERBOSITY;
445
446 #ifdef MFS
447 /* This is enough to get through the correct kernel code paths */
448 memset(&args, 0, sizeof args);
449 args.fspec = mountfromname;
450 if (mntflags & (MNT_GETARGS | MNT_UPDATE)) {
451 if ((mntflags & MNT_GETARGS) == 0)
452 mntflags |= MNT_ASYNC;
453 if (mount(MOUNT_MFS, argv[1], mntflags,
454 &args, sizeof args) == -1)
455 err(1, "mount `%s' failed", argv[1]);
456 if (mntflags & MNT_GETARGS)
457 printf("base=%p, size=%ld\n", args.base, args.size);
458 exit(0);
459 }
460 #endif
461
462 if (argc != 2 && (mfs || argc != 1))
463 usage();
464
465 memset(&sb, 0, sizeof sb);
466 memset(&dkw, 0, sizeof dkw);
467 special = argv[0];
468 if (Fflag || mfs) {
469 /*
470 * It's a file system image or an MFS,
471 * no label, use fixed default for sectorsize.
472 */
473 if (sectorsize == 0)
474 sectorsize = DFL_SECSIZE;
475
476 if (mfs) {
477 /*
478 * Default filesystem size to that of supplied device,
479 * and fall back to 8M
480 */
481 if (fssize == 0)
482 if (stat(special, &sb) == -1)
483 fssize = DFL_FSSIZE / sectorsize;
484 } else {
485 /* creating image in a regular file */
486 int fl;
487 if (Nflag)
488 fl = O_RDONLY;
489 else {
490 if (fssize > 0)
491 fl = O_RDWR | O_CREAT;
492 else
493 fl = O_RDWR;
494 }
495 fsi = open(special, fl, 0777);
496 if (fsi == -1)
497 err(1, "can't open file %s", special);
498 if (fstat(fsi, &sb) == -1)
499 err(1, "can't fstat opened %s", special);
500 if (!Nflag)
501 fso = fsi;
502 }
503 } else { /* !Fflag && !mfs */
504 raw = getfsspecname(specname, sizeof(specname), special);
505 if (raw == NULL)
506 err(1, "%s: %s", special, specname);
507 special = getdiskrawname(rawname, sizeof(rawname), raw);
508 if (special == NULL)
509 special = raw;
510
511 fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
512 special = device;
513 if (fsi < 0 || fstat(fsi, &sb) == -1)
514 err(1, "%s: open for read", special);
515 if (S_ISBLK(sb.st_mode)) {
516 errx(1, "%s is a block device. use raw device",
517 special);
518 }
519
520 if (!Nflag) {
521 fso = open(special, O_WRONLY, 0);
522 if (fso < 0)
523 err(1, "%s: open for write", special);
524
525 /* Bail if target special is mounted */
526 n = getmntinfo(&mp, MNT_NOWAIT);
527 if (n == 0)
528 err(1, "%s: getmntinfo", special);
529
530 len = sizeof(_PATH_DEV) - 1;
531 s1 = special;
532 if (strncmp(_PATH_DEV, s1, len) == 0)
533 s1 += len;
534
535 while (--n >= 0) {
536 s2 = mp->f_mntfromname;
537 if (strncmp(_PATH_DEV, s2, len) == 0) {
538 s2 += len - 1;
539 *s2 = 'r';
540 }
541 if (strcmp(s1, s2) == 0 ||
542 strcmp(s1, &s2[1]) == 0)
543 errx(1, "%s is mounted on %s",
544 special, mp->f_mntonname);
545 ++mp;
546 }
547 }
548
549 #ifdef COMPAT
550 if (disktype == NULL)
551 disktype = argv[1];
552 #endif
553 if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
554 errx(1, lmsg, special);
555 unlabeled = disktype != NULL;
556
557 if (sectorsize == 0) {
558 sectorsize = geo.dg_secsize;
559 if (sectorsize <= 0)
560 errx(1, "no default sector size");
561 }
562
563 if (dkw.dkw_parent[0]) {
564 if (dkw.dkw_size == 0)
565 errx(1, "%s partition is unavailable", special);
566
567 #ifndef NO_APPLE_UFS
568 if (strcmp(dkw.dkw_ptype, DKW_PTYPE_APPLEUFS) == 0)
569 isappleufs = 1;
570 #endif
571
572 if (!Iflag) {
573 static const char m[] =
574 "%s partition type is not `%s'";
575 if (isappleufs) {
576 if (strcmp(dkw.dkw_ptype,
577 DKW_PTYPE_APPLEUFS))
578 errx(1, m,
579 special, "Apple UFS");
580 } else {
581 if (strcmp(dkw.dkw_ptype,
582 DKW_PTYPE_FFS))
583 errx(1, m, special, "4.2BSD");
584 }
585 }
586 } /* !Fflag && !mfs */
587 }
588
589 if (byte_sized)
590 fssize /= sectorsize;
591 if (fssize <= 0) {
592 if (sb.st_size != 0)
593 fssize += sb.st_size / sectorsize;
594 else
595 fssize += dkw.dkw_size;
596 if (fssize <= 0)
597 errx(1, "Unable to determine file system size");
598 }
599
600 if (dkw.dkw_parent[0] && (uint64_t)fssize > dkw.dkw_size)
601 errx(1, "size %" PRIu64 " exceeds maximum file system size on "
602 "`%s' of %" PRIu64 " sectors",
603 fssize, special, dkw.dkw_size);
604
605 /* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
606 if (Fflag && fso != -1
607 && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
608 err(1, "can't ftruncate %s to %" PRId64, special, fssize);
609
610 if (Zflag && fso != -1) { /* pre-zero (and de-sparce) the file */
611 char *buf;
612 int bufsize, i;
613 off_t bufrem;
614 struct statvfs sfs;
615
616 if (fstatvfs(fso, &sfs) == -1) {
617 warn("can't fstatvfs `%s'", special);
618 bufsize = 8192;
619 } else
620 bufsize = sfs.f_iosize;
621
622 if ((buf = aligned_alloc(DEV_BSIZE, bufsize)) == NULL)
623 err(1, "can't malloc buffer of %d",
624 bufsize);
625 memset(buf, 0, bufsize);
626 bufrem = fssize * sectorsize;
627 if (verbosity > 0)
628 printf( "Creating file system image in `%s', "
629 "size %lld bytes, in %d byte chunks.\n",
630 special, (long long)bufrem, bufsize);
631 while (bufrem > 0) {
632 i = write(fso, buf, MIN(bufsize, bufrem));
633 if (i == -1)
634 err(1, "writing image");
635 bufrem -= i;
636 }
637 free(buf);
638 }
639
640 /* Sort out fragment and block sizes */
641 if (fsize == 0) {
642 fsize = bsize / DFL_FRAG_BLK;
643 if (fsize <= 0) {
644 if (isappleufs) {
645 fsize = APPLEUFS_DFL_FRAGSIZE;
646 } else {
647 if (fssize < SMALL_FSSIZE)
648 fsize = S_DFL_FRAGSIZE;
649 else if (fssize < MEDIUM_FSSIZE)
650 fsize = M_DFL_FRAGSIZE;
651 else if (fssize < LARGE_FSSIZE)
652 fsize = L_DFL_FRAGSIZE;
653 else
654 fsize = LL_DFL_FRAGSIZE;
655 if (fsize < sectorsize)
656 fsize = sectorsize;
657 }
658 }
659 }
660 if (bsize <= 0) {
661 if (isappleufs)
662 bsize = APPLEUFS_DFL_BLKSIZE;
663 else
664 bsize = DFL_FRAG_BLK * fsize;
665 }
666
667 if (isappleufs && (fsize < APPLEUFS_DFL_FRAGSIZE)) {
668 warnx("Warning: chosen fsize of %d is less than Apple UFS minimum of %d",
669 fsize, APPLEUFS_DFL_FRAGSIZE);
670 }
671 if (isappleufs && (bsize > APPLEUFS_DFL_BLKSIZE)) {
672 warnx("Warning: chosen bsize of %d is greater than Apple UFS maximum of %d",
673 bsize, APPLEUFS_DFL_BLKSIZE);
674 }
675
676 /*
677 * Maxcontig sets the default for the maximum number of blocks
678 * that may be allocated sequentially. With filesystem clustering
679 * it is possible to allocate contiguous blocks up to the maximum
680 * transfer size permitted by the controller or buffering.
681 */
682 if (maxcontig == 0)
683 maxcontig = MAX(1, MIN(MAXPHYS, MAXBSIZE) / bsize);
684 if (density == 0)
685 density = NFPI * fsize;
686 if (minfree < MINFREE && opt != FS_OPTSPACE) {
687 warnx("%s %s %d%%", "Warning: changing optimization to space",
688 "because minfree is less than", MINFREE);
689 opt = FS_OPTSPACE;
690 }
691 if (maxbpg == 0) {
692 if (Oflag <= 1)
693 maxbpg = MAXBLKPG_UFS1(bsize);
694 else
695 maxbpg = MAXBLKPG_UFS2(bsize);
696 }
697 mkfs(special, fsi, fso, mfsmode, mfsuid, mfsgid);
698 if (fsi != -1 && fsi != fso)
699 close(fsi);
700 if (fso != -1)
701 close(fso);
702 #ifdef MFS
703 if (mfs) {
704
705 pathadj(argv[1], mounttoname);
706 switch (pid = fork()) {
707 case -1:
708 perror("mfs");
709 exit(10);
710 case 0:
711 (void)snprintf(mountfromname, sizeof(mountfromname),
712 "mfs:%d", getpid());
713 break;
714 default:
715 (void)snprintf(mountfromname, sizeof(mountfromname),
716 "mfs:%d", pid);
717 for (;;) {
718 /*
719 * spin until the mount succeeds
720 * or the child exits
721 */
722 usleep(1);
723
724 /*
725 * XXX Here is a race condition: another process
726 * can mount a filesystem which hides our
727 * ramdisk before we see the success.
728 */
729 if (statvfs(mounttoname, &sf) < 0)
730 err(88, "statvfs %s", mounttoname);
731 if (!strcmp(sf.f_mntfromname, mountfromname) &&
732 !strncmp(sf.f_mntonname, mounttoname,
733 MNAMELEN) &&
734 !strcmp(sf.f_fstypename, "mfs"))
735 exit(0);
736
737 res = waitpid(pid, &status, WNOHANG);
738 if (res == -1)
739 err(11, "waitpid");
740 if (res != pid)
741 continue;
742 if (WIFEXITED(status)) {
743 if (WEXITSTATUS(status) == 0)
744 exit(0);
745 errx(1, "%s: mount: %s", mounttoname,
746 strerror(WEXITSTATUS(status)));
747 } else
748 errx(11, "abnormal termination");
749 }
750 /* NOTREACHED */
751 }
752
753 (void) setsid();
754 (void) close(0);
755 (void) close(1);
756 (void) close(2);
757 (void) chdir("/");
758
759 args.base = membase;
760 args.size = fssize * sectorsize;
761 if (mount(MOUNT_MFS, mounttoname, mntflags | MNT_ASYNC,
762 &args, sizeof args) == -1)
763 exit(errno); /* parent prints message */
764 }
765 #endif
766 exit(0);
767 }
768
769 static gid_t
770 mfs_group(const char *gname)
771 {
772 struct group *gp;
773
774 if (!(gp = getgrnam(gname)) && !isdigit((unsigned char)*gname))
775 errx(1, "unknown gname %s", gname);
776 return gp ? gp->gr_gid : (gid_t)atoi(gname);
777 }
778
779 static uid_t
780 mfs_user(const char *uname)
781 {
782 struct passwd *pp;
783
784 if (!(pp = getpwnam(uname)) && !isdigit((unsigned char)*uname))
785 errx(1, "unknown user %s", uname);
786 return pp ? pp->pw_uid : (uid_t)atoi(uname);
787 }
788
789 static int64_t
790 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
791 {
792 int64_t result, r1;
793 int shift = 0;
794 char *ep;
795
796 errno = 0;
797 r1 = strtoll(arg, &ep, 10);
798 if (ep[0] != '\0' && ep[1] != '\0')
799 errx(1, "%s `%s' is not a valid number.", desc, arg);
800 switch (ep[0]) {
801 case '\0':
802 case 's': case 'S':
803 if (num_suffix != NULL)
804 *num_suffix = 0;
805 break;
806 case 't': case 'T':
807 shift += 10;
808 /* FALLTHROUGH */
809 case 'g': case 'G':
810 shift += 10;
811 /* FALLTHROUGH */
812 case 'm': case 'M':
813 shift += 10;
814 /* FALLTHROUGH */
815 case 'k': case 'K':
816 shift += 10;
817 /* FALLTHROUGH */
818 case 'b': case 'B':
819 if (num_suffix != NULL)
820 *num_suffix = 1;
821 break;
822 default:
823 errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
824 }
825 result = r1 << shift;
826 if (errno == ERANGE || result >> shift != r1)
827 errx(1, "%s `%s' is too large to convert.", desc, arg);
828 if (result < min) {
829 if (Gflag) {
830 warnx("%s `%s' (%" PRId64 ") is less than the "
831 "minimum (%" PRId64 ").", desc, arg, result, min);
832 } else {
833 errx(1, "%s `%s' (%" PRId64 ") is less than the "
834 "minimum (%" PRId64 ").", desc, arg, result, min);
835 }
836 }
837 if (result > max) {
838 if (Gflag) {
839 warnx("%s `%s' (%" PRId64 ") is greater than the "
840 "maximum (%" PRId64 ").", desc, arg, result, max);
841 } else {
842 errx(1, "%s `%s' (%" PRId64 ") is greater than the "
843 "maximum (%" PRId64 ").", desc, arg, result, max);
844 }
845 }
846 return result;
847 }
848
849 #define NEWFS 1
850 #define MFS_MOUNT 2
851 #define BOTH NEWFS | MFS_MOUNT
852
853 struct help_strings {
854 int flags;
855 const char *str;
856 } const help_strings[] = {
857 #ifndef NO_FFS_EI
858 { NEWFS, "-B byteorder\tbyte order (`be' or `le')" },
859 #endif
860 { NEWFS, "-F \t\tcreate file system image in regular file" },
861 { NEWFS, "-G \t\tmake sanity calculations non-fatal (testing only!)" },
862 { NEWFS, "-I \t\tdo not check that the file system type is '4.2BSD'" },
863 { BOTH, "-N \t\tdo not create file system, just print out "
864 "parameters" },
865 { NEWFS, "-O N\t\tfilesystem format: 0 => 4.3BSD, 1 => FFSv1, 2 => FFSv2" },
866 { NEWFS, "-S secsize\tsector size" },
867 #ifdef COMPAT
868 { NEWFS, "-T disktype\tdisk type" },
869 #endif
870 { BOTH, "-V verbose\toutput verbosity: 0 ==> none, 4 ==> max" },
871 { NEWFS, "-Z \t\tpre-zero the image file" },
872 { BOTH, "-a maxcontig\tmaximum contiguous blocks" },
873 { BOTH, "-b bsize\tblock size" },
874 { BOTH, "-d maxbsize\tmaximum extent size" },
875 { BOTH, "-e maxbpg\tmaximum blocks per file in a cylinder group"
876 },
877 { BOTH, "-f fsize\tfrag size" },
878 { NEWFS, "-g avgfilesize\taverage file size" },
879 { MFS_MOUNT, "-g groupname\tgroup name of mount point" },
880 { BOTH, "-h avgfpdir\taverage files per directory" },
881 { BOTH, "-i density\tnumber of bytes per inode" },
882 { BOTH, "-m minfree\tminimum free space %" },
883 { BOTH, "-n inodes\tnumber of inodes (overrides -i density)" },
884 { BOTH, "-o optim\toptimization preference (`space' or `time')"
885 },
886 { BOTH, "-q (user|group) enable specified quota" },
887 { MFS_MOUNT, "-p perm\t\tpermissions (in octal)" },
888 { BOTH, "-s fssize\tfile system size (sectors)" },
889 { MFS_MOUNT, "-u username\tuser name of mount point" },
890 #ifndef NO_APPLE_UFS
891 { NEWFS, "-v volname\tApple UFS volume name" },
892 #endif
893 { 0, NULL }
894 };
895
896 static void
897 usage(void)
898 {
899 int match;
900 const struct help_strings *hs;
901
902 if (mfs) {
903 fprintf(stderr,
904 "usage: %s [ fsoptions ] special-device mount-point\n",
905 getprogname());
906 } else
907 fprintf(stderr,
908 "usage: %s [ fsoptions ] special-device%s\n",
909 getprogname(),
910 #ifdef COMPAT
911 " [disk-type]");
912 #else
913 "");
914 #endif
915 fprintf(stderr, "where fsoptions are:\n");
916
917 match = mfs ? MFS_MOUNT : NEWFS;
918 for (hs = help_strings; hs->flags != 0; hs++)
919 if (hs->flags & match)
920 fprintf(stderr, "\t%s\n", hs->str);
921 exit(1);
922 }
923