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