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