xref: /freebsd/sbin/fsck_ffs/main.c (revision 833a452e9f082a7982a31c21f0da437dbbe0a39d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1993
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 #if 0
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1980, 1986, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/14/95";
41 #endif /* not lint */
42 #endif
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #define	IN_RTLD			/* So we pickup the P_OSREL defines */
47 #include <sys/param.h>
48 #include <sys/file.h>
49 #include <sys/mount.h>
50 #include <sys/resource.h>
51 #include <sys/stat.h>
52 #include <sys/sysctl.h>
53 #include <sys/uio.h>
54 #include <sys/disklabel.h>
55 
56 #include <ufs/ufs/dinode.h>
57 #include <ufs/ffs/fs.h>
58 
59 #include <err.h>
60 #include <errno.h>
61 #include <fstab.h>
62 #include <grp.h>
63 #include <inttypes.h>
64 #include <libufs.h>
65 #include <mntopts.h>
66 #include <paths.h>
67 #include <stdint.h>
68 #include <string.h>
69 #include <time.h>
70 
71 #include "fsck.h"
72 
73 static int	restarts;
74 
75 static void usage(void) __dead2;
76 static intmax_t argtoimax(int flag, const char *req, const char *str, int base);
77 static int checkfilesys(char *filesys);
78 static int setup_bkgrdchk(struct statfs *mntp, int sbrdfailed, char **filesys);
79 static int openfilesys(char *dev);
80 static int chkdoreload(struct statfs *mntp);
81 static struct statfs *getmntpt(const char *);
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	int ch;
87 	struct rlimit rlimit;
88 	struct itimerval itimerval;
89 	int fsret;
90 	int ret = 0;
91 
92 	sync();
93 	skipclean = 1;
94 	inoopt = 0;
95 	while ((ch = getopt(argc, argv, "b:Bc:CdEfFm:npRrSyZz")) != -1) {
96 		switch (ch) {
97 		case 'b':
98 			skipclean = 0;
99 			bflag = argtoimax('b', "number", optarg, 10);
100 			printf("Alternate super block location: %jd\n", bflag);
101 			break;
102 
103 		case 'B':
104 			bkgrdflag = 1;
105 			break;
106 
107 		case 'c':
108 			skipclean = 0;
109 			cvtlevel = argtoimax('c', "conversion level", optarg,
110 			    10);
111 			if (cvtlevel < 3)
112 				errx(EEXIT, "cannot do level %d conversion",
113 				    cvtlevel);
114 			break;
115 
116 		case 'd':
117 			debug++;
118 			break;
119 
120 		case 'E':
121 			Eflag++;
122 			break;
123 
124 		case 'f':
125 			skipclean = 0;
126 			break;
127 
128 		case 'F':
129 			bkgrdcheck = 1;
130 			break;
131 
132 		case 'm':
133 			lfmode = argtoimax('m', "mode", optarg, 8);
134 			if (lfmode &~ 07777)
135 				errx(EEXIT, "bad mode to -m: %o", lfmode);
136 			printf("** lost+found creation mode %o\n", lfmode);
137 			break;
138 
139 		case 'n':
140 			nflag++;
141 			yflag = 0;
142 			break;
143 
144 		case 'p':
145 			preen++;
146 			/*FALLTHROUGH*/
147 
148 		case 'C':
149 			ckclean++;
150 			break;
151 
152 		case 'R':
153 			wantrestart = 1;
154 			break;
155 		case 'r':
156 			inoopt++;
157 			break;
158 
159 		case 'S':
160 			surrender = 1;
161 			break;
162 
163 		case 'y':
164 			yflag++;
165 			nflag = 0;
166 			break;
167 
168 		case 'Z':
169 			Zflag++;
170 			break;
171 
172 		case 'z':
173 			zflag++;
174 			break;
175 
176 		default:
177 			usage();
178 		}
179 	}
180 	argc -= optind;
181 	argv += optind;
182 
183 	if (!argc)
184 		usage();
185 
186 	if (bkgrdflag && cvtlevel > 0) {
187 		pfatal("CANNOT CONVERT A SNAPSHOT\n");
188 		exit(EEXIT);
189 	}
190 
191 	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
192 		(void)signal(SIGINT, catch);
193 	if (ckclean)
194 		(void)signal(SIGQUIT, catchquit);
195 	signal(SIGINFO, infohandler);
196 	if (bkgrdflag) {
197 		signal(SIGALRM, alarmhandler);
198 		itimerval.it_interval.tv_sec = 5;
199 		itimerval.it_interval.tv_usec = 0;
200 		itimerval.it_value.tv_sec = 5;
201 		itimerval.it_value.tv_usec = 0;
202 		setitimer(ITIMER_REAL, &itimerval, NULL);
203 	}
204 	/*
205 	 * Push up our allowed memory limit so we can cope
206 	 * with huge file systems.
207 	 */
208 	if (getrlimit(RLIMIT_DATA, &rlimit) == 0) {
209 		rlimit.rlim_cur = rlimit.rlim_max;
210 		(void)setrlimit(RLIMIT_DATA, &rlimit);
211 	}
212 	while (argc > 0) {
213 		if ((fsret = checkfilesys(*argv)) == ERESTART)
214 			continue;
215 		ret |= fsret;
216 		argc--;
217 		argv++;
218 	}
219 
220 	if (returntosingle)
221 		ret = 2;
222 	exit(ret);
223 }
224 
225 static intmax_t
226 argtoimax(int flag, const char *req, const char *str, int base)
227 {
228 	char *cp;
229 	intmax_t ret;
230 
231 	ret = strtoimax(str, &cp, base);
232 	if (cp == str || *cp)
233 		errx(EEXIT, "-%c flag requires a %s", flag, req);
234 	return (ret);
235 }
236 
237 /*
238  * Check the specified file system.
239  */
240 /* ARGSUSED */
241 static int
242 checkfilesys(char *filesys)
243 {
244 	ufs2_daddr_t n_ffree, n_bfree;
245 	struct dups *dp;
246 	struct statfs *mntp;
247 	intmax_t blks, files;
248 	size_t size;
249 	int sbreadfailed, ofsmodified;
250 
251 	fsutilinit();
252 	fsckinit();
253 
254 	cdevname = filesys;
255 	if (debug && ckclean)
256 		pwarn("starting\n");
257 	/*
258 	 * Make best effort to get the disk name. Check first to see
259 	 * if it is listed among the mounted file systems. Failing that
260 	 * check to see if it is listed in /etc/fstab.
261 	 */
262 	mntp = getmntpt(filesys);
263 	if (mntp != NULL)
264 		filesys = mntp->f_mntfromname;
265 	else
266 		filesys = blockcheck(filesys);
267 	/*
268 	 * If -F flag specified, check to see whether a background check
269 	 * is possible and needed. If possible and needed, exit with
270 	 * status zero. Otherwise exit with status non-zero. A non-zero
271 	 * exit status will cause a foreground check to be run.
272 	 */
273 	sblock_init();
274 	sbreadfailed = 0;
275 	if (openfilesys(filesys) == 0 || readsb(0) == 0)
276 		sbreadfailed = 1;
277 	if (bkgrdcheck) {
278 		if (sbreadfailed)
279 			exit(3);	/* Cannot read superblock */
280 		/* Earlier background failed or journaled */
281 		if (sblock.fs_flags & (FS_NEEDSFSCK | FS_SUJ))
282 			exit(4);
283 		if ((sblock.fs_flags & FS_DOSOFTDEP) == 0)
284 			exit(5);	/* Not running soft updates */
285 		size = MIBSIZE;
286 		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0)
287 			exit(6);	/* Lacks kernel support */
288 		if ((mntp == NULL && sblock.fs_clean == 1) ||
289 		    (mntp != NULL && (sblock.fs_flags & FS_UNCLEAN) == 0))
290 			exit(7);	/* Filesystem clean, report it now */
291 		exit(0);
292 	}
293 	if (ckclean && skipclean) {
294 		/*
295 		 * If file system is gjournaled, check it here.
296 		 */
297 		if (sbreadfailed)
298 			exit(3);	/* Cannot read superblock */
299 		if (bkgrdflag == 0 &&
300 		    (nflag || (fswritefd = open(filesys, O_WRONLY)) < 0)) {
301 			fswritefd = -1;
302 			if (preen)
303 				pfatal("NO WRITE ACCESS");
304 			printf(" (NO WRITE)");
305 		}
306 		if ((sblock.fs_flags & FS_GJOURNAL) != 0) {
307 			if (sblock.fs_clean == 1) {
308 				pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
309 				exit(0);
310 			}
311 			if ((sblock.fs_flags &
312 			    (FS_UNCLEAN | FS_NEEDSFSCK)) == 0) {
313 				bufinit();
314 				gjournal_check(filesys);
315 				if (chkdoreload(mntp) == 0)
316 					exit(0);
317 				exit(4);
318 			} else {
319 				pfatal("FULL FSCK NEEDED, CANNOT RUN FAST "
320 				    "FSCK\n");
321 			}
322 		}
323 		close(fswritefd);
324 		fswritefd = -1;
325 	}
326 	if (bkgrdflag) {
327 		switch (setup_bkgrdchk(mntp, sbreadfailed, &filesys)) {
328 		case -1: /* filesystem clean */
329 			goto clean;
330 		case 0: /* cannot do background, give up */
331 			exit(EEXIT);
332 		case 1: /* doing background check, preen rules apply */
333 			preen = 1;
334 			break;
335 		}
336 	}
337 
338 	switch (setup(filesys)) {
339 	case 0:
340 		if (preen)
341 			pfatal("CAN'T CHECK FILE SYSTEM.");
342 		return (EEXIT);
343 	case -1:
344 	clean:
345 		pwarn("clean, %ld free ", (long)(sblock.fs_cstotal.cs_nffree +
346 		    sblock.fs_frag * sblock.fs_cstotal.cs_nbfree));
347 		printf("(%jd frags, %jd blocks, %.1f%% fragmentation)\n",
348 		    (intmax_t)sblock.fs_cstotal.cs_nffree,
349 		    (intmax_t)sblock.fs_cstotal.cs_nbfree,
350 		    sblock.fs_cstotal.cs_nffree * 100.0 / sblock.fs_dsize);
351 		return (0);
352 	}
353 	/*
354 	 * Determine if we can and should do journal recovery.
355 	 */
356 	if ((sblock.fs_flags & FS_SUJ) == FS_SUJ) {
357 		if ((sblock.fs_flags & FS_NEEDSFSCK) != FS_NEEDSFSCK && skipclean) {
358 			sujrecovery = 1;
359 			if (suj_check(filesys) == 0) {
360 				printf("\n***** FILE SYSTEM MARKED CLEAN *****\n");
361 				if (chkdoreload(mntp) == 0)
362 					exit(0);
363 				exit(4);
364 			}
365 			sujrecovery = 0;
366 			printf("** Skipping journal, falling through to full fsck\n\n");
367 		}
368 		if (fswritefd != -1) {
369 			/*
370 			 * Write the superblock so we don't try to recover the
371 			 * journal on another pass. If this is the only change
372 			 * to the filesystem, we do not want it to be called
373 			 * out as modified.
374 			 */
375 			sblock.fs_mtime = time(NULL);
376 			sbdirty();
377 			ofsmodified = fsmodified;
378 			flush(fswritefd, &sblk);
379 			fsmodified = ofsmodified;
380 		}
381 	}
382 	/*
383 	 * If the filesystem was run on an old kernel that did not
384 	 * support check hashes, clear the check-hash flags so that
385 	 * we do not try to verify them.
386 	 */
387 	if ((sblock.fs_flags & FS_METACKHASH) == 0)
388 		sblock.fs_metackhash = 0;
389 	/*
390 	 * If we are running on a kernel that can provide check hashes
391 	 * that are not yet enabled for the filesystem and we are
392 	 * running manually without the -y flag, offer to add any
393 	 * supported check hashes that are not already enabled.
394 	 */
395 	ckhashadd = 0;
396 	if (preen == 0 && yflag == 0 && sblock.fs_magic != FS_UFS1_MAGIC &&
397 	    fswritefd != -1 && getosreldate() >= P_OSREL_CK_CYLGRP) {
398 		if ((sblock.fs_metackhash & CK_CYLGRP) == 0 &&
399 		    reply("ADD CYLINDER GROUP CHECK-HASH PROTECTION") != 0) {
400 			ckhashadd |= CK_CYLGRP;
401 			sblock.fs_metackhash |= CK_CYLGRP;
402 		}
403 		if ((sblock.fs_metackhash & CK_SUPERBLOCK) == 0 &&
404 		    getosreldate() >= P_OSREL_CK_SUPERBLOCK &&
405 		    reply("ADD SUPERBLOCK CHECK-HASH PROTECTION") != 0) {
406 			ckhashadd |= CK_SUPERBLOCK;
407 			sblock.fs_metackhash |= CK_SUPERBLOCK;
408 		}
409 		if ((sblock.fs_metackhash & CK_INODE) == 0 &&
410 		    getosreldate() >= P_OSREL_CK_INODE &&
411 		    reply("ADD INODE CHECK-HASH PROTECTION") != 0) {
412 			ckhashadd |= CK_INODE;
413 			sblock.fs_metackhash |= CK_INODE;
414 		}
415 #ifdef notyet
416 		if ((sblock.fs_metackhash & CK_INDIR) == 0 &&
417 		    getosreldate() >= P_OSREL_CK_INDIR &&
418 		    reply("ADD INDIRECT BLOCK CHECK-HASH PROTECTION") != 0) {
419 			ckhashadd |= CK_INDIR;
420 			sblock.fs_metackhash |= CK_INDIR;
421 		}
422 		if ((sblock.fs_metackhash & CK_DIR) == 0 &&
423 		    getosreldate() >= P_OSREL_CK_DIR &&
424 		    reply("ADD DIRECTORY CHECK-HASH PROTECTION") != 0) {
425 			ckhashadd |= CK_DIR;
426 			sblock.fs_metackhash |= CK_DIR;
427 		}
428 #endif /* notyet */
429 		if (ckhashadd != 0) {
430 			sblock.fs_flags |= FS_METACKHASH;
431 			sbdirty();
432 		}
433 	}
434 	/*
435 	 * Cleared if any questions answered no. Used to decide if
436 	 * the superblock should be marked clean.
437 	 */
438 	resolved = 1;
439 	/*
440 	 * 1: scan inodes tallying blocks used
441 	 */
442 	if (preen == 0) {
443 		printf("** Last Mounted on %s\n", sblock.fs_fsmnt);
444 		if (mntp != NULL && mntp->f_flags & MNT_ROOTFS)
445 			printf("** Root file system\n");
446 		printf("** Phase 1 - Check Blocks and Sizes\n");
447 	}
448 	clock_gettime(CLOCK_REALTIME_PRECISE, &startprog);
449 	pass1();
450 	IOstats("Pass1");
451 
452 	/*
453 	 * 1b: locate first references to duplicates, if any
454 	 */
455 	if (duplist) {
456 		if (preen || usedsoftdep)
457 			pfatal("INTERNAL ERROR: DUPS WITH %s%s%s",
458 			    preen ? "-p" : "",
459 			    (preen && usedsoftdep) ? " AND " : "",
460 			    usedsoftdep ? "SOFTUPDATES" : "");
461 		printf("** Phase 1b - Rescan For More DUPS\n");
462 		pass1b();
463 		IOstats("Pass1b");
464 	}
465 
466 	/*
467 	 * 2: traverse directories from root to mark all connected directories
468 	 */
469 	if (preen == 0)
470 		printf("** Phase 2 - Check Pathnames\n");
471 	pass2();
472 	IOstats("Pass2");
473 
474 	/*
475 	 * 3: scan inodes looking for disconnected directories
476 	 */
477 	if (preen == 0)
478 		printf("** Phase 3 - Check Connectivity\n");
479 	pass3();
480 	IOstats("Pass3");
481 
482 	/*
483 	 * 4: scan inodes looking for disconnected files; check reference counts
484 	 */
485 	if (preen == 0)
486 		printf("** Phase 4 - Check Reference Counts\n");
487 	pass4();
488 	IOstats("Pass4");
489 
490 	/*
491 	 * 5: check and repair resource counts in cylinder groups
492 	 */
493 	if (preen == 0)
494 		printf("** Phase 5 - Check Cyl groups\n");
495 	pass5();
496 	IOstats("Pass5");
497 
498 	/*
499 	 * print out summary statistics
500 	 */
501 	n_ffree = sblock.fs_cstotal.cs_nffree;
502 	n_bfree = sblock.fs_cstotal.cs_nbfree;
503 	files = maxino - UFS_ROOTINO - sblock.fs_cstotal.cs_nifree - n_files;
504 	blks = n_blks +
505 	    sblock.fs_ncg * (cgdmin(&sblock, 0) - cgsblock(&sblock, 0));
506 	blks += cgsblock(&sblock, 0) - cgbase(&sblock, 0);
507 	blks += howmany(sblock.fs_cssize, sblock.fs_fsize);
508 	blks = maxfsblock - (n_ffree + sblock.fs_frag * n_bfree) - blks;
509 	if (bkgrdflag && (files > 0 || blks > 0)) {
510 		countdirs = sblock.fs_cstotal.cs_ndir - countdirs;
511 		pwarn("Reclaimed: %ld directories, %jd files, %jd fragments\n",
512 		    countdirs, files - countdirs, blks);
513 	}
514 	pwarn("%ld files, %jd used, %ju free ",
515 	    (long)n_files, (intmax_t)n_blks,
516 	    (uintmax_t)n_ffree + sblock.fs_frag * n_bfree);
517 	printf("(%ju frags, %ju blocks, %.1f%% fragmentation)\n",
518 	    (uintmax_t)n_ffree, (uintmax_t)n_bfree,
519 	    n_ffree * 100.0 / sblock.fs_dsize);
520 	if (debug) {
521 		if (files < 0)
522 			printf("%jd inodes missing\n", -files);
523 		if (blks < 0)
524 			printf("%jd blocks missing\n", -blks);
525 		if (duplist != NULL) {
526 			printf("The following duplicate blocks remain:");
527 			for (dp = duplist; dp; dp = dp->next)
528 				printf(" %jd,", (intmax_t)dp->dup);
529 			printf("\n");
530 		}
531 	}
532 	duplist = (struct dups *)0;
533 	muldup = (struct dups *)0;
534 	inocleanup();
535 	if (fsmodified) {
536 		sblock.fs_time = time(NULL);
537 		sbdirty();
538 	}
539 	if (cvtlevel && (sblk.b_flags & B_DIRTY) != 0) {
540 		/*
541 		 * Write out the duplicate super blocks
542 		 */
543 		if (sbput(fswritefd, &sblock, sblock.fs_ncg) == 0)
544 			fsmodified = 1;
545 	}
546 	if (rerun)
547 		resolved = 0;
548 
549 	/*
550 	 * Check to see if the file system is mounted read-write.
551 	 */
552 	if (bkgrdflag == 0 && mntp != NULL && (mntp->f_flags & MNT_RDONLY) == 0)
553 		resolved = 0;
554 	ckfini(resolved);
555 
556 	if (fsmodified && !preen)
557 		printf("\n***** FILE SYSTEM WAS MODIFIED *****\n");
558 	if (rerun) {
559 		if (wantrestart && (restarts++ < 10) &&
560 		    (preen || reply("RESTART")))
561 			return (ERESTART);
562 		printf("\n***** PLEASE RERUN FSCK *****\n");
563 	}
564 	if (chkdoreload(mntp) != 0) {
565 		if (!fsmodified)
566 			return (0);
567 		if (!preen)
568 			printf("\n***** REBOOT NOW *****\n");
569 		sync();
570 		return (4);
571 	}
572 	return (rerun ? ERERUN : 0);
573 }
574 
575 /*
576  * If we are to do a background check:
577  *	Get the mount point information of the file system
578  *	If already clean, return -1
579  *	Check that kernel supports background fsck
580  *	Find or create the snapshot directory
581  *	Create the snapshot file
582  *	Open snapshot
583  *	If anything fails print reason and return 0 which exits
584  */
585 static int
586 setup_bkgrdchk(struct statfs *mntp, int sbreadfailed, char **filesys)
587 {
588 	struct stat snapdir;
589 	struct group *grp;
590 	struct iovec *iov;
591 	char errmsg[255];
592 	int iovlen;
593 	size_t size;
594 
595 	/* Get the mount point information of the file system */
596 	if (mntp == NULL) {
597 		pwarn("NOT MOUNTED, CANNOT RUN IN BACKGROUND\n");
598 		return (0);
599 	}
600 	if ((mntp->f_flags & MNT_RDONLY) != 0) {
601 		pwarn("MOUNTED READ-ONLY, CANNOT RUN IN BACKGROUND\n");
602 		return (0);
603 	}
604 	if ((mntp->f_flags & MNT_SOFTDEP) == 0) {
605 		pwarn("NOT USING SOFT UPDATES, CANNOT RUN IN BACKGROUND\n");
606 		return (0);
607 	}
608 	if (sbreadfailed) {
609 		pwarn("SUPERBLOCK READ FAILED, CANNOT RUN IN BACKGROUND\n");
610 		return (0);
611 	}
612 	if ((sblock.fs_flags & FS_NEEDSFSCK) != 0) {
613 		pwarn("FULL FSCK NEEDED, CANNOT RUN IN BACKGROUND\n");
614 		return (0);
615 	}
616 	if ((sblock.fs_flags & FS_SUJ) != 0) {
617 		pwarn("JOURNALED FILESYSTEM, CANNOT RUN IN BACKGROUND\n");
618 		return (0);
619 	}
620 	if (skipclean && ckclean &&
621 	   (sblock.fs_flags & (FS_UNCLEAN|FS_NEEDSFSCK)) == 0) {
622 		/*
623 		 * file system is clean;
624 		 * skip snapshot and report it clean
625 		 */
626 		pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
627 		return (-1);
628 	}
629 	/* Check that kernel supports background fsck */
630 	size = MIBSIZE;
631 	if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0||
632 	    sysctlnametomib("vfs.ffs.adjblkcnt", adjblkcnt, &size) < 0||
633 	    sysctlnametomib("vfs.ffs.setsize", setsize, &size) < 0 ||
634 	    sysctlnametomib("vfs.ffs.freefiles", freefiles, &size) < 0||
635 	    sysctlnametomib("vfs.ffs.freedirs", freedirs, &size) < 0 ||
636 	    sysctlnametomib("vfs.ffs.freeblks", freeblks, &size) < 0) {
637 		pwarn("KERNEL LACKS BACKGROUND FSCK SUPPORT\n");
638 		return (0);
639 	}
640 	/*
641 	 * When kernel lacks runtime bgfsck superblock summary
642 	 * adjustment functionality, it does not mean we can not
643 	 * continue, as old kernels will recompute the summary at
644 	 * mount time. However, it will be an unexpected softupdates
645 	 * inconsistency if it turns out that the summary is still
646 	 * incorrect. Set a flag so subsequent operation can know this.
647 	 */
648 	bkgrdsumadj = 1;
649 	if (sysctlnametomib("vfs.ffs.adjndir", adjndir, &size) < 0 ||
650 	   sysctlnametomib("vfs.ffs.adjnbfree", adjnbfree, &size) < 0 ||
651 	   sysctlnametomib("vfs.ffs.adjnifree", adjnifree, &size) < 0 ||
652 	   sysctlnametomib("vfs.ffs.adjnffree", adjnffree, &size) < 0 ||
653 	   sysctlnametomib("vfs.ffs.adjnumclusters", adjnumclusters,
654 	   &size) < 0) {
655 		bkgrdsumadj = 0;
656 		pwarn("KERNEL LACKS RUNTIME SUPERBLOCK SUMMARY ADJUSTMENT "
657 		    "SUPPORT\n");
658 	}
659 	/* Find or create the snapshot directory */
660 	snprintf(snapname, sizeof snapname, "%s/.snap",
661 	    mntp->f_mntonname);
662 	if (stat(snapname, &snapdir) < 0) {
663 		if (errno != ENOENT) {
664 			pwarn("CANNOT FIND SNAPSHOT DIRECTORY %s: %s, CANNOT "
665 			    "RUN IN BACKGROUND\n", snapname, strerror(errno));
666 			return (0);
667 		}
668 		if ((grp = getgrnam("operator")) == NULL ||
669 			   mkdir(snapname, 0770) < 0 ||
670 			   chown(snapname, -1, grp->gr_gid) < 0 ||
671 			   chmod(snapname, 0770) < 0) {
672 			pwarn("CANNOT CREATE SNAPSHOT DIRECTORY %s: %s, "
673 			    "CANNOT RUN IN BACKGROUND\n", snapname,
674 			    strerror(errno));
675 			return (0);
676 		}
677 	} else if (!S_ISDIR(snapdir.st_mode)) {
678 		pwarn("%s IS NOT A DIRECTORY, CANNOT RUN IN BACKGROUND\n",
679 		    snapname);
680 		return (0);
681 	}
682 	/* Create the snapshot file */
683 	iov = NULL;
684 	iovlen = 0;
685 	errmsg[0] = '\0';
686 	snprintf(snapname, sizeof snapname, "%s/.snap/fsck_snapshot",
687 	    mntp->f_mntonname);
688 	build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
689 	build_iovec(&iov, &iovlen, "from", snapname, (size_t)-1);
690 	build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname, (size_t)-1);
691 	build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
692 	build_iovec(&iov, &iovlen, "update", NULL, 0);
693 	build_iovec(&iov, &iovlen, "snapshot", NULL, 0);
694 	/* Create snapshot, removing old snapshot it it exists */
695 	while (nmount(iov, iovlen, mntp->f_flags) < 0) {
696 		if (errno == EEXIST && unlink(snapname) == 0)
697 			continue;
698 		pwarn("CANNOT CREATE SNAPSHOT %s: %s %s\n", snapname,
699 		    strerror(errno), errmsg);
700 		return (0);
701 	}
702 	/* Open snapshot */
703 	if (openfilesys(snapname) == 0) {
704 		unlink(snapname);
705 		pwarn("CANNOT OPEN SNAPSHOT %s: %s, CANNOT RUN IN "
706 		    "BACKGROUND\n", snapname, strerror(errno));
707 		return (0);
708 	}
709 	free(sblock.fs_csp);
710 	free(sblock.fs_si);
711 	havesb = 0;
712 	*filesys = snapname;
713 	cmd.version = FFS_CMD_VERSION;
714 	cmd.handle = fsreadfd;
715 	return (1);
716 }
717 
718 /*
719  * Open a device or file to be checked by fsck.
720  */
721 static int
722 openfilesys(char *dev)
723 {
724 	struct stat statb;
725 	int saved_fsreadfd;
726 
727 	if (stat(dev, &statb) < 0) {
728 		pfatal("CANNOT STAT %s: %s\n", dev, strerror(errno));
729 		return (0);
730 	}
731 	if ((statb.st_mode & S_IFMT) != S_IFCHR &&
732 	    (statb.st_mode & S_IFMT) != S_IFBLK) {
733 		if (bkgrdflag != 0 && (statb.st_flags & SF_SNAPSHOT) == 0) {
734 			pfatal("BACKGROUND FSCK LACKS A SNAPSHOT\n");
735 			exit(EEXIT);
736 		}
737 		if (bkgrdflag != 0) {
738 			cursnapshot = statb.st_ino;
739 		} else {
740 			pfatal("%s IS NOT A DISK DEVICE\n", dev);
741 			if (reply("CONTINUE") == 0)
742 				return (0);
743 		}
744 	}
745 	saved_fsreadfd = fsreadfd;
746 	if ((fsreadfd = open(dev, O_RDONLY)) < 0) {
747 		fsreadfd = saved_fsreadfd;
748 		pfatal("CANNOT OPEN %s: %s\n", dev, strerror(errno));
749 		return (0);
750 	}
751 	if (saved_fsreadfd != -1)
752 		close(saved_fsreadfd);
753 	return (1);
754 }
755 
756 static int
757 chkdoreload(struct statfs *mntp)
758 {
759 	struct iovec *iov;
760 	int iovlen;
761 	char errmsg[255];
762 
763 	if (mntp == NULL)
764 		return (0);
765 
766 	iov = NULL;
767 	iovlen = 0;
768 	errmsg[0] = '\0';
769 	/*
770 	 * We modified a mounted file system.  Do a mount update on
771 	 * it unless it is read-write, so we can continue using it
772 	 * as safely as possible.
773 	 */
774 	if (mntp->f_flags & MNT_RDONLY) {
775 		build_iovec(&iov, &iovlen, "fstype", "ffs", 4);
776 		build_iovec(&iov, &iovlen, "from", mntp->f_mntfromname,
777 		    (size_t)-1);
778 		build_iovec(&iov, &iovlen, "fspath", mntp->f_mntonname,
779 		    (size_t)-1);
780 		build_iovec(&iov, &iovlen, "errmsg", errmsg,
781 		    sizeof(errmsg));
782 		build_iovec(&iov, &iovlen, "update", NULL, 0);
783 		build_iovec(&iov, &iovlen, "reload", NULL, 0);
784 		/*
785 		 * XX: We need the following line until we clean up
786 		 * nmount parsing of root mounts and NFS root mounts.
787 		 */
788 		build_iovec(&iov, &iovlen, "ro", NULL, 0);
789 		if (nmount(iov, iovlen, mntp->f_flags) == 0) {
790 			return (0);
791 		}
792 		pwarn("mount reload of '%s' failed: %s %s\n\n",
793 		    mntp->f_mntonname, strerror(errno), errmsg);
794 		return (1);
795 	}
796 	return (0);
797 }
798 
799 /*
800  * Get the mount point information for name.
801  */
802 static struct statfs *
803 getmntpt(const char *name)
804 {
805 	struct stat devstat, mntdevstat;
806 	char device[sizeof(_PATH_DEV) - 1 + MNAMELEN];
807 	char *ddevname;
808 	struct statfs *mntbuf, *statfsp;
809 	int i, mntsize, isdev;
810 
811 	if (stat(name, &devstat) != 0)
812 		return (NULL);
813 	if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode))
814 		isdev = 1;
815 	else
816 		isdev = 0;
817 	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
818 	for (i = 0; i < mntsize; i++) {
819 		statfsp = &mntbuf[i];
820 		ddevname = statfsp->f_mntfromname;
821 		if (*ddevname != '/') {
822 			if (strlen(_PATH_DEV) + strlen(ddevname) + 1 >
823 			    sizeof(statfsp->f_mntfromname))
824 				continue;
825 			strcpy(device, _PATH_DEV);
826 			strcat(device, ddevname);
827 			strcpy(statfsp->f_mntfromname, device);
828 		}
829 		if (isdev == 0) {
830 			if (strcmp(name, statfsp->f_mntonname))
831 				continue;
832 			return (statfsp);
833 		}
834 		if (stat(ddevname, &mntdevstat) == 0 &&
835 		    mntdevstat.st_rdev == devstat.st_rdev)
836 			return (statfsp);
837 	}
838 	statfsp = NULL;
839 	return (statfsp);
840 }
841 
842 static void
843 usage(void)
844 {
845 	(void) fprintf(stderr,
846 "usage: %s [-BCdEFfnpRrSyZ] [-b block] [-c level] [-m mode] filesystem ...\n",
847 	    getprogname());
848 	exit(1);
849 }
850 
851 void
852 infohandler(int sig __unused)
853 {
854 	got_siginfo = 1;
855 }
856 
857 void
858 alarmhandler(int sig __unused)
859 {
860 	got_sigalarm = 1;
861 }
862