1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
5 * 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 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/param.h>
30#include <sys/disk.h>
31#include <sys/disklabel.h>
32#include <sys/mount.h>
33#include <sys/stat.h>
34
35#include <ufs/ufs/extattr.h>
36#include <ufs/ufs/quota.h>
37#include <ufs/ufs/ufsmount.h>
38#include <ufs/ufs/dinode.h>
39#include <ufs/ufs/dir.h>
40#include <ufs/ffs/fs.h>
41
42#include <assert.h>
43#include <err.h>
44#include <setjmp.h>
45#include <stdarg.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <stdint.h>
49#include <string.h>
50#include <strings.h>
51#include <sysexits.h>
52#include <time.h>
53
54#include "fsck.h"
55
56#define	DOTDOT_OFFSET	DIRECTSIZ(1)
57
58struct suj_seg {
59	TAILQ_ENTRY(suj_seg) ss_next;
60	struct jsegrec	ss_rec;
61	uint8_t		*ss_blk;
62};
63
64struct suj_rec {
65	TAILQ_ENTRY(suj_rec) sr_next;
66	union jrec	*sr_rec;
67};
68TAILQ_HEAD(srechd, suj_rec);
69
70struct suj_ino {
71	LIST_ENTRY(suj_ino)	si_next;
72	struct srechd		si_recs;
73	struct srechd		si_newrecs;
74	struct srechd		si_movs;
75	struct jtrncrec		*si_trunc;
76	ino_t			si_ino;
77	char			si_skipparent;
78	char			si_hasrecs;
79	char			si_blkadj;
80	char			si_linkadj;
81	int			si_mode;
82	nlink_t			si_nlinkadj;
83	nlink_t			si_nlink;
84	nlink_t			si_dotlinks;
85};
86LIST_HEAD(inohd, suj_ino);
87
88struct suj_blk {
89	LIST_ENTRY(suj_blk)	sb_next;
90	struct srechd		sb_recs;
91	ufs2_daddr_t		sb_blk;
92};
93LIST_HEAD(blkhd, suj_blk);
94
95struct suj_cg {
96	LIST_ENTRY(suj_cg)	sc_next;
97	struct blkhd		sc_blkhash[HASHSIZE];
98	struct inohd		sc_inohash[HASHSIZE];
99	struct ino_blk		*sc_lastiblk;
100	struct suj_ino		*sc_lastino;
101	struct suj_blk		*sc_lastblk;
102	struct bufarea		*sc_cgbp;
103	struct cg		*sc_cgp;
104	int			sc_cgx;
105};
106
107static LIST_HEAD(cghd, suj_cg) cghash[HASHSIZE];
108static struct suj_cg *lastcg;
109
110static TAILQ_HEAD(seghd, suj_seg) allsegs;
111static uint64_t oldseq;
112static struct fs *fs = NULL;
113static ino_t sujino;
114static char *joptype[JOP_NUMJOPTYPES] = JOP_NAMES;
115
116/*
117 * Summary statistics.
118 */
119static uint64_t freefrags;
120static uint64_t freeblocks;
121static uint64_t freeinos;
122static uint64_t freedir;
123static uint64_t jbytes;
124static uint64_t jrecs;
125
126static jmp_buf	jmpbuf;
127
128typedef void (*ino_visitor)(ino_t, ufs_lbn_t, ufs2_daddr_t, int);
129static void err_suj(const char *, ...) __dead2;
130static void ino_trunc(ino_t, off_t);
131static void ino_decr(ino_t);
132static void ino_adjust(struct suj_ino *);
133static void ino_build(struct suj_ino *);
134static int blk_isfree(ufs2_daddr_t);
135static void initsuj(void);
136
137static void *
138errmalloc(size_t n)
139{
140	void *a;
141
142	a = Malloc(n);
143	if (a == NULL)
144		err(EX_OSERR, "malloc(%zu)", n);
145	return (a);
146}
147
148/*
149 * When hit a fatal error in journalling check, print out
150 * the error and then offer to fallback to normal fsck.
151 */
152static void
153err_suj(const char * restrict fmt, ...)
154{
155	va_list ap;
156
157	if (preen)
158		(void)fprintf(stdout, "%s: ", cdevname);
159
160	va_start(ap, fmt);
161	(void)vfprintf(stdout, fmt, ap);
162	va_end(ap);
163
164	longjmp(jmpbuf, -1);
165}
166
167/*
168 * Lookup a cg by number in the hash so we can keep track of which cgs
169 * need stats rebuilt.
170 */
171static struct suj_cg *
172cg_lookup(int cgx)
173{
174	struct cghd *hd;
175	struct suj_cg *sc;
176	struct bufarea *cgbp;
177
178	if (cgx < 0 || cgx >= fs->fs_ncg)
179		err_suj("Bad cg number %d\n", cgx);
180	if (lastcg && lastcg->sc_cgx == cgx)
181		return (lastcg);
182	cgbp = cglookup(cgx);
183	if (!check_cgmagic(cgx, cgbp))
184		err_suj("UNABLE TO REBUILD CYLINDER GROUP %d", cgx);
185	hd = &cghash[HASH(cgx)];
186	LIST_FOREACH(sc, hd, sc_next)
187		if (sc->sc_cgx == cgx) {
188			sc->sc_cgbp = cgbp;
189			sc->sc_cgp = sc->sc_cgbp->b_un.b_cg;
190			lastcg = sc;
191			return (sc);
192		}
193	sc = errmalloc(sizeof(*sc));
194	bzero(sc, sizeof(*sc));
195	sc->sc_cgbp = cgbp;
196	sc->sc_cgp = sc->sc_cgbp->b_un.b_cg;
197	sc->sc_cgx = cgx;
198	LIST_INSERT_HEAD(hd, sc, sc_next);
199	return (sc);
200}
201
202/*
203 * Lookup an inode number in the hash and allocate a suj_ino if it does
204 * not exist.
205 */
206static struct suj_ino *
207ino_lookup(ino_t ino, int creat)
208{
209	struct suj_ino *sino;
210	struct inohd *hd;
211	struct suj_cg *sc;
212
213	sc = cg_lookup(ino_to_cg(fs, ino));
214	if (sc->sc_lastino && sc->sc_lastino->si_ino == ino)
215		return (sc->sc_lastino);
216	hd = &sc->sc_inohash[HASH(ino)];
217	LIST_FOREACH(sino, hd, si_next)
218		if (sino->si_ino == ino)
219			return (sino);
220	if (creat == 0)
221		return (NULL);
222	sino = errmalloc(sizeof(*sino));
223	bzero(sino, sizeof(*sino));
224	sino->si_ino = ino;
225	TAILQ_INIT(&sino->si_recs);
226	TAILQ_INIT(&sino->si_newrecs);
227	TAILQ_INIT(&sino->si_movs);
228	LIST_INSERT_HEAD(hd, sino, si_next);
229
230	return (sino);
231}
232
233/*
234 * Lookup a block number in the hash and allocate a suj_blk if it does
235 * not exist.
236 */
237static struct suj_blk *
238blk_lookup(ufs2_daddr_t blk, int creat)
239{
240	struct suj_blk *sblk;
241	struct suj_cg *sc;
242	struct blkhd *hd;
243
244	sc = cg_lookup(dtog(fs, blk));
245	if (sc->sc_lastblk && sc->sc_lastblk->sb_blk == blk)
246		return (sc->sc_lastblk);
247	hd = &sc->sc_blkhash[HASH(fragstoblks(fs, blk))];
248	LIST_FOREACH(sblk, hd, sb_next)
249		if (sblk->sb_blk == blk)
250			return (sblk);
251	if (creat == 0)
252		return (NULL);
253	sblk = errmalloc(sizeof(*sblk));
254	bzero(sblk, sizeof(*sblk));
255	sblk->sb_blk = blk;
256	TAILQ_INIT(&sblk->sb_recs);
257	LIST_INSERT_HEAD(hd, sblk, sb_next);
258
259	return (sblk);
260}
261
262static int
263blk_overlaps(struct jblkrec *brec, ufs2_daddr_t start, int frags)
264{
265	ufs2_daddr_t bstart;
266	ufs2_daddr_t bend;
267	ufs2_daddr_t end;
268
269	end = start + frags;
270	bstart = brec->jb_blkno + brec->jb_oldfrags;
271	bend = bstart + brec->jb_frags;
272	if (start < bend && end > bstart)
273		return (1);
274	return (0);
275}
276
277static int
278blk_equals(struct jblkrec *brec, ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t start,
279    int frags)
280{
281
282	if (brec->jb_ino != ino || brec->jb_lbn != lbn)
283		return (0);
284	if (brec->jb_blkno + brec->jb_oldfrags != start)
285		return (0);
286	if (brec->jb_frags < frags)
287		return (0);
288	return (1);
289}
290
291static void
292blk_setmask(struct jblkrec *brec, int *mask)
293{
294	int i;
295
296	for (i = brec->jb_oldfrags; i < brec->jb_oldfrags + brec->jb_frags; i++)
297		*mask |= 1 << i;
298}
299
300/*
301 * Determine whether a given block has been reallocated to a new location.
302 * Returns a mask of overlapping bits if any frags have been reused or
303 * zero if the block has not been re-used and the contents can be trusted.
304 *
305 * This is used to ensure that an orphaned pointer due to truncate is safe
306 * to be freed.  The mask value can be used to free partial blocks.
307 */
308static int
309blk_freemask(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn, int frags)
310{
311	struct suj_blk *sblk;
312	struct suj_rec *srec;
313	struct jblkrec *brec;
314	int mask;
315	int off;
316
317	/*
318	 * To be certain we're not freeing a reallocated block we lookup
319	 * this block in the blk hash and see if there is an allocation
320	 * journal record that overlaps with any fragments in the block
321	 * we're concerned with.  If any fragments have been reallocated
322	 * the block has already been freed and re-used for another purpose.
323	 */
324	mask = 0;
325	sblk = blk_lookup(blknum(fs, blk), 0);
326	if (sblk == NULL)
327		return (0);
328	off = blk - sblk->sb_blk;
329	TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
330		brec = (struct jblkrec *)srec->sr_rec;
331		/*
332		 * If the block overlaps but does not match
333		 * exactly this record refers to the current
334		 * location.
335		 */
336		if (blk_overlaps(brec, blk, frags) == 0)
337			continue;
338		if (blk_equals(brec, ino, lbn, blk, frags) == 1)
339			mask = 0;
340		else
341			blk_setmask(brec, &mask);
342	}
343	if (debug)
344		printf("blk_freemask: blk %jd sblk %jd off %d mask 0x%X\n",
345		    blk, sblk->sb_blk, off, mask);
346	return (mask >> off);
347}
348
349/*
350 * Determine whether it is safe to follow an indirect.  It is not safe
351 * if any part of the indirect has been reallocated or the last journal
352 * entry was an allocation.  Just allocated indirects may not have valid
353 * pointers yet and all of their children will have their own records.
354 * It is also not safe to follow an indirect if the cg bitmap has been
355 * cleared as a new allocation may write to the block prior to the journal
356 * being written.
357 *
358 * Returns 1 if it's safe to follow the indirect and 0 otherwise.
359 */
360static int
361blk_isindir(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn)
362{
363	struct suj_blk *sblk;
364	struct jblkrec *brec;
365
366	sblk = blk_lookup(blk, 0);
367	if (sblk == NULL)
368		return (1);
369	if (TAILQ_EMPTY(&sblk->sb_recs))
370		return (1);
371	brec = (struct jblkrec *)TAILQ_LAST(&sblk->sb_recs, srechd)->sr_rec;
372	if (blk_equals(brec, ino, lbn, blk, fs->fs_frag))
373		if (brec->jb_op == JOP_FREEBLK)
374			return (!blk_isfree(blk));
375	return (0);
376}
377
378/*
379 * Check to see if the requested block is available.
380 * We can just check in the cylinder-group maps as
381 * they will only have usable blocks in them.
382 */
383ufs2_daddr_t
384suj_checkblkavail(ufs2_daddr_t blkno, long frags)
385{
386	struct bufarea *cgbp;
387	struct cg *cgp;
388	ufs2_daddr_t j, k, baseblk;
389	long cg;
390
391	if ((u_int64_t)blkno > sblock.fs_size)
392		return (0);
393	cg = dtog(&sblock, blkno);
394	cgbp = cglookup(cg);
395	cgp = cgbp->b_un.b_cg;
396	if (!check_cgmagic(cg, cgbp))
397		return (-((cg + 1) * sblock.fs_fpg - sblock.fs_frag));
398	baseblk = dtogd(&sblock, blkno);
399	for (j = 0; j <= sblock.fs_frag - frags; j++) {
400		if (!isset(cg_blksfree(cgp), baseblk + j))
401			continue;
402		for (k = 1; k < frags; k++)
403			if (!isset(cg_blksfree(cgp), baseblk + j + k))
404				break;
405		if (k < frags) {
406			j += k;
407			continue;
408		}
409		for (k = 0; k < frags; k++)
410			clrbit(cg_blksfree(cgp), baseblk + j + k);
411		n_blks += frags;
412		if (frags == sblock.fs_frag)
413			cgp->cg_cs.cs_nbfree--;
414		else
415			cgp->cg_cs.cs_nffree -= frags;
416		cgdirty(cgbp);
417		return ((cg * sblock.fs_fpg) + baseblk + j);
418	}
419	return (0);
420}
421
422/*
423 * Clear an inode from the cg bitmap.  If the inode was already clear return
424 * 0 so the caller knows it does not have to check the inode contents.
425 */
426static int
427ino_free(ino_t ino, int mode)
428{
429	struct suj_cg *sc;
430	uint8_t *inosused;
431	struct cg *cgp;
432	int cg;
433
434	cg = ino_to_cg(fs, ino);
435	ino = ino % fs->fs_ipg;
436	sc = cg_lookup(cg);
437	cgp = sc->sc_cgp;
438	inosused = cg_inosused(cgp);
439	/*
440	 * The bitmap may never have made it to the disk so we have to
441	 * conditionally clear.  We can avoid writing the cg in this case.
442	 */
443	if (isclr(inosused, ino))
444		return (0);
445	freeinos++;
446	clrbit(inosused, ino);
447	if (ino < cgp->cg_irotor)
448		cgp->cg_irotor = ino;
449	cgp->cg_cs.cs_nifree++;
450	if ((mode & IFMT) == IFDIR) {
451		freedir++;
452		cgp->cg_cs.cs_ndir--;
453	}
454	cgdirty(sc->sc_cgbp);
455
456	return (1);
457}
458
459/*
460 * Free 'frags' frags starting at filesystem block 'bno' skipping any frags
461 * set in the mask.
462 */
463static void
464blk_free(ino_t ino, ufs2_daddr_t bno, int mask, int frags)
465{
466	ufs1_daddr_t fragno, cgbno;
467	struct suj_cg *sc;
468	struct cg *cgp;
469	int i, cg;
470	uint8_t *blksfree;
471
472	if (debug)
473		printf("Freeing %d frags at blk %jd mask 0x%x\n",
474		    frags, bno, mask);
475	/*
476	 * Check to see if the block needs to be claimed by a snapshot.
477	 * If wanted, the snapshot references it. Otherwise we free it.
478	 */
479	if (snapblkfree(fs, bno, lfragtosize(fs, frags), ino,
480	    suj_checkblkavail))
481		return;
482	cg = dtog(fs, bno);
483	sc = cg_lookup(cg);
484	cgp = sc->sc_cgp;
485	cgbno = dtogd(fs, bno);
486	blksfree = cg_blksfree(cgp);
487
488	/*
489	 * If it's not allocated we only wrote the journal entry
490	 * and never the bitmaps.  Here we unconditionally clear and
491	 * resolve the cg summary later.
492	 */
493	if (frags == fs->fs_frag && mask == 0) {
494		fragno = fragstoblks(fs, cgbno);
495		ffs_setblock(fs, blksfree, fragno);
496		freeblocks++;
497	} else {
498		/*
499		 * deallocate the fragment
500		 */
501		for (i = 0; i < frags; i++)
502			if ((mask & (1 << i)) == 0 &&
503			    isclr(blksfree, cgbno +i)) {
504				freefrags++;
505				setbit(blksfree, cgbno + i);
506			}
507	}
508	cgdirty(sc->sc_cgbp);
509}
510
511/*
512 * Returns 1 if the whole block starting at 'bno' is marked free and 0
513 * otherwise.
514 */
515static int
516blk_isfree(ufs2_daddr_t bno)
517{
518	struct suj_cg *sc;
519
520	sc = cg_lookup(dtog(fs, bno));
521	return ffs_isblock(fs, cg_blksfree(sc->sc_cgp), dtogd(fs, bno));
522}
523
524/*
525 * Determine whether a block exists at a particular lbn in an inode.
526 * Returns 1 if found, 0 if not.  lbn may be negative for indirects
527 * or ext blocks.
528 */
529static int
530blk_isat(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int *frags)
531{
532	struct inode ip;
533	union dinode *dp;
534	ufs2_daddr_t nblk;
535
536	ginode(ino, &ip);
537	dp = ip.i_dp;
538	if (DIP(dp, di_nlink) == 0 || DIP(dp, di_mode) == 0) {
539		irelse(&ip);
540		return (0);
541	}
542	nblk = ino_blkatoff(dp, ino, lbn, frags, NULL);
543	irelse(&ip);
544	return (nblk == blk);
545}
546
547/*
548 * Clear the directory entry at diroff that should point to child.  Minimal
549 * checking is done and it is assumed that this path was verified with isat.
550 */
551static void
552ino_clrat(ino_t parent, off_t diroff, ino_t child)
553{
554	union dinode *dip;
555	struct direct *dp;
556	struct inode ip;
557	ufs2_daddr_t blk;
558	struct bufarea *bp;
559	ufs_lbn_t lbn;
560	int blksize;
561	int frags;
562	int doff;
563
564	if (debug)
565		printf("Clearing inode %ju from parent %ju at offset %jd\n",
566		    (uintmax_t)child, (uintmax_t)parent, diroff);
567
568	lbn = lblkno(fs, diroff);
569	doff = blkoff(fs, diroff);
570	ginode(parent, &ip);
571	dip = ip.i_dp;
572	blk = ino_blkatoff(dip, parent, lbn, &frags, NULL);
573	blksize = sblksize(fs, DIP(dip, di_size), lbn);
574	irelse(&ip);
575	bp = getdatablk(blk, blksize, BT_DIRDATA);
576	if (bp->b_errs != 0)
577		err_suj("ino_clrat: UNRECOVERABLE I/O ERROR");
578	dp = (struct direct *)&bp->b_un.b_buf[doff];
579	if (dp->d_ino != child)
580		errx(1, "Inode %ju does not exist in %ju at %jd",
581		    (uintmax_t)child, (uintmax_t)parent, diroff);
582	dp->d_ino = 0;
583	dirty(bp);
584	brelse(bp);
585	/*
586	 * The actual .. reference count will already have been removed
587	 * from the parent by the .. remref record.
588	 */
589}
590
591/*
592 * Determines whether a pointer to an inode exists within a directory
593 * at a specified offset.  Returns the mode of the found entry.
594 */
595static int
596ino_isat(ino_t parent, off_t diroff, ino_t child, int *mode, int *isdot)
597{
598	struct inode ip;
599	union dinode *dip;
600	struct bufarea *bp;
601	struct direct *dp;
602	ufs2_daddr_t blk;
603	ufs_lbn_t lbn;
604	int blksize;
605	int frags;
606	int dpoff;
607	int doff;
608
609	*isdot = 0;
610	ginode(parent, &ip);
611	dip = ip.i_dp;
612	*mode = DIP(dip, di_mode);
613	if ((*mode & IFMT) != IFDIR) {
614		if (debug) {
615			/*
616			 * This can happen if the parent inode
617			 * was reallocated.
618			 */
619			if (*mode != 0)
620				printf("Directory %ju has bad mode %o\n",
621				    (uintmax_t)parent, *mode);
622			else
623				printf("Directory %ju has zero mode\n",
624				    (uintmax_t)parent);
625		}
626		irelse(&ip);
627		return (0);
628	}
629	lbn = lblkno(fs, diroff);
630	doff = blkoff(fs, diroff);
631	blksize = sblksize(fs, DIP(dip, di_size), lbn);
632	if (diroff + DIRECTSIZ(1) > DIP(dip, di_size) || doff >= blksize) {
633		if (debug)
634			printf("ino %ju absent from %ju due to offset %jd"
635			    " exceeding size %jd\n",
636			    (uintmax_t)child, (uintmax_t)parent, diroff,
637			    DIP(dip, di_size));
638		irelse(&ip);
639		return (0);
640	}
641	blk = ino_blkatoff(dip, parent, lbn, &frags, NULL);
642	irelse(&ip);
643	if (blk <= 0) {
644		if (debug)
645			printf("Sparse directory %ju", (uintmax_t)parent);
646		return (0);
647	}
648	bp = getdatablk(blk, blksize, BT_DIRDATA);
649	if (bp->b_errs != 0)
650		err_suj("ino_isat: UNRECOVERABLE I/O ERROR");
651	/*
652	 * Walk through the records from the start of the block to be
653	 * certain we hit a valid record and not some junk in the middle
654	 * of a file name.  Stop when we reach or pass the expected offset.
655	 */
656	dpoff = rounddown(doff, DIRBLKSIZ);
657	do {
658		dp = (struct direct *)&bp->b_un.b_buf[dpoff];
659		if (dpoff == doff)
660			break;
661		if (dp->d_reclen == 0)
662			break;
663		dpoff += dp->d_reclen;
664	} while (dpoff <= doff);
665	if (dpoff > fs->fs_bsize)
666		err_suj("Corrupt directory block in dir ino %ju\n",
667		    (uintmax_t)parent);
668	/* Not found. */
669	if (dpoff != doff) {
670		if (debug)
671			printf("ino %ju not found in %ju, lbn %jd, dpoff %d\n",
672			    (uintmax_t)child, (uintmax_t)parent, lbn, dpoff);
673		brelse(bp);
674		return (0);
675	}
676	/*
677	 * We found the item in question.  Record the mode and whether it's
678	 * a . or .. link for the caller.
679	 */
680	if (dp->d_ino == child) {
681		if (child == parent)
682			*isdot = 1;
683		else if (dp->d_namlen == 2 &&
684		    dp->d_name[0] == '.' && dp->d_name[1] == '.')
685			*isdot = 1;
686		*mode = DTTOIF(dp->d_type);
687		brelse(bp);
688		return (1);
689	}
690	if (debug)
691		printf("ino %ju doesn't match dirent ino %ju in parent %ju\n",
692		    (uintmax_t)child, (uintmax_t)dp->d_ino, (uintmax_t)parent);
693	brelse(bp);
694	return (0);
695}
696
697#define	VISIT_INDIR	0x0001
698#define	VISIT_EXT	0x0002
699#define	VISIT_ROOT	0x0004	/* Operation came via root & valid pointers. */
700
701/*
702 * Read an indirect level which may or may not be linked into an inode.
703 */
704static void
705indir_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, uint64_t *frags,
706    ino_visitor visitor, int flags)
707{
708	struct bufarea *bp;
709	ufs_lbn_t lbnadd;
710	ufs2_daddr_t nblk;
711	ufs_lbn_t nlbn;
712	int level;
713	int i;
714
715	/*
716	 * Don't visit indirect blocks with contents we can't trust.  This
717	 * should only happen when indir_visit() is called to complete a
718	 * truncate that never finished and not when a pointer is found via
719	 * an inode.
720	 */
721	if (blk == 0)
722		return;
723	level = lbn_level(lbn);
724	if (level == -1)
725		err_suj("Invalid level for lbn %jd\n", lbn);
726	if ((flags & VISIT_ROOT) == 0 && blk_isindir(blk, ino, lbn) == 0) {
727		if (debug)
728			printf("blk %jd ino %ju lbn %jd(%d) is not indir.\n",
729			    blk, (uintmax_t)ino, lbn, level);
730		goto out;
731	}
732	lbnadd = 1;
733	for (i = level; i > 0; i--)
734		lbnadd *= NINDIR(fs);
735	bp = getdatablk(blk, fs->fs_bsize, BT_LEVEL1 + level);
736	if (bp->b_errs != 0)
737		err_suj("indir_visit: UNRECOVERABLE I/O ERROR\n");
738	for (i = 0; i < NINDIR(fs); i++) {
739		if ((nblk = IBLK(bp, i)) == 0)
740			continue;
741		if (level == 0) {
742			nlbn = -lbn + i * lbnadd;
743			(*frags) += fs->fs_frag;
744			visitor(ino, nlbn, nblk, fs->fs_frag);
745		} else {
746			nlbn = (lbn + 1) - (i * lbnadd);
747			indir_visit(ino, nlbn, nblk, frags, visitor, flags);
748		}
749	}
750	brelse(bp);
751out:
752	if (flags & VISIT_INDIR) {
753		(*frags) += fs->fs_frag;
754		visitor(ino, lbn, blk, fs->fs_frag);
755	}
756}
757
758/*
759 * Visit each block in an inode as specified by 'flags' and call a
760 * callback function.  The callback may inspect or free blocks.  The
761 * count of frags found according to the size in the file is returned.
762 * This is not valid for sparse files but may be used to determine
763 * the correct di_blocks for a file.
764 */
765static uint64_t
766ino_visit(union dinode *dp, ino_t ino, ino_visitor visitor, int flags)
767{
768	ufs_lbn_t nextlbn;
769	ufs_lbn_t tmpval;
770	ufs_lbn_t lbn;
771	uint64_t size;
772	uint64_t fragcnt;
773	int mode;
774	int frags;
775	int i;
776
777	size = DIP(dp, di_size);
778	mode = DIP(dp, di_mode) & IFMT;
779	fragcnt = 0;
780	if ((flags & VISIT_EXT) &&
781	    fs->fs_magic == FS_UFS2_MAGIC && dp->dp2.di_extsize) {
782		for (i = 0; i < UFS_NXADDR; i++) {
783			if (dp->dp2.di_extb[i] == 0)
784				continue;
785			frags = sblksize(fs, dp->dp2.di_extsize, i);
786			frags = numfrags(fs, frags);
787			fragcnt += frags;
788			visitor(ino, -1 - i, dp->dp2.di_extb[i], frags);
789		}
790	}
791	/* Skip datablocks for short links and devices. */
792	if (mode == IFBLK || mode == IFCHR ||
793	    (mode == IFLNK && size < fs->fs_maxsymlinklen))
794		return (fragcnt);
795	for (i = 0; i < UFS_NDADDR; i++) {
796		if (DIP(dp, di_db[i]) == 0)
797			continue;
798		frags = sblksize(fs, size, i);
799		frags = numfrags(fs, frags);
800		fragcnt += frags;
801		visitor(ino, i, DIP(dp, di_db[i]), frags);
802	}
803	/*
804	 * We know the following indirects are real as we're following
805	 * real pointers to them.
806	 */
807	flags |= VISIT_ROOT;
808	for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR; i < UFS_NIADDR; i++,
809	    lbn = nextlbn) {
810		nextlbn = lbn + tmpval;
811		tmpval *= NINDIR(fs);
812		if (DIP(dp, di_ib[i]) == 0)
813			continue;
814		indir_visit(ino, -lbn - i, DIP(dp, di_ib[i]), &fragcnt, visitor,
815		    flags);
816	}
817	return (fragcnt);
818}
819
820/*
821 * Null visitor function used when we just want to count blocks and
822 * record the lbn.
823 */
824ufs_lbn_t visitlbn;
825static void
826null_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
827{
828	if (lbn > 0)
829		visitlbn = lbn;
830}
831
832/*
833 * Recalculate di_blocks when we discover that a block allocation or
834 * free was not successfully completed.  The kernel does not roll this back
835 * because it would be too expensive to compute which indirects were
836 * reachable at the time the inode was written.
837 */
838static void
839ino_adjblks(struct suj_ino *sino)
840{
841	struct inode ip;
842	union dinode *dp;
843	uint64_t blocks;
844	uint64_t frags;
845	off_t isize;
846	off_t size;
847	ino_t ino;
848
849	ino = sino->si_ino;
850	ginode(ino, &ip);
851	dp = ip.i_dp;
852	/* No need to adjust zero'd inodes. */
853	if (DIP(dp, di_mode) == 0) {
854		irelse(&ip);
855		return;
856	}
857	/*
858	 * Visit all blocks and count them as well as recording the last
859	 * valid lbn in the file.  If the file size doesn't agree with the
860	 * last lbn we need to truncate to fix it.  Otherwise just adjust
861	 * the blocks count.
862	 */
863	visitlbn = 0;
864	frags = ino_visit(dp, ino, null_visit, VISIT_INDIR | VISIT_EXT);
865	blocks = fsbtodb(fs, frags);
866	/*
867	 * We assume the size and direct block list is kept coherent by
868	 * softdep.  For files that have extended into indirects we truncate
869	 * to the size in the inode or the maximum size permitted by
870	 * populated indirects.
871	 */
872	if (visitlbn >= UFS_NDADDR) {
873		isize = DIP(dp, di_size);
874		size = lblktosize(fs, visitlbn + 1);
875		if (isize > size)
876			isize = size;
877		/* Always truncate to free any unpopulated indirects. */
878		ino_trunc(ino, isize);
879		irelse(&ip);
880		return;
881	}
882	if (blocks == DIP(dp, di_blocks)) {
883		irelse(&ip);
884		return;
885	}
886	if (debug)
887		printf("ino %ju adjusting block count from %jd to %jd\n",
888		    (uintmax_t)ino, DIP(dp, di_blocks), blocks);
889	DIP_SET(dp, di_blocks, blocks);
890	inodirty(&ip);
891	irelse(&ip);
892}
893
894static void
895blk_free_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
896{
897
898	blk_free(ino, blk, blk_freemask(blk, ino, lbn, frags), frags);
899}
900
901/*
902 * Free a block or tree of blocks that was previously rooted in ino at
903 * the given lbn.  If the lbn is an indirect all children are freed
904 * recursively.
905 */
906static void
907blk_free_lbn(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn, int frags, int follow)
908{
909	uint64_t resid;
910	int mask;
911
912	mask = blk_freemask(blk, ino, lbn, frags);
913	resid = 0;
914	if (lbn <= -UFS_NDADDR && follow && mask == 0)
915		indir_visit(ino, lbn, blk, &resid, blk_free_visit, VISIT_INDIR);
916	else
917		blk_free(ino, blk, mask, frags);
918}
919
920static void
921ino_setskip(struct suj_ino *sino, ino_t parent)
922{
923	int isdot;
924	int mode;
925
926	if (ino_isat(sino->si_ino, DOTDOT_OFFSET, parent, &mode, &isdot))
927		sino->si_skipparent = 1;
928}
929
930static void
931ino_remref(ino_t parent, ino_t child, uint64_t diroff, int isdotdot)
932{
933	struct suj_ino *sino;
934	struct suj_rec *srec;
935	struct jrefrec *rrec;
936
937	/*
938	 * Lookup this inode to see if we have a record for it.
939	 */
940	sino = ino_lookup(child, 0);
941	/*
942	 * Tell any child directories we've already removed their
943	 * parent link cnt.  Don't try to adjust our link down again.
944	 */
945	if (sino != NULL && isdotdot == 0)
946		ino_setskip(sino, parent);
947	/*
948	 * No valid record for this inode.  Just drop the on-disk
949	 * link by one.
950	 */
951	if (sino == NULL || sino->si_hasrecs == 0) {
952		ino_decr(child);
953		return;
954	}
955	/*
956	 * Use ino_adjust() if ino_check() has already processed this
957	 * child.  If we lose the last non-dot reference to a
958	 * directory it will be discarded.
959	 */
960	if (sino->si_linkadj) {
961		if (sino->si_nlink == 0)
962			err_suj("ino_remref: ino %ld mode 0%o about to go "
963			    "negative\n", sino->si_ino, sino->si_mode);
964		sino->si_nlink--;
965		if (isdotdot)
966			sino->si_dotlinks--;
967		ino_adjust(sino);
968		return;
969	}
970	/*
971	 * If we haven't yet processed this inode we need to make
972	 * sure we will successfully discover the lost path.  If not
973	 * use nlinkadj to remember.
974	 */
975	TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
976		rrec = (struct jrefrec *)srec->sr_rec;
977		if (rrec->jr_parent == parent &&
978		    rrec->jr_diroff == diroff)
979			return;
980	}
981	sino->si_nlinkadj++;
982}
983
984/*
985 * Free the children of a directory when the directory is discarded.
986 */
987static void
988ino_free_children(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
989{
990	struct suj_ino *sino;
991	struct bufarea *bp;
992	struct direct *dp;
993	off_t diroff;
994	int skipparent;
995	int isdotdot;
996	int dpoff;
997	int size;
998
999	sino = ino_lookup(ino, 0);
1000	if (sino)
1001		skipparent = sino->si_skipparent;
1002	else
1003		skipparent = 0;
1004	size = lfragtosize(fs, frags);
1005	bp = getdatablk(blk, size, BT_DIRDATA);
1006	if (bp->b_errs != 0)
1007		err_suj("ino_free_children: UNRECOVERABLE I/O ERROR");
1008	dp = (struct direct *)&bp->b_un.b_buf[0];
1009	for (dpoff = 0; dpoff < size && dp->d_reclen; dpoff += dp->d_reclen) {
1010		dp = (struct direct *)&bp->b_un.b_buf[dpoff];
1011		if (dp->d_ino == 0 || dp->d_ino == UFS_WINO)
1012			continue;
1013		if (dp->d_namlen == 1 && dp->d_name[0] == '.')
1014			continue;
1015		isdotdot = dp->d_namlen == 2 && dp->d_name[0] == '.' &&
1016		    dp->d_name[1] == '.';
1017		if (isdotdot && skipparent == 1)
1018			continue;
1019		if (debug)
1020			printf("Directory %ju removing ino %ju name %s\n",
1021			    (uintmax_t)ino, (uintmax_t)dp->d_ino, dp->d_name);
1022		diroff = lblktosize(fs, lbn) + dpoff;
1023		ino_remref(ino, dp->d_ino, diroff, isdotdot);
1024	}
1025	brelse(bp);
1026}
1027
1028/*
1029 * Reclaim an inode, freeing all blocks and decrementing all children's
1030 * link counts.  Free the inode back to the cg.
1031 */
1032static void
1033ino_reclaim(struct inode *ip, ino_t ino, int mode)
1034{
1035	union dinode *dp;
1036	uint32_t gen;
1037
1038	dp = ip->i_dp;
1039	if (ino == UFS_ROOTINO)
1040		err_suj("Attempting to free UFS_ROOTINO\n");
1041	if (debug)
1042		printf("Truncating and freeing ino %ju, nlink %d, mode %o\n",
1043		    (uintmax_t)ino, DIP(dp, di_nlink), DIP(dp, di_mode));
1044
1045	/* We are freeing an inode or directory. */
1046	if ((DIP(dp, di_mode) & IFMT) == IFDIR)
1047		ino_visit(dp, ino, ino_free_children, 0);
1048	DIP_SET(dp, di_nlink, 0);
1049	if ((DIP(dp, di_flags) & SF_SNAPSHOT) != 0)
1050		snapremove(ino);
1051	ino_visit(dp, ino, blk_free_visit, VISIT_EXT | VISIT_INDIR);
1052	/* Here we have to clear the inode and release any blocks it holds. */
1053	gen = DIP(dp, di_gen);
1054	if (fs->fs_magic == FS_UFS1_MAGIC)
1055		bzero(dp, sizeof(struct ufs1_dinode));
1056	else
1057		bzero(dp, sizeof(struct ufs2_dinode));
1058	DIP_SET(dp, di_gen, gen);
1059	inodirty(ip);
1060	ino_free(ino, mode);
1061	return;
1062}
1063
1064/*
1065 * Adjust an inode's link count down by one when a directory goes away.
1066 */
1067static void
1068ino_decr(ino_t ino)
1069{
1070	struct inode ip;
1071	union dinode *dp;
1072	int reqlink;
1073	int nlink;
1074	int mode;
1075
1076	ginode(ino, &ip);
1077	dp = ip.i_dp;
1078	nlink = DIP(dp, di_nlink);
1079	mode = DIP(dp, di_mode);
1080	if (nlink < 1)
1081		err_suj("Inode %d link count %d invalid\n", ino, nlink);
1082	if (mode == 0)
1083		err_suj("Inode %d has a link of %d with 0 mode\n", ino, nlink);
1084	nlink--;
1085	if ((mode & IFMT) == IFDIR)
1086		reqlink = 2;
1087	else
1088		reqlink = 1;
1089	if (nlink < reqlink) {
1090		if (debug)
1091			printf("ino %ju not enough links to live %d < %d\n",
1092			    (uintmax_t)ino, nlink, reqlink);
1093		ino_reclaim(&ip, ino, mode);
1094		irelse(&ip);
1095		return;
1096	}
1097	DIP_SET(dp, di_nlink, nlink);
1098	inodirty(&ip);
1099	irelse(&ip);
1100}
1101
1102/*
1103 * Adjust the inode link count to 'nlink'.  If the count reaches zero
1104 * free it.
1105 */
1106static void
1107ino_adjust(struct suj_ino *sino)
1108{
1109	struct jrefrec *rrec;
1110	struct suj_rec *srec;
1111	struct suj_ino *stmp;
1112	union dinode *dp;
1113	struct inode ip;
1114	nlink_t nlink;
1115	nlink_t reqlink;
1116	int recmode;
1117	int isdot;
1118	int mode;
1119	ino_t ino;
1120
1121	nlink = sino->si_nlink;
1122	ino = sino->si_ino;
1123	mode = sino->si_mode & IFMT;
1124	/*
1125	 * If it's a directory with no dot links, it was truncated before
1126	 * the name was cleared.  We need to clear the dirent that
1127	 * points at it.
1128	 */
1129	if (mode == IFDIR && nlink == 1 && sino->si_dotlinks == 0) {
1130		sino->si_nlink = nlink = 0;
1131		TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1132			rrec = (struct jrefrec *)srec->sr_rec;
1133			if (ino_isat(rrec->jr_parent, rrec->jr_diroff, ino,
1134			    &recmode, &isdot) == 0)
1135				continue;
1136			ino_clrat(rrec->jr_parent, rrec->jr_diroff, ino);
1137			break;
1138		}
1139		if (srec == NULL)
1140			errx(1, "Directory %ju name not found", (uintmax_t)ino);
1141	}
1142	/*
1143	 * If it's a directory with no real names pointing to it go ahead
1144	 * and truncate it.  This will free any children.
1145	 */
1146	if (mode == IFDIR && nlink - sino->si_dotlinks == 0) {
1147		sino->si_nlink = nlink = 0;
1148		/*
1149		 * Mark any .. links so they know not to free this inode
1150		 * when they are removed.
1151		 */
1152		TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1153			rrec = (struct jrefrec *)srec->sr_rec;
1154			if (rrec->jr_diroff == DOTDOT_OFFSET) {
1155				stmp = ino_lookup(rrec->jr_parent, 0);
1156				if (stmp)
1157					ino_setskip(stmp, ino);
1158			}
1159		}
1160	}
1161	ginode(ino, &ip);
1162	dp = ip.i_dp;
1163	mode = DIP(dp, di_mode) & IFMT;
1164	if (nlink > UFS_LINK_MAX)
1165		err_suj("ino %ju nlink manipulation error, new %ju, old %d\n",
1166		    (uintmax_t)ino, (uintmax_t)nlink, DIP(dp, di_nlink));
1167	if (debug)
1168	       printf("Adjusting ino %ju, nlink %ju, old link %d lastmode %o\n",
1169		    (uintmax_t)ino, (uintmax_t)nlink, DIP(dp, di_nlink),
1170		    sino->si_mode);
1171	if (mode == 0) {
1172		if (debug)
1173			printf("ino %ju, zero inode freeing bitmap\n",
1174			    (uintmax_t)ino);
1175		ino_free(ino, sino->si_mode);
1176		irelse(&ip);
1177		return;
1178	}
1179	/* XXX Should be an assert? */
1180	if (mode != sino->si_mode && debug)
1181		printf("ino %ju, mode %o != %o\n",
1182		    (uintmax_t)ino, mode, sino->si_mode);
1183	if ((mode & IFMT) == IFDIR)
1184		reqlink = 2;
1185	else
1186		reqlink = 1;
1187	/* If the inode doesn't have enough links to live, free it. */
1188	if (nlink < reqlink) {
1189		if (debug)
1190			printf("ino %ju not enough links to live %ju < %ju\n",
1191			    (uintmax_t)ino, (uintmax_t)nlink,
1192			    (uintmax_t)reqlink);
1193		ino_reclaim(&ip, ino, mode);
1194		irelse(&ip);
1195		return;
1196	}
1197	/* If required write the updated link count. */
1198	if (DIP(dp, di_nlink) == nlink) {
1199		if (debug)
1200			printf("ino %ju, link matches, skipping.\n",
1201			    (uintmax_t)ino);
1202		irelse(&ip);
1203		return;
1204	}
1205	DIP_SET(dp, di_nlink, nlink);
1206	inodirty(&ip);
1207	irelse(&ip);
1208}
1209
1210/*
1211 * Truncate some or all blocks in an indirect, freeing any that are required
1212 * and zeroing the indirect.
1213 */
1214static void
1215indir_trunc(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, ufs_lbn_t lastlbn,
1216	union dinode *dp)
1217{
1218	struct bufarea *bp;
1219	ufs_lbn_t lbnadd;
1220	ufs2_daddr_t nblk;
1221	ufs_lbn_t next;
1222	ufs_lbn_t nlbn;
1223	int isdirty;
1224	int level;
1225	int i;
1226
1227	if (blk == 0)
1228		return;
1229	isdirty = 0;
1230	level = lbn_level(lbn);
1231	if (level == -1)
1232		err_suj("Invalid level for lbn %jd\n", lbn);
1233	lbnadd = 1;
1234	for (i = level; i > 0; i--)
1235		lbnadd *= NINDIR(fs);
1236	bp = getdatablk(blk, fs->fs_bsize, BT_LEVEL1 + level);
1237	if (bp->b_errs != 0)
1238		err_suj("indir_trunc: UNRECOVERABLE I/O ERROR");
1239	for (i = 0; i < NINDIR(fs); i++) {
1240		if ((nblk = IBLK(bp, i)) == 0)
1241			continue;
1242		if (level != 0) {
1243			nlbn = (lbn + 1) - (i * lbnadd);
1244			/*
1245			 * Calculate the lbn of the next indirect to
1246			 * determine if any of this indirect must be
1247			 * reclaimed.
1248			 */
1249			next = -(lbn + level) + ((i+1) * lbnadd);
1250			if (next <= lastlbn)
1251				continue;
1252			indir_trunc(ino, nlbn, nblk, lastlbn, dp);
1253			/* If all of this indirect was reclaimed, free it. */
1254			nlbn = next - lbnadd;
1255			if (nlbn < lastlbn)
1256				continue;
1257		} else {
1258			nlbn = -lbn + i * lbnadd;
1259			if (nlbn < lastlbn)
1260				continue;
1261		}
1262		isdirty = 1;
1263		blk_free(ino, nblk, 0, fs->fs_frag);
1264		IBLK_SET(bp, i, 0);
1265	}
1266	if (isdirty)
1267		dirty(bp);
1268	brelse(bp);
1269}
1270
1271/*
1272 * Truncate an inode to the minimum of the given size or the last populated
1273 * block after any over size have been discarded.  The kernel would allocate
1274 * the last block in the file but fsck does not and neither do we.  This
1275 * code never extends files, only shrinks them.
1276 */
1277static void
1278ino_trunc(ino_t ino, off_t size)
1279{
1280	struct inode ip;
1281	union dinode *dp;
1282	struct bufarea *bp;
1283	ufs2_daddr_t bn;
1284	uint64_t totalfrags;
1285	ufs_lbn_t nextlbn;
1286	ufs_lbn_t lastlbn;
1287	ufs_lbn_t tmpval;
1288	ufs_lbn_t lbn;
1289	ufs_lbn_t i;
1290	int blksize, frags;
1291	off_t cursize;
1292	off_t off;
1293	int mode;
1294
1295	ginode(ino, &ip);
1296	dp = ip.i_dp;
1297	mode = DIP(dp, di_mode) & IFMT;
1298	cursize = DIP(dp, di_size);
1299	/* If no size change, nothing to do */
1300	if (size == cursize) {
1301		irelse(&ip);
1302		return;
1303	}
1304	if (debug)
1305		printf("Truncating ino %ju, mode %o to size %jd from "
1306		    "size %jd\n", (uintmax_t)ino, mode, size, cursize);
1307
1308	/* Skip datablocks for short links and devices. */
1309	if (mode == 0 || mode == IFBLK || mode == IFCHR ||
1310	    (mode == IFLNK && cursize < fs->fs_maxsymlinklen)) {
1311		irelse(&ip);
1312		return;
1313	}
1314	/* Don't extend. */
1315	if (size > cursize) {
1316		irelse(&ip);
1317		return;
1318	}
1319	if ((DIP(dp, di_flags) & SF_SNAPSHOT) != 0) {
1320		if (size > 0)
1321			err_suj("Partial truncation of ino %ju snapshot file\n",
1322			    (uintmax_t)ino);
1323		snapremove(ino);
1324	}
1325	lastlbn = lblkno(fs, blkroundup(fs, size));
1326	for (i = lastlbn; i < UFS_NDADDR; i++) {
1327		if ((bn = DIP(dp, di_db[i])) == 0)
1328			continue;
1329		blksize = sblksize(fs, cursize, i);
1330		blk_free(ino, bn, 0, numfrags(fs, blksize));
1331		DIP_SET(dp, di_db[i], 0);
1332	}
1333	/*
1334	 * Follow indirect blocks, freeing anything required.
1335	 */
1336	for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR; i < UFS_NIADDR; i++,
1337	    lbn = nextlbn) {
1338		nextlbn = lbn + tmpval;
1339		tmpval *= NINDIR(fs);
1340		/* If we're not freeing any in this indirect range skip it. */
1341		if (lastlbn >= nextlbn)
1342			continue;
1343		if ((bn = DIP(dp, di_ib[i])) == 0)
1344  			continue;
1345		indir_trunc(ino, -lbn - i, bn, lastlbn, dp);
1346  		/* If we freed everything in this indirect free the indir. */
1347  		if (lastlbn > lbn)
1348  			continue;
1349		blk_free(ino, bn, 0, fs->fs_frag);
1350		DIP_SET(dp, di_ib[i], 0);
1351	}
1352	/*
1353	 * Now that we've freed any whole blocks that exceed the desired
1354	 * truncation size, figure out how many blocks remain and what the
1355	 * last populated lbn is.  We will set the size to this last lbn
1356	 * rather than worrying about allocating the final lbn as the kernel
1357	 * would've done.  This is consistent with normal fsck behavior.
1358	 */
1359	visitlbn = 0;
1360	totalfrags = ino_visit(dp, ino, null_visit, VISIT_INDIR | VISIT_EXT);
1361	if (size > lblktosize(fs, visitlbn + 1))
1362		size = lblktosize(fs, visitlbn + 1);
1363	/*
1364	 * If we're truncating direct blocks we have to adjust frags
1365	 * accordingly.
1366	 */
1367	if (visitlbn < UFS_NDADDR && totalfrags) {
1368		long oldspace, newspace;
1369
1370		bn = DIP(dp, di_db[visitlbn]);
1371		if (bn == 0)
1372			err_suj("Bad blk at ino %ju lbn %jd\n",
1373			    (uintmax_t)ino, visitlbn);
1374		oldspace = sblksize(fs, cursize, visitlbn);
1375		newspace = sblksize(fs, size, visitlbn);
1376		if (oldspace != newspace) {
1377			bn += numfrags(fs, newspace);
1378			frags = numfrags(fs, oldspace - newspace);
1379			blk_free(ino, bn, 0, frags);
1380			totalfrags -= frags;
1381		}
1382	}
1383	DIP_SET(dp, di_blocks, fsbtodb(fs, totalfrags));
1384	DIP_SET(dp, di_size, size);
1385	inodirty(&ip);
1386	/*
1387	 * If we've truncated into the middle of a block or frag we have
1388	 * to zero it here.  Otherwise the file could extend into
1389	 * uninitialized space later.
1390	 */
1391	off = blkoff(fs, size);
1392	if (off && DIP(dp, di_mode) != IFDIR) {
1393		long clrsize;
1394
1395		bn = ino_blkatoff(dp, ino, visitlbn, &frags, NULL);
1396		if (bn == 0)
1397			err_suj("Block missing from ino %ju at lbn %jd\n",
1398			    (uintmax_t)ino, visitlbn);
1399		clrsize = frags * fs->fs_fsize;
1400		bp = getdatablk(bn, clrsize, BT_DATA);
1401		if (bp->b_errs != 0)
1402			err_suj("ino_trunc: UNRECOVERABLE I/O ERROR");
1403		clrsize -= off;
1404		bzero(&bp->b_un.b_buf[off], clrsize);
1405		dirty(bp);
1406		brelse(bp);
1407	}
1408	irelse(&ip);
1409	return;
1410}
1411
1412/*
1413 * Process records available for one inode and determine whether the
1414 * link count is correct or needs adjusting.
1415 */
1416static void
1417ino_check(struct suj_ino *sino)
1418{
1419	struct suj_rec *srec;
1420	struct jrefrec *rrec;
1421	nlink_t dotlinks;
1422	nlink_t newlinks;
1423	nlink_t removes;
1424	nlink_t nlink;
1425	ino_t ino;
1426	int isdot;
1427	int isat;
1428	int mode;
1429
1430	if (sino->si_hasrecs == 0)
1431		return;
1432	ino = sino->si_ino;
1433	rrec = (struct jrefrec *)TAILQ_FIRST(&sino->si_recs)->sr_rec;
1434	nlink = rrec->jr_nlink;
1435	newlinks = 0;
1436	dotlinks = 0;
1437	removes = sino->si_nlinkadj;
1438	TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1439		rrec = (struct jrefrec *)srec->sr_rec;
1440		isat = ino_isat(rrec->jr_parent, rrec->jr_diroff,
1441		    rrec->jr_ino, &mode, &isdot);
1442		if (isat && (mode & IFMT) != (rrec->jr_mode & IFMT))
1443			err_suj("Inode mode/directory type mismatch %o != %o\n",
1444			    mode, rrec->jr_mode);
1445		if (debug)
1446			printf("jrefrec: op %s ino %ju, nlink %ju, parent %ju, "
1447			    "diroff %jd, mode %o, isat %d, isdot %d\n",
1448			    JOP_OPTYPE(rrec->jr_op), (uintmax_t)rrec->jr_ino,
1449			    (uintmax_t)rrec->jr_nlink,
1450			    (uintmax_t)rrec->jr_parent,
1451			    (uintmax_t)rrec->jr_diroff,
1452			    rrec->jr_mode, isat, isdot);
1453		mode = rrec->jr_mode & IFMT;
1454		if (rrec->jr_op == JOP_REMREF)
1455			removes++;
1456		newlinks += isat;
1457		if (isdot)
1458			dotlinks += isat;
1459	}
1460	/*
1461	 * The number of links that remain are the starting link count
1462	 * subtracted by the total number of removes with the total
1463	 * links discovered back in.  An incomplete remove thus
1464	 * makes no change to the link count but an add increases
1465	 * by one.
1466	 */
1467	if (debug)
1468		printf(
1469		    "ino %ju nlink %ju newlinks %ju removes %ju dotlinks %ju\n",
1470		    (uintmax_t)ino, (uintmax_t)nlink, (uintmax_t)newlinks,
1471		    (uintmax_t)removes, (uintmax_t)dotlinks);
1472	nlink += newlinks;
1473	nlink -= removes;
1474	sino->si_linkadj = 1;
1475	sino->si_nlink = nlink;
1476	sino->si_dotlinks = dotlinks;
1477	sino->si_mode = mode;
1478	ino_adjust(sino);
1479}
1480
1481/*
1482 * Process records available for one block and determine whether it is
1483 * still allocated and whether the owning inode needs to be updated or
1484 * a free completed.
1485 */
1486static void
1487blk_check(struct suj_blk *sblk)
1488{
1489	struct suj_rec *srec;
1490	struct jblkrec *brec;
1491	struct suj_ino *sino;
1492	ufs2_daddr_t blk;
1493	int mask;
1494	int frags;
1495	int isat;
1496
1497	/*
1498	 * Each suj_blk actually contains records for any fragments in that
1499	 * block.  As a result we must evaluate each record individually.
1500	 */
1501	sino = NULL;
1502	TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
1503		brec = (struct jblkrec *)srec->sr_rec;
1504		frags = brec->jb_frags;
1505		blk = brec->jb_blkno + brec->jb_oldfrags;
1506		isat = blk_isat(brec->jb_ino, brec->jb_lbn, blk, &frags);
1507		if (sino == NULL || sino->si_ino != brec->jb_ino) {
1508			sino = ino_lookup(brec->jb_ino, 1);
1509			sino->si_blkadj = 1;
1510		}
1511		if (debug)
1512			printf("op %s blk %jd ino %ju lbn %jd frags %d isat %d "
1513			    "(%d)\n", JOP_OPTYPE(brec->jb_op), blk,
1514			    (uintmax_t)brec->jb_ino, brec->jb_lbn,
1515			    brec->jb_frags, isat, frags);
1516		/*
1517		 * If we found the block at this address we still have to
1518		 * determine if we need to free the tail end that was
1519		 * added by adding contiguous fragments from the same block.
1520		 */
1521		if (isat == 1) {
1522			if (frags == brec->jb_frags)
1523				continue;
1524			mask = blk_freemask(blk, brec->jb_ino, brec->jb_lbn,
1525			    brec->jb_frags);
1526			mask >>= frags;
1527			blk += frags;
1528			frags = brec->jb_frags - frags;
1529			blk_free(brec->jb_ino, blk, mask, frags);
1530			continue;
1531		}
1532		/*
1533	 	 * The block wasn't found, attempt to free it.  It won't be
1534		 * freed if it was actually reallocated.  If this was an
1535		 * allocation we don't want to follow indirects as they
1536		 * may not be written yet.  Any children of the indirect will
1537		 * have their own records.  If it's a free we need to
1538		 * recursively free children.
1539		 */
1540		blk_free_lbn(blk, brec->jb_ino, brec->jb_lbn, brec->jb_frags,
1541		    brec->jb_op == JOP_FREEBLK);
1542	}
1543}
1544
1545/*
1546 * Walk the list of inode records for this cg and resolve moved and duplicate
1547 * inode references now that we have a complete picture.
1548 */
1549static void
1550cg_build(struct suj_cg *sc)
1551{
1552	struct suj_ino *sino;
1553	int i;
1554
1555	for (i = 0; i < HASHSIZE; i++)
1556		LIST_FOREACH(sino, &sc->sc_inohash[i], si_next)
1557			ino_build(sino);
1558}
1559
1560/*
1561 * Handle inodes requiring truncation.  This must be done prior to
1562 * looking up any inodes in directories.
1563 */
1564static void
1565cg_trunc(struct suj_cg *sc)
1566{
1567	struct suj_ino *sino;
1568	int i;
1569
1570	for (i = 0; i < HASHSIZE; i++) {
1571		LIST_FOREACH(sino, &sc->sc_inohash[i], si_next) {
1572			if (sino->si_trunc) {
1573				ino_trunc(sino->si_ino,
1574				    sino->si_trunc->jt_size);
1575				sino->si_blkadj = 0;
1576				sino->si_trunc = NULL;
1577			}
1578			if (sino->si_blkadj)
1579				ino_adjblks(sino);
1580		}
1581	}
1582}
1583
1584static void
1585cg_adj_blk(struct suj_cg *sc)
1586{
1587	struct suj_ino *sino;
1588	int i;
1589
1590	for (i = 0; i < HASHSIZE; i++) {
1591		LIST_FOREACH(sino, &sc->sc_inohash[i], si_next) {
1592			if (sino->si_blkadj)
1593				ino_adjblks(sino);
1594		}
1595	}
1596}
1597
1598/*
1599 * Free any partially allocated blocks and then resolve inode block
1600 * counts.
1601 */
1602static void
1603cg_check_blk(struct suj_cg *sc)
1604{
1605	struct suj_blk *sblk;
1606	int i;
1607
1608
1609	for (i = 0; i < HASHSIZE; i++)
1610		LIST_FOREACH(sblk, &sc->sc_blkhash[i], sb_next)
1611			blk_check(sblk);
1612}
1613
1614/*
1615 * Walk the list of inode records for this cg, recovering any
1616 * changes which were not complete at the time of crash.
1617 */
1618static void
1619cg_check_ino(struct suj_cg *sc)
1620{
1621	struct suj_ino *sino;
1622	int i;
1623
1624	for (i = 0; i < HASHSIZE; i++)
1625		LIST_FOREACH(sino, &sc->sc_inohash[i], si_next)
1626			ino_check(sino);
1627}
1628
1629static void
1630cg_apply(void (*apply)(struct suj_cg *))
1631{
1632	struct suj_cg *scg;
1633	int i;
1634
1635	for (i = 0; i < HASHSIZE; i++)
1636		LIST_FOREACH(scg, &cghash[i], sc_next)
1637			apply(scg);
1638}
1639
1640/*
1641 * Process the unlinked but referenced file list.  Freeing all inodes.
1642 */
1643static void
1644ino_unlinked(void)
1645{
1646	struct inode ip;
1647	union dinode *dp;
1648	uint16_t mode;
1649	ino_t inon;
1650	ino_t ino;
1651
1652	ino = fs->fs_sujfree;
1653	fs->fs_sujfree = 0;
1654	while (ino != 0) {
1655		ginode(ino, &ip);
1656		dp = ip.i_dp;
1657		mode = DIP(dp, di_mode) & IFMT;
1658		inon = DIP(dp, di_freelink);
1659		DIP_SET(dp, di_freelink, 0);
1660		inodirty(&ip);
1661		/*
1662		 * XXX Should this be an errx?
1663		 */
1664		if (DIP(dp, di_nlink) == 0) {
1665			if (debug)
1666				printf("Freeing unlinked ino %ju mode %o\n",
1667				    (uintmax_t)ino, mode);
1668			ino_reclaim(&ip, ino, mode);
1669		} else if (debug)
1670			printf("Skipping ino %ju mode %o with link %d\n",
1671			    (uintmax_t)ino, mode, DIP(dp, di_nlink));
1672		ino = inon;
1673		irelse(&ip);
1674	}
1675}
1676
1677/*
1678 * Append a new record to the list of records requiring processing.
1679 */
1680static void
1681ino_append(union jrec *rec)
1682{
1683	struct jrefrec *refrec;
1684	struct jmvrec *mvrec;
1685	struct suj_ino *sino;
1686	struct suj_rec *srec;
1687
1688	mvrec = &rec->rec_jmvrec;
1689	refrec = &rec->rec_jrefrec;
1690	if (debug && mvrec->jm_op == JOP_MVREF)
1691		printf("ino move: ino %ju, parent %ju, "
1692		    "diroff %jd, oldoff %jd\n",
1693		    (uintmax_t)mvrec->jm_ino, (uintmax_t)mvrec->jm_parent,
1694		    (uintmax_t)mvrec->jm_newoff, (uintmax_t)mvrec->jm_oldoff);
1695	else if (debug &&
1696	    (refrec->jr_op == JOP_ADDREF || refrec->jr_op == JOP_REMREF))
1697		printf("ino ref: op %s, ino %ju, nlink %ju, "
1698		    "parent %ju, diroff %jd\n",
1699		    JOP_OPTYPE(refrec->jr_op), (uintmax_t)refrec->jr_ino,
1700		    (uintmax_t)refrec->jr_nlink,
1701		    (uintmax_t)refrec->jr_parent, (uintmax_t)refrec->jr_diroff);
1702	sino = ino_lookup(((struct jrefrec *)rec)->jr_ino, 1);
1703	sino->si_hasrecs = 1;
1704	srec = errmalloc(sizeof(*srec));
1705	srec->sr_rec = rec;
1706	TAILQ_INSERT_TAIL(&sino->si_newrecs, srec, sr_next);
1707}
1708
1709/*
1710 * Add a reference adjustment to the sino list and eliminate dups.  The
1711 * primary loop in ino_build_ref() checks for dups but new ones may be
1712 * created as a result of offset adjustments.
1713 */
1714static void
1715ino_add_ref(struct suj_ino *sino, struct suj_rec *srec)
1716{
1717	struct jrefrec *refrec;
1718	struct suj_rec *srn;
1719	struct jrefrec *rrn;
1720
1721	refrec = (struct jrefrec *)srec->sr_rec;
1722	/*
1723	 * We walk backwards so that the oldest link count is preserved.  If
1724	 * an add record conflicts with a remove keep the remove.  Redundant
1725	 * removes are eliminated in ino_build_ref.  Otherwise we keep the
1726	 * oldest record at a given location.
1727	 */
1728	for (srn = TAILQ_LAST(&sino->si_recs, srechd); srn;
1729	    srn = TAILQ_PREV(srn, srechd, sr_next)) {
1730		rrn = (struct jrefrec *)srn->sr_rec;
1731		if (rrn->jr_parent != refrec->jr_parent ||
1732		    rrn->jr_diroff != refrec->jr_diroff)
1733			continue;
1734		if (rrn->jr_op == JOP_REMREF || refrec->jr_op == JOP_ADDREF) {
1735			rrn->jr_mode = refrec->jr_mode;
1736			return;
1737		}
1738		/*
1739		 * Adding a remove.
1740		 *
1741		 * Replace the record in place with the old nlink in case
1742		 * we replace the head of the list.  Abandon srec as a dup.
1743		 */
1744		refrec->jr_nlink = rrn->jr_nlink;
1745		srn->sr_rec = srec->sr_rec;
1746		return;
1747	}
1748	TAILQ_INSERT_TAIL(&sino->si_recs, srec, sr_next);
1749}
1750
1751/*
1752 * Create a duplicate of a reference at a previous location.
1753 */
1754static void
1755ino_dup_ref(struct suj_ino *sino, struct jrefrec *refrec, off_t diroff)
1756{
1757	struct jrefrec *rrn;
1758	struct suj_rec *srn;
1759
1760	rrn = errmalloc(sizeof(*refrec));
1761	*rrn = *refrec;
1762	rrn->jr_op = JOP_ADDREF;
1763	rrn->jr_diroff = diroff;
1764	srn = errmalloc(sizeof(*srn));
1765	srn->sr_rec = (union jrec *)rrn;
1766	ino_add_ref(sino, srn);
1767}
1768
1769/*
1770 * Add a reference to the list at all known locations.  We follow the offset
1771 * changes for a single instance and create duplicate add refs at each so
1772 * that we can tolerate any version of the directory block.  Eliminate
1773 * removes which collide with adds that are seen in the journal.  They should
1774 * not adjust the link count down.
1775 */
1776static void
1777ino_build_ref(struct suj_ino *sino, struct suj_rec *srec)
1778{
1779	struct jrefrec *refrec;
1780	struct jmvrec *mvrec;
1781	struct suj_rec *srp;
1782	struct suj_rec *srn;
1783	struct jrefrec *rrn;
1784	off_t diroff;
1785
1786	refrec = (struct jrefrec *)srec->sr_rec;
1787	/*
1788	 * Search for a mvrec that matches this offset.  Whether it's an add
1789	 * or a remove we can delete the mvref after creating a dup record in
1790	 * the old location.
1791	 */
1792	if (!TAILQ_EMPTY(&sino->si_movs)) {
1793		diroff = refrec->jr_diroff;
1794		for (srn = TAILQ_LAST(&sino->si_movs, srechd); srn; srn = srp) {
1795			srp = TAILQ_PREV(srn, srechd, sr_next);
1796			mvrec = (struct jmvrec *)srn->sr_rec;
1797			if (mvrec->jm_parent != refrec->jr_parent ||
1798			    mvrec->jm_newoff != diroff)
1799				continue;
1800			diroff = mvrec->jm_oldoff;
1801			TAILQ_REMOVE(&sino->si_movs, srn, sr_next);
1802			free(srn);
1803			ino_dup_ref(sino, refrec, diroff);
1804		}
1805	}
1806	/*
1807	 * If a remove wasn't eliminated by an earlier add just append it to
1808	 * the list.
1809	 */
1810	if (refrec->jr_op == JOP_REMREF) {
1811		ino_add_ref(sino, srec);
1812		return;
1813	}
1814	/*
1815	 * Walk the list of records waiting to be added to the list.  We
1816	 * must check for moves that apply to our current offset and remove
1817	 * them from the list.  Remove any duplicates to eliminate removes
1818	 * with corresponding adds.
1819	 */
1820	TAILQ_FOREACH_SAFE(srn, &sino->si_newrecs, sr_next, srp) {
1821		switch (srn->sr_rec->rec_jrefrec.jr_op) {
1822		case JOP_ADDREF:
1823			/*
1824			 * This should actually be an error we should
1825			 * have a remove for every add journaled.
1826			 */
1827			rrn = (struct jrefrec *)srn->sr_rec;
1828			if (rrn->jr_parent != refrec->jr_parent ||
1829			    rrn->jr_diroff != refrec->jr_diroff)
1830				break;
1831			TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1832			break;
1833		case JOP_REMREF:
1834			/*
1835			 * Once we remove the current iteration of the
1836			 * record at this address we're done.
1837			 */
1838			rrn = (struct jrefrec *)srn->sr_rec;
1839			if (rrn->jr_parent != refrec->jr_parent ||
1840			    rrn->jr_diroff != refrec->jr_diroff)
1841				break;
1842			TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1843			ino_add_ref(sino, srec);
1844			return;
1845		case JOP_MVREF:
1846			/*
1847			 * Update our diroff based on any moves that match
1848			 * and remove the move.
1849			 */
1850			mvrec = (struct jmvrec *)srn->sr_rec;
1851			if (mvrec->jm_parent != refrec->jr_parent ||
1852			    mvrec->jm_oldoff != refrec->jr_diroff)
1853				break;
1854			ino_dup_ref(sino, refrec, mvrec->jm_oldoff);
1855			refrec->jr_diroff = mvrec->jm_newoff;
1856			TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1857			break;
1858		default:
1859			err_suj("ino_build_ref: Unknown op %s\n",
1860			    JOP_OPTYPE(srn->sr_rec->rec_jrefrec.jr_op));
1861		}
1862	}
1863	ino_add_ref(sino, srec);
1864}
1865
1866/*
1867 * Walk the list of new records and add them in-order resolving any
1868 * dups and adjusted offsets.
1869 */
1870static void
1871ino_build(struct suj_ino *sino)
1872{
1873	struct suj_rec *srec;
1874
1875	while ((srec = TAILQ_FIRST(&sino->si_newrecs)) != NULL) {
1876		TAILQ_REMOVE(&sino->si_newrecs, srec, sr_next);
1877		switch (srec->sr_rec->rec_jrefrec.jr_op) {
1878		case JOP_ADDREF:
1879		case JOP_REMREF:
1880			ino_build_ref(sino, srec);
1881			break;
1882		case JOP_MVREF:
1883			/*
1884			 * Add this mvrec to the queue of pending mvs.
1885			 */
1886			TAILQ_INSERT_TAIL(&sino->si_movs, srec, sr_next);
1887			break;
1888		default:
1889			err_suj("ino_build: Unknown op %s\n",
1890			    JOP_OPTYPE(srec->sr_rec->rec_jrefrec.jr_op));
1891		}
1892	}
1893	if (TAILQ_EMPTY(&sino->si_recs))
1894		sino->si_hasrecs = 0;
1895}
1896
1897/*
1898 * Modify journal records so they refer to the base block number
1899 * and a start and end frag range.  This is to facilitate the discovery
1900 * of overlapping fragment allocations.
1901 */
1902static void
1903blk_build(struct jblkrec *blkrec)
1904{
1905	struct suj_rec *srec;
1906	struct suj_blk *sblk;
1907	struct jblkrec *blkrn;
1908	ufs2_daddr_t blk;
1909	int frag;
1910
1911	if (debug)
1912		printf("blk_build: op %s blkno %jd frags %d oldfrags %d "
1913		    "ino %ju lbn %jd\n",
1914		    JOP_OPTYPE(blkrec->jb_op), (uintmax_t)blkrec->jb_blkno,
1915		    blkrec->jb_frags, blkrec->jb_oldfrags,
1916		    (uintmax_t)blkrec->jb_ino, (uintmax_t)blkrec->jb_lbn);
1917
1918	blk = blknum(fs, blkrec->jb_blkno);
1919	frag = fragnum(fs, blkrec->jb_blkno);
1920	if (blkrec->jb_blkno < 0 || blk + fs->fs_frag - frag > fs->fs_size)
1921		err_suj("Out-of-bounds journal block number %jd\n",
1922		    blkrec->jb_blkno);
1923	sblk = blk_lookup(blk, 1);
1924	/*
1925	 * Rewrite the record using oldfrags to indicate the offset into
1926	 * the block.  Leave jb_frags as the actual allocated count.
1927	 */
1928	blkrec->jb_blkno -= frag;
1929	blkrec->jb_oldfrags = frag;
1930	if (blkrec->jb_oldfrags + blkrec->jb_frags > fs->fs_frag)
1931		err_suj("Invalid fragment count %d oldfrags %d\n",
1932		    blkrec->jb_frags, frag);
1933	/*
1934	 * Detect dups.  If we detect a dup we always discard the oldest
1935	 * record as it is superseded by the new record.  This speeds up
1936	 * later stages but also eliminates free records which are used
1937	 * to indicate that the contents of indirects can be trusted.
1938	 */
1939	TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
1940		blkrn = (struct jblkrec *)srec->sr_rec;
1941		if (blkrn->jb_ino != blkrec->jb_ino ||
1942		    blkrn->jb_lbn != blkrec->jb_lbn ||
1943		    blkrn->jb_blkno != blkrec->jb_blkno ||
1944		    blkrn->jb_frags != blkrec->jb_frags ||
1945		    blkrn->jb_oldfrags != blkrec->jb_oldfrags)
1946			continue;
1947		if (debug)
1948			printf("Removed dup.\n");
1949		/* Discard the free which is a dup with an alloc. */
1950		if (blkrec->jb_op == JOP_FREEBLK)
1951			return;
1952		TAILQ_REMOVE(&sblk->sb_recs, srec, sr_next);
1953		free(srec);
1954		break;
1955	}
1956	srec = errmalloc(sizeof(*srec));
1957	srec->sr_rec = (union jrec *)blkrec;
1958	TAILQ_INSERT_TAIL(&sblk->sb_recs, srec, sr_next);
1959}
1960
1961static void
1962ino_build_trunc(struct jtrncrec *rec)
1963{
1964	struct suj_ino *sino;
1965
1966	if (debug)
1967		printf("ino_build_trunc: op %d ino %ju, size %jd\n",
1968		    rec->jt_op, (uintmax_t)rec->jt_ino,
1969		    (uintmax_t)rec->jt_size);
1970	if (chkfilesize(IFREG, rec->jt_size) == 0)
1971		err_suj("ino_build: truncation size too large %ju\n",
1972		    (intmax_t)rec->jt_size);
1973	sino = ino_lookup(rec->jt_ino, 1);
1974	if (rec->jt_op == JOP_SYNC) {
1975		sino->si_trunc = NULL;
1976		return;
1977	}
1978	if (sino->si_trunc == NULL || sino->si_trunc->jt_size > rec->jt_size)
1979		sino->si_trunc = rec;
1980}
1981
1982/*
1983 * Build up tables of the operations we need to recover.
1984 */
1985static void
1986suj_build(void)
1987{
1988	struct suj_seg *seg;
1989	union jrec *rec;
1990	int off;
1991	int i;
1992
1993	TAILQ_FOREACH(seg, &allsegs, ss_next) {
1994		if (debug)
1995			printf("seg %jd has %d records, oldseq %jd.\n",
1996			    seg->ss_rec.jsr_seq, seg->ss_rec.jsr_cnt,
1997			    seg->ss_rec.jsr_oldest);
1998		off = 0;
1999		rec = (union jrec *)seg->ss_blk;
2000		for (i = 0; i < seg->ss_rec.jsr_cnt; off += JREC_SIZE, rec++) {
2001			/* skip the segrec. */
2002			if ((off % real_dev_bsize) == 0)
2003				continue;
2004			switch (rec->rec_jrefrec.jr_op) {
2005			case JOP_ADDREF:
2006			case JOP_REMREF:
2007			case JOP_MVREF:
2008				ino_append(rec);
2009				break;
2010			case JOP_NEWBLK:
2011			case JOP_FREEBLK:
2012				blk_build((struct jblkrec *)rec);
2013				break;
2014			case JOP_TRUNC:
2015			case JOP_SYNC:
2016				ino_build_trunc((struct jtrncrec *)rec);
2017				break;
2018			default:
2019				err_suj("Unknown journal operation %s at %d\n",
2020				    JOP_OPTYPE(rec->rec_jrefrec.jr_op), off);
2021			}
2022			i++;
2023		}
2024	}
2025}
2026
2027/*
2028 * Prune the journal segments to those we care about based on the
2029 * oldest sequence in the newest segment.  Order the segment list
2030 * based on sequence number.
2031 */
2032static void
2033suj_prune(void)
2034{
2035	struct suj_seg *seg;
2036	struct suj_seg *segn;
2037	uint64_t newseq;
2038	int discard;
2039
2040	if (debug)
2041		printf("Pruning up to %jd\n", oldseq);
2042	/* First free the expired segments. */
2043	TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2044		if (seg->ss_rec.jsr_seq >= oldseq)
2045			continue;
2046		TAILQ_REMOVE(&allsegs, seg, ss_next);
2047		free(seg->ss_blk);
2048		free(seg);
2049	}
2050	/* Next ensure that segments are ordered properly. */
2051	seg = TAILQ_FIRST(&allsegs);
2052	if (seg == NULL) {
2053		if (debug)
2054			printf("Empty journal\n");
2055		return;
2056	}
2057	newseq = seg->ss_rec.jsr_seq;
2058	for (;;) {
2059		seg = TAILQ_LAST(&allsegs, seghd);
2060		if (seg->ss_rec.jsr_seq >= newseq)
2061			break;
2062		TAILQ_REMOVE(&allsegs, seg, ss_next);
2063		TAILQ_INSERT_HEAD(&allsegs, seg, ss_next);
2064		newseq = seg->ss_rec.jsr_seq;
2065
2066	}
2067	if (newseq != oldseq) {
2068		TAILQ_FOREACH(seg, &allsegs, ss_next) {
2069			printf("%jd, ", seg->ss_rec.jsr_seq);
2070		}
2071		printf("\n");
2072		err_suj("Journal file sequence mismatch %jd != %jd\n",
2073		    newseq, oldseq);
2074	}
2075	/*
2076	 * The kernel may asynchronously write segments which can create
2077	 * gaps in the sequence space.  Throw away any segments after the
2078	 * gap as the kernel guarantees only those that are contiguously
2079	 * reachable are marked as completed.
2080	 */
2081	discard = 0;
2082	TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2083		if (!discard && newseq++ == seg->ss_rec.jsr_seq) {
2084			jrecs += seg->ss_rec.jsr_cnt;
2085			jbytes += seg->ss_rec.jsr_blocks * real_dev_bsize;
2086			continue;
2087		}
2088		discard = 1;
2089		if (debug)
2090			printf("Journal order mismatch %jd != %jd pruning\n",
2091			    newseq-1, seg->ss_rec.jsr_seq);
2092		TAILQ_REMOVE(&allsegs, seg, ss_next);
2093		free(seg->ss_blk);
2094		free(seg);
2095	}
2096	if (debug)
2097		printf("Processing journal segments from %jd to %jd\n",
2098		    oldseq, newseq-1);
2099}
2100
2101/*
2102 * Verify the journal inode before attempting to read records.
2103 */
2104static int
2105suj_verifyino(union dinode *dp)
2106{
2107
2108	if (DIP(dp, di_nlink) != 1) {
2109		printf("Invalid link count %d for journal inode %ju\n",
2110		    DIP(dp, di_nlink), (uintmax_t)sujino);
2111		return (-1);
2112	}
2113
2114	if ((DIP(dp, di_flags) & (SF_IMMUTABLE | SF_NOUNLINK)) !=
2115	    (SF_IMMUTABLE | SF_NOUNLINK)) {
2116		printf("Invalid flags 0x%X for journal inode %ju\n",
2117		    DIP(dp, di_flags), (uintmax_t)sujino);
2118		return (-1);
2119	}
2120
2121	if (DIP(dp, di_mode) != (IFREG | IREAD)) {
2122		printf("Invalid mode %o for journal inode %ju\n",
2123		    DIP(dp, di_mode), (uintmax_t)sujino);
2124		return (-1);
2125	}
2126
2127	if (DIP(dp, di_size) < SUJ_MIN) {
2128		printf("Invalid size %jd for journal inode %ju\n",
2129		    DIP(dp, di_size), (uintmax_t)sujino);
2130		return (-1);
2131	}
2132
2133	if (DIP(dp, di_modrev) != fs->fs_mtime) {
2134		if (!bkgrdcheck || debug)
2135			printf("Journal timestamp does not match "
2136			    "fs mount time\n");
2137		return (-1);
2138	}
2139
2140	return (0);
2141}
2142
2143struct jblocks {
2144	struct jextent *jb_extent;	/* Extent array. */
2145	int		jb_avail;	/* Available extents. */
2146	int		jb_used;	/* Last used extent. */
2147	int		jb_head;	/* Allocator head. */
2148	int		jb_off;		/* Allocator extent offset. */
2149};
2150struct jextent {
2151	ufs2_daddr_t	je_daddr;	/* Disk block address. */
2152	int		je_blocks;	/* Disk block count. */
2153};
2154
2155static struct jblocks *suj_jblocks;
2156
2157static struct jblocks *
2158jblocks_create(void)
2159{
2160	struct jblocks *jblocks;
2161	int size;
2162
2163	jblocks = errmalloc(sizeof(*jblocks));
2164	jblocks->jb_avail = 10;
2165	jblocks->jb_used = 0;
2166	jblocks->jb_head = 0;
2167	jblocks->jb_off = 0;
2168	size = sizeof(struct jextent) * jblocks->jb_avail;
2169	jblocks->jb_extent = errmalloc(size);
2170	bzero(jblocks->jb_extent, size);
2171
2172	return (jblocks);
2173}
2174
2175/*
2176 * Return the next available disk block and the amount of contiguous
2177 * free space it contains.
2178 */
2179static ufs2_daddr_t
2180jblocks_next(struct jblocks *jblocks, int bytes, int *actual)
2181{
2182	struct jextent *jext;
2183	ufs2_daddr_t daddr;
2184	int freecnt;
2185	int blocks;
2186
2187	blocks = btodb(bytes);
2188	jext = &jblocks->jb_extent[jblocks->jb_head];
2189	freecnt = jext->je_blocks - jblocks->jb_off;
2190	if (freecnt == 0) {
2191		jblocks->jb_off = 0;
2192		if (++jblocks->jb_head > jblocks->jb_used)
2193			return (0);
2194		jext = &jblocks->jb_extent[jblocks->jb_head];
2195		freecnt = jext->je_blocks;
2196	}
2197	if (freecnt > blocks)
2198		freecnt = blocks;
2199	*actual = dbtob(freecnt);
2200	daddr = jext->je_daddr + jblocks->jb_off;
2201
2202	return (daddr);
2203}
2204
2205/*
2206 * Advance the allocation head by a specified number of bytes, consuming
2207 * one journal segment.
2208 */
2209static void
2210jblocks_advance(struct jblocks *jblocks, int bytes)
2211{
2212
2213	jblocks->jb_off += btodb(bytes);
2214}
2215
2216static void
2217jblocks_destroy(struct jblocks *jblocks)
2218{
2219
2220	free(jblocks->jb_extent);
2221	free(jblocks);
2222}
2223
2224static void
2225jblocks_add(struct jblocks *jblocks, ufs2_daddr_t daddr, int blocks)
2226{
2227	struct jextent *jext;
2228	int size;
2229
2230	jext = &jblocks->jb_extent[jblocks->jb_used];
2231	/* Adding the first block. */
2232	if (jext->je_daddr == 0) {
2233		jext->je_daddr = daddr;
2234		jext->je_blocks = blocks;
2235		return;
2236	}
2237	/* Extending the last extent. */
2238	if (jext->je_daddr + jext->je_blocks == daddr) {
2239		jext->je_blocks += blocks;
2240		return;
2241	}
2242	/* Adding a new extent. */
2243	if (++jblocks->jb_used == jblocks->jb_avail) {
2244		jblocks->jb_avail *= 2;
2245		size = sizeof(struct jextent) * jblocks->jb_avail;
2246		jext = errmalloc(size);
2247		bzero(jext, size);
2248		bcopy(jblocks->jb_extent, jext,
2249		    sizeof(struct jextent) * jblocks->jb_used);
2250		free(jblocks->jb_extent);
2251		jblocks->jb_extent = jext;
2252	}
2253	jext = &jblocks->jb_extent[jblocks->jb_used];
2254	jext->je_daddr = daddr;
2255	jext->je_blocks = blocks;
2256
2257	return;
2258}
2259
2260/*
2261 * Add a file block from the journal to the extent map.  We can't read
2262 * each file block individually because the kernel treats it as a circular
2263 * buffer and segments may span multiple contiguous blocks.
2264 */
2265static void
2266suj_add_block(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
2267{
2268
2269	jblocks_add(suj_jblocks, fsbtodb(fs, blk), fsbtodb(fs, frags));
2270}
2271
2272static void
2273suj_read(void)
2274{
2275	uint8_t block[1 * 1024 * 1024] __aligned(LIBUFS_BUFALIGN);
2276	struct suj_seg *seg;
2277	struct jsegrec *recn;
2278	struct jsegrec *rec;
2279	ufs2_daddr_t blk;
2280	int readsize;
2281	int blocks;
2282	int recsize;
2283	int size;
2284	int i;
2285
2286	/*
2287	 * Read records until we exhaust the journal space.  If we find
2288	 * an invalid record we start searching for a valid segment header
2289	 * at the next block.  This is because we don't have a head/tail
2290	 * pointer and must recover the information indirectly.  At the gap
2291	 * between the head and tail we won't necessarily have a valid
2292	 * segment.
2293	 */
2294restart:
2295	for (;;) {
2296		size = sizeof(block);
2297		blk = jblocks_next(suj_jblocks, size, &readsize);
2298		if (blk == 0)
2299			return;
2300		size = readsize;
2301		/*
2302		 * Read 1MB at a time and scan for records within this block.
2303		 */
2304		if (pread(fsreadfd, &block, size, dbtob(blk)) != size) {
2305			err_suj("Error reading journal block %jd\n",
2306			    (intmax_t)blk);
2307		}
2308		for (rec = (void *)block; size; size -= recsize,
2309		    rec = (struct jsegrec *)((uintptr_t)rec + recsize)) {
2310			recsize = real_dev_bsize;
2311			if (rec->jsr_time != fs->fs_mtime) {
2312#ifdef notdef
2313				if (debug)
2314					printf("Rec time %jd != fs mtime %jd\n",
2315					    rec->jsr_time, fs->fs_mtime);
2316#endif
2317				jblocks_advance(suj_jblocks, recsize);
2318				continue;
2319			}
2320			if (rec->jsr_cnt == 0) {
2321				if (debug)
2322					printf("Found illegal count %d\n",
2323					    rec->jsr_cnt);
2324				jblocks_advance(suj_jblocks, recsize);
2325				continue;
2326			}
2327			blocks = rec->jsr_blocks;
2328			recsize = blocks * real_dev_bsize;
2329			if (recsize > size) {
2330				/*
2331				 * We may just have run out of buffer, restart
2332				 * the loop to re-read from this spot.
2333				 */
2334				if (size < fs->fs_bsize &&
2335				    size != readsize &&
2336				    recsize <= fs->fs_bsize)
2337					goto restart;
2338				if (debug)
2339					printf("Found invalid segsize "
2340					    "%d > %d\n", recsize, size);
2341				recsize = real_dev_bsize;
2342				jblocks_advance(suj_jblocks, recsize);
2343				continue;
2344			}
2345			/*
2346			 * Verify that all blocks in the segment are present.
2347			 */
2348			for (i = 1; i < blocks; i++) {
2349				recn = (void *)((uintptr_t)rec) + i *
2350				    real_dev_bsize;
2351				if (recn->jsr_seq == rec->jsr_seq &&
2352				    recn->jsr_time == rec->jsr_time)
2353					continue;
2354				if (debug)
2355					printf("Incomplete record %jd (%d)\n",
2356					    rec->jsr_seq, i);
2357				recsize = i * real_dev_bsize;
2358				jblocks_advance(suj_jblocks, recsize);
2359				goto restart;
2360			}
2361			seg = errmalloc(sizeof(*seg));
2362			seg->ss_blk = errmalloc(recsize);
2363			seg->ss_rec = *rec;
2364			bcopy((void *)rec, seg->ss_blk, recsize);
2365			if (rec->jsr_oldest > oldseq)
2366				oldseq = rec->jsr_oldest;
2367			TAILQ_INSERT_TAIL(&allsegs, seg, ss_next);
2368			jblocks_advance(suj_jblocks, recsize);
2369		}
2370	}
2371}
2372
2373/*
2374 * Orchestrate the verification of a filesystem via the softupdates journal.
2375 */
2376int
2377suj_check(const char *filesys)
2378{
2379	struct inodesc idesc;
2380	struct csum *cgsum;
2381	union dinode *dp, *jip;
2382	struct inode ip;
2383	uint64_t blocks;
2384	int i, retval;
2385	struct suj_seg *seg;
2386	struct suj_seg *segn;
2387
2388	initsuj();
2389	fs = &sblock;
2390	if (real_dev_bsize == 0 && ioctl(fsreadfd, DIOCGSECTORSIZE,
2391	    &real_dev_bsize) == -1)
2392		real_dev_bsize = secsize;
2393	if (debug)
2394		printf("dev_bsize %u\n", real_dev_bsize);
2395
2396	/*
2397	 * Set an exit point when SUJ check failed
2398	 */
2399	retval = setjmp(jmpbuf);
2400	if (retval != 0) {
2401		pwarn("UNEXPECTED SU+J INCONSISTENCY\n");
2402		TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2403			TAILQ_REMOVE(&allsegs, seg, ss_next);
2404				free(seg->ss_blk);
2405				free(seg);
2406		}
2407		if (reply("FALLBACK TO FULL FSCK") == 0) {
2408			ckfini(0);
2409			exit(EEXIT);
2410		} else
2411			return (-1);
2412	}
2413
2414	/*
2415	 * Search the root directory for the SUJ_FILE.
2416	 */
2417	idesc.id_type = DATA;
2418	idesc.id_fix = IGNORE;
2419	idesc.id_number = UFS_ROOTINO;
2420	idesc.id_func = findino;
2421	idesc.id_name = SUJ_FILE;
2422	ginode(UFS_ROOTINO, &ip);
2423	dp = ip.i_dp;
2424	if ((DIP(dp, di_mode) & IFMT) != IFDIR) {
2425		irelse(&ip);
2426		err_suj("root inode is not a directory\n");
2427	}
2428	if (DIP(dp, di_size) < 0 || DIP(dp, di_size) > MAXDIRSIZE) {
2429		irelse(&ip);
2430		err_suj("negative or oversized root directory %jd\n",
2431		    (uintmax_t)DIP(dp, di_size));
2432	}
2433	if ((ckinode(dp, &idesc) & FOUND) == FOUND) {
2434		sujino = idesc.id_parent;
2435		irelse(&ip);
2436	} else {
2437		if (!bkgrdcheck || debug)
2438			printf("Journal inode removed.  "
2439			    "Use tunefs to re-create.\n");
2440		sblock.fs_flags &= ~FS_SUJ;
2441		sblock.fs_sujfree = 0;
2442		irelse(&ip);
2443		return (-1);
2444	}
2445	/*
2446	 * Fetch the journal inode and verify it.
2447	 */
2448	ginode(sujino, &ip);
2449	jip = ip.i_dp;
2450	if (!bkgrdcheck || debug)
2451		printf("** SU+J Recovering %s\n", filesys);
2452	if (suj_verifyino(jip) != 0 || (!preen && !reply("USE JOURNAL"))) {
2453		irelse(&ip);
2454		return (-1);
2455	}
2456	/*
2457	 * Build a list of journal blocks in jblocks before parsing the
2458	 * available journal blocks in with suj_read().
2459	 */
2460	if (!bkgrdcheck || debug)
2461		printf("** Reading %jd byte journal from inode %ju.\n",
2462		    DIP(jip, di_size), (uintmax_t)sujino);
2463	suj_jblocks = jblocks_create();
2464	blocks = ino_visit(jip, sujino, suj_add_block, 0);
2465	if (blocks != numfrags(fs, DIP(jip, di_size))) {
2466		if (!bkgrdcheck || debug)
2467			printf("Sparse journal inode %ju.\n",
2468			    (uintmax_t)sujino);
2469		irelse(&ip);
2470		return (-1);
2471	}
2472	/* If journal is valid then do journal check rather than background */
2473	if (bkgrdcheck) {
2474		irelse(&ip);
2475		return (0);
2476	}
2477	irelse(&ip);
2478	suj_read();
2479	jblocks_destroy(suj_jblocks);
2480	suj_jblocks = NULL;
2481	if (preen || reply("RECOVER")) {
2482		printf("** Building recovery table.\n");
2483		suj_prune();
2484		suj_build();
2485		cg_apply(cg_build);
2486		printf("** Resolving unreferenced inode list.\n");
2487		ino_unlinked();
2488		printf("** Processing journal entries.\n");
2489		cg_apply(cg_trunc);
2490		cg_apply(cg_check_blk);
2491		cg_apply(cg_adj_blk);
2492		cg_apply(cg_check_ino);
2493	}
2494	if (preen == 0 && (jrecs > 0 || jbytes > 0) &&
2495	    reply("WRITE CHANGES") == 0)
2496		return (0);
2497	/*
2498	 * Check block counts of snapshot inodes and
2499	 * make copies of any needed snapshot blocks.
2500	 */
2501	for (i = 0; i < snapcnt; i++)
2502		check_blkcnt(&snaplist[i]);
2503	snapflush(suj_checkblkavail);
2504	/*
2505	 * Recompute the fs summary info from correct cs summaries.
2506	 */
2507	bzero(&fs->fs_cstotal, sizeof(struct csum_total));
2508	for (i = 0; i < fs->fs_ncg; i++) {
2509		cgsum = &fs->fs_cs(fs, i);
2510		fs->fs_cstotal.cs_nffree += cgsum->cs_nffree;
2511		fs->fs_cstotal.cs_nbfree += cgsum->cs_nbfree;
2512		fs->fs_cstotal.cs_nifree += cgsum->cs_nifree;
2513		fs->fs_cstotal.cs_ndir += cgsum->cs_ndir;
2514	}
2515	fs->fs_pendinginodes = 0;
2516	fs->fs_pendingblocks = 0;
2517	fs->fs_clean = 1;
2518	fs->fs_time = time(NULL);
2519	fs->fs_mtime = time(NULL);
2520	sbdirty();
2521	ckfini(1);
2522	if (jrecs > 0 || jbytes > 0) {
2523		printf("** %jd journal records in %jd bytes for %.2f%% "
2524		    "utilization\n", jrecs, jbytes,
2525		    ((float)jrecs / (float)(jbytes / JREC_SIZE)) * 100);
2526		printf("** Freed %jd inodes (%jd dirs) %jd blocks, and %jd "
2527		    "frags.\n", freeinos, freedir, freeblocks, freefrags);
2528	}
2529
2530	return (0);
2531}
2532
2533static void
2534initsuj(void)
2535{
2536	int i;
2537
2538	for (i = 0; i < HASHSIZE; i++)
2539		LIST_INIT(&cghash[i]);
2540	lastcg = NULL;
2541	TAILQ_INIT(&allsegs);
2542	oldseq = 0;
2543	fs = NULL;
2544	sujino = 0;
2545	freefrags = 0;
2546	freeblocks = 0;
2547	freeinos = 0;
2548	freedir = 0;
2549	jbytes = 0;
2550	jrecs = 0;
2551	suj_jblocks = NULL;
2552}
2553