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