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