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