xref: /netbsd-src/sbin/fsck_ffs/setup.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: setup.c,v 1.61 2003/04/11 10:21:40 enami Exp $	*/
2 
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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)setup.c	8.10 (Berkeley) 5/9/95";
40 #else
41 __RCSID("$NetBSD: setup.c,v 1.61 2003/04/11 10:21:40 enami Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/ioctl.h>
49 #define FSTYPENAMES
50 #include <sys/disklabel.h>
51 #include <sys/file.h>
52 
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ufs/dir.h>
55 #include <ufs/ufs/ufs_bswap.h>
56 #include <ufs/ffs/fs.h>
57 #include <ufs/ffs/ffs_extern.h>
58 
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 
66 #include "fsck.h"
67 #include "extern.h"
68 #include "fsutil.h"
69 
70 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
71 
72 static void badsb __P((int, char *));
73 static int calcsb __P((const char *, int, struct fs *));
74 static struct disklabel *getdisklabel __P((const char *, int));
75 static struct partition *getdisklabelpart __P((const char *, struct disklabel *));
76 static int readsb __P((int));
77 static int readappleufs __P((void));
78 
79 /*
80  * Read in a superblock finding an alternate if necessary.
81  * Return 1 if successful, 0 if unsuccessful, -1 if filesystem
82  * is already clean (preen mode only).
83  */
84 int
85 setup(dev)
86 	const char *dev;
87 {
88 	long cg, size, asked, i, j;
89 	long bmapsize;
90 	struct disklabel *lp;
91 	off_t sizepb;
92 	struct stat statb;
93 	struct fs proto;
94 	int doskipclean;
95 	u_int64_t maxfilesize;
96 	struct csum *ccsp;
97 
98 	havesb = 0;
99 	fswritefd = -1;
100 	doskipclean = skipclean;
101 	if (stat(dev, &statb) < 0) {
102 		printf("Can't stat %s: %s\n", dev, strerror(errno));
103 		return (0);
104 	}
105 	if (!forceimage && !S_ISCHR(statb.st_mode)) {
106 		pfatal("%s is not a character device", dev);
107 		if (reply("CONTINUE") == 0)
108 			return (0);
109 	}
110 	if ((fsreadfd = open(dev, O_RDONLY)) < 0) {
111 		printf("Can't open %s: %s\n", dev, strerror(errno));
112 		return (0);
113 	}
114 	if (preen == 0)
115 		printf("** %s", dev);
116 	if (nflag || (fswritefd = open(dev, O_WRONLY)) < 0) {
117 		fswritefd = -1;
118 		if (preen)
119 			pfatal("NO WRITE ACCESS");
120 		printf(" (NO WRITE)");
121 	}
122 	if (preen == 0)
123 		printf("\n");
124 	fsmodified = 0;
125 	lfdir = 0;
126 	initbarea(&sblk);
127 	initbarea(&asblk);
128 	sblk.b_un.b_buf = malloc(SBLOCKSIZE);
129 	sblock = malloc(SBLOCKSIZE);
130 	asblk.b_un.b_buf = malloc(SBLOCKSIZE);
131 	altsblock = malloc(SBLOCKSIZE);
132 	if (sblk.b_un.b_buf == NULL || asblk.b_un.b_buf == NULL ||
133 		sblock == NULL || altsblock == NULL)
134 		errx(EEXIT, "cannot allocate space for superblock");
135 	if (!forceimage && (lp = getdisklabel(NULL, fsreadfd)) != NULL)
136 		dev_bsize = secsize = lp->d_secsize;
137 	else
138 		dev_bsize = secsize = DEV_BSIZE;
139 	/*
140 	 * Read in the superblock, looking for alternates if necessary
141 	 */
142 	if (readsb(1) == 0) {
143 		if (bflag || preen || forceimage ||
144 		    calcsb(dev, fsreadfd, &proto) == 0)
145 			return(0);
146 		if (reply("LOOK FOR ALTERNATE SUPERBLOCKS") == 0)
147 			return (0);
148 		for (cg = 0; cg < proto.fs_ncg; cg++) {
149 			bflag = fsbtodb(&proto, cgsblock(&proto, cg));
150 			if (readsb(0) != 0)
151 				break;
152 		}
153 		if (cg >= proto.fs_ncg) {
154 			printf("%s %s\n%s %s\n%s %s\n",
155 				"SEARCH FOR ALTERNATE SUPER-BLOCK",
156 				"FAILED. YOU MUST USE THE",
157 				"-b OPTION TO fsck_ffs TO SPECIFY THE",
158 				"LOCATION OF AN ALTERNATE",
159 				"SUPER-BLOCK TO SUPPLY NEEDED",
160 				"INFORMATION; SEE fsck_ffs(8).");
161 			return(0);
162 		}
163 		doskipclean = 0;
164 		pwarn("USING ALTERNATE SUPERBLOCK AT %d\n", bflag);
165 	}
166 	if (debug)
167 		printf("clean = %d\n", sblock->fs_clean);
168 	if (doswap)
169 		doskipclean = 0;
170 	if (sblock->fs_old_postblformat == FS_42POSTBLFMT) {
171 		pwarn("%sile system is in 4.2BSD format, check skipped\n",
172 		    preen ? "f" : "** F");
173 		return -1;
174 	}
175 	if (sblock->fs_clean & FS_ISCLEAN) {
176 		if (doskipclean) {
177 			pwarn("%sile system is clean; not checking\n",
178 			    preen ? "f" : "** F");
179 			return (-1);
180 		}
181 		if (!preen && !doswap)
182 			pwarn("** File system is already clean\n");
183 	}
184 	maxfsblock = sblock->fs_size;
185 	maxino = sblock->fs_ncg * sblock->fs_ipg;
186 	sizepb = sblock->fs_bsize;
187 	maxfilesize = sblock->fs_bsize * NDADDR - 1;
188 	for (i = 0; i < NIADDR; i++) {
189 		sizepb *= NINDIR(sblock);
190 		maxfilesize += sizepb;
191 	}
192 	/*
193 	 * Check and potentially fix certain fields in the super block.
194 	 */
195 	if (sblock->fs_optim != FS_OPTTIME && sblock->fs_optim != FS_OPTSPACE) {
196 		pfatal("UNDEFINED OPTIMIZATION IN SUPERBLOCK");
197 		if (reply("SET TO DEFAULT") == 1) {
198 			sblock->fs_optim = FS_OPTTIME;
199 			sbdirty();
200 		}
201 	}
202 	if ((sblock->fs_minfree < 0 || sblock->fs_minfree > 99)) {
203 		pfatal("IMPOSSIBLE MINFREE=%d IN SUPERBLOCK",
204 			sblock->fs_minfree);
205 		if (reply("SET TO DEFAULT") == 1) {
206 			sblock->fs_minfree = 10;
207 			sbdirty();
208 		}
209 	}
210 	if (!is_ufs2 && sblock->fs_old_postblformat != FS_42POSTBLFMT &&
211 	    (sblock->fs_old_interleave < 1 ||
212 	    sblock->fs_old_interleave > sblock->fs_old_nsect)) {
213 		pwarn("IMPOSSIBLE INTERLEAVE=%d IN SUPERBLOCK",
214 			sblock->fs_old_interleave);
215 		sblock->fs_old_interleave = 1;
216 		if (preen)
217 			printf(" (FIXED)\n");
218 		if (preen || reply("SET TO DEFAULT") == 1) {
219 			sbdirty();
220 			dirty(&asblk);
221 		}
222 	}
223 	if (!is_ufs2 && sblock->fs_old_postblformat != FS_42POSTBLFMT &&
224 	    (sblock->fs_old_npsect < sblock->fs_old_nsect ||
225 	    sblock->fs_old_npsect > sblock->fs_old_nsect*2)) {
226 		pwarn("IMPOSSIBLE NPSECT=%d IN SUPERBLOCK",
227 			sblock->fs_old_npsect);
228 		sblock->fs_old_npsect = sblock->fs_old_nsect;
229 		if (preen)
230 			printf(" (FIXED)\n");
231 		if (preen || reply("SET TO DEFAULT") == 1) {
232 			sbdirty();
233 			dirty(&asblk);
234 		}
235 	}
236 	if (sblock->fs_bmask != ~(sblock->fs_bsize - 1)) {
237 		pwarn("INCORRECT BMASK=0x%x IN SUPERBLOCK",
238 			sblock->fs_bmask);
239 		sblock->fs_bmask = ~(sblock->fs_bsize - 1);
240 		if (preen)
241 			printf(" (FIXED)\n");
242 		if (preen || reply("FIX") == 1) {
243 			sbdirty();
244 			dirty(&asblk);
245 		}
246 	}
247 	if (sblock->fs_fmask != ~(sblock->fs_fsize - 1)) {
248 		pwarn("INCORRECT FMASK=0x%x IN SUPERBLOCK",
249 			sblock->fs_fmask);
250 		sblock->fs_fmask = ~(sblock->fs_fsize - 1);
251 		if (preen)
252 			printf(" (FIXED)\n");
253 		if (preen || reply("FIX") == 1) {
254 			sbdirty();
255 			dirty(&asblk);
256 		}
257 	}
258 	if (sblock->fs_old_inodefmt >= FS_44INODEFMT) {
259 		if (sblock->fs_maxfilesize != maxfilesize) {
260 			pwarn("INCORRECT MAXFILESIZE=%lld IN SUPERBLOCK",
261 			    (unsigned long long)sblock->fs_maxfilesize);
262 			sblock->fs_maxfilesize = maxfilesize;
263 			if (preen)
264 				printf(" (FIXED)\n");
265 			if (preen || reply("FIX") == 1) {
266 				sbdirty();
267 				dirty(&asblk);
268 			}
269 		}
270 		if ((is_ufs2 && sblock->fs_maxsymlinklen != MAXSYMLINKLEN_UFS2)
271 		    ||
272 		   (!is_ufs2 && sblock->fs_maxsymlinklen != MAXSYMLINKLEN_UFS1))
273 		    {
274 			pwarn("INCORRECT MAXSYMLINKLEN=%d IN SUPERBLOCK",
275 				sblock->fs_maxsymlinklen);
276 			sblock->fs_maxsymlinklen = is_ufs2 ?
277 			    MAXSYMLINKLEN_UFS2 : MAXSYMLINKLEN_UFS1;
278 			if (preen)
279 				printf(" (FIXED)\n");
280 			if (preen || reply("FIX") == 1) {
281 				sbdirty();
282 				dirty(&asblk);
283 			}
284 		}
285 		if (sblock->fs_qbmask != ~sblock->fs_bmask) {
286 			pwarn("INCORRECT QBMASK=%llx IN SUPERBLOCK",
287 			    (unsigned long long)sblock->fs_qbmask);
288 			sblock->fs_qbmask = ~sblock->fs_bmask;
289 			if (preen)
290 				printf(" (FIXED)\n");
291 			if (preen || reply("FIX") == 1) {
292 				sbdirty();
293 				dirty(&asblk);
294 			}
295 		}
296 		if (sblock->fs_qfmask != ~sblock->fs_fmask) {
297 			pwarn("INCORRECT QFMASK=%llx IN SUPERBLOCK",
298 			    (unsigned long long)sblock->fs_qfmask);
299 			sblock->fs_qfmask = ~sblock->fs_fmask;
300 			if (preen)
301 				printf(" (FIXED)\n");
302 			if (preen || reply("FIX") == 1) {
303 				sbdirty();
304 				dirty(&asblk);
305 			}
306 		}
307 		newinofmt = 1;
308 	} else {
309 		sblock->fs_qbmask = ~sblock->fs_bmask;
310 		sblock->fs_qfmask = ~sblock->fs_fmask;
311 		newinofmt = 0;
312 	}
313 	/*
314 	 * Convert to new inode format.
315 	 */
316 	if (!is_ufs2 && cvtlevel >= 2 &&
317 	    sblock->fs_old_inodefmt < FS_44INODEFMT) {
318 		if (preen)
319 			pwarn("CONVERTING TO NEW INODE FORMAT\n");
320 		else if (!reply("CONVERT TO NEW INODE FORMAT"))
321 			return(0);
322 		doinglevel2++;
323 		sblock->fs_old_inodefmt = FS_44INODEFMT;
324 		sblock->fs_maxfilesize = maxfilesize;
325 		sblock->fs_maxsymlinklen = MAXSYMLINKLEN_UFS1;
326 		sblock->fs_qbmask = ~sblock->fs_bmask;
327 		sblock->fs_qfmask = ~sblock->fs_fmask;
328 		sbdirty();
329 		dirty(&asblk);
330 	}
331 	/*
332 	 * Convert to new cylinder group format.
333 	 */
334 	if (!is_ufs2 && cvtlevel >= 1 &&
335 	    sblock->fs_old_postblformat == FS_42POSTBLFMT) {
336 		if (preen)
337 			pwarn("CONVERTING TO NEW CYLINDER GROUP FORMAT\n");
338 		else if (!reply("CONVERT TO NEW CYLINDER GROUP FORMAT"))
339 			return(0);
340 		doinglevel1++;
341 		sblock->fs_old_postblformat = FS_DYNAMICPOSTBLFMT;
342 		sblock->fs_old_nrpos = 0;
343 		sbdirty();
344 		dirty(&asblk);
345 	}
346 	if (asblk.b_dirty && !bflag) {
347 		memmove((struct fs*)sblk.b_un.b_fs, sblock, SBLOCKSIZE);
348 		if (needswap)
349 			ffs_sb_swap(sblock, (struct fs*)sblk.b_un.b_fs);
350 		memmove(asblk.b_un.b_fs, sblk.b_un.b_fs, (size_t)sblock->fs_sbsize);
351 		flush(fswritefd, &asblk);
352 	}
353 	/*
354 	 * read in the summary info.
355 	 */
356 	asked = 0;
357 	sblock->fs_csp = (struct csum *)calloc(1, sblock->fs_cssize);
358 	for (i = 0, j = 0; i < sblock->fs_cssize; i += sblock->fs_bsize, j++) {
359 		size = sblock->fs_cssize - i < sblock->fs_bsize ?
360 		    sblock->fs_cssize - i : sblock->fs_bsize;
361 		ccsp = (struct csum *)((char *)sblock->fs_csp + i);
362 		if (bread(fsreadfd, (char *)ccsp,
363 		    fsbtodb(sblock, sblock->fs_csaddr + j * sblock->fs_frag),
364 		    size) != 0 && !asked) {
365 			pfatal("BAD SUMMARY INFORMATION");
366 			if (reply("CONTINUE") == 0) {
367 				markclean = 0;
368 				exit(EEXIT);
369 			}
370 			asked++;
371 		}
372 		if (doswap) {
373 			ffs_csum_swap(ccsp, ccsp, size);
374 			bwrite(fswritefd, (char *)ccsp,
375 			    fsbtodb(sblock,
376 				sblock->fs_csaddr + j * sblock->fs_frag),
377 			    size);
378 		}
379 		if (needswap)
380 			ffs_csum_swap(ccsp, ccsp, size);
381 	}
382 	/*
383 	 * allocate and initialize the necessary maps
384 	 */
385 	bmapsize = roundup(howmany(maxfsblock, NBBY), sizeof(int16_t));
386 	blockmap = calloc((unsigned)bmapsize, sizeof (char));
387 	if (blockmap == NULL) {
388 		printf("cannot alloc %u bytes for blockmap\n",
389 		    (unsigned)bmapsize);
390 		goto badsblabel;
391 	}
392 	inostathead = calloc((unsigned)(sblock->fs_ncg),
393 	    sizeof(struct inostatlist));
394 	if (inostathead == NULL) {
395 		printf("cannot alloc %u bytes for inostathead\n",
396 		    (unsigned)(sizeof(struct inostatlist) * (sblock->fs_ncg)));
397 		goto badsblabel;
398 	}
399 	/*
400 	 * cs_ndir may be inaccurate, particularly if we're using the -b
401 	 * option, so set a minimum to prevent bogus subdirectory reconnects
402 	 * and really inefficient directory scans.
403 	 * Also set a maximum in case the value is too large.
404 	 */
405 	numdirs = sblock->fs_cstotal.cs_ndir;
406 	if (numdirs < 1024)
407 		numdirs = 1024;
408 	if (numdirs > maxino + 1)
409 		numdirs = maxino + 1;
410 	dirhash = numdirs;
411 	inplast = 0;
412 	listmax = numdirs + 10;
413 	inpsort = (struct inoinfo **)calloc((unsigned)listmax,
414 	    sizeof(struct inoinfo *));
415 	inphead = (struct inoinfo **)calloc((unsigned)numdirs,
416 	    sizeof(struct inoinfo *));
417 	if (inpsort == NULL || inphead == NULL) {
418 		printf("cannot alloc %u bytes for inphead\n",
419 		    (unsigned)(numdirs * sizeof(struct inoinfo *)));
420 		goto badsblabel;
421 	}
422 	cgrp = malloc(sblock->fs_cgsize);
423 	if (cgrp == NULL) {
424 		printf("cannot alloc %u bytes for cylinder group\n",
425 		    sblock->fs_cgsize);
426 		goto badsblabel;
427 	}
428 	bufinit();
429 	if (sblock->fs_flags & FS_DOSOFTDEP)
430 		usedsoftdep = 1;
431 	else
432 		usedsoftdep = 0;
433 
434 	{
435 		struct partition *pp = 0;
436 		if (!forceimage && lp)
437 			pp = getdisklabelpart(dev,lp);
438 		if (pp && (pp->p_fstype == FS_APPLEUFS)) {
439 			isappleufs = 1;
440 		}
441 	}
442 	if (readappleufs()) {
443 		isappleufs = 1;
444 	}
445 
446 	dirblksiz = DIRBLKSIZ;
447 	if (isappleufs)
448 		dirblksiz = APPLEUFS_DIRBLKSIZ;
449 
450 	if (debug)
451 		printf("isappleufs = %d, dirblksiz = %d\n", isappleufs, dirblksiz);
452 
453 	return (1);
454 
455 badsblabel:
456 	markclean=0;
457 	ckfini();
458 	return (0);
459 }
460 
461 static int
462 readappleufs()
463 {
464 	daddr_t label = APPLEUFS_LABEL_OFFSET / dev_bsize;
465 	struct appleufslabel *appleufs;
466 	int i;
467 
468 	/* XXX do we have to deal with APPLEUFS_LABEL_OFFSET not
469 	 * being block aligned (CD's?)
470 	 */
471 	if (bread(fsreadfd, (char *)appleufsblk.b_un.b_fs, label, (long)APPLEUFS_LABEL_SIZE) != 0)
472 		return 0;
473 	appleufsblk.b_bno = label;
474 	appleufsblk.b_size = APPLEUFS_LABEL_SIZE;
475 
476 	appleufs = appleufsblk.b_un.b_appleufs;
477 
478 	if (ntohl(appleufs->ul_magic) != APPLEUFS_LABEL_MAGIC) {
479 		if (!isappleufs) {
480 			return 0;
481 		} else {
482 			pfatal("MISSING APPLEUFS VOLUME LABEL\n");
483 			if (reply("FIX") == 0) {
484 				return 1;
485 			}
486 			ffs_appleufs_set(appleufs,NULL,-1);
487 			appleufsdirty();
488 		}
489 	}
490 
491 	if (ntohl(appleufs->ul_version) != APPLEUFS_LABEL_VERSION) {
492 		pwarn("INCORRECT APPLE UFS VERSION NUMBER (%d should be %d)",
493 			ntohl(appleufs->ul_version),APPLEUFS_LABEL_VERSION);
494 		if (preen) {
495 			printf(" (CORRECTED)\n");
496 		}
497 		if (preen || reply("CORRECT")) {
498 			appleufs->ul_version = htonl(APPLEUFS_LABEL_VERSION);
499 			appleufsdirty();
500 		}
501 	}
502 
503 	if (ntohs(appleufs->ul_namelen) > APPLEUFS_MAX_LABEL_NAME) {
504 		pwarn("APPLE UFS LABEL NAME TOO LONG");
505 		if (preen) {
506 			printf(" (TRUNCATED)\n");
507 		}
508 		if (preen || reply("TRUNCATE")) {
509 			appleufs->ul_namelen = htons(APPLEUFS_MAX_LABEL_NAME);
510 			appleufsdirty();
511 		}
512 	}
513 
514 	if (ntohs(appleufs->ul_namelen) == 0) {
515 		pwarn("MISSING APPLE UFS LABEL NAME");
516 		if (preen) {
517 			printf(" (FIXED)\n");
518 		}
519 		if (preen || reply("FIX")) {
520 			ffs_appleufs_set(appleufs,NULL,-1);
521 			appleufsdirty();
522 		}
523 	}
524 
525 	/* Scan name for first illegal character */
526 	for (i=0;i<ntohs(appleufs->ul_namelen);i++) {
527 		if ((appleufs->ul_name[i] == '\0') ||
528 			(appleufs->ul_name[i] == ':') ||
529 			(appleufs->ul_name[i] == '/')) {
530 			pwarn("APPLE UFS LABEL NAME CONTAINS ILLEGAL CHARACTER");
531 			if (preen) {
532 				printf(" (TRUNCATED)\n");
533 			}
534 			if (preen || reply("TRUNCATE")) {
535 				appleufs->ul_namelen = i+1;
536 				appleufsdirty();
537 			}
538 			break;
539 		}
540 	}
541 
542 	/* Check the checksum last, because if anything else was wrong,
543 	 * then the checksum gets reset anyway.
544 	 */
545 	appleufs->ul_checksum = 0;
546 	appleufs->ul_checksum = ffs_appleufs_cksum(appleufs);
547 	if (appleufsblk.b_un.b_appleufs->ul_checksum != appleufs->ul_checksum) {
548 		pwarn("INVALID APPLE UFS CHECKSUM (%#04x should be %#04x)",
549 			appleufsblk.b_un.b_appleufs->ul_checksum, appleufs->ul_checksum);
550 		if (preen) {
551 			printf(" (CORRECTED)\n");
552 		}
553 		if (preen || reply("CORRECT")) {
554 			appleufsdirty();
555 		} else {
556 			/* put the incorrect checksum back in place */
557 			appleufs->ul_checksum = appleufsblk.b_un.b_appleufs->ul_checksum;
558 		}
559 	}
560 	return 1;
561 }
562 
563 /*
564  * Detect byte order. Return 0 if valid magic found, -1 otherwise.
565  */
566 static int
567 detect_byteorder(struct fs *fs)
568 {
569 	if (fs->fs_magic == FS_UFS1_MAGIC || fs->fs_magic == FS_UFS2_MAGIC) {
570 		if (endian == 0 || BYTE_ORDER == endian) {
571 			needswap = 0;
572 			doswap = do_blkswap = do_dirswap = 0;
573 		} else {
574 			needswap = 1;
575 			doswap = do_blkswap = do_dirswap = 1;
576 		}
577 		return 0;
578 	} else if (fs->fs_magic == bswap32(FS_UFS1_MAGIC) ||
579 		   fs->fs_magic == bswap32(FS_UFS2_MAGIC)) {
580 		if (endian == 0 || BYTE_ORDER != endian) {
581 			needswap = 1;
582 			doswap = do_blkswap = do_dirswap = 0;
583 		} else {
584 			needswap = 0;
585 			doswap = do_blkswap = do_dirswap = 1;
586 		}
587 		return 0;
588 	}
589 	return -1;
590 }
591 
592 /*
593  * Possible superblock locations ordered from most to least likely.
594  */
595 static off_t sblock_try[] = SBLOCKSEARCH;
596 
597 /*
598  * Read in the super block and its summary info.
599  */
600 static int
601 readsb(listerr)
602 	int listerr;
603 {
604 	daddr_t super;
605 	struct fs *fs;
606 	int i;
607 
608 	if (bflag) {
609 		super = bflag;
610 		if (bread(fsreadfd, (char *)sblk.b_un.b_fs, super,
611 		    (long)SBLOCKSIZE) != 0)
612 			return (0);
613 		fs = sblk.b_un.b_fs;
614 		if (detect_byteorder(fs) < 0) {
615 			badsb(listerr, "MAGIC NUMBER WRONG");
616 			return (0);
617 		}
618 	} else {
619 		for (i = 0; sblock_try[i] != -1; i++) {
620 			super = sblock_try[i] / dev_bsize;
621 			if (bread(fsreadfd, (char *)sblk.b_un.b_fs,
622 			    super, (long)SBLOCKSIZE) != 0)
623 				continue;
624 			fs = sblk.b_un.b_fs;
625 			if (detect_byteorder(fs) == 0)
626 				break;
627 		}
628 		if (sblock_try[i] == -1) {
629 			badsb(listerr, "CAN'T FIND SUPERBLOCK");
630 			return (0);
631 		}
632 	}
633 	if (doswap) {
634 		if (preen)
635 			errx(EEXIT, "incompatible options -B and -p");
636 		if (nflag)
637 			errx(EEXIT, "incompatible options -B and -n");
638 		if (endian == LITTLE_ENDIAN) {
639 			if (!reply("CONVERT TO LITTLE ENDIAN"))
640 				return 0;
641 		} else if (endian == BIG_ENDIAN) {
642 			if (!reply("CONVERT TO BIG ENDIAN"))
643 				return 0;
644 		} else
645 			pfatal("INTERNAL ERROR: unknown endian");
646 	}
647 	if (needswap)
648 		printf("** Swapped byte order\n");
649 	/* swap SB byte order if asked */
650 	if (doswap)
651 		ffs_sb_swap(sblk.b_un.b_fs, sblk.b_un.b_fs);
652 
653 	memmove(sblock, sblk.b_un.b_fs, SBLOCKSIZE);
654 	if (needswap)
655 		ffs_sb_swap(sblk.b_un.b_fs, sblock);
656 
657 	is_ufs2 = sblock->fs_magic == FS_UFS2_MAGIC;
658 
659 	/*
660 	 * run a few consistency checks of the super block
661 	 */
662 	if (sblock->fs_sbsize > SBLOCKSIZE)
663 		{ badsb(listerr, "SIZE PREPOSTEROUSLY LARGE"); return (0); }
664 	/*
665 	 * Compute block size that the filesystem is based on,
666 	 * according to fsbtodb, and adjust superblock block number
667 	 * so we can tell if this is an alternate later.
668 	 */
669 	super *= dev_bsize;
670 	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
671 	sblk.b_bno = super / dev_bsize;
672 	sblk.b_size = SBLOCKSIZE;
673 	if (bflag)
674 		goto out;
675 	/*
676 	 * Set all possible fields that could differ, then do check
677 	 * of whole super block against an alternate super block->
678 	 * When an alternate super-block is specified this check is skipped.
679 	 */
680 	getblk(&asblk, cgsblock(sblock, sblock->fs_ncg - 1), sblock->fs_sbsize);
681 	if (asblk.b_errs)
682 		return (0);
683 	/* swap SB byte order if asked */
684 	if (doswap)
685 		ffs_sb_swap(asblk.b_un.b_fs, asblk.b_un.b_fs);
686 
687 	memmove(altsblock, asblk.b_un.b_fs, sblock->fs_sbsize);
688 	if (needswap)
689 		ffs_sb_swap(asblk.b_un.b_fs, altsblock);
690 	if (cmpsblks(sblock, altsblock)) {
691 		badsb(listerr,
692 		"VALUES IN SUPER BLOCK DISAGREE WITH THOSE IN FIRST ALTERNATE");
693 		return (0);
694 	}
695 out:
696         /*
697          * If not yet done, update UFS1 superblock with new wider fields.
698          */
699         if (sblock->fs_magic == FS_UFS1_MAGIC) {
700 		if (sblock->fs_maxbsize != sblock->fs_bsize ||
701 		    sblock->fs_time < sblock->fs_old_time) {
702 			sblock->fs_cstotal.cs_ndir =
703 			    sblock->fs_old_cstotal.cs_ndir;
704 			sblock->fs_cstotal.cs_nbfree =
705 			    sblock->fs_old_cstotal.cs_nbfree;
706 			sblock->fs_cstotal.cs_nifree =
707 			    sblock->fs_old_cstotal.cs_nifree;
708 			sblock->fs_cstotal.cs_nffree =
709 			    sblock->fs_old_cstotal.cs_nffree;
710 		}
711 		if (sblock->fs_maxbsize != sblock->fs_bsize) {
712 			sblock->fs_maxbsize = sblock->fs_bsize;
713 			sblock->fs_time = sblock->fs_old_time;
714 			sblock->fs_size = sblock->fs_old_size;
715 			sblock->fs_dsize = sblock->fs_old_dsize;
716 			sblock->fs_csaddr = sblock->fs_old_csaddr;
717 		}
718 	}
719 
720 	/* Now we know the SB is valid, we can write it back if needed */
721 	if (doswap) {
722 		sbdirty();
723 		dirty(&asblk);
724 	}
725 	havesb = 1;
726 	return (1);
727 }
728 
729 int
730 cmpsblks(const struct fs *sb, struct fs *asb)
731 {
732         if (asb->fs_sblkno != sb->fs_sblkno ||
733 	    asb->fs_cblkno != sb->fs_cblkno ||
734 	    asb->fs_iblkno != sb->fs_iblkno ||
735 	    asb->fs_dblkno != sb->fs_dblkno ||
736 	    asb->fs_ncg != sb->fs_ncg ||
737 	    asb->fs_bsize != sb->fs_bsize ||
738 	    asb->fs_fsize != sb->fs_fsize ||
739 	    asb->fs_frag != sb->fs_frag ||
740 	    asb->fs_bmask != sb->fs_bmask ||
741 	    asb->fs_fmask != sb->fs_fmask ||
742 	    asb->fs_bshift != sb->fs_bshift ||
743 	    asb->fs_fshift != sb->fs_fshift ||
744 	    asb->fs_fragshift != sb->fs_fragshift ||
745 	    asb->fs_fsbtodb != sb->fs_fsbtodb ||
746 	    asb->fs_sbsize != sb->fs_sbsize ||
747 	    asb->fs_nindir != sb->fs_nindir ||
748 	    asb->fs_inopb != sb->fs_inopb ||
749 	    asb->fs_cssize != sb->fs_cssize ||
750 	    asb->fs_ipg != sb->fs_ipg ||
751 	    asb->fs_fpg != sb->fs_fpg ||
752 	    asb->fs_magic != sb->fs_magic)
753 		return 1;
754 	return 0;
755 }
756 
757 static void
758 badsb(listerr, s)
759 	int listerr;
760 	char *s;
761 {
762 
763 	if (!listerr)
764 		return;
765 	if (preen)
766 		printf("%s: ", cdevname());
767 	pfatal("BAD SUPER BLOCK: %s\n", s);
768 }
769 
770 /*
771  * Calculate a prototype superblock based on information in the disk label.
772  * When done the cgsblock macro can be calculated and the fs_ncg field
773  * can be used. Do NOT attempt to use other macros without verifying that
774  * their needed information is available!
775  */
776 static int
777 calcsb(dev, devfd, fs)
778 	const char *dev;
779 	int devfd;
780 	struct fs *fs;
781 {
782 	struct disklabel *lp;
783 	struct partition *pp;
784 	int i, nspf;
785 
786 	lp = getdisklabel(dev, devfd);
787 	pp = getdisklabelpart(dev,lp);
788 	if (pp == 0) {
789 		pfatal("%s: CANNOT FIGURE OUT FILE SYSTEM PARTITION\n", dev);
790 		return (0);
791 	}
792 	if ((pp->p_fstype != FS_BSDFFS) && (pp->p_fstype != FS_APPLEUFS)) {
793 		pfatal("%s: NOT LABELED AS A BSD FILE SYSTEM (%s)\n",
794 			dev, pp->p_fstype < FSMAXTYPES ?
795 			fstypenames[pp->p_fstype] : "unknown");
796 		return (0);
797 	}
798 	/* avoid divide by 0 */
799 	if (pp->p_fsize == 0 || pp->p_frag == 0)
800 		return (0);
801 	memset(fs, 0, sizeof(struct fs));
802 	fs->fs_fsize = pp->p_fsize;
803 	fs->fs_frag = pp->p_frag;
804 	fs->fs_size = pp->p_size;
805 	fs->fs_sblkno = roundup(
806 		howmany(lp->d_bbsize + lp->d_sbsize, fs->fs_fsize),
807 		fs->fs_frag);
808 	nspf = fs->fs_fsize / lp->d_secsize;
809 	fs->fs_old_nspf = nspf;
810 	for (fs->fs_fsbtodb = 0, i = nspf; i > 1; i >>= 1)
811 		fs->fs_fsbtodb++;
812 	dev_bsize = lp->d_secsize;
813 	if (fs->fs_magic == FS_UFS2_MAGIC) {
814 		fs->fs_fpg = pp->p_cpg;
815 		fs->fs_ncg = howmany(fs->fs_size, fs->fs_fpg);
816 	} else /* if (fs->fs_magic == FS_UFS1_MAGIC) */ {
817 		fs->fs_old_cpg = pp->p_cpg;
818 		fs->fs_old_cgmask = 0xffffffff;
819 		for (i = lp->d_ntracks; i > 1; i >>= 1)
820 			fs->fs_old_cgmask <<= 1;
821 		if (!POWEROF2(lp->d_ntracks))
822 			fs->fs_old_cgmask <<= 1;
823 		fs->fs_old_cgoffset = roundup(
824 			howmany(lp->d_nsectors, nspf), fs->fs_frag);
825 		fs->fs_fpg = (fs->fs_old_cpg * lp->d_secpercyl) / nspf;
826 		fs->fs_ncg = howmany(fs->fs_size / lp->d_secpercyl,
827 		    fs->fs_old_cpg);
828 	}
829 	return (1);
830 }
831 
832 static struct disklabel *
833 getdisklabel(s, fd)
834 	const char *s;
835 	int	fd;
836 {
837 	static struct disklabel lab;
838 
839 	if (ioctl(fd, DIOCGDINFO, (char *)&lab) < 0) {
840 		if (s == NULL)
841 			return ((struct disklabel *)NULL);
842 		pwarn("ioctl (GCINFO): %s\n", strerror(errno));
843 		errx(EEXIT, "%s: can't read disk label", s);
844 	}
845 	return (&lab);
846 }
847 
848 static struct partition *
849 getdisklabelpart(dev, lp)
850 	const char *dev;
851 	struct disklabel *lp;
852 {
853 	char *cp;
854 
855 	cp = strchr(dev, '\0') - 1;
856 	if ((cp == (char *)-1 || (*cp < 'a' || *cp > 'p')) && !isdigit(*cp)) {
857 		return 0;
858 	}
859 	if (isdigit(*cp))
860 		return &lp->d_partitions[0];
861 	else
862 		return &lp->d_partitions[*cp - 'a'];
863 }
864 
865