2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/param.h>
31 #include <sys/disklabel.h>
32 #include <sys/mount.h>
35 #include <ufs/ufs/extattr.h>
36 #include <ufs/ufs/quota.h>
37 #include <ufs/ufs/ufsmount.h>
38 #include <ufs/ufs/dinode.h>
39 #include <ufs/ufs/dir.h>
40 #include <ufs/ffs/fs.h>
56 #define DOTDOT_OFFSET DIRECTSIZ(1)
59 TAILQ_ENTRY(suj_seg) ss_next;
60 struct jsegrec ss_rec;
65 TAILQ_ENTRY(suj_rec) sr_next;
68 TAILQ_HEAD(srechd, suj_rec);
71 LIST_ENTRY(suj_ino) si_next;
72 struct srechd si_recs;
73 struct srechd si_newrecs;
74 struct srechd si_movs;
75 struct jtrncrec *si_trunc;
86 LIST_HEAD(inohd, suj_ino);
89 LIST_ENTRY(suj_blk) sb_next;
90 struct srechd sb_recs;
93 LIST_HEAD(blkhd, suj_blk);
96 LIST_ENTRY(suj_cg) sc_next;
97 struct blkhd sc_blkhash[HASHSIZE];
98 struct inohd sc_inohash[HASHSIZE];
99 struct ino_blk *sc_lastiblk;
100 struct suj_ino *sc_lastino;
101 struct suj_blk *sc_lastblk;
102 struct bufarea *sc_cgbp;
107 static LIST_HEAD(cghd, suj_cg) cghash[HASHSIZE];
108 static struct suj_cg *lastcg;
110 static TAILQ_HEAD(seghd, suj_seg) allsegs;
111 static uint64_t oldseq;
112 static struct fs *fs = NULL;
114 static char *joptype[JOP_NUMJOPTYPES] = JOP_NAMES;
117 * Summary statistics.
119 static uint64_t freefrags;
120 static uint64_t freeblocks;
121 static uint64_t freeinos;
122 static uint64_t freedir;
123 static uint64_t jbytes;
124 static uint64_t jrecs;
126 static jmp_buf jmpbuf;
128 typedef void (*ino_visitor)(ino_t, ufs_lbn_t, ufs2_daddr_t, int);
129 static void err_suj(const char *, ...) __dead2;
130 static void ino_trunc(ino_t, off_t);
131 static void ino_decr(ino_t);
132 static void ino_adjust(struct suj_ino *);
133 static void ino_build(struct suj_ino *);
134 static int blk_isfree(ufs2_daddr_t);
135 static void initsuj(void);
144 err(EX_OSERR, "malloc(%zu)", n);
149 * When hit a fatal error in journalling check, print out
150 * the error and then offer to fallback to normal fsck.
153 err_suj(const char * restrict fmt, ...)
158 (void)fprintf(stdout, "%s: ", cdevname);
161 (void)vfprintf(stdout, fmt, ap);
168 * Lookup a cg by number in the hash so we can keep track of which cgs
169 * need stats rebuilt.
171 static struct suj_cg *
176 struct bufarea *cgbp;
178 if (cgx < 0 || cgx >= fs->fs_ncg)
179 err_suj("Bad cg number %d\n", cgx);
180 if (lastcg && lastcg->sc_cgx == cgx)
182 cgbp = cglookup(cgx);
183 if (!check_cgmagic(cgx, cgbp))
184 err_suj("UNABLE TO REBUILD CYLINDER GROUP %d", cgx);
185 hd = &cghash[HASH(cgx)];
186 LIST_FOREACH(sc, hd, sc_next)
187 if (sc->sc_cgx == cgx) {
189 sc->sc_cgp = sc->sc_cgbp->b_un.b_cg;
193 sc = errmalloc(sizeof(*sc));
194 bzero(sc, sizeof(*sc));
196 sc->sc_cgp = sc->sc_cgbp->b_un.b_cg;
198 LIST_INSERT_HEAD(hd, sc, sc_next);
203 * Lookup an inode number in the hash and allocate a suj_ino if it does
206 static struct suj_ino *
207 ino_lookup(ino_t ino, int creat)
209 struct suj_ino *sino;
213 sc = cg_lookup(ino_to_cg(fs, ino));
214 if (sc->sc_lastino && sc->sc_lastino->si_ino == ino)
215 return (sc->sc_lastino);
216 hd = &sc->sc_inohash[HASH(ino)];
217 LIST_FOREACH(sino, hd, si_next)
218 if (sino->si_ino == ino)
222 sino = errmalloc(sizeof(*sino));
223 bzero(sino, sizeof(*sino));
225 TAILQ_INIT(&sino->si_recs);
226 TAILQ_INIT(&sino->si_newrecs);
227 TAILQ_INIT(&sino->si_movs);
228 LIST_INSERT_HEAD(hd, sino, si_next);
234 * Lookup a block number in the hash and allocate a suj_blk if it does
237 static struct suj_blk *
238 blk_lookup(ufs2_daddr_t blk, int creat)
240 struct suj_blk *sblk;
244 sc = cg_lookup(dtog(fs, blk));
245 if (sc->sc_lastblk && sc->sc_lastblk->sb_blk == blk)
246 return (sc->sc_lastblk);
247 hd = &sc->sc_blkhash[HASH(fragstoblks(fs, blk))];
248 LIST_FOREACH(sblk, hd, sb_next)
249 if (sblk->sb_blk == blk)
253 sblk = errmalloc(sizeof(*sblk));
254 bzero(sblk, sizeof(*sblk));
256 TAILQ_INIT(&sblk->sb_recs);
257 LIST_INSERT_HEAD(hd, sblk, sb_next);
263 blk_overlaps(struct jblkrec *brec, ufs2_daddr_t start, int frags)
270 bstart = brec->jb_blkno + brec->jb_oldfrags;
271 bend = bstart + brec->jb_frags;
272 if (start < bend && end > bstart)
278 blk_equals(struct jblkrec *brec, ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t start,
282 if (brec->jb_ino != ino || brec->jb_lbn != lbn)
284 if (brec->jb_blkno + brec->jb_oldfrags != start)
286 if (brec->jb_frags < frags)
292 blk_setmask(struct jblkrec *brec, int *mask)
296 for (i = brec->jb_oldfrags; i < brec->jb_oldfrags + brec->jb_frags; i++)
301 * Determine whether a given block has been reallocated to a new location.
302 * Returns a mask of overlapping bits if any frags have been reused or
303 * zero if the block has not been re-used and the contents can be trusted.
305 * This is used to ensure that an orphaned pointer due to truncate is safe
306 * to be freed. The mask value can be used to free partial blocks.
309 blk_freemask(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn, int frags)
311 struct suj_blk *sblk;
312 struct suj_rec *srec;
313 struct jblkrec *brec;
318 * To be certain we're not freeing a reallocated block we lookup
319 * this block in the blk hash and see if there is an allocation
320 * journal record that overlaps with any fragments in the block
321 * we're concerned with. If any fragments have been reallocated
322 * the block has already been freed and re-used for another purpose.
325 sblk = blk_lookup(blknum(fs, blk), 0);
328 off = blk - sblk->sb_blk;
329 TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
330 brec = (struct jblkrec *)srec->sr_rec;
332 * If the block overlaps but does not match
333 * exactly this record refers to the current
336 if (blk_overlaps(brec, blk, frags) == 0)
338 if (blk_equals(brec, ino, lbn, blk, frags) == 1)
341 blk_setmask(brec, &mask);
344 printf("blk_freemask: blk %jd sblk %jd off %d mask 0x%X\n",
345 blk, sblk->sb_blk, off, mask);
346 return (mask >> off);
350 * Determine whether it is safe to follow an indirect. It is not safe
351 * if any part of the indirect has been reallocated or the last journal
352 * entry was an allocation. Just allocated indirects may not have valid
353 * pointers yet and all of their children will have their own records.
354 * It is also not safe to follow an indirect if the cg bitmap has been
355 * cleared as a new allocation may write to the block prior to the journal
358 * Returns 1 if it's safe to follow the indirect and 0 otherwise.
361 blk_isindir(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn)
363 struct suj_blk *sblk;
364 struct jblkrec *brec;
366 sblk = blk_lookup(blk, 0);
369 if (TAILQ_EMPTY(&sblk->sb_recs))
371 brec = (struct jblkrec *)TAILQ_LAST(&sblk->sb_recs, srechd)->sr_rec;
372 if (blk_equals(brec, ino, lbn, blk, fs->fs_frag))
373 if (brec->jb_op == JOP_FREEBLK)
374 return (!blk_isfree(blk));
379 * Check to see if the requested block is available.
380 * We can just check in the cylinder-group maps as
381 * they will only have usable blocks in them.
384 suj_checkblkavail(ufs2_daddr_t blkno, long frags)
386 struct bufarea *cgbp;
388 ufs2_daddr_t j, k, baseblk;
391 if ((u_int64_t)blkno > sblock.fs_size)
393 cg = dtog(&sblock, blkno);
395 cgp = cgbp->b_un.b_cg;
396 if (!check_cgmagic(cg, cgbp))
397 return (-((cg + 1) * sblock.fs_fpg - sblock.fs_frag));
398 baseblk = dtogd(&sblock, blkno);
399 for (j = 0; j <= sblock.fs_frag - frags; j++) {
400 if (!isset(cg_blksfree(cgp), baseblk + j))
402 for (k = 1; k < frags; k++)
403 if (!isset(cg_blksfree(cgp), baseblk + j + k))
409 for (k = 0; k < frags; k++)
410 clrbit(cg_blksfree(cgp), baseblk + j + k);
412 if (frags == sblock.fs_frag)
413 cgp->cg_cs.cs_nbfree--;
415 cgp->cg_cs.cs_nffree -= frags;
417 return ((cg * sblock.fs_fpg) + baseblk + j);
423 * Clear an inode from the cg bitmap. If the inode was already clear return
424 * 0 so the caller knows it does not have to check the inode contents.
427 ino_free(ino_t ino, int mode)
434 cg = ino_to_cg(fs, ino);
435 ino = ino % fs->fs_ipg;
438 inosused = cg_inosused(cgp);
440 * The bitmap may never have made it to the disk so we have to
441 * conditionally clear. We can avoid writing the cg in this case.
443 if (isclr(inosused, ino))
446 clrbit(inosused, ino);
447 if (ino < cgp->cg_irotor)
448 cgp->cg_irotor = ino;
449 cgp->cg_cs.cs_nifree++;
450 if ((mode & IFMT) == IFDIR) {
452 cgp->cg_cs.cs_ndir--;
454 cgdirty(sc->sc_cgbp);
460 * Free 'frags' frags starting at filesystem block 'bno' skipping any frags
464 blk_free(ino_t ino, ufs2_daddr_t bno, int mask, int frags)
466 ufs1_daddr_t fragno, cgbno;
473 printf("Freeing %d frags at blk %jd mask 0x%x\n",
476 * Check to see if the block needs to be claimed by a snapshot.
477 * If wanted, the snapshot references it. Otherwise we free it.
479 if (snapblkfree(fs, bno, lfragtosize(fs, frags), ino,
485 cgbno = dtogd(fs, bno);
486 blksfree = cg_blksfree(cgp);
489 * If it's not allocated we only wrote the journal entry
490 * and never the bitmaps. Here we unconditionally clear and
491 * resolve the cg summary later.
493 if (frags == fs->fs_frag && mask == 0) {
494 fragno = fragstoblks(fs, cgbno);
495 ffs_setblock(fs, blksfree, fragno);
499 * deallocate the fragment
501 for (i = 0; i < frags; i++)
502 if ((mask & (1 << i)) == 0 &&
503 isclr(blksfree, cgbno +i)) {
505 setbit(blksfree, cgbno + i);
508 cgdirty(sc->sc_cgbp);
512 * Returns 1 if the whole block starting at 'bno' is marked free and 0
516 blk_isfree(ufs2_daddr_t bno)
520 sc = cg_lookup(dtog(fs, bno));
521 return ffs_isblock(fs, cg_blksfree(sc->sc_cgp), dtogd(fs, bno));
525 * Determine whether a block exists at a particular lbn in an inode.
526 * Returns 1 if found, 0 if not. lbn may be negative for indirects
530 blk_isat(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int *frags)
538 if (DIP(dp, di_nlink) == 0 || DIP(dp, di_mode) == 0) {
542 nblk = ino_blkatoff(dp, ino, lbn, frags, NULL);
544 return (nblk == blk);
548 * Clear the directory entry at diroff that should point to child. Minimal
549 * checking is done and it is assumed that this path was verified with isat.
552 ino_clrat(ino_t parent, off_t diroff, ino_t child)
565 printf("Clearing inode %ju from parent %ju at offset %jd\n",
566 (uintmax_t)child, (uintmax_t)parent, diroff);
568 lbn = lblkno(fs, diroff);
569 doff = blkoff(fs, diroff);
572 blk = ino_blkatoff(dip, parent, lbn, &frags, NULL);
573 blksize = sblksize(fs, DIP(dip, di_size), lbn);
575 bp = getdatablk(blk, blksize, BT_DIRDATA);
577 err_suj("ino_clrat: UNRECOVERABLE I/O ERROR");
578 dp = (struct direct *)&bp->b_un.b_buf[doff];
579 if (dp->d_ino != child)
580 errx(1, "Inode %ju does not exist in %ju at %jd",
581 (uintmax_t)child, (uintmax_t)parent, diroff);
586 * The actual .. reference count will already have been removed
587 * from the parent by the .. remref record.
592 * Determines whether a pointer to an inode exists within a directory
593 * at a specified offset. Returns the mode of the found entry.
596 ino_isat(ino_t parent, off_t diroff, ino_t child, int *mode, int *isdot)
612 *mode = DIP(dip, di_mode);
613 if ((*mode & IFMT) != IFDIR) {
616 * This can happen if the parent inode
620 printf("Directory %ju has bad mode %o\n",
621 (uintmax_t)parent, *mode);
623 printf("Directory %ju has zero mode\n",
629 lbn = lblkno(fs, diroff);
630 doff = blkoff(fs, diroff);
631 blksize = sblksize(fs, DIP(dip, di_size), lbn);
632 if (diroff + DIRECTSIZ(1) > DIP(dip, di_size) || doff >= blksize) {
634 printf("ino %ju absent from %ju due to offset %jd"
635 " exceeding size %jd\n",
636 (uintmax_t)child, (uintmax_t)parent, diroff,
641 blk = ino_blkatoff(dip, parent, lbn, &frags, NULL);
645 printf("Sparse directory %ju", (uintmax_t)parent);
648 bp = getdatablk(blk, blksize, BT_DIRDATA);
650 err_suj("ino_isat: UNRECOVERABLE I/O ERROR");
652 * Walk through the records from the start of the block to be
653 * certain we hit a valid record and not some junk in the middle
654 * of a file name. Stop when we reach or pass the expected offset.
656 dpoff = rounddown(doff, DIRBLKSIZ);
658 dp = (struct direct *)&bp->b_un.b_buf[dpoff];
661 if (dp->d_reclen == 0)
663 dpoff += dp->d_reclen;
664 } while (dpoff <= doff);
665 if (dpoff > fs->fs_bsize)
666 err_suj("Corrupt directory block in dir ino %ju\n",
671 printf("ino %ju not found in %ju, lbn %jd, dpoff %d\n",
672 (uintmax_t)child, (uintmax_t)parent, lbn, dpoff);
677 * We found the item in question. Record the mode and whether it's
678 * a . or .. link for the caller.
680 if (dp->d_ino == child) {
683 else if (dp->d_namlen == 2 &&
684 dp->d_name[0] == '.' && dp->d_name[1] == '.')
686 *mode = DTTOIF(dp->d_type);
691 printf("ino %ju doesn't match dirent ino %ju in parent %ju\n",
692 (uintmax_t)child, (uintmax_t)dp->d_ino, (uintmax_t)parent);
697 #define VISIT_INDIR 0x0001
698 #define VISIT_EXT 0x0002
699 #define VISIT_ROOT 0x0004 /* Operation came via root & valid pointers. */
702 * Read an indirect level which may or may not be linked into an inode.
705 indir_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, uint64_t *frags,
706 ino_visitor visitor, int flags)
716 * Don't visit indirect blocks with contents we can't trust. This
717 * should only happen when indir_visit() is called to complete a
718 * truncate that never finished and not when a pointer is found via
723 level = lbn_level(lbn);
725 err_suj("Invalid level for lbn %jd\n", lbn);
726 if ((flags & VISIT_ROOT) == 0 && blk_isindir(blk, ino, lbn) == 0) {
728 printf("blk %jd ino %ju lbn %jd(%d) is not indir.\n",
729 blk, (uintmax_t)ino, lbn, level);
733 for (i = level; i > 0; i--)
734 lbnadd *= NINDIR(fs);
735 bp = getdatablk(blk, fs->fs_bsize, BT_LEVEL1 + level);
737 err_suj("indir_visit: UNRECOVERABLE I/O ERROR\n");
738 for (i = 0; i < NINDIR(fs); i++) {
739 if ((nblk = IBLK(bp, i)) == 0)
742 nlbn = -lbn + i * lbnadd;
743 (*frags) += fs->fs_frag;
744 visitor(ino, nlbn, nblk, fs->fs_frag);
746 nlbn = (lbn + 1) - (i * lbnadd);
747 indir_visit(ino, nlbn, nblk, frags, visitor, flags);
752 if (flags & VISIT_INDIR) {
753 (*frags) += fs->fs_frag;
754 visitor(ino, lbn, blk, fs->fs_frag);
759 * Visit each block in an inode as specified by 'flags' and call a
760 * callback function. The callback may inspect or free blocks. The
761 * count of frags found according to the size in the file is returned.
762 * This is not valid for sparse files but may be used to determine
763 * the correct di_blocks for a file.
766 ino_visit(union dinode *dp, ino_t ino, ino_visitor visitor, int flags)
777 size = DIP(dp, di_size);
778 mode = DIP(dp, di_mode) & IFMT;
780 if ((flags & VISIT_EXT) &&
781 fs->fs_magic == FS_UFS2_MAGIC && dp->dp2.di_extsize) {
782 for (i = 0; i < UFS_NXADDR; i++) {
783 if (dp->dp2.di_extb[i] == 0)
785 frags = sblksize(fs, dp->dp2.di_extsize, i);
786 frags = numfrags(fs, frags);
788 visitor(ino, -1 - i, dp->dp2.di_extb[i], frags);
791 /* Skip datablocks for short links and devices. */
792 if (mode == IFBLK || mode == IFCHR ||
793 (mode == IFLNK && size < fs->fs_maxsymlinklen))
795 for (i = 0; i < UFS_NDADDR; i++) {
796 if (DIP(dp, di_db[i]) == 0)
798 frags = sblksize(fs, size, i);
799 frags = numfrags(fs, frags);
801 visitor(ino, i, DIP(dp, di_db[i]), frags);
804 * We know the following indirects are real as we're following
805 * real pointers to them.
808 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR; i < UFS_NIADDR; i++,
810 nextlbn = lbn + tmpval;
811 tmpval *= NINDIR(fs);
812 if (DIP(dp, di_ib[i]) == 0)
814 indir_visit(ino, -lbn - i, DIP(dp, di_ib[i]), &fragcnt, visitor,
821 * Null visitor function used when we just want to count blocks and
826 null_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
833 * Recalculate di_blocks when we discover that a block allocation or
834 * free was not successfully completed. The kernel does not roll this back
835 * because it would be too expensive to compute which indirects were
836 * reachable at the time the inode was written.
839 ino_adjblks(struct suj_ino *sino)
852 /* No need to adjust zero'd inodes. */
853 if (DIP(dp, di_mode) == 0) {
858 * Visit all blocks and count them as well as recording the last
859 * valid lbn in the file. If the file size doesn't agree with the
860 * last lbn we need to truncate to fix it. Otherwise just adjust
864 frags = ino_visit(dp, ino, null_visit, VISIT_INDIR | VISIT_EXT);
865 blocks = fsbtodb(fs, frags);
867 * We assume the size and direct block list is kept coherent by
868 * softdep. For files that have extended into indirects we truncate
869 * to the size in the inode or the maximum size permitted by
870 * populated indirects.
872 if (visitlbn >= UFS_NDADDR) {
873 isize = DIP(dp, di_size);
874 size = lblktosize(fs, visitlbn + 1);
877 /* Always truncate to free any unpopulated indirects. */
878 ino_trunc(ino, isize);
882 if (blocks == DIP(dp, di_blocks)) {
887 printf("ino %ju adjusting block count from %jd to %jd\n",
888 (uintmax_t)ino, DIP(dp, di_blocks), blocks);
889 DIP_SET(dp, di_blocks, blocks);
895 blk_free_visit(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
898 blk_free(ino, blk, blk_freemask(blk, ino, lbn, frags), frags);
902 * Free a block or tree of blocks that was previously rooted in ino at
903 * the given lbn. If the lbn is an indirect all children are freed
907 blk_free_lbn(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t lbn, int frags, int follow)
912 mask = blk_freemask(blk, ino, lbn, frags);
914 if (lbn <= -UFS_NDADDR && follow && mask == 0)
915 indir_visit(ino, lbn, blk, &resid, blk_free_visit, VISIT_INDIR);
917 blk_free(ino, blk, mask, frags);
921 ino_setskip(struct suj_ino *sino, ino_t parent)
926 if (ino_isat(sino->si_ino, DOTDOT_OFFSET, parent, &mode, &isdot))
927 sino->si_skipparent = 1;
931 ino_remref(ino_t parent, ino_t child, uint64_t diroff, int isdotdot)
933 struct suj_ino *sino;
934 struct suj_rec *srec;
935 struct jrefrec *rrec;
938 * Lookup this inode to see if we have a record for it.
940 sino = ino_lookup(child, 0);
942 * Tell any child directories we've already removed their
943 * parent link cnt. Don't try to adjust our link down again.
945 if (sino != NULL && isdotdot == 0)
946 ino_setskip(sino, parent);
948 * No valid record for this inode. Just drop the on-disk
951 if (sino == NULL || sino->si_hasrecs == 0) {
956 * Use ino_adjust() if ino_check() has already processed this
957 * child. If we lose the last non-dot reference to a
958 * directory it will be discarded.
960 if (sino->si_linkadj) {
961 if (sino->si_nlink == 0)
962 err_suj("ino_remref: ino %ld mode 0%o about to go "
963 "negative\n", sino->si_ino, sino->si_mode);
971 * If we haven't yet processed this inode we need to make
972 * sure we will successfully discover the lost path. If not
973 * use nlinkadj to remember.
975 TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
976 rrec = (struct jrefrec *)srec->sr_rec;
977 if (rrec->jr_parent == parent &&
978 rrec->jr_diroff == diroff)
985 * Free the children of a directory when the directory is discarded.
988 ino_free_children(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
990 struct suj_ino *sino;
999 sino = ino_lookup(ino, 0);
1001 skipparent = sino->si_skipparent;
1004 size = lfragtosize(fs, frags);
1005 bp = getdatablk(blk, size, BT_DIRDATA);
1006 if (bp->b_errs != 0)
1007 err_suj("ino_free_children: UNRECOVERABLE I/O ERROR");
1008 dp = (struct direct *)&bp->b_un.b_buf[0];
1009 for (dpoff = 0; dpoff < size && dp->d_reclen; dpoff += dp->d_reclen) {
1010 dp = (struct direct *)&bp->b_un.b_buf[dpoff];
1011 if (dp->d_ino == 0 || dp->d_ino == UFS_WINO)
1013 if (dp->d_namlen == 1 && dp->d_name[0] == '.')
1015 isdotdot = dp->d_namlen == 2 && dp->d_name[0] == '.' &&
1016 dp->d_name[1] == '.';
1017 if (isdotdot && skipparent == 1)
1020 printf("Directory %ju removing ino %ju name %s\n",
1021 (uintmax_t)ino, (uintmax_t)dp->d_ino, dp->d_name);
1022 diroff = lblktosize(fs, lbn) + dpoff;
1023 ino_remref(ino, dp->d_ino, diroff, isdotdot);
1029 * Reclaim an inode, freeing all blocks and decrementing all children's
1030 * link counts. Free the inode back to the cg.
1033 ino_reclaim(struct inode *ip, ino_t ino, int mode)
1039 if (ino == UFS_ROOTINO)
1040 err_suj("Attempting to free UFS_ROOTINO\n");
1042 printf("Truncating and freeing ino %ju, nlink %d, mode %o\n",
1043 (uintmax_t)ino, DIP(dp, di_nlink), DIP(dp, di_mode));
1045 /* We are freeing an inode or directory. */
1046 if ((DIP(dp, di_mode) & IFMT) == IFDIR)
1047 ino_visit(dp, ino, ino_free_children, 0);
1048 DIP_SET(dp, di_nlink, 0);
1049 if ((DIP(dp, di_flags) & SF_SNAPSHOT) != 0)
1051 ino_visit(dp, ino, blk_free_visit, VISIT_EXT | VISIT_INDIR);
1052 /* Here we have to clear the inode and release any blocks it holds. */
1053 gen = DIP(dp, di_gen);
1054 if (fs->fs_magic == FS_UFS1_MAGIC)
1055 bzero(dp, sizeof(struct ufs1_dinode));
1057 bzero(dp, sizeof(struct ufs2_dinode));
1058 DIP_SET(dp, di_gen, gen);
1060 ino_free(ino, mode);
1065 * Adjust an inode's link count down by one when a directory goes away.
1078 nlink = DIP(dp, di_nlink);
1079 mode = DIP(dp, di_mode);
1081 err_suj("Inode %d link count %d invalid\n", ino, nlink);
1083 err_suj("Inode %d has a link of %d with 0 mode\n", ino, nlink);
1085 if ((mode & IFMT) == IFDIR)
1089 if (nlink < reqlink) {
1091 printf("ino %ju not enough links to live %d < %d\n",
1092 (uintmax_t)ino, nlink, reqlink);
1093 ino_reclaim(&ip, ino, mode);
1097 DIP_SET(dp, di_nlink, nlink);
1103 * Adjust the inode link count to 'nlink'. If the count reaches zero
1107 ino_adjust(struct suj_ino *sino)
1109 struct jrefrec *rrec;
1110 struct suj_rec *srec;
1111 struct suj_ino *stmp;
1121 nlink = sino->si_nlink;
1123 mode = sino->si_mode & IFMT;
1125 * If it's a directory with no dot links, it was truncated before
1126 * the name was cleared. We need to clear the dirent that
1129 if (mode == IFDIR && nlink == 1 && sino->si_dotlinks == 0) {
1130 sino->si_nlink = nlink = 0;
1131 TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1132 rrec = (struct jrefrec *)srec->sr_rec;
1133 if (ino_isat(rrec->jr_parent, rrec->jr_diroff, ino,
1134 &recmode, &isdot) == 0)
1136 ino_clrat(rrec->jr_parent, rrec->jr_diroff, ino);
1140 errx(1, "Directory %ju name not found", (uintmax_t)ino);
1143 * If it's a directory with no real names pointing to it go ahead
1144 * and truncate it. This will free any children.
1146 if (mode == IFDIR && nlink - sino->si_dotlinks == 0) {
1147 sino->si_nlink = nlink = 0;
1149 * Mark any .. links so they know not to free this inode
1150 * when they are removed.
1152 TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1153 rrec = (struct jrefrec *)srec->sr_rec;
1154 if (rrec->jr_diroff == DOTDOT_OFFSET) {
1155 stmp = ino_lookup(rrec->jr_parent, 0);
1157 ino_setskip(stmp, ino);
1163 mode = DIP(dp, di_mode) & IFMT;
1164 if (nlink > UFS_LINK_MAX)
1165 err_suj("ino %ju nlink manipulation error, new %ju, old %d\n",
1166 (uintmax_t)ino, (uintmax_t)nlink, DIP(dp, di_nlink));
1168 printf("Adjusting ino %ju, nlink %ju, old link %d lastmode %o\n",
1169 (uintmax_t)ino, (uintmax_t)nlink, DIP(dp, di_nlink),
1173 printf("ino %ju, zero inode freeing bitmap\n",
1175 ino_free(ino, sino->si_mode);
1179 /* XXX Should be an assert? */
1180 if (mode != sino->si_mode && debug)
1181 printf("ino %ju, mode %o != %o\n",
1182 (uintmax_t)ino, mode, sino->si_mode);
1183 if ((mode & IFMT) == IFDIR)
1187 /* If the inode doesn't have enough links to live, free it. */
1188 if (nlink < reqlink) {
1190 printf("ino %ju not enough links to live %ju < %ju\n",
1191 (uintmax_t)ino, (uintmax_t)nlink,
1192 (uintmax_t)reqlink);
1193 ino_reclaim(&ip, ino, mode);
1197 /* If required write the updated link count. */
1198 if (DIP(dp, di_nlink) == nlink) {
1200 printf("ino %ju, link matches, skipping.\n",
1205 DIP_SET(dp, di_nlink, nlink);
1211 * Truncate some or all blocks in an indirect, freeing any that are required
1212 * and zeroing the indirect.
1215 indir_trunc(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, ufs_lbn_t lastlbn,
1230 level = lbn_level(lbn);
1232 err_suj("Invalid level for lbn %jd\n", lbn);
1234 for (i = level; i > 0; i--)
1235 lbnadd *= NINDIR(fs);
1236 bp = getdatablk(blk, fs->fs_bsize, BT_LEVEL1 + level);
1237 if (bp->b_errs != 0)
1238 err_suj("indir_trunc: UNRECOVERABLE I/O ERROR");
1239 for (i = 0; i < NINDIR(fs); i++) {
1240 if ((nblk = IBLK(bp, i)) == 0)
1243 nlbn = (lbn + 1) - (i * lbnadd);
1245 * Calculate the lbn of the next indirect to
1246 * determine if any of this indirect must be
1249 next = -(lbn + level) + ((i+1) * lbnadd);
1250 if (next <= lastlbn)
1252 indir_trunc(ino, nlbn, nblk, lastlbn, dp);
1253 /* If all of this indirect was reclaimed, free it. */
1254 nlbn = next - lbnadd;
1258 nlbn = -lbn + i * lbnadd;
1263 blk_free(ino, nblk, 0, fs->fs_frag);
1272 * Truncate an inode to the minimum of the given size or the last populated
1273 * block after any over size have been discarded. The kernel would allocate
1274 * the last block in the file but fsck does not and neither do we. This
1275 * code never extends files, only shrinks them.
1278 ino_trunc(ino_t ino, off_t size)
1284 uint64_t totalfrags;
1297 mode = DIP(dp, di_mode) & IFMT;
1298 cursize = DIP(dp, di_size);
1299 /* If no size change, nothing to do */
1300 if (size == cursize) {
1305 printf("Truncating ino %ju, mode %o to size %jd from "
1306 "size %jd\n", (uintmax_t)ino, mode, size, cursize);
1308 /* Skip datablocks for short links and devices. */
1309 if (mode == 0 || mode == IFBLK || mode == IFCHR ||
1310 (mode == IFLNK && cursize < fs->fs_maxsymlinklen)) {
1315 if (size > cursize) {
1319 if ((DIP(dp, di_flags) & SF_SNAPSHOT) != 0) {
1321 err_suj("Partial truncation of ino %ju snapshot file\n",
1325 lastlbn = lblkno(fs, blkroundup(fs, size));
1326 for (i = lastlbn; i < UFS_NDADDR; i++) {
1327 if ((bn = DIP(dp, di_db[i])) == 0)
1329 blksize = sblksize(fs, cursize, i);
1330 blk_free(ino, bn, 0, numfrags(fs, blksize));
1331 DIP_SET(dp, di_db[i], 0);
1334 * Follow indirect blocks, freeing anything required.
1336 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR; i < UFS_NIADDR; i++,
1338 nextlbn = lbn + tmpval;
1339 tmpval *= NINDIR(fs);
1340 /* If we're not freeing any in this indirect range skip it. */
1341 if (lastlbn >= nextlbn)
1343 if ((bn = DIP(dp, di_ib[i])) == 0)
1345 indir_trunc(ino, -lbn - i, bn, lastlbn, dp);
1346 /* If we freed everything in this indirect free the indir. */
1349 blk_free(ino, bn, 0, fs->fs_frag);
1350 DIP_SET(dp, di_ib[i], 0);
1353 * Now that we've freed any whole blocks that exceed the desired
1354 * truncation size, figure out how many blocks remain and what the
1355 * last populated lbn is. We will set the size to this last lbn
1356 * rather than worrying about allocating the final lbn as the kernel
1357 * would've done. This is consistent with normal fsck behavior.
1360 totalfrags = ino_visit(dp, ino, null_visit, VISIT_INDIR | VISIT_EXT);
1361 if (size > lblktosize(fs, visitlbn + 1))
1362 size = lblktosize(fs, visitlbn + 1);
1364 * If we're truncating direct blocks we have to adjust frags
1367 if (visitlbn < UFS_NDADDR && totalfrags) {
1368 long oldspace, newspace;
1370 bn = DIP(dp, di_db[visitlbn]);
1372 err_suj("Bad blk at ino %ju lbn %jd\n",
1373 (uintmax_t)ino, visitlbn);
1374 oldspace = sblksize(fs, cursize, visitlbn);
1375 newspace = sblksize(fs, size, visitlbn);
1376 if (oldspace != newspace) {
1377 bn += numfrags(fs, newspace);
1378 frags = numfrags(fs, oldspace - newspace);
1379 blk_free(ino, bn, 0, frags);
1380 totalfrags -= frags;
1383 DIP_SET(dp, di_blocks, fsbtodb(fs, totalfrags));
1384 DIP_SET(dp, di_size, size);
1387 * If we've truncated into the middle of a block or frag we have
1388 * to zero it here. Otherwise the file could extend into
1389 * uninitialized space later.
1391 off = blkoff(fs, size);
1392 if (off && DIP(dp, di_mode) != IFDIR) {
1395 bn = ino_blkatoff(dp, ino, visitlbn, &frags, NULL);
1397 err_suj("Block missing from ino %ju at lbn %jd\n",
1398 (uintmax_t)ino, visitlbn);
1399 clrsize = frags * fs->fs_fsize;
1400 bp = getdatablk(bn, clrsize, BT_DATA);
1401 if (bp->b_errs != 0)
1402 err_suj("ino_trunc: UNRECOVERABLE I/O ERROR");
1404 bzero(&bp->b_un.b_buf[off], clrsize);
1413 * Process records available for one inode and determine whether the
1414 * link count is correct or needs adjusting.
1417 ino_check(struct suj_ino *sino)
1419 struct suj_rec *srec;
1420 struct jrefrec *rrec;
1430 if (sino->si_hasrecs == 0)
1433 rrec = (struct jrefrec *)TAILQ_FIRST(&sino->si_recs)->sr_rec;
1434 nlink = rrec->jr_nlink;
1437 removes = sino->si_nlinkadj;
1438 TAILQ_FOREACH(srec, &sino->si_recs, sr_next) {
1439 rrec = (struct jrefrec *)srec->sr_rec;
1440 isat = ino_isat(rrec->jr_parent, rrec->jr_diroff,
1441 rrec->jr_ino, &mode, &isdot);
1442 if (isat && (mode & IFMT) != (rrec->jr_mode & IFMT))
1443 err_suj("Inode mode/directory type mismatch %o != %o\n",
1444 mode, rrec->jr_mode);
1446 printf("jrefrec: op %s ino %ju, nlink %ju, parent %ju, "
1447 "diroff %jd, mode %o, isat %d, isdot %d\n",
1448 JOP_OPTYPE(rrec->jr_op), (uintmax_t)rrec->jr_ino,
1449 (uintmax_t)rrec->jr_nlink,
1450 (uintmax_t)rrec->jr_parent,
1451 (uintmax_t)rrec->jr_diroff,
1452 rrec->jr_mode, isat, isdot);
1453 mode = rrec->jr_mode & IFMT;
1454 if (rrec->jr_op == JOP_REMREF)
1461 * The number of links that remain are the starting link count
1462 * subtracted by the total number of removes with the total
1463 * links discovered back in. An incomplete remove thus
1464 * makes no change to the link count but an add increases
1469 "ino %ju nlink %ju newlinks %ju removes %ju dotlinks %ju\n",
1470 (uintmax_t)ino, (uintmax_t)nlink, (uintmax_t)newlinks,
1471 (uintmax_t)removes, (uintmax_t)dotlinks);
1474 sino->si_linkadj = 1;
1475 sino->si_nlink = nlink;
1476 sino->si_dotlinks = dotlinks;
1477 sino->si_mode = mode;
1482 * Process records available for one block and determine whether it is
1483 * still allocated and whether the owning inode needs to be updated or
1487 blk_check(struct suj_blk *sblk)
1489 struct suj_rec *srec;
1490 struct jblkrec *brec;
1491 struct suj_ino *sino;
1498 * Each suj_blk actually contains records for any fragments in that
1499 * block. As a result we must evaluate each record individually.
1502 TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
1503 brec = (struct jblkrec *)srec->sr_rec;
1504 frags = brec->jb_frags;
1505 blk = brec->jb_blkno + brec->jb_oldfrags;
1506 isat = blk_isat(brec->jb_ino, brec->jb_lbn, blk, &frags);
1507 if (sino == NULL || sino->si_ino != brec->jb_ino) {
1508 sino = ino_lookup(brec->jb_ino, 1);
1509 sino->si_blkadj = 1;
1512 printf("op %s blk %jd ino %ju lbn %jd frags %d isat %d "
1513 "(%d)\n", JOP_OPTYPE(brec->jb_op), blk,
1514 (uintmax_t)brec->jb_ino, brec->jb_lbn,
1515 brec->jb_frags, isat, frags);
1517 * If we found the block at this address we still have to
1518 * determine if we need to free the tail end that was
1519 * added by adding contiguous fragments from the same block.
1522 if (frags == brec->jb_frags)
1524 mask = blk_freemask(blk, brec->jb_ino, brec->jb_lbn,
1528 frags = brec->jb_frags - frags;
1529 blk_free(brec->jb_ino, blk, mask, frags);
1533 * The block wasn't found, attempt to free it. It won't be
1534 * freed if it was actually reallocated. If this was an
1535 * allocation we don't want to follow indirects as they
1536 * may not be written yet. Any children of the indirect will
1537 * have their own records. If it's a free we need to
1538 * recursively free children.
1540 blk_free_lbn(blk, brec->jb_ino, brec->jb_lbn, brec->jb_frags,
1541 brec->jb_op == JOP_FREEBLK);
1546 * Walk the list of inode records for this cg and resolve moved and duplicate
1547 * inode references now that we have a complete picture.
1550 cg_build(struct suj_cg *sc)
1552 struct suj_ino *sino;
1555 for (i = 0; i < HASHSIZE; i++)
1556 LIST_FOREACH(sino, &sc->sc_inohash[i], si_next)
1561 * Handle inodes requiring truncation. This must be done prior to
1562 * looking up any inodes in directories.
1565 cg_trunc(struct suj_cg *sc)
1567 struct suj_ino *sino;
1570 for (i = 0; i < HASHSIZE; i++) {
1571 LIST_FOREACH(sino, &sc->sc_inohash[i], si_next) {
1572 if (sino->si_trunc) {
1573 ino_trunc(sino->si_ino,
1574 sino->si_trunc->jt_size);
1575 sino->si_blkadj = 0;
1576 sino->si_trunc = NULL;
1578 if (sino->si_blkadj)
1585 cg_adj_blk(struct suj_cg *sc)
1587 struct suj_ino *sino;
1590 for (i = 0; i < HASHSIZE; i++) {
1591 LIST_FOREACH(sino, &sc->sc_inohash[i], si_next) {
1592 if (sino->si_blkadj)
1599 * Free any partially allocated blocks and then resolve inode block
1603 cg_check_blk(struct suj_cg *sc)
1605 struct suj_blk *sblk;
1609 for (i = 0; i < HASHSIZE; i++)
1610 LIST_FOREACH(sblk, &sc->sc_blkhash[i], sb_next)
1615 * Walk the list of inode records for this cg, recovering any
1616 * changes which were not complete at the time of crash.
1619 cg_check_ino(struct suj_cg *sc)
1621 struct suj_ino *sino;
1624 for (i = 0; i < HASHSIZE; i++)
1625 LIST_FOREACH(sino, &sc->sc_inohash[i], si_next)
1630 cg_apply(void (*apply)(struct suj_cg *))
1635 for (i = 0; i < HASHSIZE; i++)
1636 LIST_FOREACH(scg, &cghash[i], sc_next)
1641 * Process the unlinked but referenced file list. Freeing all inodes.
1652 ino = fs->fs_sujfree;
1657 mode = DIP(dp, di_mode) & IFMT;
1658 inon = DIP(dp, di_freelink);
1659 DIP_SET(dp, di_freelink, 0);
1662 * XXX Should this be an errx?
1664 if (DIP(dp, di_nlink) == 0) {
1666 printf("Freeing unlinked ino %ju mode %o\n",
1667 (uintmax_t)ino, mode);
1668 ino_reclaim(&ip, ino, mode);
1670 printf("Skipping ino %ju mode %o with link %d\n",
1671 (uintmax_t)ino, mode, DIP(dp, di_nlink));
1678 * Append a new record to the list of records requiring processing.
1681 ino_append(union jrec *rec)
1683 struct jrefrec *refrec;
1684 struct jmvrec *mvrec;
1685 struct suj_ino *sino;
1686 struct suj_rec *srec;
1688 mvrec = &rec->rec_jmvrec;
1689 refrec = &rec->rec_jrefrec;
1690 if (debug && mvrec->jm_op == JOP_MVREF)
1691 printf("ino move: ino %ju, parent %ju, "
1692 "diroff %jd, oldoff %jd\n",
1693 (uintmax_t)mvrec->jm_ino, (uintmax_t)mvrec->jm_parent,
1694 (uintmax_t)mvrec->jm_newoff, (uintmax_t)mvrec->jm_oldoff);
1696 (refrec->jr_op == JOP_ADDREF || refrec->jr_op == JOP_REMREF))
1697 printf("ino ref: op %s, ino %ju, nlink %ju, "
1698 "parent %ju, diroff %jd\n",
1699 JOP_OPTYPE(refrec->jr_op), (uintmax_t)refrec->jr_ino,
1700 (uintmax_t)refrec->jr_nlink,
1701 (uintmax_t)refrec->jr_parent, (uintmax_t)refrec->jr_diroff);
1702 sino = ino_lookup(((struct jrefrec *)rec)->jr_ino, 1);
1703 sino->si_hasrecs = 1;
1704 srec = errmalloc(sizeof(*srec));
1706 TAILQ_INSERT_TAIL(&sino->si_newrecs, srec, sr_next);
1710 * Add a reference adjustment to the sino list and eliminate dups. The
1711 * primary loop in ino_build_ref() checks for dups but new ones may be
1712 * created as a result of offset adjustments.
1715 ino_add_ref(struct suj_ino *sino, struct suj_rec *srec)
1717 struct jrefrec *refrec;
1718 struct suj_rec *srn;
1719 struct jrefrec *rrn;
1721 refrec = (struct jrefrec *)srec->sr_rec;
1723 * We walk backwards so that the oldest link count is preserved. If
1724 * an add record conflicts with a remove keep the remove. Redundant
1725 * removes are eliminated in ino_build_ref. Otherwise we keep the
1726 * oldest record at a given location.
1728 for (srn = TAILQ_LAST(&sino->si_recs, srechd); srn;
1729 srn = TAILQ_PREV(srn, srechd, sr_next)) {
1730 rrn = (struct jrefrec *)srn->sr_rec;
1731 if (rrn->jr_parent != refrec->jr_parent ||
1732 rrn->jr_diroff != refrec->jr_diroff)
1734 if (rrn->jr_op == JOP_REMREF || refrec->jr_op == JOP_ADDREF) {
1735 rrn->jr_mode = refrec->jr_mode;
1741 * Replace the record in place with the old nlink in case
1742 * we replace the head of the list. Abandon srec as a dup.
1744 refrec->jr_nlink = rrn->jr_nlink;
1745 srn->sr_rec = srec->sr_rec;
1748 TAILQ_INSERT_TAIL(&sino->si_recs, srec, sr_next);
1752 * Create a duplicate of a reference at a previous location.
1755 ino_dup_ref(struct suj_ino *sino, struct jrefrec *refrec, off_t diroff)
1757 struct jrefrec *rrn;
1758 struct suj_rec *srn;
1760 rrn = errmalloc(sizeof(*refrec));
1762 rrn->jr_op = JOP_ADDREF;
1763 rrn->jr_diroff = diroff;
1764 srn = errmalloc(sizeof(*srn));
1765 srn->sr_rec = (union jrec *)rrn;
1766 ino_add_ref(sino, srn);
1770 * Add a reference to the list at all known locations. We follow the offset
1771 * changes for a single instance and create duplicate add refs at each so
1772 * that we can tolerate any version of the directory block. Eliminate
1773 * removes which collide with adds that are seen in the journal. They should
1774 * not adjust the link count down.
1777 ino_build_ref(struct suj_ino *sino, struct suj_rec *srec)
1779 struct jrefrec *refrec;
1780 struct jmvrec *mvrec;
1781 struct suj_rec *srp;
1782 struct suj_rec *srn;
1783 struct jrefrec *rrn;
1786 refrec = (struct jrefrec *)srec->sr_rec;
1788 * Search for a mvrec that matches this offset. Whether it's an add
1789 * or a remove we can delete the mvref after creating a dup record in
1792 if (!TAILQ_EMPTY(&sino->si_movs)) {
1793 diroff = refrec->jr_diroff;
1794 for (srn = TAILQ_LAST(&sino->si_movs, srechd); srn; srn = srp) {
1795 srp = TAILQ_PREV(srn, srechd, sr_next);
1796 mvrec = (struct jmvrec *)srn->sr_rec;
1797 if (mvrec->jm_parent != refrec->jr_parent ||
1798 mvrec->jm_newoff != diroff)
1800 diroff = mvrec->jm_oldoff;
1801 TAILQ_REMOVE(&sino->si_movs, srn, sr_next);
1803 ino_dup_ref(sino, refrec, diroff);
1807 * If a remove wasn't eliminated by an earlier add just append it to
1810 if (refrec->jr_op == JOP_REMREF) {
1811 ino_add_ref(sino, srec);
1815 * Walk the list of records waiting to be added to the list. We
1816 * must check for moves that apply to our current offset and remove
1817 * them from the list. Remove any duplicates to eliminate removes
1818 * with corresponding adds.
1820 TAILQ_FOREACH_SAFE(srn, &sino->si_newrecs, sr_next, srp) {
1821 switch (srn->sr_rec->rec_jrefrec.jr_op) {
1824 * This should actually be an error we should
1825 * have a remove for every add journaled.
1827 rrn = (struct jrefrec *)srn->sr_rec;
1828 if (rrn->jr_parent != refrec->jr_parent ||
1829 rrn->jr_diroff != refrec->jr_diroff)
1831 TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1835 * Once we remove the current iteration of the
1836 * record at this address we're done.
1838 rrn = (struct jrefrec *)srn->sr_rec;
1839 if (rrn->jr_parent != refrec->jr_parent ||
1840 rrn->jr_diroff != refrec->jr_diroff)
1842 TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1843 ino_add_ref(sino, srec);
1847 * Update our diroff based on any moves that match
1848 * and remove the move.
1850 mvrec = (struct jmvrec *)srn->sr_rec;
1851 if (mvrec->jm_parent != refrec->jr_parent ||
1852 mvrec->jm_oldoff != refrec->jr_diroff)
1854 ino_dup_ref(sino, refrec, mvrec->jm_oldoff);
1855 refrec->jr_diroff = mvrec->jm_newoff;
1856 TAILQ_REMOVE(&sino->si_newrecs, srn, sr_next);
1859 err_suj("ino_build_ref: Unknown op %s\n",
1860 JOP_OPTYPE(srn->sr_rec->rec_jrefrec.jr_op));
1863 ino_add_ref(sino, srec);
1867 * Walk the list of new records and add them in-order resolving any
1868 * dups and adjusted offsets.
1871 ino_build(struct suj_ino *sino)
1873 struct suj_rec *srec;
1875 while ((srec = TAILQ_FIRST(&sino->si_newrecs)) != NULL) {
1876 TAILQ_REMOVE(&sino->si_newrecs, srec, sr_next);
1877 switch (srec->sr_rec->rec_jrefrec.jr_op) {
1880 ino_build_ref(sino, srec);
1884 * Add this mvrec to the queue of pending mvs.
1886 TAILQ_INSERT_TAIL(&sino->si_movs, srec, sr_next);
1889 err_suj("ino_build: Unknown op %s\n",
1890 JOP_OPTYPE(srec->sr_rec->rec_jrefrec.jr_op));
1893 if (TAILQ_EMPTY(&sino->si_recs))
1894 sino->si_hasrecs = 0;
1898 * Modify journal records so they refer to the base block number
1899 * and a start and end frag range. This is to facilitate the discovery
1900 * of overlapping fragment allocations.
1903 blk_build(struct jblkrec *blkrec)
1905 struct suj_rec *srec;
1906 struct suj_blk *sblk;
1907 struct jblkrec *blkrn;
1912 printf("blk_build: op %s blkno %jd frags %d oldfrags %d "
1913 "ino %ju lbn %jd\n",
1914 JOP_OPTYPE(blkrec->jb_op), (uintmax_t)blkrec->jb_blkno,
1915 blkrec->jb_frags, blkrec->jb_oldfrags,
1916 (uintmax_t)blkrec->jb_ino, (uintmax_t)blkrec->jb_lbn);
1918 blk = blknum(fs, blkrec->jb_blkno);
1919 frag = fragnum(fs, blkrec->jb_blkno);
1920 if (blkrec->jb_blkno < 0 || blk + fs->fs_frag - frag > fs->fs_size)
1921 err_suj("Out-of-bounds journal block number %jd\n",
1923 sblk = blk_lookup(blk, 1);
1925 * Rewrite the record using oldfrags to indicate the offset into
1926 * the block. Leave jb_frags as the actual allocated count.
1928 blkrec->jb_blkno -= frag;
1929 blkrec->jb_oldfrags = frag;
1930 if (blkrec->jb_oldfrags + blkrec->jb_frags > fs->fs_frag)
1931 err_suj("Invalid fragment count %d oldfrags %d\n",
1932 blkrec->jb_frags, frag);
1934 * Detect dups. If we detect a dup we always discard the oldest
1935 * record as it is superseded by the new record. This speeds up
1936 * later stages but also eliminates free records which are used
1937 * to indicate that the contents of indirects can be trusted.
1939 TAILQ_FOREACH(srec, &sblk->sb_recs, sr_next) {
1940 blkrn = (struct jblkrec *)srec->sr_rec;
1941 if (blkrn->jb_ino != blkrec->jb_ino ||
1942 blkrn->jb_lbn != blkrec->jb_lbn ||
1943 blkrn->jb_blkno != blkrec->jb_blkno ||
1944 blkrn->jb_frags != blkrec->jb_frags ||
1945 blkrn->jb_oldfrags != blkrec->jb_oldfrags)
1948 printf("Removed dup.\n");
1949 /* Discard the free which is a dup with an alloc. */
1950 if (blkrec->jb_op == JOP_FREEBLK)
1952 TAILQ_REMOVE(&sblk->sb_recs, srec, sr_next);
1956 srec = errmalloc(sizeof(*srec));
1957 srec->sr_rec = (union jrec *)blkrec;
1958 TAILQ_INSERT_TAIL(&sblk->sb_recs, srec, sr_next);
1962 ino_build_trunc(struct jtrncrec *rec)
1964 struct suj_ino *sino;
1967 printf("ino_build_trunc: op %d ino %ju, size %jd\n",
1968 rec->jt_op, (uintmax_t)rec->jt_ino,
1969 (uintmax_t)rec->jt_size);
1970 if (chkfilesize(IFREG, rec->jt_size) == 0)
1971 err_suj("ino_build: truncation size too large %ju\n",
1972 (intmax_t)rec->jt_size);
1973 sino = ino_lookup(rec->jt_ino, 1);
1974 if (rec->jt_op == JOP_SYNC) {
1975 sino->si_trunc = NULL;
1978 if (sino->si_trunc == NULL || sino->si_trunc->jt_size > rec->jt_size)
1979 sino->si_trunc = rec;
1983 * Build up tables of the operations we need to recover.
1988 struct suj_seg *seg;
1993 TAILQ_FOREACH(seg, &allsegs, ss_next) {
1995 printf("seg %jd has %d records, oldseq %jd.\n",
1996 seg->ss_rec.jsr_seq, seg->ss_rec.jsr_cnt,
1997 seg->ss_rec.jsr_oldest);
1999 rec = (union jrec *)seg->ss_blk;
2000 for (i = 0; i < seg->ss_rec.jsr_cnt; off += JREC_SIZE, rec++) {
2001 /* skip the segrec. */
2002 if ((off % real_dev_bsize) == 0)
2004 switch (rec->rec_jrefrec.jr_op) {
2012 blk_build((struct jblkrec *)rec);
2016 ino_build_trunc((struct jtrncrec *)rec);
2019 err_suj("Unknown journal operation %s at %d\n",
2020 JOP_OPTYPE(rec->rec_jrefrec.jr_op), off);
2028 * Prune the journal segments to those we care about based on the
2029 * oldest sequence in the newest segment. Order the segment list
2030 * based on sequence number.
2035 struct suj_seg *seg;
2036 struct suj_seg *segn;
2041 printf("Pruning up to %jd\n", oldseq);
2042 /* First free the expired segments. */
2043 TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2044 if (seg->ss_rec.jsr_seq >= oldseq)
2046 TAILQ_REMOVE(&allsegs, seg, ss_next);
2050 /* Next ensure that segments are ordered properly. */
2051 seg = TAILQ_FIRST(&allsegs);
2054 printf("Empty journal\n");
2057 newseq = seg->ss_rec.jsr_seq;
2059 seg = TAILQ_LAST(&allsegs, seghd);
2060 if (seg->ss_rec.jsr_seq >= newseq)
2062 TAILQ_REMOVE(&allsegs, seg, ss_next);
2063 TAILQ_INSERT_HEAD(&allsegs, seg, ss_next);
2064 newseq = seg->ss_rec.jsr_seq;
2067 if (newseq != oldseq) {
2068 TAILQ_FOREACH(seg, &allsegs, ss_next) {
2069 printf("%jd, ", seg->ss_rec.jsr_seq);
2072 err_suj("Journal file sequence mismatch %jd != %jd\n",
2076 * The kernel may asynchronously write segments which can create
2077 * gaps in the sequence space. Throw away any segments after the
2078 * gap as the kernel guarantees only those that are contiguously
2079 * reachable are marked as completed.
2082 TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2083 if (!discard && newseq++ == seg->ss_rec.jsr_seq) {
2084 jrecs += seg->ss_rec.jsr_cnt;
2085 jbytes += seg->ss_rec.jsr_blocks * real_dev_bsize;
2090 printf("Journal order mismatch %jd != %jd pruning\n",
2091 newseq-1, seg->ss_rec.jsr_seq);
2092 TAILQ_REMOVE(&allsegs, seg, ss_next);
2097 printf("Processing journal segments from %jd to %jd\n",
2102 * Verify the journal inode before attempting to read records.
2105 suj_verifyino(union dinode *dp)
2108 if (DIP(dp, di_nlink) != 1) {
2109 printf("Invalid link count %d for journal inode %ju\n",
2110 DIP(dp, di_nlink), (uintmax_t)sujino);
2114 if ((DIP(dp, di_flags) & (SF_IMMUTABLE | SF_NOUNLINK)) !=
2115 (SF_IMMUTABLE | SF_NOUNLINK)) {
2116 printf("Invalid flags 0x%X for journal inode %ju\n",
2117 DIP(dp, di_flags), (uintmax_t)sujino);
2121 if (DIP(dp, di_mode) != (IFREG | IREAD)) {
2122 printf("Invalid mode %o for journal inode %ju\n",
2123 DIP(dp, di_mode), (uintmax_t)sujino);
2127 if (DIP(dp, di_size) < SUJ_MIN) {
2128 printf("Invalid size %jd for journal inode %ju\n",
2129 DIP(dp, di_size), (uintmax_t)sujino);
2133 if (DIP(dp, di_modrev) != fs->fs_mtime) {
2134 if (!bkgrdcheck || debug)
2135 printf("Journal timestamp does not match "
2144 struct jextent *jb_extent; /* Extent array. */
2145 int jb_avail; /* Available extents. */
2146 int jb_used; /* Last used extent. */
2147 int jb_head; /* Allocator head. */
2148 int jb_off; /* Allocator extent offset. */
2151 ufs2_daddr_t je_daddr; /* Disk block address. */
2152 int je_blocks; /* Disk block count. */
2155 static struct jblocks *suj_jblocks;
2157 static struct jblocks *
2158 jblocks_create(void)
2160 struct jblocks *jblocks;
2163 jblocks = errmalloc(sizeof(*jblocks));
2164 jblocks->jb_avail = 10;
2165 jblocks->jb_used = 0;
2166 jblocks->jb_head = 0;
2167 jblocks->jb_off = 0;
2168 size = sizeof(struct jextent) * jblocks->jb_avail;
2169 jblocks->jb_extent = errmalloc(size);
2170 bzero(jblocks->jb_extent, size);
2176 * Return the next available disk block and the amount of contiguous
2177 * free space it contains.
2180 jblocks_next(struct jblocks *jblocks, int bytes, int *actual)
2182 struct jextent *jext;
2187 blocks = btodb(bytes);
2188 jext = &jblocks->jb_extent[jblocks->jb_head];
2189 freecnt = jext->je_blocks - jblocks->jb_off;
2191 jblocks->jb_off = 0;
2192 if (++jblocks->jb_head > jblocks->jb_used)
2194 jext = &jblocks->jb_extent[jblocks->jb_head];
2195 freecnt = jext->je_blocks;
2197 if (freecnt > blocks)
2199 *actual = dbtob(freecnt);
2200 daddr = jext->je_daddr + jblocks->jb_off;
2206 * Advance the allocation head by a specified number of bytes, consuming
2207 * one journal segment.
2210 jblocks_advance(struct jblocks *jblocks, int bytes)
2213 jblocks->jb_off += btodb(bytes);
2217 jblocks_destroy(struct jblocks *jblocks)
2220 free(jblocks->jb_extent);
2225 jblocks_add(struct jblocks *jblocks, ufs2_daddr_t daddr, int blocks)
2227 struct jextent *jext;
2230 jext = &jblocks->jb_extent[jblocks->jb_used];
2231 /* Adding the first block. */
2232 if (jext->je_daddr == 0) {
2233 jext->je_daddr = daddr;
2234 jext->je_blocks = blocks;
2237 /* Extending the last extent. */
2238 if (jext->je_daddr + jext->je_blocks == daddr) {
2239 jext->je_blocks += blocks;
2242 /* Adding a new extent. */
2243 if (++jblocks->jb_used == jblocks->jb_avail) {
2244 jblocks->jb_avail *= 2;
2245 size = sizeof(struct jextent) * jblocks->jb_avail;
2246 jext = errmalloc(size);
2248 bcopy(jblocks->jb_extent, jext,
2249 sizeof(struct jextent) * jblocks->jb_used);
2250 free(jblocks->jb_extent);
2251 jblocks->jb_extent = jext;
2253 jext = &jblocks->jb_extent[jblocks->jb_used];
2254 jext->je_daddr = daddr;
2255 jext->je_blocks = blocks;
2261 * Add a file block from the journal to the extent map. We can't read
2262 * each file block individually because the kernel treats it as a circular
2263 * buffer and segments may span multiple contiguous blocks.
2266 suj_add_block(ino_t ino, ufs_lbn_t lbn, ufs2_daddr_t blk, int frags)
2269 jblocks_add(suj_jblocks, fsbtodb(fs, blk), fsbtodb(fs, frags));
2275 uint8_t block[1 * 1024 * 1024] __aligned(LIBUFS_BUFALIGN);
2276 struct suj_seg *seg;
2277 struct jsegrec *recn;
2278 struct jsegrec *rec;
2287 * Read records until we exhaust the journal space. If we find
2288 * an invalid record we start searching for a valid segment header
2289 * at the next block. This is because we don't have a head/tail
2290 * pointer and must recover the information indirectly. At the gap
2291 * between the head and tail we won't necessarily have a valid
2296 size = sizeof(block);
2297 blk = jblocks_next(suj_jblocks, size, &readsize);
2302 * Read 1MB at a time and scan for records within this block.
2304 if (pread(fsreadfd, &block, size, dbtob(blk)) != size) {
2305 err_suj("Error reading journal block %jd\n",
2308 for (rec = (void *)block; size; size -= recsize,
2309 rec = (struct jsegrec *)((uintptr_t)rec + recsize)) {
2310 recsize = real_dev_bsize;
2311 if (rec->jsr_time != fs->fs_mtime) {
2314 printf("Rec time %jd != fs mtime %jd\n",
2315 rec->jsr_time, fs->fs_mtime);
2317 jblocks_advance(suj_jblocks, recsize);
2320 if (rec->jsr_cnt == 0) {
2322 printf("Found illegal count %d\n",
2324 jblocks_advance(suj_jblocks, recsize);
2327 blocks = rec->jsr_blocks;
2328 recsize = blocks * real_dev_bsize;
2329 if (recsize > size) {
2331 * We may just have run out of buffer, restart
2332 * the loop to re-read from this spot.
2334 if (size < fs->fs_bsize &&
2336 recsize <= fs->fs_bsize)
2339 printf("Found invalid segsize "
2340 "%d > %d\n", recsize, size);
2341 recsize = real_dev_bsize;
2342 jblocks_advance(suj_jblocks, recsize);
2346 * Verify that all blocks in the segment are present.
2348 for (i = 1; i < blocks; i++) {
2349 recn = (void *)((uintptr_t)rec) + i *
2351 if (recn->jsr_seq == rec->jsr_seq &&
2352 recn->jsr_time == rec->jsr_time)
2355 printf("Incomplete record %jd (%d)\n",
2357 recsize = i * real_dev_bsize;
2358 jblocks_advance(suj_jblocks, recsize);
2361 seg = errmalloc(sizeof(*seg));
2362 seg->ss_blk = errmalloc(recsize);
2364 bcopy((void *)rec, seg->ss_blk, recsize);
2365 if (rec->jsr_oldest > oldseq)
2366 oldseq = rec->jsr_oldest;
2367 TAILQ_INSERT_TAIL(&allsegs, seg, ss_next);
2368 jblocks_advance(suj_jblocks, recsize);
2374 * Orchestrate the verification of a filesystem via the softupdates journal.
2377 suj_check(const char *filesys)
2379 struct inodesc idesc;
2381 union dinode *dp, *jip;
2385 struct suj_seg *seg;
2386 struct suj_seg *segn;
2390 if (real_dev_bsize == 0 && ioctl(fsreadfd, DIOCGSECTORSIZE,
2391 &real_dev_bsize) == -1)
2392 real_dev_bsize = secsize;
2394 printf("dev_bsize %u\n", real_dev_bsize);
2397 * Set an exit point when SUJ check failed
2399 retval = setjmp(jmpbuf);
2401 pwarn("UNEXPECTED SU+J INCONSISTENCY\n");
2402 TAILQ_FOREACH_SAFE(seg, &allsegs, ss_next, segn) {
2403 TAILQ_REMOVE(&allsegs, seg, ss_next);
2407 if (reply("FALLBACK TO FULL FSCK") == 0) {
2415 * Search the root directory for the SUJ_FILE.
2417 idesc.id_type = DATA;
2418 idesc.id_fix = IGNORE;
2419 idesc.id_number = UFS_ROOTINO;
2420 idesc.id_func = findino;
2421 idesc.id_name = SUJ_FILE;
2422 ginode(UFS_ROOTINO, &ip);
2424 if ((DIP(dp, di_mode) & IFMT) != IFDIR) {
2426 err_suj("root inode is not a directory\n");
2428 if (DIP(dp, di_size) < 0 || DIP(dp, di_size) > MAXDIRSIZE) {
2430 err_suj("negative or oversized root directory %jd\n",
2431 (uintmax_t)DIP(dp, di_size));
2433 if ((ckinode(dp, &idesc) & FOUND) == FOUND) {
2434 sujino = idesc.id_parent;
2437 if (!bkgrdcheck || debug)
2438 printf("Journal inode removed. "
2439 "Use tunefs to re-create.\n");
2440 sblock.fs_flags &= ~FS_SUJ;
2441 sblock.fs_sujfree = 0;
2446 * Fetch the journal inode and verify it.
2448 ginode(sujino, &ip);
2450 if (!bkgrdcheck || debug)
2451 printf("** SU+J Recovering %s\n", filesys);
2452 if (suj_verifyino(jip) != 0 || (!preen && !reply("USE JOURNAL"))) {
2457 * Build a list of journal blocks in jblocks before parsing the
2458 * available journal blocks in with suj_read().
2460 if (!bkgrdcheck || debug)
2461 printf("** Reading %jd byte journal from inode %ju.\n",
2462 DIP(jip, di_size), (uintmax_t)sujino);
2463 suj_jblocks = jblocks_create();
2464 blocks = ino_visit(jip, sujino, suj_add_block, 0);
2465 if (blocks != numfrags(fs, DIP(jip, di_size))) {
2466 if (!bkgrdcheck || debug)
2467 printf("Sparse journal inode %ju.\n",
2472 /* If journal is valid then do journal check rather than background */
2479 jblocks_destroy(suj_jblocks);
2481 if (preen || reply("RECOVER")) {
2482 printf("** Building recovery table.\n");
2486 printf("** Resolving unreferenced inode list.\n");
2488 printf("** Processing journal entries.\n");
2490 cg_apply(cg_check_blk);
2491 cg_apply(cg_adj_blk);
2492 cg_apply(cg_check_ino);
2494 if (preen == 0 && (jrecs > 0 || jbytes > 0) &&
2495 reply("WRITE CHANGES") == 0)
2498 * Check block counts of snapshot inodes and
2499 * make copies of any needed snapshot blocks.
2501 for (i = 0; i < snapcnt; i++)
2502 check_blkcnt(&snaplist[i]);
2503 snapflush(suj_checkblkavail);
2505 * Recompute the fs summary info from correct cs summaries.
2507 bzero(&fs->fs_cstotal, sizeof(struct csum_total));
2508 for (i = 0; i < fs->fs_ncg; i++) {
2509 cgsum = &fs->fs_cs(fs, i);
2510 fs->fs_cstotal.cs_nffree += cgsum->cs_nffree;
2511 fs->fs_cstotal.cs_nbfree += cgsum->cs_nbfree;
2512 fs->fs_cstotal.cs_nifree += cgsum->cs_nifree;
2513 fs->fs_cstotal.cs_ndir += cgsum->cs_ndir;
2515 fs->fs_pendinginodes = 0;
2516 fs->fs_pendingblocks = 0;
2518 fs->fs_time = time(NULL);
2519 fs->fs_mtime = time(NULL);
2522 if (jrecs > 0 || jbytes > 0) {
2523 printf("** %jd journal records in %jd bytes for %.2f%% "
2524 "utilization\n", jrecs, jbytes,
2525 ((float)jrecs / (float)(jbytes / JREC_SIZE)) * 100);
2526 printf("** Freed %jd inodes (%jd dirs) %jd blocks, and %jd "
2527 "frags.\n", freeinos, freedir, freeblocks, freefrags);
2538 for (i = 0; i < HASHSIZE; i++)
2539 LIST_INIT(&cghash[i]);
2541 TAILQ_INIT(&allsegs);