xref: /freebsd/sbin/fsck_ffs/setup.c (revision a0409676120c1e558d0ade943019934e0f15118d)
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 sccsid[] = "@(#)setup.c	8.10 (Berkeley) 5/9/95";
35 #endif /* not lint */
36 #endif
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/disk.h>
42 #include <sys/stat.h>
43 #define FSTYPENAMES
44 #include <sys/disklabel.h>
45 #include <sys/file.h>
46 #include <sys/sysctl.h>
47 
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ffs/fs.h>
50 
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <limits.h>
55 #include <stdint.h>
56 #include <string.h>
57 #include <libufs.h>
58 
59 #include "fsck.h"
60 
61 struct inoinfo **inphead, **inpsort;	/* info about all inodes */
62 
63 struct bufarea asblk;
64 #define altsblock (*asblk.b_un.b_fs)
65 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
66 
67 static int calcsb(char *dev, int devfd, struct fs *fs);
68 static void saverecovery(int readfd, int writefd);
69 static int chkrecovery(int devfd);
70 
71 /*
72  * Read in a superblock finding an alternate if necessary.
73  * Return 1 if successful, 0 if unsuccessful, -1 if file system
74  * is already clean (ckclean and preen mode only).
75  */
76 int
77 setup(char *dev)
78 {
79 	long cg, asked, i, j;
80 	long bmapsize;
81 	struct stat statb;
82 	struct fs proto;
83 	size_t size;
84 
85 	havesb = 0;
86 	fswritefd = -1;
87 	cursnapshot = 0;
88 	if (stat(dev, &statb) < 0) {
89 		printf("Can't stat %s: %s\n", dev, strerror(errno));
90 		if (bkgrdflag) {
91 			unlink(snapname);
92 			bkgrdflag = 0;
93 		}
94 		return (0);
95 	}
96 	if ((statb.st_mode & S_IFMT) != S_IFCHR &&
97 	    (statb.st_mode & S_IFMT) != S_IFBLK) {
98 		if (bkgrdflag != 0 && (statb.st_flags & SF_SNAPSHOT) == 0) {
99 			unlink(snapname);
100 			printf("background fsck lacks a snapshot\n");
101 			exit(EEXIT);
102 		}
103 		if ((statb.st_flags & SF_SNAPSHOT) != 0 && cvtlevel == 0) {
104 			cursnapshot = statb.st_ino;
105 		} else {
106 			if (cvtlevel == 0 ||
107 			    (statb.st_flags & SF_SNAPSHOT) == 0) {
108 				if (preen && bkgrdflag) {
109 					unlink(snapname);
110 					bkgrdflag = 0;
111 				}
112 				pfatal("%s is not a disk device", dev);
113 				if (reply("CONTINUE") == 0) {
114 					if (bkgrdflag) {
115 						unlink(snapname);
116 						bkgrdflag = 0;
117 					}
118 					return (0);
119 				}
120 			} else {
121 				if (bkgrdflag) {
122 					unlink(snapname);
123 					bkgrdflag = 0;
124 				}
125 				pfatal("cannot convert a snapshot");
126 				exit(EEXIT);
127 			}
128 		}
129 	}
130 	if ((fsreadfd = open(dev, O_RDONLY)) < 0) {
131 		if (bkgrdflag) {
132 			unlink(snapname);
133 			bkgrdflag = 0;
134 		}
135 		printf("Can't open %s: %s\n", dev, strerror(errno));
136 		return (0);
137 	}
138 	if (bkgrdflag) {
139 		unlink(snapname);
140 		size = MIBSIZE;
141 		if (sysctlnametomib("vfs.ffs.adjrefcnt", adjrefcnt, &size) < 0||
142 		    sysctlnametomib("vfs.ffs.adjblkcnt", adjblkcnt, &size) < 0||
143 		    sysctlnametomib("vfs.ffs.setsize", setsize, &size) < 0 ||
144 		    sysctlnametomib("vfs.ffs.freefiles", freefiles, &size) < 0||
145 		    sysctlnametomib("vfs.ffs.freedirs", freedirs, &size) < 0 ||
146 		    sysctlnametomib("vfs.ffs.freeblks", freeblks, &size) < 0) {
147 			pfatal("kernel lacks background fsck support\n");
148 			exit(EEXIT);
149 		}
150 		/*
151 		 * When kernel is lack of runtime bgfsck superblock summary
152 		 * adjustment functionality, it does not mean we can not
153 		 * continue, as old kernels will recompute the summary at
154 		 * mount time.  However, it will be an unexpected softupdates
155 		 * inconsistency if it turns out that the summary is still
156 		 * incorrect.  Set a flag so subsequent operation can know
157 		 * this.
158 		 */
159 		bkgrdsumadj = 1;
160 		if (sysctlnametomib("vfs.ffs.adjndir", adjndir, &size) < 0 ||
161 		    sysctlnametomib("vfs.ffs.adjnbfree", adjnbfree, &size) < 0 ||
162 		    sysctlnametomib("vfs.ffs.adjnifree", adjnifree, &size) < 0 ||
163 		    sysctlnametomib("vfs.ffs.adjnffree", adjnffree, &size) < 0 ||
164 		    sysctlnametomib("vfs.ffs.adjnumclusters", adjnumclusters, &size) < 0) {
165 			bkgrdsumadj = 0;
166 			pwarn("kernel lacks runtime superblock summary adjustment support");
167 		}
168 		cmd.version = FFS_CMD_VERSION;
169 		cmd.handle = fsreadfd;
170 		fswritefd = -1;
171 	}
172 	if (preen == 0)
173 		printf("** %s", dev);
174 	if (bkgrdflag == 0 &&
175 	    (nflag || (fswritefd = open(dev, O_WRONLY)) < 0)) {
176 		fswritefd = -1;
177 		if (preen)
178 			pfatal("NO WRITE ACCESS");
179 		printf(" (NO WRITE)");
180 	}
181 	if (preen == 0)
182 		printf("\n");
183 	/*
184 	 * Read in the superblock, looking for alternates if necessary
185 	 */
186 	if (readsb(1) == 0) {
187 		skipclean = 0;
188 		if (bflag || preen || calcsb(dev, fsreadfd, &proto) == 0)
189 			return(0);
190 		if (reply("LOOK FOR ALTERNATE SUPERBLOCKS") == 0)
191 			return (0);
192 		for (cg = 0; cg < proto.fs_ncg; cg++) {
193 			bflag = fsbtodb(&proto, cgsblock(&proto, cg));
194 			if (readsb(0) != 0)
195 				break;
196 		}
197 		if (cg >= proto.fs_ncg) {
198 			printf("%s %s\n%s %s\n%s %s\n",
199 				"SEARCH FOR ALTERNATE SUPER-BLOCK",
200 				"FAILED. YOU MUST USE THE",
201 				"-b OPTION TO FSCK TO SPECIFY THE",
202 				"LOCATION OF AN ALTERNATE",
203 				"SUPER-BLOCK TO SUPPLY NEEDED",
204 				"INFORMATION; SEE fsck_ffs(8).");
205 			bflag = 0;
206 			return(0);
207 		}
208 		pwarn("USING ALTERNATE SUPERBLOCK AT %jd\n", bflag);
209 		bflag = 0;
210 	}
211 	if (skipclean && ckclean && sblock.fs_clean) {
212 		pwarn("FILE SYSTEM CLEAN; SKIPPING CHECKS\n");
213 		return (-1);
214 	}
215 	maxfsblock = sblock.fs_size;
216 	maxino = sblock.fs_ncg * sblock.fs_ipg;
217 	/*
218 	 * Check and potentially fix certain fields in the super block.
219 	 */
220 	if (sblock.fs_optim != FS_OPTTIME && sblock.fs_optim != FS_OPTSPACE) {
221 		pfatal("UNDEFINED OPTIMIZATION IN SUPERBLOCK");
222 		if (reply("SET TO DEFAULT") == 1) {
223 			sblock.fs_optim = FS_OPTTIME;
224 			sbdirty();
225 		}
226 	}
227 	if ((sblock.fs_minfree < 0 || sblock.fs_minfree > 99)) {
228 		pfatal("IMPOSSIBLE MINFREE=%d IN SUPERBLOCK",
229 			sblock.fs_minfree);
230 		if (reply("SET TO DEFAULT") == 1) {
231 			sblock.fs_minfree = 10;
232 			sbdirty();
233 		}
234 	}
235 	if (sblock.fs_magic == FS_UFS1_MAGIC &&
236 	    sblock.fs_old_inodefmt < FS_44INODEFMT) {
237 		pwarn("Format of file system is too old.\n");
238 		pwarn("Must update to modern format using a version of fsck\n");
239 		pfatal("from before 2002 with the command ``fsck -c 2''\n");
240 		exit(EEXIT);
241 	}
242 	if ((asblk.b_flags & B_DIRTY) != 0 && !bflag) {
243 		memmove(&altsblock, &sblock, (size_t)sblock.fs_sbsize);
244 		flush(fswritefd, &asblk);
245 	}
246 	if (preen == 0 && yflag == 0 && sblock.fs_magic == FS_UFS2_MAGIC &&
247 	    fswritefd != -1 && chkrecovery(fsreadfd) == 0 &&
248 	    reply("SAVE DATA TO FIND ALTERNATE SUPERBLOCKS") != 0)
249 		saverecovery(fsreadfd, fswritefd);
250 	/*
251 	 * read in the summary info.
252 	 */
253 	asked = 0;
254 	sblock.fs_csp = Calloc(1, sblock.fs_cssize);
255 	if (sblock.fs_csp == NULL) {
256 		printf("cannot alloc %u bytes for cg summary info\n",
257 		    (unsigned)sblock.fs_cssize);
258 		goto badsb;
259 	}
260 	for (i = 0, j = 0; i < sblock.fs_cssize; i += sblock.fs_bsize, j++) {
261 		size = MIN(sblock.fs_cssize - i, sblock.fs_bsize);
262 		readcnt[sblk.b_type]++;
263 		if (blread(fsreadfd, (char *)sblock.fs_csp + i,
264 		    fsbtodb(&sblock, sblock.fs_csaddr + j * sblock.fs_frag),
265 		    size) != 0 && !asked) {
266 			pfatal("BAD SUMMARY INFORMATION");
267 			if (reply("CONTINUE") == 0) {
268 				ckfini(0);
269 				exit(EEXIT);
270 			}
271 			asked++;
272 		}
273 	}
274 	/*
275 	 * allocate and initialize the necessary maps
276 	 */
277 	bmapsize = roundup(howmany(maxfsblock, CHAR_BIT), sizeof(short));
278 	blockmap = Calloc((unsigned)bmapsize, sizeof (char));
279 	if (blockmap == NULL) {
280 		printf("cannot alloc %u bytes for blockmap\n",
281 		    (unsigned)bmapsize);
282 		goto badsb;
283 	}
284 	inostathead = Calloc(sblock.fs_ncg, sizeof(struct inostatlist));
285 	if (inostathead == NULL) {
286 		printf("cannot alloc %u bytes for inostathead\n",
287 		    (unsigned)(sizeof(struct inostatlist) * (sblock.fs_ncg)));
288 		goto badsb;
289 	}
290 	numdirs = MAX(sblock.fs_cstotal.cs_ndir, 128);
291 	dirhash = numdirs;
292 	inplast = 0;
293 	listmax = numdirs + 10;
294 	inpsort = (struct inoinfo **)Calloc(listmax, sizeof(struct inoinfo *));
295 	inphead = (struct inoinfo **)Calloc(numdirs, sizeof(struct inoinfo *));
296 	if (inpsort == NULL || inphead == NULL) {
297 		printf("cannot alloc %ju bytes for inphead\n",
298 		    (uintmax_t)numdirs * sizeof(struct inoinfo *));
299 		goto badsb;
300 	}
301 	bufinit();
302 	if (sblock.fs_flags & FS_DOSOFTDEP)
303 		usedsoftdep = 1;
304 	else
305 		usedsoftdep = 0;
306 	return (1);
307 
308 badsb:
309 	ckfini(0);
310 	return (0);
311 }
312 
313 /*
314  * Read in the super block and its summary info.
315  */
316 int
317 readsb(int listerr)
318 {
319 	off_t super;
320 	int bad, ret;
321 	struct fs *fs;
322 
323 	super = bflag ? bflag * dev_bsize : STDSB_NOHASHFAIL;
324 	readcnt[sblk.b_type]++;
325 	if ((ret = sbget(fsreadfd, &fs, super)) != 0) {
326 		switch (ret) {
327 		case EINVAL:
328 			/* Superblock check-hash failed */
329 			return (0);
330 		case ENOENT:
331 			if (bflag)
332 				printf("%jd is not a file system "
333 				    "superblock\n", super / dev_bsize);
334 			else
335 				printf("Cannot find file system "
336 				    "superblock\n");
337 			return (0);
338 		case EIO:
339 		default:
340 			printf("I/O error reading %jd\n",
341 			    super / dev_bsize);
342 			return (0);
343 		}
344 	}
345 	memcpy(&sblock, fs, fs->fs_sbsize);
346 	free(fs);
347 	/*
348 	 * Compute block size that the file system is based on,
349 	 * according to fsbtodb, and adjust superblock block number
350 	 * so we can tell if this is an alternate later.
351 	 */
352 	dev_bsize = sblock.fs_fsize / fsbtodb(&sblock, 1);
353 	sblk.b_bno = sblock.fs_sblockactualloc / dev_bsize;
354 	sblk.b_size = SBLOCKSIZE;
355 	/*
356 	 * Compare all fields that should not differ in alternate super block.
357 	 * When an alternate super-block is specified this check is skipped.
358 	 */
359 	if (bflag)
360 		goto out;
361 	getblk(&asblk, cgsblock(&sblock, sblock.fs_ncg - 1), sblock.fs_sbsize);
362 	if (asblk.b_errs)
363 		return (0);
364 	bad = 0;
365 #define CHK(x, y)				\
366 	if (altsblock.x != sblock.x) {		\
367 		bad++;				\
368 		if (listerr && debug)		\
369 			printf("SUPER BLOCK VS ALTERNATE MISMATCH %s: " y " vs " y "\n", \
370 			    #x, (intmax_t)sblock.x, (intmax_t)altsblock.x); \
371 	}
372 	CHK(fs_sblkno, "%jd");
373 	CHK(fs_cblkno, "%jd");
374 	CHK(fs_iblkno, "%jd");
375 	CHK(fs_dblkno, "%jd");
376 	CHK(fs_ncg, "%jd");
377 	CHK(fs_bsize, "%jd");
378 	CHK(fs_fsize, "%jd");
379 	CHK(fs_frag, "%jd");
380 	CHK(fs_bmask, "%#jx");
381 	CHK(fs_fmask, "%#jx");
382 	CHK(fs_bshift, "%jd");
383 	CHK(fs_fshift, "%jd");
384 	CHK(fs_fragshift, "%jd");
385 	CHK(fs_fsbtodb, "%jd");
386 	CHK(fs_sbsize, "%jd");
387 	CHK(fs_nindir, "%jd");
388 	CHK(fs_inopb, "%jd");
389 	CHK(fs_cssize, "%jd");
390 	CHK(fs_ipg, "%jd");
391 	CHK(fs_fpg, "%jd");
392 	CHK(fs_magic, "%#jx");
393 #undef CHK
394 	if (bad) {
395 		if (listerr == 0)
396 			return (0);
397 		if (preen)
398 			printf("%s: ", cdevname);
399 		printf(
400 		    "VALUES IN SUPER BLOCK LSB=%jd DISAGREE WITH THOSE IN\n"
401 		    "LAST ALTERNATE LSB=%jd\n",
402 		    sblk.b_bno, asblk.b_bno);
403 		if (reply("IGNORE ALTERNATE SUPER BLOCK") == 0)
404 			return (0);
405 	}
406 out:
407 	/*
408 	 * If not yet done, update UFS1 superblock with new wider fields.
409 	 */
410 	if (sblock.fs_magic == FS_UFS1_MAGIC &&
411 	    sblock.fs_maxbsize != sblock.fs_bsize) {
412 		sblock.fs_maxbsize = sblock.fs_bsize;
413 		sblock.fs_time = sblock.fs_old_time;
414 		sblock.fs_size = sblock.fs_old_size;
415 		sblock.fs_dsize = sblock.fs_old_dsize;
416 		sblock.fs_csaddr = sblock.fs_old_csaddr;
417 		sblock.fs_cstotal.cs_ndir = sblock.fs_old_cstotal.cs_ndir;
418 		sblock.fs_cstotal.cs_nbfree = sblock.fs_old_cstotal.cs_nbfree;
419 		sblock.fs_cstotal.cs_nifree = sblock.fs_old_cstotal.cs_nifree;
420 		sblock.fs_cstotal.cs_nffree = sblock.fs_old_cstotal.cs_nffree;
421 	}
422 	havesb = 1;
423 	return (1);
424 }
425 
426 void
427 sblock_init(void)
428 {
429 
430 	fswritefd = -1;
431 	fsmodified = 0;
432 	lfdir = 0;
433 	initbarea(&sblk, BT_SUPERBLK);
434 	initbarea(&asblk, BT_SUPERBLK);
435 	sblk.b_un.b_buf = Malloc(SBLOCKSIZE);
436 	asblk.b_un.b_buf = Malloc(SBLOCKSIZE);
437 	if (sblk.b_un.b_buf == NULL || asblk.b_un.b_buf == NULL)
438 		errx(EEXIT, "cannot allocate space for superblock");
439 	dev_bsize = secsize = DEV_BSIZE;
440 }
441 
442 /*
443  * Calculate a prototype superblock based on information in the boot area.
444  * When done the cgsblock macro can be calculated and the fs_ncg field
445  * can be used. Do NOT attempt to use other macros without verifying that
446  * their needed information is available!
447  */
448 static int
449 calcsb(char *dev, int devfd, struct fs *fs)
450 {
451 	struct fsrecovery *fsr;
452 	char *fsrbuf;
453 	u_int secsize;
454 
455 	/*
456 	 * We need fragments-per-group and the partition-size.
457 	 *
458 	 * Newfs stores these details at the end of the boot block area
459 	 * at the start of the filesystem partition. If they have been
460 	 * overwritten by a boot block, we fail. But usually they are
461 	 * there and we can use them.
462 	 */
463 	if (ioctl(devfd, DIOCGSECTORSIZE, &secsize) == -1)
464 		return (0);
465 	fsrbuf = Malloc(secsize);
466 	if (fsrbuf == NULL)
467 		errx(EEXIT, "calcsb: cannot allocate recovery buffer");
468 	if (blread(devfd, fsrbuf,
469 	    (SBLOCK_UFS2 - secsize) / dev_bsize, secsize) != 0) {
470 		free(fsrbuf);
471 		return (0);
472 	}
473 	fsr = (struct fsrecovery *)&fsrbuf[secsize - sizeof *fsr];
474 	if (fsr->fsr_magic != FS_UFS2_MAGIC) {
475 		free(fsrbuf);
476 		return (0);
477 	}
478 	memset(fs, 0, sizeof(struct fs));
479 	fs->fs_fpg = fsr->fsr_fpg;
480 	fs->fs_fsbtodb = fsr->fsr_fsbtodb;
481 	fs->fs_sblkno = fsr->fsr_sblkno;
482 	fs->fs_magic = fsr->fsr_magic;
483 	fs->fs_ncg = fsr->fsr_ncg;
484 	free(fsrbuf);
485 	return (1);
486 }
487 
488 /*
489  * Check to see if recovery information exists.
490  * Return 1 if it exists or cannot be created.
491  * Return 0 if it does not exist and can be created.
492  */
493 static int
494 chkrecovery(int devfd)
495 {
496 	struct fsrecovery *fsr;
497 	char *fsrbuf;
498 	u_int secsize;
499 
500 	/*
501 	 * Could not determine if backup material exists, so do not
502 	 * offer to create it.
503 	 */
504 	fsrbuf = NULL;
505 	if (ioctl(devfd, DIOCGSECTORSIZE, &secsize) == -1 ||
506 	    (fsrbuf = Malloc(secsize)) == NULL ||
507 	    blread(devfd, fsrbuf, (SBLOCK_UFS2 - secsize) / dev_bsize,
508 	      secsize) != 0) {
509 		free(fsrbuf);
510 		return (1);
511 	}
512 	/*
513 	 * Recovery material has already been created, so do not
514 	 * need to create it again.
515 	 */
516 	fsr = (struct fsrecovery *)&fsrbuf[secsize - sizeof *fsr];
517 	if (fsr->fsr_magic == FS_UFS2_MAGIC) {
518 		free(fsrbuf);
519 		return (1);
520 	}
521 	/*
522 	 * Recovery material has not been created and can be if desired.
523 	 */
524 	free(fsrbuf);
525 	return (0);
526 }
527 
528 /*
529  * Read the last sector of the boot block, replace the last
530  * 20 bytes with the recovery information, then write it back.
531  * The recovery information only works for UFS2 filesystems.
532  */
533 static void
534 saverecovery(int readfd, int writefd)
535 {
536 	struct fsrecovery *fsr;
537 	char *fsrbuf;
538 	u_int secsize;
539 
540 	fsrbuf = NULL;
541 	if (sblock.fs_magic != FS_UFS2_MAGIC ||
542 	    ioctl(readfd, DIOCGSECTORSIZE, &secsize) == -1 ||
543 	    (fsrbuf = Malloc(secsize)) == NULL ||
544 	    blread(readfd, fsrbuf, (SBLOCK_UFS2 - secsize) / dev_bsize,
545 	      secsize) != 0) {
546 		printf("RECOVERY DATA COULD NOT BE CREATED\n");
547 		free(fsrbuf);
548 		return;
549 	}
550 	fsr = (struct fsrecovery *)&fsrbuf[secsize - sizeof *fsr];
551 	fsr->fsr_magic = sblock.fs_magic;
552 	fsr->fsr_fpg = sblock.fs_fpg;
553 	fsr->fsr_fsbtodb = sblock.fs_fsbtodb;
554 	fsr->fsr_sblkno = sblock.fs_sblkno;
555 	fsr->fsr_ncg = sblock.fs_ncg;
556 	blwrite(writefd, fsrbuf, (SBLOCK_UFS2 - secsize) / secsize, secsize);
557 	free(fsrbuf);
558 }
559