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