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