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