xref: /netbsd-src/sbin/fsck_ffs/setup.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: setup.c,v 1.84 2008/08/30 10:46:16 bouyer 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. 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 #include <sys/cdefs.h>
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)setup.c	8.10 (Berkeley) 5/9/95";
36 #else
37 __RCSID("$NetBSD: setup.c,v 1.84 2008/08/30 10:46:16 bouyer Exp $");
38 #endif
39 #endif /* not lint */
40 
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/file.h>
46 #include <sys/disk.h>
47 
48 #include <ufs/ufs/dinode.h>
49 #include <ufs/ufs/dir.h>
50 #include <ufs/ufs/ufs_bswap.h>
51 #include <ufs/ffs/fs.h>
52 #include <ufs/ffs/ffs_extern.h>
53 
54 #include <ctype.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 
61 #include "fsck.h"
62 #include "extern.h"
63 #include "fsutil.h"
64 #include "partutil.h"
65 #include "exitvalues.h"
66 
67 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
68 
69 static void badsb(int, const char *);
70 static int calcsb(const char *, int, struct fs *);
71 static int readsb(int);
72 static int readappleufs(void);
73 
74 int16_t sblkpostbl[256];
75 
76 /*
77  * Read in a superblock finding an alternate if necessary.
78  * Return 1 if successful, 0 if unsuccessful, -1 if filesystem
79  * is already clean (preen mode only).
80  */
81 int
82 setup(const char *dev, const char *origdev)
83 {
84 	long cg, size, asked, i, j;
85 	long bmapsize;
86 	struct disk_geom geo;
87 	struct dkwedge_info dkw;
88 	off_t sizepb;
89 	struct stat statb;
90 	struct fs proto;
91 	int doskipclean;
92 	u_int64_t maxfilesize;
93 	struct csum *ccsp;
94 	int fd;
95 
96 	havesb = 0;
97 	fswritefd = -1;
98 	doskipclean = skipclean;
99 	if (stat(dev, &statb) < 0) {
100 		printf("Can't stat %s: %s\n", dev, strerror(errno));
101 		return (0);
102 	}
103 	if (!forceimage && !S_ISCHR(statb.st_mode)) {
104 		pfatal("%s is not a character device", dev);
105 		if (reply("CONTINUE") == 0)
106 			return (0);
107 	}
108 	if ((fsreadfd = open(dev, O_RDONLY)) < 0) {
109 		printf("Can't open %s: %s\n", dev, strerror(errno));
110 		return (0);
111 	}
112 	if (nflag || (fswritefd = open(dev, O_WRONLY)) < 0) {
113 		fswritefd = -1;
114 		if (preen)
115 			pfatal("NO WRITE ACCESS");
116 		printf("** %s (NO WRITE)\n", dev);
117 		quiet = 0;
118 	} else
119 		if (!preen && !quiet)
120 			printf("** %s\n", dev);
121 	fsmodified = 0;
122 	lfdir = 0;
123 	initbarea(&sblk);
124 	initbarea(&asblk);
125 	sblk.b_un.b_buf = malloc(SBLOCKSIZE);
126 	sblock = malloc(SBLOCKSIZE);
127 	asblk.b_un.b_buf = malloc(SBLOCKSIZE);
128 	altsblock = malloc(SBLOCKSIZE);
129 	if (sblk.b_un.b_buf == NULL || asblk.b_un.b_buf == NULL ||
130 		sblock == NULL || altsblock == NULL)
131 		errexit("Cannot allocate space for superblock");
132 	if (strcmp(dev, origdev) && !forceimage) {
133 		/*
134 		 * dev isn't the original fs (for example it's a snapshot)
135 		 * do getdiskinfo on the original device
136 		 */
137 		 fd = open(origdev, O_RDONLY);
138 		 if (fd < 0) {
139 			warn("Can't open %s", origdev);
140 			return (0);
141 		}
142 	} else {
143 		fd = fsreadfd;
144 	}
145 	if (!forceimage && getdiskinfo(origdev, fd, NULL, &geo, &dkw) != -1)
146 		dev_bsize = secsize = geo.dg_secsize;
147 	else
148 		dev_bsize = secsize = DEV_BSIZE;
149 	/*
150 	 * Read in the superblock, looking for alternates if necessary
151 	 */
152 	if (readsb(1) == 0) {
153 		if (bflag || preen || forceimage ||
154 		    calcsb(dev, fsreadfd, &proto) == 0)
155 			return(0);
156 		if (reply("LOOK FOR ALTERNATE SUPERBLOCKS") == 0)
157 			return (0);
158 		for (cg = 0; cg < proto.fs_ncg; cg++) {
159 			bflag = fsbtodb(&proto, cgsblock(&proto, cg));
160 			if (readsb(0) != 0)
161 				break;
162 		}
163 		if (cg >= proto.fs_ncg) {
164 			printf("%s %s\n%s %s\n%s %s\n",
165 				"SEARCH FOR ALTERNATE SUPER-BLOCK",
166 				"FAILED. YOU MUST USE THE",
167 				"-b OPTION TO fsck_ffs TO SPECIFY THE",
168 				"LOCATION OF AN ALTERNATE",
169 				"SUPER-BLOCK TO SUPPLY NEEDED",
170 				"INFORMATION; SEE fsck_ffs(8).");
171 			return(0);
172 		}
173 		doskipclean = 0;
174 		pwarn("USING ALTERNATE SUPERBLOCK AT %d\n", bflag);
175 	}
176 	if (sblock->fs_flags & FS_DOWAPBL) {
177 		if (preen) {
178 			if (!quiet)
179 				pwarn("file system is journaled; not checking\n");
180 			return (-1);
181 		}
182 		if (!quiet)
183 			pwarn("** File system is journaled; replaying journal\n");
184 		replay_wapbl();
185 		doskipclean = 0;
186 		sblock->fs_flags &= ~FS_DOWAPBL;
187 		sbdirty();
188 		/* Although we may have updated the superblock from the
189 		 * journal, we are still going to do a full check, so we
190 		 * don't bother to re-read the superblock from the journal.
191 		 * XXX, instead we could re-read the superblock and then not
192 		 * force doskipclean = 0
193 		 */
194 	}
195 	if (debug)
196 		printf("clean = %d\n", sblock->fs_clean);
197 	if (doswap)
198 		doskipclean = 0;
199 	if (sblock->fs_clean & FS_ISCLEAN) {
200 		if (doskipclean) {
201 			if (!quiet)
202 				pwarn("%sile system is clean; not checking\n",
203 				    preen ? "f" : "** F");
204 			return (-1);
205 		}
206 		if (!preen && !doswap)
207 			pwarn("** File system is already clean\n");
208 	}
209 	maxfsblock = sblock->fs_size;
210 	maxino = sblock->fs_ncg * sblock->fs_ipg;
211 	sizepb = sblock->fs_bsize;
212 	maxfilesize = sblock->fs_bsize * NDADDR - 1;
213 	for (i = 0; i < NIADDR; i++) {
214 		sizepb *= NINDIR(sblock);
215 		maxfilesize += sizepb;
216 	}
217 	if ((!is_ufs2 && cvtlevel >= 4) &&
218 			(sblock->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
219 		if (preen)
220 			pwarn("CONVERTING TO NEW SUPERBLOCK LAYOUT\n");
221 		else if (!reply("CONVERT TO NEW SUPERBLOCK LAYOUT"))
222 			return(0);
223 		sblock->fs_old_flags |= FS_FLAGS_UPDATED;
224 		/* Disable the postbl tables */
225 		sblock->fs_old_cpc = 0;
226 		sblock->fs_old_nrpos = 1;
227 		sblock->fs_old_trackskew = 0;
228 		/* The other fields have already been updated by
229 		 * sb_oldfscompat_read
230 		 */
231 		sbdirty();
232 	}
233 	if (!is_ufs2 && cvtlevel == 3 &&
234 	    (sblock->fs_old_flags & FS_FLAGS_UPDATED)) {
235 		if (preen)
236 			pwarn("DOWNGRADING TO OLD SUPERBLOCK LAYOUT\n");
237 		else if (!reply("DOWNGRADE TO OLD SUPERBLOCK LAYOUT"))
238 			return(0);
239 		sblock->fs_old_flags &= ~FS_FLAGS_UPDATED;
240 		sb_oldfscompat_write(sblock, sblock);
241 		sblock->fs_old_flags &= ~FS_FLAGS_UPDATED; /* just in case */
242 		/* Leave postbl tables disabled, but blank its superblock region anyway */
243 		sblock->fs_old_postblformat = FS_DYNAMICPOSTBLFMT;
244 		sblock->fs_old_cpc = 0;
245 		sblock->fs_old_nrpos = 1;
246 		sblock->fs_old_trackskew = 0;
247 		memset(&sblock->fs_old_postbl_start, 0xff, 256);
248 		sb_oldfscompat_read(sblock, &sblocksave);
249 		sbdirty();
250 	}
251 	/*
252 	 * Check and potentially fix certain fields in the super block.
253 	 */
254 	if (sblock->fs_flags & ~(FS_KNOWN_FLAGS)) {
255 		pfatal("UNKNOWN FLAGS=0x%08x IN SUPERBLOCK", sblock->fs_flags);
256 		if (reply("CLEAR") == 1) {
257 			sblock->fs_flags &= FS_KNOWN_FLAGS;
258 			sbdirty();
259 		}
260 	}
261 	if (sblock->fs_optim != FS_OPTTIME && sblock->fs_optim != FS_OPTSPACE) {
262 		pfatal("UNDEFINED OPTIMIZATION IN SUPERBLOCK");
263 		if (reply("SET TO DEFAULT") == 1) {
264 			sblock->fs_optim = FS_OPTTIME;
265 			sbdirty();
266 		}
267 	}
268 	if ((sblock->fs_minfree < 0 || sblock->fs_minfree > 99)) {
269 		pfatal("IMPOSSIBLE MINFREE=%d IN SUPERBLOCK",
270 			sblock->fs_minfree);
271 		if (reply("SET TO DEFAULT") == 1) {
272 			sblock->fs_minfree = 10;
273 			sbdirty();
274 		}
275 	}
276 	if (!is_ufs2 && sblock->fs_old_postblformat != FS_42POSTBLFMT &&
277 	    (sblock->fs_old_interleave < 1 ||
278 	    sblock->fs_old_interleave > sblock->fs_old_nsect)) {
279 		pwarn("IMPOSSIBLE INTERLEAVE=%d IN SUPERBLOCK",
280 			sblock->fs_old_interleave);
281 		sblock->fs_old_interleave = 1;
282 		if (preen)
283 			printf(" (FIXED)\n");
284 		if (preen || reply("SET TO DEFAULT") == 1) {
285 			sbdirty();
286 			dirty(&asblk);
287 		}
288 	}
289 	if (!is_ufs2 && sblock->fs_old_postblformat != FS_42POSTBLFMT &&
290 	    (sblock->fs_old_npsect < sblock->fs_old_nsect ||
291 	    sblock->fs_old_npsect > sblock->fs_old_nsect*2)) {
292 		pwarn("IMPOSSIBLE NPSECT=%d IN SUPERBLOCK",
293 			sblock->fs_old_npsect);
294 		sblock->fs_old_npsect = sblock->fs_old_nsect;
295 		if (preen)
296 			printf(" (FIXED)\n");
297 		if (preen || reply("SET TO DEFAULT") == 1) {
298 			sbdirty();
299 			dirty(&asblk);
300 		}
301 	}
302 	if (sblock->fs_bmask != ~(sblock->fs_bsize - 1)) {
303 		pwarn("INCORRECT BMASK=0x%x IN SUPERBLOCK",
304 			sblock->fs_bmask);
305 		sblock->fs_bmask = ~(sblock->fs_bsize - 1);
306 		if (preen)
307 			printf(" (FIXED)\n");
308 		if (preen || reply("FIX") == 1) {
309 			sbdirty();
310 			dirty(&asblk);
311 		}
312 	}
313 	if (sblock->fs_fmask != ~(sblock->fs_fsize - 1)) {
314 		pwarn("INCORRECT FMASK=0x%x IN SUPERBLOCK",
315 			sblock->fs_fmask);
316 		sblock->fs_fmask = ~(sblock->fs_fsize - 1);
317 		if (preen)
318 			printf(" (FIXED)\n");
319 		if (preen || reply("FIX") == 1) {
320 			sbdirty();
321 			dirty(&asblk);
322 		}
323 	}
324 	if (is_ufs2 || sblock->fs_old_inodefmt >= FS_44INODEFMT) {
325 		if (sblock->fs_maxfilesize != maxfilesize) {
326 			pwarn("INCORRECT MAXFILESIZE=%lld IN SUPERBLOCK",
327 			    (unsigned long long)sblock->fs_maxfilesize);
328 			sblock->fs_maxfilesize = maxfilesize;
329 			if (preen)
330 				printf(" (FIXED)\n");
331 			if (preen || reply("FIX") == 1) {
332 				sbdirty();
333 				dirty(&asblk);
334 			}
335 		}
336 		if ((is_ufs2 && sblock->fs_maxsymlinklen != MAXSYMLINKLEN_UFS2)
337 		    ||
338 		   (!is_ufs2 && sblock->fs_maxsymlinklen != MAXSYMLINKLEN_UFS1))
339 		    {
340 			pwarn("INCORRECT MAXSYMLINKLEN=%d IN SUPERBLOCK",
341 				sblock->fs_maxsymlinklen);
342 			sblock->fs_maxsymlinklen = is_ufs2 ?
343 			    MAXSYMLINKLEN_UFS2 : MAXSYMLINKLEN_UFS1;
344 			if (preen)
345 				printf(" (FIXED)\n");
346 			if (preen || reply("FIX") == 1) {
347 				sbdirty();
348 				dirty(&asblk);
349 			}
350 		}
351 		if (sblock->fs_qbmask != ~sblock->fs_bmask) {
352 			pwarn("INCORRECT QBMASK=%#llx IN SUPERBLOCK",
353 			    (unsigned long long)sblock->fs_qbmask);
354 			sblock->fs_qbmask = ~sblock->fs_bmask;
355 			if (preen)
356 				printf(" (FIXED)\n");
357 			if (preen || reply("FIX") == 1) {
358 				sbdirty();
359 				dirty(&asblk);
360 			}
361 		}
362 		if (sblock->fs_qfmask != ~sblock->fs_fmask) {
363 			pwarn("INCORRECT QFMASK=%#llx IN SUPERBLOCK",
364 			    (unsigned long long)sblock->fs_qfmask);
365 			sblock->fs_qfmask = ~sblock->fs_fmask;
366 			if (preen)
367 				printf(" (FIXED)\n");
368 			if (preen || reply("FIX") == 1) {
369 				sbdirty();
370 				dirty(&asblk);
371 			}
372 		}
373 		newinofmt = 1;
374 	} else {
375 		sblock->fs_qbmask = ~sblock->fs_bmask;
376 		sblock->fs_qfmask = ~sblock->fs_fmask;
377 		newinofmt = 0;
378 	}
379 	/*
380 	 * Convert to new inode format.
381 	 */
382 	if (!is_ufs2 && cvtlevel >= 2 &&
383 	    sblock->fs_old_inodefmt < FS_44INODEFMT) {
384 		if (preen)
385 			pwarn("CONVERTING TO NEW INODE FORMAT\n");
386 		else if (!reply("CONVERT TO NEW INODE FORMAT"))
387 			return(0);
388 		doinglevel2++;
389 		sblock->fs_old_inodefmt = FS_44INODEFMT;
390 		sblock->fs_maxfilesize = maxfilesize;
391 		sblock->fs_maxsymlinklen = MAXSYMLINKLEN_UFS1;
392 		sblock->fs_qbmask = ~sblock->fs_bmask;
393 		sblock->fs_qfmask = ~sblock->fs_fmask;
394 		sbdirty();
395 		dirty(&asblk);
396 	}
397 	/*
398 	 * Convert to new cylinder group format.
399 	 */
400 	if (!is_ufs2 && cvtlevel >= 1 &&
401 	    sblock->fs_old_postblformat == FS_42POSTBLFMT) {
402 		if (preen)
403 			pwarn("CONVERTING TO NEW CYLINDER GROUP FORMAT\n");
404 		else if (!reply("CONVERT TO NEW CYLINDER GROUP FORMAT"))
405 			return(0);
406 		doinglevel1++;
407 		sblock->fs_old_postblformat = FS_DYNAMICPOSTBLFMT;
408 		sblock->fs_old_nrpos = 8;
409 		sblock->fs_old_postbloff =
410 		    (char *)(&sblock->fs_old_postbl_start) -
411 		    (char *)(&sblock->fs_firstfield);
412 		sblock->fs_old_rotbloff =
413 				(char *)(&sblock->fs_magic+1) -
414 				(char *)(&sblock->fs_firstfield);
415 		sblock->fs_cgsize =
416 			fragroundup(sblock, CGSIZE(sblock));
417 		sbdirty();
418 		dirty(&asblk);
419 	}
420 	if (asblk.b_dirty && !bflag) {
421 		memmove(sblk.b_un.b_fs, sblock, SBLOCKSIZE);
422 		sb_oldfscompat_write(sblk.b_un.b_fs, sblocksave);
423 		if (needswap)
424 			ffs_sb_swap(sblk.b_un.b_fs, sblk.b_un.b_fs);
425 		memmove(asblk.b_un.b_fs, sblk.b_un.b_fs, (size_t)sblock->fs_sbsize);
426 		flush(fswritefd, &asblk);
427 	}
428 	/*
429 	 * read in the summary info.
430 	 */
431 	asked = 0;
432 	sblock->fs_csp = (struct csum *)calloc(1, sblock->fs_cssize);
433 	if (sblock->fs_csp == NULL) {
434 		pwarn("cannot alloc %u bytes for summary info\n",
435 		    sblock->fs_cssize);
436 		goto badsblabel;
437 	}
438 	for (i = 0, j = 0; i < sblock->fs_cssize; i += sblock->fs_bsize, j++) {
439 		size = sblock->fs_cssize - i < sblock->fs_bsize ?
440 		    sblock->fs_cssize - i : sblock->fs_bsize;
441 		ccsp = (struct csum *)((char *)sblock->fs_csp + i);
442 		if (bread(fsreadfd, (char *)ccsp,
443 		    fsbtodb(sblock, sblock->fs_csaddr + j * sblock->fs_frag),
444 		    size) != 0 && !asked) {
445 			pfatal("BAD SUMMARY INFORMATION");
446 			if (reply("CONTINUE") == 0) {
447 				markclean = 0;
448 				exit(FSCK_EXIT_CHECK_FAILED);
449 			}
450 			asked++;
451 		}
452 		if (doswap) {
453 			ffs_csum_swap(ccsp, ccsp, size);
454 			bwrite(fswritefd, (char *)ccsp,
455 			    fsbtodb(sblock,
456 				sblock->fs_csaddr + j * sblock->fs_frag),
457 			    size);
458 		}
459 		if (needswap)
460 			ffs_csum_swap(ccsp, ccsp, size);
461 	}
462 	/*
463 	 * allocate and initialize the necessary maps
464 	 */
465 	bmapsize = roundup(howmany(maxfsblock, NBBY), sizeof(int16_t));
466 	blockmap = calloc((unsigned)bmapsize, sizeof (char));
467 	if (blockmap == NULL) {
468 		pwarn("cannot alloc %u bytes for blockmap\n",
469 		    (unsigned)bmapsize);
470 		goto badsblabel;
471 	}
472 	inostathead = calloc((unsigned)(sblock->fs_ncg),
473 	    sizeof(struct inostatlist));
474 	if (inostathead == NULL) {
475 		pwarn("cannot alloc %u bytes for inostathead\n",
476 		    (unsigned)(sizeof(struct inostatlist) * (sblock->fs_ncg)));
477 		goto badsblabel;
478 	}
479 	/*
480 	 * cs_ndir may be inaccurate, particularly if we're using the -b
481 	 * option, so set a minimum to prevent bogus subdirectory reconnects
482 	 * and really inefficient directory scans.
483 	 * Also set a maximum in case the value is too large.
484 	 */
485 	numdirs = sblock->fs_cstotal.cs_ndir;
486 	if (numdirs < 1024)
487 		numdirs = 1024;
488 	if (numdirs > maxino + 1)
489 		numdirs = maxino + 1;
490 	dirhash = numdirs;
491 	inplast = 0;
492 	listmax = numdirs + 10;
493 	inpsort = (struct inoinfo **)calloc((unsigned)listmax,
494 	    sizeof(struct inoinfo *));
495 	inphead = (struct inoinfo **)calloc((unsigned)numdirs,
496 	    sizeof(struct inoinfo *));
497 	if (inpsort == NULL || inphead == NULL) {
498 		pwarn("cannot alloc %u bytes for inphead\n",
499 		    (unsigned)(numdirs * sizeof(struct inoinfo *)));
500 		goto badsblabel;
501 	}
502 	cgrp = malloc(sblock->fs_cgsize);
503 	if (cgrp == NULL) {
504 		pwarn("cannot alloc %u bytes for cylinder group\n",
505 		    sblock->fs_cgsize);
506 		goto badsblabel;
507 	}
508 	bufinit();
509 	if (sblock->fs_flags & FS_DOSOFTDEP)
510 		usedsoftdep = 1;
511 	else
512 		usedsoftdep = 0;
513 
514 	if (!forceimage && dkw.dkw_parent[0])
515 		if (strcmp(dkw.dkw_ptype, DKW_PTYPE_APPLEUFS) == 0)
516 			isappleufs = 1;
517 
518 	if (readappleufs())
519 		isappleufs = 1;
520 
521 	dirblksiz = DIRBLKSIZ;
522 	if (isappleufs)
523 		dirblksiz = APPLEUFS_DIRBLKSIZ;
524 
525 	if (debug)
526 		printf("isappleufs = %d, dirblksiz = %d\n", isappleufs, dirblksiz);
527 
528 	return (1);
529 
530 badsblabel:
531 	markclean=0;
532 	ckfini();
533 	return (0);
534 }
535 
536 static int
537 readappleufs(void)
538 {
539 	daddr_t label = APPLEUFS_LABEL_OFFSET / dev_bsize;
540 	struct appleufslabel *appleufs;
541 	int i;
542 
543 	/* XXX do we have to deal with APPLEUFS_LABEL_OFFSET not
544 	 * being block aligned (CD's?)
545 	 */
546 	if (bread(fsreadfd, (char *)appleufsblk.b_un.b_fs, label,
547 	    (long)APPLEUFS_LABEL_SIZE) != 0)
548 		return 0;
549 	appleufsblk.b_bno = label;
550 	appleufsblk.b_size = APPLEUFS_LABEL_SIZE;
551 
552 	appleufs = appleufsblk.b_un.b_appleufs;
553 
554 	if (ntohl(appleufs->ul_magic) != APPLEUFS_LABEL_MAGIC) {
555 		if (!isappleufs) {
556 			return 0;
557 		} else {
558 			pfatal("MISSING APPLEUFS VOLUME LABEL\n");
559 			if (reply("FIX") == 0) {
560 				return 1;
561 			}
562 			ffs_appleufs_set(appleufs, NULL, -1, 0);
563 			appleufsdirty();
564 		}
565 	}
566 
567 	if (ntohl(appleufs->ul_version) != APPLEUFS_LABEL_VERSION) {
568 		pwarn("INCORRECT APPLE UFS VERSION NUMBER (%d should be %d)",
569 			ntohl(appleufs->ul_version),APPLEUFS_LABEL_VERSION);
570 		if (preen) {
571 			printf(" (CORRECTED)\n");
572 		}
573 		if (preen || reply("CORRECT")) {
574 			appleufs->ul_version = htonl(APPLEUFS_LABEL_VERSION);
575 			appleufsdirty();
576 		}
577 	}
578 
579 	if (ntohs(appleufs->ul_namelen) > APPLEUFS_MAX_LABEL_NAME) {
580 		pwarn("APPLE UFS LABEL NAME TOO LONG");
581 		if (preen) {
582 			printf(" (TRUNCATED)\n");
583 		}
584 		if (preen || reply("TRUNCATE")) {
585 			appleufs->ul_namelen = htons(APPLEUFS_MAX_LABEL_NAME);
586 			appleufsdirty();
587 		}
588 	}
589 
590 	if (ntohs(appleufs->ul_namelen) == 0) {
591 		pwarn("MISSING APPLE UFS LABEL NAME");
592 		if (preen) {
593 			printf(" (FIXED)\n");
594 		}
595 		if (preen || reply("FIX")) {
596 			ffs_appleufs_set(appleufs, NULL, -1, 0);
597 			appleufsdirty();
598 		}
599 	}
600 
601 	/* Scan name for first illegal character */
602 	for (i=0;i<ntohs(appleufs->ul_namelen);i++) {
603 		if ((appleufs->ul_name[i] == '\0') ||
604 			(appleufs->ul_name[i] == ':') ||
605 			(appleufs->ul_name[i] == '/')) {
606 			pwarn("APPLE UFS LABEL NAME CONTAINS ILLEGAL CHARACTER");
607 			if (preen) {
608 				printf(" (TRUNCATED)\n");
609 			}
610 			if (preen || reply("TRUNCATE")) {
611 				appleufs->ul_namelen = i+1;
612 				appleufsdirty();
613 			}
614 			break;
615 		}
616 	}
617 
618 	/* Check the checksum last, because if anything else was wrong,
619 	 * then the checksum gets reset anyway.
620 	 */
621 	appleufs->ul_checksum = 0;
622 	appleufs->ul_checksum = ffs_appleufs_cksum(appleufs);
623 	if (appleufsblk.b_un.b_appleufs->ul_checksum != appleufs->ul_checksum) {
624 		pwarn("INVALID APPLE UFS CHECKSUM (%#04x should be %#04x)",
625 			appleufsblk.b_un.b_appleufs->ul_checksum, appleufs->ul_checksum);
626 		if (preen) {
627 			printf(" (CORRECTED)\n");
628 		}
629 		if (preen || reply("CORRECT")) {
630 			appleufsdirty();
631 		} else {
632 			/* put the incorrect checksum back in place */
633 			appleufs->ul_checksum = appleufsblk.b_un.b_appleufs->ul_checksum;
634 		}
635 	}
636 	return 1;
637 }
638 
639 /*
640  * Detect byte order. Return 0 if valid magic found, -1 otherwise.
641  */
642 static int
643 detect_byteorder(struct fs *fs, int sblockoff)
644 {
645 	if (sblockoff == SBLOCK_UFS2 && (fs->fs_magic == FS_UFS1_MAGIC ||
646 	    fs->fs_magic == bswap32(FS_UFS1_MAGIC)))
647 		/* Likely to be the first alternate of a fs with 64k blocks */
648 		return -1;
649 	if (fs->fs_magic == FS_UFS1_MAGIC || fs->fs_magic == FS_UFS2_MAGIC) {
650 		if (endian == 0 || BYTE_ORDER == endian) {
651 			needswap = 0;
652 			doswap = do_blkswap = do_dirswap = 0;
653 		} else {
654 			needswap = 1;
655 			doswap = do_blkswap = do_dirswap = 1;
656 		}
657 		return 0;
658 	} else if (fs->fs_magic == bswap32(FS_UFS1_MAGIC) ||
659 		   fs->fs_magic == bswap32(FS_UFS2_MAGIC)) {
660 		if (endian == 0 || BYTE_ORDER != endian) {
661 			needswap = 1;
662 			doswap = do_blkswap = do_dirswap = 0;
663 		} else {
664 			needswap = 0;
665 			doswap = do_blkswap = do_dirswap = 1;
666 		}
667 		return 0;
668 	}
669 	return -1;
670 }
671 
672 /*
673  * Possible superblock locations ordered from most to least likely.
674  */
675 static off_t sblock_try[] = SBLOCKSEARCH;
676 
677 /*
678  * Read in the super block and its summary info.
679  */
680 static int
681 readsb(int listerr)
682 {
683 	daddr_t super = 0;
684 	struct fs *fs;
685 	int i;
686 
687 	if (bflag) {
688 		super = bflag;
689 		if (bread(fsreadfd, (char *)sblk.b_un.b_fs, super,
690 		    (long)SBLOCKSIZE) != 0)
691 			return (0);
692 		fs = sblk.b_un.b_fs;
693 		if (detect_byteorder(fs, -1) < 0) {
694 			badsb(listerr, "MAGIC NUMBER WRONG");
695 			return (0);
696 		}
697 	} else {
698 		for (i = 0; sblock_try[i] != -1; i++) {
699 			super = sblock_try[i] / dev_bsize;
700 			if (bread(fsreadfd, (char *)sblk.b_un.b_fs,
701 			    super, (long)SBLOCKSIZE) != 0)
702 				continue;
703 			fs = sblk.b_un.b_fs;
704 			if (detect_byteorder(fs, sblock_try[i]) == 0)
705 				break;
706 		}
707 		if (sblock_try[i] == -1) {
708 			badsb(listerr, "CAN'T FIND SUPERBLOCK");
709 			return (0);
710 		}
711 	}
712 	if (doswap) {
713 		if (preen)
714 			errx(FSCK_EXIT_USAGE,
715 			    "Incompatible options -B and -p");
716 		if (nflag)
717 			errx(FSCK_EXIT_USAGE,
718 			    "Incompatible options -B and -n");
719 		if (endian == LITTLE_ENDIAN) {
720 			if (!reply("CONVERT TO LITTLE ENDIAN"))
721 				return 0;
722 		} else if (endian == BIG_ENDIAN) {
723 			if (!reply("CONVERT TO BIG ENDIAN"))
724 				return 0;
725 		} else
726 			pfatal("INTERNAL ERROR: unknown endian");
727 	}
728 	if (needswap)
729 		pwarn("** Swapped byte order\n");
730 	/* swap SB byte order if asked */
731 	if (doswap)
732 		ffs_sb_swap(sblk.b_un.b_fs, sblk.b_un.b_fs);
733 
734 	memmove(sblock, sblk.b_un.b_fs, SBLOCKSIZE);
735 	if (needswap)
736 		ffs_sb_swap(sblk.b_un.b_fs, sblock);
737 
738 	is_ufs2 = sblock->fs_magic == FS_UFS2_MAGIC;
739 
740 	/*
741 	 * run a few consistency checks of the super block
742 	 */
743 	if (sblock->fs_sbsize > SBLOCKSIZE)
744 		{ badsb(listerr, "SIZE PREPOSTEROUSLY LARGE"); return (0); }
745 	/*
746 	 * Compute block size that the filesystem is based on,
747 	 * according to fsbtodb, and adjust superblock block number
748 	 * so we can tell if this is an alternate later.
749 	 */
750 	super *= dev_bsize;
751 	dev_bsize = sblock->fs_fsize / fsbtodb(sblock, 1);
752 	sblk.b_bno = super / dev_bsize;
753 	sblk.b_size = SBLOCKSIZE;
754 	if (bflag)
755 		goto out;
756 	/*
757 	 * Set all possible fields that could differ, then do check
758 	 * of whole super block against an alternate super block->
759 	 * When an alternate super-block is specified this check is skipped.
760 	 */
761 	getblk(&asblk, cgsblock(sblock, sblock->fs_ncg - 1), sblock->fs_sbsize);
762 	if (asblk.b_errs)
763 		return (0);
764 	/* swap SB byte order if asked */
765 	if (doswap)
766 		ffs_sb_swap(asblk.b_un.b_fs, asblk.b_un.b_fs);
767 
768 	memmove(altsblock, asblk.b_un.b_fs, sblock->fs_sbsize);
769 	if (needswap)
770 		ffs_sb_swap(asblk.b_un.b_fs, altsblock);
771 	if (cmpsblks(sblock, altsblock)) {
772 		if (debug) {
773 			uint32_t *nlp, *olp, *endlp;
774 
775 			printf("superblock mismatches\n");
776 			nlp = (uint32_t *)altsblock;
777 			olp = (uint32_t *)sblock;
778 			endlp = olp + (sblock->fs_sbsize / sizeof *olp);
779 			for ( ; olp < endlp; olp++, nlp++) {
780 				if (*olp == *nlp)
781 					continue;
782 				printf("offset %#x, original 0x%08x, alternate "
783 				       "0x%08x\n",
784 				    (int)((uint8_t *)olp-(uint8_t *)sblock),
785 				    *olp, *nlp);
786 			}
787 		}
788 		badsb(listerr,
789 		"VALUES IN SUPER BLOCK DISAGREE WITH THOSE IN FIRST ALTERNATE");
790 /*
791 		return (0);
792 */
793 	}
794 out:
795 
796 	sb_oldfscompat_read(sblock, &sblocksave);
797 
798 	/* Now we know the SB is valid, we can write it back if needed */
799 	if (doswap) {
800 		sbdirty();
801 		dirty(&asblk);
802 	}
803 	havesb = 1;
804 	return (1);
805 }
806 
807 int
808 cmpsblks(const struct fs *sb, struct fs *asb)
809 {
810 	if (!is_ufs2 && ((sb->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
811 		if (sb->fs_old_postblformat < FS_DYNAMICPOSTBLFMT)
812 			return cmpsblks42(sb, asb);
813 		else
814 			return cmpsblks44(sb, asb);
815 	}
816 	if (asb->fs_sblkno != sb->fs_sblkno ||
817 	    asb->fs_cblkno != sb->fs_cblkno ||
818 	    asb->fs_iblkno != sb->fs_iblkno ||
819 	    asb->fs_dblkno != sb->fs_dblkno ||
820 	    asb->fs_ncg != sb->fs_ncg ||
821 	    asb->fs_bsize != sb->fs_bsize ||
822 	    asb->fs_fsize != sb->fs_fsize ||
823 	    asb->fs_frag != sb->fs_frag ||
824 	    asb->fs_bmask != sb->fs_bmask ||
825 	    asb->fs_fmask != sb->fs_fmask ||
826 	    asb->fs_bshift != sb->fs_bshift ||
827 	    asb->fs_fshift != sb->fs_fshift ||
828 	    asb->fs_fragshift != sb->fs_fragshift ||
829 	    asb->fs_fsbtodb != sb->fs_fsbtodb ||
830 	    asb->fs_sbsize != sb->fs_sbsize ||
831 	    asb->fs_nindir != sb->fs_nindir ||
832 	    asb->fs_inopb != sb->fs_inopb ||
833 	    asb->fs_cssize != sb->fs_cssize ||
834 	    asb->fs_ipg != sb->fs_ipg ||
835 	    asb->fs_fpg != sb->fs_fpg ||
836 	    asb->fs_magic != sb->fs_magic)
837 		return 1;
838 	return 0;
839 }
840 
841 /* BSD 4.2 performed the following superblock comparison
842  * It should correspond to FS_42POSTBLFMT
843  * (although note that in 4.2, the fs_old_postblformat
844  * field didn't exist and the corresponding bits are
845  * located near the end of the postbl itself, where they
846  * are not likely to be used.)
847  */
848 int
849 cmpsblks42(const struct fs *sb, struct fs *asb)
850 {
851 	asb->fs_firstfield = sb->fs_firstfield; /* fs_link */
852 	asb->fs_unused_1 = sb->fs_unused_1; /* fs_rlink */
853 	asb->fs_old_time = sb->fs_old_time; /* fs_time */
854 	asb->fs_old_cstotal = sb->fs_old_cstotal; /* fs_cstotal */
855 	asb->fs_cgrotor = sb->fs_cgrotor;
856 	asb->fs_fmod = sb->fs_fmod;
857 	asb->fs_clean = sb->fs_clean;
858 	asb->fs_ronly = sb->fs_ronly;
859 	asb->fs_old_flags = sb->fs_old_flags;
860 	asb->fs_maxcontig = sb->fs_maxcontig;
861 	asb->fs_minfree = sb->fs_minfree;
862 	asb->fs_old_rotdelay = sb->fs_old_rotdelay;
863 	asb->fs_maxbpg = sb->fs_maxbpg;
864 
865 	/* The former fs_csp, totaling 128 bytes  */
866 	memmove(asb->fs_ocsp, sb->fs_ocsp, sizeof sb->fs_ocsp);
867 	asb->fs_contigdirs = sb->fs_contigdirs;
868 	asb->fs_csp = sb->fs_csp;
869 	asb->fs_maxcluster = sb->fs_maxcluster;
870 	asb->fs_active = sb->fs_active;
871 
872 	/* The former fs_fsmnt, totaling 512 bytes */
873 	memmove(asb->fs_fsmnt, sb->fs_fsmnt, sizeof sb->fs_fsmnt);
874 	memmove(asb->fs_volname, sb->fs_volname, sizeof sb->fs_volname);
875 
876 	return memcmp(sb, asb, sb->fs_sbsize);
877 }
878 
879 /* BSD 4.4 performed the following superblock comparison
880  * This was used in NetBSD through 1.6.1
881  *
882  * Note that this implementation is destructive to asb.
883  */
884 int
885 cmpsblks44(const struct fs *sb, struct fs *asb)
886 {
887 	/*
888 	 * "Copy fields which we don't care if they're different in the
889 	 * alternate superblocks, as they're either likely to be
890 	 * different because they're per-cylinder-group specific, or
891 	 * because they're transient details which are only maintained
892 	 * in the primary superblock."
893 	 */
894 	asb->fs_firstfield = sb->fs_firstfield;
895 	asb->fs_unused_1 = sb->fs_unused_1;
896 	asb->fs_old_time = sb->fs_old_time;
897 	asb->fs_old_cstotal = sb->fs_old_cstotal;
898 	asb->fs_cgrotor = sb->fs_cgrotor;
899 	asb->fs_fmod = sb->fs_fmod;
900 	asb->fs_clean = sb->fs_clean;
901 	asb->fs_ronly = sb->fs_ronly;
902 	asb->fs_old_flags = sb->fs_old_flags;
903 	asb->fs_maxcontig = sb->fs_maxcontig;
904 	asb->fs_minfree = sb->fs_minfree;
905 	asb->fs_optim = sb->fs_optim;
906 	asb->fs_old_rotdelay = sb->fs_old_rotdelay;
907 	asb->fs_maxbpg = sb->fs_maxbpg;
908 
909 	/* The former fs_csp and fs_maxcluster, totaling 128 bytes */
910 	memmove(asb->fs_ocsp, sb->fs_ocsp, sizeof sb->fs_ocsp);
911 	asb->fs_contigdirs = sb->fs_contigdirs;
912 	asb->fs_csp = sb->fs_csp;
913 	asb->fs_maxcluster = sb->fs_maxcluster;
914 	asb->fs_active = sb->fs_active;
915 
916 	/* The former fs_fsmnt, totaling 512 bytes */
917 	memmove(asb->fs_fsmnt, sb->fs_fsmnt, sizeof sb->fs_fsmnt);
918 	memmove(asb->fs_volname, sb->fs_volname, sizeof sb->fs_volname);
919 
920 	/* The former fs_sparecon, totaling 200 bytes */
921 	memmove(asb->fs_snapinum,
922 		sb->fs_snapinum, sizeof sb->fs_snapinum);
923 	asb->fs_avgfilesize = sb->fs_avgfilesize;
924 	asb->fs_avgfpdir = sb->fs_avgfpdir;
925 	asb->fs_save_cgsize = sb->fs_save_cgsize;
926 	memmove(asb->fs_sparecon32,
927 		sb->fs_sparecon32, sizeof sb->fs_sparecon32);
928 	asb->fs_flags = sb->fs_flags;
929 
930 	/* Original comment:
931 	 * "The following should not have to be copied, but need to be."
932 	 */
933 	asb->fs_fsbtodb = sb->fs_fsbtodb;
934 	asb->fs_old_interleave = sb->fs_old_interleave;
935 	asb->fs_old_npsect = sb->fs_old_npsect;
936 	asb->fs_old_nrpos = sb->fs_old_nrpos;
937 	asb->fs_state = sb->fs_state;
938 	asb->fs_qbmask = sb->fs_qbmask;
939 	asb->fs_qfmask = sb->fs_qfmask;
940 	asb->fs_state = sb->fs_state;
941 	asb->fs_maxfilesize = sb->fs_maxfilesize;
942 
943 	/*
944 	 * "Compare the superblocks, effectively checking every other
945 	 * field to see if they differ."
946 	 */
947 	return memcmp(sb, asb, sb->fs_sbsize);
948 }
949 
950 
951 static void
952 badsb(int listerr, const char *s)
953 {
954 
955 	if (!listerr)
956 		return;
957 	if (preen)
958 		printf("%s: ", cdevname());
959 	pfatal("BAD SUPER BLOCK: %s\n", s);
960 }
961 
962 /*
963  * Calculate a prototype superblock based on information in the disk label.
964  * When done the cgsblock macro can be calculated and the fs_ncg field
965  * can be used. Do NOT attempt to use other macros without verifying that
966  * their needed information is available!
967  */
968 static int
969 calcsb(const char *dev, int devfd, struct fs *fs)
970 {
971 	struct dkwedge_info dkw;
972 	struct disk_geom geo;
973 	int i, nspf;
974 
975 	if (getdiskinfo(dev, fsreadfd, NULL, &geo, &dkw) == -1)
976 		pfatal("%s: CANNOT FIGURE OUT FILE SYSTEM PARTITION\n", dev);
977 	if (dkw.dkw_parent[0] == '\0') {
978 		pfatal("%s: CANNOT FIGURE OUT FILE SYSTEM PARTITION\n", dev);
979 		return (0);
980 	}
981 	if (strcmp(dkw.dkw_ptype, DKW_PTYPE_FFS) &&
982 	    strcmp(dkw.dkw_ptype, DKW_PTYPE_APPLEUFS)) {
983 		pfatal("%s: NOT LABELED AS A BSD FILE SYSTEM (%s)\n",
984 		    dev, dkw.dkw_ptype);
985 		return (0);
986 	}
987 	if (geo.dg_secsize == 0) {
988 		pfatal("%s: CANNOT FIGURE OUT SECTOR SIZE\n", dev);
989 		return 0;
990 	}
991 	if (geo.dg_secpercyl == 0) {
992 		pfatal("%s: CANNOT FIGURE OUT SECTORS PER CYLINDER\n", dev);
993 		return 0;
994 	}
995 	if (sblk.b_un.b_fs->fs_fsize == 0) {
996 		pfatal("%s: CANNOT FIGURE OUT FRAG BLOCK SIZE\n", dev);
997 		return 0;
998 	}
999 	if (sblk.b_un.b_fs->fs_fpg == 0) {
1000 		pfatal("%s: CANNOT FIGURE OUT FRAGS PER GROUP\n", dev);
1001 		return 0;
1002 	}
1003 	if (sblk.b_un.b_fs->fs_old_cpg == 0) {
1004 		pfatal("%s: CANNOT FIGURE OUT OLD CYLINDERS PER GROUP\n", dev);
1005 		return 0;
1006 	}
1007 	memcpy(fs, &sblk.b_un.b_fs, sizeof(struct fs));
1008 	nspf = fs->fs_fsize / geo.dg_secsize;
1009 	fs->fs_old_nspf = nspf;
1010 	for (fs->fs_fsbtodb = 0, i = nspf; i > 1; i >>= 1)
1011 		fs->fs_fsbtodb++;
1012 	dev_bsize = geo.dg_secsize;
1013 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1014 		fs->fs_ncg = howmany(fs->fs_size, fs->fs_fpg);
1015 	} else /* if (fs->fs_magic == FS_UFS1_MAGIC) */ {
1016 		fs->fs_old_cgmask = 0xffffffff;
1017 		for (i = geo.dg_ntracks; i > 1; i >>= 1)
1018 			fs->fs_old_cgmask <<= 1;
1019 		if (!POWEROF2(geo.dg_ntracks))
1020 			fs->fs_old_cgmask <<= 1;
1021 		fs->fs_old_cgoffset = roundup(
1022 			howmany(geo.dg_nsectors, nspf), fs->fs_frag);
1023 		fs->fs_fpg = (fs->fs_old_cpg * geo.dg_secpercyl) / nspf;
1024 		fs->fs_ncg = howmany(fs->fs_size / geo.dg_secpercyl,
1025 		    fs->fs_old_cpg);
1026 	}
1027 	return (1);
1028 }
1029