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