suj.c revision 207144
111820Sjulian/*-
211820Sjulian * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
311820Sjulian * All rights reserved.
411820Sjulian *
511820Sjulian * Redistribution and use in source and binary forms, with or without
611820Sjulian * modification, are permitted provided that the following conditions
711820Sjulian * are met:
811820Sjulian * 1. Redistributions of source code must retain the above copyright
911820Sjulian *    notice, this list of conditions and the following disclaimer.
1011820Sjulian * 2. Redistributions in binary form must reproduce the above copyright
1111820Sjulian *    notice, this list of conditions and the following disclaimer in the
1211820Sjulian *    documentation and/or other materials provided with the distribution.
1311820Sjulian *
1411820Sjulian * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
1511820Sjulian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1611820Sjulian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1711820Sjulian * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
1811820Sjulian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1911820Sjulian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2011820Sjulian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2111820Sjulian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2211820Sjulian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2311820Sjulian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2411820Sjulian * SUCH DAMAGE.
2511820Sjulian */
2611820Sjulian
2711820Sjulian#include <sys/cdefs.h>
2811820Sjulian__FBSDID("$FreeBSD: head/sbin/fsck_ffs/suj.c 207144 2010-04-24 07:58:59Z pjd $");
2911820Sjulian
3011820Sjulian#include <sys/param.h>
3111820Sjulian#include <sys/disklabel.h>
3211820Sjulian#include <sys/mount.h>
3311820Sjulian#include <sys/stat.h>
3411820Sjulian
3511820Sjulian#include <ufs/ufs/ufsmount.h>
3611820Sjulian#include <ufs/ufs/dinode.h>
3711820Sjulian#include <ufs/ufs/dir.h>
3811820Sjulian#include <ufs/ffs/fs.h>
3911820Sjulian
4097632Swollman#include <stdio.h>
4111820Sjulian#include <stdlib.h>
4297632Swollman#include <stdint.h>
4397632Swollman#include <libufs.h>
4497632Swollman#include <string.h>
4511820Sjulian#include <strings.h>
4611820Sjulian#include <err.h>
4711820Sjulian#include <assert.h>
4811820Sjulian
4911820Sjulian#include "fsck.h"
5011820Sjulian
5111820Sjulian#define	DOTDOT_OFFSET	DIRECTSIZ(1)
5211820Sjulian#define	SUJ_HASHSIZE	2048
5311820Sjulian#define	SUJ_HASHMASK	(SUJ_HASHSIZE - 1)
5411820Sjulian#define	SUJ_HASH(x)	((x * 2654435761) & SUJ_HASHMASK)
5511820Sjulian
5611820Sjulianstruct suj_seg {
5711820Sjulian	TAILQ_ENTRY(suj_seg) ss_next;
5811820Sjulian	struct jsegrec	ss_rec;
5911820Sjulian	uint8_t		*ss_blk;
6011820Sjulian};
6111820Sjulian
6297632Swollmanstruct suj_rec {
6311820Sjulian	TAILQ_ENTRY(suj_rec) sr_next;
6411820Sjulian	union jrec	*sr_rec;
6511820Sjulian};
6611820SjulianTAILQ_HEAD(srechd, suj_rec);
6711820Sjulian
6811820Sjulianstruct suj_ino {
6911820Sjulian	LIST_ENTRY(suj_ino)	si_next;
7011820Sjulian	struct srechd		si_recs;
7111820Sjulian	struct srechd		si_newrecs;
7211820Sjulian	struct srechd		si_movs;
7311820Sjulian	struct jtrncrec		*si_trunc;
7411820Sjulian	ino_t			si_ino;
7511820Sjulian	char			si_skipparent;
7611820Sjulian	char			si_hasrecs;
7711820Sjulian	char			si_blkadj;
7811820Sjulian	char			si_linkadj;
7911820Sjulian	int			si_mode;
8011820Sjulian	nlink_t			si_nlinkadj;
8111820Sjulian	nlink_t			si_nlink;
8211820Sjulian	nlink_t			si_dotlinks;
8311820Sjulian};
8411820SjulianLIST_HEAD(inohd, suj_ino);
8511820Sjulian
8611820Sjulianstruct suj_blk {
8711820Sjulian	LIST_ENTRY(suj_blk)	sb_next;
8811820Sjulian	struct srechd		sb_recs;
8911820Sjulian	ufs2_daddr_t		sb_blk;
9011820Sjulian};
9111820SjulianLIST_HEAD(blkhd, suj_blk);
9211820Sjulian
9311820Sjulianstruct data_blk {
9411820Sjulian	LIST_ENTRY(data_blk)	db_next;
9511820Sjulian	uint8_t			*db_buf;
9611820Sjulian	ufs2_daddr_t		db_blk;
9711820Sjulian	int			db_size;
9811820Sjulian	int			db_dirty;
9911820Sjulian};
10011820Sjulian
10111820Sjulianstruct ino_blk {
10211820Sjulian	LIST_ENTRY(ino_blk)	ib_next;
10311820Sjulian	uint8_t			*ib_buf;
10411820Sjulian	int			ib_dirty;
10511820Sjulian	ufs2_daddr_t		ib_blk;
10611820Sjulian};
10711820SjulianLIST_HEAD(iblkhd, ino_blk);
10811820Sjulian
10911820Sjulianstruct suj_cg {
11011820Sjulian	LIST_ENTRY(suj_cg)	sc_next;
11111820Sjulian	struct blkhd		sc_blkhash[SUJ_HASHSIZE];
11211820Sjulian	struct inohd		sc_inohash[SUJ_HASHSIZE];
11311820Sjulian	struct iblkhd		sc_iblkhash[SUJ_HASHSIZE];
11411820Sjulian	struct ino_blk		*sc_lastiblk;
11511820Sjulian	struct suj_ino		*sc_lastino;
11611820Sjulian	struct suj_blk		*sc_lastblk;
11711820Sjulian	uint8_t			*sc_cgbuf;
11811820Sjulian	struct cg		*sc_cgp;
11911820Sjulian	int			sc_dirty;
12011820Sjulian	int			sc_cgx;
12111820Sjulian};
12211820Sjulian
12311820SjulianLIST_HEAD(cghd, suj_cg) cghash[SUJ_HASHSIZE];
12411820SjulianLIST_HEAD(dblkhd, data_blk) dbhash[SUJ_HASHSIZE];
12511820Sjulianstruct suj_cg *lastcg;
12611820Sjulianstruct data_blk *lastblk;
12711820Sjulian
12811820SjulianTAILQ_HEAD(seghd, suj_seg) allsegs;
12911820Sjulianuint64_t oldseq;
13011820Sjulianstatic struct uufsd *disk = NULL;
13111820Sjulianstatic struct fs *fs = NULL;
13211820Sjulianino_t sujino;
13311820Sjulian
13411820Sjulian/*
13511820Sjulian * Summary statistics.
13611820Sjulian */
13711820Sjulianuint64_t freefrags;
13811820Sjulianuint64_t freeblocks;
13911820Sjulianuint64_t freeinos;
14011820Sjulianuint64_t freedir;
14111820Sjulianuint64_t jbytes;
14211820Sjulianuint64_t jrecs;
14311820Sjulian
14411820Sjuliantypedef void (*ino_visitor)(ino_t, ufs_lbn_t, ufs2_daddr_t, int);
14511820Sjulianstatic void ino_trunc(ino_t, off_t);
14611820Sjulianstatic void ino_decr(ino_t);
14711820Sjulianstatic void ino_adjust(struct suj_ino *);
14811820Sjulianstatic void ino_build(struct suj_ino *);
14911820Sjulianstatic int blk_isfree(ufs2_daddr_t);
15011820Sjulian
15111820Sjulianstatic void *
15211820Sjulianerrmalloc(size_t n)
15311820Sjulian{
15411820Sjulian	void *a;
15511820Sjulian
15611820Sjulian	a = malloc(n);
15711820Sjulian	if (a == NULL)
15811820Sjulian		errx(1, "malloc(%zu)", n);
15911820Sjulian	return (a);
16011820Sjulian}
16111820Sjulian
16211820Sjulian/*
16311820Sjulian * Open the given provider, load superblock.
16411820Sjulian */
16511820Sjulianstatic void
16611820Sjulianopendisk(const char *devnam)
16711820Sjulian{
16811820Sjulian	if (disk != NULL)
16911820Sjulian		return;
17011820Sjulian	disk = malloc(sizeof(*disk));
17111820Sjulian	if (disk == NULL)
17211820Sjulian		errx(1, "malloc(%zu)", sizeof(*disk));
17311820Sjulian	if (ufs_disk_fillout(disk, devnam) == -1) {
17411820Sjulian		err(1, "ufs_disk_fillout(%s) failed: %s", devnam,
17511820Sjulian		    disk->d_error);
17611820Sjulian	}
17711820Sjulian	fs = &disk->d_fs;
17811820Sjulian}
17911820Sjulian
18011820Sjulian/*
18111820Sjulian * Mark file system as clean, write the super-block back, close the disk.
18211820Sjulian */
18311820Sjulianstatic void
18411820Sjulianclosedisk(const char *devnam)
18511820Sjulian{
18611820Sjulian	struct csum *cgsum;
18711820Sjulian	int i;
18811820Sjulian
18911820Sjulian	/*
19011820Sjulian	 * Recompute the fs summary info from correct cs summaries.
19111820Sjulian	 */
19211820Sjulian	bzero(&fs->fs_cstotal, sizeof(struct csum_total));
19311820Sjulian	for (i = 0; i < fs->fs_ncg; i++) {
19411820Sjulian		cgsum = &fs->fs_cs(fs, i);
19511820Sjulian		fs->fs_cstotal.cs_nffree += cgsum->cs_nffree;
19611820Sjulian		fs->fs_cstotal.cs_nbfree += cgsum->cs_nbfree;
19711820Sjulian		fs->fs_cstotal.cs_nifree += cgsum->cs_nifree;
19811820Sjulian		fs->fs_cstotal.cs_ndir += cgsum->cs_ndir;
19911820Sjulian	}
20011820Sjulian	fs->fs_pendinginodes = 0;
20111820Sjulian	fs->fs_pendingblocks = 0;
20211820Sjulian	fs->fs_clean = 1;
20311820Sjulian	fs->fs_time = time(NULL);
20411820Sjulian	fs->fs_mtime = time(NULL);
20511820Sjulian	if (sbwrite(disk, 0) == -1)
20611820Sjulian		err(1, "sbwrite(%s)", devnam);
20711820Sjulian	if (ufs_disk_close(disk) == -1)
20811820Sjulian		err(1, "ufs_disk_close(%s)", devnam);
20911820Sjulian	free(disk);
21011820Sjulian	disk = NULL;
21111820Sjulian	fs = NULL;
21211820Sjulian}
21311820Sjulian
21411820Sjulian/*
21511820Sjulian * Lookup a cg by number in the hash so we can keep track of which cgs
21611820Sjulian * need stats rebuilt.
21711820Sjulian */
21811820Sjulianstatic struct suj_cg *
21911820Sjuliancg_lookup(int cgx)
22011820Sjulian{
22111820Sjulian	struct cghd *hd;
22211820Sjulian	struct suj_cg *sc;
22311820Sjulian
22427244Sjhay	if (cgx < 0 || cgx >= fs->fs_ncg) {
22527244Sjhay		abort();
22627244Sjhay		errx(1, "Bad cg number %d", cgx);
22727244Sjhay	}
22827244Sjhay	if (lastcg && lastcg->sc_cgx == cgx)
22927244Sjhay		return (lastcg);
23027244Sjhay	hd = &cghash[SUJ_HASH(cgx)];
23127244Sjhay	LIST_FOREACH(sc, hd, sc_next)
23227244Sjhay		if (sc->sc_cgx == cgx) {
23327244Sjhay			lastcg = sc;
23427244Sjhay			return (sc);
23527244Sjhay		}
23627244Sjhay	sc = errmalloc(sizeof(*sc));
23727244Sjhay	bzero(sc, sizeof(*sc));
23827244Sjhay	sc->sc_cgbuf = errmalloc(fs->fs_bsize);
23927244Sjhay	sc->sc_cgp = (struct cg *)sc->sc_cgbuf;
24027244Sjhay	sc->sc_cgx = cgx;
24127244Sjhay	LIST_INSERT_HEAD(hd, sc, sc_next);
24227244Sjhay	if (bread(disk, fsbtodb(fs, cgtod(fs, sc->sc_cgx)), sc->sc_cgbuf,
24327244Sjhay	    fs->fs_bsize) == -1)
24427244Sjhay		err(1, "Unable to read cylinder group %d", sc->sc_cgx);
24527244Sjhay
24627244Sjhay	return (sc);
24727244Sjhay}
24827244Sjhay
24927244Sjhay/*
25027244Sjhay * Lookup an inode number in the hash and allocate a suj_ino if it does
25127244Sjhay * not exist.
25227244Sjhay */
25327244Sjhaystatic struct suj_ino *
25427244Sjhayino_lookup(ino_t ino, int creat)
25527244Sjhay{
25627244Sjhay	struct suj_ino *sino;
25727244Sjhay	struct inohd *hd;
25827244Sjhay	struct suj_cg *sc;
25927244Sjhay
26027244Sjhay	sc = cg_lookup(ino_to_cg(fs, ino));
26127244Sjhay	if (sc->sc_lastino && sc->sc_lastino->si_ino == ino)
26227244Sjhay		return (sc->sc_lastino);
26327244Sjhay	hd = &sc->sc_inohash[SUJ_HASH(ino)];
26427244Sjhay	LIST_FOREACH(sino, hd, si_next)
26527244Sjhay		if (sino->si_ino == ino)
26627244Sjhay			return (sino);
26727244Sjhay	if (creat == 0)
26827244Sjhay		return (NULL);
26927244Sjhay	sino = errmalloc(sizeof(*sino));
27027244Sjhay	bzero(sino, sizeof(*sino));
27127244Sjhay	sino->si_ino = ino;
27227244Sjhay	TAILQ_INIT(&sino->si_recs);
27327244Sjhay	TAILQ_INIT(&sino->si_newrecs);
27427244Sjhay	TAILQ_INIT(&sino->si_movs);
27527244Sjhay	LIST_INSERT_HEAD(hd, sino, si_next);
27627244Sjhay
27727244Sjhay	return (sino);
27827244Sjhay}
27927244Sjhay
28027244Sjhay/*
28127244Sjhay * Lookup a block number in the hash and allocate a suj_blk if it does
28227244Sjhay * not exist.
28327244Sjhay */
28462984Skrisstatic struct suj_blk *
28527244Sjhayblk_lookup(ufs2_daddr_t blk, int creat)
28627244Sjhay{
28727244Sjhay	struct suj_blk *sblk;
28827244Sjhay	struct suj_cg *sc;
28927244Sjhay	struct blkhd *hd;
29027244Sjhay
29127244Sjhay	sc = cg_lookup(dtog(fs, blk));
29227244Sjhay	if (sc->sc_lastblk && sc->sc_lastblk->sb_blk == blk)
29327244Sjhay		return (sc->sc_lastblk);
29427244Sjhay	hd = &sc->sc_blkhash[SUJ_HASH(fragstoblks(fs, blk))];
29527244Sjhay	LIST_FOREACH(sblk, hd, sb_next)
29627244Sjhay		if (sblk->sb_blk == blk)
29727244Sjhay			return (sblk);
29827244Sjhay	if (creat == 0)
29927244Sjhay		return (NULL);
30027244Sjhay	sblk = errmalloc(sizeof(*sblk));
30127244Sjhay	bzero(sblk, sizeof(*sblk));
30227244Sjhay	sblk->sb_blk = blk;
30327244Sjhay	TAILQ_INIT(&sblk->sb_recs);
30427244Sjhay	LIST_INSERT_HEAD(hd, sblk, sb_next);
30511820Sjulian
30611820Sjulian	return (sblk);
30711820Sjulian}
30811820Sjulian
30911820Sjulianstatic struct data_blk *
31011820Sjuliandblk_lookup(ufs2_daddr_t blk)
31111820Sjulian{
31211820Sjulian	struct data_blk *dblk;
31311820Sjulian	struct dblkhd *hd;
31411820Sjulian
31511820Sjulian	hd = &dbhash[SUJ_HASH(fragstoblks(fs, blk))];
31611820Sjulian	if (lastblk && lastblk->db_blk == blk)
31711820Sjulian		return (lastblk);
31811820Sjulian	LIST_FOREACH(dblk, hd, db_next)
31911820Sjulian		if (dblk->db_blk == blk)
32011820Sjulian			return (dblk);
32111820Sjulian	/*
32211820Sjulian	 * The inode block wasn't located, allocate a new one.
32311820Sjulian	 */
32411820Sjulian	dblk = errmalloc(sizeof(*dblk));
32511820Sjulian	bzero(dblk, sizeof(*dblk));
32611820Sjulian	LIST_INSERT_HEAD(hd, dblk, db_next);
32711820Sjulian	dblk->db_blk = blk;
32811820Sjulian	return (dblk);
32911820Sjulian}
33011820Sjulian
33111820Sjulianstatic uint8_t *
33211820Sjuliandblk_read(ufs2_daddr_t blk, int size)
33311820Sjulian{
33411820Sjulian	struct data_blk *dblk;
33511820Sjulian
33611820Sjulian	dblk = dblk_lookup(blk);
33711820Sjulian	/*
33811820Sjulian	 * I doubt size mismatches can happen in practice but it is trivial
33911820Sjulian	 * to handle.
34011820Sjulian	 */
34111820Sjulian	if (size != dblk->db_size) {
34211820Sjulian		if (dblk->db_buf)
34311820Sjulian			free(dblk->db_buf);
34411820Sjulian		dblk->db_buf = errmalloc(size);
34511820Sjulian		dblk->db_size = size;
34611820Sjulian		if (bread(disk, fsbtodb(fs, blk), dblk->db_buf, size) == -1)
34711820Sjulian			err(1, "Failed to read data block %jd", blk);
34811820Sjulian	}
34911820Sjulian	return (dblk->db_buf);
35011820Sjulian}
35111820Sjulian
35211820Sjulianstatic void
35311820Sjuliandblk_dirty(ufs2_daddr_t blk)
35411820Sjulian{
35511820Sjulian	struct data_blk *dblk;
35611820Sjulian
35711820Sjulian	dblk = dblk_lookup(blk);
35811820Sjulian	dblk->db_dirty = 1;
35911820Sjulian}
36011820Sjulian
36111820Sjulianstatic void
36211820Sjuliandblk_write(void)
36311820Sjulian{
36411820Sjulian	struct data_blk *dblk;
36511820Sjulian	int i;
36611820Sjulian
367121552Speter	for (i = 0; i < SUJ_HASHSIZE; i++) {
368121552Speter		LIST_FOREACH(dblk, &dbhash[i], db_next) {
36911820Sjulian			if (dblk->db_dirty == 0 || dblk->db_size == 0)
37011820Sjulian				continue;
37111820Sjulian			if (bwrite(disk, fsbtodb(fs, dblk->db_blk),
37211820Sjulian			    dblk->db_buf, dblk->db_size) == -1)
37311820Sjulian				err(1, "Unable to write block %jd",
37411820Sjulian				    dblk->db_blk);
37511820Sjulian		}
37611820Sjulian	}
37711820Sjulian}
37811820Sjulian
37911820Sjulianstatic union dinode *
38011820Sjulianino_read(ino_t ino)
38111820Sjulian{
38211820Sjulian	struct ino_blk *iblk;
38311820Sjulian	struct iblkhd *hd;
38411820Sjulian	struct suj_cg *sc;
38511820Sjulian	ufs2_daddr_t blk;
38611820Sjulian	int off;
38711820Sjulian
38811820Sjulian	blk = ino_to_fsba(fs, ino);
38911820Sjulian	sc = cg_lookup(ino_to_cg(fs, ino));
39011820Sjulian	iblk = sc->sc_lastiblk;
39111820Sjulian	if (iblk && iblk->ib_blk == blk)
39211820Sjulian		goto found;
39311820Sjulian	hd = &sc->sc_iblkhash[SUJ_HASH(fragstoblks(fs, blk))];
39411820Sjulian	LIST_FOREACH(iblk, hd, ib_next)
39511820Sjulian		if (iblk->ib_blk == blk)
39611820Sjulian			goto found;
39711820Sjulian	/*
39811820Sjulian	 * The inode block wasn't located, allocate a new one.
39911820Sjulian	 */
40011820Sjulian	iblk = errmalloc(sizeof(*iblk));
40111820Sjulian	bzero(iblk, sizeof(*iblk));
40211820Sjulian	iblk->ib_buf = errmalloc(fs->fs_bsize);
40311820Sjulian	iblk->ib_blk = blk;
40411820Sjulian	LIST_INSERT_HEAD(hd, iblk, ib_next);
40511820Sjulian	if (bread(disk, fsbtodb(fs, blk), iblk->ib_buf, fs->fs_bsize) == -1)
40611820Sjulian		err(1, "Failed to read inode block %jd", blk);
40711820Sjulianfound:
40811820Sjulian	sc->sc_lastiblk = iblk;
40911820Sjulian	off = ino_to_fsbo(fs, ino);
41011820Sjulian	if (fs->fs_magic == FS_UFS1_MAGIC)
411121552Speter		return (union dinode *)&((struct ufs1_dinode *)iblk->ib_buf)[off];
412121552Speter	else
41311820Sjulian		return (union dinode *)&((struct ufs2_dinode *)iblk->ib_buf)[off];
41411820Sjulian}
41511820Sjulian
41611820Sjulianstatic void
41711820Sjulianino_dirty(ino_t ino)
41811820Sjulian{
41911820Sjulian	struct ino_blk *iblk;
42011820Sjulian	struct iblkhd *hd;
42111820Sjulian	struct suj_cg *sc;
42211820Sjulian	ufs2_daddr_t blk;
42311820Sjulian
42411820Sjulian	blk = ino_to_fsba(fs, ino);
42511820Sjulian	sc = cg_lookup(ino_to_cg(fs, ino));
42611820Sjulian	iblk = sc->sc_lastiblk;
42711820Sjulian	if (iblk && iblk->ib_blk == blk) {
42811820Sjulian		iblk->ib_dirty = 1;
42911820Sjulian		return;
43011820Sjulian	}
43111820Sjulian	hd = &sc->sc_iblkhash[SUJ_HASH(fragstoblks(fs, blk))];
43211820Sjulian	LIST_FOREACH(iblk, hd, ib_next) {
43311820Sjulian		if (iblk->ib_blk == blk) {
43411820Sjulian			iblk->ib_dirty = 1;
43511820Sjulian			return;
43611820Sjulian		}
43711820Sjulian	}
43811820Sjulian	ino_read(ino);
43911820Sjulian	ino_dirty(ino);
44011820Sjulian}
44111820Sjulian
44211820Sjulianstatic void
44311820Sjulianiblk_write(struct ino_blk *iblk)
44411820Sjulian{
44511820Sjulian
44611820Sjulian	if (iblk->ib_dirty == 0)
44711820Sjulian		return;
44811820Sjulian	if (bwrite(disk, fsbtodb(fs, iblk->ib_blk), iblk->ib_buf,
44911820Sjulian	    fs->fs_bsize) == -1)
45011820Sjulian		err(1, "Failed to write inode block %jd", iblk->ib_blk);
45111820Sjulian}
45211820Sjulian
45311820Sjulianstatic int
45411820Sjulianblk_overlaps(struct jblkrec *brec, ufs2_daddr_t start, int frags)
45511820Sjulian{
45611820Sjulian	ufs2_daddr_t bstart;
45711820Sjulian	ufs2_daddr_t bend;
45811820Sjulian	ufs2_daddr_t end;
45911820Sjulian
46011820Sjulian	end = start + frags;
46111820Sjulian	bstart = brec->jb_blkno + brec->jb_oldfrags;
46211820Sjulian	bend = bstart + brec->jb_frags;
46311820Sjulian	if (start < bend && end > bstart)
46411820Sjulian		return (1);
46511820Sjulian	return (0);
46611820Sjulian}
46715248Sjhay
46815248Sjhaystatic int
46915248Sjhayblk_equals(struct jblkrec *brec, ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t start,
47015248Sjhay    int frags)
47115248Sjhay{
47215248Sjhay
47315248Sjhay	if (brec->jb_ino != ino || brec->jb_lbn != lbn)
47415248Sjhay		return (0);
47515248Sjhay	if (brec->jb_blkno + brec->jb_oldfrags != start)
47615248Sjhay		return (0);
47715248Sjhay	if (brec->jb_frags != frags)
47815248Sjhay		return (0);
47915248Sjhay	return (1);
48015248Sjhay}
48115248Sjhay
48215248Sjhaystatic void
48315248Sjhayblk_setmask(struct jblkrec *brec, int *mask)
48415248Sjhay{
48515248Sjhay	int i;
48615248Sjhay
48715248Sjhay	for (i = brec->jb_oldfrags; i < brec->jb_oldfrags + brec->jb_frags; i++)
48815248Sjhay		*mask |= 1 << i;
48915248Sjhay}
49015248Sjhay
49115248Sjhay/*
49215248Sjhay * Determine whether a given block has been reallocated to a new location.
49315248Sjhay * Returns a mask of overlapping bits if any frags have been reused or
49415248Sjhay * zero if the block has not been re-used and the contents can be trusted.
49511820Sjulian *
49611820Sjulian * This is used to ensure that an orphaned pointer due to truncate is safe
49711820Sjulian * to be freed.  The mask value can be used to free partial blocks.
49811820Sjulian */
49911820Sjulianstatic int
50011820Sjulianblk_freemask(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn, int frags)
50111820Sjulian{
50211820Sjulian	struct suj_blk *sblk;
503122760Strhodes	struct suj_rec *srec;
50411820Sjulian	struct jblkrec *brec;
50511820Sjulian	int mask;
50611820Sjulian	int off;
50711820Sjulian
50811820Sjulian	/*
50911820Sjulian	 * To be certain we're not freeing a reallocated block we lookup
51011820Sjulian	 * this block in the blk hash and see if there is an allocation
51111820Sjulian	 * journal record that overlaps with any fragments in the block
51211820Sjulian	 * we're concerned with.  If any fragments have ben reallocated
51311820Sjulian	 * the block has already been freed and re-used for another purpose.
51411820Sjulian	 */
51511820Sjulian	mask = 0;
51611820Sjulian	sblk = blk_lookup(blknum(fs, blk), 0);
51711820Sjulian	if (sblk == NULL)
51811820Sjulian		return (0);
51911820Sjulian	off = blk - sblk->sb_blk;
52011820Sjulian	TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
52111820Sjulian		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 */
552static int
553blk_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 */
574static int
575ino_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 */
611static void
612blk_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 */
654static int
655blk_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 */
668static ufs2_daddr_t
669indir_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 */
721static ufs2_daddr_t
722ino_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 */
773static int
774blk_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 */
792static int
793ino_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 */
888static void
889indir_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	}
938out:
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 */
952static uint64_t
953ino_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 */
1011ufs_lbn_t visitlbn;
1012static void
1013null_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 */
1025static void
1026ino_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
1073static void
1074blk_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 */
1089static void
1090blk_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
1105static void
1106ino_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 */
1118static void
1119ino_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 */
1200static void
1201ino_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 */
1231static void
1232ino_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 */
1266static void
1267ino_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 */
1344static void
1345indir_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 */
1412static void
1413ino_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 */
1531static void
1532ino_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 */
1597static void
1598blk_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 */
1659static void
1660cg_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 */
1674static void
1675cg_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 */
1693static void
1694cg_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 */
1719static void
1720cg_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 */
1734static void
1735cg_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 */
1787static void
1788cg_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
1799static void
1800cg_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 */
1813static void
1814ino_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 */
1846static void
1847ino_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 */
1885static void
1886ino_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 */
1925static void
1926ino_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 */
1947static void
1948ino_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 */
2040static void
2041ino_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 */
2072static void
2073blk_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
2140static void
2141ino_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 */
2155static void
2156suj_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 */
2201static void
2202suj_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 */
2268static int
2269suj_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
2305struct 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};
2312struct jextent {
2313	ufs2_daddr_t	je_daddr;	/* Disk block address. */
2314	int		je_blocks;	/* Disk block count. */
2315};
2316
2317struct jblocks *suj_jblocks;
2318
2319static struct jblocks *
2320jblocks_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 */
2341static ufs2_daddr_t
2342jblocks_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 */
2371static void
2372jblocks_advance(struct jblocks *jblocks, int bytes)
2373{
2374
2375	jblocks->jb_off += bytes / DEV_BSIZE;
2376}
2377
2378static void
2379jblocks_destroy(struct jblocks *jblocks)
2380{
2381
2382	free(jblocks->jb_extent);
2383	free(jblocks);
2384}
2385
2386static void
2387jblocks_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 */
2427static void
2428suj_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
2434static void
2435suj_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	 */
2456restart:
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 */
2535static void
2536suj_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 */
2566int
2567suj_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