xref: /openbsd-src/sbin/newfs/newfs.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: newfs.c,v 1.90 2011/05/23 10:56:17 dcoppa Exp $	*/
2 /*	$NetBSD: newfs.c,v 1.20 1996/05/16 07:13:03 thorpej Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Marshall
9  * Kirk McKusick and Network Associates Laboratories, the Security
10  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
11  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
12  * research program.
13  *
14  * Copyright (c) 1983, 1989, 1993, 1994
15  *	The Regents of the University of California.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41 
42 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/dkio.h>
47 #include <sys/disklabel.h>
48 #include <sys/mount.h>
49 #include <sys/resource.h>
50 #include <sys/sysctl.h>
51 #include <sys/wait.h>
52 
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ufs/dir.h>
55 #include <ufs/ffs/fs.h>
56 
57 #include <ctype.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <paths.h>
62 #include <stdarg.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <syslog.h>
67 #include <unistd.h>
68 #include <signal.h>
69 #include <util.h>
70 
71 #include "mntopts.h"
72 #include "pathnames.h"
73 
74 struct mntopt mopts[] = {
75 	MOPT_STDOPTS,
76 	MOPT_ASYNC,
77 	MOPT_UPDATE,
78 	MOPT_FORCE,
79 	{ NULL },
80 };
81 
82 void	fatal(const char *fmt, ...);
83 __dead void	usage(void);
84 void	mkfs(struct partition *, char *, int, int, mode_t, uid_t, gid_t);
85 void	rewritelabel(char *, int, struct disklabel *);
86 u_short	dkcksum(struct disklabel *);
87 
88 /*
89  * The following two constants set the default block and fragment sizes.
90  * Both constants must be a power of 2 and meet the following constraints:
91  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
92  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
93  *	DESBLKSIZE / DESFRAGSIZE <= 8
94  */
95 #define	DFL_FRAGSIZE	2048
96 #define	DFL_BLKSIZE	16384
97 
98 /*
99  * MAXBLKPG determines the maximum number of data blocks which are
100  * placed in a single cylinder group. The default is one indirect
101  * block worth of data blocks.
102  */
103 #define MAXBLKPG_FFS1(bsize)	((bsize) / sizeof(int32_t))
104 #define MAXBLKPG_FFS2(bsize)	((bsize) / sizeof(int64_t))
105 
106 /*
107  * Each file system has a number of inodes statically allocated.
108  * We allocate one inode slot per NFPI fragments, expecting this
109  * to be far more than we will ever need.
110  */
111 #define	NFPI		4
112 
113 int	mfs;			/* run as the memory based filesystem */
114 int	Nflag;			/* run without writing file system */
115 int	Oflag = 1;		/* 0 = 4.3BSD ffs, 1 = 4.4BSD ffs, 2 = ffs2 */
116 daddr64_t	fssize;			/* file system size */
117 long long	sectorsize;		/* bytes/sector */
118 int	fsize = 0;		/* fragment size */
119 int	bsize = 0;		/* block size */
120 int	maxfrgspercg = INT_MAX;	/* maximum fragments per cylinder group */
121 int	minfree = MINFREE;	/* free space threshold */
122 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
123 int	reqopt = -1;		/* opt preference has not been specified */
124 int	density;		/* number of bytes per inode */
125 int	maxbpg;			/* maximum blocks per file in a cyl group */
126 int	avgfilesize = AVFILESIZ;/* expected average file size */
127 int	avgfilesperdir = AFPDIR;/* expected number of files per directory */
128 int	mntflags = MNT_ASYNC;	/* flags to be passed to mount */
129 int	quiet = 0;		/* quiet flag */
130 caddr_t	membase;		/* start address of memory based filesystem */
131 char	*disktype;
132 int	unlabeled;
133 
134 extern	char *__progname;
135 struct disklabel *getdisklabel(char *, int);
136 
137 #ifdef MFS
138 static int do_exec(const char *, const char *, char *const[]);
139 static int isdir(const char *);
140 static void copy(char *, char *, struct mfs_args *);
141 static int gettmpmnt(char *, size_t);
142 #endif
143 
144 int
145 main(int argc, char *argv[])
146 {
147 	int ch;
148 	struct partition *pp;
149 	struct disklabel *lp;
150 	struct disklabel mfsfakelabel;
151 	struct partition oldpartition;
152 	struct stat st;
153 	struct statfs *mp;
154 	struct rlimit rl;
155 	int fsi = -1, oflagset = 0, fso, len, n, maxpartitions;
156 	char *cp = NULL, *s1, *s2, *special, *opstring, *realdev;
157 #ifdef MFS
158 	char mountfromname[BUFSIZ];
159 	char *pop = NULL, node[MAXPATHLEN];
160 	pid_t pid, res;
161 	struct statfs sf;
162 	struct stat mountpoint;
163 	int status;
164 #endif
165 	uid_t mfsuid = 0;
166 	gid_t mfsgid = 0;
167 	mode_t mfsmode = 0;
168 	char *fstype = NULL;
169 	char **saveargv = argv;
170 	int ffsflag = 1;
171 	const char *errstr;
172 	long long fssize_input = 0;
173 	int fssize_usebytes = 0;
174 
175 	if (strstr(__progname, "mfs"))
176 		mfs = Nflag = quiet = 1;
177 
178 	maxpartitions = getmaxpartitions();
179 	if (maxpartitions > 26)
180 		fatal("insane maxpartitions value %d", maxpartitions);
181 
182 	opstring = mfs ?
183 	    "P:T:b:c:e:f:i:m:o:s:" :
184 	    "NO:S:T:b:c:e:f:g:h:i:m:o:qs:t:";
185 	while ((ch = getopt(argc, argv, opstring)) != -1) {
186 		switch (ch) {
187 		case 'N':
188 			Nflag = 1;
189 			break;
190 		case 'O':
191 			Oflag = strtonum(optarg, 0, 2, &errstr);
192 			if (errstr)
193 				fatal("%s: invalid ffs version", optarg);
194 			oflagset = 1;
195 			break;
196 		case 'S':
197 			if (scan_scaled(optarg, &sectorsize) == -1 ||
198 			    sectorsize <= 0 || (sectorsize % DEV_BSIZE))
199 				fatal("sector size invalid: %s", optarg);
200 			break;
201 		case 'T':
202 			disktype = optarg;
203 			break;
204 		case 'b':
205 			bsize = strtonum(optarg, MINBSIZE, MAXBSIZE, &errstr);
206 			if (errstr)
207 				fatal("block size is %s: %s", errstr, optarg);
208 			break;
209 		case 'c':
210 			maxfrgspercg = strtonum(optarg, 1, INT_MAX, &errstr);
211 			if (errstr)
212 				fatal("fragments per cylinder group is %s: %s",
213 				    errstr, optarg);
214 			break;
215 		case 'e':
216 			maxbpg = strtonum(optarg, 1, INT_MAX, &errstr);
217 			if (errstr)
218 				fatal("blocks per file in a cylinder group is"
219 				    " %s: %s", errstr, optarg);
220 			break;
221 		case 'f':
222 			fsize = strtonum(optarg, MINBSIZE / MAXFRAG, MAXBSIZE,
223 			    &errstr);
224 			if (errstr)
225 				fatal("fragment size is %s: %s",
226 				    errstr, optarg);
227 			break;
228 		case 'g':
229 			avgfilesize = strtonum(optarg, 1, INT_MAX, &errstr);
230 			if (errstr)
231 				fatal("average file size is %s: %s",
232 				    errstr, optarg);
233 			break;
234 		case 'h':
235 			avgfilesperdir = strtonum(optarg, 1, INT_MAX, &errstr);
236 			if (errstr)
237 				fatal("average files per dir is %s: %s",
238 				    errstr, optarg);
239 			break;
240 		case 'i':
241 			density = strtonum(optarg, 1, INT_MAX, &errstr);
242 			if (errstr)
243 				fatal("bytes per inode is %s: %s",
244 				    errstr, optarg);
245 			break;
246 		case 'm':
247 			minfree = strtonum(optarg, 0, 99, &errstr);
248 			if (errstr)
249 				fatal("free space %% is %s: %s",
250 				    errstr, optarg);
251 			break;
252 		case 'o':
253 			if (mfs)
254 				getmntopts(optarg, mopts, &mntflags);
255 			else {
256 				if (strcmp(optarg, "space") == 0)
257 					reqopt = opt = FS_OPTSPACE;
258 				else if (strcmp(optarg, "time") == 0)
259 					reqopt = opt = FS_OPTTIME;
260 				else
261 					fatal("%s: unknown optimization "
262 					    "preference: use `space' or `time'.",
263 					    optarg);
264 			}
265 			break;
266 		case 'q':
267 			quiet = 1;
268 			break;
269 		case 's':
270 			if (scan_scaled(optarg, &fssize_input) == -1 ||
271 			    fssize_input <= 0)
272 				fatal("file system size invalid: %s", optarg);
273 			fssize_usebytes = 0;    /* in case of multiple -s */
274 			for (s1 = optarg; *s1 != '\0'; s1++)
275 				if (isalpha(*s1)) {
276 					fssize_usebytes = 1;
277 					break;
278 				}
279 			break;
280 		case 't':
281 			fstype = optarg;
282 			if (strcmp(fstype, "ffs"))
283 				ffsflag = 0;
284 			break;
285 #ifdef MFS
286 		case 'P':
287 			pop = optarg;
288 			break;
289 #endif
290 		case '?':
291 		default:
292 			usage();
293 		}
294 		if (!ffsflag)
295 			break;
296 	}
297 	argc -= optind;
298 	argv += optind;
299 
300 	if (ffsflag && argc - mfs != 1)
301 		usage();
302 
303 	if (mfs) {
304 		/* Increase our data size to the max */
305 		if (getrlimit(RLIMIT_DATA, &rl) == 0) {
306 			rl.rlim_cur = rl.rlim_max;
307 			(void)setrlimit(RLIMIT_DATA, &rl);
308 		}
309 	}
310 
311 	special = argv[0];
312 
313 	if (!mfs) {
314 		char execname[MAXPATHLEN], name[MAXPATHLEN];
315 
316 		if (fstype == NULL)
317 			fstype = readlabelfs(special, 0);
318 		if (fstype != NULL && strcmp(fstype, "ffs")) {
319 			snprintf(name, sizeof name, "newfs_%s", fstype);
320 			saveargv[0] = name;
321 			snprintf(execname, sizeof execname, "%s/newfs_%s",
322 			    _PATH_SBIN, fstype);
323 			(void)execv(execname, saveargv);
324 			snprintf(execname, sizeof execname, "%s/newfs_%s",
325 			    _PATH_USRSBIN, fstype);
326 			(void)execv(execname, saveargv);
327 			err(1, "%s not found", name);
328 		}
329 	}
330 
331 	if (mfs && !strcmp(special, "swap")) {
332 		/*
333 		 * it's an MFS, mounted on "swap."  fake up a label.
334 		 * XXX XXX XXX
335 		 */
336 		fso = -1;	/* XXX; normally done below. */
337 
338 		memset(&mfsfakelabel, 0, sizeof(mfsfakelabel));
339 		mfsfakelabel.d_secsize = 512;
340 		mfsfakelabel.d_nsectors = 64;
341 		mfsfakelabel.d_ntracks = 16;
342 		mfsfakelabel.d_ncylinders = 16;
343 		mfsfakelabel.d_secpercyl = 1024;
344 		mfsfakelabel.d_secperunit = 16384;
345 		mfsfakelabel.d_npartitions = 1;
346 		mfsfakelabel.d_version = 1;
347 		DL_SETPSIZE(&mfsfakelabel.d_partitions[0], 16384);
348 		mfsfakelabel.d_partitions[0].p_fragblock =
349 		    DISKLABELV1_FFS_FRAGBLOCK(1024, 8);
350 		mfsfakelabel.d_partitions[0].p_cpg = 16;
351 
352 		lp = &mfsfakelabel;
353 		pp = &mfsfakelabel.d_partitions[0];
354 
355 		goto havelabel;
356 	}
357 	if (Nflag) {
358 		fso = -1;
359 	} else {
360 		fso = opendev(special, O_WRONLY, 0, &realdev);
361 		if (fso < 0)
362 			fatal("%s: %s", special, strerror(errno));
363 		special = realdev;
364 
365 		/* Bail if target special is mounted */
366 		n = getmntinfo(&mp, MNT_NOWAIT);
367 		if (n == 0)
368 			fatal("%s: getmntinfo: %s", special, strerror(errno));
369 
370 		len = sizeof(_PATH_DEV) - 1;
371 		s1 = special;
372 		if (strncmp(_PATH_DEV, s1, len) == 0)
373 			s1 += len;
374 
375 		while (--n >= 0) {
376 			s2 = mp->f_mntfromname;
377 			if (strncmp(_PATH_DEV, s2, len) == 0) {
378 				s2 += len - 1;
379 				*s2 = 'r';
380 			}
381 			if (strcmp(s1, s2) == 0 || strcmp(s1, &s2[1]) == 0)
382 				fatal("%s is mounted on %s",
383 				    special, mp->f_mntonname);
384 			++mp;
385 		}
386 	}
387 	if (mfs && disktype != NULL) {
388 		lp = (struct disklabel *)getdiskbyname(disktype);
389 		if (lp == NULL)
390 			fatal("%s: unknown disk type", disktype);
391 		pp = &lp->d_partitions[1];
392 	} else {
393 		fsi = opendev(special, O_RDONLY, 0, NULL);
394 		if (fsi < 0)
395 			fatal("%s: %s", special, strerror(errno));
396 		if (fstat(fsi, &st) < 0)
397 			fatal("%s: %s", special, strerror(errno));
398 		if (!mfs) {
399 			if (S_ISBLK(st.st_mode))
400 				fatal("%s: block device", special);
401 			if (!S_ISCHR(st.st_mode))
402 				warnx("%s: not a character-special device",
403 				    special);
404 		}
405 		cp = strchr(argv[0], '\0') - 1;
406 		if (cp == NULL ||
407 		    ((*cp < 'a' || *cp > ('a' + maxpartitions - 1))
408 		    && !isdigit(*cp)))
409 			fatal("%s: can't figure out file system partition",
410 			    argv[0]);
411 		lp = getdisklabel(special, fsi);
412 		if (isdigit(*cp))
413 			pp = &lp->d_partitions[0];
414 		else
415 			pp = &lp->d_partitions[*cp - 'a'];
416 		if (DL_GETPSIZE(pp) == 0)
417 			fatal("%s: `%c' partition is unavailable",
418 			    argv[0], *cp);
419 		if (pp->p_fstype == FS_BOOT)
420 			fatal("%s: `%c' partition overlaps boot program",
421 			      argv[0], *cp);
422 	}
423 havelabel:
424 	if (sectorsize == 0) {
425 		sectorsize = lp->d_secsize;
426 		if (sectorsize <= 0)
427 			fatal("%s: no default sector size", argv[0]);
428 	}
429 
430 	if (fssize_usebytes) {
431 		fssize = (daddr64_t)fssize_input / (daddr64_t)sectorsize;
432 		if ((daddr64_t)fssize_input % (daddr64_t)sectorsize != 0)
433 			fssize++;
434 	} else if (fssize_input == 0)
435 		fssize = DL_GETPSIZE(pp);
436 	else
437 		fssize = (daddr64_t)fssize_input;
438 
439 	if (fssize > DL_GETPSIZE(pp) && !mfs)
440 	       fatal("%s: maximum file system size on the `%c' partition is "
441 		   "%lld sectors", argv[0], *cp, DL_GETPSIZE(pp));
442 
443 	fssize *= sectorsize / DEV_BSIZE;
444 	if (oflagset == 0 && fssize >= INT_MAX)
445 		Oflag = 2;	/* FFS2 */
446 	if (fsize == 0) {
447 		fsize = DISKLABELV1_FFS_FSIZE(pp->p_fragblock);
448 		if (fsize <= 0)
449 			fsize = MAX(DFL_FRAGSIZE, lp->d_secsize);
450 	}
451 	if (bsize == 0) {
452 		bsize = DISKLABELV1_FFS_BSIZE(pp->p_fragblock);
453 		if (bsize <= 0)
454 			bsize = MIN(DFL_BLKSIZE, 8 * fsize);
455 	}
456 	if (density == 0)
457 		density = NFPI * fsize;
458 	if (minfree < MINFREE && opt != FS_OPTSPACE && reqopt == -1) {
459 		warnx("warning: changing optimization to space "
460 		    "because minfree is less than %d%%\n", MINFREE);
461 		opt = FS_OPTSPACE;
462 	}
463 	if (maxbpg == 0) {
464 		if (Oflag <= 1)
465 			maxbpg = MAXBLKPG_FFS1(bsize);
466 		else
467 			maxbpg = MAXBLKPG_FFS2(bsize);
468 	}
469 	oldpartition = *pp;
470 #ifdef MFS
471 	if (mfs) {
472 		if (realpath(argv[1], node) == NULL)
473 			err(1, "realpath %s", argv[1]);
474 		if (stat(node, &mountpoint) < 0)
475 			err(ECANCELED, "stat %s", node);
476 		mfsuid = mountpoint.st_uid;
477 		mfsgid = mountpoint.st_gid;
478 		mfsmode = mountpoint.st_mode & ALLPERMS;
479 	}
480 #endif
481 
482 	mkfs(pp, special, fsi, fso, mfsmode, mfsuid, mfsgid);
483 	if (!Nflag && memcmp(pp, &oldpartition, sizeof(oldpartition)))
484 		rewritelabel(special, fso, lp);
485 	if (!Nflag)
486 		close(fso);
487 	close(fsi);
488 #ifdef MFS
489 	if (mfs) {
490 		struct mfs_args args;
491 		memset(&args, 0, sizeof(args));
492 		args.base = membase;
493 		args.size = fssize * DEV_BSIZE;
494 		args.export_info.ex_root = -2;
495 		if (mntflags & MNT_RDONLY)
496 			args.export_info.ex_flags = MNT_EXRDONLY;
497 
498 		switch (pid = fork()) {
499 		case -1:
500 			err(10, "mfs");
501 		case 0:
502 			snprintf(mountfromname, sizeof(mountfromname),
503 			    "mfs:%d", getpid());
504 			break;
505 		default:
506 			snprintf(mountfromname, sizeof(mountfromname),
507 			    "mfs:%d", pid);
508 			for (;;) {
509 				/*
510 				 * spin until the mount succeeds
511 				 * or the child exits
512 				 */
513 				usleep(1);
514 
515 				/*
516 				 * XXX Here is a race condition: another process
517 				 * can mount a filesystem which hides our
518 				 * ramdisk before we see the success.
519 				 */
520 				if (statfs(node, &sf) < 0)
521 					err(ECANCELED, "statfs %s", node);
522 				if (!strcmp(sf.f_mntfromname, mountfromname) &&
523 				    !strncmp(sf.f_mntonname, node,
524 					     MNAMELEN) &&
525 				    !strcmp(sf.f_fstypename, "mfs")) {
526 					if (pop != NULL)
527 						copy(pop, node, &args);
528 					exit(0);
529 				}
530 				res = waitpid(pid, &status, WNOHANG);
531 				if (res == -1)
532 					err(EDEADLK, "waitpid");
533 				if (res != pid)
534 					continue;
535 				if (WIFEXITED(status)) {
536 					if (WEXITSTATUS(status) == 0)
537 						exit(0);
538 					errx(1, "%s: mount: %s", node,
539 					     strerror(WEXITSTATUS(status)));
540 				} else
541 					errx(EDEADLK, "abnormal termination");
542 			}
543 			/* NOTREACHED */
544 		}
545 
546 		(void) setsid();
547 		(void) close(0);
548 		(void) close(1);
549 		(void) close(2);
550 		(void) chdir("/");
551 
552 		args.fspec = mountfromname;
553 		if (mntflags & MNT_RDONLY && pop != NULL)
554 			mntflags &= ~MNT_RDONLY;
555 		if (mount(MOUNT_MFS, node, mntflags, &args) < 0)
556 			exit(errno); /* parent prints message */
557 	}
558 #endif
559 	exit(0);
560 }
561 
562 char lmsg[] = "%s: can't read disk label; disk type must be specified";
563 
564 struct disklabel *
565 getdisklabel(char *s, int fd)
566 {
567 	static struct disklabel lab;
568 
569 	if (ioctl(fd, DIOCGDINFO, (char *)&lab) < 0) {
570 		if (disktype != NULL) {
571 			struct disklabel *lp;
572 
573 			unlabeled++;
574 			lp = getdiskbyname(disktype);
575 			if (lp == NULL)
576 				fatal("%s: unknown disk type", disktype);
577 			return (lp);
578 		}
579 		warn("ioctl (GDINFO)");
580 		fatal(lmsg, s);
581 	}
582 	return (&lab);
583 }
584 
585 void
586 rewritelabel(char *s, int fd, struct disklabel *lp)
587 {
588 	if (unlabeled)
589 		return;
590 
591 	lp->d_checksum = 0;
592 	lp->d_checksum = dkcksum(lp);
593 	if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
594 		warn("ioctl (WDINFO)");
595 		fatal("%s: can't rewrite disk label", s);
596 	}
597 #ifdef __vax__
598 	if (lp->d_type == DTYPE_SMD && lp->d_flags & D_BADSECT) {
599 		int i;
600 		int cfd;
601 		daddr64_t alt;
602 		char specname[64];
603 		char blk[1024];
604 		char *cp;
605 
606 		/*
607 		 * Make name for 'c' partition.
608 		 */
609 		strncpy(specname, s, sizeof(specname) - 1);
610 		specname[sizeof(specname) - 1] = '\0';
611 		cp = specname + strlen(specname) - 1;
612 		if (!isdigit(*cp))
613 			*cp = 'c';
614 		cfd = open(specname, O_WRONLY);
615 		if (cfd < 0)
616 			fatal("%s: %s", specname, strerror(errno));
617 		memset(blk, 0, sizeof(blk));
618 		*(struct disklabel *)(blk + LABELOFFSET) = *lp;
619 		alt = lp->d_ncylinders * lp->d_secpercyl - lp->d_nsectors;
620 		for (i = 1; i < 11 && i < lp->d_nsectors; i += 2) {
621 			off_t offset;
622 
623 			offset = alt + i;
624 			offset *= lp->d_secsize;
625 			if (lseek(cfd, offset, SEEK_SET) == -1)
626 				fatal("lseek to badsector area: %s",
627 				    strerror(errno));
628 			if (write(cfd, blk, lp->d_secsize) != lp->d_secsize)
629 				warn("alternate label %d write", i/2);
630 		}
631 		close(cfd);
632 	}
633 #endif	/*__vax__*/
634 }
635 
636 /*VARARGS*/
637 void
638 fatal(const char *fmt, ...)
639 {
640 	va_list ap;
641 
642 	va_start(ap, fmt);
643 	if (fcntl(STDERR_FILENO, F_GETFL) < 0) {
644 		openlog(__progname, LOG_CONS, LOG_DAEMON);
645 		vsyslog(LOG_ERR, fmt, ap);
646 		closelog();
647 	} else {
648 		vwarnx(fmt, ap);
649 	}
650 	va_end(ap);
651 	exit(1);
652 	/*NOTREACHED*/
653 }
654 
655 __dead void
656 usage(void)
657 {
658 	extern char *__progname;
659 
660 	if (mfs) {
661 	    fprintf(stderr,
662 	        "usage: %s [-b block-size] [-c fragments-per-cylinder-group] "
663 		"[-e maxbpg]\n"
664 		"\t[-f frag-size] [-i bytes] [-m free-space] [-o options] "
665 		"[-P file]\n"
666 		"\t[-s size] special node\n",
667 		__progname);
668 	} else {
669 	    fprintf(stderr,
670 	        "usage: %s [-Nq] [-b block-size] "
671 		"[-c fragments-per-cylinder-group] [-e maxbpg]\n"
672 		"\t[-f frag-size] [-g avgfilesize] [-h avgfpdir] [-i bytes]\n"
673 		"\t[-m free-space] [-O filesystem-format] [-o optimization]\n"
674 		"\t[-S sector-size] [-s size] [-T disktype] [-t fstype] "
675 		"special\n",
676 		__progname);
677 	}
678 
679 	exit(1);
680 }
681 
682 #ifdef MFS
683 
684 static int
685 do_exec(const char *dir, const char *cmd, char *const argv[])
686 {
687 	pid_t pid;
688 	int ret, status;
689 	sig_t intsave, quitsave;
690 
691 	switch (pid = fork()) {
692 	case -1:
693 		err(1, "fork");
694 	case 0:
695 		if (dir != NULL && chdir(dir) != 0)
696 			err(1, "chdir");
697 		if (execv(cmd, argv) != 0)
698 			err(1, "%s", cmd);
699 		break;
700 	default:
701 		intsave = signal(SIGINT, SIG_IGN);
702 		quitsave = signal(SIGQUIT, SIG_IGN);
703 		for (;;) {
704 			ret = waitpid(pid, &status, 0);
705 			if (ret == -1)
706 				err(11, "waitpid");
707 			if (WIFEXITED(status)) {
708 				status = WEXITSTATUS(status);
709 				if (status != 0)
710 					warnx("%s: exited", cmd);
711 				break;
712 			} else if (WIFSIGNALED(status)) {
713 				warnx("%s: %s", cmd,
714 				    strsignal(WTERMSIG(status)));
715 				status = 1;
716 				break;
717 			}
718 		}
719 		signal(SIGINT, intsave);
720 		signal(SIGQUIT, quitsave);
721 		return (status);
722 	}
723 	/* NOTREACHED */
724 	return (-1);
725 }
726 
727 static int
728 isdir(const char *path)
729 {
730 	struct stat st;
731 
732 	if (stat(path, &st) != 0)
733 		err(1, "cannot stat %s", path);
734 	if (!S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode))
735 		errx(1, "%s: not a dir or a block device", path);
736 	return (S_ISDIR(st.st_mode));
737 }
738 
739 static void
740 copy(char *src, char *dst, struct mfs_args *args)
741 {
742 	int ret, dir, created = 0;
743 	struct ufs_args mount_args;
744 	char mountpoint[MNAMELEN];
745 	char *const argv[] = { "pax", "-rw", "-pe", ".", dst, NULL } ;
746 
747 	dir = isdir(src);
748 	if (dir)
749 		strlcpy(mountpoint, src, sizeof(mountpoint));
750 	else {
751 		created = gettmpmnt(mountpoint, sizeof(mountpoint));
752 		memset(&mount_args, 0, sizeof(mount_args));
753 		mount_args.fspec = src;
754 		ret = mount(MOUNT_FFS, mountpoint, MNT_RDONLY, &mount_args);
755 		if (ret != 0) {
756 			if (created && rmdir(mountpoint) != 0)
757 				warn("rmdir %s", mountpoint);
758 			if (unmount(dst, 0) != 0)
759 				warn("unmount %s", dst);
760 			err(1, "mount %s %s", src, mountpoint);
761 		}
762 	}
763 	ret = do_exec(mountpoint, "/bin/pax", argv);
764 	if (!dir && unmount(mountpoint, 0) != 0)
765 		warn("unmount %s", mountpoint);
766 	if (created && rmdir(mountpoint) != 0)
767 		warn("rmdir %s", mountpoint);
768 	if (ret != 0) {
769 		if (unmount(dst, 0) != 0)
770 			warn("unmount %s", dst);
771 		errx(1, "copy %s to %s failed", mountpoint, dst);
772 	}
773 
774 	if (mntflags & MNT_RDONLY) {
775 		mntflags |= MNT_UPDATE;
776 		if (mount(MOUNT_MFS, dst, mntflags, args) < 0) {
777 			warn("%s: mount (update, rdonly)", dst);
778 			if (unmount(dst, 0) != 0)
779 				warn("unmount %s", dst);
780 			exit(1);
781 		}
782 	}
783 }
784 
785 static int
786 gettmpmnt(char *mountpoint, size_t len)
787 {
788 	const char *tmp;
789 	const char *mnt = _PATH_MNT;
790 	struct statfs fs;
791 	size_t n;
792 
793 	tmp = getenv("TMPDIR");
794 	if (tmp == NULL || *tmp == '\0')
795 		tmp = _PATH_TMP;
796 
797 	if (statfs(tmp, &fs) != 0)
798 		err(1, "statfs %s", tmp);
799 	if (fs.f_flags & MNT_RDONLY) {
800 		if (statfs(mnt, &fs) != 0)
801 			err(1, "statfs %s", mnt);
802 		if (strcmp(fs.f_mntonname, "/") != 0)
803 			errx(1, "tmp mountpoint %s busy", mnt);
804 		if (strlcpy(mountpoint, mnt, len) >= len)
805 			errx(1, "tmp mountpoint %s too long", mnt);
806 		return (0);
807 	}
808 	n = strlcpy(mountpoint, tmp, len);
809 	if (n >= len)
810 		errx(1, "tmp mount point too long");
811 	if (mountpoint[n - 1] != '/')
812 		strlcat(mountpoint, "/", len);
813 	n = strlcat(mountpoint, "mntXXXXXXXXXX", len);
814 	if (n >= len)
815 		errx(1, "tmp mount point too long");
816 	if (mkdtemp(mountpoint) == NULL)
817 		err(1, "mkdtemp %s", mountpoint);
818 	return (1);
819 }
820 
821 #endif /* MFS */
822