diff options
Diffstat (limited to 'e2fsck')
45 files changed, 32137 insertions, 0 deletions
diff --git a/e2fsck/Android.bp b/e2fsck/Android.bp new file mode 100644 index 0000000..b42de9d --- /dev/null +++ b/e2fsck/Android.bp @@ -0,0 +1,86 @@ +// Copyright 2017 The Android Open Source Project + +//######################## +// Build the e2fsck binary + +package { + // See: http://go/android-license-faq + // A large-scale-change added 'default_applicable_licenses' to import + // all of the 'license_kinds' from "external_e2fsprogs_license" + // to get the below license kinds: + // SPDX-license-identifier-GPL + // SPDX-license-identifier-GPL-2.0 + // SPDX-license-identifier-LGPL + default_applicable_licenses: ["external_e2fsprogs_license"], +} + +cc_defaults { + name: "e2fsck-defaults", + defaults: ["e2fsprogs-defaults"], + srcs: [ + "e2fsck.c", + "super.c", + "pass1.c", + "pass1b.c", + "pass2.c", + "pass3.c", + "pass4.c", + "pass5.c", + "logfile.c", + "journal.c", + "recovery.c", + "revoke.c", + "badblocks.c", + "util.c", + "unix.c", + "dirinfo.c", + "dx_dirinfo.c", + "ehandler.c", + "problem.c", + "message.c", + "ea_refcount.c", + "quota.c", + "rehash.c", + "region.c", + "sigcatcher.c", + "readahead.c", + "extents.c", + "encrypted_files.c", + ], +} + +e2fsck_libs = [ + "libext2fs", + "libext2_blkid", + "libext2_com_err", + "libext2_uuid", + "libext2_quota", + "libext2_e2p", +] + +cc_binary { + name: "e2fsck", + host_supported: true, + vendor_ramdisk_available: true, + defaults: ["e2fsck-defaults"], + + shared_libs: e2fsck_libs, + required: ["badblocks"], +} + +cc_binary { + name: "e2fsck_static", + static_executable: true, + defaults: ["e2fsck-defaults"], + + static_libs: e2fsck_libs, +} + +cc_binary { + name: "e2fsck_ramdisk", + stem: "e2fsck", + static_executable: true, + ramdisk: true, + defaults: ["e2fsck-defaults"], + static_libs: e2fsck_libs, +} diff --git a/e2fsck/CHANGES b/e2fsck/CHANGES new file mode 100644 index 0000000..eb4cfde --- /dev/null +++ b/e2fsck/CHANGES @@ -0,0 +1,53 @@ +[tytso:19940101.1200EST] + +Add new options -l and -L, to append to and modify the bad-blocks list. + +Fix bugs in bad-block cloning. + +[tytso:19931230.1832EST] + +Clean up e2fsck and library to be clean even when compiling with full +warnings enabled. + +Make e2fsck deal with zero-length directories correctly. + +Deleted inodes from old ext2fs code (inodes with dtime set but +non-zero link count) are detected, and the user is given the +opportunity to clear them. + +The last bit in the last group of the block bitmap padding was not +being checked; now fixed. + +The free_blocks and free_inodes count in the last group weren't being +checked. Now fixed. + +[tytso:19931101.0007EST] + +Fixed bugs with root reallocation; previously the parent pointers in +the dirinfo structure would get corrupted, causing many different '..' +links to be wrong. Also, the inode link count for the root directory +wasn't always being set correctly. (All of this would be fixed on +the second e2fsck, however). + +Fixed to recognize filesystem corruption caused by mke2fs 0.2b (where +/ and /lost+found had non-zero dtime entries). Offers to fix /'s +dtime entry. + +e2fsck will now expand the /lost+found directory if it runs out of room. + +Fixed dependency on BLOCK_SIZE in pass2. e2fsck will now handle 4k +filesystems w/o problems. + +e2fsck will now move bad blocks found in the inode bitmaps, block +bitmaps, and in the inode tables. (Can't handle bad blocks found in +the superblock and the group descriptors.) (Doesn't update alternate +superblocks, group descriptors.) + +e2fsck now supports the -b option, to allow a user to specify an +alternate superblock. + +The -B option now specifies the blocksize of the filesystem. (If not +specified, and the -b option is specified, e2fsck will attempt to +search through various blocksizes to find the correct one.) + +Added manual page. diff --git a/e2fsck/Makefile.in b/e2fsck/Makefile.in new file mode 100644 index 0000000..fbb7b15 --- /dev/null +++ b/e2fsck/Makefile.in @@ -0,0 +1,656 @@ +# +# Makefile for e2fsck +# + +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +VPATH = @srcdir@ +top_builddir = .. +my_dir = e2fsck +INSTALL = @INSTALL@ +MKDIR_P = @MKDIR_P@ + +@MCONFIG@ + +PROGS= e2fsck +MANPAGES= e2fsck.8 +FMANPAGES= e2fsck.conf.5 + +LIBS= $(LIBSUPPORT) $(LIBEXT2FS) $(LIBCOM_ERR) $(LIBBLKID) $(LIBUUID) \ + $(LIBINTL) $(LIBE2P) $(LIBMAGIC) $(SYSLIBS) +DEPLIBS= $(DEPLIBSUPPORT) $(LIBEXT2FS) $(DEPLIBCOM_ERR) $(DEPLIBBLKID) \ + $(DEPLIBUUID) $(DEPLIBE2P) + +STATIC_LIBS= $(STATIC_LIBSUPPORT) $(STATIC_LIBEXT2FS) $(STATIC_LIBCOM_ERR) \ + $(STATIC_LIBBLKID) $(STATIC_LIBUUID) $(LIBINTL) $(STATIC_LIBE2P) \ + $(LIBMAGIC) $(SYSLIBS) +STATIC_DEPLIBS= $(DEPSTATIC_LIBSUPPORT) $(STATIC_LIBEXT2FS) \ + $(DEPSTATIC_LIBCOM_ERR) $(DEPSTATIC_LIBBLKID) \ + $(DEPSTATIC_LIBUUID) $(DEPSTATIC_LIBE2P) + +PROFILED_LIBS= $(PROFILED_LIBSUPPORT) $(PROFILED_LIBEXT2FS) \ + $(PROFILED_LIBCOM_ERR) $(PROFILED_LIBBLKID) $(PROFILED_LIBUUID) \ + $(PROFILED_LIBE2P) $(LIBINTL) $(LIBMAGIC) $(SYSLIBS) +PROFILED_DEPLIBS= $(DEPPROFILED_LIBSUPPORT) $(PROFILED_LIBEXT2FS) \ + $(DEPPROFILED_LIBCOM_ERR) $(DEPPROFILED_LIBBLKID) \ + $(DEPPROFILED_LIBUUID) $(DEPPROFILED_LIBE2P) + +COMPILE_ET= _ET_DIR_OVERRIDE=$(srcdir)/../lib/et/et ../lib/et/compile_et + +.c.o: + $(E) " CC $<" + $(Q) $(CC) -c $(ALL_CFLAGS) $< -o $@ + $(Q) $(CHECK_CMD) $(ALL_CFLAGS) $< + $(Q) $(CPPCHECK_CMD) $(CPPFLAGS) $< +@PROFILE_CMT@ $(Q) $(CC) $(ALL_CFLAGS) -g -pg -o profiled/$*.o -c $< + +# +# Flags for doing mtrace --- uncomment to produce mtracing e2fsck +# Note: The optimization flags must include -g +# +#MTRACE= -DMTRACE +#MTRACE_OBJ= mtrace.o +#MTRACE_SRC= $(srcdir)/mtrace.c +#OPT= -g + +# +# Flags for doing mcheck --- uncomment to produce mchecking e2fsck +# Note: The optimization flags must include -g +# +#MCHECK= -DMCHECK + +OBJS= unix.o e2fsck.o super.o pass1.o pass1b.o pass2.o \ + pass3.o pass4.o pass5.o journal.o badblocks.o util.o dirinfo.o \ + dx_dirinfo.o ehandler.o problem.o message.o quota.o recovery.o \ + region.o revoke.o ea_refcount.o rehash.o \ + logfile.o sigcatcher.o $(MTRACE_OBJ) readahead.o \ + extents.o encrypted_files.o + +PROFILED_OBJS= profiled/unix.o profiled/e2fsck.o \ + profiled/super.o profiled/pass1.o profiled/pass1b.o \ + profiled/pass2.o profiled/pass3.o profiled/pass4.o profiled/pass5.o \ + profiled/journal.o profiled/badblocks.o profiled/util.o \ + profiled/dirinfo.o profiled/dx_dirinfo.o profiled/ehandler.o \ + profiled/message.o profiled/problem.o profiled/quota.o \ + profiled/recovery.o profiled/region.o profiled/revoke.o \ + profiled/ea_refcount.o profiled/rehash.o \ + profiled/logfile.o profiled/sigcatcher.o \ + profiled/readahead.o profiled/extents.o \ + profiled/encrypted_files.o + +SRCS= $(srcdir)/e2fsck.c \ + $(srcdir)/super.c \ + $(srcdir)/pass1.c \ + $(srcdir)/pass1b.c \ + $(srcdir)/pass2.c \ + $(srcdir)/pass3.c \ + $(srcdir)/pass4.c \ + $(srcdir)/pass5.c \ + $(srcdir)/journal.c \ + $(srcdir)/recovery.c \ + $(srcdir)/revoke.c \ + $(srcdir)/badblocks.c \ + $(srcdir)/util.c \ + $(srcdir)/unix.c \ + $(srcdir)/dirinfo.c \ + $(srcdir)/dx_dirinfo.c \ + $(srcdir)/ehandler.c \ + $(srcdir)/problem.c \ + $(srcdir)/message.c \ + $(srcdir)/ea_refcount.c \ + $(srcdir)/rehash.c \ + $(srcdir)/readahead.c \ + $(srcdir)/region.c \ + $(srcdir)/sigcatcher.c \ + $(srcdir)/logfile.c \ + $(srcdir)/quota.c \ + $(srcdir)/extents.c \ + $(srcdir)/encrypted_files.c \ + $(MTRACE_SRC) + +all:: profiled $(PROGS) e2fsck $(MANPAGES) $(FMANPAGES) + +@PROFILE_CMT@all:: e2fsck.profiled + +all-static:: e2fsck.static + +e2fsck: $(OBJS) $(DEPLIBS) + $(E) " LD $@" + $(Q) $(LD) $(ALL_LDFLAGS) $(RDYNAMIC) -o e2fsck $(OBJS) $(LIBS) + +e2fsck.static: $(OBJS) $(STATIC_DEPLIBS) + $(E) " LD $@" + $(Q) $(LD) $(LDFLAGS_STATIC) -o e2fsck.static $(OBJS) $(STATIC_LIBS) + +e2fsck.profiled: $(OBJS) $(PROFILED_DEPLIBS) + $(E) " LD $@" + $(Q) $(LD) $(ALL_LDFLAGS) -g -pg -o e2fsck.profiled $(PROFILED_OBJS) \ + $(PROFILED_LIBS) + +tst_sigcatcher: $(srcdir)/sigcatcher.c sigcatcher.o + $(E) " CC $@" + $(Q) $(CC) $(ALL_CFLAGS) $(ALL_LDFLAGS) $(RDYNAMIC) \ + $(srcdir)/sigcatcher.c -DDEBUG -o tst_sigcatcher + +tst_problem: $(srcdir)/problem.c $(srcdir)/problem.h $(LIBEXT2FS) \ + $(DEPLIBCOM_ERR) + $(Q) $(CC) $(ALL_CFLAGS) $(ALL_LDFLAGS) -o tst_problem \ + $(srcdir)/problem.c -DUNITTEST $(LIBEXT2FS) $(LIBCOM_ERR) \ + $(LIBINTL) $(SYSLIBS) + +tst_refcount: ea_refcount.c $(DEPLIBCOM_ERR) $(LIBEXT2FS) + $(E) " LD $@" + $(Q) $(CC) -o tst_refcount $(srcdir)/ea_refcount.c \ + $(ALL_CFLAGS) $(ALL_LDFLAGS) -DTEST_PROGRAM \ + $(LIBCOM_ERR) $(LIBEXT2FS) $(SYSLIBS) + +tst_logfile: $(srcdir)/logfile.c + $(E) " LD $@" + $(Q) $(CC) -o tst_logfile $(srcdir)/logfile.c \ + $(ALL_CFLAGS) $(ALL_LDFLAGS) -DTEST_PROGRAM $(SYSLIBS) + +tst_region: region.c $(LIBEXT2FS) $(DEPLIBCOM_ERR) + $(E) " LD $@" + $(Q) $(CC) -o tst_region $(srcdir)/region.c \ + $(ALL_CFLAGS) $(ALL_LDFLAGS) -DTEST_PROGRAM \ + $(LIBEXT2FS) $(LIBCOM_ERR) $(SYSLIBS) + +fullcheck check:: tst_refcount tst_region tst_problem + $(TESTENV) ./tst_refcount + $(TESTENV) ./tst_region + $(TESTENV) ./tst_problem + +extend: extend.o + $(E) " LD $@" + $(Q) $(LD) $(ALL_LDFLAGS) -o extend extend.o $(CHECKLIB) + +flushb: flushb.o + $(E) " LD $@" + $(Q) $(LD) $(ALL_LDFLAGS) -o flushb flushb.o $(CHECKLIB) + +iscan: iscan.o $(DEPLIBS) + $(E) " LD $@" + $(Q) $(LD) $(ALL_LDFLAGS) -o iscan iscan.o $(LIBS) + +iscan.static: iscan.o $(STATIC_DEPLIBS) + $(E) " LD $@" + $(Q) $(LD) $(LDFLAGS_STATIC) -o iscan.static iscan.o $(STATIC_LIBS) + +test_profile: $(srcdir)/profile.c profile_helpers.o argv_parse.o \ + prof_err.o profile.h $(DEPSTATIC_LIBCOM_ERR) + $(E) " LD $@" + $(Q) $(CC) -o test_profile -DDEBUG_PROGRAM $(srcdir)/profile.c prof_err.o \ + profile_helpers.o argv_parse.o $(STATIC_LIBCOM_ERR) \ + $(ALL_CFLAGS) + +profiled: +@PROFILE_CMT@ $(E) " MKDIR $@" +@PROFILE_CMT@ $(Q) mkdir profiled + +e2fsck.8: $(DEP_SUBSTITUTE) $(srcdir)/e2fsck.8.in + $(E) " SUBST $@" + $(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/e2fsck.8.in e2fsck.8 + +e2fsck.conf.5: $(DEP_SUBSTITUTE) $(srcdir)/e2fsck.conf.5.in + $(E) " SUBST $@" + $(Q) $(SUBSTITUTE_UPTIME) $(srcdir)/e2fsck.conf.5.in e2fsck.conf.5 + +installdirs: + $(E) " MKDIR_P $(root_sbindir) $(man8dir)" + $(Q) $(MKDIR_P) $(DESTDIR)$(root_sbindir) \ + $(DESTDIR)$(man8dir) $(DESTDIR)$(man5dir) + +install: $(PROGS) $(MANPAGES) $(FMANPAGES) installdirs + $(Q) for i in $(PROGS); do \ + $(ES) " INSTALL $(root_sbindir)/$$i"; \ + $(INSTALL_PROGRAM) $$i $(DESTDIR)$(root_sbindir)/$$i; \ + done + $(Q) for i in ext2 ext3 ext4; do \ + $(ES) " LINK $(root_sbindir)/fsck.$$i"; \ + (cd $(DESTDIR)$(root_sbindir); \ + $(LN) $(LINK_INSTALL_FLAGS) e2fsck fsck.$$i); \ + done + $(Q) for i in $(MANPAGES); do \ + for j in $(COMPRESS_EXT); do \ + $(RM) -f $(DESTDIR)$(man8dir)/$$i.$$j; \ + done; \ + $(ES) " INSTALL_DATA $(man8dir)/$$i"; \ + $(INSTALL_DATA) $$i $(DESTDIR)$(man8dir)/$$i; \ + done + $(Q) for i in $(FMANPAGES); do \ + for j in $(COMPRESS_EXT); do \ + $(RM) -f $(DESTDIR)$(man5dir)/$$i.$$j; \ + done; \ + $(ES) " INSTALL_DATA $(man5dir)/$$i"; \ + $(INSTALL_DATA) $$i $(DESTDIR)$(man5dir)/$$i; \ + done + $(Q) for i in ext2 ext3 ext4; do \ + $(ES) " LINK $(man8dir)/fsck.$$i.8"; \ + (cd $(DESTDIR)$(man8dir); \ + $(LN) $(LINK_INSTALL_FLAGS) e2fsck.8 fsck.$$i.8); \ + done + +install-strip: install + $(Q) for i in $(PROGS); do \ + $(ES) " STRIP $(root_sbindir)/$$i"; \ + $(STRIP) $(DESTDIR)$(root_sbindir)/$$i; \ + done + +uninstall: + for i in $(PROGS); do \ + $(RM) -f $(DESTDIR)$(root_sbindir)/$$i; \ + done + $(RM) -f $(DESTDIR)$(root_sbindir)/fsck.ext2 \ + $(DESTDIR)$(root_sbindir)/fsck.ext3 \ + $(DESTDIR)$(root_sbindir)/fsck.ext4 + for i in $(MANPAGES); do \ + $(RM) -f $(DESTDIR)$(man8dir)/$$i; \ + done + for i in $(FMANPAGES); do \ + $(RM) -f $(DESTDIR)$(man5dir)/$$i; \ + done + $(RM) -f $(DESTDIR)$(root_sbindir)/fsck.ext2 \ + $(DESTDIR)$(root_sbindir)/fsck.ext3 \ + $(DESTDIR)$(root_sbindir)/fsck.ext4 + +clean:: + $(RM) -f $(PROGS) \#* *\# *.s *.o *.a *~ core e2fsck.static \ + e2fsck.shared e2fsck.profiled flushb e2fsck.8 \ + tst_problem tst_region tst_refcount tst_crc32 \ + gen_crc32table e2fsck.conf.5 \ + prof_err.c prof_err.h test_profile iscan iscan.static + $(RM) -rf profiled + +mostlyclean: clean +distclean: clean + $(RM) -f .depend Makefile $(srcdir)/TAGS $(srcdir)/Makefile.in.old + +# +++ Dependency line eater +++ +# +# Makefile dependencies follow. This must be the last section in +# the Makefile.in file +# +e2fsck.o: $(srcdir)/e2fsck.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +super.o: $(srcdir)/super.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +pass1.o: $(srcdir)/pass1.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(top_srcdir)/lib/e2p/e2p.h $(srcdir)/problem.h +pass1b.o: $(srcdir)/pass1b.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(top_srcdir)/lib/et/com_err.h \ + $(srcdir)/e2fsck.h $(top_srcdir)/lib/ext2fs/ext2_fs.h \ + $(top_builddir)/lib/ext2fs/ext2_types.h $(top_srcdir)/lib/ext2fs/ext2fs.h \ + $(top_srcdir)/lib/ext2fs/ext3_extents.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(top_srcdir)/lib/support/dict.h +pass2.o: $(srcdir)/pass2.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(top_srcdir)/lib/support/dict.h +pass3.o: $(srcdir)/pass3.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +pass4.o: $(srcdir)/pass4.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +pass5.o: $(srcdir)/pass5.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +journal.o: $(srcdir)/journal.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/jfs_user.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(top_srcdir)/lib/ext2fs/kernel-jbd.h $(srcdir)/problem.h +recovery.o: $(srcdir)/recovery.c $(srcdir)/jfs_user.h \ + $(top_builddir)/lib/config.h $(top_builddir)/lib/dirpaths.h \ + $(srcdir)/e2fsck.h $(top_srcdir)/lib/ext2fs/ext2_fs.h \ + $(top_builddir)/lib/ext2fs/ext2_types.h $(top_srcdir)/lib/ext2fs/ext2fs.h \ + $(top_srcdir)/lib/ext2fs/ext3_extents.h $(top_srcdir)/lib/et/com_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_io.h $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(top_srcdir)/lib/ext2fs/kernel-jbd.h +revoke.o: $(srcdir)/revoke.c $(srcdir)/jfs_user.h \ + $(top_builddir)/lib/config.h $(top_builddir)/lib/dirpaths.h \ + $(srcdir)/e2fsck.h $(top_srcdir)/lib/ext2fs/ext2_fs.h \ + $(top_builddir)/lib/ext2fs/ext2_types.h $(top_srcdir)/lib/ext2fs/ext2fs.h \ + $(top_srcdir)/lib/ext2fs/ext3_extents.h $(top_srcdir)/lib/et/com_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_io.h $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(top_srcdir)/lib/ext2fs/kernel-jbd.h +badblocks.o: $(srcdir)/badblocks.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(top_srcdir)/lib/et/com_err.h \ + $(srcdir)/e2fsck.h $(top_srcdir)/lib/ext2fs/ext2_fs.h \ + $(top_builddir)/lib/ext2fs/ext2_types.h $(top_srcdir)/lib/ext2fs/ext2fs.h \ + $(top_srcdir)/lib/ext2fs/ext3_extents.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +util.o: $(srcdir)/util.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +unix.o: $(srcdir)/unix.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(top_srcdir)/lib/e2p/e2p.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/support/plausible.h \ + $(top_srcdir)/lib/support/devname.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/ext2fs/ext2_io.h $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(srcdir)/jfs_user.h \ + $(top_srcdir)/lib/ext2fs/kernel-jbd.h $(top_srcdir)/version.h +dirinfo.o: $(srcdir)/dirinfo.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(top_srcdir)/lib/ext2fs/tdb.h +dx_dirinfo.o: $(srcdir)/dx_dirinfo.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +ehandler.o: $(srcdir)/ehandler.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +problem.o: $(srcdir)/problem.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(srcdir)/problemP.h +message.o: $(srcdir)/message.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/support/profile.h $(top_builddir)/lib/support/prof_err.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +ea_refcount.o: $(srcdir)/ea_refcount.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +rehash.o: $(srcdir)/rehash.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(top_srcdir)/lib/support/sort_r.h +readahead.o: $(srcdir)/readahead.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +region.o: $(srcdir)/region.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +sigcatcher.o: $(srcdir)/sigcatcher.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +logfile.o: $(srcdir)/logfile.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h +quota.o: $(srcdir)/quota.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +extents.o: $(srcdir)/extents.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h +encrypted_files.o: $(srcdir)/encrypted_files.c $(top_builddir)/lib/config.h \ + $(top_builddir)/lib/dirpaths.h $(srcdir)/e2fsck.h \ + $(top_srcdir)/lib/ext2fs/ext2_fs.h $(top_builddir)/lib/ext2fs/ext2_types.h \ + $(top_srcdir)/lib/ext2fs/ext2fs.h $(top_srcdir)/lib/ext2fs/ext3_extents.h \ + $(top_srcdir)/lib/et/com_err.h $(top_srcdir)/lib/ext2fs/ext2_io.h \ + $(top_builddir)/lib/ext2fs/ext2_err.h \ + $(top_srcdir)/lib/ext2fs/ext2_ext_attr.h $(top_srcdir)/lib/ext2fs/hashmap.h \ + $(top_srcdir)/lib/ext2fs/bitops.h $(top_srcdir)/lib/support/profile.h \ + $(top_builddir)/lib/support/prof_err.h $(top_srcdir)/lib/support/quotaio.h \ + $(top_srcdir)/lib/support/dqblk_v2.h \ + $(top_srcdir)/lib/support/quotaio_tree.h \ + $(top_srcdir)/lib/ext2fs/fast_commit.h $(top_srcdir)/lib/ext2fs/jfs_compat.h \ + $(top_srcdir)/lib/ext2fs/kernel-list.h $(top_srcdir)/lib/ext2fs/compiler.h \ + $(srcdir)/problem.h $(top_srcdir)/lib/ext2fs/rbtree.h diff --git a/e2fsck/badblocks.c b/e2fsck/badblocks.c new file mode 100644 index 0000000..fec5f10 --- /dev/null +++ b/e2fsck/badblocks.c @@ -0,0 +1,142 @@ +/* + * badblocks.c --- replace/append bad blocks to the bad block inode + * + * Copyright (C) 1993, 1994 Theodore Ts'o. This file may be + * redistributed under the terms of the GNU Public License. + */ + +#include "config.h" +#include <time.h> +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include <et/com_err.h> +#include "e2fsck.h" + +static int check_bb_inode_blocks(ext2_filsys fs, blk_t *block_nr, int blockcnt, + void *priv_data); + + +static void invalid_block(ext2_filsys fs EXT2FS_ATTR((unused)), blk_t blk) +{ + printf(_("Bad block %u out of range; ignored.\n"), blk); + return; +} + +void read_bad_blocks_file(e2fsck_t ctx, const char *bad_blocks_file, + int replace_bad_blocks) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + badblocks_list bb_list = 0; + FILE *f; + char buf[1024]; + + e2fsck_read_bitmaps(ctx); + + /* + * Make sure the bad block inode is sane. If there are any + * illegal blocks, clear them. + */ + retval = ext2fs_block_iterate(fs, EXT2_BAD_INO, 0, 0, + check_bb_inode_blocks, 0); + if (retval) { + com_err("ext2fs_block_iterate", retval, "%s", + _("while sanity checking the bad blocks inode")); + goto fatal; + } + + /* + * If we're appending to the bad blocks inode, read in the + * current bad blocks. + */ + if (!replace_bad_blocks) { + retval = ext2fs_read_bb_inode(fs, &bb_list); + if (retval) { + com_err("ext2fs_read_bb_inode", retval, "%s", + _("while reading the bad blocks inode")); + goto fatal; + } + } + + /* + * Now read in the bad blocks from the file; if + * bad_blocks_file is null, then try to run the badblocks + * command. + */ + if (bad_blocks_file) { + f = fopen(bad_blocks_file, "r"); + if (!f) { + com_err("read_bad_blocks_file", errno, + _("while trying to open %s"), bad_blocks_file); + goto fatal; + } + } else { + sprintf(buf, "badblocks -b %d -X %s%s%s %llu", fs->blocksize, + (ctx->options & E2F_OPT_PREEN) ? "" : "-s ", + (ctx->options & E2F_OPT_WRITECHECK) ? "-n " : "", + fs->device_name, + (unsigned long long) ext2fs_blocks_count(fs->super)-1); + f = popen(buf, "r"); + if (!f) { + com_err("read_bad_blocks_file", errno, + _("while trying popen '%s'"), buf); + goto fatal; + } + } + retval = ext2fs_read_bb_FILE(fs, f, &bb_list, invalid_block); + if (bad_blocks_file) + fclose(f); + else + pclose(f); + if (retval) { + com_err("ext2fs_read_bb_FILE", retval, "%s", + _("while reading in list of bad blocks from file")); + goto fatal; + } + + /* + * Finally, update the bad blocks from the bad_block_map + */ + printf("%s: Updating bad block inode.\n", ctx->device_name); + retval = ext2fs_update_bb_inode(fs, bb_list); + if (retval) { + com_err("ext2fs_update_bb_inode", retval, "%s", + _("while updating bad block inode")); + goto fatal; + } + + ext2fs_badblocks_list_free(bb_list); + return; + +fatal: + ctx->flags |= E2F_FLAG_ABORT; + if (bb_list) + ext2fs_badblocks_list_free(bb_list); + return; + +} + +static int check_bb_inode_blocks(ext2_filsys fs, + blk_t *block_nr, + int blockcnt EXT2FS_ATTR((unused)), + void *priv_data EXT2FS_ATTR((unused))) +{ + if (!*block_nr) + return 0; + + /* + * If the block number is outrageous, clear it and ignore it. + */ + if (*block_nr >= ext2fs_blocks_count(fs->super) || + *block_nr < fs->super->s_first_data_block) { + printf(_("Warning: illegal block %u found in bad block inode. " + "Cleared.\n"), *block_nr); + *block_nr = 0; + return BLOCK_CHANGED; + } + + return 0; +} + diff --git a/e2fsck/dirinfo.c b/e2fsck/dirinfo.c new file mode 100644 index 0000000..9873e38 --- /dev/null +++ b/e2fsck/dirinfo.c @@ -0,0 +1,489 @@ +/* + * dirinfo.c --- maintains the directory information table for e2fsck. + * + * Copyright (C) 1993 Theodore Ts'o. This file may be redistributed + * under the terms of the GNU Public License. + */ + +#undef DIRINFO_DEBUG + +#include "config.h" +#include "e2fsck.h" +#include <sys/stat.h> +#include <fcntl.h> +#include "uuid/uuid.h" + +#include "ext2fs/ext2fs.h" +#include <ext2fs/tdb.h> + +struct dir_info_db { + ext2_ino_t count; + ext2_ino_t size; + struct dir_info *array; + struct dir_info *last_lookup; +#ifdef CONFIG_TDB + char *tdb_fn; + TDB_CONTEXT *tdb; +#endif +}; + +struct dir_info_iter { + ext2_ino_t i; +#ifdef CONFIG_TDB + TDB_DATA tdb_iter; +#endif +}; + +struct dir_info_ent { + ext2_ino_t dotdot; /* Parent according to '..' */ + ext2_ino_t parent; /* Parent according to treewalk */ +}; + + +static void e2fsck_put_dir_info(e2fsck_t ctx, struct dir_info *dir); + +#ifdef CONFIG_TDB +static void setup_tdb(e2fsck_t ctx, ext2_ino_t num_dirs) +{ + struct dir_info_db *db = ctx->dir_info; + ext2_ino_t threshold; + errcode_t retval; + mode_t save_umask; + char *tdb_dir, uuid[40]; + int fd, enable; + + profile_get_string(ctx->profile, "scratch_files", "directory", 0, 0, + &tdb_dir); + profile_get_uint(ctx->profile, "scratch_files", + "numdirs_threshold", 0, 0, &threshold); + profile_get_boolean(ctx->profile, "scratch_files", + "dirinfo", 0, 1, &enable); + + if (!enable || !tdb_dir || access(tdb_dir, W_OK) || + (threshold && num_dirs <= threshold)) + return; + + retval = ext2fs_get_mem(strlen(tdb_dir) + 64, &db->tdb_fn); + if (retval) + return; + + uuid_unparse(ctx->fs->super->s_uuid, uuid); + sprintf(db->tdb_fn, "%s/%s-dirinfo-XXXXXX", tdb_dir, uuid); + save_umask = umask(077); + fd = mkstemp(db->tdb_fn); + umask(save_umask); + if (fd < 0) { + db->tdb = NULL; + return; + } + + if (num_dirs < 99991) + num_dirs = 99991; /* largest 5 digit prime */ + + db->tdb = tdb_open(db->tdb_fn, num_dirs, TDB_NOLOCK | TDB_NOSYNC, + O_RDWR | O_CREAT | O_TRUNC, 0600); + close(fd); +} +#endif + +static void setup_db(e2fsck_t ctx) +{ + struct dir_info_db *db; + ext2_ino_t num_dirs; + errcode_t retval; + + db = (struct dir_info_db *) + e2fsck_allocate_memory(ctx, sizeof(struct dir_info_db), + "directory map db"); + db->count = db->size = 0; + db->array = 0; + + ctx->dir_info = db; + + retval = ext2fs_get_num_dirs(ctx->fs, &num_dirs); + if (retval) + num_dirs = 1024; /* Guess */ + +#ifdef CONFIG_TDB + setup_tdb(ctx, num_dirs); + + if (db->tdb) { +#ifdef DIRINFO_DEBUG + printf("Note: using tdb!\n"); +#endif + return; + } +#endif + + db->size = num_dirs + 10; + db->array = (struct dir_info *) + e2fsck_allocate_memory(ctx, db->size + * sizeof (struct dir_info), + "directory map"); +} + +/* + * This subroutine is called during pass1 to create a directory info + * entry. During pass1, the passed-in parent is 0; it will get filled + * in during pass2. + */ +void e2fsck_add_dir_info(e2fsck_t ctx, ext2_ino_t ino, ext2_ino_t parent) +{ + struct dir_info *dir, *old_array; + ext2_ino_t i, j; + errcode_t retval; + unsigned long old_size; + +#ifdef DIRINFO_DEBUG + printf("add_dir_info for inode (%u, %u)...\n", ino, parent); +#endif + if (!ctx->dir_info) + setup_db(ctx); + + if (ctx->dir_info->count >= ctx->dir_info->size) { + old_size = ctx->dir_info->size * sizeof(struct dir_info); + ctx->dir_info->size += 10; + old_array = ctx->dir_info->array; + retval = ext2fs_resize_mem(old_size, ctx->dir_info->size * + sizeof(struct dir_info), + &ctx->dir_info->array); + if (retval) { + fprintf(stderr, "Couldn't reallocate dir_info " + "structure to %u entries\n", + ctx->dir_info->size); + fatal_error(ctx, 0); + ctx->dir_info->size -= 10; + return; + } + if (old_array != ctx->dir_info->array) + ctx->dir_info->last_lookup = NULL; + } + +#ifdef CONFIG_TDB + if (ctx->dir_info->tdb) { + struct dir_info ent; + + ent.ino = ino; + ent.parent = parent; + ent.dotdot = parent; + e2fsck_put_dir_info(ctx, &ent); + return; + } +#endif + + /* + * Normally, add_dir_info is called with each inode in + * sequential order; but once in a while (like when pass 3 + * needs to recreate the root directory or lost+found + * directory) it is called out of order. In those cases, we + * need to move the dir_info entries down to make room, since + * the dir_info array needs to be sorted by inode number for + * get_dir_info()'s sake. + */ + if (ctx->dir_info->count && + ctx->dir_info->array[ctx->dir_info->count-1].ino >= ino) { + for (i = ctx->dir_info->count-1; i > 0; i--) + if (ctx->dir_info->array[i-1].ino < ino) + break; + dir = &ctx->dir_info->array[i]; + if (dir->ino != ino) + for (j = ctx->dir_info->count++; j > i; j--) + ctx->dir_info->array[j] = ctx->dir_info->array[j-1]; + } else + dir = &ctx->dir_info->array[ctx->dir_info->count++]; + + dir->ino = ino; + dir->dotdot = parent; + dir->parent = parent; +} + +/* + * get_dir_info() --- given an inode number, try to find the directory + * information entry for it. + */ +static struct dir_info *e2fsck_get_dir_info(e2fsck_t ctx, ext2_ino_t ino) +{ + struct dir_info_db *db = ctx->dir_info; + ext2_ino_t low, high, mid; + + if (!db) + return 0; + +#ifdef DIRINFO_DEBUG + printf("e2fsck_get_dir_info %u...", ino); +#endif + +#ifdef CONFIG_TDB + if (db->tdb) { + static struct dir_info ret_dir_info; + TDB_DATA key, data; + struct dir_info_ent *buf; + + key.dptr = (unsigned char *) &ino; + key.dsize = sizeof(ext2_ino_t); + + data = tdb_fetch(db->tdb, key); + if (!data.dptr) { + if (tdb_error(db->tdb) != TDB_ERR_NOEXIST) + printf("fetch failed: %s\n", + tdb_errorstr(db->tdb)); + return 0; + } + + buf = (struct dir_info_ent *) data.dptr; + ret_dir_info.ino = ino; + ret_dir_info.dotdot = buf->dotdot; + ret_dir_info.parent = buf->parent; +#ifdef DIRINFO_DEBUG + printf("(%u,%u,%u)\n", ino, buf->dotdot, buf->parent); +#endif + free(data.dptr); + return &ret_dir_info; + } +#endif + + if (db->last_lookup && db->last_lookup->ino == ino) + return db->last_lookup; + + low = 0; + high = ctx->dir_info->count - 1; + if (ino == ctx->dir_info->array[low].ino) { +#ifdef DIRINFO_DEBUG + printf("(%u,%u,%u)\n", ino, + ctx->dir_info->array[low].dotdot, + ctx->dir_info->array[low].parent); +#endif + return &ctx->dir_info->array[low]; + } + if (ino == ctx->dir_info->array[high].ino) { +#ifdef DIRINFO_DEBUG + printf("(%u,%u,%u)\n", ino, + ctx->dir_info->array[high].dotdot, + ctx->dir_info->array[high].parent); +#endif + return &ctx->dir_info->array[high]; + } + + while (low < high) { + /* sum may overflow, but result will fit into mid again */ + mid = (unsigned long long)(low + high) / 2; + if (mid == low || mid == high) + break; + if (ino == ctx->dir_info->array[mid].ino) { +#ifdef DIRINFO_DEBUG + printf("(%u,%u,%u)\n", ino, + ctx->dir_info->array[mid].dotdot, + ctx->dir_info->array[mid].parent); +#endif + return &ctx->dir_info->array[mid]; + } + if (ino < ctx->dir_info->array[mid].ino) + high = mid; + else + low = mid; + } + return 0; +} + +static void e2fsck_put_dir_info(e2fsck_t ctx EXT2FS_NO_TDB_UNUSED, + struct dir_info *dir EXT2FS_NO_TDB_UNUSED) +{ +#ifdef CONFIG_TDB + struct dir_info_db *db = ctx->dir_info; + struct dir_info_ent buf; + TDB_DATA key, data; +#endif + +#ifdef DIRINFO_DEBUG + printf("e2fsck_put_dir_info (%u, %u, %u)...", dir->ino, dir->dotdot, + dir->parent); +#endif + +#ifdef CONFIG_TDB + if (!db->tdb) + return; + + buf.parent = dir->parent; + buf.dotdot = dir->dotdot; + + key.dptr = (unsigned char *) &dir->ino; + key.dsize = sizeof(ext2_ino_t); + data.dptr = (unsigned char *) &buf; + data.dsize = sizeof(buf); + + if (tdb_store(db->tdb, key, data, TDB_REPLACE) == -1) { + printf("store failed: %s\n", tdb_errorstr(db->tdb)); + } +#endif +} + +/* + * Free the dir_info structure when it isn't needed any more. + */ +void e2fsck_free_dir_info(e2fsck_t ctx) +{ + if (ctx->dir_info) { +#ifdef CONFIG_TDB + if (ctx->dir_info->tdb) + tdb_close(ctx->dir_info->tdb); + if (ctx->dir_info->tdb_fn) { + if (unlink(ctx->dir_info->tdb_fn) < 0) + com_err("e2fsck_free_dir_info", errno, + _("while freeing dir_info tdb file")); + ext2fs_free_mem(&ctx->dir_info->tdb_fn); + } +#endif + if (ctx->dir_info->array) + ext2fs_free_mem(&ctx->dir_info->array); + ctx->dir_info->array = 0; + ctx->dir_info->size = 0; + ctx->dir_info->count = 0; + ext2fs_free_mem(&ctx->dir_info); + ctx->dir_info = 0; + } +} + +/* + * Return the count of number of directories in the dir_info structure + */ +int e2fsck_get_num_dirinfo(e2fsck_t ctx) +{ + return ctx->dir_info ? ctx->dir_info->count : 0; +} + +struct dir_info_iter *e2fsck_dir_info_iter_begin(e2fsck_t ctx) +{ + struct dir_info_iter *iter; + + iter = e2fsck_allocate_memory(ctx, sizeof(struct dir_info_iter), + "dir_info iterator"); + +#ifdef CONFIG_TDB + if (ctx->dir_info->tdb) + iter->tdb_iter = tdb_firstkey(ctx->dir_info->tdb); +#endif + + return iter; +} + +void e2fsck_dir_info_iter_end(e2fsck_t ctx EXT2FS_ATTR((unused)), + struct dir_info_iter *iter) +{ +#ifdef CONFIG_TDB + free(iter->tdb_iter.dptr); +#endif + ext2fs_free_mem(&iter); +} + +/* + * A simple iterator function + */ +struct dir_info *e2fsck_dir_info_iter(e2fsck_t ctx, struct dir_info_iter *iter) +{ + if (!ctx->dir_info || !iter) + return 0; + +#ifdef CONFIG_TDB + if (ctx->dir_info->tdb) { + static struct dir_info ret_dir_info; + struct dir_info_ent *buf; + TDB_DATA data, key; + + if (iter->tdb_iter.dptr == 0) + return 0; + key = iter->tdb_iter; + data = tdb_fetch(ctx->dir_info->tdb, key); + if (!data.dptr) { + printf("iter fetch failed: %s\n", + tdb_errorstr(ctx->dir_info->tdb)); + return 0; + } + buf = (struct dir_info_ent *) data.dptr; + ret_dir_info.ino = *((ext2_ino_t *) iter->tdb_iter.dptr); + ret_dir_info.dotdot = buf->dotdot; + ret_dir_info.parent = buf->parent; + iter->tdb_iter = tdb_nextkey(ctx->dir_info->tdb, key); + free(key.dptr); + free(data.dptr); + return &ret_dir_info; + } +#endif + + if (iter->i >= ctx->dir_info->count) + return 0; + +#ifdef DIRINFO_DEBUG + printf("iter(%u, %u, %u)...", ctx->dir_info->array[iter->i].ino, + ctx->dir_info->array[iter->i].dotdot, + ctx->dir_info->array[iter->i].parent); +#endif + ctx->dir_info->last_lookup = ctx->dir_info->array + iter->i++; + return(ctx->dir_info->last_lookup); +} + +/* + * This function only sets the parent pointer, and requires that + * dirinfo structure has already been created. + */ +int e2fsck_dir_info_set_parent(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t parent) +{ + struct dir_info *p; + + p = e2fsck_get_dir_info(ctx, ino); + if (!p) + return 1; + p->parent = parent; + e2fsck_put_dir_info(ctx, p); + return 0; +} + +/* + * This function only sets the dot dot pointer, and requires that + * dirinfo structure has already been created. + */ +int e2fsck_dir_info_set_dotdot(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t dotdot) +{ + struct dir_info *p; + + p = e2fsck_get_dir_info(ctx, ino); + if (!p) + return 1; + p->dotdot = dotdot; + e2fsck_put_dir_info(ctx, p); + return 0; +} + +/* + * This function only sets the parent pointer, and requires that + * dirinfo structure has already been created. + */ +int e2fsck_dir_info_get_parent(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t *parent) +{ + struct dir_info *p; + + p = e2fsck_get_dir_info(ctx, ino); + if (!p) + return 1; + *parent = p->parent; + return 0; +} + +/* + * This function only sets the dot dot pointer, and requires that + * dirinfo structure has already been created. + */ +int e2fsck_dir_info_get_dotdot(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t *dotdot) +{ + struct dir_info *p; + + p = e2fsck_get_dir_info(ctx, ino); + if (!p) + return 1; + *dotdot = p->dotdot; + return 0; +} + diff --git a/e2fsck/dx_dirinfo.c b/e2fsck/dx_dirinfo.c new file mode 100644 index 0000000..4b764b0 --- /dev/null +++ b/e2fsck/dx_dirinfo.c @@ -0,0 +1,154 @@ +/* + * dirinfo.c --- maintains the directory information table for e2fsck. + * + * Copyright (C) 1993 Theodore Ts'o. This file may be redistributed + * under the terms of the GNU Public License. + */ + +#include "config.h" +#include "e2fsck.h" + +/* + * This subroutine is called during pass1 to create a directory info + * entry. During pass1, the passed-in parent is 0; it will get filled + * in during pass2. + */ +void e2fsck_add_dx_dir(e2fsck_t ctx, ext2_ino_t ino, struct ext2_inode *inode, + int num_blocks) +{ + struct dx_dir_info *dir; + ext2_ino_t i, j; + errcode_t retval; + unsigned long old_size; + +#if 0 + printf("add_dx_dir_info for inode %lu...\n", ino); +#endif + if (!ctx->dx_dir_info) { + ctx->dx_dir_info_count = 0; + ctx->dx_dir_info_size = 100; /* Guess */ + ctx->dx_dir_info = (struct dx_dir_info *) + e2fsck_allocate_memory(ctx, ctx->dx_dir_info_size + * sizeof (struct dx_dir_info), + "directory map"); + } + + if (ctx->dx_dir_info_count >= ctx->dx_dir_info_size) { + old_size = ctx->dx_dir_info_size * sizeof(struct dx_dir_info); + ctx->dx_dir_info_size += 10; + retval = ext2fs_resize_mem(old_size, ctx->dx_dir_info_size * + sizeof(struct dx_dir_info), + &ctx->dx_dir_info); + if (retval) { + fprintf(stderr, "Couldn't reallocate dx_dir_info " + "structure to %u entries\n", + ctx->dx_dir_info_size); + fatal_error(ctx, 0); + ctx->dx_dir_info_size -= 10; + return; + } + } + + /* + * Normally, add_dx_dir_info is called with each inode in + * sequential order; but once in a while (like when pass 3 + * needs to recreate the root directory or lost+found + * directory) it is called out of order. In those cases, we + * need to move the dx_dir_info entries down to make room, since + * the dx_dir_info array needs to be sorted by inode number for + * get_dx_dir_info()'s sake. + */ + if (ctx->dx_dir_info_count && + ctx->dx_dir_info[ctx->dx_dir_info_count-1].ino >= ino) { + for (i = ctx->dx_dir_info_count-1; i > 0; i--) + if (ctx->dx_dir_info[i-1].ino < ino) + break; + dir = &ctx->dx_dir_info[i]; + if (dir->ino != ino) + for (j = ctx->dx_dir_info_count++; j > i; j--) + ctx->dx_dir_info[j] = ctx->dx_dir_info[j-1]; + } else + dir = &ctx->dx_dir_info[ctx->dx_dir_info_count++]; + + dir->ino = ino; + dir->numblocks = num_blocks; + dir->hashversion = 0; + dir->casefolded_hash = !!(inode->i_flags & EXT4_CASEFOLD_FL); + dir->dx_block = e2fsck_allocate_memory(ctx, num_blocks + * sizeof (struct dx_dirblock_info), + "dx_block info array"); +} + +/* + * get_dx_dir_info() --- given an inode number, try to find the directory + * information entry for it. + */ +struct dx_dir_info *e2fsck_get_dx_dir_info(e2fsck_t ctx, ext2_ino_t ino) +{ + ext2_ino_t low, high, mid; + + low = 0; + high = ctx->dx_dir_info_count-1; + if (!ctx->dx_dir_info) + return 0; + if (ino == ctx->dx_dir_info[low].ino) + return &ctx->dx_dir_info[low]; + if (ino == ctx->dx_dir_info[high].ino) + return &ctx->dx_dir_info[high]; + + while (low < high) { + /* sum may overflow, but result will fit into mid again */ + mid = (unsigned long long)(low + high) / 2; + if (mid == low || mid == high) + break; + if (ino == ctx->dx_dir_info[mid].ino) + return &ctx->dx_dir_info[mid]; + if (ino < ctx->dx_dir_info[mid].ino) + high = mid; + else + low = mid; + } + return 0; +} + +/* + * Free the dx_dir_info structure when it isn't needed any more. + */ +void e2fsck_free_dx_dir_info(e2fsck_t ctx) +{ + struct dx_dir_info *dir; + ext2_ino_t i; + + if (ctx->dx_dir_info) { + dir = ctx->dx_dir_info; + for (i=0; i < ctx->dx_dir_info_count; i++,dir++) { + if (dir->dx_block) { + ext2fs_free_mem(&dir->dx_block); + dir->dx_block = 0; + } + } + ext2fs_free_mem(&ctx->dx_dir_info); + ctx->dx_dir_info = 0; + } + ctx->dx_dir_info_size = 0; + ctx->dx_dir_info_count = 0; +} + +/* + * Return the count of number of directories in the dx_dir_info structure + */ +ext2_ino_t e2fsck_get_num_dx_dirinfo(e2fsck_t ctx) +{ + return ctx->dx_dir_info_count; +} + +/* + * A simple iterator function + */ +struct dx_dir_info *e2fsck_dx_dir_info_iter(e2fsck_t ctx, ext2_ino_t *control) +{ + if (*control >= ctx->dx_dir_info_count) + return 0; + + return ctx->dx_dir_info + (*control)++; +} diff --git a/e2fsck/e2fsck.8.in b/e2fsck/e2fsck.8.in new file mode 100644 index 0000000..dc6a585 --- /dev/null +++ b/e2fsck/e2fsck.8.in @@ -0,0 +1,509 @@ +.\" -*- nroff -*- +.\" Copyright 1993, 1994, 1995 by Theodore Ts'o. All Rights Reserved. +.\" This file may be copied under the terms of the GNU Public License. +.\" +.TH E2FSCK 8 "@E2FSPROGS_MONTH@ @E2FSPROGS_YEAR@" "E2fsprogs version @E2FSPROGS_VERSION@" +.SH NAME +e2fsck \- check a Linux ext2/ext3/ext4 file system +.SH SYNOPSIS +.B e2fsck +[ +.B \-pacnyrdfkvtDFV +] +[ +.B \-b +.I superblock +] +[ +.B \-B +.I blocksize +] +[ +.BR \-l | \-L +.I bad_blocks_file +] +[ +.B \-C +.I fd +] +@JDEV@[ +@JDEV@.B \-j +@JDEV@.I external-journal +@JDEV@] +[ +.B \-E +.I extended_options +] +[ +.B \-z +.I undo_file +] +.I device +.SH DESCRIPTION +.B e2fsck +is used to check the ext2/ext3/ext4 family of file systems. +For ext3 and ext4 file systems that use a journal, if the system has been +shut down uncleanly without any errors, normally, after replaying the +committed transactions in the journal, the file system should be +marked as clean. Hence, for file systems that use journaling, +.B e2fsck +will normally replay the journal and exit, unless its superblock +indicates that further checking is required. +.PP +.I device +is a block device (e.g., +.IR /dev/sdc1 ) +or file containing the file system. +.PP +Note that in general it is not safe to run +.B e2fsck +on mounted file systems. The only exception is if the +.B \-n +option is specified, and +.BR \-c , +.BR \-l , +or +.B -L +options are +.I not +specified. However, even if it is safe to do so, the results printed by +.B e2fsck +are not valid if the file system is mounted. If +.B e2fsck +asks whether or not you should check a file system which is mounted, +the only correct answer is ``no''. Only experts who really know what +they are doing should consider answering this question in any other way. +.PP +If +.B e2fsck +is run in interactive mode (meaning that none of +.BR \-y , +.BR \-n , +or +.BR \-p +are specified), the program will ask the user to fix each problem found in the +file system. A response of 'y' will fix the error; 'n' will leave the error +unfixed; and 'a' will fix the problem and all subsequent problems; pressing +Enter will proceed with the default response, which is printed before the +question mark. Pressing Control-C terminates e2fsck immediately. +.SH OPTIONS +.TP +.B \-a +This option does the same thing as the +.B \-p +option. It is provided for backwards compatibility only; it is +suggested that people use +.B \-p +option whenever possible. +.TP +.BI \-b " superblock" +Instead of using the normal superblock, use an alternative superblock +specified by +.IR superblock . +This option is normally used when the primary superblock has been +corrupted. The location of backup superblocks is dependent on the +file system's blocksize, the number of blocks per group, and features +such as +.BR sparse_super . +.IP +Additional backup superblocks can be determined by using the +.B mke2fs +program using the +.B \-n +option to print out where the superblocks exist, supposing +.B mke2fs +is supplied with arguments that are consistent with the file system's layout +(e.g. blocksize, blocks per group, +.BR sparse_super , +etc.). +.IP +If an alternative superblock is specified and +the file system is not opened read-only, e2fsck will make sure that the +primary superblock is updated appropriately upon completion of the +file system check. +.TP +.BI \-B " blocksize" +Normally, +.B e2fsck +will search for the superblock at various different +block sizes in an attempt to find the appropriate block size. +This search can be fooled in some cases. This option forces +.B e2fsck +to only try locating the superblock at a particular blocksize. +If the superblock is not found, +.B e2fsck +will terminate with a fatal error. +.TP +.B \-c +This option causes +.B e2fsck +to use +.BR badblocks (8) +program to do a read-only scan of the device in order to find any bad +blocks. If any bad blocks are found, they are added to the bad block +inode to prevent them from being allocated to a file or directory. If +this option is specified twice, then the bad block scan will be done +using a non-destructive read-write test. +.TP +.BI \-C " fd" +This option causes +.B e2fsck +to write completion information to the specified file descriptor +so that the progress of the file system +check can be monitored. This option is typically used by programs +which are running +.BR e2fsck . +If the file descriptor number is negative, then absolute value of +the file descriptor will be used, and the progress information will be +suppressed initially. It can later be enabled by sending the +.B e2fsck +process a SIGUSR1 signal. +If the file descriptor specified is 0, +.B e2fsck +will print a completion bar as it goes about its business. This requires +that e2fsck is running on a video console or terminal. +.TP +.B \-d +Print debugging output (useless unless you are debugging +.BR e2fsck ). +.TP +.B \-D +Optimize directories in file system. This option causes e2fsck to +try to optimize all directories, either by re-indexing them if the +file system supports directory indexing, or by sorting and compressing +directories for smaller directories, or for file systems using +traditional linear directories. +.IP +Even without the +.B \-D +option, +.B e2fsck +may sometimes optimize a few directories --- for example, if +directory indexing is enabled and a directory is not indexed and would +benefit from being indexed, or if the index structures are corrupted +and need to be rebuilt. The +.B \-D +option forces all directories in the file system to be optimized. This can +sometimes make them a little smaller and slightly faster to search, but +in practice, you should rarely need to use this option. +.IP +The +.B \-D +option will detect directory entries with duplicate names in a single +directory, which e2fsck normally does not enforce for performance reasons. +.TP +.BI \-E " extended_options" +Set e2fsck extended options. Extended options are comma +separated, and may take an argument using the equals ('=') sign. The +following options are supported: +.RS 1.2i +.TP +.BI ea_ver= extended_attribute_version +Set the version of the extended attribute blocks which +.B e2fsck +will require while checking the file system. The version number may +be 1 or 2. The default extended attribute version format is 2. +.TP +.BI journal_only +Only replay the journal if required, but do not perform any further checks +or repairs. +.TP +.BI fragcheck +During pass 1, print a detailed report of any discontiguous blocks for +files in the file system. +.TP +.BI discard +Attempt to discard free blocks and unused inode blocks after the full +file system check (discarding blocks is useful on solid state devices and sparse +/ thin-provisioned storage). Note that discard is done in pass 5 AFTER the +file system has been fully checked and only if it does not contain recognizable +errors. However there might be cases where +.B e2fsck +does not fully recognize a problem and hence in this case this +option may prevent you from further manual data recovery. +.TP +.BI nodiscard +Do not attempt to discard free blocks and unused inode blocks. This option is +exactly the opposite of discard option. This is set as default. +.TP +.BI no_optimize_extents +Do not offer to optimize the extent tree by eliminating unnecessary +width or depth. This can also be enabled in the options section of +.BR /etc/e2fsck.conf . +.TP +.BI optimize_extents +Offer to optimize the extent tree by eliminating unnecessary +width or depth. This is the default unless otherwise specified in +.BR /etc/e2fsck.conf . +.TP +.BI inode_count_fullmap +Trade off using memory for speed when checking a file system with a +large number of hard-linked files. The amount of memory required is +proportional to the number of inodes in the file system. For large file +systems, this can be gigabytes of memory. (For example, a 40TB file system +with 2.8 billion inodes will consume an additional 5.7 GB memory if this +optimization is enabled.) This optimization can also be enabled in the +options section of +.BR /etc/e2fsck.conf . +.TP +.BI no_inode_count_fullmap +Disable the +.B inode_count_fullmap +optimization. This is the default unless otherwise specified in +.BR /etc/e2fsck.conf . +.TP +.BI readahead_kb +Use this many KiB of memory to pre-fetch metadata in the hopes of reducing +e2fsck runtime. By default, this is set to the size of two block groups' inode +tables (typically 4MiB on a regular ext4 file system); if this amount is more +than 1/50th of total physical memory, readahead is disabled. Set this to zero +to disable readahead entirely. +.TP +.BI bmap2extent +Convert block-mapped files to extent-mapped files. +.TP +.BI fixes_only +Only fix damaged metadata; do not optimize htree directories or compress +extent trees. This option is incompatible with the -D and -E bmap2extent +options. +.TP +.BI check_encoding +Force verification of encoded filenames in case-insensitive directories. +This is the default mode if the file system has the strict flag enabled. +.TP +.BI unshare_blocks +If the file system has shared blocks, with the shared blocks read-only feature +enabled, then this will unshare all shared blocks and unset the read-only +feature bit. If there is not enough free space then the operation will fail. +If the file system does not have the read-only feature bit, but has shared +blocks anyway, then this option will have no effect. Note when using this +option, if there is no free space to clone blocks, there is no prompt to +delete files and instead the operation will fail. +.IP +Note that unshare_blocks implies the "-f" option to ensure that all passes +are run. Additionally, if "-n" is also specified, e2fsck will simulate trying +to allocate enough space to deduplicate. If this fails, the exit code will +be non-zero. +.RE +.TP +.B \-f +Force checking even if the file system seems clean. +.TP +.B \-F +Flush the file system device's buffer caches before beginning. Only +really useful for doing +.B e2fsck +time trials. +@JDEV@.TP +@JDEV@.BI \-j " external-journal" +@JDEV@Set the pathname where the external-journal for this file system can be +@JDEV@found. +.TP +.BI \-k +When combined with the +.B \-c +option, any existing bad blocks in the bad blocks list are preserved, +and any new bad blocks found by running +.BR badblocks (8) +will be added to the existing bad blocks list. +.TP +.BI \-l " filename" +Add the block numbers listed in the file specified by +.I filename +to the list of bad blocks. The format of this file is the same as the +one generated by the +.BR badblocks (8) +program. Note that the block numbers are based on the blocksize +of the file system. Hence, +.BR badblocks (8) +must be given the blocksize of the file system in order to obtain correct +results. As a result, it is much simpler and safer to use the +.B -c +option to +.BR e2fsck , +since it will assure that the correct parameters are passed to the +.B badblocks +program. +.TP +.BI \-L " filename" +Set the bad blocks list to be the list of blocks specified by +.IR filename . +(This option is the same as the +.B \-l +option, except the bad blocks list is cleared before the blocks listed +in the file are added to the bad blocks list.) +.TP +.B \-n +Open the file system read-only, and assume an answer of `no' to all +questions. Allows +.B e2fsck +to be used non-interactively. This option +may not be specified at the same time as the +.B \-p +or +.B \-y +options. +.TP +.B \-p +Automatically repair ("preen") the file system. This option will cause +.B e2fsck +to automatically +fix any file system problems that can be safely fixed without human +intervention. If +.B e2fsck +discovers a problem which may require the system administrator +to take additional corrective action, +.B e2fsck +will print a description of the problem and then exit with the value 4 +logically or'ed into the exit code. (See the \fBEXIT CODE\fR section.) +This option is normally used by the system's boot scripts. It may not +be specified at the same time as the +.B \-n +or +.B \-y +options. +.TP +.B \-r +This option does nothing at all; it is provided only for backwards +compatibility. +.TP +.B \-t +Print timing statistics for +.BR e2fsck . +If this option is used twice, additional timing statistics are printed +on a pass by pass basis. +.TP +.B \-v +Verbose mode. +.TP +.B \-V +Print version information and exit. +.TP +.B \-y +Assume an answer of `yes' to all questions; allows +.B e2fsck +to be used non-interactively. This option +may not be specified at the same time as the +.B \-n +or +.B \-p +options. +.TP +.BI \-z " undo_file" +Before overwriting a file system block, write the old contents of the block to +an undo file. This undo file can be used with e2undo(8) to restore the old +contents of the file system should something go wrong. If the empty string is +passed as the undo_file argument, the undo file will be written to a file named +e2fsck-\fIdevice\fR.e2undo in the directory specified via the +\fIE2FSPROGS_UNDO_DIR\fR environment variable. + +WARNING: The undo file cannot be used to recover from a power or system crash. +.SH EXIT CODE +The exit code returned by +.B e2fsck +is the sum of the following conditions: +.br +\ 0\ \-\ No errors +.br +\ 1\ \-\ File system errors corrected +.br +\ 2\ \-\ File system errors corrected, system should +.br +\ \ \ \ be rebooted +.br +\ 4\ \-\ File system errors left uncorrected +.br +\ 8\ \-\ Operational error +.br +\ 16\ \-\ Usage or syntax error +.br +\ 32\ \-\ E2fsck canceled by user request +.br +\ 128\ \-\ Shared library error +.br +.SH SIGNALS +The following signals have the following effect when sent to +.BR e2fsck . +.TP +.B SIGUSR1 +This signal causes +.B e2fsck +to start displaying a completion bar or emitting progress information. +(See discussion of the +.B \-C +option.) +.TP +.B SIGUSR2 +This signal causes +.B e2fsck +to stop displaying a completion bar or emitting progress information. +.SH REPORTING BUGS +Almost any piece of software will have bugs. If you manage to find a +file system which causes +.B e2fsck +to crash, or which +.B e2fsck +is unable to repair, please report it to the author. +.PP +Please include as much information as possible in your bug report. +Ideally, include a complete transcript of the +.B e2fsck +run, so I can see exactly what error messages are displayed. (Make sure +the messages printed by +.B e2fsck +are in English; if your system has been +configured so that +.BR e2fsck 's +messages have been translated into another language, please set the the +.B LC_ALL +environment variable to +.B C +so that the transcript of e2fsck's output will be useful to me.) +If you +have a writable file system where the transcript can be stored, the +.BR script (1) +program is a handy way to save the output of +.B e2fsck +to a file. +.PP +It is also useful to send the output of +.BR dumpe2fs (8). +If a specific inode or inodes seems to be giving +.B e2fsck +trouble, try running the +.BR debugfs (8) +command and send the output of the +.BR stat (1u) +command run on the relevant inode(s). If the inode is a directory, the +.B debugfs +.I dump +command will allow you to extract the contents of the directory inode, +which can sent to me after being first run through +.BR uuencode (1). +The most useful data you can send to help reproduce +the bug is a compressed raw image dump of the file system, generated using +.BR e2image (8). +See the +.BR e2image (8) +man page for more details. +.PP +Always include the full version string which +.B e2fsck +displays when it is run, so I know which version you are running. +.SH ENVIRONMENT +.TP +.BI E2FSCK_CONFIG +Determines the location of the configuration file (see +.BR e2fsck.conf (5)). +.SH AUTHOR +This version of +.B e2fsck +was written by Theodore Ts'o <tytso@mit.edu>. +.SH SEE ALSO +.BR e2fsck.conf (5), +.BR badblocks (8), +.BR dumpe2fs (8), +.BR debugfs (8), +.BR e2image (8), +.BR mke2fs (8), +.BR tune2fs (8) diff --git a/e2fsck/e2fsck.c b/e2fsck/e2fsck.c new file mode 100644 index 0000000..1e295e3 --- /dev/null +++ b/e2fsck/e2fsck.c @@ -0,0 +1,271 @@ +/* + * e2fsck.c - a consistency checker for the new extended file system. + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#include <errno.h> + +#include "e2fsck.h" +#include "problem.h" + +/* + * This function allocates an e2fsck context + */ +errcode_t e2fsck_allocate_context(e2fsck_t *ret) +{ + e2fsck_t context; + errcode_t retval; + char *time_env; + + retval = ext2fs_get_mem(sizeof(struct e2fsck_struct), &context); + if (retval) + return retval; + + memset(context, 0, sizeof(struct e2fsck_struct)); + + context->process_inode_size = 256; + context->ext_attr_ver = 2; + context->blocks_per_page = 1; + context->htree_slack_percentage = 255; + + time_env = getenv("E2FSCK_TIME"); + if (time_env) + context->now = (time_t) strtoull(time_env, NULL, 0); + else { + context->now = time(0); + if (context->now < 1262322000) /* January 1 2010 */ + context->flags |= E2F_FLAG_TIME_INSANE; + } + + *ret = context; + return 0; +} + +/* + * This function resets an e2fsck context; it is called when e2fsck + * needs to be restarted. + */ +errcode_t e2fsck_reset_context(e2fsck_t ctx) +{ + int i; + + ctx->flags &= E2F_RESET_FLAGS; + ctx->lost_and_found = 0; + ctx->bad_lost_and_found = 0; + if (ctx->inode_used_map) { + ext2fs_free_inode_bitmap(ctx->inode_used_map); + ctx->inode_used_map = 0; + } + if (ctx->inode_dir_map) { + ext2fs_free_inode_bitmap(ctx->inode_dir_map); + ctx->inode_dir_map = 0; + } + if (ctx->inode_reg_map) { + ext2fs_free_inode_bitmap(ctx->inode_reg_map); + ctx->inode_reg_map = 0; + } + if (ctx->block_found_map) { + ext2fs_free_block_bitmap(ctx->block_found_map); + ctx->block_found_map = 0; + } + if (ctx->inode_casefold_map) { + ext2fs_free_block_bitmap(ctx->inode_casefold_map); + ctx->inode_casefold_map = 0; + } + if (ctx->inode_link_info) { + ext2fs_free_icount(ctx->inode_link_info); + ctx->inode_link_info = 0; + } + if (ctx->journal_io) { + if (ctx->fs && ctx->fs->io != ctx->journal_io) + io_channel_close(ctx->journal_io); + ctx->journal_io = 0; + } + if (ctx->fs && ctx->fs->dblist) { + ext2fs_free_dblist(ctx->fs->dblist); + ctx->fs->dblist = 0; + } + e2fsck_free_dir_info(ctx); + e2fsck_free_dx_dir_info(ctx); + if (ctx->refcount) { + ea_refcount_free(ctx->refcount); + ctx->refcount = 0; + } + if (ctx->refcount_extra) { + ea_refcount_free(ctx->refcount_extra); + ctx->refcount_extra = 0; + } + if (ctx->ea_block_quota_blocks) { + ea_refcount_free(ctx->ea_block_quota_blocks); + ctx->ea_block_quota_blocks = 0; + } + if (ctx->ea_block_quota_inodes) { + ea_refcount_free(ctx->ea_block_quota_inodes); + ctx->ea_block_quota_inodes = 0; + } + if (ctx->ea_inode_refs) { + ea_refcount_free(ctx->ea_inode_refs); + ctx->ea_inode_refs = 0; + } + if (ctx->block_dup_map) { + ext2fs_free_block_bitmap(ctx->block_dup_map); + ctx->block_dup_map = 0; + } + if (ctx->block_ea_map) { + ext2fs_free_block_bitmap(ctx->block_ea_map); + ctx->block_ea_map = 0; + } + if (ctx->block_metadata_map) { + ext2fs_free_block_bitmap(ctx->block_metadata_map); + ctx->block_metadata_map = 0; + } + if (ctx->inode_bb_map) { + ext2fs_free_inode_bitmap(ctx->inode_bb_map); + ctx->inode_bb_map = 0; + } + if (ctx->inode_bad_map) { + ext2fs_free_inode_bitmap(ctx->inode_bad_map); + ctx->inode_bad_map = 0; + } + if (ctx->inode_imagic_map) { + ext2fs_free_inode_bitmap(ctx->inode_imagic_map); + ctx->inode_imagic_map = 0; + } + if (ctx->dirs_to_hash) { + ext2fs_u32_list_free(ctx->dirs_to_hash); + ctx->dirs_to_hash = 0; + } + destroy_encrypted_file_info(ctx); + + /* + * Clear the array of invalid meta-data flags + */ + if (ctx->invalid_inode_bitmap_flag) { + ext2fs_free_mem(&ctx->invalid_inode_bitmap_flag); + ctx->invalid_inode_bitmap_flag = 0; + } + if (ctx->invalid_block_bitmap_flag) { + ext2fs_free_mem(&ctx->invalid_block_bitmap_flag); + ctx->invalid_block_bitmap_flag = 0; + } + if (ctx->invalid_inode_table_flag) { + ext2fs_free_mem(&ctx->invalid_inode_table_flag); + ctx->invalid_inode_table_flag = 0; + } + if (ctx->casefolded_dirs) { + ext2fs_u32_list_free(ctx->casefolded_dirs); + ctx->casefolded_dirs = 0; + } + if (ctx->inode_count) { + ext2fs_free_icount(ctx->inode_count); + ctx->inode_count = 0; + } + + /* Clear statistic counters */ + ctx->fs_directory_count = 0; + ctx->fs_regular_count = 0; + ctx->fs_blockdev_count = 0; + ctx->fs_chardev_count = 0; + ctx->fs_links_count = 0; + ctx->fs_symlinks_count = 0; + ctx->fs_fast_symlinks_count = 0; + ctx->fs_fifo_count = 0; + ctx->fs_total_count = 0; + ctx->fs_badblocks_count = 0; + ctx->fs_sockets_count = 0; + ctx->fs_ind_count = 0; + ctx->fs_dind_count = 0; + ctx->fs_tind_count = 0; + ctx->fs_fragmented = 0; + ctx->fs_fragmented_dir = 0; + ctx->large_files = 0; + ctx->large_dirs = 0; + + for (i=0; i < MAX_EXTENT_DEPTH_COUNT; i++) + ctx->extent_depth_count[i] = 0; + + /* Reset the superblock to the user's requested value */ + ctx->superblock = ctx->use_superblock; + + return 0; +} + +void e2fsck_free_context(e2fsck_t ctx) +{ + if (!ctx) + return; + + e2fsck_reset_context(ctx); + if (ctx->blkid) + blkid_put_cache(ctx->blkid); + + if (ctx->profile) + profile_release(ctx->profile); + + if (ctx->filesystem_name) + ext2fs_free_mem(&ctx->filesystem_name); + + if (ctx->device_name) + ext2fs_free_mem(&ctx->device_name); + + if (ctx->log_fn) + free(ctx->log_fn); + + if (ctx->logf) + fclose(ctx->logf); + + if (ctx->problem_log_fn) + free(ctx->problem_log_fn); + + if (ctx->problem_logf) { + fputs("</problem_log>\n", ctx->problem_logf); + fclose(ctx->problem_logf); + } + ext2fs_free_mem(&ctx); +} + +/* + * This function runs through the e2fsck passes and calls them all, + * returning restart, abort, or cancel as necessary... + */ +typedef void (*pass_t)(e2fsck_t ctx); + +static pass_t e2fsck_passes[] = { + e2fsck_pass1, e2fsck_pass1e, e2fsck_pass2, e2fsck_pass3, + e2fsck_pass4, e2fsck_pass5, 0 }; + +int e2fsck_run(e2fsck_t ctx) +{ + int i; + pass_t e2fsck_pass; + +#ifdef HAVE_SETJMP_H + if (setjmp(ctx->abort_loc)) { + ctx->flags &= ~E2F_FLAG_SETJMP_OK; + return (ctx->flags & E2F_FLAG_RUN_RETURN); + } + ctx->flags |= E2F_FLAG_SETJMP_OK; +#endif + + for (i=0; (e2fsck_pass = e2fsck_passes[i]); i++) { + if (ctx->flags & E2F_FLAG_RUN_RETURN) + break; + if (e2fsck_mmp_update(ctx->fs)) + fatal_error(ctx, 0); + e2fsck_pass(ctx); + if (ctx->progress) + (void) (ctx->progress)(ctx, 0, 0, 0); + } + ctx->flags &= ~E2F_FLAG_SETJMP_OK; + + if (ctx->flags & E2F_FLAG_RUN_RETURN) + return (ctx->flags & E2F_FLAG_RUN_RETURN); + return 0; +} diff --git a/e2fsck/e2fsck.conf.5.in b/e2fsck/e2fsck.conf.5.in new file mode 100644 index 0000000..e82610d --- /dev/null +++ b/e2fsck/e2fsck.conf.5.in @@ -0,0 +1,501 @@ +.\" -*- nroff -*- +.\" Copyright 2006 by Theodore Ts'o. All Rights Reserved. +.\" This file may be copied under the terms of the GNU Public License. +.\" +.TH e2fsck.conf 5 "@E2FSPROGS_MONTH@ @E2FSPROGS_YEAR@" "E2fsprogs version @E2FSPROGS_VERSION@" +.SH NAME +e2fsck.conf \- Configuration file for e2fsck +.SH DESCRIPTION +.I e2fsck.conf +is the configuration file for +.BR e2fsck (8). +It controls the default behavior of +.BR e2fsck (8) +while it is checking ext2, ext3, or ext4 file systems. +.PP +The +.I e2fsck.conf +file uses an INI-style format. Stanzas, or top-level sections, are +delimited by square braces: [ ]. Within each section, each line +defines a relation, which assigns tags to values, or to a subsection, +which contains further relations or subsections. +.\" Tags can be assigned multiple values +An example of the INI-style format used by this configuration file +follows below: +.P + [section1] +.br + tag1 = value_a +.br + tag1 = value_b +.br + tag2 = value_c +.P + [section 2] +.br + tag3 = { +.br + subtag1 = subtag_value_a +.br + subtag1 = subtag_value_b +.br + subtag2 = subtag_value_c +.br + } +.br + tag1 = value_d +.br + tag2 = value_e +.br + } +.P +Comments are delimited by a semicolon (';') or a hash ('#') character +at the beginning of the comment, and are terminated by the end of +line character. +.P +Tags and values must be quoted using double quotes if they contain +spaces. Within a quoted string, the standard backslash interpretations +apply: "\en" (for the newline character), +"\et" (for the tab character), "\eb" (for the backspace character), +and "\e\e" (for the backslash character). +.P +The following stanzas are used in the +.I e2fsck.conf +file. They will be described in more detail in future sections of this +document. +.TP +.I [options] +This stanza contains general configuration parameters for +.BR e2fsck 's +behavior. +.TP +.I [defaults] +Contains relations which define the default parameters used by +.BR e2fsck (8). +In general, these defaults may be overridden by command-line options +provided by the user. +.TP +.I [problems] +This stanza allows the administrator to reconfigure how e2fsck handles +various file system inconsistencies. +@TDB_MAN_COMMENT@.TP +@TDB_MAN_COMMENT@.I [scratch_files] +@TDB_MAN_COMMENT@This stanza controls when e2fsck will attempt to use +@TDB_MAN_COMMENT@scratch files to reduce the need for memory. +.SH THE [options] STANZA +The following relations are defined in the +.I [options] +stanza. +.TP +.I allow_cancellation +If this relation is set to a boolean value of true, then if the user +interrupts e2fsck using ^C, and the file system is not explicitly flagged +as containing errors, e2fsck will exit with an exit status of 0 instead +of 32. This setting defaults to false. +.TP +.I accept_time_fudge +Unfortunately, due to Windows' unfortunate design decision +to configure the hardware clock to tick localtime, instead +of the more proper and less error-prone UTC time, many +users end up in the situation where the system clock is +incorrectly set at the time when e2fsck is run. +.IP +Historically this was usually due to some distributions +having buggy init scripts and/or installers that didn't +correctly detect this case and take appropriate +countermeasures. Unfortunately, this is occasionally +true even today, usually due to a +buggy or misconfigured virtualization manager or the +installer not having access to a network time server +during the installation process. So by default, we allow +the superblock times to be fudged by up to 24 hours. +This can be disabled by setting +.I accept_time_fudge +to the +boolean value of false. This setting defaults to true. +.TP +.I broken_system_clock +The +.BR e2fsck (8) +program has some heuristics that assume that the system clock is +correct. In addition, many system programs make similar assumptions. +For example, the UUID library depends on time not going backwards in +order for it to be able to make its guarantees about issuing universally +unique ID's. Systems with broken system clocks, are well, broken. +However, broken system clocks, particularly in embedded systems, do +exist. E2fsck will attempt to use heuristics to determine if the time +can not be trusted; and to skip time-based checks if this is true. If +this boolean is set to true, then e2fsck will always assume that the +system clock can not be trusted. +.TP +.I buggy_init_scripts +This boolean relation is an alias for +.I accept_time_fudge +for backwards compatibility; it used to +be that the behavior defined by +.I accept_time_fudge +above defaulted to false, and +.I buggy_init_scripts +would enable superblock time field to be wrong by up to 24 hours. When +we changed the default, we also renamed this boolean relation to +.IR accept_time_fudge. +.TP +.I clear_test_fs_flag +This boolean relation controls whether or not +.BR e2fsck (8) +will offer to clear +the test_fs flag if the ext4 file system is available on the system. It +defaults to true. +.TP +.I defer_check_on_battery +This boolean relation controls whether or not the interval between +file system checks (either based on time or number of mounts) should +be doubled if the system is running on battery. This setting defaults to +true. +.TP +.I indexed_dir_slack_percentage +When +.BR e2fsck (8) +repacks a indexed directory, reserve the specified percentage of +empty space in each leaf nodes so that a few new entries can +be added to the directory without splitting leaf nodes, so that +the average fill ratio of directories can be maintained at a +higher, more efficient level. This relation defaults to 20 +percent. +.TP +.I inode_count_fullmap +If this boolean relation is true, trade off using memory for speed when +checking a file system with a large number of hard-linked files. The +amount of memory required is proportional to the number of inodes in the +file system. For large file systems, this can be gigabytes of memory. +(For example a 40TB file system with 2.8 billion inodes will consume an +additional 5.7 GB memory if this optimization is enabled.) This setting +defaults to false. +.TP +.I log_dir +If the +.I log_filename +or +.I problem_log_filename +relations contains a relative pathname, then the log file will be placed +in the directory named by the +.I log_dir +relation. +.TP +.I log_dir_fallback +This relation contains an alternate directory that will be used if the +directory specified by +.I log_dir +is not available or is not writable. +.TP +.I log_dir_wait +If this boolean relation is true, them if the directories specified by +.I log_dir +or +.I log_dir_fallback +are not available or are not yet writable, e2fsck will save the output +in a memory buffer, and a child process will periodically test to see if +the log directory has become available after the boot sequence has +mounted the requested file system for reading/writing. This implements the +functionality provided by +.BR logsave (8) +for e2fsck log files. +.TP +.I log_filename +This relation specifies the file name where a copy of e2fsck's output +will be written. If certain problem reports are suppressed using the +.I max_count_problems +relation, (or on a per-problem basis using the +.I max_count +relation), the full set of problem reports will be written to the log +file. The filename may contain various percent-expressions (%D, %T, %N, +etc.) which will be expanded so that the file name for the log file can +include things like date, time, device name, and other run-time +parameters. See the +.B LOGGING +section for more details. +.TP +.I max_count_problems +This relation specifies the maximum number of problem reports of a +particular type will be printed to stdout before further problem reports +of that type are squelched. This can be useful if the console is slow +(i.e., connected to a serial port) and so a large amount of output could +end up delaying the boot process for a long time (potentially hours). +.TP +.I no_optimize_extents +If this boolean relation is true, do not offer to optimize the extent +tree by reducing the tree's width or depth. This setting defaults to false. +.TP +.I problem_log_filename +This relation specifies the file name where a log of problem codes +found by e2fsck be written. The filename may contain various +percent-expressions (%D, %T, %N, +etc.) which will be expanded so that the file name for the log file can +include things like date, time, device name, and other run-time +parameters. See the +.B LOGGING +section for more details. +.TP +.I readahead_mem_pct +Use this percentage of memory to try to read in metadata blocks ahead of the +main e2fsck thread. This should reduce run times, depending on the speed of +the underlying storage and the amount of free memory. There is no default, but +see +.B readahead_kb +for more details. +.TP +.I readahead_kb +Use this amount of memory to read in metadata blocks ahead of the main checking +thread. Setting this value to zero disables readahead entirely. By default, +this is set the size of two block groups' inode tables (typically 4MiB on a +regular ext4 file system); if this amount is more than 1/50th of total physical +memory, readahead is disabled. +.TP +.I report_features +If this boolean relation is true, e2fsck will print the file system +features as part of its verbose reporting (i.e., if the +.B -v +option is specified) +.TP +.I report_time +If this boolean relation is true, e2fsck will run as if the options +.B -tt +are always specified. This will cause e2fsck to print timing statistics +on a pass by pass basis for full file system checks. +.TP +.I report_verbose +If this boolean relation is true, e2fsck will run as if the option +.B -v +is always specified. This will cause e2fsck to print some additional +information at the end of each full file system check. +.SH THE [defaults] STANZA +The following relations are defined in the +.I [defaults] +stanza. +.TP +.I undo_dir +This relation specifies the directory where the undo file should be +stored. It can be overridden via the +.B E2FSPROGS_UNDO_DIR +environment variable. If the directory location is set to the value +.IR none , +.B e2fsck +will not create an undo file. +.SH THE [problems] STANZA +Each tag in the +.I [problems] +stanza names a problem code specified with a leading "0x" followed by +six hex digits. +The value of the tag is a subsection where the relations in that +subsection override the default treatment of that particular problem +code. +.P +Note that inappropriate settings in this stanza may cause +.B e2fsck +to behave incorrectly, or even crash. Most system administrators should +not be making changes to this section without referring to source code. +.P +Within each problem code's subsection, the following tags may be used: +.TP +.I description +This relation allows the message which is printed when this file system +inconsistency is detected to be overridden. +.TP +.I preen_ok +This boolean relation overrides the default behavior controlling +whether this file system problem should be automatically fixed when +.B e2fsck +is running in preen mode. +.TP +.I max_count +This integer relation overrides the +.I max_count_problems +parameter (set in the options section) for this particular problem. +.TP +.I no_ok +This boolean relation overrides the default behavior determining +whether or not the file system will be marked as inconsistent if the user +declines to fix the reported problem. +.TP +.I no_default +This boolean relation overrides whether the default answer for this +problem (or question) should be "no". +.TP +.I preen_nomessage +This boolean relation overrides the default behavior controlling +whether or not the description for this file system problem should +be suppressed when +.B e2fsck +is running in preen mode. +.TP +.I no_nomsg +This boolean relation overrides the default behavior controlling +whether or not the description for this file system problem should +be suppressed when a problem forced not to be fixed, either because +.B e2fsck +is run with the +.B -n +option or because the +.I force_no +flag has been set for the problem. +.TP +.I force_no +This boolean option, if set to true, forces a problem to never be fixed. +That is, it will be as if the user problem responds 'no' to the question +of 'should this problem be fixed?'. The +.I force_no +option even overrides the +.B -y +option given on the command-line (just for the specific problem, of course). +.TP +.I not_a_fix +This boolean option, it set to true, marks the problem as +one where if the user gives permission to make the requested change, +it does not mean that the file system had a problem which has since +been fixed. This is used for requests to optimize the file system's +data structure, such as pruning an extent tree. +@TDB_MAN_COMMENT@.SH THE [scratch_files] STANZA +@TDB_MAN_COMMENT@The following relations are defined in the +@TDB_MAN_COMMENT@.I [scratch_files] +@TDB_MAN_COMMENT@stanza. +@TDB_MAN_COMMENT@.TP +@TDB_MAN_COMMENT@.I directory +@TDB_MAN_COMMENT@If the directory named by this relation exists and is +@TDB_MAN_COMMENT@writeable, then e2fsck will attempt to use this +@TDB_MAN_COMMENT@directory to store scratch files instead of using +@TDB_MAN_COMMENT@in-memory data structures. +@TDB_MAN_COMMENT@.TP +@TDB_MAN_COMMENT@.I numdirs_threshold +@TDB_MAN_COMMENT@If this relation is set, then in-memory data structures +@TDB_MAN_COMMENT@will be used if the number of directories in the file system +@TDB_MAN_COMMENT@are fewer than amount specified. +@TDB_MAN_COMMENT@.TP +@TDB_MAN_COMMENT@.I dirinfo +@TDB_MAN_COMMENT@This relation controls whether or not the scratch file +@TDB_MAN_COMMENT@directory is used instead of an in-memory data +@TDB_MAN_COMMENT@structure for directory information. It defaults to +@TDB_MAN_COMMENT@true. +@TDB_MAN_COMMENT@.TP +@TDB_MAN_COMMENT@.I icount +@TDB_MAN_COMMENT@This relation controls whether or not the scratch file +@TDB_MAN_COMMENT@directory is used instead of an in-memory data +@TDB_MAN_COMMENT@structure when tracking inode counts. It defaults to +@TDB_MAN_COMMENT@true. +.SH LOGGING +E2fsck has the facility to save the information from an e2fsck run in a +directory so that a system administrator can review its output at their +leisure. This allows information captured during the automatic e2fsck +preen run, as well as a manually started e2fsck run, to be saved for +posterity. This facility is controlled by the +.IR log_filename , +.IR log_dir , +.IR log_dir_fallback , +and +.I log_dir_wait +relations in the +.I [options] +stanza. +.PP +The filename in +.I log_filename +may contain the following percent-expressions that will be expanded as +follows. +.TP +.B %d +The current day of the month +.TP +.B %D +The current date; this is a equivalent of +.B %Y%m%d +.TP +.B %h +The hostname of the system. +.TP +.B %H +The current hour in 24-hour format (00..23) +.TP +.B %m +The current month as a two-digit number (01..12) +.TP +.B %M +The current minute (00..59) +.TP +.B %N +The name of the block device containing the file system, with any +directory pathname stripped off. +.TP +.B %p +The pid of the e2fsck process +.TP +.B %s +The current time expressed as the number of seconds since 1970-01-01 +00:00:00 UTC +.TP +.B %S +The current second (00..59) +.TP +.B %T +The current time; this is equivalent of +.B %H%M%S +.TP +.B %u +The name of the user running e2fsck. +.TP +.B %U +This percent expression does not expand to anything, but it signals that +any following date or time expressions should be expressed in UTC time +instead of the local timezone. +.TP +.B %y +The last two digits of the current year (00..99) +.TP +.B %Y +The current year (i.e., 2012). +.SH EXAMPLES +The following recipe will prevent e2fsck from aborting during the boot +process when a file system contains orphaned files. (Of course, this is +not always a good idea, since critical files that are needed for the +security of the system could potentially end up in lost+found, and +starting the system without first having a system administrator check +things out may be dangerous.) +.P +.br + [problems] +.br + 0x040002 = { +.br + preen_ok = true +.br + description = "@u @i %i. " +.br + } +.P +The following recipe will cause an e2fsck logfile to be written to the +directory /var/log/e2fsck, with a filename that contains the device +name, the hostname of the system, the date, and time: e.g., +"e2fsck-sda3.server.INFO.20120314-112142". If the directory containing +/var/log is located on the root file system +which is initially mounted read-only, then the output will be saved in +memory and written out once the root file system has been remounted +read/write. To avoid too much detail from being written to the serial +console (which could potentially slow down the boot sequence), only print +no more than 16 instances of each type of file system corruption. +.P +.br + [options] +.br + max_count_problems = 16 +.br + log_dir = /var/log/e2fsck +.br + log_filename = e2fsck-%N.%h.INFO.%D-%T +.br + log_dir_wait = true +.P +.SH FILES +.TP +.I /etc/e2fsck.conf +The configuration file for +.BR e2fsck (8). +.SH SEE ALSO +.BR e2fsck (8) diff --git a/e2fsck/e2fsck.h b/e2fsck/e2fsck.h new file mode 100644 index 0000000..3f2dc30 --- /dev/null +++ b/e2fsck/e2fsck.h @@ -0,0 +1,738 @@ +/* + * e2fsck.h + * + * Copyright (C) 1993, 1994 Theodore Ts'o. This file may be + * redistributed under the terms of the GNU Public License. + * + */ + +#ifndef _E2FSCK_H +#define _E2FSCK_H + +#include <stdio.h> +#include <string.h> +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#include <stdlib.h> +#include <time.h> +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_SETJMP_H +#include <setjmp.h> +#endif + +#if EXT2_FLAT_INCLUDES +#include "ext2_fs.h" +#include "ext2fs.h" +#include "blkid.h" +#else +#include "ext2fs/ext2_fs.h" +#include "ext2fs/ext2fs.h" +#include "blkid/blkid.h" +#endif + +#include "support/profile.h" +#include "support/prof_err.h" + +#ifdef ENABLE_NLS +#include <libintl.h> +#include <locale.h> +#define _(a) (gettext (a)) +#ifdef gettext_noop +#define N_(a) gettext_noop (a) +#else +#define N_(a) (a) +#endif +#define P_(singular, plural, n) (ngettext (singular, plural, n)) +#ifndef NLS_CAT_NAME +#define NLS_CAT_NAME "e2fsprogs" +#endif +#ifndef LOCALEDIR +#define LOCALEDIR "/usr/share/locale" +#endif +#else +#define _(a) (a) +#define N_(a) a +#define P_(singular, plural, n) ((n) == 1 ? (singular) : (plural)) +#endif + +#ifdef __GNUC__ +#define E2FSCK_ATTR(x) __attribute__(x) +#else +#define E2FSCK_ATTR(x) +#endif + +#include "support/quotaio.h" +#if __GNUC_PREREQ (4, 6) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-function" +#endif +#include "ext2fs/fast_commit.h" +#if __GNUC_PREREQ (4, 6) +#pragma GCC diagnostic pop +#endif + +/* + * Exit codes used by fsck-type programs + */ +#define FSCK_OK 0 /* No errors */ +#define FSCK_NONDESTRUCT 1 /* File system errors corrected */ +#define FSCK_REBOOT 2 /* System should be rebooted */ +#define FSCK_UNCORRECTED 4 /* File system errors left uncorrected */ +#define FSCK_ERROR 8 /* Operational error */ +#define FSCK_USAGE 16 /* Usage or syntax error */ +#define FSCK_CANCELED 32 /* Aborted with a signal or ^C */ +#define FSCK_LIBRARY 128 /* Shared library error */ + +/* + * The last ext2fs revision level that this version of e2fsck is able to + * support + */ +#define E2FSCK_CURRENT_REV 1 + +/* + * The directory information structure; stores directory information + * collected in earlier passes, to avoid disk i/o in fetching the + * directory information. + */ +struct dir_info { + ext2_ino_t ino; /* Inode number */ + ext2_ino_t dotdot; /* Parent according to '..' */ + ext2_ino_t parent; /* Parent according to treewalk */ +}; + + +/* + * The indexed directory information structure; stores information for + * directories which contain a hash tree index. + */ +struct dx_dir_info { + ext2_ino_t ino; /* Inode number */ + short depth; /* depth of tree (15 bits) */ + __u8 hashversion; + __u8 casefolded_hash:1; + blk_t numblocks; /* number of blocks in dir */ + struct dx_dirblock_info *dx_block; /* Array of size numblocks */ +}; + +#define DX_DIRBLOCK_ROOT 1 +#define DX_DIRBLOCK_LEAF 2 +#define DX_DIRBLOCK_NODE 3 +#define DX_DIRBLOCK_CORRUPT 4 +#define DX_DIRBLOCK_CLEARED 8 + +struct dx_dirblock_info { + int type; + int flags; + blk64_t phys; + blk64_t parent; + blk64_t previous; + ext2_dirhash_t min_hash; + ext2_dirhash_t max_hash; + ext2_dirhash_t node_min_hash; + ext2_dirhash_t node_max_hash; +}; + +#define DX_FLAG_REFERENCED 1 +#define DX_FLAG_DUP_REF 2 +#define DX_FLAG_FIRST 4 +#define DX_FLAG_LAST 8 + +struct encrypted_file_info; + +#define RESOURCE_TRACK + +#ifdef RESOURCE_TRACK +/* + * This structure is used for keeping track of how much resources have + * been used for a particular pass of e2fsck. + */ +struct resource_track { + struct timeval time_start; + struct timeval user_start; + struct timeval system_start; + void *brk_start; + unsigned long long bytes_read; + unsigned long long bytes_written; +}; +#endif + +/* + * E2fsck options + */ +#define E2F_OPT_READONLY 0x0001 +#define E2F_OPT_PREEN 0x0002 +#define E2F_OPT_YES 0x0004 +#define E2F_OPT_NO 0x0008 +#define E2F_OPT_TIME 0x0010 +#define E2F_OPT_TIME2 0x0020 +#define E2F_OPT_CHECKBLOCKS 0x0040 +#define E2F_OPT_DEBUG 0x0080 +#define E2F_OPT_FORCE 0x0100 +#define E2F_OPT_WRITECHECK 0x0200 +#define E2F_OPT_COMPRESS_DIRS 0x0400 +#define E2F_OPT_FRAGCHECK 0x0800 +#define E2F_OPT_JOURNAL_ONLY 0x1000 /* only replay the journal */ +#define E2F_OPT_DISCARD 0x2000 +#define E2F_OPT_CONVERT_BMAP 0x4000 /* convert blockmap to extent */ +#define E2F_OPT_FIXES_ONLY 0x8000 /* skip all optimizations */ +#define E2F_OPT_NOOPT_EXTENTS 0x10000 /* don't optimize extents */ +#define E2F_OPT_ICOUNT_FULLMAP 0x20000 /* use an array for inode counts */ +#define E2F_OPT_UNSHARE_BLOCKS 0x40000 +#define E2F_OPT_CLEAR_UNINIT 0x80000 /* Hack to clear the uninit bit */ +#define E2F_OPT_CHECK_ENCODING 0x100000 /* Force verification of encoded filenames */ + +/* + * E2fsck flags + */ +#define E2F_FLAG_ABORT 0x0001 /* Abort signaled */ +#define E2F_FLAG_CANCEL 0x0002 /* Cancel signaled */ +#define E2F_FLAG_SIGNAL_MASK (E2F_FLAG_ABORT | E2F_FLAG_CANCEL) +#define E2F_FLAG_RESTART 0x0004 /* Restart signaled */ +#define E2F_FLAG_RUN_RETURN (E2F_FLAG_SIGNAL_MASK | E2F_FLAG_RESTART) +#define E2F_FLAG_RESTART_LATER 0x0008 /* Restart after all iterations done */ +#define E2F_FLAG_SETJMP_OK 0x0010 /* Setjmp valid for abort */ + +#define E2F_FLAG_PROG_BAR 0x0020 /* Progress bar on screen */ +#define E2F_FLAG_PROG_SUPPRESS 0x0040 /* Progress suspended */ +#define E2F_FLAG_JOURNAL_INODE 0x0080 /* Create a new ext3 journal inode */ +#define E2F_FLAG_SB_SPECIFIED 0x0100 /* The superblock was explicitly + * specified by the user */ +#define E2F_FLAG_RESTARTED 0x0200 /* E2fsck has been restarted */ +#define E2F_FLAG_RESIZE_INODE 0x0400 /* Request to recreate resize inode */ +#define E2F_FLAG_GOT_DEVSIZE 0x0800 /* Device size has been fetched */ +#define E2F_FLAG_EXITING 0x1000 /* E2fsck exiting due to errors */ +#define E2F_FLAG_TIME_INSANE 0x2000 /* Time is insane */ +#define E2F_FLAG_PROBLEMS_FIXED 0x4000 /* At least one problem was fixed */ +#define E2F_FLAG_ALLOC_OK 0x8000 /* Can we allocate blocks? */ + +#define E2F_RESET_FLAGS (E2F_FLAG_TIME_INSANE | E2F_FLAG_PROBLEMS_FIXED) + +/* + * Defines for indicating the e2fsck pass number + */ +#define E2F_PASS_1 1 +#define E2F_PASS_2 2 +#define E2F_PASS_3 3 +#define E2F_PASS_4 4 +#define E2F_PASS_5 5 +#define E2F_PASS_1B 6 + +/* + * Define the extended attribute refcount structure + */ +typedef struct ea_refcount *ext2_refcount_t; + +/* + * This is the global e2fsck structure. + */ +typedef struct e2fsck_struct *e2fsck_t; + +#define MAX_EXTENT_DEPTH_COUNT 8 + +/* + * This structure is used to manage the list of extents in a file. Placing + * it here since this is used by fast_commit.h. + */ +struct extent_list { + blk64_t blocks_freed; + struct ext2fs_extent *extents; + unsigned int count; + unsigned int size; + unsigned int ext_read; + errcode_t retval; + ext2_ino_t ino; +}; + +/* State structure for fast commit replay */ +struct e2fsck_fc_replay_state { + struct extent_list fc_extent_list; + int fc_replay_num_tags; + int fc_replay_expected_off; + enum passtype fc_current_pass; + int fc_cur_tag; + unsigned int fc_crc; + __u16 fc_super_state; +}; + +struct e2fsck_struct { + ext2_filsys fs; + const char *program_name; + char *filesystem_name; + char *device_name; + char *io_options; + FILE *logf; + char *log_fn; + FILE *problem_logf; + char *problem_log_fn; + int flags; /* E2fsck internal flags */ + int options; + unsigned blocksize; /* blocksize */ + blk64_t use_superblock; /* sb requested by user */ + blk64_t superblock; /* sb used to open fs */ + blk64_t num_blocks; /* Total number of blocks */ + blk64_t free_blocks; + ext2_ino_t free_inodes; + int mount_flags; + int openfs_flags; + blkid_cache blkid; /* blkid cache */ + +#ifdef HAVE_SETJMP_H + jmp_buf abort_loc; +#endif + unsigned long abort_code; + + int (*progress)(e2fsck_t ctx, int pass, unsigned long cur, + unsigned long max); + + ext2fs_inode_bitmap inode_used_map; /* Inodes which are in use */ + ext2fs_inode_bitmap inode_bad_map; /* Inodes which are bad somehow */ + ext2fs_inode_bitmap inode_dir_map; /* Inodes which are directories */ + ext2fs_inode_bitmap inode_bb_map; /* Inodes which are in bad blocks */ + ext2fs_inode_bitmap inode_imagic_map; /* AFS inodes */ + ext2fs_inode_bitmap inode_reg_map; /* Inodes which are regular files*/ + ext2fs_inode_bitmap inode_casefold_map; /* Inodes which are casefolded */ + + ext2fs_block_bitmap block_found_map; /* Blocks which are in use */ + ext2fs_block_bitmap block_dup_map; /* Blks referenced more than once */ + ext2fs_block_bitmap block_ea_map; /* Blocks which are used by EA's */ + + /* + * Inode count arrays + */ + ext2_icount_t inode_count; + ext2_icount_t inode_link_info; + + ext2_refcount_t refcount; + ext2_refcount_t refcount_extra; + + /* + * Quota blocks and inodes to be charged for each ea block. + */ + ext2_refcount_t ea_block_quota_blocks; + ext2_refcount_t ea_block_quota_inodes; + + /* + * ea_inode references from attr entries. + */ + ext2_refcount_t ea_inode_refs; + + /* + * Array of flags indicating whether an inode bitmap, block + * bitmap, or inode table is invalid + */ + int *invalid_inode_bitmap_flag; + int *invalid_block_bitmap_flag; + int *invalid_inode_table_flag; + int invalid_bitmaps; /* There are invalid bitmaps/itable */ + + /* + * Block buffer + */ + char *block_buf; + + /* + * For pass1_check_directory and pass1_get_blocks + */ + ext2_ino_t stashed_ino; + struct ext2_inode *stashed_inode; + + /* + * Location of the lost and found directory + */ + ext2_ino_t lost_and_found; + int bad_lost_and_found; + + /* + * Directory information + */ + struct dir_info_db *dir_info; + + /* + * Indexed directory information + */ + ext2_ino_t dx_dir_info_count; + ext2_ino_t dx_dir_info_size; + struct dx_dir_info *dx_dir_info; + + /* + * Directories to hash + */ + ext2_u32_list dirs_to_hash; + + /* + * Encrypted file information + */ + struct encrypted_file_info *encrypted_files; + + /* + * Tuning parameters + */ + int process_inode_size; + int inode_buffer_blocks; + unsigned int htree_slack_percentage; + + /* + * ext3 journal support + */ + io_channel journal_io; + char *journal_name; + + /* + * Ext4 quota support + */ + quota_ctx_t qctx; +#ifdef RESOURCE_TRACK + /* + * For timing purposes + */ + struct resource_track global_rtrack; +#endif + + /* + * How we display the progress update (for unix) + */ + int progress_fd; + int progress_pos; + int progress_last_percent; + unsigned int progress_last_time; + int interactive; /* Are we connected directly to a tty? */ + char start_meta[2], stop_meta[2]; + + /* File counts */ + __u32 fs_directory_count; + __u32 fs_regular_count; + __u32 fs_blockdev_count; + __u32 fs_chardev_count; + __u32 fs_links_count; + __u32 fs_symlinks_count; + __u32 fs_fast_symlinks_count; + __u32 fs_fifo_count; + __u32 fs_total_count; + __u32 fs_badblocks_count; + __u32 fs_sockets_count; + __u32 fs_ind_count; + __u32 fs_dind_count; + __u32 fs_tind_count; + __u32 fs_fragmented; + __u32 fs_fragmented_dir; + __u32 large_files; + __u32 large_dirs; + __u32 fs_ext_attr_inodes; + __u32 fs_ext_attr_blocks; + __u32 extent_depth_count[MAX_EXTENT_DEPTH_COUNT]; + + /* misc fields */ + time_t now; + time_t time_fudge; /* For working around buggy init scripts */ + int ext_attr_ver; + profile_t profile; + int blocks_per_page; + ext2_u32_list casefolded_dirs; + + /* Reserve blocks for root and l+f re-creation */ + blk64_t root_repair_block, lnf_repair_block; + + /* + * For the use of callers of the e2fsck functions; not used by + * e2fsck functions themselves. + */ + void *priv_data; + ext2fs_block_bitmap block_metadata_map; /* Metadata blocks */ + + /* How much are we allowed to readahead? */ + unsigned long long readahead_kb; + + /* + * Inodes to rebuild extent trees + */ + ext2fs_inode_bitmap inodes_to_rebuild; + + /* Undo file */ + char *undo_file; + + /* Fast commit replay state */ + struct e2fsck_fc_replay_state fc_replay_state; +}; + +/* Data structures to evaluate whether an extent tree needs rebuilding. */ +struct extent_tree_level { + unsigned int num_extents; + unsigned int max_extents; +}; + +struct extent_tree_info { + ext2_ino_t ino; + int force_rebuild; + struct extent_tree_level ext_info[MAX_EXTENT_DEPTH_COUNT]; +}; + +/* Used by the region allocation code */ +typedef __u64 region_addr_t; +typedef struct region_struct *region_t; + +#ifndef HAVE_STRNLEN +#define strnlen(str, x) e2fsck_strnlen((str),(x)) +extern int e2fsck_strnlen(const char * s, int count); +#endif + +/* + * Procedure declarations + */ + +extern void e2fsck_pass1(e2fsck_t ctx); +extern void e2fsck_pass1_dupblocks(e2fsck_t ctx, char *block_buf); +extern void e2fsck_pass2(e2fsck_t ctx); +extern void e2fsck_pass3(e2fsck_t ctx); +extern void e2fsck_pass4(e2fsck_t ctx); +extern void e2fsck_pass5(e2fsck_t ctx); + +/* e2fsck.c */ +extern errcode_t e2fsck_allocate_context(e2fsck_t *ret); +extern errcode_t e2fsck_reset_context(e2fsck_t ctx); +extern void e2fsck_free_context(e2fsck_t ctx); +extern int e2fsck_run(e2fsck_t ctx); + + +/* badblock.c */ +extern void read_bad_blocks_file(e2fsck_t ctx, const char *bad_blocks_file, + int replace_bad_blocks); + +/* dirinfo.c */ +extern void e2fsck_add_dir_info(e2fsck_t ctx, ext2_ino_t ino, ext2_ino_t parent); +extern void e2fsck_free_dir_info(e2fsck_t ctx); +extern int e2fsck_get_num_dirinfo(e2fsck_t ctx); +extern struct dir_info_iter *e2fsck_dir_info_iter_begin(e2fsck_t ctx); +extern struct dir_info *e2fsck_dir_info_iter(e2fsck_t ctx, + struct dir_info_iter *); +extern void e2fsck_dir_info_iter_end(e2fsck_t ctx, struct dir_info_iter *); +extern int e2fsck_dir_info_set_parent(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t parent); +extern int e2fsck_dir_info_set_dotdot(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t dotdot); +extern int e2fsck_dir_info_get_parent(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t *parent); +extern int e2fsck_dir_info_get_dotdot(e2fsck_t ctx, ext2_ino_t ino, + ext2_ino_t *dotdot); + +/* dx_dirinfo.c */ +extern void e2fsck_add_dx_dir(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode *inode, int num_blocks); +extern struct dx_dir_info *e2fsck_get_dx_dir_info(e2fsck_t ctx, ext2_ino_t ino); +extern void e2fsck_free_dx_dir_info(e2fsck_t ctx); +extern ext2_ino_t e2fsck_get_num_dx_dirinfo(e2fsck_t ctx); +extern struct dx_dir_info *e2fsck_dx_dir_info_iter(e2fsck_t ctx, + ext2_ino_t *control); + +/* ea_refcount.c */ +typedef __u64 ea_key_t; +typedef __u64 ea_value_t; + +extern errcode_t ea_refcount_create(size_t size, ext2_refcount_t *ret); +extern void ea_refcount_free(ext2_refcount_t refcount); +extern errcode_t ea_refcount_fetch(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t *ret); +extern errcode_t ea_refcount_increment(ext2_refcount_t refcount, + ea_key_t ea_key, ea_value_t *ret); +extern errcode_t ea_refcount_decrement(ext2_refcount_t refcount, + ea_key_t ea_key, ea_value_t *ret); +extern errcode_t ea_refcount_store(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t count); +extern size_t ext2fs_get_refcount_size(ext2_refcount_t refcount); +extern void ea_refcount_intr_begin(ext2_refcount_t refcount); +extern ea_key_t ea_refcount_intr_next(ext2_refcount_t refcount, + ea_value_t *ret); + +/* ehandler.c */ +extern const char *ehandler_operation(const char *op); +extern void ehandler_init(io_channel channel); + +/* encrypted_files.c */ + +struct problem_context; +int add_encrypted_file(e2fsck_t ctx, struct problem_context *pctx); + +#define NO_ENCRYPTION_POLICY ((__u32)-1) +#define CORRUPT_ENCRYPTION_POLICY ((__u32)-2) +#define UNRECOGNIZED_ENCRYPTION_POLICY ((__u32)-3) +__u32 find_encryption_policy(e2fsck_t ctx, ext2_ino_t ino); + +void destroy_encryption_policy_map(e2fsck_t ctx); +void destroy_encrypted_file_info(e2fsck_t ctx); + +/* extents.c */ +errcode_t e2fsck_rebuild_extents_later(e2fsck_t ctx, ext2_ino_t ino); +int e2fsck_ino_will_be_rebuilt(e2fsck_t ctx, ext2_ino_t ino); +void e2fsck_pass1e(e2fsck_t ctx); +errcode_t e2fsck_check_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode *inode, + struct problem_context *pctx); +errcode_t e2fsck_should_rebuild_extents(e2fsck_t ctx, + struct problem_context *pctx, + struct extent_tree_info *eti, + struct ext2_extent_info *info); +errcode_t e2fsck_read_extents(e2fsck_t ctx, struct extent_list *extents); +errcode_t e2fsck_rewrite_extent_tree(e2fsck_t ctx, + struct extent_list *extents); + +/* journal.c */ +extern errcode_t e2fsck_check_ext3_journal(e2fsck_t ctx); +extern errcode_t e2fsck_run_ext3_journal(e2fsck_t ctx); +extern void e2fsck_move_ext3_journal(e2fsck_t ctx); +extern int e2fsck_fix_ext3_journal_hint(e2fsck_t ctx); + +/* logfile.c */ +extern void set_up_logging(e2fsck_t ctx); + +/* quota.c */ +extern void e2fsck_hide_quota(e2fsck_t ctx); +extern void e2fsck_validate_quota_inodes(e2fsck_t ctx); + +/* pass1.c */ +extern errcode_t e2fsck_setup_icount(e2fsck_t ctx, const char *icount_name, + int flags, ext2_icount_t hint, + ext2_icount_t *ret); +extern void e2fsck_use_inode_shortcuts(e2fsck_t ctx, int use_shortcuts); +extern int e2fsck_pass1_check_device_inode(ext2_filsys fs, + struct ext2_inode *inode); +extern int e2fsck_pass1_check_symlink(ext2_filsys fs, ext2_ino_t ino, + struct ext2_inode *inode, char *buf); +extern void e2fsck_clear_inode(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode *inode, int restart_flag, + const char *source); +extern void e2fsck_intercept_block_allocations(e2fsck_t ctx); + +/* pass2.c */ +extern int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir, + ext2_ino_t ino, char *buf); + +/* pass3.c */ +extern int e2fsck_reconnect_file(e2fsck_t ctx, ext2_ino_t inode); +extern errcode_t e2fsck_expand_directory(e2fsck_t ctx, ext2_ino_t dir, + int num, int gauranteed_size); +extern ext2_ino_t e2fsck_get_lost_and_found(e2fsck_t ctx, int fix); +extern errcode_t e2fsck_adjust_inode_count(e2fsck_t ctx, ext2_ino_t ino, + int adj); + +/* readahead.c */ +#define E2FSCK_READA_SUPER (0x01) +#define E2FSCK_READA_GDT (0x02) +#define E2FSCK_READA_BBITMAP (0x04) +#define E2FSCK_READA_IBITMAP (0x08) +#define E2FSCK_READA_ITABLE (0x10) +#define E2FSCK_READA_ALL_FLAGS (0x1F) +errcode_t e2fsck_readahead(ext2_filsys fs, int flags, dgrp_t start, + dgrp_t ngroups); +#define E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT (0x01) +#define E2FSCK_RA_DBLIST_ALL_FLAGS (0x01) +errcode_t e2fsck_readahead_dblist(ext2_filsys fs, int flags, + ext2_dblist dblist, + unsigned long long start, + unsigned long long count); +int e2fsck_can_readahead(ext2_filsys fs); +unsigned long long e2fsck_guess_readahead(ext2_filsys fs); + +/* region.c */ +extern region_t region_create(region_addr_t min, region_addr_t max); +extern void region_free(region_t region); +extern int region_allocate(region_t region, region_addr_t start, int n); + +/* rehash.c */ +void e2fsck_rehash_dir_later(e2fsck_t ctx, ext2_ino_t ino); +int e2fsck_dir_will_be_rehashed(e2fsck_t ctx, ext2_ino_t ino); +errcode_t e2fsck_rehash_dir(e2fsck_t ctx, ext2_ino_t ino, + struct problem_context *pctx); +void e2fsck_rehash_directories(e2fsck_t ctx); + +/* sigcatcher.c */ +void sigcatcher_setup(void); + +/* super.c */ +void check_super_block(e2fsck_t ctx); +int check_backup_super_block(e2fsck_t ctx); +void check_resize_inode(e2fsck_t ctx); +int check_init_orphan_file(e2fsck_t ctx); + +/* util.c */ +extern void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size, + const char *description); +extern int ask(e2fsck_t ctx, const char * string, int def); +extern int ask_yn(e2fsck_t ctx, const char * string, int def); +extern void fatal_error(e2fsck_t ctx, const char * fmt_string); +extern void log_out(e2fsck_t ctx, const char *fmt, ...) + E2FSCK_ATTR((format(printf, 2, 3))); +extern void log_err(e2fsck_t ctx, const char *fmt, ...) + E2FSCK_ATTR((format(printf, 2, 3))); +extern void e2fsck_read_bitmaps(e2fsck_t ctx); +extern void e2fsck_write_bitmaps(e2fsck_t ctx); +extern void preenhalt(e2fsck_t ctx); +extern char *string_copy(e2fsck_t ctx, const char *str, size_t len); +extern int fs_proc_check(const char *fs_name); +extern int check_for_modules(const char *fs_name); +#ifdef RESOURCE_TRACK +extern void print_resource_track(e2fsck_t ctx, + const char *desc, + struct resource_track *track, + io_channel channel); +extern void init_resource_track(struct resource_track *track, + io_channel channel); +#else +#define print_resource_track(ctx, desc, track, channel) do { } while (0) +#define init_resource_track(track, channel) do { } while (0) +#endif +extern int inode_has_valid_blocks(struct ext2_inode *inode); +extern void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, const char * proc); +extern void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino, + struct ext2_inode *inode, + const int bufsize, const char *proc); +extern void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, const char * proc); +extern void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, int bufsize, + const char *proc); +#ifdef MTRACE +extern void mtrace_print(char *mesg); +#endif +extern blk64_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, + const char *name, io_manager manager); +extern int ext2_file_type(unsigned int mode); +extern int write_all(int fd, char *buf, size_t count); +void dump_mmp_msg(struct mmp_struct *mmp, const char *fmt, ...) + E2FSCK_ATTR((format(printf, 2, 3))); +errcode_t e2fsck_mmp_update(ext2_filsys fs); + +extern void e2fsck_set_bitmap_type(ext2_filsys fs, + unsigned int default_type, + const char *profile_name, + unsigned int *old_type); +extern errcode_t e2fsck_allocate_inode_bitmap(ext2_filsys fs, + const char *descr, + int default_type, + const char *profile_name, + ext2fs_inode_bitmap *ret); +extern errcode_t e2fsck_allocate_block_bitmap(ext2_filsys fs, + const char *descr, + int default_type, + const char *profile_name, + ext2fs_block_bitmap *ret); +extern errcode_t e2fsck_allocate_subcluster_bitmap(ext2_filsys fs, + const char *descr, + int default_type, + const char *profile_name, + ext2fs_block_bitmap *ret); +unsigned long long get_memory_size(void); + +/* unix.c */ +extern void e2fsck_clear_progbar(e2fsck_t ctx); +extern int e2fsck_simple_progress(e2fsck_t ctx, const char *label, + float percent, unsigned int dpynum); + +#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d)) + +#endif /* _E2FSCK_H */ diff --git a/e2fsck/ea_refcount.c b/e2fsck/ea_refcount.c new file mode 100644 index 0000000..7154b47 --- /dev/null +++ b/e2fsck/ea_refcount.c @@ -0,0 +1,476 @@ +/* + * ea_refcount.c + * + * Copyright (C) 2001 Theodore Ts'o. This file may be + * redistributed under the terms of the GNU Public License. + */ + +#include "config.h" +#if HAVE_UNISTD_H +#include <unistd.h> +#endif +#include <string.h> +#include <stdio.h> + +#ifdef TEST_PROGRAM +#undef ENABLE_NLS +#endif +#include "e2fsck.h" + +/* + * The strategy we use for keeping track of EA refcounts is as + * follows. We keep a sorted array of first EA blocks and its + * reference counts. Once the refcount has dropped to zero, it is + * removed from the array to save memory space. Once the EA block is + * checked, its bit is set in the block_ea_map bitmap. + */ +struct ea_refcount_el { + /* ea_key could either be an inode number or block number. */ + ea_key_t ea_key; + ea_value_t ea_value; +}; + +struct ea_refcount { + size_t count; + size_t size; + size_t cursor; + struct ea_refcount_el *list; +}; + +void ea_refcount_free(ext2_refcount_t refcount) +{ + if (!refcount) + return; + + if (refcount->list) + ext2fs_free_mem(&refcount->list); + ext2fs_free_mem(&refcount); +} + +errcode_t ea_refcount_create(size_t size, ext2_refcount_t *ret) +{ + ext2_refcount_t refcount; + errcode_t retval; + size_t bytes; + + retval = ext2fs_get_memzero(sizeof(struct ea_refcount), &refcount); + if (retval) + return retval; + + if (!size) + size = 500; + refcount->size = size; + bytes = size * sizeof(struct ea_refcount_el); +#ifdef DEBUG + printf("Refcount allocated %zu entries, %zu bytes.\n", + refcount->size, bytes); +#endif + retval = ext2fs_get_memzero(bytes, &refcount->list); + if (retval) + goto errout; + + refcount->count = 0; + refcount->cursor = 0; + + *ret = refcount; + return 0; + +errout: + ea_refcount_free(refcount); + return(retval); +} + +/* + * collapse_refcount() --- go through the refcount array, and get rid + * of any count == zero entries + */ +static void refcount_collapse(ext2_refcount_t refcount) +{ + unsigned int i, j; + struct ea_refcount_el *list; + + list = refcount->list; + for (i = 0, j = 0; i < refcount->count; i++) { + if (list[i].ea_value) { + if (i != j) + list[j] = list[i]; + j++; + } + } +#if defined(DEBUG) || defined(TEST_PROGRAM) + printf("Refcount_collapse: size was %zu, now %d\n", + refcount->count, j); +#endif + refcount->count = j; +} + + +/* + * insert_refcount_el() --- Insert a new entry into the sorted list at a + * specified position. + */ +static struct ea_refcount_el *insert_refcount_el(ext2_refcount_t refcount, + ea_key_t ea_key, int pos) +{ + struct ea_refcount_el *el; + errcode_t retval; + size_t new_size = 0; + int num; + + if (refcount->count >= refcount->size) { + new_size = refcount->size + 100; +#ifdef DEBUG + printf("Reallocating refcount %d entries...\n", new_size); +#endif + retval = ext2fs_resize_mem((size_t) refcount->size * + sizeof(struct ea_refcount_el), + (size_t) new_size * + sizeof(struct ea_refcount_el), + &refcount->list); + if (retval) + return 0; + refcount->size = new_size; + } + num = (int) refcount->count - pos; + if (num < 0) + return 0; /* should never happen */ + if (num) { + memmove(&refcount->list[pos+1], &refcount->list[pos], + sizeof(struct ea_refcount_el) * num); + } + refcount->count++; + el = &refcount->list[pos]; + el->ea_key = ea_key; + el->ea_value = 0; + return el; +} + + +/* + * get_refcount_el() --- given an block number, try to find refcount + * information in the sorted list. If the create flag is set, + * and we can't find an entry, create one in the sorted list. + */ +static struct ea_refcount_el *get_refcount_el(ext2_refcount_t refcount, + ea_key_t ea_key, int create) +{ + int low, high, mid; + + if (!refcount || !refcount->list) + return 0; +retry: + low = 0; + high = (int) refcount->count-1; + if (create && ((refcount->count == 0) || + (ea_key > refcount->list[high].ea_key))) { + if (refcount->count >= refcount->size) + refcount_collapse(refcount); + + return insert_refcount_el(refcount, ea_key, + (unsigned) refcount->count); + } + if (refcount->count == 0) + return 0; + + if (refcount->cursor >= refcount->count) + refcount->cursor = 0; + if (ea_key == refcount->list[refcount->cursor].ea_key) + return &refcount->list[refcount->cursor++]; +#ifdef DEBUG + printf("Non-cursor get_refcount_el: %u\n", ea_key); +#endif + while (low <= high) { + mid = (low+high)/2; + if (ea_key == refcount->list[mid].ea_key) { + refcount->cursor = mid+1; + return &refcount->list[mid]; + } + if (ea_key < refcount->list[mid].ea_key) + high = mid-1; + else + low = mid+1; + } + /* + * If we need to create a new entry, it should be right at + * low (where high will be left at low-1). + */ + if (create) { + if (refcount->count >= refcount->size) { + refcount_collapse(refcount); + if (refcount->count < refcount->size) + goto retry; + } + return insert_refcount_el(refcount, ea_key, low); + } + return 0; +} + +errcode_t ea_refcount_fetch(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t *ret) +{ + struct ea_refcount_el *el; + + el = get_refcount_el(refcount, ea_key, 0); + if (!el) { + *ret = 0; + return 0; + } + *ret = el->ea_value; + return 0; +} + +errcode_t ea_refcount_increment(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t *ret) +{ + struct ea_refcount_el *el; + + el = get_refcount_el(refcount, ea_key, 1); + if (!el) + return EXT2_ET_NO_MEMORY; + el->ea_value++; + + if (ret) + *ret = el->ea_value; + return 0; +} + +errcode_t ea_refcount_decrement(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t *ret) +{ + struct ea_refcount_el *el; + + el = get_refcount_el(refcount, ea_key, 0); + if (!el || el->ea_value == 0) + return EXT2_ET_INVALID_ARGUMENT; + + el->ea_value--; + + if (ret) + *ret = el->ea_value; + return 0; +} + +errcode_t ea_refcount_store(ext2_refcount_t refcount, ea_key_t ea_key, + ea_value_t ea_value) +{ + struct ea_refcount_el *el; + + /* + * Get the refcount element + */ + el = get_refcount_el(refcount, ea_key, ea_value ? 1 : 0); + if (!el) + return ea_value ? EXT2_ET_NO_MEMORY : 0; + el->ea_value = ea_value; + return 0; +} + +size_t ext2fs_get_refcount_size(ext2_refcount_t refcount) +{ + if (!refcount) + return 0; + + return refcount->size; +} + +void ea_refcount_intr_begin(ext2_refcount_t refcount) +{ + refcount->cursor = 0; +} + +ea_key_t ea_refcount_intr_next(ext2_refcount_t refcount, + ea_value_t *ret) +{ + struct ea_refcount_el *list; + + while (1) { + if (refcount->cursor >= refcount->count) + return 0; + list = refcount->list; + if (list[refcount->cursor].ea_value) { + if (ret) + *ret = list[refcount->cursor].ea_value; + return list[refcount->cursor++].ea_key; + } + refcount->cursor++; + } +} + + +#ifdef TEST_PROGRAM + +errcode_t ea_refcount_validate(ext2_refcount_t refcount, FILE *out) +{ + errcode_t ret = 0; + int i; + const char *bad = "bad refcount"; + + if (refcount->count > refcount->size) { + fprintf(out, "%s: count > size\n", bad); + return EXT2_ET_INVALID_ARGUMENT; + } + for (i=1; i < refcount->count; i++) { + if (refcount->list[i-1].ea_key >= refcount->list[i].ea_key) { + fprintf(out, + "%s: list[%d].ea_key=%llu, list[%d].ea_key=%llu\n", + bad, i-1, + (unsigned long long) refcount->list[i-1].ea_key, + i, + (unsigned long long) refcount->list[i].ea_key); + ret = EXT2_ET_INVALID_ARGUMENT; + } + } + return ret; +} + +#define BCODE_END 0 +#define BCODE_CREATE 1 +#define BCODE_FREE 2 +#define BCODE_STORE 3 +#define BCODE_INCR 4 +#define BCODE_DECR 5 +#define BCODE_FETCH 6 +#define BCODE_VALIDATE 7 +#define BCODE_LIST 8 +#define BCODE_COLLAPSE 9 + +int bcode_program[] = { + BCODE_CREATE, 5, + BCODE_STORE, 3, 3, + BCODE_STORE, 4, 4, + BCODE_STORE, 1, 1, + BCODE_STORE, 8, 8, + BCODE_STORE, 2, 2, + BCODE_STORE, 4, 0, + BCODE_STORE, 2, 0, + BCODE_STORE, 6, 6, + BCODE_VALIDATE, + BCODE_STORE, 4, 4, + BCODE_STORE, 2, 2, + BCODE_FETCH, 1, + BCODE_FETCH, 2, + BCODE_INCR, 3, + BCODE_INCR, 3, + BCODE_DECR, 4, + BCODE_STORE, 4, 4, + BCODE_VALIDATE, + BCODE_STORE, 20, 20, + BCODE_STORE, 40, 40, + BCODE_STORE, 30, 30, + BCODE_STORE, 10, 10, + BCODE_DECR, 30, + BCODE_FETCH, 30, + BCODE_DECR, 2, + BCODE_DECR, 2, + BCODE_COLLAPSE, + BCODE_LIST, + BCODE_VALIDATE, + BCODE_FREE, + BCODE_END +}; + +int main(int argc, char **argv) +{ + int i = 0; + ext2_refcount_t refcount; + size_t size; + ea_key_t ea_key; + ea_value_t arg; + errcode_t retval; + + while (1) { + switch (bcode_program[i++]) { + case BCODE_END: + exit(0); + case BCODE_CREATE: + size = bcode_program[i++]; + retval = ea_refcount_create(size, &refcount); + if (retval) { + com_err("ea_refcount_create", retval, + "while creating size %zu", size); + exit(1); + } else + printf("Creating refcount with size %zu\n", + size); + break; + case BCODE_FREE: + ea_refcount_free(refcount); + refcount = 0; + printf("Freeing refcount\n"); + break; + case BCODE_STORE: + ea_key = (size_t) bcode_program[i++]; + arg = bcode_program[i++]; + printf("Storing ea_key %llu with value %llu\n", + (unsigned long long) ea_key, + (unsigned long long) arg); + retval = ea_refcount_store(refcount, ea_key, arg); + if (retval) + com_err("ea_refcount_store", retval, + "while storing ea_key %llu", + (unsigned long long) ea_key); + break; + case BCODE_FETCH: + ea_key = (size_t) bcode_program[i++]; + retval = ea_refcount_fetch(refcount, ea_key, &arg); + if (retval) + com_err("ea_refcount_fetch", retval, + "while fetching ea_key %llu", + (unsigned long long) ea_key); + else + printf("bcode_fetch(%llu) returns %llu\n", + (unsigned long long) ea_key, + (unsigned long long) arg); + break; + case BCODE_INCR: + ea_key = (size_t) bcode_program[i++]; + retval = ea_refcount_increment(refcount, ea_key, &arg); + if (retval) + com_err("ea_refcount_increment", retval, + "while incrementing ea_key %llu", + (unsigned long long) ea_key); + else + printf("bcode_increment(%llu) returns %llu\n", + (unsigned long long) ea_key, + (unsigned long long) arg); + break; + case BCODE_DECR: + ea_key = (size_t) bcode_program[i++]; + retval = ea_refcount_decrement(refcount, ea_key, &arg); + if (retval) + com_err("ea_refcount_decrement", retval, + "while decrementing ea_key %llu", + (unsigned long long) ea_key); + else + printf("bcode_decrement(%llu) returns %llu\n", + (unsigned long long) ea_key, + (unsigned long long) arg); + break; + case BCODE_VALIDATE: + retval = ea_refcount_validate(refcount, stderr); + if (retval) + com_err("ea_refcount_validate", retval, + "while validating"); + else + printf("Refcount validation OK.\n"); + break; + case BCODE_LIST: + ea_refcount_intr_begin(refcount); + while (1) { + ea_key = ea_refcount_intr_next(refcount, &arg); + if (!ea_key) + break; + printf("\tea_key=%llu, count=%llu\n", + (unsigned long long) ea_key, + (unsigned long long) arg); + } + break; + case BCODE_COLLAPSE: + refcount_collapse(refcount); + break; + } + + } +} + +#endif diff --git a/e2fsck/ehandler.c b/e2fsck/ehandler.c new file mode 100644 index 0000000..71ca301 --- /dev/null +++ b/e2fsck/ehandler.c @@ -0,0 +1,133 @@ +/* + * ehandler.c --- handle bad block errors which come up during the + * course of an e2fsck session. + * + * Copyright (C) 1994 Theodore Ts'o. This file may be redistributed + * under the terms of the GNU Public License. + */ + +#include "config.h" +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <ctype.h> +#include <termios.h> + +#include "e2fsck.h" + +#include <sys/time.h> +#include <sys/resource.h> + +static const char *operation; + +static errcode_t e2fsck_handle_read_error(io_channel channel, + unsigned long block, + int count, + void *data, + size_t size EXT2FS_ATTR((unused)), + int actual EXT2FS_ATTR((unused)), + errcode_t error) +{ + int i; + char *p; + ext2_filsys fs = (ext2_filsys) channel->app_data; + e2fsck_t ctx; + + ctx = (e2fsck_t) fs->priv_data; + if (ctx->flags & E2F_FLAG_EXITING) + return 0; + /* + * If more than one block was read, try reading each block + * separately. We could use the actual bytes read to figure + * out where to start, but we don't bother. + */ + if (count > 1) { + p = (char *) data; + for (i=0; i < count; i++, p += channel->block_size, block++) { + error = io_channel_read_blk64(channel, block, + 1, p); + if (error) + return error; + } + return 0; + } + if (operation) + printf(_("Error reading block %lu (%s) while %s. "), block, + error_message(error), operation); + else + printf(_("Error reading block %lu (%s). "), block, + error_message(error)); + preenhalt(ctx); + + /* Don't rewrite a block past the end of the FS. */ + if (block >= ext2fs_blocks_count(fs->super)) + return 0; + + if (ask(ctx, _("Ignore error"), 1)) { + if (ask(ctx, _("Force rewrite"), 1)) + io_channel_write_blk64(channel, block, count, data); + return 0; + } + + return error; +} + +static errcode_t e2fsck_handle_write_error(io_channel channel, + unsigned long block, + int count, + const void *data, + size_t size EXT2FS_ATTR((unused)), + int actual EXT2FS_ATTR((unused)), + errcode_t error) +{ + int i; + const char *p; + ext2_filsys fs = (ext2_filsys) channel->app_data; + e2fsck_t ctx; + + ctx = (e2fsck_t) fs->priv_data; + if (ctx->flags & E2F_FLAG_EXITING) + return 0; + + /* + * If more than one block was written, try writing each block + * separately. We could use the actual bytes read to figure + * out where to start, but we don't bother. + */ + if (count > 1) { + p = (const char *) data; + for (i=0; i < count; i++, p += channel->block_size, block++) { + error = io_channel_write_blk64(channel, block, + 1, p); + if (error) + return error; + } + return 0; + } + + if (operation) + printf(_("Error writing block %lu (%s) while %s. "), block, + error_message(error), operation); + else + printf(_("Error writing block %lu (%s). "), block, + error_message(error)); + preenhalt(ctx); + if (ask(ctx, _("Ignore error"), 1)) + return 0; + + return error; +} + +const char *ehandler_operation(const char *op) +{ + const char *ret = operation; + + operation = op; + return ret; +} + +void ehandler_init(io_channel channel) +{ + channel->read_error = e2fsck_handle_read_error; + channel->write_error = e2fsck_handle_write_error; +} diff --git a/e2fsck/emptydir.c b/e2fsck/emptydir.c new file mode 100644 index 0000000..7aea7b6 --- /dev/null +++ b/e2fsck/emptydir.c @@ -0,0 +1,194 @@ +/* + * emptydir.c --- clear empty directory blocks + * + * Copyright (C) 1998 Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * This file has the necessary routines to search for empty directory + * blocks and get rid of them. + */ + +#include "config.h" +#include "e2fsck.h" +#include "problem.h" + +/* + * For e2fsck.h + */ +struct empty_dir_info_struct { + ext2_dblist empty_dblist; + ext2fs_block_bitmap empty_dir_blocks; + ext2fs_inode_bitmap dir_map; + char *block_buf; + ext2_ino_t ino; + struct ext2_inode inode; + blk64_t logblk; + blk64_t freed_blocks; +}; + +typedef struct empty_dir_info_struct *empty_dir_info; + +extern empty_dir_info init_empty_dir(e2fsck_t ctx); +extern void free_empty_dirblock(empty_dir_info edi); +extern void add_empty_dirblock(empty_dir_info edi, + struct ext2_db_entry2 *db); +extern void process_empty_dirblock(e2fsck_t ctx, empty_dir_info edi); + + +empty_dir_info init_empty_dir(e2fsck_t ctx) +{ + empty_dir_info edi; + errcode_t retval; + + edi = e2fsck_allocate_memzero(ctx, sizeof(struct empty_dir_info_struct), + "empty dir info"); + if (retval) + return NULL; + + retval = ext2fs_init_dblist(ctx->fs, &edi->empty_dblist); + if (retval) + goto errout; + + retval = ext2fs_allocate_block_bitmap(ctx->fs, _("empty dirblocks"), + &edi->empty_dir_blocks); + if (retval) + goto errout; + + retval = ext2fs_allocate_inode_bitmap(ctx->fs, _("empty dir map"), + &edi->dir_map); + if (retval) + goto errout; + + return (edi); + +errout: + free_empty_dirblock(edi); + return NULL; +} + +void free_empty_dirblock(empty_dir_info edi) +{ + if (!edi) + return; + if (edi->empty_dblist) + ext2fs_free_dblist(edi->empty_dblist); + if (edi->empty_dir_blocks) + ext2fs_free_block_bitmap(edi->empty_dir_blocks); + if (edi->dir_map) + ext2fs_free_inode_bitmap(edi->dir_map); + + memset(edi, 0, sizeof(struct empty_dir_info_struct)); + ext2fs_free_mem(&edi); +} + +void add_empty_dirblock(empty_dir_info edi, + struct ext2_db_entry2 *db) +{ + if (!edi || !db) + return; + + if (db->ino == 11) + return; /* Inode number 11 is usually lost+found */ + + printf(_("Empty directory block %u (#%d) in inode %u\n"), + db->blk, db->blockcnt, db->ino); + + ext2fs_mark_block_bitmap2(edi->empty_dir_blocks, db->blk); + if (ext2fs_test_inode_bitmap(edi->dir_map, db->ino)) + return; + ext2fs_mark_inode_bitmap(edi->dir_map, db->ino); + + ext2fs_add_dir_block2(edi->empty_dblist, db->ino, + db->blk, db->blockcnt); +} + +/* + * Helper function used by fix_directory. + * + * XXX need to finish this. General approach is to use bmap to + * iterate over all of the logical blocks using the bmap function, and + * copy the block reference as necessary. Big question --- what do + * about error recovery? + * + * Also question --- how to free the indirect blocks. + */ +int empty_pass1(ext2_filsys fs, blk64_t *block_nr, e2_blkcnt_t blockcnt, + blk64_t ref_block, int ref_offset, void *priv_data) +{ + empty_dir_info edi = (empty_dir_info) priv_data; + blk64_t block, new_block; + errcode_t retval; + + if (blockcnt < 0) + return 0; + block = *block_nr; + do { + retval = ext2fs_bmap2(fs, edi->ino, &edi->inode, + edi->block_buf, 0, edi->logblk, 0, + &new_block); + if (retval) + return DIRENT_ABORT; /* XXX what to do? */ + if (new_block == 0) + break; + edi->logblk++; + } while (ext2fs_test_block_bitmap2(edi->empty_dir_blocks, new_block)); + + if (new_block == block) + return 0; + if (new_block == 0) + edi->freed_blocks++; + *block_nr = new_block; + return BLOCK_CHANGED; +} + +static int fix_directory(ext2_filsys fs, + struct ext2_db_entry2 *db, + void *priv_data) +{ + errcode_t retval; + + empty_dir_info edi = (empty_dir_info) priv_data; + + edi->logblk = 0; + edi->freed_blocks = 0; + edi->ino = db->ino; + + retval = ext2fs_read_inode(fs, db->ino, &edi->inode); + if (retval) + return 0; + + retval = ext2fs_block_iterate3(fs, db->ino, 0, edi->block_buf, + empty_pass1, edi); + if (retval) + return 0; + + if (edi->freed_blocks) { + edi->inode.i_size -= edi->freed_blocks * fs->blocksize; + ext2fs_iblk_add_blocks(fs, &edi->inode, edi->freed_blocks); + retval = ext2fs_write_inode(fs, db->ino, &edi->inode); + if (retval) + return 0; + } + return 0; +} + +void process_empty_dirblock(e2fsck_t ctx, empty_dir_info edi) +{ + if (!edi) + return; + + retval = ext2f_get_mem(ctx, ctx->fs->blocksize * 3, + &edi->block_buf); + + if (edi->block_buf) { + (void) ext2fs_dblist_iterate2(edi->empty_dblist, + fix_directory, &edi); + } + ext2fs_free_mem(&edi->block_buf); + free_empty_dirblock(edi); +} + diff --git a/e2fsck/encrypted_files.c b/e2fsck/encrypted_files.c new file mode 100644 index 0000000..16be2d6 --- /dev/null +++ b/e2fsck/encrypted_files.c @@ -0,0 +1,458 @@ +/* + * encrypted_files.c --- save information about encrypted files + * + * Copyright 2019 Google LLC + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +/* + * e2fsck pass 1 (inode table scan) creates a map from inode number to + * encryption policy for all encrypted inodes. But it's optimized so that the + * full xattrs aren't saved but rather only 32-bit "policy IDs", since usually + * many inodes share the same encryption policy. This requires also maintaining + * a second map, from policy to policy ID. See add_encrypted_file(). + * + * We also use run-length encoding to save memory when many adjacent inodes + * share the same encryption policy, which is often the case too. + * + * e2fsck pass 2 (directory structure check) uses the inode => policy ID map to + * verify that all regular files, directories, and symlinks in encrypted + * directories use the directory's encryption policy. + */ + +#include "config.h" + +#include "e2fsck.h" +#include "problem.h" +#include "ext2fs/rbtree.h" + +#define FSCRYPT_KEY_DESCRIPTOR_SIZE 8 +#define FSCRYPT_KEY_IDENTIFIER_SIZE 16 +#define FS_KEY_DERIVATION_NONCE_SIZE 16 + +struct fscrypt_context_v1 { + __u8 version; + __u8 contents_encryption_mode; + __u8 filenames_encryption_mode; + __u8 flags; + __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE]; + __u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE]; +}; + +struct fscrypt_context_v2 { + __u8 version; + __u8 contents_encryption_mode; + __u8 filenames_encryption_mode; + __u8 flags; + __u8 __reserved[4]; + __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE]; + __u8 nonce[FS_KEY_DERIVATION_NONCE_SIZE]; +}; + +/* On-disk format of encryption xattr */ +union fscrypt_context { + __u8 version; + struct fscrypt_context_v1 v1; + struct fscrypt_context_v2 v2; +}; + +struct fscrypt_policy_v1 { + __u8 version; + __u8 contents_encryption_mode; + __u8 filenames_encryption_mode; + __u8 flags; + __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE]; +}; + +struct fscrypt_policy_v2 { + __u8 version; + __u8 contents_encryption_mode; + __u8 filenames_encryption_mode; + __u8 flags; + __u8 __reserved[4]; + __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE]; +}; + +/* The encryption "policy" is the fscrypt_context excluding the nonce. */ +union fscrypt_policy { + __u8 version; + struct fscrypt_policy_v1 v1; + struct fscrypt_policy_v2 v2; +}; + +/* A range of inodes which share the same encryption policy */ +struct encrypted_file_range { + ext2_ino_t first_ino; + ext2_ino_t last_ino; + __u32 policy_id; +}; + +/* Information about the encrypted files which have been seen so far */ +struct encrypted_file_info { + /* + * Map from inode number to encryption policy ID, implemented as a + * sorted array of inode ranges, each of which shares the same policy. + * Inodes are added in order of increasing inode number. + * + * Freed after pass 2. + */ + struct encrypted_file_range *file_ranges; + size_t file_ranges_count; + size_t file_ranges_capacity; + + /* + * Map from encryption policy to encryption policy ID, for the unique + * encryption policies that have been seen so far. next_policy_id is + * the next available ID, starting at 0. + * + * Freed after pass 1. + */ + struct rb_root policies; + __u32 next_policy_id; +}; + +/* Entry in encrypted_file_info::policies */ +struct policy_map_entry { + union fscrypt_policy policy; + __u32 policy_id; + struct rb_node node; +}; + +static int cmp_fscrypt_policies(e2fsck_t ctx, const union fscrypt_policy *a, + const union fscrypt_policy *b) +{ + if (a->version != b->version) + return (int)a->version - (int)b->version; + + switch (a->version) { + case 1: + return memcmp(a, b, sizeof(a->v1)); + case 2: + return memcmp(a, b, sizeof(a->v2)); + } + fatal_error(ctx, "Unhandled encryption policy version"); + return 0; +} + +/* Read an inode's encryption xattr. */ +static errcode_t read_encryption_xattr(e2fsck_t ctx, ext2_ino_t ino, + void **value, size_t *value_len) +{ + struct ext2_xattr_handle *h; + errcode_t retval; + + retval = ext2fs_xattrs_open(ctx->fs, ino, &h); + if (retval) + return retval; + + retval = ext2fs_xattrs_read(h); + if (retval == 0) + retval = ext2fs_xattr_get(h, "c", value, value_len); + + ext2fs_xattrs_close(&h); + return retval; +} + +/* + * Convert an fscrypt_context to an fscrypt_policy. Returns 0, + * CORRUPT_ENCRYPTION_POLICY, or UNRECOGNIZED_ENCRYPTION_POLICY. + */ +static __u32 fscrypt_context_to_policy(const void *xattr, size_t xattr_size, + union fscrypt_policy *policy_u) +{ + const union fscrypt_context *ctx_u = xattr; + + if (xattr_size < 1) + return CORRUPT_ENCRYPTION_POLICY; + switch (ctx_u->version) { + case 0: + return CORRUPT_ENCRYPTION_POLICY; + case 1: { + struct fscrypt_policy_v1 *policy = &policy_u->v1; + const struct fscrypt_context_v1 *ctx = &ctx_u->v1; + + if (xattr_size != sizeof(*ctx)) + return CORRUPT_ENCRYPTION_POLICY; + policy->version = ctx->version; + policy->contents_encryption_mode = + ctx->contents_encryption_mode; + policy->filenames_encryption_mode = + ctx->filenames_encryption_mode; + policy->flags = ctx->flags; + memcpy(policy->master_key_descriptor, + ctx->master_key_descriptor, + sizeof(policy->master_key_descriptor)); + return 0; + } + case 2: { + struct fscrypt_policy_v2 *policy = &policy_u->v2; + const struct fscrypt_context_v2 *ctx = &ctx_u->v2; + + if (xattr_size != sizeof(*ctx)) + return CORRUPT_ENCRYPTION_POLICY; + policy->version = ctx->version; + policy->contents_encryption_mode = + ctx->contents_encryption_mode; + policy->filenames_encryption_mode = + ctx->filenames_encryption_mode; + policy->flags = ctx->flags; + memcpy(policy->__reserved, ctx->__reserved, + sizeof(policy->__reserved)); + memcpy(policy->master_key_identifier, + ctx->master_key_identifier, + sizeof(policy->master_key_identifier)); + return 0; + } + } + return UNRECOGNIZED_ENCRYPTION_POLICY; +} + +/* + * Read an inode's encryption xattr and get/allocate its encryption policy ID, + * or alternatively use one of the special IDs NO_ENCRYPTION_POLICY, + * CORRUPT_ENCRYPTION_POLICY, or UNRECOGNIZED_ENCRYPTION_POLICY. + * + * Returns nonzero only if out of memory. + */ +static errcode_t get_encryption_policy_id(e2fsck_t ctx, ext2_ino_t ino, + __u32 *policy_id_ret) +{ + struct encrypted_file_info *info = ctx->encrypted_files; + struct rb_node **new = &info->policies.rb_node; + struct rb_node *parent = NULL; + void *xattr; + size_t xattr_size; + union fscrypt_policy policy; + __u32 policy_id; + struct policy_map_entry *entry; + errcode_t retval; + + retval = read_encryption_xattr(ctx, ino, &xattr, &xattr_size); + if (retval == EXT2_ET_NO_MEMORY) + return retval; + if (retval) { + *policy_id_ret = NO_ENCRYPTION_POLICY; + return 0; + } + + /* Translate the xattr to an fscrypt_policy, if possible. */ + policy_id = fscrypt_context_to_policy(xattr, xattr_size, &policy); + ext2fs_free_mem(&xattr); + if (policy_id != 0) + goto out; + + /* Check if the policy was already seen. */ + while (*new) { + int res; + + parent = *new; + entry = ext2fs_rb_entry(parent, struct policy_map_entry, node); + res = cmp_fscrypt_policies(ctx, &policy, &entry->policy); + if (res < 0) { + new = &parent->rb_left; + } else if (res > 0) { + new = &parent->rb_right; + } else { + /* Policy already seen. Use existing ID. */ + policy_id = entry->policy_id; + goto out; + } + } + + /* First time seeing this policy. Allocate a new policy ID. */ + retval = ext2fs_get_mem(sizeof(*entry), &entry); + if (retval) + goto out; + policy_id = info->next_policy_id++; + entry->policy_id = policy_id; + entry->policy = policy; + ext2fs_rb_link_node(&entry->node, parent, new); + ext2fs_rb_insert_color(&entry->node, &info->policies); +out: + *policy_id_ret = policy_id; + return retval; +} + +static int handle_nomem(e2fsck_t ctx, struct problem_context *pctx, + size_t size_needed) +{ + pctx->num = size_needed; + fix_problem(ctx, PR_1_ALLOCATE_ENCRYPTED_INODE_LIST, pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return 0; +} + +static int append_ino_and_policy_id(e2fsck_t ctx, struct problem_context *pctx, + ext2_ino_t ino, __u32 policy_id) +{ + struct encrypted_file_info *info = ctx->encrypted_files; + struct encrypted_file_range *range; + + /* See if we can just extend the last range. */ + if (info->file_ranges_count > 0) { + range = &info->file_ranges[info->file_ranges_count - 1]; + + if (ino <= range->last_ino) { + /* Should never get here */ + fatal_error(ctx, + "Encrypted inodes processed out of order"); + } + + if (ino == range->last_ino + 1 && + policy_id == range->policy_id) { + range->last_ino++; + return 0; + } + } + /* Nope, a new range is needed. */ + + if (info->file_ranges_count == info->file_ranges_capacity) { + /* Double the capacity by default. */ + size_t new_capacity = info->file_ranges_capacity * 2; + + /* ... but go from 0 to 128 right away. */ + if (new_capacity < 128) + new_capacity = 128; + + /* We won't need more than the filesystem's inode count. */ + if (new_capacity > ctx->fs->super->s_inodes_count) + new_capacity = ctx->fs->super->s_inodes_count; + + /* To be safe, ensure the capacity really increases. */ + if (new_capacity < info->file_ranges_capacity + 1) + new_capacity = info->file_ranges_capacity + 1; + + if (ext2fs_resize_mem(info->file_ranges_capacity * + sizeof(*range), + new_capacity * sizeof(*range), + &info->file_ranges) != 0) + return handle_nomem(ctx, pctx, + new_capacity * sizeof(*range)); + + info->file_ranges_capacity = new_capacity; + } + range = &info->file_ranges[info->file_ranges_count++]; + range->first_ino = ino; + range->last_ino = ino; + range->policy_id = policy_id; + return 0; +} + +/* + * Handle an inode that has EXT4_ENCRYPT_FL set during pass 1. Normally this + * just finds the unique ID that identifies the inode's encryption policy + * (allocating a new ID if needed), and adds the inode number and its policy ID + * to the encrypted_file_info so that it's available in pass 2. + * + * But this also handles: + * - If the inode doesn't have an encryption xattr at all, offer to clear the + * encrypt flag. + * - If the encryption xattr is clearly corrupt, tell the caller that the whole + * inode should be cleared. + * - To be future-proof: if the encryption xattr has an unrecognized version + * number, it *might* be valid, so we don't consider it invalid. But we can't + * do much with it, so give all such policies the same ID, + * UNRECOGNIZED_ENCRYPTION_POLICY. + * + * Returns -1 if the inode should be cleared, otherwise 0. + */ +int add_encrypted_file(e2fsck_t ctx, struct problem_context *pctx) +{ + struct encrypted_file_info *info = ctx->encrypted_files; + ext2_ino_t ino = pctx->ino; + __u32 policy_id; + + /* Allocate the encrypted_file_info if needed. */ + if (info == NULL) { + if (ext2fs_get_memzero(sizeof(*info), &info) != 0) + return handle_nomem(ctx, pctx, sizeof(*info)); + ctx->encrypted_files = info; + } + + /* Get a unique ID for this inode's encryption policy. */ + if (get_encryption_policy_id(ctx, ino, &policy_id) != 0) + return handle_nomem(ctx, pctx, 0 /* unknown size */); + if (policy_id == NO_ENCRYPTION_POLICY) { + if (fix_problem(ctx, PR_1_MISSING_ENCRYPTION_XATTR, pctx)) { + pctx->inode->i_flags &= ~EXT4_ENCRYPT_FL; + e2fsck_write_inode(ctx, ino, pctx->inode, "pass1"); + } + return 0; + } else if (policy_id == CORRUPT_ENCRYPTION_POLICY) { + if (fix_problem(ctx, PR_1_CORRUPT_ENCRYPTION_XATTR, pctx)) + return -1; + return 0; + } + + /* Store this ino => policy_id mapping in the encrypted_file_info. */ + return append_ino_and_policy_id(ctx, pctx, ino, policy_id); +} + +/* + * Find the ID of an inode's encryption policy, using the information saved + * earlier. + * + * If the inode is encrypted, returns the policy ID or + * UNRECOGNIZED_ENCRYPTION_POLICY. Else, returns NO_ENCRYPTION_POLICY. + */ +__u32 find_encryption_policy(e2fsck_t ctx, ext2_ino_t ino) +{ + const struct encrypted_file_info *info = ctx->encrypted_files; + size_t l, r; + + if (info == NULL) + return NO_ENCRYPTION_POLICY; + l = 0; + r = info->file_ranges_count; + while (l < r) { + size_t m = l + (r - l) / 2; + const struct encrypted_file_range *range = + &info->file_ranges[m]; + + if (ino < range->first_ino) + r = m; + else if (ino > range->last_ino) + l = m + 1; + else + return range->policy_id; + } + return NO_ENCRYPTION_POLICY; +} + +/* Destroy ctx->encrypted_files->policies */ +void destroy_encryption_policy_map(e2fsck_t ctx) +{ + struct encrypted_file_info *info = ctx->encrypted_files; + + if (info) { + struct rb_root *policies = &info->policies; + + while (!ext2fs_rb_empty_root(policies)) { + struct policy_map_entry *entry; + + entry = ext2fs_rb_entry(policies->rb_node, + struct policy_map_entry, node); + ext2fs_rb_erase(&entry->node, policies); + ext2fs_free_mem(&entry); + } + info->next_policy_id = 0; + } +} + +/* Destroy ctx->encrypted_files */ +void destroy_encrypted_file_info(e2fsck_t ctx) +{ + struct encrypted_file_info *info = ctx->encrypted_files; + + if (info) { + destroy_encryption_policy_map(ctx); + ext2fs_free_mem(&info->file_ranges); + ext2fs_free_mem(&info); + ctx->encrypted_files = NULL; + } +} diff --git a/e2fsck/extend.c b/e2fsck/extend.c new file mode 100644 index 0000000..9d17e44 --- /dev/null +++ b/e2fsck/extend.c @@ -0,0 +1,83 @@ +/* + * extend.c --- extend a file so that it has at least a specified + * number of blocks. + * + * Copyright (C) 1993, 1994, 1995 Theodore Ts'o. + * + * This file may be redistributed under the terms of the GNU Public + * License. + */ + +#include "config.h" +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <fcntl.h> +#include "../misc/nls-enable.h" + +static void usage(char *progname) +{ + fprintf(stderr, _("%s: %s filename nblocks blocksize\n"), + progname, progname); + exit(1); +} + + +int main(int argc, char **argv) +{ + char *filename; + int nblocks, blocksize; + int fd; + char *block; + errcode_t retval; + int ret; + + if (argc != 4) + usage(argv[0]); + + filename = argv[1]; + nblocks = strtoul(argv[2], 0, 0) - 1; + blocksize = strtoul(argv[3], 0, 0); + + if (nblocks < 0) { + fprintf(stderr, _("Illegal number of blocks!\n")); + exit(1); + } + + retval = ext2fs_get_memzero(blocksize, &block); + if (retval) { + fprintf(stderr, _("Couldn't allocate block buffer (size=%d)\n"), + blocksize); + exit(1); + } + + fd = open(filename, O_RDWR); + if (fd < 0) { + perror(filename); + exit(1); + } + ret = lseek(fd, nblocks*blocksize, SEEK_SET); + if (ret < 0) { + perror("lseek"); + exit(1); + } + ret = read(fd, block, blocksize); + if (ret < 0) { + perror("read"); + exit(1); + } + ret = lseek(fd, nblocks*blocksize, SEEK_SET); + if (ret < 0) { + perror("lseek #2"); + exit(1); + } + ret = write(fd, block, blocksize); + if (ret < 0) { + perror("read"); + exit(1); + } + ext2fs_free_mem(&block); + return(0); +} diff --git a/e2fsck/extents.c b/e2fsck/extents.c new file mode 100644 index 0000000..70798f3 --- /dev/null +++ b/e2fsck/extents.c @@ -0,0 +1,620 @@ +/* + * extents.c --- rebuild extent tree + * + * Copyright (C) 2014 Oracle. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License, version 2. + * %End-Header% + */ + +#include "config.h" +#include <string.h> +#include <ctype.h> +#include <errno.h> +#include "e2fsck.h" +#include "problem.h" + +#undef DEBUG +#undef DEBUG_SUMMARY +#undef DEBUG_FREE + +#define NUM_EXTENTS 341 /* about one ETB' worth of extents */ + +static errcode_t e2fsck_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino); + +/* Schedule an inode to have its extent tree rebuilt during pass 1E. */ +errcode_t e2fsck_rebuild_extents_later(e2fsck_t ctx, ext2_ino_t ino) +{ + errcode_t retval = 0; + + if (!ext2fs_has_feature_extents(ctx->fs->super) || + (ctx->options & E2F_OPT_NO) || + (ino != EXT2_ROOT_INO && ino < ctx->fs->super->s_first_ino)) + return 0; + + if (ctx->flags & E2F_FLAG_ALLOC_OK) + return e2fsck_rebuild_extents(ctx, ino); + + if (!ctx->inodes_to_rebuild) + retval = e2fsck_allocate_inode_bitmap(ctx->fs, + _("extent rebuild inode map"), + EXT2FS_BMAP64_RBTREE, + "inodes_to_rebuild", + &ctx->inodes_to_rebuild); + if (retval) + return retval; + + ext2fs_mark_inode_bitmap2(ctx->inodes_to_rebuild, ino); + return 0; +} + +/* Ask if an inode will have its extents rebuilt during pass 1E. */ +int e2fsck_ino_will_be_rebuilt(e2fsck_t ctx, ext2_ino_t ino) +{ + if (!ctx->inodes_to_rebuild) + return 0; + return ext2fs_test_inode_bitmap2(ctx->inodes_to_rebuild, ino); +} + +static errcode_t load_extents(e2fsck_t ctx, struct extent_list *list) +{ + ext2_filsys fs = ctx->fs; + ext2_extent_handle_t handle; + struct ext2fs_extent extent; + errcode_t retval; + + retval = ext2fs_extent_open(fs, list->ino, &handle); + if (retval) + return retval; + + retval = ext2fs_extent_get(handle, EXT2_EXTENT_ROOT, &extent); + if (retval) + goto out; + + do { + if (extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT) + goto next; + + /* Internal node; free it and we'll re-allocate it later */ + if (!(extent.e_flags & EXT2_EXTENT_FLAGS_LEAF)) { +#if defined(DEBUG) || defined(DEBUG_FREE) + printf("ino=%d free=%llu bf=%llu\n", list->ino, + extent.e_pblk, list->blocks_freed + 1); +#endif + list->blocks_freed++; + ext2fs_block_alloc_stats2(fs, extent.e_pblk, -1); + goto next; + } + + list->ext_read++; + /* Can we attach it to the previous extent? */ + if (list->count) { + struct ext2fs_extent *last = list->extents + + list->count - 1; + blk64_t end = last->e_len + extent.e_len; + + if (last->e_pblk + last->e_len == extent.e_pblk && + last->e_lblk + last->e_len == extent.e_lblk && + (last->e_flags & EXT2_EXTENT_FLAGS_UNINIT) == + (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) && + end < (1ULL << 32)) { + last->e_len += extent.e_len; +#ifdef DEBUG + printf("R: ino=%d len=%u\n", list->ino, + last->e_len); +#endif + goto next; + } + } + + /* Do we need to expand? */ + if (list->count == list->size) { + unsigned int new_size = (list->size + NUM_EXTENTS) * + sizeof(struct ext2fs_extent); + retval = ext2fs_resize_mem(0, new_size, &list->extents); + if (retval) + goto out; + list->size += NUM_EXTENTS; + } + + /* Add a new extent */ + memcpy(list->extents + list->count, &extent, sizeof(extent)); +#ifdef DEBUG + printf("R: ino=%d pblk=%llu lblk=%llu len=%u\n", list->ino, + extent.e_pblk, extent.e_lblk, extent.e_len); +#endif + list->count++; +next: + retval = ext2fs_extent_get(handle, EXT2_EXTENT_NEXT, &extent); + } while (retval == 0); + +out: + /* Ok if we run off the end */ + if (retval == EXT2_ET_EXTENT_NO_NEXT) + retval = 0; + ext2fs_extent_free(handle); + return retval; +} + +static int find_blocks(ext2_filsys fs, blk64_t *blocknr, e2_blkcnt_t blockcnt, + blk64_t ref_blk EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), void *priv_data) +{ + struct extent_list *list = priv_data; + + /* Internal node? */ + if (blockcnt < 0) { +#if defined(DEBUG) || defined(DEBUG_FREE) + printf("ino=%d free=%llu bf=%llu\n", list->ino, *blocknr, + list->blocks_freed + 1); +#endif + list->blocks_freed++; + ext2fs_block_alloc_stats2(fs, *blocknr, -1); + return 0; + } + + /* Can we attach it to the previous extent? */ + if (list->count) { + struct ext2fs_extent *last = list->extents + + list->count - 1; + blk64_t end = last->e_len + 1; + + if (last->e_lblk + last->e_len == (__u64) blockcnt && + last->e_pblk + last->e_len == *blocknr && + end < (1ULL << 32)) { + last->e_len++; +#ifdef DEBUG + printf("R: ino=%d len=%u\n", list->ino, last->e_len); +#endif + return 0; + } + } + + /* Do we need to expand? */ + if (list->count == list->size) { + unsigned int new_size = (list->size + NUM_EXTENTS) * + sizeof(struct ext2fs_extent); + list->retval = ext2fs_resize_mem(0, new_size, &list->extents); + if (list->retval) + return BLOCK_ABORT; + list->size += NUM_EXTENTS; + } + + /* Add a new extent */ + list->extents[list->count].e_pblk = *blocknr; + list->extents[list->count].e_lblk = blockcnt; + list->extents[list->count].e_len = 1; + list->extents[list->count].e_flags = 0; +#ifdef DEBUG + printf("R: ino=%d pblk=%llu lblk=%llu len=%u\n", list->ino, *blocknr, + blockcnt, 1); +#endif + list->count++; + + return 0; +} + +static errcode_t rewrite_extent_replay(e2fsck_t ctx, struct extent_list *list, + struct ext2_inode_large *inode) +{ + errcode_t retval; + ext2_extent_handle_t handle; + unsigned int i, ext_written; + struct ext2fs_extent *ex, extent; + blk64_t start_val, delta; + + /* Reset extent tree */ + inode->i_flags &= ~EXT4_EXTENTS_FL; + memset(inode->i_block, 0, sizeof(inode->i_block)); + + /* Make a note of freed blocks */ + quota_data_sub(ctx->qctx, inode, list->ino, + list->blocks_freed * ctx->fs->blocksize); + retval = ext2fs_iblk_sub_blocks(ctx->fs, EXT2_INODE(inode), + list->blocks_freed); + if (retval) + return retval; + + /* Now stuff extents into the file */ + retval = ext2fs_extent_open2(ctx->fs, list->ino, EXT2_INODE(inode), + &handle); + if (retval) + return retval; + + ext_written = 0; + + start_val = ext2fs_get_stat_i_blocks(ctx->fs, EXT2_INODE(inode)); + + for (i = 0, ex = list->extents; i < list->count; i++, ex++) { + if (ex->e_len == 0) + continue; + memcpy(&extent, ex, sizeof(struct ext2fs_extent)); + extent.e_flags &= EXT2_EXTENT_FLAGS_UNINIT; + if (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) { + if (extent.e_len > EXT_UNINIT_MAX_LEN) { + extent.e_len = EXT_UNINIT_MAX_LEN; + ex->e_pblk += EXT_UNINIT_MAX_LEN; + ex->e_lblk += EXT_UNINIT_MAX_LEN; + ex->e_len -= EXT_UNINIT_MAX_LEN; + ex--; + i--; + } + } else { + if (extent.e_len > EXT_INIT_MAX_LEN) { + extent.e_len = EXT_INIT_MAX_LEN; + ex->e_pblk += EXT_INIT_MAX_LEN; + ex->e_lblk += EXT_INIT_MAX_LEN; + ex->e_len -= EXT_INIT_MAX_LEN; + ex--; + i--; + } + } + +#ifdef DEBUG + printf("W: ino=%d pblk=%llu lblk=%llu len=%u\n", list->ino, + extent.e_pblk, extent.e_lblk, extent.e_len); +#endif + retval = ext2fs_extent_insert(handle, EXT2_EXTENT_INSERT_AFTER, + &extent); + if (retval) + goto err; + retval = ext2fs_extent_fix_parents(handle); + if (retval) + goto err; + ext_written++; + } + + delta = ext2fs_get_stat_i_blocks(ctx->fs, EXT2_INODE(inode)) - + start_val; + if (delta) + quota_data_add(ctx->qctx, inode, list->ino, delta << 9); + +#if defined(DEBUG) || defined(DEBUG_SUMMARY) + printf("rebuild: ino=%d extents=%d->%d\n", ino, list->ext_read, + ext_written); +#endif + e2fsck_write_inode(ctx, list->ino, EXT2_INODE(inode), + "rebuild_extents"); + +err: + ext2fs_extent_free(handle); + return retval; +} + +errcode_t e2fsck_rewrite_extent_tree(e2fsck_t ctx, struct extent_list *list) +{ + struct ext2_inode_large inode; + blk64_t blk_count; + errcode_t err; + + memset(&inode, 0, sizeof(inode)); + err = ext2fs_read_inode_full(ctx->fs, list->ino, EXT2_INODE(&inode), + sizeof(inode)); + if (err) + return err; + + /* Skip deleted inodes and inline data files */ + if (inode.i_flags & EXT4_INLINE_DATA_FL) + return 0; + + err = rewrite_extent_replay(ctx, list, &inode); + if (err) + return err; + + err = ext2fs_count_blocks(ctx->fs, list->ino, EXT2_INODE(&inode), + &blk_count); + if (err) + return err; + err = ext2fs_iblk_set(ctx->fs, EXT2_INODE(&inode), blk_count); + if (err) + return err; + return ext2fs_write_inode_full(ctx->fs, list->ino, EXT2_INODE(&inode), + sizeof(inode)); +} + +errcode_t e2fsck_read_extents(e2fsck_t ctx, struct extent_list *extents) +{ + struct ext2_inode_large inode; + errcode_t retval; + + extents->extents = NULL; + extents->count = 0; + extents->blocks_freed = 0; + extents->ext_read = 0; + extents->size = NUM_EXTENTS; + retval = ext2fs_get_array(NUM_EXTENTS, sizeof(struct ext2fs_extent), + &extents->extents); + if (retval) + return ENOMEM; + + retval = ext2fs_read_inode(ctx->fs, extents->ino, EXT2_INODE(&inode)); + if (retval) + goto err_out; + + retval = load_extents(ctx, extents); + if (!retval) + return 0; +err_out: + ext2fs_free_mem(&extents->extents); + extents->size = 0; + extents->count = 0; + return retval; +} + +static errcode_t rebuild_extent_tree(e2fsck_t ctx, struct extent_list *list, + ext2_ino_t ino) +{ + struct ext2_inode_large inode; + errcode_t retval; + + list->count = 0; + list->blocks_freed = 0; + list->ino = ino; + list->ext_read = 0; + e2fsck_read_inode_full(ctx, ino, EXT2_INODE(&inode), sizeof(inode), + "rebuild_extents"); + + /* Skip deleted inodes and inline data files */ + if (inode.i_links_count == 0 || + inode.i_flags & EXT4_INLINE_DATA_FL) + return 0; + + /* Collect lblk->pblk mappings */ + if (inode.i_flags & EXT4_EXTENTS_FL) { + retval = load_extents(ctx, list); + if (retval) + return retval; + return rewrite_extent_replay(ctx, list, &inode); + } + + retval = ext2fs_block_iterate3(ctx->fs, ino, BLOCK_FLAG_READ_ONLY, 0, + find_blocks, list); + + return retval || list->retval || + rewrite_extent_replay(ctx, list, &inode); +} + +/* Rebuild the extents immediately */ +static errcode_t e2fsck_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino) +{ + struct extent_list list = { 0 }; + errcode_t err; + + if (!ext2fs_has_feature_extents(ctx->fs->super) || + (ctx->options & E2F_OPT_NO) || + (ino != EXT2_ROOT_INO && ino < ctx->fs->super->s_first_ino)) + return 0; + + e2fsck_read_bitmaps(ctx); + err = ext2fs_get_array(NUM_EXTENTS, sizeof(struct ext2fs_extent), + &list.extents); + if (err) + return err; + list.size = NUM_EXTENTS; + err = rebuild_extent_tree(ctx, &list, ino); + ext2fs_free_mem(&list.extents); + + return err; +} + +static void rebuild_extents(e2fsck_t ctx, const char *pass_name, int pr_header) +{ + struct problem_context pctx; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct extent_list list = { 0 }; + int first = 1; + ext2_ino_t ino = 0; + errcode_t retval; + + if (!ext2fs_has_feature_extents(ctx->fs->super) || + !ext2fs_test_valid(ctx->fs) || + ctx->invalid_bitmaps) { + if (ctx->inodes_to_rebuild) + ext2fs_free_inode_bitmap(ctx->inodes_to_rebuild); + ctx->inodes_to_rebuild = NULL; + } + + if (ctx->inodes_to_rebuild == NULL) + return; + + init_resource_track(&rtrack, ctx->fs->io); + clear_problem_context(&pctx); + e2fsck_read_bitmaps(ctx); + + list.size = NUM_EXTENTS; + retval = ext2fs_get_array(sizeof(struct ext2fs_extent), + list.size, &list.extents); + if (retval) + return; + while (1) { + retval = ext2fs_find_first_set_inode_bitmap2( + ctx->inodes_to_rebuild, ino + 1, + ctx->fs->super->s_inodes_count, &ino); + if (retval) + break; + pctx.ino = ino; + if (first) { + fix_problem(ctx, pr_header, &pctx); + first = 0; + } + pctx.errcode = rebuild_extent_tree(ctx, &list, ino); + if (pctx.errcode) { + end_problem_latch(ctx, PR_LATCH_OPTIMIZE_EXT); + fix_problem(ctx, PR_1E_OPTIMIZE_EXT_ERR, &pctx); + } + if (ctx->progress && !ctx->progress_fd) + e2fsck_simple_progress(ctx, "Rebuilding extents", + 100.0 * (float) ino / + (float) ctx->fs->super->s_inodes_count, + ino); + } + end_problem_latch(ctx, PR_LATCH_OPTIMIZE_EXT); + + ext2fs_free_inode_bitmap(ctx->inodes_to_rebuild); + ctx->inodes_to_rebuild = NULL; + ext2fs_free_mem(&list.extents); + + print_resource_track(ctx, pass_name, &rtrack, ctx->fs->io); +} + +/* Scan a file to see if we should rebuild its extent tree */ +errcode_t e2fsck_check_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode *inode, + struct problem_context *pctx) +{ + struct extent_tree_info eti; + struct ext2_extent_info info, top_info; + struct ext2fs_extent extent; + ext2_extent_handle_t ehandle; + ext2_filsys fs = ctx->fs; + errcode_t retval; + + /* block map file and we want extent conversion */ + if (!(inode->i_flags & EXT4_EXTENTS_FL) && + !(inode->i_flags & EXT4_INLINE_DATA_FL) && + (ctx->options & E2F_OPT_CONVERT_BMAP)) { + return e2fsck_rebuild_extents_later(ctx, ino); + } + + if (!(inode->i_flags & EXT4_EXTENTS_FL)) + return 0; + memset(&eti, 0, sizeof(eti)); + eti.ino = ino; + + /* Otherwise, go scan the extent tree... */ + retval = ext2fs_extent_open2(fs, ino, inode, &ehandle); + if (retval) + return 0; + + retval = ext2fs_extent_get_info(ehandle, &top_info); + if (retval) + goto out; + + /* Check maximum extent depth */ + pctx->ino = ino; + pctx->blk = top_info.max_depth; + pctx->blk2 = ext2fs_max_extent_depth(ehandle); + if (pctx->blk2 < pctx->blk && + fix_problem(ctx, PR_1_EXTENT_BAD_MAX_DEPTH, pctx)) + eti.force_rebuild = 1; + + /* Can we collect extent tree level stats? */ + pctx->blk = MAX_EXTENT_DEPTH_COUNT; + if (pctx->blk2 > pctx->blk) + fix_problem(ctx, PR_1E_MAX_EXTENT_TREE_DEPTH, pctx); + + /* We need to fix tree depth problems, but the scan isn't a fix. */ + if (ctx->options & E2F_OPT_FIXES_ONLY) + goto out; + + retval = ext2fs_extent_get(ehandle, EXT2_EXTENT_ROOT, &extent); + if (retval) + goto out; + + do { + retval = ext2fs_extent_get_info(ehandle, &info); + if (retval) + break; + + /* + * If this is the first extent in an extent block that we + * haven't visited, collect stats on the block. + */ + if (info.curr_entry == 1 && + !(extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT) && + !eti.force_rebuild && + info.curr_level < MAX_EXTENT_DEPTH_COUNT) { + struct extent_tree_level *etl; + + etl = eti.ext_info + info.curr_level; + etl->num_extents += info.num_entries; + etl->max_extents += info.max_entries; + /* + * Implementation wart: Splitting extent blocks when + * appending will leave the old block with one free + * entry. Therefore unless the node is totally full, + * pretend that a non-root extent block can hold one + * fewer entry than it actually does, so that we don't + * repeatedly rebuild the extent tree. + */ + if (info.curr_level && + info.num_entries < info.max_entries) + etl->max_extents--; + } + + /* Skip to the end of a block of leaf nodes */ + if (extent.e_flags & EXT2_EXTENT_FLAGS_LEAF) { + retval = ext2fs_extent_get(ehandle, + EXT2_EXTENT_LAST_SIB, + &extent); + if (retval) + break; + } + + retval = ext2fs_extent_get(ehandle, EXT2_EXTENT_NEXT, &extent); + } while (retval == 0); +out: + ext2fs_extent_free(ehandle); + return e2fsck_should_rebuild_extents(ctx, pctx, &eti, &top_info); +} + +/* Having scanned a file's extent tree, decide if we should rebuild it */ +errcode_t e2fsck_should_rebuild_extents(e2fsck_t ctx, + struct problem_context *pctx, + struct extent_tree_info *eti, + struct ext2_extent_info *info) +{ + struct extent_tree_level *ei; + int i, j, op; + unsigned int extents_per_block; + + if (eti->force_rebuild) + goto rebuild; + + if (ctx->options & E2F_OPT_NOOPT_EXTENTS) + return 0; + + extents_per_block = (ctx->fs->blocksize - + sizeof(struct ext3_extent_header)) / + sizeof(struct ext3_extent); + + /* If the extent tree is too deep, then rebuild it. */ + if (info->max_depth > MAX_EXTENT_DEPTH_COUNT-1) { + pctx->blk = info->max_depth; + op = PR_1E_CAN_COLLAPSE_EXTENT_TREE; + goto rebuild; + } + /* + * If we can consolidate a level or shorten the tree, schedule the + * extent tree to be rebuilt. + */ + for (i = 0, ei = eti->ext_info; i < info->max_depth + 1; i++, ei++) { + if (ei->max_extents - ei->num_extents > extents_per_block) { + pctx->blk = i; + op = PR_1E_CAN_NARROW_EXTENT_TREE; + goto rebuild; + } + for (j = 0; j < i; j++) { + if (ei->num_extents < eti->ext_info[j].max_extents) { + pctx->blk = i; + op = PR_1E_CAN_COLLAPSE_EXTENT_TREE; + goto rebuild; + } + } + } + return 0; + +rebuild: + if (eti->force_rebuild || fix_problem(ctx, op, pctx)) + return e2fsck_rebuild_extents_later(ctx, eti->ino); + return 0; +} + +void e2fsck_pass1e(e2fsck_t ctx) +{ + rebuild_extents(ctx, "Pass 1E", PR_1E_PASS_HEADER); +} diff --git a/e2fsck/flushb.c b/e2fsck/flushb.c new file mode 100644 index 0000000..6100fc6 --- /dev/null +++ b/e2fsck/flushb.c @@ -0,0 +1,67 @@ +/* + * flushb.c --- This routine flushes the disk buffers for a disk + * + * Copyright 1997, 2000, by Theodore Ts'o. + * + * WARNING: use of flushb on some older 2.2 kernels on a heavily loaded + * system will corrupt filesystems. This program is not really useful + * beyond for benchmarking scripts. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <stdlib.h> +#include <fcntl.h> +#include <sys/ioctl.h> +#include <sys/mount.h> +#include "../misc/nls-enable.h" + +/* For Linux, define BLKFLSBUF if necessary */ +#if (!defined(BLKFLSBUF) && defined(__linux__)) +#define BLKFLSBUF _IO(0x12,97) /* flush buffer cache */ +#endif + +const char *progname; + +static void usage(void) +{ + fprintf(stderr, _("Usage: %s disk\n"), progname); + exit(1); +} + +int main(int argc, char **argv) +{ + int fd; + + progname = argv[0]; + if (argc != 2) + usage(); + + fd = open(argv[1], O_RDONLY, 0); + if (fd < 0) { + perror("open"); + exit(1); + } + /* + * Note: to reread the partition table, use the ioctl + * BLKRRPART instead of BLKFSLBUF. + */ +#ifdef BLKFLSBUF + if (ioctl(fd, BLKFLSBUF, 0) < 0) { + perror("ioctl BLKFLSBUF"); + exit(1); + } + return 0; +#else + fprintf(stderr, + _("BLKFLSBUF ioctl not supported! Can't flush buffers.\n")); + return 1; +#endif +} diff --git a/e2fsck/iscan.c b/e2fsck/iscan.c new file mode 100644 index 0000000..33c6a4c --- /dev/null +++ b/e2fsck/iscan.c @@ -0,0 +1,265 @@ +/* + * Test to see how quickly we can scan the inode table (not doing + * anything else) + */ + +#include "config.h" +#include <string.h> +#include <fcntl.h> +#include <ctype.h> +#include <termios.h> +#include <time.h> +#ifdef HAVE_GETOPT_H +#include <getopt.h> +#endif +#include <unistd.h> +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <sys/ioctl.h> +#ifdef HAVE_MALLOC_H +#include <malloc.h> +#endif +#include <sys/time.h> +#include <sys/resource.h> + +#if EXT2_FLAT_INCLUDES +#include "ext2_fs.h" +#include "ext2fs.h" +#include "blkid.h" +#else +#include "ext2fs/ext2_fs.h" +#include "ext2fs/ext2fs.h" +#include "blkid/blkid.h" +#endif + +#include "et/com_err.h" +#include "../version.h" + +struct resource_track { + struct timeval time_start; + struct timeval user_start; + struct timeval system_start; + void *brk_start; + unsigned long long bytes_read; + unsigned long long bytes_written; +}; + +extern int isatty(int); + +const char * program_name = "iscan"; +const char * device_name = NULL; + +int yflag = 0; +int nflag = 0; +int preen = 0; +int inode_buffer_blocks = 0; +int invalid_bitmaps = 0; + +struct resource_track global_rtrack; + +void init_resource_track(struct resource_track *track, io_channel channel) +{ +#ifdef HAVE_GETRUSAGE + struct rusage r; +#endif + io_stats io_start = 0; + + track->brk_start = sbrk(0); + gettimeofday(&track->time_start, 0); +#ifdef HAVE_GETRUSAGE +#ifdef sun + memset(&r, 0, sizeof(struct rusage)); +#endif + getrusage(RUSAGE_SELF, &r); + track->user_start = r.ru_utime; + track->system_start = r.ru_stime; +#else + track->user_start.tv_sec = track->user_start.tv_usec = 0; + track->system_start.tv_sec = track->system_start.tv_usec = 0; +#endif + track->bytes_read = 0; + track->bytes_written = 0; + if (channel && channel->manager && channel->manager->get_stats) + channel->manager->get_stats(channel, &io_start); + if (io_start) { + track->bytes_read = io_start->bytes_read; + track->bytes_written = io_start->bytes_written; + } +} + +static float timeval_subtract(struct timeval *tv1, + struct timeval *tv2) +{ + return ((tv1->tv_sec - tv2->tv_sec) + + ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000); +} + +void print_resource_track(const char *desc, + struct resource_track *track, io_channel channel) +{ +#ifdef HAVE_GETRUSAGE + struct rusage r; +#endif + struct timeval time_end; + + gettimeofday(&time_end, 0); + + if (desc) + printf("%s: ", desc); + +#define kbytes(x) (((unsigned long long)(x) + 1023) / 1024) +#ifdef HAVE_MALLINFO2 + if (1) { + struct mallinfo2 malloc_info = mallinfo2(); + + printf("Memory used: %lluk/%lluk (%lluk/%lluk), ", + kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd), + kbytes(malloc_info.uordblks), + kbytes(malloc_info.fordblks)); + } else +#elif defined HAVE_MALLINFO + /* don't use mallinfo() if over 2GB used, since it returns "int" */ + if ((char *)sbrk(0) - (char *)track->brk_start < 2LL << 30) { + struct mallinfo malloc_info = mallinfo(); + + printf("Memory used: %lluk/%lluk (%lluk/%lluk), ", + kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd), + kbytes(malloc_info.uordblks), + kbytes(malloc_info.fordblks)); + } else +#endif + printf("Memory used: %lluk, ", + kbytes(((char *)sbrk(0)) - ((char *)track->brk_start))); + +#ifdef HAVE_GETRUSAGE + getrusage(RUSAGE_SELF, &r); + + printf("time: %5.2f/%5.2f/%5.2f\n", + timeval_subtract(&time_end, &track->time_start), + timeval_subtract(&r.ru_utime, &track->user_start), + timeval_subtract(&r.ru_stime, &track->system_start)); +#else + printf("elapsed time: %6.3f\n", + timeval_subtract(&time_end, &track->time_start)); +#endif +#define mbytes(x) (((x) + 1048575) / 1048576) + if (channel && channel->manager && channel->manager->get_stats) { + io_stats delta = 0; + unsigned long long bytes_read = 0; + unsigned long long bytes_written = 0; + + if (desc) + printf("%s: ", desc); + + channel->manager->get_stats(channel, &delta); + if (delta) { + bytes_read = delta->bytes_read - track->bytes_read; + bytes_written = delta->bytes_written - + track->bytes_written; + } + printf("I/O read: %lluMB, write: %lluMB, " + "rate: %.2fMB/s\n", + mbytes(bytes_read), mbytes(bytes_written), + (double)mbytes(bytes_read + bytes_written) / + timeval_subtract(&time_end, &track->time_start)); + } +} + +static void usage(void) +{ + fprintf(stderr, + "Usage: %s [-F] [-I inode_buffer_blocks] device\n", + program_name); + exit(1); +} + +static void PRS(int argc, char *argv[]) +{ + int flush = 0; + int c; +#ifdef MTRACE + extern void *mallwatch; +#endif + errcode_t retval; + + setbuf(stdout, NULL); + setbuf(stderr, NULL); + initialize_ext2_error_table(); + + if (argc && *argv) + program_name = *argv; + while ((c = getopt (argc, argv, "FI")) != EOF) + switch (c) { + case 'F': + flush = 1; + break; + case 'I': + inode_buffer_blocks = atoi(optarg); + break; + default: + usage (); + } + device_name = argv[optind]; + if (flush) { + int fd = open(device_name, O_RDONLY, 0); + + if (fd < 0) { + com_err("open", errno, + "while opening %s for flushing", device_name); + exit(1); + } + if ((retval = ext2fs_sync_device(fd, 1))) { + com_err("ext2fs_sync_device", retval, + "while trying to flush %s", device_name); + exit(1); + } + close(fd); + } +} + +int main (int argc, char *argv[]) +{ + errcode_t retval = 0; + int exit_value = 0; + ext2_filsys fs; + ext2_ino_t ino; + __u32 num_inodes = 0; + struct ext2_inode inode; + ext2_inode_scan scan; + + PRS(argc, argv); + + retval = ext2fs_open(device_name, 0, + 0, 0, unix_io_manager, &fs); + if (retval) { + com_err(program_name, retval, "while trying to open '%s'", + device_name); + exit(1); + } + + init_resource_track(&global_rtrack, fs->io); + + retval = ext2fs_open_inode_scan(fs, inode_buffer_blocks, &scan); + if (retval) { + com_err(program_name, retval, "while opening inode scan"); + exit(1); + } + + while (1) { + retval = ext2fs_get_next_inode(scan, &ino, &inode); + if (retval) { + com_err(program_name, retval, + "while getting next inode"); + exit(1); + } + if (ino == 0) + break; + num_inodes++; + } + + print_resource_track(NULL, &global_rtrack, fs->io); + printf("%u inodes scanned.\n", num_inodes); + + exit(0); +} diff --git a/e2fsck/jfs_user.h b/e2fsck/jfs_user.h new file mode 100644 index 0000000..5928a8a --- /dev/null +++ b/e2fsck/jfs_user.h @@ -0,0 +1,321 @@ +/* + * Compatibility header file for e2fsck which should be included + * instead of linux/jfs.h + * + * Copyright (C) 2000 Stephen C. Tweedie + * + * This file may be redistributed under the terms of the + * GNU General Public License version 2 or at your discretion + * any later version. + */ +#ifndef _JFS_USER_H +#define _JFS_USER_H + +#include "config.h" + +#ifdef DEBUGFS +#include <stdio.h> +#include <stdlib.h> +#if EXT2_FLAT_INCLUDES +#include "ext2_fs.h" +#include "ext2fs.h" +#include "blkid.h" +#else +#include "ext2fs/ext2_fs.h" +#include "ext2fs/ext2fs.h" +#include "blkid/blkid.h" +#endif +#else +/* + * Pull in the definition of the e2fsck context structure + */ +#include "e2fsck.h" +#endif + +#if __STDC_VERSION__ < 199901L +# if __GNUC__ >= 2 || _MSC_VER >= 1300 +# define __func__ __FUNCTION__ +# else +# define __func__ "<unknown>" +# endif +#endif + +struct buffer_head { +#ifdef DEBUGFS + ext2_filsys b_fs; +#else + e2fsck_t b_ctx; +#endif + io_channel b_io; + int b_size; + int b_err; + unsigned int b_dirty:1; + unsigned int b_uptodate:1; + unsigned long long b_blocknr; + char b_data[4096]; +}; + +struct inode { +#ifdef DEBUGFS + ext2_filsys i_fs; +#else + e2fsck_t i_ctx; +#endif + ext2_ino_t i_ino; + struct ext2_inode i_ext2; +}; + +struct kdev_s { +#ifdef DEBUGFS + ext2_filsys k_fs; +#else + e2fsck_t k_ctx; +#endif + int k_dev; +}; + +#define K_DEV_FS 1 +#define K_DEV_JOURNAL 2 + +#define lock_buffer(bh) do {} while (0) +#define unlock_buffer(bh) do {} while (0) +#define buffer_req(bh) 1 +#define do_readahead(journal, start) do {} while (0) + +struct kmem_cache { + unsigned int object_size; +}; + +#define cond_resched() do { } while (0) + +#define __init + +/* + * Now pull in the real linux/jfs.h definitions. + */ +#include <ext2fs/kernel-jbd.h> + +/* + * We use the standard libext2fs portability tricks for inline + * functions. + */ +#ifdef NO_INLINE_FUNCS +extern struct kmem_cache *kmem_cache_create(const char *name, + unsigned int size, + unsigned int align, + unsigned int flags, + void (*ctor)(void *)); +extern void kmem_cache_destroy(struct kmem_cache *s); +extern void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags); +extern void kmem_cache_free(struct kmem_cache *s, void *objp); +extern void *kmalloc(size_t size, gfp_t flags); +extern void kfree(const void *objp); +extern size_t journal_tag_bytes(journal_t *journal); +extern __u32 __hash_32(__u32 val); +extern __u32 hash_32(__u32 val, unsigned int bits); +extern __u32 hash_64(__u64 val, unsigned int bits); +extern void *kmalloc_array(unsigned n, unsigned size, int flags); +extern __u32 jbd2_chksum(journal_t *j, __u32 crc, const void *address, + unsigned int length); +extern void jbd2_descriptor_block_csum_set(journal_t *j, + struct buffer_head *bh); +#endif + +#if (defined(E2FSCK_INCLUDE_INLINE_FUNCS) || !defined(NO_INLINE_FUNCS)) +#ifdef E2FSCK_INCLUDE_INLINE_FUNCS +#if (__STDC_VERSION__ >= 199901L) +#define _INLINE_ extern inline +#else +#define _INLINE_ inline +#endif +#else /* !E2FSCK_INCLUDE_INLINE FUNCS */ +#if (__STDC_VERSION__ >= 199901L) +#define _INLINE_ inline +#else /* not C99 */ +#ifdef __GNUC__ +#define _INLINE_ extern __inline__ +#else /* For Watcom C */ +#define _INLINE_ extern inline +#endif /* __GNUC__ */ +#endif /* __STDC_VERSION__ >= 199901L */ +#endif /* E2FSCK_INCLUDE_INLINE_FUNCS */ + +_INLINE_ struct kmem_cache * +kmem_cache_create(const char *name EXT2FS_ATTR((unused)), + unsigned int size, + unsigned int align EXT2FS_ATTR((unused)), + unsigned int flags EXT2FS_ATTR((unused)), + void (*ctor)(void *) EXT2FS_ATTR((unused))) +{ + struct kmem_cache *new_cache; + + new_cache = malloc(sizeof(*new_cache)); + if (new_cache) + new_cache->object_size = size; + return new_cache; +} + +_INLINE_ void kmem_cache_destroy(struct kmem_cache *s) +{ + free(s); +} + +_INLINE_ void *kmem_cache_alloc(struct kmem_cache *cachep, + gfp_t flags EXT2FS_ATTR((unused))) +{ + return malloc(cachep->object_size); +} + +_INLINE_ void kmem_cache_free(struct kmem_cache *s EXT2FS_ATTR((unused)), + void *objp) +{ + free(objp); +} + +_INLINE_ void *kmalloc(size_t size, gfp_t flags EXT2FS_ATTR((unused))) +{ + return malloc(size); +} + +_INLINE_ void kfree(const void *objp) +{ +#ifdef HAVE_INTPTR_T + /* + * Work around a botch in the C standard, which triggers + * compiler warnings. For better or for worse, the kernel + * uses const void * for kfree, while the C standard mandates + * the use of void *. See: https://yarchive.net/comp/const.html + */ + free((void *)(intptr_t)objp); +#else + free((void *)objp); +#endif +} + +/* generic hashing taken from the Linux kernel */ +#define GOLDEN_RATIO_32 0x61C88647 +#define GOLDEN_RATIO_64 0x61C8864680B583EBull + +_INLINE_ __u32 __hash_32(__u32 val) +{ + return val * GOLDEN_RATIO_32; +} + +_INLINE_ __u32 hash_32(__u32 val, unsigned int bits) +{ + /* High bits are more random, so use them. */ + return __hash_32(val) >> (32 - bits); +} + +_INLINE_ __u32 hash_64(__u64 val, unsigned int bits) +{ + if (sizeof(long) >= 8) { + /* 64x64-bit multiply is efficient on all 64-bit processors */ + return val * GOLDEN_RATIO_64 >> (64 - bits); + } else { + /* Hash 64 bits using only 32x32-bit multiply. */ + return hash_32((__u32)val ^ __hash_32(val >> 32), bits); + } +} + +_INLINE_ void *kmalloc_array(unsigned n, unsigned size, + int flags EXT2FS_ATTR((unused))) +{ + if (n && (~0U)/n < size) + return NULL; + return malloc(n * size); +} + +_INLINE_ __u32 jbd2_chksum(journal_t *j EXT2FS_ATTR((unused)), + __u32 crc, const void *address, + unsigned int length) +{ + return ext2fs_crc32c_le(crc, address, length); +} + +_INLINE_ void jbd2_descriptor_block_csum_set(journal_t *j, + struct buffer_head *bh) +{ + struct jbd2_journal_block_tail *tail; + __u32 csum; + + if (!jbd2_journal_has_csum_v2or3(j)) + return; + + tail = (struct jbd2_journal_block_tail *)(bh->b_data + j->j_blocksize - + sizeof(struct jbd2_journal_block_tail)); + tail->t_checksum = 0; + csum = jbd2_chksum(j, j->j_csum_seed, bh->b_data, j->j_blocksize); + tail->t_checksum = cpu_to_be32(csum); +} +#undef _INLINE_ +#endif + +/* + * Kernel compatibility functions are defined in journal.c + */ +int jbd2_journal_bmap(journal_t *journal, unsigned long block, + unsigned long long *phys); +struct buffer_head *getblk(kdev_t ctx, unsigned long long blocknr, + int blocksize); +int sync_blockdev(kdev_t kdev); +void ll_rw_block(int rw, int op_flags, int nr, struct buffer_head *bh[]); +void mark_buffer_dirty(struct buffer_head *bh); +void mark_buffer_uptodate(struct buffer_head *bh, int val); +void brelse(struct buffer_head *bh); +int buffer_uptodate(struct buffer_head *bh); +void wait_on_buffer(struct buffer_head *bh); + +/* + * Define newer 2.5 interfaces + */ +#define __getblk(dev, blocknr, blocksize) getblk(dev, blocknr, blocksize) +#define set_buffer_uptodate(bh) mark_buffer_uptodate(bh, 1) + +#ifdef DEBUGFS +#include <assert.h> +#undef J_ASSERT +#define J_ASSERT(x) assert(x) + +#define JSB_HAS_INCOMPAT_FEATURE(jsb, mask) \ + ((jsb)->s_header.h_blocktype == ext2fs_cpu_to_be32(JBD2_SUPERBLOCK_V2) && \ + ((jsb)->s_feature_incompat & ext2fs_cpu_to_be32((mask)))) +#else /* !DEBUGFS */ + +extern e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */ + +#define J_ASSERT(assert) \ + do { if (!(assert)) { \ + printf ("Assertion failure in %s() at %s line %d: " \ + "\"%s\"\n", \ + __func__, __FILE__, __LINE__, # assert); \ + fatal_error(e2fsck_global_ctx, 0); \ + } } while (0) + +#endif /* DEBUGFS */ + +#ifndef EFSBADCRC +#define EFSBADCRC EXT2_ET_BAD_CRC +#endif +#ifndef EFSCORRUPTED +#define EFSCORRUPTED EXT2_ET_FILESYSTEM_CORRUPTED +#endif + +/* recovery.c */ +extern int jbd2_journal_recover (journal_t *journal); +extern int jbd2_journal_skip_recovery (journal_t *); + +/* revoke.c */ +extern int jbd2_journal_init_revoke(journal_t *, int); +extern void jbd2_journal_destroy_revoke(journal_t *); +extern void jbd2_journal_destroy_revoke_record_cache(void); +extern void jbd2_journal_destroy_revoke_table_cache(void); +extern int jbd2_journal_init_revoke_record_cache(void); +extern int jbd2_journal_init_revoke_table_cache(void); + + +extern int jbd2_journal_set_revoke(journal_t *, unsigned long long, tid_t); +extern int jbd2_journal_test_revoke(journal_t *, unsigned long long, tid_t); +extern void jbd2_journal_clear_revoke(journal_t *); + +#endif /* _JFS_USER_H */ diff --git a/e2fsck/journal.c b/e2fsck/journal.c new file mode 100644 index 0000000..c7868d8 --- /dev/null +++ b/e2fsck/journal.c @@ -0,0 +1,1900 @@ +/* + * journal.c --- code for handling the "ext3" journal + * + * Copyright (C) 2000 Andreas Dilger + * Copyright (C) 2000 Theodore Ts'o + * + * Parts of the code are based on fs/jfs/journal.c by Stephen C. Tweedie + * Copyright (C) 1999 Red Hat Software + * + * This file may be redistributed under the terms of the + * GNU General Public License version 2 or at your discretion + * any later version. + */ + +#include "config.h" +#ifdef HAVE_SYS_MOUNT_H +#include <sys/param.h> +#include <sys/mount.h> +#define MNT_FL (MS_MGC_VAL | MS_RDONLY) +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif + +#define E2FSCK_INCLUDE_INLINE_FUNCS +#include "jfs_user.h" +#include "problem.h" +#include "uuid/uuid.h" + +static int bh_count = 0; + +/* + * Define USE_INODE_IO to use the inode_io.c / fileio.c codepaths. + * This creates a larger static binary, and a smaller binary using + * shared libraries. It's also probably slightly less CPU-efficient, + * which is why it's not on by default. But, it's a good way of + * testing the functions in inode_io.c and fileio.c. + */ +#undef USE_INODE_IO + +/* Checksumming functions */ +static int e2fsck_journal_verify_csum_type(journal_t *j, + journal_superblock_t *jsb) +{ + if (!jbd2_journal_has_csum_v2or3(j)) + return 1; + + return jsb->s_checksum_type == JBD2_CRC32C_CHKSUM; +} + +static __u32 e2fsck_journal_sb_csum(journal_superblock_t *jsb) +{ + __u32 crc, old_crc; + + old_crc = jsb->s_checksum; + jsb->s_checksum = 0; + crc = ext2fs_crc32c_le(~0, (unsigned char *)jsb, + sizeof(journal_superblock_t)); + jsb->s_checksum = old_crc; + + return crc; +} + +static int e2fsck_journal_sb_csum_verify(journal_t *j, + journal_superblock_t *jsb) +{ + __u32 provided, calculated; + + if (!jbd2_journal_has_csum_v2or3(j)) + return 1; + + provided = ext2fs_be32_to_cpu(jsb->s_checksum); + calculated = e2fsck_journal_sb_csum(jsb); + + return provided == calculated; +} + +static errcode_t e2fsck_journal_sb_csum_set(journal_t *j, + journal_superblock_t *jsb) +{ + __u32 crc; + + if (!jbd2_journal_has_csum_v2or3(j)) + return 0; + + crc = e2fsck_journal_sb_csum(jsb); + jsb->s_checksum = ext2fs_cpu_to_be32(crc); + return 0; +} + +/* Kernel compatibility functions for handling the journal. These allow us + * to use the recovery.c file virtually unchanged from the kernel, so we + * don't have to do much to keep kernel and user recovery in sync. + */ +int jbd2_journal_bmap(journal_t *journal, unsigned long block, + unsigned long long *phys) +{ +#ifdef USE_INODE_IO + *phys = block; + return 0; +#else + struct inode *inode = journal->j_inode; + errcode_t retval; + blk64_t pblk; + + if (!inode) { + *phys = block; + return 0; + } + + retval= ext2fs_bmap2(inode->i_ctx->fs, inode->i_ino, + &inode->i_ext2, NULL, 0, (blk64_t) block, + 0, &pblk); + *phys = pblk; + return -1 * ((int) retval); +#endif +} + +struct buffer_head *getblk(kdev_t kdev, unsigned long long blocknr, + int blocksize) +{ + struct buffer_head *bh; + int bufsize = sizeof(*bh) + kdev->k_ctx->fs->blocksize - + sizeof(bh->b_data); + + bh = e2fsck_allocate_memory(kdev->k_ctx, bufsize, "block buffer"); + if (!bh) + return NULL; + + if (journal_enable_debug >= 3) + bh_count++; + jfs_debug(4, "getblk for block %llu (%d bytes)(total %d)\n", + blocknr, blocksize, bh_count); + + bh->b_ctx = kdev->k_ctx; + if (kdev->k_dev == K_DEV_FS) + bh->b_io = kdev->k_ctx->fs->io; + else + bh->b_io = kdev->k_ctx->journal_io; + bh->b_size = blocksize; + bh->b_blocknr = blocknr; + + return bh; +} + +int sync_blockdev(kdev_t kdev) +{ + io_channel io; + + if (kdev->k_dev == K_DEV_FS) + io = kdev->k_ctx->fs->io; + else + io = kdev->k_ctx->journal_io; + + return io_channel_flush(io) ? -EIO : 0; +} + +void ll_rw_block(int rw, int op_flags EXT2FS_ATTR((unused)), int nr, + struct buffer_head *bhp[]) +{ + errcode_t retval; + struct buffer_head *bh; + + for (; nr > 0; --nr) { + bh = *bhp++; + if (rw == REQ_OP_READ && !bh->b_uptodate) { + jfs_debug(3, "reading block %llu/%p\n", + bh->b_blocknr, (void *) bh); + retval = io_channel_read_blk64(bh->b_io, + bh->b_blocknr, + 1, bh->b_data); + if (retval) { + com_err(bh->b_ctx->device_name, retval, + "while reading block %llu\n", + bh->b_blocknr); + bh->b_err = (int) retval; + continue; + } + bh->b_uptodate = 1; + } else if (rw == REQ_OP_WRITE && bh->b_dirty) { + jfs_debug(3, "writing block %llu/%p\n", + bh->b_blocknr, + (void *) bh); + retval = io_channel_write_blk64(bh->b_io, + bh->b_blocknr, + 1, bh->b_data); + if (retval) { + com_err(bh->b_ctx->device_name, retval, + "while writing block %llu\n", + bh->b_blocknr); + bh->b_err = (int) retval; + continue; + } + bh->b_dirty = 0; + bh->b_uptodate = 1; + } else { + jfs_debug(3, "no-op %s for block %llu\n", + rw == REQ_OP_READ ? "read" : "write", + bh->b_blocknr); + } + } +} + +void mark_buffer_dirty(struct buffer_head *bh) +{ + bh->b_dirty = 1; +} + +static void mark_buffer_clean(struct buffer_head * bh) +{ + bh->b_dirty = 0; +} + +void brelse(struct buffer_head *bh) +{ + if (bh->b_dirty) + ll_rw_block(REQ_OP_WRITE, 0, 1, &bh); + jfs_debug(3, "freeing block %llu/%p (total %d)\n", + bh->b_blocknr, (void *) bh, --bh_count); + ext2fs_free_mem(&bh); +} + +int buffer_uptodate(struct buffer_head *bh) +{ + return bh->b_uptodate; +} + +void mark_buffer_uptodate(struct buffer_head *bh, int val) +{ + bh->b_uptodate = val; +} + +void wait_on_buffer(struct buffer_head *bh) +{ + if (!bh->b_uptodate) + ll_rw_block(REQ_OP_READ, 0, 1, &bh); +} + + +static void e2fsck_clear_recover(e2fsck_t ctx, int error) +{ + ext2fs_clear_feature_journal_needs_recovery(ctx->fs->super); + + /* if we had an error doing journal recovery, we need a full fsck */ + if (error) + ctx->fs->super->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(ctx->fs); +} + +/* + * This is a helper function to check the validity of the journal. + */ +struct process_block_struct { + e2_blkcnt_t last_block; +}; + +static int process_journal_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *p; + blk64_t blk = *block_nr; + + p = (struct process_block_struct *) priv_data; + + if (!blk || blk < fs->super->s_first_data_block || + blk >= ext2fs_blocks_count(fs->super)) + return BLOCK_ABORT; + + if (blockcnt >= 0) + p->last_block = blockcnt; + return 0; +} + +static int ext4_fc_replay_scan(journal_t *j, struct buffer_head *bh, + int off, tid_t expected_tid) +{ + e2fsck_t ctx = j->j_fs_dev->k_ctx; + struct e2fsck_fc_replay_state *state; + int ret = JBD2_FC_REPLAY_CONTINUE; + struct ext4_fc_add_range ext; + struct ext4_fc_tl tl; + struct ext4_fc_tail tail; + __u8 *start, *cur, *end, *val; + struct ext4_fc_head head; + struct ext2fs_extent ext2fs_ex = {0}; + + state = &ctx->fc_replay_state; + + start = (__u8 *)bh->b_data; + end = (__u8 *)bh->b_data + j->j_blocksize - 1; + + jbd_debug(1, "Scan phase starting, expected %d", expected_tid); + if (state->fc_replay_expected_off == 0) { + memset(state, 0, sizeof(*state)); + /* Check if we can stop early */ + if (le16_to_cpu(((struct ext4_fc_tl *)start)->fc_tag) + != EXT4_FC_TAG_HEAD) { + jbd_debug(1, "Ending early!, not a head tag"); + return 0; + } + } + + if (off != state->fc_replay_expected_off) { + ret = -EFSCORRUPTED; + goto out_err; + } + + state->fc_replay_expected_off++; + for (cur = start; cur < end; cur = cur + le16_to_cpu(tl.fc_len) + sizeof(tl)) { + memcpy(&tl, cur, sizeof(tl)); + val = cur + sizeof(tl); + + jbd_debug(3, "Scan phase, tag:%s, blk %lld\n", + tag2str(le16_to_cpu(tl.fc_tag)), bh->b_blocknr); + switch (le16_to_cpu(tl.fc_tag)) { + case EXT4_FC_TAG_ADD_RANGE: + memcpy(&ext, val, sizeof(ext)); + ret = ext2fs_decode_extent(&ext2fs_ex, + (void *)&ext.fc_ex, + sizeof(ext.fc_ex)); + if (ret) + ret = JBD2_FC_REPLAY_STOP; + else + ret = JBD2_FC_REPLAY_CONTINUE; + /* fallthrough */ + case EXT4_FC_TAG_DEL_RANGE: + case EXT4_FC_TAG_LINK: + case EXT4_FC_TAG_UNLINK: + case EXT4_FC_TAG_CREAT: + case EXT4_FC_TAG_INODE: + case EXT4_FC_TAG_PAD: + state->fc_cur_tag++; + state->fc_crc = jbd2_chksum(j, state->fc_crc, cur, + sizeof(tl) + ext4_fc_tag_len(&tl)); + break; + case EXT4_FC_TAG_TAIL: + state->fc_cur_tag++; + memcpy(&tail, val, sizeof(tail)); + state->fc_crc = jbd2_chksum(j, state->fc_crc, cur, + sizeof(tl) + + offsetof(struct ext4_fc_tail, + fc_crc)); + jbd_debug(1, "tail tid %d, expected %d\n", + le32_to_cpu(tail.fc_tid), expected_tid); + if (le32_to_cpu(tail.fc_tid) == expected_tid && + le32_to_cpu(tail.fc_crc) == state->fc_crc) { + state->fc_replay_num_tags = state->fc_cur_tag; + } else { + ret = state->fc_replay_num_tags ? + JBD2_FC_REPLAY_STOP : -EFSBADCRC; + } + state->fc_crc = 0; + break; + case EXT4_FC_TAG_HEAD: + memcpy(&head, val, sizeof(head)); + if (le32_to_cpu(head.fc_features) & + ~EXT4_FC_SUPPORTED_FEATURES) { + ret = -EOPNOTSUPP; + break; + } + if (le32_to_cpu(head.fc_tid) != expected_tid) { + ret = -EINVAL; + break; + } + state->fc_cur_tag++; + state->fc_crc = jbd2_chksum(j, state->fc_crc, cur, + sizeof(tl) + ext4_fc_tag_len(&tl)); + break; + default: + ret = state->fc_replay_num_tags ? + JBD2_FC_REPLAY_STOP : -ECANCELED; + } + if (ret < 0 || ret == JBD2_FC_REPLAY_STOP) + break; + } + +out_err: + return ret; +} + +static int __errcode_to_errno(errcode_t err, const char *func, int line) +{ + if (err == 0) + return 0; + fprintf(stderr, "Error \"%s\" encountered in function %s at line %d\n", + error_message(err), func, line); + if (err <= 256) + return -err; + return -EFAULT; +} + +#define errcode_to_errno(err) __errcode_to_errno(err, __func__, __LINE__) + +#define ex_end(__ex) ((__ex)->e_lblk + (__ex)->e_len - 1) +#define ex_pend(__ex) ((__ex)->e_pblk + (__ex)->e_len - 1) + +static int make_room(struct extent_list *list, int i) +{ + int ret; + + if (list->count == list->size) { + unsigned int new_size = (list->size + 341) * + sizeof(struct ext2fs_extent); + ret = errcode_to_errno(ext2fs_resize_mem(0, new_size, &list->extents)); + if (ret) + return ret; + list->size += 341; + } + + memmove(&list->extents[i + 1], &list->extents[i], + sizeof(list->extents[0]) * (list->count - i)); + list->count++; + return 0; +} + +static int ex_compar(const void *arg1, const void *arg2) +{ + const struct ext2fs_extent *ex1 = (const struct ext2fs_extent *)arg1; + const struct ext2fs_extent *ex2 = (const struct ext2fs_extent *)arg2; + + if (ex1->e_lblk < ex2->e_lblk) + return -1; + if (ex1->e_lblk > ex2->e_lblk) + return 1; + return ex1->e_len - ex2->e_len; +} + +static int ex_len_compar(const void *arg1, const void *arg2) +{ + const struct ext2fs_extent *ex1 = (const struct ext2fs_extent *)arg1; + const struct ext2fs_extent *ex2 = (const struct ext2fs_extent *)arg2; + + if (ex1->e_len < ex2->e_len) + return 1; + + if (ex1->e_lblk > ex2->e_lblk) + return -1; + + return 0; +} + +static void ex_sort_and_merge(struct extent_list *list) +{ + unsigned int i, j; + + if (list->count < 2) + return; + + /* + * Reverse sort by length, that way we strip off all the 0 length + * extents + */ + qsort(list->extents, list->count, sizeof(struct ext2fs_extent), + ex_len_compar); + + for (i = 0; i < list->count; i++) { + if (list->extents[i].e_len == 0) { + list->count = i; + break; + } + } + + if (list->count == 0) + return; + + /* Now sort by logical offset */ + qsort(list->extents, list->count, sizeof(list->extents[0]), + ex_compar); + + /* Merge adjacent extents if they are logically and physically contiguous */ + i = 0; + while (i < list->count - 1) { + if (ex_end(&list->extents[i]) + 1 != list->extents[i + 1].e_lblk || + ex_pend(&list->extents[i]) + 1 != list->extents[i + 1].e_pblk || + (list->extents[i].e_flags & EXT2_EXTENT_FLAGS_UNINIT) != + (list->extents[i + 1].e_flags & EXT2_EXTENT_FLAGS_UNINIT)) { + i++; + continue; + } + + list->extents[i].e_len += list->extents[i + 1].e_len; + for (j = i + 1; j < list->count - 1; j++) + list->extents[j] = list->extents[j + 1]; + list->count--; + } +} + +/* must free blocks that are released */ +static int ext4_modify_extent_list(e2fsck_t ctx, struct extent_list *list, + struct ext2fs_extent *ex, int del) +{ + int ret, offset; + unsigned int i; + struct ext2fs_extent add_ex = *ex; + + /* First let's create a hole from ex->e_lblk of length ex->e_len */ + for (i = 0; i < list->count; i++) { + if (ex_end(&list->extents[i]) < add_ex.e_lblk) + continue; + + /* Case 1: No overlap */ + if (list->extents[i].e_lblk > ex_end(&add_ex)) + break; + /* + * Unmark all the blocks in bb now. All the blocks get marked + * before we exit this function. + */ + ext2fs_unmark_block_bitmap_range2(ctx->fs->block_map, + list->extents[i].e_pblk, list->extents[i].e_len); + /* Case 2: Split */ + if (list->extents[i].e_lblk < add_ex.e_lblk && + ex_end(&list->extents[i]) > ex_end(&add_ex)) { + ret = make_room(list, i + 1); + if (ret) + return ret; + list->extents[i + 1] = list->extents[i]; + offset = ex_end(&add_ex) + 1 - list->extents[i].e_lblk; + list->extents[i + 1].e_lblk += offset; + list->extents[i + 1].e_pblk += offset; + list->extents[i + 1].e_len -= offset; + list->extents[i].e_len = + add_ex.e_lblk - list->extents[i].e_lblk; + break; + } + + /* Case 3: Exact overlap */ + if (add_ex.e_lblk <= list->extents[i].e_lblk && + ex_end(&list->extents[i]) <= ex_end(&add_ex)) { + + list->extents[i].e_len = 0; + continue; + } + + /* Case 4: Partial overlap */ + if (ex_end(&list->extents[i]) > ex_end(&add_ex)) { + offset = ex_end(&add_ex) + 1 - list->extents[i].e_lblk; + list->extents[i].e_lblk += offset; + list->extents[i].e_pblk += offset; + list->extents[i].e_len -= offset; + break; + } + + if (ex_end(&add_ex) >= ex_end(&list->extents[i])) + list->extents[i].e_len = + add_ex.e_lblk > list->extents[i].e_lblk ? + add_ex.e_lblk - list->extents[i].e_lblk : 0; + } + + if (add_ex.e_len && !del) { + make_room(list, list->count); + list->extents[list->count - 1] = add_ex; + } + + ex_sort_and_merge(list); + + /* Mark all occupied blocks allocated */ + for (i = 0; i < list->count; i++) + ext2fs_mark_block_bitmap_range2(ctx->fs->block_map, + list->extents[i].e_pblk, list->extents[i].e_len); + ext2fs_mark_bb_dirty(ctx->fs); + + return 0; +} + +static int ext4_add_extent_to_list(e2fsck_t ctx, struct extent_list *list, + struct ext2fs_extent *ex) +{ + return ext4_modify_extent_list(ctx, list, ex, 0 /* add */); +} + +static int ext4_del_extent_from_list(e2fsck_t ctx, struct extent_list *list, + struct ext2fs_extent *ex) +{ + return ext4_modify_extent_list(ctx, list, ex, 1 /* delete */); +} + +static int ext4_fc_read_extents(e2fsck_t ctx, ext2_ino_t ino) +{ + struct extent_list *extent_list = &ctx->fc_replay_state.fc_extent_list; + + if (extent_list->ino == ino) + return 0; + + extent_list->ino = ino; + return errcode_to_errno(e2fsck_read_extents(ctx, extent_list)); +} + +/* + * Flush extents in replay state on disk. @ino is the inode that is going + * to be processed next. So, we hold back flushing of the extent list + * if the next inode that's going to be processed is same as the one with + * cached extents in our replay state. That allows us to gather multiple extents + * for the inode so that we can flush all of them at once and it also saves us + * from continuously growing and shrinking the extent tree. + */ +static void ext4_fc_flush_extents(e2fsck_t ctx, ext2_ino_t ino) +{ + struct extent_list *extent_list = &ctx->fc_replay_state.fc_extent_list; + + if (extent_list->ino == ino || extent_list->ino == 0) + return; + e2fsck_rewrite_extent_tree(ctx, extent_list); + ext2fs_free_mem(&extent_list->extents); + memset(extent_list, 0, sizeof(*extent_list)); +} + +/* Helper struct for dentry replay routines */ +struct dentry_info_args { + ext2_ino_t parent_ino; + ext2_ino_t ino; + int dname_len; + char *dname; +}; + +static inline int tl_to_darg(struct dentry_info_args *darg, + struct ext4_fc_tl *tl, __u8 *val) +{ + struct ext4_fc_dentry_info fcd; + + memcpy(&fcd, val, sizeof(fcd)); + + darg->parent_ino = le32_to_cpu(fcd.fc_parent_ino); + darg->ino = le32_to_cpu(fcd.fc_ino); + darg->dname_len = ext4_fc_tag_len(tl) - + sizeof(struct ext4_fc_dentry_info); + darg->dname = malloc(darg->dname_len + 1); + if (!darg->dname) + return -ENOMEM; + memcpy(darg->dname, + val + sizeof(struct ext4_fc_dentry_info), + darg->dname_len); + darg->dname[darg->dname_len] = 0; + jbd_debug(1, "%s: %s, ino %u, parent %u\n", + le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_CREAT ? "create" : + (le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_LINK ? "link" : + (le16_to_cpu(tl->fc_tag) == EXT4_FC_TAG_UNLINK ? "unlink" : + "error")), darg->dname, darg->ino, darg->parent_ino); + return 0; +} + +static int ext4_fc_handle_unlink(e2fsck_t ctx, struct ext4_fc_tl *tl, __u8 *val) +{ + struct dentry_info_args darg; + int ret; + + ret = tl_to_darg(&darg, tl, val); + if (ret) + return ret; + ext4_fc_flush_extents(ctx, darg.ino); + ret = errcode_to_errno(ext2fs_unlink(ctx->fs, darg.parent_ino, + darg.dname, darg.ino, 0)); + /* It's okay if the above call fails */ + free(darg.dname); + + return ret; +} + +static int ext4_fc_handle_link_and_create(e2fsck_t ctx, struct ext4_fc_tl *tl, __u8 *val) +{ + struct dentry_info_args darg; + ext2_filsys fs = ctx->fs; + struct ext2_inode_large inode_large; + int ret, filetype, mode; + + ret = tl_to_darg(&darg, tl, val); + if (ret) + return ret; + ext4_fc_flush_extents(ctx, 0); + ret = errcode_to_errno(ext2fs_read_inode(fs, darg.ino, + (struct ext2_inode *)&inode_large)); + if (ret) + goto out; + + mode = inode_large.i_mode; + + if (LINUX_S_ISREG(mode)) + filetype = EXT2_FT_REG_FILE; + else if (LINUX_S_ISDIR(mode)) + filetype = EXT2_FT_DIR; + else if (LINUX_S_ISCHR(mode)) + filetype = EXT2_FT_CHRDEV; + else if (LINUX_S_ISBLK(mode)) + filetype = EXT2_FT_BLKDEV; + else if (LINUX_S_ISLNK(mode)) + return EXT2_FT_SYMLINK; + else if (LINUX_S_ISFIFO(mode)) + filetype = EXT2_FT_FIFO; + else if (LINUX_S_ISSOCK(mode)) + filetype = EXT2_FT_SOCK; + else { + ret = -EINVAL; + goto out; + } + + /* + * Forcefully unlink if the same name is present and ignore the error + * if any, since this dirent might not exist + */ + ext2fs_unlink(fs, darg.parent_ino, darg.dname, darg.ino, + EXT2FS_UNLINK_FORCE); + + ret = errcode_to_errno( + ext2fs_link(fs, darg.parent_ino, darg.dname, darg.ino, + filetype)); +out: + free(darg.dname); + return ret; + +} + +/* This function fixes the i_blocks field in the replayed indoe */ +static void ext4_fc_replay_fixup_iblocks(struct ext2_inode_large *ondisk_inode, + struct ext2_inode_large *fc_inode) +{ + if (ondisk_inode->i_flags & EXT4_EXTENTS_FL) { + struct ext3_extent_header *eh; + + eh = (struct ext3_extent_header *)(&ondisk_inode->i_block[0]); + if (le16_to_cpu(eh->eh_magic) != EXT3_EXT_MAGIC) { + memset(eh, 0, sizeof(*eh)); + eh->eh_magic = cpu_to_le16(EXT3_EXT_MAGIC); + eh->eh_max = cpu_to_le16( + (sizeof(ondisk_inode->i_block) - + sizeof(struct ext3_extent_header)) / + sizeof(struct ext3_extent)); + } + } else if (ondisk_inode->i_flags & EXT4_INLINE_DATA_FL) { + memcpy(ondisk_inode->i_block, fc_inode->i_block, + sizeof(fc_inode->i_block)); + } +} + +static int ext4_fc_handle_inode(e2fsck_t ctx, __u8 *val) +{ + int ino, inode_len = EXT2_GOOD_OLD_INODE_SIZE; + struct ext2_inode_large *inode = NULL, *fc_inode = NULL; + __le32 fc_ino; + __u8 *fc_raw_inode; + errcode_t err; + blk64_t blks; + + memcpy(&fc_ino, val, sizeof(fc_ino)); + fc_raw_inode = val + sizeof(fc_ino); + ino = le32_to_cpu(fc_ino); + + if (EXT2_INODE_SIZE(ctx->fs->super) > EXT2_GOOD_OLD_INODE_SIZE) { + __u16 extra_isize = ext2fs_le16_to_cpu( + ((struct ext2_inode_large *)fc_raw_inode)->i_extra_isize); + + if ((extra_isize < (sizeof(inode->i_extra_isize) + + sizeof(inode->i_checksum_hi))) || + (extra_isize > (EXT2_INODE_SIZE(ctx->fs->super) - + EXT2_GOOD_OLD_INODE_SIZE))) { + err = EFSCORRUPTED; + goto out; + } + inode_len += extra_isize; + } + err = ext2fs_get_mem(inode_len, &inode); + if (err) + goto out; + err = ext2fs_get_mem(inode_len, &fc_inode); + if (err) + goto out; + ext4_fc_flush_extents(ctx, ino); + + err = ext2fs_read_inode_full(ctx->fs, ino, (struct ext2_inode *)inode, + inode_len); + if (err) + goto out; + memcpy(fc_inode, fc_raw_inode, inode_len); +#ifdef WORDS_BIGENDIAN + ext2fs_swap_inode_full(ctx->fs, fc_inode, fc_inode, 0, inode_len); +#endif + memcpy(inode, fc_inode, offsetof(struct ext2_inode_large, i_block)); + memcpy(&inode->i_generation, &fc_inode->i_generation, + inode_len - offsetof(struct ext2_inode_large, i_generation)); + ext4_fc_replay_fixup_iblocks(inode, fc_inode); + err = ext2fs_count_blocks(ctx->fs, ino, EXT2_INODE(inode), &blks); + if (err) + goto out; + ext2fs_iblk_set(ctx->fs, EXT2_INODE(inode), blks); + ext2fs_inode_csum_set(ctx->fs, ino, inode); + + err = ext2fs_write_inode_full(ctx->fs, ino, (struct ext2_inode *)inode, + inode_len); + if (err) + goto out; + if (inode->i_links_count) + ext2fs_mark_inode_bitmap2(ctx->fs->inode_map, ino); + else + ext2fs_unmark_inode_bitmap2(ctx->fs->inode_map, ino); + ext2fs_mark_ib_dirty(ctx->fs); + +out: + ext2fs_free_mem(&inode); + ext2fs_free_mem(&fc_inode); + return errcode_to_errno(err); +} + +/* + * Handle add extent replay tag. + */ +static int ext4_fc_handle_add_extent(e2fsck_t ctx, __u8 *val) +{ + struct ext2fs_extent extent; + struct ext4_fc_add_range add_range; + ext2_ino_t ino; + int ret = 0; + + memcpy(&add_range, val, sizeof(add_range)); + ino = le32_to_cpu(add_range.fc_ino); + ext4_fc_flush_extents(ctx, ino); + + ret = ext4_fc_read_extents(ctx, ino); + if (ret) + return ret; + memset(&extent, 0, sizeof(extent)); + ret = errcode_to_errno(ext2fs_decode_extent( + &extent, (void *)add_range.fc_ex, + sizeof(add_range.fc_ex))); + if (ret) + return ret; + return ext4_add_extent_to_list(ctx, + &ctx->fc_replay_state.fc_extent_list, &extent); +} + +/* + * Handle delete logical range replay tag. + */ +static int ext4_fc_handle_del_range(e2fsck_t ctx, __u8 *val) +{ + struct ext2fs_extent extent; + struct ext4_fc_del_range del_range; + int ret, ino; + + memcpy(&del_range, val, sizeof(del_range)); + ino = le32_to_cpu(del_range.fc_ino); + ext4_fc_flush_extents(ctx, ino); + + memset(&extent, 0, sizeof(extent)); + extent.e_lblk = le32_to_cpu(del_range.fc_lblk); + extent.e_len = le32_to_cpu(del_range.fc_len); + ret = ext4_fc_read_extents(ctx, ino); + if (ret) + return ret; + return ext4_del_extent_from_list(ctx, + &ctx->fc_replay_state.fc_extent_list, &extent); +} + +/* + * Main recovery path entry point. This function returns JBD2_FC_REPLAY_CONTINUE + * to indicate that it is expecting more fast commit blocks. It returns + * JBD2_FC_REPLAY_STOP to indicate that replay is done. + */ +static int ext4_fc_replay(journal_t *journal, struct buffer_head *bh, + enum passtype pass, int off, tid_t expected_tid) +{ + e2fsck_t ctx = journal->j_fs_dev->k_ctx; + struct e2fsck_fc_replay_state *state = &ctx->fc_replay_state; + int ret = JBD2_FC_REPLAY_CONTINUE; + struct ext4_fc_tl tl; + __u8 *start, *end, *cur, *val; + + if (pass == PASS_SCAN) { + state->fc_current_pass = PASS_SCAN; + return ext4_fc_replay_scan(journal, bh, off, expected_tid); + } + + if (state->fc_replay_num_tags == 0) + goto replay_done; + + if (state->fc_current_pass != pass) { + /* Starting replay phase */ + state->fc_current_pass = pass; + /* We will reset checksums */ + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + ret = errcode_to_errno(ext2fs_read_bitmaps(ctx->fs)); + if (ret) { + jbd_debug(1, "Error %d while reading bitmaps\n", ret); + return ret; + } + state->fc_super_state = ctx->fs->super->s_state; + /* + * Mark the file system to indicate it contains errors. That's + * because the updates performed by fast commit replay code are + * not atomic and may result in inconsistent file system if it + * crashes before the replay is complete. + */ + ctx->fs->super->s_state |= EXT2_ERROR_FS; + ctx->fs->super->s_state |= EXT4_FC_REPLAY; + ext2fs_mark_super_dirty(ctx->fs); + ext2fs_flush(ctx->fs); + } + + start = (__u8 *)bh->b_data; + end = (__u8 *)bh->b_data + journal->j_blocksize - 1; + + for (cur = start; cur < end; cur = cur + le16_to_cpu(tl.fc_len) + sizeof(tl)) { + memcpy(&tl, cur, sizeof(tl)); + val = cur + sizeof(tl); + + if (state->fc_replay_num_tags == 0) + goto replay_done; + jbd_debug(3, "Replay phase processing %s tag\n", + tag2str(le16_to_cpu(tl.fc_tag))); + state->fc_replay_num_tags--; + switch (le16_to_cpu(tl.fc_tag)) { + case EXT4_FC_TAG_CREAT: + case EXT4_FC_TAG_LINK: + ret = ext4_fc_handle_link_and_create(ctx, &tl, val); + break; + case EXT4_FC_TAG_UNLINK: + ret = ext4_fc_handle_unlink(ctx, &tl, val); + break; + case EXT4_FC_TAG_ADD_RANGE: + ret = ext4_fc_handle_add_extent(ctx, val); + break; + case EXT4_FC_TAG_DEL_RANGE: + ret = ext4_fc_handle_del_range(ctx, val); + break; + case EXT4_FC_TAG_INODE: + ret = ext4_fc_handle_inode(ctx, val); + break; + case EXT4_FC_TAG_TAIL: + ext4_fc_flush_extents(ctx, 0); + case EXT4_FC_TAG_PAD: + case EXT4_FC_TAG_HEAD: + break; + default: + ret = -ECANCELED; + break; + } + if (ret < 0) + break; + ret = JBD2_FC_REPLAY_CONTINUE; + } + return ret; +replay_done: + jbd_debug(1, "End of fast commit replay\n"); + if (state->fc_current_pass != pass) + return JBD2_FC_REPLAY_STOP; + + ext2fs_calculate_summary_stats(ctx->fs, 0 /* update bg also */); + ext2fs_write_block_bitmap(ctx->fs); + ext2fs_write_inode_bitmap(ctx->fs); + ext2fs_mark_super_dirty(ctx->fs); + ext2fs_set_gdt_csum(ctx->fs); + ctx->fs->super->s_state = state->fc_super_state; + ext2fs_flush(ctx->fs); + + return JBD2_FC_REPLAY_STOP; +} + +static errcode_t e2fsck_get_journal(e2fsck_t ctx, journal_t **ret_journal) +{ + struct process_block_struct pb; + struct ext2_super_block *sb = ctx->fs->super; + struct ext2_super_block jsuper; + struct problem_context pctx; + struct buffer_head *bh; + struct inode *j_inode = NULL; + struct kdev_s *dev_fs = NULL, *dev_journal; + const char *journal_name = 0; + journal_t *journal = NULL; + errcode_t retval = 0; + io_manager io_ptr = 0; + unsigned long long start = 0; + int ret; + int ext_journal = 0; + int tried_backup_jnl = 0; + + clear_problem_context(&pctx); + + journal = e2fsck_allocate_memory(ctx, sizeof(journal_t), "journal"); + if (!journal) { + return EXT2_ET_NO_MEMORY; + } + + dev_fs = e2fsck_allocate_memory(ctx, 2*sizeof(struct kdev_s), "kdev"); + if (!dev_fs) { + retval = EXT2_ET_NO_MEMORY; + goto errout; + } + dev_journal = dev_fs+1; + + dev_fs->k_ctx = dev_journal->k_ctx = ctx; + dev_fs->k_dev = K_DEV_FS; + dev_journal->k_dev = K_DEV_JOURNAL; + + journal->j_dev = dev_journal; + journal->j_fs_dev = dev_fs; + journal->j_inode = NULL; + journal->j_blocksize = ctx->fs->blocksize; + + if (uuid_is_null(sb->s_journal_uuid)) { + /* + * The full set of superblock sanity checks haven't + * been performed yet, so we need to do some basic + * checks here to avoid potential array overruns. + */ + if (!sb->s_journal_inum || + (sb->s_journal_inum > + (ctx->fs->group_desc_count * sb->s_inodes_per_group))) { + retval = EXT2_ET_BAD_INODE_NUM; + goto errout; + } + j_inode = e2fsck_allocate_memory(ctx, sizeof(*j_inode), + "journal inode"); + if (!j_inode) { + retval = EXT2_ET_NO_MEMORY; + goto errout; + } + + j_inode->i_ctx = ctx; + j_inode->i_ino = sb->s_journal_inum; + + if ((retval = ext2fs_read_inode(ctx->fs, + sb->s_journal_inum, + &j_inode->i_ext2))) { + try_backup_journal: + if (sb->s_jnl_backup_type != EXT3_JNL_BACKUP_BLOCKS || + tried_backup_jnl) + goto errout; + memset(&j_inode->i_ext2, 0, sizeof(struct ext2_inode)); + memcpy(&j_inode->i_ext2.i_block[0], sb->s_jnl_blocks, + EXT2_N_BLOCKS*4); + j_inode->i_ext2.i_size_high = sb->s_jnl_blocks[15]; + j_inode->i_ext2.i_size = sb->s_jnl_blocks[16]; + j_inode->i_ext2.i_links_count = 1; + j_inode->i_ext2.i_mode = LINUX_S_IFREG | 0600; + e2fsck_use_inode_shortcuts(ctx, 1); + ctx->stashed_ino = j_inode->i_ino; + ctx->stashed_inode = &j_inode->i_ext2; + tried_backup_jnl++; + } + if (!j_inode->i_ext2.i_links_count || + !LINUX_S_ISREG(j_inode->i_ext2.i_mode) || + (j_inode->i_ext2.i_flags & EXT4_ENCRYPT_FL)) { + retval = EXT2_ET_NO_JOURNAL; + goto try_backup_journal; + } + if (EXT2_I_SIZE(&j_inode->i_ext2) / journal->j_blocksize < + JBD2_MIN_JOURNAL_BLOCKS) { + retval = EXT2_ET_JOURNAL_TOO_SMALL; + goto try_backup_journal; + } + pb.last_block = -1; + retval = ext2fs_block_iterate3(ctx->fs, j_inode->i_ino, + BLOCK_FLAG_HOLE, 0, + process_journal_block, &pb); + if ((pb.last_block + 1) * ctx->fs->blocksize < + (int) EXT2_I_SIZE(&j_inode->i_ext2)) { + retval = EXT2_ET_JOURNAL_TOO_SMALL; + goto try_backup_journal; + } + if (tried_backup_jnl && !(ctx->options & E2F_OPT_READONLY)) { + retval = ext2fs_write_inode(ctx->fs, sb->s_journal_inum, + &j_inode->i_ext2); + if (retval) + goto errout; + } + + journal->j_total_len = EXT2_I_SIZE(&j_inode->i_ext2) / + journal->j_blocksize; + +#ifdef USE_INODE_IO + retval = ext2fs_inode_io_intern2(ctx->fs, sb->s_journal_inum, + &j_inode->i_ext2, + &journal_name); + if (retval) + goto errout; + + io_ptr = inode_io_manager; +#else + journal->j_inode = j_inode; + ctx->journal_io = ctx->fs->io; + if ((ret = jbd2_journal_bmap(journal, 0, &start)) != 0) { + retval = (errcode_t) (-1 * ret); + goto errout; + } +#endif + } else { + ext_journal = 1; + if (!ctx->journal_name) { + char uuid[37]; + + uuid_unparse(sb->s_journal_uuid, uuid); + ctx->journal_name = blkid_get_devname(ctx->blkid, + "UUID", uuid); + if (!ctx->journal_name) + ctx->journal_name = blkid_devno_to_devname(sb->s_journal_dev); + } + journal_name = ctx->journal_name; + + if (!journal_name) { + fix_problem(ctx, PR_0_CANT_FIND_JOURNAL, &pctx); + retval = EXT2_ET_LOAD_EXT_JOURNAL; + goto errout; + } + + jfs_debug(1, "Using journal file %s\n", journal_name); + io_ptr = unix_io_manager; + } + +#if 0 + test_io_backing_manager = io_ptr; + io_ptr = test_io_manager; +#endif +#ifndef USE_INODE_IO + if (ext_journal) +#endif + { + int flags = IO_FLAG_RW; + if (!(ctx->mount_flags & EXT2_MF_ISROOT && + ctx->mount_flags & EXT2_MF_READONLY)) + flags |= IO_FLAG_EXCLUSIVE; + if ((ctx->mount_flags & EXT2_MF_READONLY) && + (ctx->options & E2F_OPT_FORCE)) + flags &= ~IO_FLAG_EXCLUSIVE; + + + retval = io_ptr->open(journal_name, flags, + &ctx->journal_io); + } + if (retval) + goto errout; + + io_channel_set_blksize(ctx->journal_io, ctx->fs->blocksize); + + if (ext_journal) { + blk64_t maxlen; + + start = ext2fs_journal_sb_start(ctx->fs->blocksize) - 1; + bh = getblk(dev_journal, start, ctx->fs->blocksize); + if (!bh) { + retval = EXT2_ET_NO_MEMORY; + goto errout; + } + ll_rw_block(REQ_OP_READ, 0, 1, &bh); + if ((retval = bh->b_err) != 0) { + brelse(bh); + goto errout; + } + memcpy(&jsuper, start ? bh->b_data : bh->b_data + SUPERBLOCK_OFFSET, + sizeof(jsuper)); +#ifdef WORDS_BIGENDIAN + if (jsuper.s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC)) + ext2fs_swap_super(&jsuper); +#endif + if (jsuper.s_magic != EXT2_SUPER_MAGIC || + !ext2fs_has_feature_journal_dev(&jsuper)) { + fix_problem(ctx, PR_0_EXT_JOURNAL_BAD_SUPER, &pctx); + retval = EXT2_ET_LOAD_EXT_JOURNAL; + brelse(bh); + goto errout; + } + /* Make sure the journal UUID is correct */ + if (memcmp(jsuper.s_uuid, ctx->fs->super->s_journal_uuid, + sizeof(jsuper.s_uuid))) { + fix_problem(ctx, PR_0_JOURNAL_BAD_UUID, &pctx); + retval = EXT2_ET_LOAD_EXT_JOURNAL; + brelse(bh); + goto errout; + } + + /* Check the superblock checksum */ + if (ext2fs_has_feature_metadata_csum(&jsuper)) { + struct struct_ext2_filsys fsx; + struct ext2_super_block superx; + void *p; + + p = start ? bh->b_data : bh->b_data + SUPERBLOCK_OFFSET; + memcpy(&fsx, ctx->fs, sizeof(fsx)); + memcpy(&superx, ctx->fs->super, sizeof(superx)); + fsx.super = &superx; + ext2fs_set_feature_metadata_csum(fsx.super); + if (!ext2fs_superblock_csum_verify(&fsx, p) && + fix_problem(ctx, PR_0_EXT_JOURNAL_SUPER_CSUM_INVALID, + &pctx)) { + ext2fs_superblock_csum_set(&fsx, p); + mark_buffer_dirty(bh); + } + } + brelse(bh); + + maxlen = ext2fs_blocks_count(&jsuper); + journal->j_total_len = (maxlen < 1ULL << 32) ? maxlen : (1ULL << 32) - 1; + start++; + } + + if (!(bh = getblk(dev_journal, start, journal->j_blocksize))) { + retval = EXT2_ET_NO_MEMORY; + goto errout; + } + + journal->j_sb_buffer = bh; + journal->j_superblock = (journal_superblock_t *)bh->b_data; + if (ext2fs_has_feature_fast_commit(ctx->fs->super)) + journal->j_fc_replay_callback = ext4_fc_replay; + else + journal->j_fc_replay_callback = NULL; + +#ifdef USE_INODE_IO + if (j_inode) + ext2fs_free_mem(&j_inode); +#endif + + *ret_journal = journal; + e2fsck_use_inode_shortcuts(ctx, 0); + return 0; + +errout: + e2fsck_use_inode_shortcuts(ctx, 0); + if (dev_fs) + ext2fs_free_mem(&dev_fs); + if (j_inode) + ext2fs_free_mem(&j_inode); + if (journal) + ext2fs_free_mem(&journal); + return retval; +} + +static errcode_t e2fsck_journal_fix_bad_inode(e2fsck_t ctx, + struct problem_context *pctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super); + int has_journal = ext2fs_has_feature_journal(ctx->fs->super); + + if (has_journal || sb->s_journal_inum) { + /* The journal inode is bogus, remove and force full fsck */ + pctx->ino = sb->s_journal_inum; + if (fix_problem(ctx, PR_0_JOURNAL_BAD_INODE, pctx)) { + if (has_journal && sb->s_journal_inum) + printf("*** journal has been deleted ***\n\n"); + ext2fs_clear_feature_journal(sb); + sb->s_journal_inum = 0; + memset(sb->s_jnl_blocks, 0, sizeof(sb->s_jnl_blocks)); + ctx->flags |= E2F_FLAG_JOURNAL_INODE; + ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + e2fsck_clear_recover(ctx, 1); + return 0; + } + return EXT2_ET_CORRUPT_JOURNAL_SB; + } else if (recover) { + if (fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, pctx)) { + e2fsck_clear_recover(ctx, 1); + return 0; + } + return EXT2_ET_UNSUPP_FEATURE; + } + return 0; +} + +#define V1_SB_SIZE 0x0024 +static void clear_v2_journal_fields(journal_t *journal) +{ + e2fsck_t ctx = journal->j_dev->k_ctx; + struct problem_context pctx; + + clear_problem_context(&pctx); + + if (!fix_problem(ctx, PR_0_CLEAR_V2_JOURNAL, &pctx)) + return; + + ctx->flags |= E2F_FLAG_PROBLEMS_FIXED; + memset(((char *) journal->j_superblock) + V1_SB_SIZE, 0, + ctx->fs->blocksize-V1_SB_SIZE); + mark_buffer_dirty(journal->j_sb_buffer); +} + + +static errcode_t e2fsck_journal_load(journal_t *journal) +{ + e2fsck_t ctx = journal->j_dev->k_ctx; + journal_superblock_t *jsb; + struct buffer_head *jbh = journal->j_sb_buffer; + struct problem_context pctx; + + clear_problem_context(&pctx); + + ll_rw_block(REQ_OP_READ, 0, 1, &jbh); + if (jbh->b_err) { + com_err(ctx->device_name, jbh->b_err, "%s", + _("reading journal superblock\n")); + return jbh->b_err; + } + + jsb = journal->j_superblock; + /* If we don't even have JBD2_MAGIC, we probably have a wrong inode */ + if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER)) + return e2fsck_journal_fix_bad_inode(ctx, &pctx); + + switch (ntohl(jsb->s_header.h_blocktype)) { + case JBD2_SUPERBLOCK_V1: + journal->j_format_version = 1; + if (jsb->s_feature_compat || + jsb->s_feature_incompat || + jsb->s_feature_ro_compat || + jsb->s_nr_users) + clear_v2_journal_fields(journal); + break; + + case JBD2_SUPERBLOCK_V2: + journal->j_format_version = 2; + if (ntohl(jsb->s_nr_users) > 1 && + uuid_is_null(ctx->fs->super->s_journal_uuid)) + clear_v2_journal_fields(journal); + if (ntohl(jsb->s_nr_users) > 1) { + fix_problem(ctx, PR_0_JOURNAL_UNSUPP_MULTIFS, &pctx); + return EXT2_ET_JOURNAL_UNSUPP_VERSION; + } + break; + + /* + * These should never appear in a journal super block, so if + * they do, the journal is badly corrupted. + */ + case JBD2_DESCRIPTOR_BLOCK: + case JBD2_COMMIT_BLOCK: + case JBD2_REVOKE_BLOCK: + return EXT2_ET_CORRUPT_JOURNAL_SB; + + /* If we don't understand the superblock major type, but there + * is a magic number, then it is likely to be a new format we + * just don't understand, so leave it alone. */ + default: + return EXT2_ET_JOURNAL_UNSUPP_VERSION; + } + + if (JBD2_HAS_INCOMPAT_FEATURE(journal, ~JBD2_KNOWN_INCOMPAT_FEATURES)) + return EXT2_ET_UNSUPP_FEATURE; + + if (JBD2_HAS_RO_COMPAT_FEATURE(journal, ~JBD2_KNOWN_ROCOMPAT_FEATURES)) + return EXT2_ET_RO_UNSUPP_FEATURE; + + /* Checksum v1-3 are mutually exclusive features. */ + if (jbd2_has_feature_csum2(journal) && jbd2_has_feature_csum3(journal)) + return EXT2_ET_CORRUPT_JOURNAL_SB; + + if (jbd2_journal_has_csum_v2or3(journal) && + jbd2_has_feature_checksum(journal)) + return EXT2_ET_CORRUPT_JOURNAL_SB; + + if (!e2fsck_journal_verify_csum_type(journal, jsb) || + !e2fsck_journal_sb_csum_verify(journal, jsb)) + return EXT2_ET_CORRUPT_JOURNAL_SB; + + if (jbd2_journal_has_csum_v2or3(journal)) + journal->j_csum_seed = jbd2_chksum(journal, ~0, jsb->s_uuid, + sizeof(jsb->s_uuid)); + + /* We have now checked whether we know enough about the journal + * format to be able to proceed safely, so any other checks that + * fail we should attempt to recover from. */ + if (jsb->s_blocksize != htonl(journal->j_blocksize)) { + com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB, + _("%s: no valid journal superblock found\n"), + ctx->device_name); + return EXT2_ET_CORRUPT_JOURNAL_SB; + } + + if (ntohl(jsb->s_maxlen) < journal->j_total_len) + journal->j_total_len = ntohl(jsb->s_maxlen); + else if (ntohl(jsb->s_maxlen) > journal->j_total_len) { + com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB, + _("%s: journal too short\n"), + ctx->device_name); + return EXT2_ET_CORRUPT_JOURNAL_SB; + } + + journal->j_tail_sequence = ntohl(jsb->s_sequence); + journal->j_transaction_sequence = journal->j_tail_sequence; + journal->j_tail = ntohl(jsb->s_start); + journal->j_first = ntohl(jsb->s_first); + if (jbd2_has_feature_fast_commit(journal)) { + if (ntohl(jsb->s_maxlen) - jbd2_journal_get_num_fc_blks(jsb) + < JBD2_MIN_JOURNAL_BLOCKS) { + com_err(ctx->program_name, EXT2_ET_CORRUPT_JOURNAL_SB, + _("%s: incorrect fast commit blocks\n"), + ctx->device_name); + return EXT2_ET_CORRUPT_JOURNAL_SB; + } + journal->j_fc_last = ntohl(jsb->s_maxlen); + journal->j_last = journal->j_fc_last - + jbd2_journal_get_num_fc_blks(jsb); + journal->j_fc_first = journal->j_last + 1; + } else { + journal->j_last = ntohl(jsb->s_maxlen); + } + + return 0; +} + +static void e2fsck_journal_reset_super(e2fsck_t ctx, journal_superblock_t *jsb, + journal_t *journal) +{ + char *p; + union { + uuid_t uuid; + __u32 val[4]; + } u; + __u32 new_seq = 0; + int i; + + /* Leave a valid existing V1 superblock signature alone. + * Anything unrecognisable we overwrite with a new V2 + * signature. */ + + if (jsb->s_header.h_magic != htonl(JBD2_MAGIC_NUMBER) || + jsb->s_header.h_blocktype != htonl(JBD2_SUPERBLOCK_V1)) { + jsb->s_header.h_magic = htonl(JBD2_MAGIC_NUMBER); + jsb->s_header.h_blocktype = htonl(JBD2_SUPERBLOCK_V2); + } + + /* Zero out everything else beyond the superblock header */ + + p = ((char *) jsb) + sizeof(journal_header_t); + memset (p, 0, ctx->fs->blocksize-sizeof(journal_header_t)); + + jsb->s_blocksize = htonl(ctx->fs->blocksize); + jsb->s_maxlen = htonl(journal->j_total_len); + jsb->s_first = htonl(1); + + /* Initialize the journal sequence number so that there is "no" + * chance we will find old "valid" transactions in the journal. + * This avoids the need to zero the whole journal (slow to do, + * and risky when we are just recovering the filesystem). + */ + uuid_generate(u.uuid); + for (i = 0; i < 4; i ++) + new_seq ^= u.val[i]; + jsb->s_sequence = htonl(new_seq); + e2fsck_journal_sb_csum_set(journal, jsb); + + mark_buffer_dirty(journal->j_sb_buffer); + ll_rw_block(REQ_OP_WRITE, 0, 1, &journal->j_sb_buffer); +} + +static errcode_t e2fsck_journal_fix_corrupt_super(e2fsck_t ctx, + journal_t *journal, + struct problem_context *pctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super); + + if (ext2fs_has_feature_journal(sb)) { + if (fix_problem(ctx, PR_0_JOURNAL_BAD_SUPER, pctx)) { + e2fsck_journal_reset_super(ctx, journal->j_superblock, + journal); + journal->j_transaction_sequence = 1; + e2fsck_clear_recover(ctx, recover); + return 0; + } + return EXT2_ET_CORRUPT_JOURNAL_SB; + } else if (e2fsck_journal_fix_bad_inode(ctx, pctx)) + return EXT2_ET_CORRUPT_JOURNAL_SB; + + return 0; +} + +static void e2fsck_journal_release(e2fsck_t ctx, journal_t *journal, + int reset, int drop) +{ + journal_superblock_t *jsb; + + if (drop) + mark_buffer_clean(journal->j_sb_buffer); + else if (!(ctx->options & E2F_OPT_READONLY)) { + jsb = journal->j_superblock; + jsb->s_sequence = htonl(journal->j_tail_sequence); + if (reset) + jsb->s_start = 0; /* this marks the journal as empty */ + e2fsck_journal_sb_csum_set(journal, jsb); + mark_buffer_dirty(journal->j_sb_buffer); + } + brelse(journal->j_sb_buffer); + + if (ctx->journal_io) { + if (ctx->fs && ctx->fs->io != ctx->journal_io) + io_channel_close(ctx->journal_io); + ctx->journal_io = 0; + } + +#ifndef USE_INODE_IO + if (journal->j_inode) + ext2fs_free_mem(&journal->j_inode); +#endif + if (journal->j_fs_dev) + ext2fs_free_mem(&journal->j_fs_dev); + ext2fs_free_mem(&journal); +} + +/* + * This function makes sure that the superblock fields regarding the + * journal are consistent. + */ +errcode_t e2fsck_check_ext3_journal(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + journal_t *journal; + int recover = ext2fs_has_feature_journal_needs_recovery(ctx->fs->super); + struct problem_context pctx; + problem_t problem; + int reset = 0, force_fsck = 0; + errcode_t retval; + + /* If we don't have any journal features, don't do anything more */ + if (!ext2fs_has_feature_journal(sb) && + !recover && sb->s_journal_inum == 0 && sb->s_journal_dev == 0 && + uuid_is_null(sb->s_journal_uuid)) + return 0; + + clear_problem_context(&pctx); + pctx.num = sb->s_journal_inum; + + retval = e2fsck_get_journal(ctx, &journal); + if (retval) { + if ((retval == EXT2_ET_BAD_INODE_NUM) || + (retval == EXT2_ET_BAD_BLOCK_NUM) || + (retval == EXT2_ET_JOURNAL_TOO_SMALL) || + (retval == EXT2_ET_NO_JOURNAL)) + return e2fsck_journal_fix_bad_inode(ctx, &pctx); + return retval; + } + + retval = e2fsck_journal_load(journal); + if (retval) { + if ((retval == EXT2_ET_CORRUPT_JOURNAL_SB) || + ((retval == EXT2_ET_UNSUPP_FEATURE) && + (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_INCOMPAT, + &pctx))) || + ((retval == EXT2_ET_RO_UNSUPP_FEATURE) && + (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_ROCOMPAT, + &pctx))) || + ((retval == EXT2_ET_JOURNAL_UNSUPP_VERSION) && + (!fix_problem(ctx, PR_0_JOURNAL_UNSUPP_VERSION, &pctx)))) + retval = e2fsck_journal_fix_corrupt_super(ctx, journal, + &pctx); + e2fsck_journal_release(ctx, journal, 0, 1); + return retval; + } + + /* + * We want to make the flags consistent here. We will not leave with + * needs_recovery set but has_journal clear. We can't get in a loop + * with -y, -n, or -p, only if a user isn't making up their mind. + */ +no_has_journal: + if (!ext2fs_has_feature_journal(sb)) { + recover = ext2fs_has_feature_journal_needs_recovery(sb); + if (fix_problem(ctx, PR_0_JOURNAL_HAS_JOURNAL, &pctx)) { + if (recover && + !fix_problem(ctx, PR_0_JOURNAL_RECOVER_SET, &pctx)) + goto no_has_journal; + /* + * Need a full fsck if we are releasing a + * journal stored on a reserved inode. + */ + force_fsck = recover || + (sb->s_journal_inum < EXT2_FIRST_INODE(sb)); + /* Clear all of the journal fields */ + sb->s_journal_inum = 0; + sb->s_journal_dev = 0; + memset(sb->s_journal_uuid, 0, + sizeof(sb->s_journal_uuid)); + e2fsck_clear_recover(ctx, force_fsck); + } else if (!(ctx->options & E2F_OPT_READONLY)) { + ext2fs_set_feature_journal(sb); + ctx->fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + ext2fs_mark_super_dirty(ctx->fs); + } + } + + if (ext2fs_has_feature_journal(sb) && + !ext2fs_has_feature_journal_needs_recovery(sb) && + journal->j_superblock->s_start != 0) { + /* Print status information */ + fix_problem(ctx, PR_0_JOURNAL_RECOVERY_CLEAR, &pctx); + if (ctx->superblock) + problem = PR_0_JOURNAL_RUN_DEFAULT; + else + problem = PR_0_JOURNAL_RUN; + if (fix_problem(ctx, problem, &pctx)) { + ctx->options |= E2F_OPT_FORCE; + ext2fs_set_feature_journal_needs_recovery(sb); + ext2fs_mark_super_dirty(ctx->fs); + } else if (fix_problem(ctx, + PR_0_JOURNAL_RESET_JOURNAL, &pctx)) { + reset = 1; + sb->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(ctx->fs); + } + /* + * If the user answers no to the above question, we + * ignore the fact that journal apparently has data; + * accidentally replaying over valid data would be far + * worse than skipping a questionable recovery. + * + * XXX should we abort with a fatal error here? What + * will the ext3 kernel code do if a filesystem with + * !NEEDS_RECOVERY but with a non-zero + * journal->j_superblock->s_start is mounted? + */ + } + + /* + * If we don't need to do replay the journal, check to see if + * the journal's errno is set; if so, we need to mark the file + * system as being corrupt and clear the journal's s_errno. + */ + if (!ext2fs_has_feature_journal_needs_recovery(sb) && + journal->j_superblock->s_errno) { + ctx->fs->super->s_state |= EXT2_ERROR_FS; + ext2fs_mark_super_dirty(ctx->fs); + journal->j_superblock->s_errno = 0; + e2fsck_journal_sb_csum_set(journal, journal->j_superblock); + mark_buffer_dirty(journal->j_sb_buffer); + } + + e2fsck_journal_release(ctx, journal, reset, 0); + return retval; +} + +static errcode_t recover_ext3_journal(e2fsck_t ctx) +{ + struct problem_context pctx; + journal_t *journal; + errcode_t retval; + + clear_problem_context(&pctx); + + retval = jbd2_journal_init_revoke_record_cache(); + if (retval) + return retval; + + retval = jbd2_journal_init_revoke_table_cache(); + if (retval) + return retval; + + retval = e2fsck_get_journal(ctx, &journal); + if (retval) + return retval; + + retval = e2fsck_journal_load(journal); + if (retval) + goto errout; + + retval = jbd2_journal_init_revoke(journal, 1024); + if (retval) + goto errout; + + retval = -jbd2_journal_recover(journal); + if (retval) + goto errout; + + if (journal->j_failed_commit) { + pctx.ino = journal->j_failed_commit; + fix_problem(ctx, PR_0_JNL_TXN_CORRUPT, &pctx); + journal->j_superblock->s_errno = -EINVAL; + mark_buffer_dirty(journal->j_sb_buffer); + } + + journal->j_tail_sequence = journal->j_transaction_sequence; + +errout: + jbd2_journal_destroy_revoke(journal); + jbd2_journal_destroy_revoke_record_cache(); + jbd2_journal_destroy_revoke_table_cache(); + e2fsck_journal_release(ctx, journal, 1, 0); + return retval; +} + +errcode_t e2fsck_run_ext3_journal(e2fsck_t ctx) +{ + io_manager io_ptr = ctx->fs->io->manager; + int blocksize = ctx->fs->blocksize; + errcode_t retval, recover_retval; + io_stats stats = 0; + unsigned long long kbytes_written = 0; + + printf(_("%s: recovering journal\n"), ctx->device_name); + if (ctx->options & E2F_OPT_READONLY) { + printf(_("%s: won't do journal recovery while read-only\n"), + ctx->device_name); + return EXT2_ET_FILE_RO; + } + + if (ctx->fs->flags & EXT2_FLAG_DIRTY) + ext2fs_flush(ctx->fs); /* Force out any modifications */ + + recover_retval = recover_ext3_journal(ctx); + + /* + * Reload the filesystem context to get up-to-date data from disk + * because journal recovery will change the filesystem under us. + */ + if (ctx->fs->super->s_kbytes_written && + ctx->fs->io->manager->get_stats) + ctx->fs->io->manager->get_stats(ctx->fs->io, &stats); + if (stats && stats->bytes_written) + kbytes_written = stats->bytes_written >> 10; + + ext2fs_mmp_stop(ctx->fs); + ext2fs_free(ctx->fs); + retval = ext2fs_open(ctx->filesystem_name, ctx->openfs_flags, + ctx->superblock, blocksize, io_ptr, + &ctx->fs); + if (retval) { + com_err(ctx->program_name, retval, + _("while trying to re-open %s"), + ctx->device_name); + fatal_error(ctx, 0); + } + ctx->fs->priv_data = ctx; + ctx->fs->now = ctx->now; + ctx->fs->flags |= EXT2_FLAG_MASTER_SB_ONLY; + ctx->fs->super->s_kbytes_written += kbytes_written; + + /* Set the superblock flags */ + e2fsck_clear_recover(ctx, recover_retval != 0); + + /* + * Do one last sanity check, and propagate journal->s_errno to + * the EXT2_ERROR_FS flag in the fs superblock if needed. + */ + retval = e2fsck_check_ext3_journal(ctx); + return retval ? retval : recover_retval; +} + +/* + * This function will move the journal inode from a visible file in + * the filesystem directory hierarchy to the reserved inode if necessary. + */ +static const char * const journal_names[] = { + ".journal", "journal", ".journal.dat", "journal.dat", 0 }; + +void e2fsck_move_ext3_journal(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + struct ext2_inode inode; + ext2_filsys fs = ctx->fs; + ext2_ino_t ino; + errcode_t retval; + const char * const * cpp; + dgrp_t group; + int mount_flags; + + clear_problem_context(&pctx); + + /* + * If the filesystem is opened read-only, or there is no + * journal, then do nothing. + */ + if ((ctx->options & E2F_OPT_READONLY) || + (sb->s_journal_inum == 0) || + !ext2fs_has_feature_journal(sb)) + return; + + /* + * Read in the journal inode + */ + if (ext2fs_read_inode(fs, sb->s_journal_inum, &inode) != 0) + return; + + /* + * If it's necessary to backup the journal inode, do so. + */ + if ((sb->s_jnl_backup_type == 0) || + ((sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS) && + memcmp(inode.i_block, sb->s_jnl_blocks, EXT2_N_BLOCKS*4))) { + if (fix_problem(ctx, PR_0_BACKUP_JNL, &pctx)) { + memcpy(sb->s_jnl_blocks, inode.i_block, + EXT2_N_BLOCKS*4); + sb->s_jnl_blocks[15] = inode.i_size_high; + sb->s_jnl_blocks[16] = inode.i_size; + sb->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS; + ext2fs_mark_super_dirty(fs); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } + } + + /* + * If the journal is already the hidden inode, then do nothing + */ + if (sb->s_journal_inum == EXT2_JOURNAL_INO) + return; + + /* + * The journal inode had better have only one link and not be readable. + */ + if (inode.i_links_count != 1) + return; + + /* + * If the filesystem is mounted, or we can't tell whether + * or not it's mounted, do nothing. + */ + retval = ext2fs_check_if_mounted(ctx->filesystem_name, &mount_flags); + if (retval || (mount_flags & EXT2_MF_MOUNTED)) + return; + + /* + * If we can't find the name of the journal inode, then do + * nothing. + */ + for (cpp = journal_names; *cpp; cpp++) { + retval = ext2fs_lookup(fs, EXT2_ROOT_INO, *cpp, + strlen(*cpp), 0, &ino); + if ((retval == 0) && (ino == sb->s_journal_inum)) + break; + } + if (*cpp == 0) + return; + + /* We need the inode bitmap to be loaded */ + retval = ext2fs_read_bitmaps(fs); + if (retval) + return; + + pctx.str = *cpp; + if (!fix_problem(ctx, PR_0_MOVE_JOURNAL, &pctx)) + return; + + /* + * OK, we've done all the checks, let's actually move the + * journal inode. Errors at this point mean we need to force + * an ext2 filesystem check. + */ + if ((retval = ext2fs_unlink(fs, EXT2_ROOT_INO, *cpp, ino, 0)) != 0) + goto err_out; + if ((retval = ext2fs_write_inode(fs, EXT2_JOURNAL_INO, &inode)) != 0) + goto err_out; + sb->s_journal_inum = EXT2_JOURNAL_INO; + ext2fs_mark_super_dirty(fs); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + inode.i_links_count = 0; + inode.i_dtime = ctx->now; + if ((retval = ext2fs_write_inode(fs, ino, &inode)) != 0) + goto err_out; + + group = ext2fs_group_of_ino(fs, ino); + ext2fs_unmark_inode_bitmap2(fs->inode_map, ino); + ext2fs_mark_ib_dirty(fs); + ext2fs_bg_free_inodes_count_set(fs, group, ext2fs_bg_free_inodes_count(fs, group) + 1); + ext2fs_group_desc_csum_set(fs, group); + fs->super->s_free_inodes_count++; + return; + +err_out: + pctx.errcode = retval; + fix_problem(ctx, PR_0_ERR_MOVE_JOURNAL, &pctx); + fs->super->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(fs); + return; +} + +/* + * This function makes sure the superblock hint for the external + * journal is correct. + */ +int e2fsck_fix_ext3_journal_hint(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + char uuid[37], *journal_name; + struct stat st; + + if (!ext2fs_has_feature_journal(sb) || + uuid_is_null(sb->s_journal_uuid)) + return 0; + + uuid_unparse(sb->s_journal_uuid, uuid); + journal_name = blkid_get_devname(ctx->blkid, "UUID", uuid); + if (!journal_name) + return 0; + + if (stat(journal_name, &st) < 0) { + free(journal_name); + return 0; + } + + if (st.st_rdev != sb->s_journal_dev) { + clear_problem_context(&pctx); + pctx.num = st.st_rdev; + if (fix_problem(ctx, PR_0_EXTERNAL_JOURNAL_HINT, &pctx)) { + sb->s_journal_dev = st.st_rdev; + ext2fs_mark_super_dirty(ctx->fs); + } + } + + free(journal_name); + return 0; +} diff --git a/e2fsck/logfile.c b/e2fsck/logfile.c new file mode 100644 index 0000000..9d79eed --- /dev/null +++ b/e2fsck/logfile.c @@ -0,0 +1,411 @@ +/* + * logfile.c --- set up e2fsck log files + * + * Copyright 1996, 1997 by Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +#include "e2fsck.h" +#include <pwd.h> + +extern e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */ + +struct string { + char *s; + int len; + int end; +}; + +static void alloc_string(struct string *s, int len) +{ + s->s = malloc(len); +/* e2fsck_allocate_memory(ctx, len, "logfile name"); */ + s->len = s->s ? len : 0; + s->end = 0; +} + +static void append_string(struct string *s, const char *a, int len) +{ + int needlen; + + if (!len) + len = strlen(a); + + needlen = s->end + len + 1; + if (needlen > s->len) { + char *n; + + if (s->len * 2 > needlen) + needlen = s->len * 2; + n = realloc(s->s, needlen); + + if (n) { + s->s = n; + s->len = needlen; + } else { + /* Don't append if we ran out of memory */ + return; + } + } + memcpy(s->s + s->end, a, len); + s->end += len; + s->s[s->end] = 0; +} + +#define FLAG_UTC 0x0001 + +static void expand_percent_expression(e2fsck_t ctx, char ch, + struct string *s, int *flags) +{ + struct tm *tm = NULL, tm_struct; + struct passwd *pw = NULL, pw_struct; + char *cp; + char buf[256]; + + if ((ch == 'D') || (ch == 'd') || (ch == 'm') || (ch == 'y') || + (ch == 'Y') || + (ch == 'T') || (ch == 'H') || (ch == 'M') || (ch == 'S')) { + tzset(); + tm = (*flags & FLAG_UTC) ? gmtime_r(&ctx->now, &tm_struct) : + localtime_r(&ctx->now, &tm_struct); + } + + switch (ch) { + case '%': + append_string(s, "%", 1); + return; + case 'd': + sprintf(buf, "%02d", tm->tm_mday); + break; + case 'D': + sprintf(buf, "%d%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1, + tm->tm_mday); + break; + case 'h': +#ifdef TEST_PROGRAM + strcpy(buf, "server"); +#else + buf[0] = 0; + gethostname(buf, sizeof(buf)); + buf[sizeof(buf)-1] = 0; +#endif + break; + case 'H': + sprintf(buf, "%02d", tm->tm_hour); + break; + case 'm': + sprintf(buf, "%02d", tm->tm_mon + 1); + break; + case 'M': + sprintf(buf, "%02d", tm->tm_min); + break; + case 'N': /* block device name */ + cp = strrchr(ctx->filesystem_name, '/'); + if (cp) + cp++; + else + cp = ctx->filesystem_name; + append_string(s, cp, 0); + return; + case 'p': + sprintf(buf, "%lu", (unsigned long) getpid()); + break; + case 's': + sprintf(buf, "%lu", (unsigned long) ctx->now); + break; + case 'S': + sprintf(buf, "%02d", tm->tm_sec); + break; + case 'T': + sprintf(buf, "%02d%02d%02d", tm->tm_hour, tm->tm_min, + tm->tm_sec); + break; + case 'u': +#ifdef TEST_PROGRAM + strcpy(buf, "tytso"); + break; +#else +#ifdef HAVE_GETPWUID_R + getpwuid_r(getuid(), &pw_struct, buf, sizeof(buf), &pw); +#else + pw = getpwuid(getuid()); +#endif + if (pw) + append_string(s, pw->pw_name, 0); + return; +#endif + case 'U': + *flags |= FLAG_UTC; + return; + case 'y': + sprintf(buf, "%02d", tm->tm_year % 100); + break; + case 'Y': + sprintf(buf, "%d", tm->tm_year + 1900); + break; + default: + sprintf(buf, "%%%c", ch); + break; + } + append_string(s, buf, 0); +} + +static void expand_logfn(e2fsck_t ctx, const char *log_fn, struct string *s) +{ + const char *cp; + int i; + int flags = 0; + + alloc_string(s, 100); + for (cp = log_fn; *cp; cp++) { + if (cp[0] == '%') { + cp++; + expand_percent_expression(ctx, *cp, s, &flags); + continue; + } + for (i = 0; cp[i]; i++) + if (cp[i] == '%') + break; + append_string(s, cp, i); + cp += i-1; + } +} + +static int outbufsize; +static void *outbuf; + +static int do_read(int fd) +{ + int c; + char *n; + char buffer[4096]; + + c = read(fd, buffer, sizeof(buffer)-1); + if (c <= 0) + return c; + + n = realloc(outbuf, outbufsize + c); + if (n) { + outbuf = n; + memcpy(((char *)outbuf)+outbufsize, buffer, c); + outbufsize += c; + } + return c; +} + +/* + * Fork a child process to save the output of the logfile until the + * appropriate file system is mounted read/write. + */ +static FILE *save_output(const char *s0, const char *s1, const char *s2) +{ + int c, fd, fds[2]; + char *cp; + pid_t pid; + FILE *ret; + + if (s0 && *s0 == 0) + s0 = 0; + if (s1 && *s1 == 0) + s1 = 0; + if (s2 && *s2 == 0) + s2 = 0; + + /* At least one potential output file name is valid */ + if (!s0 && !s1 && !s2) + return NULL; + if (pipe(fds) < 0) { + perror("pipe"); + exit(1); + } + + pid = fork(); + if (pid < 0) { + perror("fork"); + exit(1); + } + + if (pid == 0) { + if (e2fsck_global_ctx && e2fsck_global_ctx->progress_fd) + close(e2fsck_global_ctx->progress_fd); + if (daemon(0, 0) < 0) { + perror("daemon"); + exit(1); + } + /* + * Grab the output from our parent + */ + close(fds[1]); + while (do_read(fds[0]) > 0) + ; + close(fds[0]); + + /* OK, now let's try to open the output file */ + fd = -1; + while (1) { + if (fd < 0 && s0) + fd = open(s0, O_WRONLY|O_CREAT|O_TRUNC, 0644); + if (fd < 0 && s1) + fd = open(s1, O_WRONLY|O_CREAT|O_TRUNC, 0644); + if (fd < 0 && s2) + fd = open(s2, O_WRONLY|O_CREAT|O_TRUNC, 0644); + if (fd >= 0) + break; + sleep(1); + } + + cp = outbuf; + while (outbufsize > 0) { + c = write(fd, cp, outbufsize); + if (c < 0) { + if ((errno == EAGAIN) || (errno == EINTR)) + continue; + break; + } + outbufsize -= c; + cp += c; + } + exit(0); + } + + close(fds[0]); + ret = fdopen(fds[1], "w"); + if (!ret) + close(fds[1]); + return ret; +} + +#ifndef TEST_PROGRAM +static FILE *set_up_log_file(e2fsck_t ctx, const char *key, const char *fn) +{ + FILE *f = NULL; + struct string s, s1, s2; + char *s0 = 0, *log_dir = 0, *log_fn = 0; + int log_dir_wait = 0; + + s.s = s1.s = s2.s = 0; + + profile_get_boolean(ctx->profile, "options", "log_dir_wait", 0, 0, + &log_dir_wait); + if (fn) + log_fn = string_copy(ctx, fn, 0); + else + profile_get_string(ctx->profile, "options", key, + 0, 0, &log_fn); + profile_get_string(ctx->profile, "options", "log_dir", 0, 0, &log_dir); + + if (!log_fn || !log_fn[0]) + goto out; + + expand_logfn(ctx, log_fn, &s); + if ((log_fn[0] == '/') || !log_dir || !log_dir[0]) + s0 = s.s; + + if (log_dir && log_dir[0]) { + alloc_string(&s1, strlen(log_dir) + strlen(s.s) + 2); + append_string(&s1, log_dir, 0); + append_string(&s1, "/", 1); + append_string(&s1, s.s, 0); + } + + free(log_dir); + profile_get_string(ctx->profile, "options", "log_dir_fallback", 0, 0, + &log_dir); + if (log_dir && log_dir[0]) { + alloc_string(&s2, strlen(log_dir) + strlen(s.s) + 2); + append_string(&s2, log_dir, 0); + append_string(&s2, "/", 1); + append_string(&s2, s.s, 0); + printf("%s\n", s2.s); + } + + if (s0) + f = fopen(s0, "w"); + if (!f && s1.s) + f = fopen(s1.s, "w"); + if (!f && s2.s) + f = fopen(s2.s, "w"); + if (!f && log_dir_wait) + f = save_output(s0, s1.s, s2.s); + +out: + free(s.s); + free(s1.s); + free(s2.s); + free(log_fn); + free(log_dir); + return f; +} + +void set_up_logging(e2fsck_t ctx) +{ + ctx->logf = set_up_log_file(ctx, "log_filename", ctx->log_fn); + ctx->problem_logf = set_up_log_file(ctx, "problem_log_filename", + ctx->problem_log_fn); +} +#else +void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size, + const char *description) +{ + void *ret; + char buf[256]; + + ret = malloc(size); + if (!ret) { + sprintf(buf, "Can't allocate %s\n", description); + exit(1); + } + memset(ret, 0, size); + return ret; +} + +errcode_t e2fsck_allocate_context(e2fsck_t *ret) +{ + e2fsck_t context; + errcode_t retval; + char *time_env; + + context = malloc(sizeof(struct e2fsck_struct)); + if (!context) + return ENOMEM; + + memset(context, 0, sizeof(struct e2fsck_struct)); + + context->now = 1332006474; + + context->filesystem_name = "/dev/sda3"; + context->device_name = "fslabel"; + + *ret = context; + return 0; +} + +int main(int argc, char **argv) +{ + e2fsck_t ctx; + struct string s; + + putenv("TZ=EST+5:00"); + e2fsck_allocate_context(&ctx); + expand_logfn(ctx, "e2fsck-%N.%h.%u.%D-%T", &s); + printf("%s\n", s.s); + free(s.s); + expand_logfn(ctx, "e2fsck-%N.%h.%u.%Y%m%d-%H%M%S", &s); + printf("%s\n", s.s); + free(s.s); + + return 0; +} +#endif diff --git a/e2fsck/message.c b/e2fsck/message.c new file mode 100644 index 0000000..ba38038 --- /dev/null +++ b/e2fsck/message.c @@ -0,0 +1,556 @@ +/* + * message.c --- print e2fsck messages (with compression) + * + * Copyright 1996, 1997 by Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * print_e2fsck_message() prints a message to the user, using + * compression techniques and expansions of abbreviations. + * + * The following % expansions are supported: + * + * %b <blk> block number + * %B <blkcount> interpret blkcount as blkcount + * %c <blk2> block number + * %Di <dirent>->ino inode number + * %Dn <dirent>->name string + * %Dr <dirent>->rec_len + * %Dl <dirent>->name_len + * %Dt <dirent>->filetype + * %d <dir> inode number + * %g <group> integer + * %i <ino> inode number + * %Is <inode> -> i_size + * %IS <inode> -> i_extra_isize + * %Ib <inode> -> i_blocks + * %Il <inode> -> i_links_count + * %Im <inode> -> i_mode + * %IM <inode> -> i_mtime + * %IF <inode> -> i_faddr + * %If <inode> -> i_file_acl + * %Id <inode> -> i_size_high + * %Iu <inode> -> i_uid + * %Ig <inode> -> i_gid + * %It <inode type> + * %j <ino2> inode number + * %m <com_err error message> + * %N <num> + * %p ext2fs_get_pathname of directory <ino> + * %P ext2fs_get_pathname of <dirent>->ino with <ino2> as + * the containing directory. (If dirent is NULL + * then return the pathname of directory <ino2>) + * %q ext2fs_get_pathname of directory <dir> + * %Q ext2fs_get_pathname of directory <ino> with <dir> as + * the containing directory. + * %r <blkcount> interpret blkcount as refcount + * %s <str> miscellaneous string + * %t time (in <num>) + * %T current time + * %U quota type (in <num>) + * %S backup superblock + * %X <num> hexadecimal format + * + * The following '@' expansions are supported: + * + * @a extended attribute + * @A error allocating + * @b block + * @B bitmap + * @c compress + * @C conflicts with some other fs block + * @D deleted + * @d directory + * @e entry + * @E Entry '%Dn' in %p (%i) + * @f filesystem + * @F for @i %i (%Q) is + * @g group + * @h HTREE directory inode + * @i inode + * @I illegal + * @j journal + * @l lost+found + * @L is a link + * @m multiply-claimed + * @n invalid + * @o orphaned + * @p problem in + * @q quota + * @r root inode + * @s should be + * @S superblock + * @u unattached + * @v device + * @x extent + * @z zero-length + */ + +#include "config.h" +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <ctype.h> +#include <termios.h> +#include "support/quotaio.h" + +#include "e2fsck.h" +#include "problem.h" + +#ifdef __GNUC__ +#define _INLINE_ __inline__ +#else +#define _INLINE_ +#endif + +/* + * This structure defines the abbreviations used by the text strings + * below. The first character in the string is the index letter. An + * abbreviation of the form '@<i>' is expanded by looking up the index + * letter <i> in the table below. + */ +static const char *abbrevs[] = { + N_("aextended attribute"), + N_("Aerror allocating"), + N_("bblock"), + N_("Bbitmap"), + N_("ccompress"), + N_("Cconflicts with some other fs @b"), + N_("ddirectory"), + N_("Ddeleted"), + N_("eentry"), + N_("E@e '%Dn' in %p (%i)"), + N_("ffilesystem"), + N_("Ffor @i %i (%Q) is"), + N_("ggroup"), + N_("hHTREE @d @i"), + N_("iinode"), + N_("Iillegal"), + N_("jjournal"), + N_("llost+found"), + N_("Lis a link"), + N_("mmultiply-claimed"), + N_("ninvalid"), + N_("oorphaned"), + N_("pproblem in"), + N_("qquota"), + N_("rroot @i"), + N_("sshould be"), + N_("Ssuper@b"), + N_("uunattached"), + N_("vdevice"), + N_("xextent"), + N_("zzero-length"), + "@@", + 0 + }; + +/* + * Give more user friendly names to the "special" inodes. + */ +#define num_special_inodes 11 +static const char *special_inode_name[] = +{ + N_("<The NULL inode>"), /* 0 */ + N_("<The bad blocks inode>"), /* 1 */ + "/", /* 2 */ + N_("<The user quota inode>"), /* 3 */ + N_("<The group quota inode>"), /* 4 */ + N_("<The boot loader inode>"), /* 5 */ + N_("<The undelete directory inode>"), /* 6 */ + N_("<The group descriptor inode>"), /* 7 */ + N_("<The journal inode>"), /* 8 */ + N_("<Reserved inode 9>"), /* 9 */ + N_("<Reserved inode 10>"), /* 10 */ +}; + +/* + * This function does "safe" printing. It will convert non-printable + * ASCII characters using '^' and M- notation. + */ +static void safe_print(FILE *f, const char *cp, int len) +{ + unsigned char ch; + + if (len < 0) + len = strlen(cp); + + while (len--) { + ch = *cp++; + if (ch > 128) { + fputs("M-", f); + ch -= 128; + } + if ((ch < 32) || (ch == 0x7f)) { + fputc('^', f); + ch ^= 0x40; /* ^@, ^A, ^B; ^? for DEL */ + } + fputc(ch, f); + } +} + + +/* + * This function prints a pathname, using the ext2fs_get_pathname + * function + */ +static void print_pathname(FILE *f, ext2_filsys fs, ext2_ino_t dir, + ext2_ino_t ino) +{ + errcode_t retval = 0; + char *path; + + if (!dir && (ino < num_special_inodes)) { + fputs(_(special_inode_name[ino]), f); + return; + } + + if (fs) + retval = ext2fs_get_pathname(fs, dir, ino, &path); + if (!fs || retval) + fputs("???", f); + else { + safe_print(f, path, -1); + ext2fs_free_mem(&path); + } +} + +static void print_time(FILE *f, time_t t) +{ + const char * time_str; + static int do_gmt = -1; + +#ifdef __dietlibc__ + /* The diet libc doesn't respect the TZ environment variable */ + if (do_gmt == -1) { + time_str = getenv("TZ"); + if (!time_str) + time_str = ""; + do_gmt = !strcmp(time_str, "GMT") || + !strcmp(time_str, "GMT0"); + } +#endif + time_str = asctime((do_gmt > 0) ? gmtime(&t) : localtime(&t)); + fprintf(f, "%.24s", time_str); +} + +/* + * This function handles the '@' expansion. We allow recursive + * expansion; an @ expression can contain further '@' and '%' + * expressions. + */ +static _INLINE_ void expand_at_expression(FILE *f, e2fsck_t ctx, char ch, + struct problem_context *pctx, + int *first, int recurse) +{ + const char **cpp, *str; + + /* Search for the abbreviation */ + for (cpp = abbrevs; *cpp; cpp++) { + if (ch == *cpp[0]) + break; + } + if (*cpp && recurse < 10) { + str = _(*cpp) + 1; + if (*first && islower(*str)) { + *first = 0; + fputc(toupper(*str++), f); + } + print_e2fsck_message(f, ctx, str, pctx, *first, recurse+1); + } else + fprintf(f, "@%c", ch); +} + +/* + * This function expands '%IX' expressions + */ +static _INLINE_ void expand_inode_expression(FILE *f, ext2_filsys fs, char ch, + struct problem_context *ctx) +{ + struct ext2_inode *inode; + struct ext2_inode_large *large_inode; + + if (!ctx || !ctx->inode) + goto no_inode; + + inode = ctx->inode; + large_inode = (struct ext2_inode_large *) inode; + + switch (ch) { + case 's': + fprintf(f, "%llu", (unsigned long long) EXT2_I_SIZE(inode)); + break; + case 'S': + fprintf(f, "%u", large_inode->i_extra_isize); + break; + case 'b': + if (ext2fs_has_feature_huge_file(fs->super)) + fprintf(f, "%llu", inode->i_blocks + + (((long long) inode->osd2.linux2.l_i_blocks_hi) + << 32)); + else + fprintf(f, "%u", inode->i_blocks); + break; + case 'l': + fprintf(f, "%d", inode->i_links_count); + break; + case 'm': + fprintf(f, "0%o", inode->i_mode); + break; + case 'M': + print_time(f, inode->i_mtime); + break; + case 'F': + fprintf(f, "%u", inode->i_faddr); + break; + case 'f': + fprintf(f, "%llu", + (unsigned long long) ext2fs_file_acl_block(fs, inode)); + break; + case 'd': + fprintf(f, "%u", (LINUX_S_ISDIR(inode->i_mode) ? + inode->i_size_high : 0)); + break; + case 'u': + fprintf(f, "%d", inode_uid(*inode)); + break; + case 'g': + fprintf(f, "%d", inode_gid(*inode)); + break; + case 't': + if (LINUX_S_ISREG(inode->i_mode)) + fputs(_("regular file"), f); + else if (LINUX_S_ISDIR(inode->i_mode)) + fputs(_("directory"), f); + else if (LINUX_S_ISCHR(inode->i_mode)) + fputs(_("character device"), f); + else if (LINUX_S_ISBLK(inode->i_mode)) + fputs(_("block device"), f); + else if (LINUX_S_ISFIFO(inode->i_mode)) + fputs(_("named pipe"), f); + else if (LINUX_S_ISLNK(inode->i_mode)) + fputs(_("symbolic link"), f); + else if (LINUX_S_ISSOCK(inode->i_mode)) + fputs(_("socket"), f); + else + fprintf(f, _("unknown file type with mode 0%o"), + inode->i_mode); + break; + default: + no_inode: + fprintf(f, "%%I%c", ch); + break; + } +} + +/* + * This function expands '%dX' expressions + */ +static _INLINE_ void expand_dirent_expression(FILE *f, ext2_filsys fs, char ch, + struct problem_context *ctx) +{ + struct ext2_dir_entry *dirent; + unsigned int rec_len, len; + + if (!ctx || !ctx->dirent) + goto no_dirent; + + dirent = ctx->dirent; + + switch (ch) { + case 'i': + fprintf(f, "%u", dirent->inode); + break; + case 'n': + len = ext2fs_dirent_name_len(dirent); + if ((ext2fs_get_rec_len(fs, dirent, &rec_len) == 0) && + (len > rec_len)) + len = rec_len; + safe_print(f, dirent->name, len); + break; + case 'r': + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + fprintf(f, "%u", rec_len); + break; + case 'l': + fprintf(f, "%u", ext2fs_dirent_name_len(dirent)); + break; + case 't': + fprintf(f, "%u", ext2fs_dirent_file_type(dirent)); + break; + default: + no_dirent: + fprintf(f, "%%D%c", ch); + break; + } +} + +static _INLINE_ void expand_percent_expression(FILE *f, ext2_filsys fs, + char ch, int width, int *first, + struct problem_context *ctx) +{ + e2fsck_t e2fsck_ctx = fs ? (e2fsck_t) fs->priv_data : NULL; + const char *m; + + if (!ctx) + goto no_context; + + switch (ch) { + case '%': + fputc('%', f); + break; + case 'b': + fprintf(f, "%*llu", width, (unsigned long long) ctx->blk); + break; + case 'B': + if (ctx->blkcount == BLOCK_COUNT_IND) + m = _("indirect block"); + else if (ctx->blkcount == BLOCK_COUNT_DIND) + m = _("double indirect block"); + else if (ctx->blkcount == BLOCK_COUNT_TIND) + m = _("triple indirect block"); + else if (ctx->blkcount == BLOCK_COUNT_TRANSLATOR) + m = _("translator block"); + else + m = _("block #"); + if (*first && islower(m[0])) + fputc(toupper(*m++), f); + fputs(m, f); + if (ctx->blkcount >= 0) + fprintf(f, "%lld", (long long) ctx->blkcount); + break; + case 'c': + fprintf(f, "%*llu", width, (unsigned long long) ctx->blk2); + break; + case 'd': + fprintf(f, "%*u", width, ctx->dir); + break; + case 'g': + fprintf(f, "%*u", width, ctx->group); + break; + case 'i': + fprintf(f, "%*u", width, ctx->ino); + break; + case 'j': + fprintf(f, "%*u", width, ctx->ino2); + break; + case 'm': + fprintf(f, "%*s", width, error_message(ctx->errcode)); + break; + case 'N': + fprintf(f, "%*llu", width, (long long)ctx->num); + break; + case 'n': + fprintf(f, "%*llu", width, (long long)ctx->num2); + break; + case 'p': + print_pathname(f, fs, ctx->ino, 0); + break; + case 'P': + print_pathname(f, fs, ctx->ino2, + ctx->dirent ? ctx->dirent->inode : 0); + break; + case 'q': + print_pathname(f, fs, ctx->dir, 0); + break; + case 'Q': + print_pathname(f, fs, ctx->dir, ctx->ino); + break; + case 'r': + fprintf(f, "%*lld", width, (long long) ctx->blkcount); + break; + case 'S': + fprintf(f, "%llu", + (unsigned long long) get_backup_sb(NULL, fs, + NULL, NULL)); + break; + case 's': + fprintf(f, "%*s", width, ctx->str ? ctx->str : "NULL"); + break; + case 't': + print_time(f, (time_t) ctx->num); + break; + case 'T': + print_time(f, e2fsck_ctx ? e2fsck_ctx->now : time(0)); + break; + case 'U': + switch (ctx->num) { + case USRQUOTA: + m = _("user"); + break; + case GRPQUOTA: + m = _("group"); + break; + case PRJQUOTA: + m = _("project"); + break; + default: + m = _("unknown quota type"); + break; + } + if (*first && islower(m[0])) + fputc(toupper(*m++), f); + fputs(m, f); + if (ctx->num > PRJQUOTA) + fprintf(f, " %d", (int) ctx->num); + break; + case 'x': + fprintf(f, "0x%0*x", width, ctx->csum1); + break; + case 'X': + fprintf(f, "0x%0*llx", width, (long long)ctx->num); + break; + case 'y': + fprintf(f, "0x%0*x", width, ctx->csum2); + break; + default: + no_context: + fprintf(f, "%%%c", ch); + break; + } +} + +void print_e2fsck_message(FILE *f, e2fsck_t ctx, const char *msg, + struct problem_context *pctx, int first, + int recurse) +{ + ext2_filsys fs = ctx->fs; + const char * cp; + int i, width; + + e2fsck_clear_progbar(ctx); + for (cp = msg; *cp; cp++) { + if (cp[0] == '@') { + cp++; + expand_at_expression(f, ctx, *cp, pctx, &first, + recurse); + } else if (cp[0] == '%') { + cp++; + width = 0; + while (isdigit(cp[0])) { + width = (width * 10) + cp[0] - '0'; + cp++; + } + if (cp[0] == 'I') { + cp++; + expand_inode_expression(f, fs, *cp, pctx); + } else if (cp[0] == 'D') { + cp++; + expand_dirent_expression(f, fs, *cp, pctx); + } else { + expand_percent_expression(f, fs, *cp, width, + &first, pctx); + } + } else { + for (i=0; cp[i]; i++) + if ((cp[i] == '@') || cp[i] == '%') + break; + fprintf(f, "%.*s", i, cp); + cp += i-1; + } + first = 0; + } +} diff --git a/e2fsck/mtrace.awk b/e2fsck/mtrace.awk new file mode 100644 index 0000000..7e96b8a --- /dev/null +++ b/e2fsck/mtrace.awk @@ -0,0 +1,37 @@ +#!/usr/bin/awk -f +# +# Awk program to analyze mtrace.c output. +# +$1 == "+" { if (allocated[$2] != "") + print "+", $2, "Alloc", NR, "duplicate:", allocated[$2]; + else + allocated[$2] = $3; + } +$1 == "-" { if (allocated[$2] != "") { + allocated[$2] = ""; + if (allocated[$2] != "") + print "DELETE FAILED", $2, allocated[$2]; + } else + print "-", $2, "Free", NR, "was never alloc'd"; + } +$1 == "<" { if (allocated[$2] != "") + allocated[$2] = ""; + else + print "-", $2, "Realloc", NR, "was never alloc'd"; + } +$1 == ">" { if (allocated[$2] != "") + print "+", $2, "Realloc", NR, "duplicate:", allocated[$2]; + else + allocated[$2] = $3; + } + +# Ignore "= Start" +$1 == "=" { } +# Ignore failed realloc attempts for now +$1 == "!" { } + + +END { for (x in allocated) + if (allocated[x] != "") + print "+", x, allocated[x]; + } diff --git a/e2fsck/mtrace.c b/e2fsck/mtrace.c new file mode 100644 index 0000000..2b7b34a --- /dev/null +++ b/e2fsck/mtrace.c @@ -0,0 +1,160 @@ +/* More debugging hooks for `malloc'. + Copyright (C) 1991, 1992 Free Software Foundation, Inc. + Written April 2, 1991 by John Gilmore of Cygnus Support. + Based on mcheck.c by Mike Haertel. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Library General Public License as +published by the Free Software Foundation; either version 2 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Library General Public License for more details. + +You should have received a copy of the GNU Library General Public +License along with this library; see the file COPYING.LIB. If +not, write to the Free Software Foundation, Inc., 675 Mass Ave, +Cambridge, MA 02139, USA. + + The author may be reached (Email) at the address mike@ai.mit.edu, + or (US mail) as Mike Haertel c/o Free Software Foundation. */ + +#include "config.h" + +#ifndef _MALLOC_INTERNAL +#define _MALLOC_INTERNAL +#include "./mtrace.h" +#endif + +#include <stdio.h> + +#ifndef __GNU_LIBRARY__ +extern char *getenv (); +#else +#include <stdlib.h> +#endif + +static FILE *mallstream; +static char mallenv[]= "MALLOC_TRACE"; +static char mallbuf[BUFSIZ]; /* Buffer for the output. */ + +/* Address to breakpoint on accesses to... */ +__ptr_t mallwatch; + +/* Old hook values. */ +static void (*tr_old_free_hook) __P ((__ptr_t ptr)); +static __ptr_t (*tr_old_malloc_hook) __P ((size_t size)); +static __ptr_t (*tr_old_realloc_hook) __P ((__ptr_t ptr, size_t size)); + +/* + * Added by TYT, 10/10/93 --- so that we can print + */ +FILE *malloc_get_mallstream() +{ + return mallstream; +} + +/* This function is called when the block being alloc'd, realloc'd, or + freed has an address matching the variable "mallwatch". In a debugger, + set "mallwatch" to the address of interest, then put a breakpoint on + tr_break. */ + +void tr_break __P ((void)); +void +tr_break () +{ +} + +static void tr_freehook __P ((__ptr_t)); +static void +tr_freehook (ptr) + __ptr_t ptr; +{ + fprintf (mallstream, "- %p\n", ptr); /* Be sure to print it first. */ + if (ptr == mallwatch) + tr_break (); + __free_hook = tr_old_free_hook; + free (ptr); + __free_hook = tr_freehook; +} + +static __ptr_t tr_mallochook __P ((size_t)); +static __ptr_t +tr_mallochook (size) + size_t size; +{ + __ptr_t hdr; + + __malloc_hook = tr_old_malloc_hook; + hdr = (__ptr_t) malloc (size); + __malloc_hook = tr_mallochook; + + /* We could be printing a NULL here; that's OK. */ + fprintf (mallstream, "+ %p %d\n", hdr, size); + + if (hdr == mallwatch) + tr_break (); + + return hdr; +} + +static __ptr_t tr_reallochook __P ((__ptr_t, size_t)); +static __ptr_t +tr_reallochook (ptr, size) + __ptr_t ptr; + size_t size; +{ + __ptr_t hdr; + + if (ptr == mallwatch) + tr_break (); + + __free_hook = tr_old_free_hook; + __malloc_hook = tr_old_malloc_hook; + __realloc_hook = tr_old_realloc_hook; + hdr = (__ptr_t) realloc (ptr, size); + __free_hook = tr_freehook; + __malloc_hook = tr_mallochook; + __realloc_hook = tr_reallochook; + if (hdr == NULL) + /* Failed realloc. */ + fprintf (mallstream, "! %p %d\n", ptr, size); + else + fprintf (mallstream, "< %p\n> %p %d\n", ptr, hdr, size); + + if (hdr == mallwatch) + tr_break (); + + return hdr; +} + +/* We enable tracing if either the environment variable MALLOC_TRACE + is set, or if the variable mallwatch has been patched to an address + that the debugging user wants us to stop on. When patching mallwatch, + don't forget to set a breakpoint on tr_break! */ + +void +mtrace () +{ + char *mallfile; + + mallfile = getenv (mallenv); + if (mallfile != NULL || mallwatch != NULL) + { + mallstream = fopen (mallfile != NULL ? mallfile : "/dev/null", "w"); + if (mallstream != NULL) + { + /* Be sure it doesn't malloc its buffer! */ + setbuf (mallstream, mallbuf); + fprintf (mallstream, "= Start\n"); + tr_old_free_hook = __free_hook; + __free_hook = tr_freehook; + tr_old_malloc_hook = __malloc_hook; + __malloc_hook = tr_mallochook; + tr_old_realloc_hook = __realloc_hook; + __realloc_hook = tr_reallochook; + } + } +} diff --git a/e2fsck/mtrace.h b/e2fsck/mtrace.h new file mode 100644 index 0000000..2ed20eb --- /dev/null +++ b/e2fsck/mtrace.h @@ -0,0 +1,231 @@ +/* Declarations for `malloc' and friends. + Copyright 1990, 1991, 1992 Free Software Foundation, Inc. + Written May 1989 by Mike Haertel. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Library General Public License as +published by the Free Software Foundation; either version 2 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Library General Public License for more details. + +You should have received a copy of the GNU Library General Public +License along with this library; see the file COPYING.LIB. If +not, write to the Free Software Foundation, Inc., 675 Mass Ave, +Cambridge, MA 02139, USA. + + The author may be reached (Email) at the address mike@ai.mit.edu, + or (US mail) as Mike Haertel c/o Free Software Foundation. */ + +#ifndef _MTRACE_H + +#define _MTRACE_H 1 + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if defined (__cplusplus) || (defined (__STDC__) && __STDC__) +#undef __P +#define __P(args) args +#undef __ptr_t +#define __ptr_t void * +#else /* Not C++ or ANSI C. */ +#undef __P +#define __P(args) () +#undef const +#define const +#undef __ptr_t +#define __ptr_t char * +#endif /* C++ or ANSI C. */ + +#ifndef NULL +#define NULL 0 +#endif + +#ifdef __STDC__ +#include <stddef.h> +#else +#undef size_t +#define size_t unsigned int +#undef ptrdiff_t +#define ptrdiff_t int +#endif + + +/* Allocate SIZE bytes of memory. */ +extern __ptr_t malloc __P ((size_t __size)); +/* Re-allocate the previously allocated block + in __ptr_t, making the new block SIZE bytes long. */ +extern __ptr_t realloc __P ((__ptr_t __ptr, size_t __size)); +/* Allocate NMEMB elements of SIZE bytes each, all initialized to 0. */ +extern __ptr_t calloc __P ((size_t __nmemb, size_t __size)); +/* Free a block allocated by `malloc', `realloc' or `calloc'. */ +extern void free __P ((__ptr_t __ptr)); + +/* Allocate SIZE bytes allocated to ALIGNMENT bytes. */ +extern __ptr_t memalign __P ((size_t __alignment, size_t __size)); + +/* Allocate SIZE bytes on a page boundary. */ +extern __ptr_t valloc __P ((size_t __size)); + + +#ifdef _MALLOC_INTERNAL + +#include <stdio.h> /* Harmless, gets __GNU_LIBRARY__ defined. */ + +#if defined(__GNU_LIBRARY__) || defined(STDC_HEADERS) || defined(USG) +#include <string.h> +#else +#ifndef memset +#define memset(s, zero, n) bzero ((s), (n)) +#endif +#ifndef memcpy +#define memcpy(d, s, n) bcopy ((s), (d), (n)) +#endif +#endif + + +#if defined(__GNU_LIBRARY__) || defined(__STDC__) +#include <limits.h> +#else +#define CHAR_BIT 8 +#endif + +/* The allocator divides the heap into blocks of fixed size; large + requests receive one or more whole blocks, and small requests + receive a fragment of a block. Fragment sizes are powers of two, + and all fragments of a block are the same size. When all the + fragments in a block have been freed, the block itself is freed. */ +#define INT_BIT (CHAR_BIT * sizeof(int)) +#define BLOCKLOG (INT_BIT > 16 ? 12 : 9) +#define BLOCKSIZE (1 << BLOCKLOG) +#define BLOCKIFY(SIZE) (((SIZE) + BLOCKSIZE - 1) / BLOCKSIZE) + +/* Determine the amount of memory spanned by the initial heap table + (not an absolute limit). */ +#define HEAP (INT_BIT > 16 ? 4194304 : 65536) + +/* Number of contiguous free blocks allowed to build up at the end of + memory before they will be returned to the system. */ +#define FINAL_FREE_BLOCKS 8 + +/* Data structure giving per-block information. */ +typedef union + { + /* Heap information for a busy block. */ + struct + { + /* Zero for a large block, or positive giving the + logarithm to the base two of the fragment size. */ + int type; + union + { + struct + { + size_t nfree; /* Free fragments in a fragmented block. */ + size_t first; /* First free fragment of the block. */ + } frag; + /* Size (in blocks) of a large cluster. */ + size_t size; + } info; + } busy; + /* Heap information for a free block + (that may be the first of a free cluster). */ + struct + { + size_t size; /* Size (in blocks) of a free cluster. */ + size_t next; /* Index of next free cluster. */ + size_t prev; /* Index of previous free cluster. */ + } free; + } malloc_info; + +/* Pointer to first block of the heap. */ +extern char *_heapbase; + +/* Table indexed by block number giving per-block information. */ +extern malloc_info *_heapinfo; + +/* Address to block number and vice versa. */ +#define BLOCK(A) (((char *) (A) - _heapbase) / BLOCKSIZE + 1) +#define ADDRESS(B) ((__ptr_t) (((B) - 1) * BLOCKSIZE + _heapbase)) + +/* Current search index for the heap table. */ +extern size_t _heapindex; + +/* Limit of valid info table indices. */ +extern size_t _heaplimit; + +/* Doubly linked lists of free fragments. */ +struct list + { + struct list *next; + struct list *prev; + }; + +/* Free list headers for each fragment size. */ +extern struct list _fraghead[]; + +/* List of blocks allocated with `memalign' (or `valloc'). */ +struct alignlist + { + struct alignlist *next; + __ptr_t aligned; /* The address that memaligned returned. */ + __ptr_t exact; /* The address that malloc returned. */ + }; +extern struct alignlist *_aligned_blocks; + +/* Instrumentation. */ +extern size_t _chunks_used; +extern size_t _bytes_used; +extern size_t _chunks_free; +extern size_t _bytes_free; + +/* Internal version of `free' used in `morecore' (malloc.c). */ +extern void _free_internal __P ((__ptr_t __ptr)); + +#endif /* _MALLOC_INTERNAL. */ + +/* Underlying allocation function; successive calls should + return contiguous pieces of memory. */ +extern __ptr_t (*__morecore) __P ((ptrdiff_t __size)); + +/* Default value of `__morecore'. */ +extern __ptr_t __default_morecore __P ((ptrdiff_t __size)); + +/* Nonzero if `malloc' has been called and done its initialization. */ +extern int __malloc_initialized; + +/* Hooks for debugging versions. */ +extern void (*__free_hook) __P ((__ptr_t __ptr)); +extern __ptr_t (*__malloc_hook) __P ((size_t __size)); +extern __ptr_t (*__realloc_hook) __P ((__ptr_t __ptr, size_t __size)); + +/* Activate a standard collection of debugging hooks. */ +extern void mcheck __P ((void (*__func) __P ((void)))); + +/* Activate a standard collection of tracing hooks. */ +extern void mtrace __P ((void)); + +/* Statistics available to the user. */ +struct mstats + { + size_t bytes_total; /* Total size of the heap. */ + size_t chunks_used; /* Chunks allocated by the user. */ + size_t bytes_used; /* Byte total of user-allocated chunks. */ + size_t chunks_free; /* Chunks in the free list. */ + size_t bytes_free; /* Byte total of chunks in the free list. */ + }; + +/* Pick up the current statistics. */ +extern struct mstats mstats __P ((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* mtrace.h */ diff --git a/e2fsck/pass1.c b/e2fsck/pass1.c new file mode 100644 index 0000000..a341c72 --- /dev/null +++ b/e2fsck/pass1.c @@ -0,0 +1,4466 @@ +/* + * pass1.c -- pass #1 of e2fsck: sequential scan of the inode table + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * Pass 1 of e2fsck iterates over all the inodes in the filesystems, + * and applies the following tests to each inode: + * + * - The mode field of the inode must be legal. + * - The size and block count fields of the inode are correct. + * - A data block must not be used by another inode + * + * Pass 1 also gathers the collects the following information: + * + * - A bitmap of which inodes are in use. (inode_used_map) + * - A bitmap of which inodes are directories. (inode_dir_map) + * - A bitmap of which inodes are regular files. (inode_reg_map) + * - A bitmap of which inodes have bad fields. (inode_bad_map) + * - A bitmap of which inodes are in bad blocks. (inode_bb_map) + * - A bitmap of which inodes are imagic inodes. (inode_imagic_map) + * - A bitmap of which inodes are casefolded. (inode_casefold_map) + * - A bitmap of which blocks are in use. (block_found_map) + * - A bitmap of which blocks are in use by two inodes (block_dup_map) + * - The data blocks of the directory inodes. (dir_map) + * - Ref counts for ea_inodes. (ea_inode_refs) + * - The encryption policy ID of each encrypted inode. (encrypted_files) + * + * Pass 1 is designed to stash away enough information so that the + * other passes should not need to read in the inode information + * during the normal course of a filesystem check. (Although if an + * inconsistency is detected, other passes may need to read in an + * inode to fix it.) + * + * Note that pass 1B will be invoked if there are any duplicate blocks + * found. + */ + +#define _GNU_SOURCE 1 /* get strnlen() */ +#include "config.h" +#include <string.h> +#include <time.h> +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "e2fsck.h" +#include <ext2fs/ext2_ext_attr.h> +#include <e2p/e2p.h> + +#include "problem.h" + +#ifdef NO_INLINE_FUNCS +#define _INLINE_ +#else +#define _INLINE_ inline +#endif + +#undef DEBUG + +struct ea_quota { + blk64_t blocks; + __u64 inodes; +}; + +static int process_block(ext2_filsys fs, blk64_t *blocknr, + e2_blkcnt_t blockcnt, blk64_t ref_blk, + int ref_offset, void *priv_data); +static int process_bad_block(ext2_filsys fs, blk64_t *block_nr, + e2_blkcnt_t blockcnt, blk64_t ref_blk, + int ref_offset, void *priv_data); +static void check_blocks(e2fsck_t ctx, struct problem_context *pctx, + char *block_buf, + const struct ea_quota *ea_ibody_quota); +static void mark_table_blocks(e2fsck_t ctx); +static void alloc_bb_map(e2fsck_t ctx); +static void alloc_imagic_map(e2fsck_t ctx); +static void mark_inode_bad(e2fsck_t ctx, ext2_ino_t ino); +static void add_casefolded_dir(e2fsck_t ctx, ext2_ino_t ino); +static void handle_fs_bad_blocks(e2fsck_t ctx); +static void process_inodes(e2fsck_t ctx, char *block_buf); +static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b); +static errcode_t scan_callback(ext2_filsys fs, ext2_inode_scan scan, + dgrp_t group, void * priv_data); +static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount, + char *block_buf, int adjust_sign); +/* static char *describe_illegal_block(ext2_filsys fs, blk64_t block); */ + +struct process_block_struct { + ext2_ino_t ino; + unsigned is_dir:1, is_reg:1, clear:1, suppress:1, + fragmented:1, compressed:1, bbcheck:1, + inode_modified:1; + blk64_t num_blocks; + blk64_t max_blocks; + blk64_t last_block; + e2_blkcnt_t last_init_lblock; + e2_blkcnt_t last_db_block; + int num_illegal_blocks; + blk64_t previous_block; + struct ext2_inode *inode; + struct problem_context *pctx; + ext2fs_block_bitmap fs_meta_blocks; + e2fsck_t ctx; + blk64_t next_lblock; + struct extent_tree_info eti; +}; + +struct process_inode_block { + ext2_ino_t ino; + struct ea_quota ea_ibody_quota; + struct ext2_inode_large inode; +}; + +struct scan_callback_struct { + e2fsck_t ctx; + char *block_buf; +}; + +/* + * For the inodes to process list. + */ +static struct process_inode_block *inodes_to_process; +static int process_inode_count; + +static __u64 ext2_max_sizes[EXT2_MAX_BLOCK_LOG_SIZE - + EXT2_MIN_BLOCK_LOG_SIZE + 1]; + +/* + * Check to make sure a device inode is real. Returns 1 if the device + * checks out, 0 if not. + * + * Note: this routine is now also used to check FIFO's and Sockets, + * since they have the same requirement; the i_block fields should be + * zero. + */ +int e2fsck_pass1_check_device_inode(ext2_filsys fs EXT2FS_ATTR((unused)), + struct ext2_inode *inode) +{ + int i; + + /* + * If the index or extents flag is set, then this is a bogus + * device/fifo/socket + */ + if (inode->i_flags & (EXT2_INDEX_FL | EXT4_EXTENTS_FL)) + return 0; + + /* + * We should be able to do the test below all the time, but + * because the kernel doesn't forcibly clear the device + * inode's additional i_block fields, there are some rare + * occasions when a legitimate device inode will have non-zero + * additional i_block fields. So for now, we only complain + * when the immutable flag is set, which should never happen + * for devices. (And that's when the problem is caused, since + * you can't set or clear immutable flags for devices.) Once + * the kernel has been fixed we can change this... + */ + if (inode->i_flags & (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL)) { + for (i=4; i < EXT2_N_BLOCKS; i++) + if (inode->i_block[i]) + return 0; + } + return 1; +} + +/* + * Check to make sure a symlink inode is real. Returns 1 if the symlink + * checks out, 0 if not. + */ +int e2fsck_pass1_check_symlink(ext2_filsys fs, ext2_ino_t ino, + struct ext2_inode *inode, char *buf) +{ + unsigned int buflen; + unsigned int len; + + if ((inode->i_size_high || inode->i_size == 0) || + (inode->i_flags & EXT2_INDEX_FL)) + return 0; + + if (inode->i_flags & EXT4_INLINE_DATA_FL) { + size_t inline_size; + + if (inode->i_flags & EXT4_EXTENTS_FL) + return 0; + if (ext2fs_inline_data_size(fs, ino, &inline_size)) + return 0; + if (inode->i_size != inline_size) + return 0; + + return 1; + } + + if (ext2fs_is_fast_symlink(inode)) { + if (inode->i_flags & EXT4_EXTENTS_FL) + return 0; + buf = (char *)inode->i_block; + buflen = sizeof(inode->i_block); + } else { + ext2_extent_handle_t handle; + struct ext2_extent_info info; + struct ext2fs_extent extent; + blk64_t blk; + int i; + + if (inode->i_flags & EXT4_EXTENTS_FL) { + if (ext2fs_extent_open2(fs, ino, inode, &handle)) + return 0; + if (ext2fs_extent_get_info(handle, &info) || + (info.num_entries != 1) || + (info.max_depth != 0)) { + ext2fs_extent_free(handle); + return 0; + } + if (ext2fs_extent_get(handle, EXT2_EXTENT_ROOT, + &extent) || + (extent.e_lblk != 0) || + (extent.e_len != 1)) { + ext2fs_extent_free(handle); + return 0; + } + blk = extent.e_pblk; + ext2fs_extent_free(handle); + } else { + blk = inode->i_block[0]; + + for (i = 1; i < EXT2_N_BLOCKS; i++) + if (inode->i_block[i]) + return 0; + } + + if (blk < fs->super->s_first_data_block || + blk >= ext2fs_blocks_count(fs->super)) + return 0; + + if (io_channel_read_blk64(fs->io, blk, 1, buf)) + return 0; + + buflen = fs->blocksize; + } + + if (inode->i_flags & EXT4_ENCRYPT_FL) + len = ext2fs_le16_to_cpu(*(__u16 *)buf) + 2; + else + len = strnlen(buf, buflen); + + if (len >= buflen) + return 0; + + if (len != inode->i_size) + return 0; + return 1; +} + +/* + * If the extents or inlinedata flags are set on the inode, offer to clear 'em. + */ +#define BAD_SPECIAL_FLAGS (EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL) +static void check_extents_inlinedata(e2fsck_t ctx, + struct problem_context *pctx) +{ + if (!(pctx->inode->i_flags & BAD_SPECIAL_FLAGS)) + return; + + if (!fix_problem(ctx, PR_1_SPECIAL_EXTENTS_IDATA, pctx)) + return; + + pctx->inode->i_flags &= ~BAD_SPECIAL_FLAGS; + e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1"); +} +#undef BAD_SPECIAL_FLAGS + +/* + * If the immutable (or append-only) flag is set on the inode, offer + * to clear it. + */ +#define BAD_SPECIAL_FLAGS (EXT2_IMMUTABLE_FL | EXT2_APPEND_FL) +static void check_immutable(e2fsck_t ctx, struct problem_context *pctx) +{ + if (!(pctx->inode->i_flags & BAD_SPECIAL_FLAGS)) + return; + + if (!fix_problem(ctx, PR_1_SET_IMMUTABLE, pctx)) + return; + + pctx->inode->i_flags &= ~BAD_SPECIAL_FLAGS; + e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1"); +} + +/* + * If device, fifo or socket, check size is zero -- if not offer to + * clear it + */ +static void check_size(e2fsck_t ctx, struct problem_context *pctx) +{ + struct ext2_inode *inode = pctx->inode; + + if (EXT2_I_SIZE(inode) == 0) + return; + + if (!fix_problem(ctx, PR_1_SET_NONZSIZE, pctx)) + return; + + ext2fs_inode_size_set(ctx->fs, inode, 0); + e2fsck_write_inode(ctx, pctx->ino, pctx->inode, "pass1"); +} + +/* + * For a given size, calculate how many blocks would be charged towards quota. + */ +static blk64_t size_to_quota_blocks(ext2_filsys fs, size_t size) +{ + blk64_t clusters; + + clusters = DIV_ROUND_UP(size, fs->blocksize << fs->cluster_ratio_bits); + return EXT2FS_C2B(fs, clusters); +} + +/* + * Check validity of EA inode. Return 0 if EA inode is valid, otherwise return + * the problem code. + */ +static problem_t check_large_ea_inode(e2fsck_t ctx, + struct ext2_ext_attr_entry *entry, + struct problem_context *pctx, + blk64_t *quota_blocks) +{ + struct ext2_inode inode; + __u32 hash, signed_hash; + errcode_t retval; + + /* Check if inode is within valid range */ + if ((entry->e_value_inum < EXT2_FIRST_INODE(ctx->fs->super)) || + (entry->e_value_inum > ctx->fs->super->s_inodes_count)) { + pctx->num = entry->e_value_inum; + return PR_1_ATTR_VALUE_EA_INODE; + } + + e2fsck_read_inode(ctx, entry->e_value_inum, &inode, "pass1"); + + retval = ext2fs_ext_attr_hash_entry3(ctx->fs, entry, NULL, &hash, + &signed_hash); + if (retval) { + com_err("check_large_ea_inode", retval, + _("while hashing entry with e_value_inum = %u"), + entry->e_value_inum); + fatal_error(ctx, 0); + } + + if ((hash == entry->e_hash) || (signed_hash == entry->e_hash)) { + *quota_blocks = size_to_quota_blocks(ctx->fs, + entry->e_value_size); + } else { + /* This might be an old Lustre-style ea_inode reference. */ + if (inode.i_mtime == pctx->ino && + inode.i_generation == pctx->inode->i_generation) { + *quota_blocks = 0; + } else { + /* If target inode is also missing EA_INODE flag, + * this is likely to be a bad reference. + */ + if (!(inode.i_flags & EXT4_EA_INODE_FL)) { + pctx->num = entry->e_value_inum; + return PR_1_ATTR_VALUE_EA_INODE; + } else { + pctx->num = entry->e_hash; + return PR_1_ATTR_HASH; + } + } + } + + if (!(inode.i_flags & EXT4_EA_INODE_FL)) { + pctx->num = entry->e_value_inum; + if (fix_problem(ctx, PR_1_ATTR_SET_EA_INODE_FL, pctx)) { + inode.i_flags |= EXT4_EA_INODE_FL; + ext2fs_write_inode(ctx->fs, entry->e_value_inum, + &inode); + } else { + return PR_1_ATTR_NO_EA_INODE_FL; + } + } + return 0; +} + +static void inc_ea_inode_refs(e2fsck_t ctx, struct problem_context *pctx, + struct ext2_ext_attr_entry *first, void *end) +{ + struct ext2_ext_attr_entry *entry = first; + struct ext2_ext_attr_entry *np = EXT2_EXT_ATTR_NEXT(entry); + + while ((void *) entry < end && (void *) np < end && + !EXT2_EXT_IS_LAST_ENTRY(entry)) { + if (!entry->e_value_inum) + goto next; + if (!ctx->ea_inode_refs) { + pctx->errcode = ea_refcount_create(0, + &ctx->ea_inode_refs); + if (pctx->errcode) { + pctx->num = 4; + fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + ea_refcount_increment(ctx->ea_inode_refs, entry->e_value_inum, + 0); + next: + entry = np; + np = EXT2_EXT_ATTR_NEXT(entry); + } +} + +static void check_ea_in_inode(e2fsck_t ctx, struct problem_context *pctx, + struct ea_quota *ea_ibody_quota) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct ext2_inode_large *inode; + struct ext2_ext_attr_entry *entry; + char *start, *header, *end; + unsigned int storage_size, remain; + problem_t problem = 0; + region_t region = 0; + + ea_ibody_quota->blocks = 0; + ea_ibody_quota->inodes = 0; + + inode = (struct ext2_inode_large *) pctx->inode; + storage_size = EXT2_INODE_SIZE(ctx->fs->super) - EXT2_GOOD_OLD_INODE_SIZE - + inode->i_extra_isize; + header = ((char *) inode) + EXT2_GOOD_OLD_INODE_SIZE + + inode->i_extra_isize; + end = header + storage_size; + start = header + sizeof(__u32); + entry = (struct ext2_ext_attr_entry *) start; + + /* scan all entry's headers first */ + + /* take finish entry 0UL into account */ + remain = storage_size - sizeof(__u32); + + region = region_create(0, storage_size); + if (!region) { + fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx); + problem = 0; + ctx->flags |= E2F_FLAG_ABORT; + return; + } + if (region_allocate(region, 0, sizeof(__u32))) { + problem = PR_1_INODE_EA_ALLOC_COLLISION; + goto fix; + } + + while (remain >= sizeof(struct ext2_ext_attr_entry) && + !EXT2_EXT_IS_LAST_ENTRY(entry)) { + __u32 hash; + + if (region_allocate(region, (char *)entry - (char *)header, + EXT2_EXT_ATTR_LEN(entry->e_name_len))) { + problem = PR_1_INODE_EA_ALLOC_COLLISION; + goto fix; + } + + /* header eats this space */ + remain -= sizeof(struct ext2_ext_attr_entry); + + /* is attribute name valid? */ + if (EXT2_EXT_ATTR_SIZE(entry->e_name_len) > remain) { + pctx->num = entry->e_name_len; + problem = PR_1_ATTR_NAME_LEN; + goto fix; + } + + /* attribute len eats this space */ + remain -= EXT2_EXT_ATTR_SIZE(entry->e_name_len); + + if (entry->e_value_inum == 0) { + /* check value size */ + if (entry->e_value_size > remain) { + pctx->num = entry->e_value_size; + problem = PR_1_ATTR_VALUE_SIZE; + goto fix; + } + + if (entry->e_value_size && + region_allocate(region, + sizeof(__u32) + entry->e_value_offs, + EXT2_EXT_ATTR_SIZE( + entry->e_value_size))) { + problem = PR_1_INODE_EA_ALLOC_COLLISION; + goto fix; + } + + hash = ext2fs_ext_attr_hash_entry(entry, + start + entry->e_value_offs); + if (entry->e_hash != 0 && entry->e_hash != hash) + hash = ext2fs_ext_attr_hash_entry_signed(entry, + start + entry->e_value_offs); + + /* e_hash may be 0 in older inode's ea */ + if (entry->e_hash != 0 && entry->e_hash != hash) { + pctx->num = entry->e_hash; + problem = PR_1_ATTR_HASH; + goto fix; + } + } else { + blk64_t quota_blocks; + + problem = check_large_ea_inode(ctx, entry, pctx, + "a_blocks); + if (problem != 0) + goto fix; + + ea_ibody_quota->blocks += quota_blocks; + ea_ibody_quota->inodes++; + } + + /* If EA value is stored in external inode then it does not + * consume space here */ + if (entry->e_value_inum == 0) + remain -= entry->e_value_size; + + entry = EXT2_EXT_ATTR_NEXT(entry); + } + + if (region_allocate(region, (char *)entry - (char *)header, + sizeof(__u32))) { + problem = PR_1_INODE_EA_ALLOC_COLLISION; + goto fix; + } +fix: + if (region) + region_free(region); + /* + * it seems like a corruption. it's very unlikely we could repair + * EA(s) in automatic fashion -bzzz + */ + if (problem == 0 || !fix_problem(ctx, problem, pctx)) { + inc_ea_inode_refs(ctx, pctx, + (struct ext2_ext_attr_entry *)start, end); + return; + } + + /* simply remove all possible EA(s) */ + *((__u32 *)header) = 0UL; + e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode, + EXT2_INODE_SIZE(sb), "pass1"); + ea_ibody_quota->blocks = 0; + ea_ibody_quota->inodes = 0; +} + +static int check_inode_extra_negative_epoch(__u32 xtime, __u32 extra) { + return (xtime & (1U << 31)) != 0 && + (extra & EXT4_EPOCH_MASK) == EXT4_EPOCH_MASK; +} + +#define CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, xtime) \ + check_inode_extra_negative_epoch(inode->i_##xtime, \ + inode->i_##xtime##_extra) + +/* When today's date is earlier than 2242, we assume that atimes, + * ctimes, crtimes, and mtimes with years in the range 2310..2378 are + * actually pre-1970 dates mis-encoded. + */ +#define EXT4_EXTRA_NEGATIVE_DATE_CUTOFF 2 * (1LL << 32) + +static void check_inode_extra_space(e2fsck_t ctx, struct problem_context *pctx, + struct ea_quota *ea_ibody_quota) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct ext2_inode_large *inode; + __u32 *eamagic; + int min, max; + + ea_ibody_quota->blocks = 0; + ea_ibody_quota->inodes = 0; + + inode = (struct ext2_inode_large *) pctx->inode; + if (EXT2_INODE_SIZE(sb) == EXT2_GOOD_OLD_INODE_SIZE) { + /* this isn't large inode. so, nothing to check */ + return; + } + +#if 0 + printf("inode #%u, i_extra_size %d\n", pctx->ino, + inode->i_extra_isize); +#endif + /* i_extra_isize must cover i_extra_isize + i_checksum_hi at least */ + min = sizeof(inode->i_extra_isize) + sizeof(inode->i_checksum_hi); + max = EXT2_INODE_SIZE(sb) - EXT2_GOOD_OLD_INODE_SIZE; + /* + * For now we will allow i_extra_isize to be 0, but really + * implementations should never allow i_extra_isize to be 0 + */ + if (inode->i_extra_isize && + (inode->i_extra_isize < min || inode->i_extra_isize > max || + inode->i_extra_isize & 3)) { + if (!fix_problem(ctx, PR_1_EXTRA_ISIZE, pctx)) + return; + if (inode->i_extra_isize < min || inode->i_extra_isize > max) + inode->i_extra_isize = sb->s_want_extra_isize; + else + inode->i_extra_isize = (inode->i_extra_isize + 3) & ~3; + e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode, + EXT2_INODE_SIZE(sb), "pass1"); + } + + /* check if there is no place for an EA header */ + if (inode->i_extra_isize >= max - sizeof(__u32)) + return; + + eamagic = (__u32 *) (((char *) inode) + EXT2_GOOD_OLD_INODE_SIZE + + inode->i_extra_isize); + if (*eamagic == EXT2_EXT_ATTR_MAGIC) { + /* it seems inode has an extended attribute(s) in body */ + check_ea_in_inode(ctx, pctx, ea_ibody_quota); + } + + /* + * If the inode's extended atime (ctime, crtime, mtime) is stored in + * the old, invalid format, repair it. + */ + if (((sizeof(time_t) <= 4) || + (((sizeof(time_t) > 4) && + ctx->now < EXT4_EXTRA_NEGATIVE_DATE_CUTOFF))) && + (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, atime) || + CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, ctime) || + CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, crtime) || + CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, mtime))) { + + if (!fix_problem(ctx, PR_1_EA_TIME_OUT_OF_RANGE, pctx)) + return; + + if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, atime)) + inode->i_atime_extra &= ~EXT4_EPOCH_MASK; + if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, ctime)) + inode->i_ctime_extra &= ~EXT4_EPOCH_MASK; + if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, crtime)) + inode->i_crtime_extra &= ~EXT4_EPOCH_MASK; + if (CHECK_INODE_EXTRA_NEGATIVE_EPOCH(inode, mtime)) + inode->i_mtime_extra &= ~EXT4_EPOCH_MASK; + e2fsck_write_inode_full(ctx, pctx->ino, pctx->inode, + EXT2_INODE_SIZE(sb), "pass1"); + } + +} + +/* + * Check to see if the inode might really be a directory, despite i_mode + * + * This is a lot of complexity for something for which I'm not really + * convinced happens frequently in the wild. If for any reason this + * causes any problems, take this code out. + * [tytso:20070331.0827EDT] + */ +static void check_is_really_dir(e2fsck_t ctx, struct problem_context *pctx, + char *buf) +{ + struct ext2_inode *inode = pctx->inode; + struct ext2_dir_entry *dirent; + errcode_t retval; + blk64_t blk; + unsigned int i, rec_len, not_device = 0; + int extent_fs; + int inlinedata_fs; + + /* + * If the mode looks OK, we believe it. If the first block in + * the i_block array is 0, this cannot be a directory. If the + * inode is extent-mapped, it is still the case that the latter + * cannot be 0 - the magic number in the extent header would make + * it nonzero. + */ + if (LINUX_S_ISDIR(inode->i_mode) || LINUX_S_ISREG(inode->i_mode) || + LINUX_S_ISLNK(inode->i_mode) || inode->i_block[0] == 0) + return; + + /* + * Check the block numbers in the i_block array for validity: + * zero blocks are skipped (but the first one cannot be zero - + * see above), other blocks are checked against the first and + * max data blocks (from the the superblock) and against the + * block bitmap. Any invalid block found means this cannot be + * a directory. + * + * If there are non-zero blocks past the fourth entry, then + * this cannot be a device file: we remember that for the next + * check. + * + * For extent mapped files, we don't do any sanity checking: + * just try to get the phys block of logical block 0 and run + * with it. + * + * For inline data files, we just try to get the size of inline + * data. If it's true, we will treat it as a directory. + */ + + extent_fs = ext2fs_has_feature_extents(ctx->fs->super); + inlinedata_fs = ext2fs_has_feature_inline_data(ctx->fs->super); + if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL)) { + size_t size; + __u32 dotdot; + unsigned int rec_len2; + struct ext2_dir_entry de; + + if (ext2fs_inline_data_size(ctx->fs, pctx->ino, &size)) + return; + /* + * If the size isn't a multiple of 4, it's probably not a + * directory?? + */ + if (size & 3) + return; + /* + * If the first 10 bytes don't look like a directory entry, + * it's probably not a directory. + */ + memcpy(&dotdot, inode->i_block, sizeof(dotdot)); + memcpy(&de, ((char *)inode->i_block) + EXT4_INLINE_DATA_DOTDOT_SIZE, + EXT2_DIR_REC_LEN(0)); + dotdot = ext2fs_le32_to_cpu(dotdot); + de.inode = ext2fs_le32_to_cpu(de.inode); + de.rec_len = ext2fs_le16_to_cpu(de.rec_len); + ext2fs_get_rec_len(ctx->fs, &de, &rec_len2); + if (dotdot >= ctx->fs->super->s_inodes_count || + (dotdot < EXT2_FIRST_INO(ctx->fs->super) && + dotdot != EXT2_ROOT_INO) || + de.inode >= ctx->fs->super->s_inodes_count || + (de.inode < EXT2_FIRST_INO(ctx->fs->super) && + de.inode != 0) || + rec_len2 > EXT4_MIN_INLINE_DATA_SIZE - + EXT4_INLINE_DATA_DOTDOT_SIZE) + return; + /* device files never have a "system.data" entry */ + goto isdir; + } else if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) { + /* extent mapped */ + if (ext2fs_bmap2(ctx->fs, pctx->ino, inode, 0, 0, 0, 0, + &blk)) + return; + /* device files are never extent mapped */ + not_device++; + } else { + for (i=0; i < EXT2_N_BLOCKS; i++) { + blk = inode->i_block[i]; + if (!blk) + continue; + if (i >= 4) + not_device++; + + if (blk < ctx->fs->super->s_first_data_block || + blk >= ext2fs_blocks_count(ctx->fs->super) || + ext2fs_fast_test_block_bitmap2(ctx->block_found_map, + blk)) + return; /* Invalid block, can't be dir */ + } + blk = inode->i_block[0]; + } + + /* + * If the mode says this is a device file and the i_links_count field + * is sane and we have not ruled it out as a device file previously, + * we declare it a device file, not a directory. + */ + if ((LINUX_S_ISCHR(inode->i_mode) || LINUX_S_ISBLK(inode->i_mode)) && + (inode->i_links_count == 1) && !not_device) + return; + + /* read the first block */ + ehandler_operation(_("reading directory block")); + retval = ext2fs_read_dir_block4(ctx->fs, blk, buf, 0, pctx->ino); + ehandler_operation(0); + if (retval) + return; + + dirent = (struct ext2_dir_entry *) buf; + retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len); + if (retval) + return; + if ((ext2fs_dirent_name_len(dirent) != 1) || + (dirent->name[0] != '.') || + (dirent->inode != pctx->ino) || + (rec_len < 12) || + (rec_len % 4) || + (rec_len >= ctx->fs->blocksize - 12)) + return; + + dirent = (struct ext2_dir_entry *) (buf + rec_len); + retval = ext2fs_get_rec_len(ctx->fs, dirent, &rec_len); + if (retval) + return; + if ((ext2fs_dirent_name_len(dirent) != 2) || + (dirent->name[0] != '.') || + (dirent->name[1] != '.') || + (rec_len < 12) || + (rec_len % 4)) + return; + +isdir: + if (fix_problem(ctx, PR_1_TREAT_AS_DIRECTORY, pctx)) { + inode->i_mode = (inode->i_mode & 07777) | LINUX_S_IFDIR; + e2fsck_write_inode_full(ctx, pctx->ino, inode, + EXT2_INODE_SIZE(ctx->fs->super), + "check_is_really_dir"); + } +} + +extern errcode_t e2fsck_setup_icount(e2fsck_t ctx, const char *icount_name, + int flags, ext2_icount_t hint, + ext2_icount_t *ret) +{ + unsigned int threshold; + unsigned int save_type; + ext2_ino_t num_dirs; + errcode_t retval; + char *tdb_dir; + int enable; + + *ret = 0; + + profile_get_string(ctx->profile, "scratch_files", "directory", 0, 0, + &tdb_dir); + profile_get_uint(ctx->profile, "scratch_files", + "numdirs_threshold", 0, 0, &threshold); + profile_get_boolean(ctx->profile, "scratch_files", + "icount", 0, 1, &enable); + + retval = ext2fs_get_num_dirs(ctx->fs, &num_dirs); + if (retval) + num_dirs = 1024; /* Guess */ + + if (enable && tdb_dir && !access(tdb_dir, W_OK) && + (!threshold || num_dirs > threshold)) { + retval = ext2fs_create_icount_tdb(ctx->fs, tdb_dir, + flags, ret); + if (retval == 0) + return 0; + } + e2fsck_set_bitmap_type(ctx->fs, EXT2FS_BMAP64_RBTREE, icount_name, + &save_type); + if (ctx->options & E2F_OPT_ICOUNT_FULLMAP) + flags |= EXT2_ICOUNT_OPT_FULLMAP; + retval = ext2fs_create_icount2(ctx->fs, flags, 0, hint, ret); + ctx->fs->default_bitmap_type = save_type; + return retval; +} + +static errcode_t recheck_bad_inode_checksum(ext2_filsys fs, ext2_ino_t ino, + e2fsck_t ctx, + struct problem_context *pctx) +{ + errcode_t retval; + struct ext2_inode_large inode; + + /* + * Reread inode. If we don't see checksum error, then this inode + * has been fixed elsewhere. + */ + ctx->stashed_ino = 0; + retval = ext2fs_read_inode_full(fs, ino, (struct ext2_inode *)&inode, + sizeof(inode)); + if (retval && retval != EXT2_ET_INODE_CSUM_INVALID) + return retval; + if (!retval) + return 0; + + /* + * Checksum still doesn't match. That implies that the inode passes + * all the sanity checks, so maybe the checksum is simply corrupt. + * See if the user will go for fixing that. + */ + if (!fix_problem(ctx, PR_1_INODE_ONLY_CSUM_INVALID, pctx)) + return 0; + + retval = ext2fs_write_inode_full(fs, ino, (struct ext2_inode *)&inode, + sizeof(inode)); + return retval; +} + +static void reserve_block_for_root_repair(e2fsck_t ctx) +{ + blk64_t blk = 0; + errcode_t err; + ext2_filsys fs = ctx->fs; + + ctx->root_repair_block = 0; + if (ext2fs_test_inode_bitmap2(ctx->inode_used_map, EXT2_ROOT_INO)) + return; + + err = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk); + if (err) + return; + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); + ctx->root_repair_block = blk; +} + +static void reserve_block_for_lnf_repair(e2fsck_t ctx) +{ + blk64_t blk = 0; + errcode_t err; + ext2_filsys fs = ctx->fs; + static const char name[] = "lost+found"; + ext2_ino_t ino; + + ctx->lnf_repair_block = 0; + if (!ext2fs_lookup(fs, EXT2_ROOT_INO, name, sizeof(name)-1, 0, &ino)) + return; + + err = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk); + if (err) + return; + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); + ctx->lnf_repair_block = blk; +} + +static errcode_t get_inline_data_ea_size(ext2_filsys fs, ext2_ino_t ino, + struct ext2_inode *inode, + size_t *sz) +{ + void *p; + struct ext2_xattr_handle *handle; + errcode_t retval; + + retval = ext2fs_xattrs_open(fs, ino, &handle); + if (retval) + return retval; + + retval = ext2fs_xattrs_read_inode(handle, + (struct ext2_inode_large *)inode); + if (retval) + goto err; + + retval = ext2fs_xattr_get(handle, "system.data", &p, sz); + if (retval) + goto err; + ext2fs_free_mem(&p); +err: + (void) ext2fs_xattrs_close(&handle); + return retval; +} + +static void finish_processing_inode(e2fsck_t ctx, ext2_ino_t ino, + struct problem_context *pctx, + int failed_csum) +{ + if (!failed_csum) + return; + + /* + * If the inode failed the checksum and the user didn't + * clear the inode, test the checksum again -- if it still + * fails, ask the user if the checksum should be corrected. + */ + pctx->errcode = recheck_bad_inode_checksum(ctx->fs, ino, ctx, pctx); + if (pctx->errcode) + ctx->flags |= E2F_FLAG_ABORT; +} +#define FINISH_INODE_LOOP(ctx, ino, pctx, failed_csum) \ + do { \ + finish_processing_inode((ctx), (ino), (pctx), (failed_csum)); \ + if ((ctx)->flags & E2F_FLAG_ABORT) \ + return; \ + } while (0) + +static int could_be_block_map(ext2_filsys fs, struct ext2_inode *inode) +{ + __u32 x; + int i; + + for (i = 0; i < EXT2_N_BLOCKS; i++) { + x = inode->i_block[i]; +#ifdef WORDS_BIGENDIAN + x = ext2fs_swab32(x); +#endif + if (x >= ext2fs_blocks_count(fs->super)) + return 0; + } + + return 1; +} + +/* + * Figure out what to do with an inode that has both extents and inline data + * inode flags set. Returns -1 if we decide to erase the inode, 0 otherwise. + */ +static int fix_inline_data_extents_file(e2fsck_t ctx, + ext2_ino_t ino, + struct ext2_inode *inode, + int inode_size, + struct problem_context *pctx) +{ + size_t max_inline_ea_size; + ext2_filsys fs = ctx->fs; + int dirty = 0; + + /* Both feature flags not set? Just run the regular checks */ + if (!ext2fs_has_feature_extents(fs->super) && + !ext2fs_has_feature_inline_data(fs->super)) + return 0; + + /* Clear both flags if it's a special file */ + if (LINUX_S_ISCHR(inode->i_mode) || + LINUX_S_ISBLK(inode->i_mode) || + LINUX_S_ISFIFO(inode->i_mode) || + LINUX_S_ISSOCK(inode->i_mode)) { + check_extents_inlinedata(ctx, pctx); + return 0; + } + + /* If it looks like an extent tree, try to clear inlinedata */ + if (ext2fs_extent_header_verify(inode->i_block, + sizeof(inode->i_block)) == 0 && + fix_problem(ctx, PR_1_CLEAR_INLINE_DATA_FOR_EXTENT, pctx)) { + inode->i_flags &= ~EXT4_INLINE_DATA_FL; + dirty = 1; + goto out; + } + + /* If it looks short enough to be inline data, try to clear extents */ + if (inode_size > EXT2_GOOD_OLD_INODE_SIZE) + max_inline_ea_size = inode_size - + (EXT2_GOOD_OLD_INODE_SIZE + + ((struct ext2_inode_large *)inode)->i_extra_isize); + else + max_inline_ea_size = 0; + if (EXT2_I_SIZE(inode) < + EXT4_MIN_INLINE_DATA_SIZE + max_inline_ea_size && + fix_problem(ctx, PR_1_CLEAR_EXTENT_FOR_INLINE_DATA, pctx)) { + inode->i_flags &= ~EXT4_EXTENTS_FL; + dirty = 1; + goto out; + } + + /* + * Too big for inline data, but no evidence of extent tree - + * maybe it's a block map file? If the mappings all look valid? + */ + if (could_be_block_map(fs, inode) && + fix_problem(ctx, PR_1_CLEAR_EXTENT_INLINE_DATA_FLAGS, pctx)) { +#ifdef WORDS_BIGENDIAN + int i; + + for (i = 0; i < EXT2_N_BLOCKS; i++) + inode->i_block[i] = ext2fs_swab32(inode->i_block[i]); +#endif + + inode->i_flags &= ~(EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL); + dirty = 1; + goto out; + } + + /* Oh well, just clear the busted inode. */ + if (fix_problem(ctx, PR_1_CLEAR_EXTENT_INLINE_DATA_INODE, pctx)) { + e2fsck_clear_inode(ctx, ino, inode, 0, "pass1"); + return -1; + } + +out: + if (dirty) + e2fsck_write_inode(ctx, ino, inode, "pass1"); + + return 0; +} + +static void pass1_readahead(e2fsck_t ctx, dgrp_t *group, ext2_ino_t *next_ino) +{ + ext2_ino_t inodes_in_group = 0, inodes_per_block, inodes_per_buffer; + dgrp_t start = *group, grp; + blk64_t blocks_to_read = 0; + errcode_t err = EXT2_ET_INVALID_ARGUMENT; + + if (ctx->readahead_kb == 0) + goto out; + + /* Keep iterating groups until we have enough to readahead */ + inodes_per_block = EXT2_INODES_PER_BLOCK(ctx->fs->super); + for (grp = start; grp < ctx->fs->group_desc_count; grp++) { + if (ext2fs_bg_flags_test(ctx->fs, grp, EXT2_BG_INODE_UNINIT)) + continue; + inodes_in_group = ctx->fs->super->s_inodes_per_group - + ext2fs_bg_itable_unused(ctx->fs, grp); + blocks_to_read += (inodes_in_group + inodes_per_block - 1) / + inodes_per_block; + if (blocks_to_read * ctx->fs->blocksize > + ctx->readahead_kb * 1024) + break; + } + + err = e2fsck_readahead(ctx->fs, E2FSCK_READA_ITABLE, start, + grp - start + 1); + if (err == EAGAIN) { + ctx->readahead_kb /= 2; + err = 0; + } + +out: + if (err) { + /* Error; disable itable readahead */ + *group = ctx->fs->group_desc_count; + *next_ino = ctx->fs->super->s_inodes_count; + } else { + /* + * Don't do more readahead until we've reached the first inode + * of the last inode scan buffer block for the last group. + */ + *group = grp + 1; + inodes_per_buffer = (ctx->inode_buffer_blocks ? + ctx->inode_buffer_blocks : + EXT2_INODE_SCAN_DEFAULT_BUFFER_BLOCKS) * + ctx->fs->blocksize / + EXT2_INODE_SIZE(ctx->fs->super); + inodes_in_group--; + *next_ino = inodes_in_group - + (inodes_in_group % inodes_per_buffer) + 1 + + (grp * ctx->fs->super->s_inodes_per_group); + } +} + +/* + * Check if the passed ino is one of the used superblock quota inodes. + * + * Before the quota inodes were journaled, older superblock quota inodes + * were just regular files in the filesystem and not reserved inodes. This + * checks if the passed ino is one of the s_*_quota_inum superblock fields, + * which may not always be the same as the EXT4_*_QUOTA_INO fields. + */ +static int quota_inum_is_super(struct ext2_super_block *sb, ext2_ino_t ino) +{ + enum quota_type qtype; + + for (qtype = 0; qtype < MAXQUOTAS; qtype++) + if (*quota_sb_inump(sb, qtype) == ino) + return 1; + + return 0; +} + +/* + * Check if the passed ino is one of the reserved quota inodes. + * This checks if the inode number is one of the reserved EXT4_*_QUOTA_INO + * inodes. These inodes may or may not be in use by the quota feature. + */ +static int quota_inum_is_reserved(ext2_filsys fs, ext2_ino_t ino) +{ + enum quota_type qtype; + + for (qtype = 0; qtype < MAXQUOTAS; qtype++) + if (quota_type2inum(qtype, fs->super) == ino) + return 1; + + return 0; +} + +void e2fsck_pass1(e2fsck_t ctx) +{ + int i; + __u64 max_sizes; + ext2_filsys fs = ctx->fs; + ext2_ino_t ino = 0; + struct ext2_inode *inode = NULL; + ext2_inode_scan scan = NULL; + char *block_buf = NULL; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + unsigned char frag, fsize; + struct problem_context pctx; + struct scan_callback_struct scan_struct; + struct ext2_super_block *sb = ctx->fs->super; + const char *old_op; + const char *eop_next_inode = _("getting next inode from scan"); + int imagic_fs, extent_fs, inlinedata_fs, casefold_fs; + int low_dtime_check = 1; + unsigned int inode_size = EXT2_INODE_SIZE(fs->super); + unsigned int bufsize; + int failed_csum = 0; + ext2_ino_t ino_threshold = 0; + dgrp_t ra_group = 0; + struct ea_quota ea_ibody_quota; + + init_resource_track(&rtrack, ctx->fs->io); + clear_problem_context(&pctx); + + /* If we can do readahead, figure out how many groups to pull in. */ + if (!e2fsck_can_readahead(ctx->fs)) + ctx->readahead_kb = 0; + else if (ctx->readahead_kb == ~0ULL) + ctx->readahead_kb = e2fsck_guess_readahead(ctx->fs); + pass1_readahead(ctx, &ra_group, &ino_threshold); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_1_PASS_HEADER, &pctx); + + if (ext2fs_has_feature_dir_index(fs->super) && + !(ctx->options & E2F_OPT_NO)) { + if (ext2fs_u32_list_create(&ctx->dirs_to_hash, 50)) + ctx->dirs_to_hash = 0; + } + +#ifdef MTRACE + mtrace_print("Pass 1"); +#endif + +#define EXT2_BPP(bits) (1ULL << ((bits) - 2)) + + for (i = EXT2_MIN_BLOCK_LOG_SIZE; i <= EXT2_MAX_BLOCK_LOG_SIZE; i++) { + max_sizes = EXT2_NDIR_BLOCKS + EXT2_BPP(i); + max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i); + max_sizes = max_sizes + EXT2_BPP(i) * EXT2_BPP(i) * EXT2_BPP(i); + max_sizes = (max_sizes * (1UL << i)); + ext2_max_sizes[i - EXT2_MIN_BLOCK_LOG_SIZE] = max_sizes; + } +#undef EXT2_BPP + + imagic_fs = ext2fs_has_feature_imagic_inodes(sb); + extent_fs = ext2fs_has_feature_extents(sb); + inlinedata_fs = ext2fs_has_feature_inline_data(sb); + casefold_fs = ext2fs_has_feature_casefold(sb); + + /* + * Allocate bitmaps structures + */ + pctx.errcode = e2fsck_allocate_inode_bitmap(fs, _("in-use inode map"), + EXT2FS_BMAP64_RBTREE, + "inode_used_map", + &ctx->inode_used_map); + if (pctx.errcode) { + pctx.num = 1; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + pctx.errcode = e2fsck_allocate_inode_bitmap(fs, + _("directory inode map"), + EXT2FS_BMAP64_AUTODIR, + "inode_dir_map", &ctx->inode_dir_map); + if (pctx.errcode) { + pctx.num = 2; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + pctx.errcode = e2fsck_allocate_inode_bitmap(fs, + _("regular file inode map"), EXT2FS_BMAP64_RBTREE, + "inode_reg_map", &ctx->inode_reg_map); + if (pctx.errcode) { + pctx.num = 6; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + pctx.errcode = e2fsck_allocate_subcluster_bitmap(fs, + _("in-use block map"), EXT2FS_BMAP64_RBTREE, + "block_found_map", &ctx->block_found_map); + if (pctx.errcode) { + pctx.num = 1; + fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + pctx.errcode = e2fsck_allocate_block_bitmap(fs, + _("metadata block map"), EXT2FS_BMAP64_RBTREE, + "block_metadata_map", &ctx->block_metadata_map); + if (pctx.errcode) { + pctx.num = 1; + fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + if (casefold_fs) { + pctx.errcode = + e2fsck_allocate_inode_bitmap(fs, + _("inode casefold map"), + EXT2FS_BMAP64_RBTREE, + "inode_casefold_map", + &ctx->inode_casefold_map); + if (pctx.errcode) { + pctx.num = 1; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + pctx.errcode = e2fsck_setup_icount(ctx, "inode_link_info", 0, NULL, + &ctx->inode_link_info); + if (pctx.errcode) { + fix_problem(ctx, PR_1_ALLOCATE_ICOUNT, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + bufsize = inode_size; + if (bufsize < sizeof(struct ext2_inode_large)) + bufsize = sizeof(struct ext2_inode_large); + inode = (struct ext2_inode *) + e2fsck_allocate_memory(ctx, bufsize, "scratch inode"); + + inodes_to_process = (struct process_inode_block *) + e2fsck_allocate_memory(ctx, + (ctx->process_inode_size * + sizeof(struct process_inode_block)), + "array of inodes to process"); + process_inode_count = 0; + + pctx.errcode = ext2fs_init_dblist(fs, 0); + if (pctx.errcode) { + fix_problem(ctx, PR_1_ALLOCATE_DBCOUNT, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + + /* + * If the last orphan field is set, clear it, since the pass1 + * processing will automatically find and clear the orphans. + * In the future, we may want to try using the last_orphan + * linked list ourselves, but for now, we clear it so that the + * ext3 mount code won't get confused. + */ + if (!(ctx->options & E2F_OPT_READONLY)) { + if (fs->super->s_last_orphan) { + fs->super->s_last_orphan = 0; + ext2fs_mark_super_dirty(fs); + } + } + + mark_table_blocks(ctx); + pctx.errcode = ext2fs_convert_subcluster_bitmap(fs, + &ctx->block_found_map); + if (pctx.errcode) { + fix_problem(ctx, PR_1_CONVERT_SUBCLUSTER, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + block_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 3, + "block iterate buffer"); + if (EXT2_INODE_SIZE(fs->super) == EXT2_GOOD_OLD_INODE_SIZE) + e2fsck_use_inode_shortcuts(ctx, 1); + e2fsck_intercept_block_allocations(ctx); + old_op = ehandler_operation(_("opening inode scan")); + pctx.errcode = ext2fs_open_inode_scan(fs, ctx->inode_buffer_blocks, + &scan); + ehandler_operation(old_op); + if (pctx.errcode) { + fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + ext2fs_inode_scan_flags(scan, EXT2_SF_SKIP_MISSING_ITABLE | + EXT2_SF_WARN_GARBAGE_INODES, 0); + ctx->stashed_inode = inode; + scan_struct.ctx = ctx; + scan_struct.block_buf = block_buf; + ext2fs_set_inode_callback(scan, scan_callback, &scan_struct); + if (ctx->progress && ((ctx->progress)(ctx, 1, 0, + ctx->fs->group_desc_count))) + goto endit; + if ((fs->super->s_wtime && + fs->super->s_wtime < fs->super->s_inodes_count) || + (fs->super->s_mtime && + fs->super->s_mtime < fs->super->s_inodes_count) || + (fs->super->s_mkfs_time && + fs->super->s_mkfs_time < fs->super->s_inodes_count)) + low_dtime_check = 0; + + if (ext2fs_has_feature_mmp(fs->super) && + fs->super->s_mmp_block > fs->super->s_first_data_block && + fs->super->s_mmp_block < ext2fs_blocks_count(fs->super)) + ext2fs_mark_block_bitmap2(ctx->block_found_map, + fs->super->s_mmp_block); + + /* Set up ctx->lost_and_found if possible */ + (void) e2fsck_get_lost_and_found(ctx, 0); + + while (1) { + if (ino % (fs->super->s_inodes_per_group * 4) == 1) { + if (e2fsck_mmp_update(fs)) + fatal_error(ctx, 0); + } + old_op = ehandler_operation(eop_next_inode); + pctx.errcode = ext2fs_get_next_inode_full(scan, &ino, + inode, inode_size); + if (ino > ino_threshold) + pass1_readahead(ctx, &ra_group, &ino_threshold); + ehandler_operation(old_op); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto endit; + if (pctx.errcode == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE) { + /* + * If badblocks says badblocks is bad, offer to clear + * the list, update the in-core bb list, and restart + * the inode scan. + */ + if (ino == EXT2_BAD_INO && + fix_problem(ctx, PR_1_BADBLOCKS_IN_BADBLOCKS, + &pctx)) { + errcode_t err; + + e2fsck_clear_inode(ctx, ino, inode, 0, "pass1"); + ext2fs_badblocks_list_free(ctx->fs->badblocks); + ctx->fs->badblocks = NULL; + err = ext2fs_read_bb_inode(ctx->fs, + &ctx->fs->badblocks); + if (err) { + fix_problem(ctx, PR_1_ISCAN_ERROR, + &pctx); + ctx->flags |= E2F_FLAG_ABORT; + } else + ctx->flags |= E2F_FLAG_RESTART; + goto endit; + } + if (!ctx->inode_bb_map) + alloc_bb_map(ctx); + ext2fs_mark_inode_bitmap2(ctx->inode_bb_map, ino); + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + continue; + } + if (pctx.errcode && + pctx.errcode != EXT2_ET_INODE_CSUM_INVALID && + pctx.errcode != EXT2_ET_INODE_IS_GARBAGE) { + fix_problem(ctx, PR_1_ISCAN_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + if (!ino) + break; + pctx.ino = ino; + pctx.inode = inode; + ctx->stashed_ino = ino; + + /* Clear trashed inode? */ + if (pctx.errcode == EXT2_ET_INODE_IS_GARBAGE && + inode->i_links_count > 0 && + fix_problem(ctx, PR_1_INODE_IS_GARBAGE, &pctx)) { + pctx.errcode = 0; + e2fsck_clear_inode(ctx, ino, inode, 0, "pass1"); + } + failed_csum = pctx.errcode != 0; + + /* + * Check for inodes who might have been part of the + * orphaned list linked list. They should have gotten + * dealt with by now, unless the list had somehow been + * corrupted. + * + * FIXME: In the future, inodes which are still in use + * (and which are therefore) pending truncation should + * be handled specially. Right now we just clear the + * dtime field, and the normal e2fsck handling of + * inodes where i_size and the inode blocks are + * inconsistent is to fix i_size, instead of releasing + * the extra blocks. This won't catch the inodes that + * was at the end of the orphan list, but it's better + * than nothing. The right answer is that there + * shouldn't be any bugs in the orphan list handling. :-) + */ + if (inode->i_dtime && low_dtime_check && + inode->i_dtime < ctx->fs->super->s_inodes_count) { + if (fix_problem(ctx, PR_1_LOW_DTIME, &pctx)) { + inode->i_dtime = inode->i_links_count ? + 0 : ctx->now; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + } + + if (inode->i_links_count) { + pctx.errcode = ext2fs_icount_store(ctx->inode_link_info, + ino, inode->i_links_count); + if (pctx.errcode) { + pctx.num = inode->i_links_count; + fix_problem(ctx, PR_1_ICOUNT_STORE, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + } else if ((ino >= EXT2_FIRST_INODE(fs->super)) && + !quota_inum_is_reserved(fs, ino)) { + if (!inode->i_dtime && inode->i_mode) { + if (fix_problem(ctx, + PR_1_ZERO_DTIME, &pctx)) { + inode->i_dtime = ctx->now; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + } + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + + if ((inode->i_flags & EXT4_CASEFOLD_FL) && + ((!LINUX_S_ISDIR(inode->i_mode) && + fix_problem(ctx, PR_1_CASEFOLD_NONDIR, &pctx)) || + (!casefold_fs && + fix_problem(ctx, PR_1_CASEFOLD_FEATURE, &pctx)))) { + inode->i_flags &= ~EXT4_CASEFOLD_FL; + e2fsck_write_inode(ctx, ino, inode, "pass1"); + } + + /* Conflicting inlinedata/extents inode flags? */ + if ((inode->i_flags & EXT4_INLINE_DATA_FL) && + (inode->i_flags & EXT4_EXTENTS_FL)) { + int res = fix_inline_data_extents_file(ctx, ino, inode, + inode_size, + &pctx); + if (res < 0) { + /* skip FINISH_INODE_LOOP */ + continue; + } + } + + /* Test for incorrect inline_data flags settings. */ + if ((inode->i_flags & EXT4_INLINE_DATA_FL) && !inlinedata_fs && + (ino >= EXT2_FIRST_INODE(fs->super))) { + size_t size = 0; + + pctx.errcode = get_inline_data_ea_size(fs, ino, inode, + &size); + if (!pctx.errcode && + fix_problem(ctx, PR_1_INLINE_DATA_FEATURE, &pctx)) { + ext2fs_set_feature_inline_data(sb); + ext2fs_mark_super_dirty(fs); + inlinedata_fs = 1; + } else if (fix_problem(ctx, PR_1_INLINE_DATA_SET, &pctx)) { + e2fsck_clear_inode(ctx, ino, inode, 0, "pass1"); + /* skip FINISH_INODE_LOOP */ + continue; + } + } + + /* Test for inline data flag but no attr */ + if ((inode->i_flags & EXT4_INLINE_DATA_FL) && inlinedata_fs && + (ino >= EXT2_FIRST_INODE(fs->super))) { + size_t size = 0; + errcode_t err; + int flags; + + flags = fs->flags; + if (failed_csum) + fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + err = get_inline_data_ea_size(fs, ino, inode, &size); + fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + + switch (err) { + case 0: + /* Everything is awesome... */ + break; + case EXT2_ET_BAD_EA_BLOCK_NUM: + case EXT2_ET_BAD_EA_HASH: + case EXT2_ET_BAD_EA_HEADER: + case EXT2_ET_EA_BAD_NAME_LEN: + case EXT2_ET_EA_BAD_VALUE_SIZE: + case EXT2_ET_EA_KEY_NOT_FOUND: + case EXT2_ET_EA_NO_SPACE: + case EXT2_ET_MISSING_EA_FEATURE: + case EXT2_ET_INLINE_DATA_CANT_ITERATE: + case EXT2_ET_INLINE_DATA_NO_BLOCK: + case EXT2_ET_INLINE_DATA_NO_SPACE: + case EXT2_ET_NO_INLINE_DATA: + case EXT2_ET_EXT_ATTR_CSUM_INVALID: + case EXT2_ET_EA_BAD_VALUE_OFFSET: + case EXT2_ET_EA_INODE_CORRUPTED: + /* broken EA or no system.data EA; truncate */ + if (fix_problem(ctx, PR_1_INLINE_DATA_NO_ATTR, + &pctx)) { + err = ext2fs_inode_size_set(fs, inode, 0); + if (err) { + pctx.errcode = err; + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + inode->i_flags &= ~EXT4_INLINE_DATA_FL; + memset(&inode->i_block, 0, + sizeof(inode->i_block)); + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + break; + default: + /* Some other kind of non-xattr error? */ + pctx.errcode = err; + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + } + + /* + * Test for incorrect extent flag settings. + * + * On big-endian machines we must be careful: + * When the inode is read, the i_block array is not swapped + * if the extent flag is set. Therefore if we are testing + * for or fixing a wrongly-set flag, we must potentially + * (un)swap before testing, or after fixing. + */ + + /* + * In this case the extents flag was set when read, so + * extent_header_verify is ok. If the inode is cleared, + * no need to swap... so no extra swapping here. + */ + if ((inode->i_flags & EXT4_EXTENTS_FL) && !extent_fs && + (inode->i_links_count || (ino == EXT2_BAD_INO) || + (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO))) { + if ((ext2fs_extent_header_verify(inode->i_block, + sizeof(inode->i_block)) == 0) && + fix_problem(ctx, PR_1_EXTENT_FEATURE, &pctx)) { + ext2fs_set_feature_extents(sb); + ext2fs_mark_super_dirty(fs); + extent_fs = 1; + } else if (fix_problem(ctx, PR_1_EXTENTS_SET, &pctx)) { + clear_inode: + e2fsck_clear_inode(ctx, ino, inode, 0, "pass1"); + if (ino == EXT2_BAD_INO) + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, + ino); + /* skip FINISH_INODE_LOOP */ + continue; + } + } + + /* + * For big-endian machines: + * If the inode didn't have the extents flag set when it + * was read, then the i_blocks array was swapped. To test + * as an extents header, we must swap it back first. + * IF we then set the extents flag, the entire i_block + * array must be un/re-swapped to make it proper extents data. + */ + if (extent_fs && !(inode->i_flags & EXT4_EXTENTS_FL) && + (inode->i_links_count || (ino == EXT2_BAD_INO) || + (ino == EXT2_ROOT_INO) || (ino == EXT2_JOURNAL_INO)) && + (LINUX_S_ISREG(inode->i_mode) || + LINUX_S_ISDIR(inode->i_mode))) { + void *ehp; +#ifdef WORDS_BIGENDIAN + __u32 tmp_block[EXT2_N_BLOCKS]; + + for (i = 0; i < EXT2_N_BLOCKS; i++) + tmp_block[i] = ext2fs_swab32(inode->i_block[i]); + ehp = tmp_block; +#else + ehp = inode->i_block; +#endif + if ((ext2fs_extent_header_verify(ehp, + sizeof(inode->i_block)) == 0) && + (fix_problem(ctx, PR_1_UNSET_EXTENT_FL, &pctx))) { + inode->i_flags |= EXT4_EXTENTS_FL; +#ifdef WORDS_BIGENDIAN + memcpy(inode->i_block, tmp_block, + sizeof(inode->i_block)); +#endif + e2fsck_write_inode(ctx, ino, inode, "pass1"); + failed_csum = 0; + } + } + + if (ino == EXT2_BAD_INO) { + struct process_block_struct pb; + + if ((failed_csum || inode->i_mode || inode->i_uid || + inode->i_gid || inode->i_links_count || + (inode->i_flags & EXT4_INLINE_DATA_FL) || + inode->i_file_acl) && + fix_problem(ctx, PR_1_INVALID_BAD_INODE, &pctx)) { + memset(inode, 0, sizeof(struct ext2_inode)); + e2fsck_write_inode(ctx, ino, inode, + "clear bad inode"); + failed_csum = 0; + } + + pctx.errcode = ext2fs_copy_bitmap(ctx->block_found_map, + &pb.fs_meta_blocks); + if (pctx.errcode) { + pctx.num = 4; + fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + pb.ino = EXT2_BAD_INO; + pb.num_blocks = pb.last_block = 0; + pb.last_db_block = -1; + pb.num_illegal_blocks = 0; + pb.suppress = 0; pb.clear = 0; pb.is_dir = 0; + pb.is_reg = 0; pb.fragmented = 0; pb.bbcheck = 0; + pb.inode = inode; + pb.pctx = &pctx; + pb.ctx = ctx; + pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, + block_buf, process_bad_block, &pb); + ext2fs_free_block_bitmap(pb.fs_meta_blocks); + if (pctx.errcode) { + fix_problem(ctx, PR_1_BLOCK_ITERATE, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + if (pb.bbcheck) + if (!fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK_PROMPT, &pctx)) { + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + clear_problem_context(&pctx); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } else if (ino == EXT2_ROOT_INO) { + /* + * Make sure the root inode is a directory; if + * not, offer to clear it. It will be + * regenerated in pass #3. + */ + if (!LINUX_S_ISDIR(inode->i_mode)) { + if (fix_problem(ctx, PR_1_ROOT_NO_DIR, &pctx)) + goto clear_inode; + } + /* + * If dtime is set, offer to clear it. mke2fs + * version 0.2b created filesystems with the + * dtime field set for the root and lost+found + * directories. We won't worry about + * /lost+found, since that can be regenerated + * easily. But we will fix the root directory + * as a special case. + */ + if (inode->i_dtime && inode->i_links_count) { + if (fix_problem(ctx, PR_1_ROOT_DTIME, &pctx)) { + inode->i_dtime = 0; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + } + } else if (ino == EXT2_JOURNAL_INO) { + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + if (fs->super->s_journal_inum == EXT2_JOURNAL_INO) { + if (!LINUX_S_ISREG(inode->i_mode) && + fix_problem(ctx, PR_1_JOURNAL_BAD_MODE, + &pctx)) { + inode->i_mode = LINUX_S_IFREG; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + check_blocks(ctx, &pctx, block_buf, NULL); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + if ((inode->i_links_count || + inode->i_blocks || inode->i_block[0]) && + fix_problem(ctx, PR_1_JOURNAL_INODE_NOT_CLEAR, + &pctx)) { + memset(inode, 0, inode_size); + ext2fs_icount_store(ctx->inode_link_info, + ino, 0); + e2fsck_write_inode_full(ctx, ino, inode, + inode_size, "pass1"); + failed_csum = 0; + } + } else if (quota_inum_is_reserved(fs, ino)) { + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + if (ext2fs_has_feature_quota(fs->super) && + quota_inum_is_super(fs->super, ino)) { + if (!LINUX_S_ISREG(inode->i_mode) && + fix_problem(ctx, PR_1_QUOTA_BAD_MODE, + &pctx)) { + inode->i_mode = LINUX_S_IFREG; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + check_blocks(ctx, &pctx, block_buf, NULL); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + if ((inode->i_links_count || + inode->i_blocks || inode->i_block[0]) && + fix_problem(ctx, PR_1_QUOTA_INODE_NOT_CLEAR, + &pctx)) { + memset(inode, 0, inode_size); + ext2fs_icount_store(ctx->inode_link_info, + ino, 0); + e2fsck_write_inode_full(ctx, ino, inode, + inode_size, "pass1"); + failed_csum = 0; + } + } else if (ino == fs->super->s_orphan_file_inum) { + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + if (ext2fs_has_feature_orphan_file(fs->super)) { + if (!LINUX_S_ISREG(inode->i_mode) && + fix_problem(ctx, PR_1_ORPHAN_FILE_BAD_MODE, + &pctx)) { + inode->i_mode = LINUX_S_IFREG; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + check_blocks(ctx, &pctx, block_buf, NULL); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + if ((inode->i_links_count || + inode->i_blocks || inode->i_block[0]) && + fix_problem(ctx, PR_1_ORPHAN_FILE_NOT_CLEAR, + &pctx)) { + memset(inode, 0, inode_size); + ext2fs_icount_store(ctx->inode_link_info, ino, + 0); + e2fsck_write_inode_full(ctx, ino, inode, + inode_size, "pass1"); + failed_csum = 0; + } + } else if (ino < EXT2_FIRST_INODE(fs->super)) { + problem_t problem = 0; + + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + if (ino == EXT2_BOOT_LOADER_INO) { + if (LINUX_S_ISDIR(inode->i_mode)) + problem = PR_1_RESERVED_BAD_MODE; + } else if (ino == EXT2_RESIZE_INO) { + if (inode->i_mode && + !LINUX_S_ISREG(inode->i_mode)) + problem = PR_1_RESERVED_BAD_MODE; + } else { + if (inode->i_mode != 0) + problem = PR_1_RESERVED_BAD_MODE; + } + if (problem) { + if (fix_problem(ctx, problem, &pctx)) { + inode->i_mode = 0; + e2fsck_write_inode(ctx, ino, inode, + "pass1"); + failed_csum = 0; + } + } + check_blocks(ctx, &pctx, block_buf, NULL); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + + if (!inode->i_links_count) { + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + /* + * n.b. 0.3c ext2fs code didn't clear i_links_count for + * deleted files. Oops. + * + * Since all new ext2 implementations get this right, + * we now assume that the case of non-zero + * i_links_count and non-zero dtime means that we + * should keep the file, not delete it. + * + */ + if (inode->i_dtime) { + if (fix_problem(ctx, PR_1_SET_DTIME, &pctx)) { + inode->i_dtime = 0; + e2fsck_write_inode(ctx, ino, inode, "pass1"); + failed_csum = 0; + } + } + + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + switch (fs->super->s_creator_os) { + case EXT2_OS_HURD: + frag = inode->osd2.hurd2.h_i_frag; + fsize = inode->osd2.hurd2.h_i_fsize; + break; + default: + frag = fsize = 0; + } + + if (inode->i_faddr || frag || fsize || + (!ext2fs_has_feature_largedir(fs->super) && + (LINUX_S_ISDIR(inode->i_mode) && inode->i_size_high))) + mark_inode_bad(ctx, ino); + if ((fs->super->s_creator_os != EXT2_OS_HURD) && + !ext2fs_has_feature_64bit(fs->super) && + inode->osd2.linux2.l_i_file_acl_high != 0) + mark_inode_bad(ctx, ino); + if ((fs->super->s_creator_os != EXT2_OS_HURD) && + !ext2fs_has_feature_huge_file(fs->super) && + (inode->osd2.linux2.l_i_blocks_hi != 0)) + mark_inode_bad(ctx, ino); + if (inode->i_flags & EXT2_IMAGIC_FL) { + if (imagic_fs) { + if (!ctx->inode_imagic_map) + alloc_imagic_map(ctx); + ext2fs_mark_inode_bitmap2(ctx->inode_imagic_map, + ino); + } else { + if (fix_problem(ctx, PR_1_SET_IMAGIC, &pctx)) { + inode->i_flags &= ~EXT2_IMAGIC_FL; + e2fsck_write_inode(ctx, ino, + inode, "pass1"); + failed_csum = 0; + } + } + } + + check_inode_extra_space(ctx, &pctx, &ea_ibody_quota); + check_is_really_dir(ctx, &pctx, block_buf); + + /* + * ext2fs_inode_has_valid_blocks2 does not actually look + * at i_block[] values, so not endian-sensitive here. + */ + if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL) && + LINUX_S_ISLNK(inode->i_mode) && + !ext2fs_inode_has_valid_blocks2(fs, inode) && + fix_problem(ctx, PR_1_FAST_SYMLINK_EXTENT_FL, &pctx)) { + inode->i_flags &= ~EXT4_EXTENTS_FL; + e2fsck_write_inode(ctx, ino, inode, "pass1"); + failed_csum = 0; + } + + if ((inode->i_flags & EXT4_ENCRYPT_FL) && + add_encrypted_file(ctx, &pctx) < 0) + goto clear_inode; + + if (casefold_fs && inode->i_flags & EXT4_CASEFOLD_FL) + ext2fs_mark_inode_bitmap2(ctx->inode_casefold_map, ino); + + if (LINUX_S_ISDIR(inode->i_mode)) { + ext2fs_mark_inode_bitmap2(ctx->inode_dir_map, ino); + e2fsck_add_dir_info(ctx, ino, 0); + ctx->fs_directory_count++; + if (inode->i_flags & EXT4_CASEFOLD_FL) + add_casefolded_dir(ctx, ino); + } else if (LINUX_S_ISREG (inode->i_mode)) { + ext2fs_mark_inode_bitmap2(ctx->inode_reg_map, ino); + ctx->fs_regular_count++; + } else if (LINUX_S_ISCHR (inode->i_mode) && + e2fsck_pass1_check_device_inode(fs, inode)) { + check_extents_inlinedata(ctx, &pctx); + check_immutable(ctx, &pctx); + check_size(ctx, &pctx); + ctx->fs_chardev_count++; + } else if (LINUX_S_ISBLK (inode->i_mode) && + e2fsck_pass1_check_device_inode(fs, inode)) { + check_extents_inlinedata(ctx, &pctx); + check_immutable(ctx, &pctx); + check_size(ctx, &pctx); + ctx->fs_blockdev_count++; + } else if (LINUX_S_ISLNK (inode->i_mode) && + e2fsck_pass1_check_symlink(fs, ino, inode, + block_buf)) { + check_immutable(ctx, &pctx); + ctx->fs_symlinks_count++; + if (inode->i_flags & EXT4_INLINE_DATA_FL) { + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } else if (ext2fs_is_fast_symlink(inode)) { + ctx->fs_fast_symlinks_count++; + check_blocks(ctx, &pctx, block_buf, + &ea_ibody_quota); + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + continue; + } + } + else if (LINUX_S_ISFIFO (inode->i_mode) && + e2fsck_pass1_check_device_inode(fs, inode)) { + check_extents_inlinedata(ctx, &pctx); + check_immutable(ctx, &pctx); + check_size(ctx, &pctx); + ctx->fs_fifo_count++; + } else if ((LINUX_S_ISSOCK (inode->i_mode)) && + e2fsck_pass1_check_device_inode(fs, inode)) { + check_extents_inlinedata(ctx, &pctx); + check_immutable(ctx, &pctx); + check_size(ctx, &pctx); + ctx->fs_sockets_count++; + } else + mark_inode_bad(ctx, ino); + if (!(inode->i_flags & EXT4_EXTENTS_FL) && + !(inode->i_flags & EXT4_INLINE_DATA_FL)) { + if (inode->i_block[EXT2_IND_BLOCK]) + ctx->fs_ind_count++; + if (inode->i_block[EXT2_DIND_BLOCK]) + ctx->fs_dind_count++; + if (inode->i_block[EXT2_TIND_BLOCK]) + ctx->fs_tind_count++; + } + if (!(inode->i_flags & EXT4_EXTENTS_FL) && + !(inode->i_flags & EXT4_INLINE_DATA_FL) && + (inode->i_block[EXT2_IND_BLOCK] || + inode->i_block[EXT2_DIND_BLOCK] || + inode->i_block[EXT2_TIND_BLOCK] || + ext2fs_file_acl_block(fs, inode))) { + struct process_inode_block *itp; + + itp = &inodes_to_process[process_inode_count]; + itp->ino = ino; + itp->ea_ibody_quota = ea_ibody_quota; + if (inode_size < sizeof(struct ext2_inode_large)) + memcpy(&itp->inode, inode, inode_size); + else + memcpy(&itp->inode, inode, sizeof(itp->inode)); + process_inode_count++; + } else + check_blocks(ctx, &pctx, block_buf, &ea_ibody_quota); + + FINISH_INODE_LOOP(ctx, ino, &pctx, failed_csum); + + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto endit; + + if (process_inode_count >= ctx->process_inode_size) { + process_inodes(ctx, block_buf); + + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto endit; + } + } + process_inodes(ctx, block_buf); + ext2fs_close_inode_scan(scan); + scan = NULL; + + reserve_block_for_root_repair(ctx); + reserve_block_for_lnf_repair(ctx); + + /* + * If any extended attribute blocks' reference counts need to + * be adjusted, either up (ctx->refcount_extra), or down + * (ctx->refcount), then fix them. + */ + if (ctx->refcount) { + adjust_extattr_refcount(ctx, ctx->refcount, block_buf, -1); + ea_refcount_free(ctx->refcount); + ctx->refcount = 0; + } + if (ctx->refcount_extra) { + adjust_extattr_refcount(ctx, ctx->refcount_extra, + block_buf, +1); + ea_refcount_free(ctx->refcount_extra); + ctx->refcount_extra = 0; + } + + if (ctx->ea_block_quota_blocks) { + ea_refcount_free(ctx->ea_block_quota_blocks); + ctx->ea_block_quota_blocks = 0; + } + + if (ctx->ea_block_quota_inodes) { + ea_refcount_free(ctx->ea_block_quota_inodes); + ctx->ea_block_quota_inodes = 0; + } + + if (ctx->invalid_bitmaps) + handle_fs_bad_blocks(ctx); + + /* We don't need the block_ea_map any more */ + if (ctx->block_ea_map) { + ext2fs_free_block_bitmap(ctx->block_ea_map); + ctx->block_ea_map = 0; + } + + /* We don't need the encryption policy => ID map any more */ + destroy_encryption_policy_map(ctx); + + if (ctx->flags & E2F_FLAG_RESIZE_INODE) { + clear_problem_context(&pctx); + pctx.errcode = ext2fs_create_resize_inode(fs); + if (pctx.errcode) { + if (!fix_problem(ctx, PR_1_RESIZE_INODE_CREATE, + &pctx)) { + ctx->flags |= E2F_FLAG_ABORT; + goto endit; + } + pctx.errcode = 0; + } + if (!pctx.errcode) { + e2fsck_read_inode(ctx, EXT2_RESIZE_INO, inode, + "recreate inode"); + inode->i_mtime = ctx->now; + e2fsck_write_inode(ctx, EXT2_RESIZE_INO, inode, + "recreate inode"); + } + ctx->flags &= ~E2F_FLAG_RESIZE_INODE; + } + + if (ctx->flags & E2F_FLAG_RESTART) { + /* + * Only the master copy of the superblock and block + * group descriptors are going to be written during a + * restart, so set the superblock to be used to be the + * master superblock. + */ + ctx->use_superblock = 0; + goto endit; + } + + if (ctx->large_dirs && !ext2fs_has_feature_largedir(fs->super)) { + if (fix_problem(ctx, PR_2_FEATURE_LARGE_DIRS, &pctx)) { + ext2fs_set_feature_largedir(fs->super); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + ext2fs_mark_super_dirty(fs); + } + if (fs->super->s_rev_level == EXT2_GOOD_OLD_REV && + fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) { + ext2fs_update_dynamic_rev(fs); + ext2fs_mark_super_dirty(fs); + } + } + + if (ctx->block_dup_map) { + if (ctx->options & E2F_OPT_PREEN) { + clear_problem_context(&pctx); + fix_problem(ctx, PR_1_DUP_BLOCKS_PREENSTOP, &pctx); + } + e2fsck_pass1_dupblocks(ctx, block_buf); + } + ctx->flags |= E2F_FLAG_ALLOC_OK; +endit: + e2fsck_use_inode_shortcuts(ctx, 0); + ext2fs_free_mem(&inodes_to_process); + inodes_to_process = 0; + + if (scan) + ext2fs_close_inode_scan(scan); + if (block_buf) + ext2fs_free_mem(&block_buf); + if (inode) + ext2fs_free_mem(&inode); + + /* + * The l+f inode may have been cleared, so zap it now and + * later passes will recalculate it if necessary + */ + ctx->lost_and_found = 0; + + if ((ctx->flags & E2F_FLAG_SIGNAL_MASK) == 0) + print_resource_track(ctx, _("Pass 1"), &rtrack, ctx->fs->io); + else + ctx->invalid_bitmaps++; +} +#undef FINISH_INODE_LOOP + +/* + * When the inode_scan routines call this callback at the end of the + * glock group, call process_inodes. + */ +static errcode_t scan_callback(ext2_filsys fs, + ext2_inode_scan scan EXT2FS_ATTR((unused)), + dgrp_t group, void * priv_data) +{ + struct scan_callback_struct *scan_struct; + e2fsck_t ctx; + + scan_struct = (struct scan_callback_struct *) priv_data; + ctx = scan_struct->ctx; + + process_inodes((e2fsck_t) fs->priv_data, scan_struct->block_buf); + + if (ctx->progress) + if ((ctx->progress)(ctx, 1, group+1, + ctx->fs->group_desc_count)) + return EXT2_ET_CANCEL_REQUESTED; + + return 0; +} + +/* + * Process the inodes in the "inodes to process" list. + */ +static void process_inodes(e2fsck_t ctx, char *block_buf) +{ + int i; + struct ext2_inode *old_stashed_inode; + ext2_ino_t old_stashed_ino; + const char *old_operation; + char buf[80]; + struct problem_context pctx; + +#if 0 + printf("begin process_inodes: "); +#endif + if (process_inode_count == 0) + return; + old_operation = ehandler_operation(0); + old_stashed_inode = ctx->stashed_inode; + old_stashed_ino = ctx->stashed_ino; + qsort(inodes_to_process, process_inode_count, + sizeof(struct process_inode_block), process_inode_cmp); + clear_problem_context(&pctx); + for (i=0; i < process_inode_count; i++) { + pctx.inode = ctx->stashed_inode = + (struct ext2_inode *) &inodes_to_process[i].inode; + pctx.ino = ctx->stashed_ino = inodes_to_process[i].ino; + +#if 0 + printf("%u ", pctx.ino); +#endif + sprintf(buf, _("reading indirect blocks of inode %u"), + pctx.ino); + ehandler_operation(buf); + check_blocks(ctx, &pctx, block_buf, + &inodes_to_process[i].ea_ibody_quota); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + break; + } + ctx->stashed_inode = old_stashed_inode; + ctx->stashed_ino = old_stashed_ino; + process_inode_count = 0; +#if 0 + printf("end process inodes\n"); +#endif + ehandler_operation(old_operation); +} + +static EXT2_QSORT_TYPE process_inode_cmp(const void *a, const void *b) +{ + const struct process_inode_block *ib_a = + (const struct process_inode_block *) a; + const struct process_inode_block *ib_b = + (const struct process_inode_block *) b; + int ret; + + ret = (ib_a->inode.i_block[EXT2_IND_BLOCK] - + ib_b->inode.i_block[EXT2_IND_BLOCK]); + if (ret == 0) + /* + * We only call process_inodes() for non-extent + * inodes, so it's OK to pass NULL to + * ext2fs_file_acl_block() here. + */ + ret = ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_a->inode)) - + ext2fs_file_acl_block(0, ext2fs_const_inode(&ib_b->inode)); + if (ret == 0) + ret = ib_a->ino - ib_b->ino; + return ret; +} + +/* + * Mark an inode as being bad in some what + */ +static void mark_inode_bad(e2fsck_t ctx, ext2_ino_t ino) +{ + struct problem_context pctx; + + if (!ctx->inode_bad_map) { + clear_problem_context(&pctx); + + pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs, + _("bad inode map"), EXT2FS_BMAP64_RBTREE, + "inode_bad_map", &ctx->inode_bad_map); + if (pctx.errcode) { + pctx.num = 3; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + ext2fs_mark_inode_bitmap2(ctx->inode_bad_map, ino); +} + +static void add_casefolded_dir(e2fsck_t ctx, ext2_ino_t ino) +{ + struct problem_context pctx; + + if (!ctx->casefolded_dirs) { + pctx.errcode = ext2fs_u32_list_create(&ctx->casefolded_dirs, 0); + if (pctx.errcode) + goto error; + } + pctx.errcode = ext2fs_u32_list_add(ctx->casefolded_dirs, ino); + if (pctx.errcode == 0) + return; +error: + fix_problem(ctx, PR_1_ALLOCATE_CASEFOLDED_DIRLIST, &pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; +} + +/* + * This procedure will allocate the inode "bb" (badblock) map table + */ +static void alloc_bb_map(e2fsck_t ctx) +{ + struct problem_context pctx; + + clear_problem_context(&pctx); + pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs, + _("inode in bad block map"), EXT2FS_BMAP64_RBTREE, + "inode_bb_map", &ctx->inode_bb_map); + if (pctx.errcode) { + pctx.num = 4; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return; + } +} + +/* + * This procedure will allocate the inode imagic table + */ +static void alloc_imagic_map(e2fsck_t ctx) +{ + struct problem_context pctx; + + clear_problem_context(&pctx); + pctx.errcode = e2fsck_allocate_inode_bitmap(ctx->fs, + _("imagic inode map"), EXT2FS_BMAP64_RBTREE, + "inode_imagic_map", &ctx->inode_imagic_map); + if (pctx.errcode) { + pctx.num = 5; + fix_problem(ctx, PR_1_ALLOCATE_IBITMAP_ERROR, &pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return; + } +} + +/* + * Marks a block as in use, setting the dup_map if it's been set + * already. Called by process_block and process_bad_block. + * + * WARNING: Assumes checks have already been done to make sure block + * is valid. This is true in both process_block and process_bad_block. + */ +static _INLINE_ void mark_block_used(e2fsck_t ctx, blk64_t block) +{ + struct problem_context pctx; + + clear_problem_context(&pctx); + + if (ext2fs_fast_test_block_bitmap2(ctx->block_found_map, block)) { + if (ext2fs_has_feature_shared_blocks(ctx->fs->super) && + !(ctx->options & E2F_OPT_UNSHARE_BLOCKS)) { + return; + } + if (!ctx->block_dup_map) { + pctx.errcode = e2fsck_allocate_block_bitmap(ctx->fs, + _("multiply claimed block map"), + EXT2FS_BMAP64_RBTREE, "block_dup_map", + &ctx->block_dup_map); + if (pctx.errcode) { + pctx.num = 3; + fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, + &pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + ext2fs_fast_mark_block_bitmap2(ctx->block_dup_map, block); + } else { + ext2fs_fast_mark_block_bitmap2(ctx->block_found_map, block); + } +} + +/* + * When cluster size is greater than one block, it is caller's responsibility + * to make sure block parameter starts at a cluster boundary. + */ +static _INLINE_ void mark_blocks_used(e2fsck_t ctx, blk64_t block, + unsigned int num) +{ + if (ext2fs_test_block_bitmap_range2(ctx->block_found_map, block, num)) + ext2fs_mark_block_bitmap_range2(ctx->block_found_map, block, num); + else { + unsigned int i; + + for (i = 0; i < num; i += EXT2FS_CLUSTER_RATIO(ctx->fs)) + mark_block_used(ctx, block + i); + } +} + +/* + * Adjust the extended attribute block's reference counts at the end + * of pass 1, either by subtracting out references for EA blocks that + * are still referenced in ctx->refcount, or by adding references for + * EA blocks that had extra references as accounted for in + * ctx->refcount_extra. + */ +static void adjust_extattr_refcount(e2fsck_t ctx, ext2_refcount_t refcount, + char *block_buf, int adjust_sign) +{ + struct ext2_ext_attr_header *header; + struct problem_context pctx; + ext2_filsys fs = ctx->fs; + blk64_t blk; + __u32 should_be; + ea_value_t count; + + clear_problem_context(&pctx); + + ea_refcount_intr_begin(refcount); + while (1) { + if ((blk = ea_refcount_intr_next(refcount, &count)) == 0) + break; + pctx.blk = blk; + pctx.errcode = ext2fs_read_ext_attr3(fs, blk, block_buf, + pctx.ino); + if (pctx.errcode) { + fix_problem(ctx, PR_1_EXTATTR_READ_ABORT, &pctx); + return; + } + header = (struct ext2_ext_attr_header *) block_buf; + pctx.blkcount = header->h_refcount; + should_be = header->h_refcount + adjust_sign * (int)count; + pctx.num = should_be; + if (fix_problem(ctx, PR_1_EXTATTR_REFCOUNT, &pctx)) { + header->h_refcount = should_be; + pctx.errcode = ext2fs_write_ext_attr3(fs, blk, + block_buf, + pctx.ino); + if (pctx.errcode) { + fix_problem(ctx, PR_1_EXTATTR_WRITE_ABORT, + &pctx); + continue; + } + } + } +} + +/* + * Handle processing the extended attribute blocks + */ +static int check_ext_attr(e2fsck_t ctx, struct problem_context *pctx, + char *block_buf, struct ea_quota *ea_block_quota) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t ino = pctx->ino; + struct ext2_inode *inode = pctx->inode; + blk64_t blk; + char * end; + struct ext2_ext_attr_header *header; + struct ext2_ext_attr_entry *first, *entry; + blk64_t quota_blocks = EXT2FS_C2B(fs, 1); + __u64 quota_inodes = 0; + region_t region = 0; + int failed_csum = 0; + + ea_block_quota->blocks = 0; + ea_block_quota->inodes = 0; + + blk = ext2fs_file_acl_block(fs, inode); + if (blk == 0) + return 0; + + /* + * If the Extended attribute flag isn't set, then a non-zero + * file acl means that the inode is corrupted. + * + * Or if the extended attribute block is an invalid block, + * then the inode is also corrupted. + */ + if (!ext2fs_has_feature_xattr(fs->super) || + (blk < fs->super->s_first_data_block) || + (blk >= ext2fs_blocks_count(fs->super))) { + mark_inode_bad(ctx, ino); + return 0; + } + + /* If ea bitmap hasn't been allocated, create it */ + if (!ctx->block_ea_map) { + pctx->errcode = e2fsck_allocate_block_bitmap(fs, + _("ext attr block map"), + EXT2FS_BMAP64_RBTREE, "block_ea_map", + &ctx->block_ea_map); + if (pctx->errcode) { + pctx->num = 2; + fix_problem(ctx, PR_1_ALLOCATE_BBITMAP_ERROR, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + } + + /* Create the EA refcount structure if necessary */ + if (!ctx->refcount) { + pctx->errcode = ea_refcount_create(0, &ctx->refcount); + if (pctx->errcode) { + pctx->num = 1; + fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + } + +#if 0 + /* Debugging text */ + printf("Inode %u has EA block %u\n", ino, blk); +#endif + + /* Have we seen this EA block before? */ + if (ext2fs_fast_test_block_bitmap2(ctx->block_ea_map, blk)) { + ea_block_quota->blocks = EXT2FS_C2B(fs, 1); + ea_block_quota->inodes = 0; + + if (ctx->ea_block_quota_blocks) { + ea_refcount_fetch(ctx->ea_block_quota_blocks, blk, + "a_blocks); + if (quota_blocks) + ea_block_quota->blocks = quota_blocks; + } + + if (ctx->ea_block_quota_inodes) + ea_refcount_fetch(ctx->ea_block_quota_inodes, blk, + &ea_block_quota->inodes); + + if (ea_refcount_decrement(ctx->refcount, blk, 0) == 0) + return 1; + /* Ooops, this EA was referenced more than it stated */ + if (!ctx->refcount_extra) { + pctx->errcode = ea_refcount_create(0, + &ctx->refcount_extra); + if (pctx->errcode) { + pctx->num = 2; + fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + } + ea_refcount_increment(ctx->refcount_extra, blk, 0); + return 1; + } + + /* + * OK, we haven't seen this EA block yet. So we need to + * validate it + */ + pctx->blk = blk; + pctx->errcode = ext2fs_read_ext_attr3(fs, blk, block_buf, pctx->ino); + if (pctx->errcode == EXT2_ET_EXT_ATTR_CSUM_INVALID) { + pctx->errcode = 0; + failed_csum = 1; + } else if (pctx->errcode == EXT2_ET_BAD_EA_HEADER) + pctx->errcode = 0; + + if (pctx->errcode && + fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx)) { + pctx->errcode = 0; + goto clear_extattr; + } + header = (struct ext2_ext_attr_header *) block_buf; + pctx->blk = ext2fs_file_acl_block(fs, inode); + if (((ctx->ext_attr_ver == 1) && + (header->h_magic != EXT2_EXT_ATTR_MAGIC_v1)) || + ((ctx->ext_attr_ver == 2) && + (header->h_magic != EXT2_EXT_ATTR_MAGIC))) { + if (fix_problem(ctx, PR_1_BAD_EA_BLOCK, pctx)) + goto clear_extattr; + } + + if (header->h_blocks != 1) { + if (fix_problem(ctx, PR_1_EA_MULTI_BLOCK, pctx)) + goto clear_extattr; + } + + if (pctx->errcode && fix_problem(ctx, PR_1_READ_EA_BLOCK, pctx)) + goto clear_extattr; + + region = region_create(0, fs->blocksize); + if (!region) { + fix_problem(ctx, PR_1_EA_ALLOC_REGION_ABORT, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + if (region_allocate(region, 0, sizeof(struct ext2_ext_attr_header))) { + if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx)) + goto clear_extattr; + } + + first = (struct ext2_ext_attr_entry *)(header+1); + end = block_buf + fs->blocksize; + entry = first; + while ((char *)entry < end && *(__u32 *)entry) { + __u32 hash; + + if (region_allocate(region, (char *)entry - (char *)header, + EXT2_EXT_ATTR_LEN(entry->e_name_len))) { + if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx)) + goto clear_extattr; + break; + } + if ((ctx->ext_attr_ver == 1 && + (entry->e_name_len == 0 || entry->e_name_index != 0)) || + (ctx->ext_attr_ver == 2 && + entry->e_name_index == 0)) { + if (fix_problem(ctx, PR_1_EA_BAD_NAME, pctx)) + goto clear_extattr; + break; + } + if (entry->e_value_inum == 0) { + if (entry->e_value_size > EXT2_XATTR_SIZE_MAX || + (entry->e_value_offs + entry->e_value_size > + fs->blocksize)) { + if (fix_problem(ctx, PR_1_EA_BAD_VALUE, pctx)) + goto clear_extattr; + break; + } + if (entry->e_value_size && + region_allocate(region, entry->e_value_offs, + EXT2_EXT_ATTR_SIZE(entry->e_value_size))) { + if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, + pctx)) + goto clear_extattr; + } + + hash = ext2fs_ext_attr_hash_entry(entry, block_buf + + entry->e_value_offs); + if (entry->e_hash != hash) + hash = ext2fs_ext_attr_hash_entry_signed(entry, + block_buf + entry->e_value_offs); + + if (entry->e_hash != hash) { + pctx->num = entry->e_hash; + if (fix_problem(ctx, PR_1_ATTR_HASH, pctx)) + goto clear_extattr; + entry->e_hash = hash; + } + } else { + problem_t problem; + blk64_t entry_quota_blocks; + + problem = check_large_ea_inode(ctx, entry, pctx, + &entry_quota_blocks); + if (problem && fix_problem(ctx, problem, pctx)) + goto clear_extattr; + + quota_blocks += entry_quota_blocks; + quota_inodes++; + } + + entry = EXT2_EXT_ATTR_NEXT(entry); + } + if (region_allocate(region, (char *)entry - (char *)header, 4)) { + if (fix_problem(ctx, PR_1_EA_ALLOC_COLLISION, pctx)) + goto clear_extattr; + } + region_free(region); + + /* + * We only get here if there was no other errors that were fixed. + * If there was a checksum fail, ask to correct it. + */ + if (failed_csum && + fix_problem(ctx, PR_1_EA_BLOCK_ONLY_CSUM_INVALID, pctx)) { + pctx->errcode = ext2fs_write_ext_attr3(fs, blk, block_buf, + pctx->ino); + if (pctx->errcode) + return 0; + } + + if (quota_blocks != EXT2FS_C2B(fs, 1U)) { + if (!ctx->ea_block_quota_blocks) { + pctx->errcode = ea_refcount_create(0, + &ctx->ea_block_quota_blocks); + if (pctx->errcode) { + pctx->num = 3; + goto refcount_fail; + } + } + ea_refcount_store(ctx->ea_block_quota_blocks, blk, + quota_blocks); + } + + if (quota_inodes) { + if (!ctx->ea_block_quota_inodes) { + pctx->errcode = ea_refcount_create(0, + &ctx->ea_block_quota_inodes); + if (pctx->errcode) { + pctx->num = 4; +refcount_fail: + fix_problem(ctx, PR_1_ALLOCATE_REFCOUNT, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + } + + ea_refcount_store(ctx->ea_block_quota_inodes, blk, + quota_inodes); + } + ea_block_quota->blocks = quota_blocks; + ea_block_quota->inodes = quota_inodes; + + inc_ea_inode_refs(ctx, pctx, first, end); + ea_refcount_store(ctx->refcount, blk, header->h_refcount - 1); + mark_block_used(ctx, blk); + ext2fs_fast_mark_block_bitmap2(ctx->block_ea_map, blk); + return 1; + +clear_extattr: + if (region) + region_free(region); + ext2fs_file_acl_block_set(fs, inode, 0); + e2fsck_write_inode(ctx, ino, inode, "check_ext_attr"); + return 0; +} + +/* Returns 1 if bad htree, 0 if OK */ +static int handle_htree(e2fsck_t ctx, struct problem_context *pctx, + ext2_ino_t ino, struct ext2_inode *inode, + char *block_buf) +{ + struct ext2_dx_root_info *root; + ext2_filsys fs = ctx->fs; + errcode_t retval; + blk64_t blk; + + if ((!LINUX_S_ISDIR(inode->i_mode) && + fix_problem(ctx, PR_1_HTREE_NODIR, pctx)) || + (!ext2fs_has_feature_dir_index(fs->super) && + fix_problem(ctx, PR_1_HTREE_SET, pctx))) + return 1; + + pctx->errcode = ext2fs_bmap2(fs, ino, inode, 0, 0, 0, 0, &blk); + + if ((pctx->errcode) || + (blk == 0) || + (blk < fs->super->s_first_data_block) || + (blk >= ext2fs_blocks_count(fs->super))) { + if (fix_problem(ctx, PR_1_HTREE_BADROOT, pctx)) + return 1; + else + return 0; + } + + retval = io_channel_read_blk64(fs->io, blk, 1, block_buf); + if (retval && fix_problem(ctx, PR_1_HTREE_BADROOT, pctx)) + return 1; + + /* XXX should check that beginning matches a directory */ + root = (struct ext2_dx_root_info *) (block_buf + 24); + + if ((root->reserved_zero || root->info_length < 8) && + fix_problem(ctx, PR_1_HTREE_BADROOT, pctx)) + return 1; + + pctx->num = root->hash_version; + if ((root->hash_version != EXT2_HASH_LEGACY) && + (root->hash_version != EXT2_HASH_HALF_MD4) && + (root->hash_version != EXT2_HASH_TEA) && + (root->hash_version != EXT2_HASH_SIPHASH) && + fix_problem(ctx, PR_1_HTREE_HASHV, pctx)) + return 1; + + if (ext4_hash_in_dirent(inode)) { + if (root->hash_version != EXT2_HASH_SIPHASH && + fix_problem(ctx, PR_1_HTREE_NEEDS_SIPHASH, pctx)) + return 1; + } else { + if (root->hash_version == EXT2_HASH_SIPHASH && + fix_problem(ctx, PR_1_HTREE_CANNOT_SIPHASH, pctx)) + return 1; + } + + if ((root->unused_flags & EXT2_HASH_FLAG_INCOMPAT) && + fix_problem(ctx, PR_1_HTREE_INCOMPAT, pctx)) + return 1; + + pctx->num = root->indirect_levels; + /* if htree level is clearly too high, consider it to be broken */ + if (root->indirect_levels > EXT4_HTREE_LEVEL && + fix_problem(ctx, PR_1_HTREE_DEPTH, pctx)) + return 1; + + /* if level is only maybe too high, LARGE_DIR feature could be unset */ + if (root->indirect_levels > ext2_dir_htree_level(fs) && + !ext2fs_has_feature_largedir(fs->super)) { + int blockbits = EXT2_BLOCK_SIZE_BITS(fs->super) + 10; + unsigned idx_pb = 1 << (blockbits - 3); + + /* compare inode size/blocks vs. max-sized 2-level htree */ + if (EXT2_I_SIZE(pctx->inode) < + (idx_pb - 1) * (idx_pb - 2) << blockbits && + pctx->inode->i_blocks < + (idx_pb - 1) * (idx_pb - 2) << (blockbits - 9) && + fix_problem(ctx, PR_1_HTREE_DEPTH, pctx)) + return 1; + } + + if (root->indirect_levels > EXT4_HTREE_LEVEL_COMPAT || + ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode))) + ctx->large_dirs++; + + return 0; +} + +void e2fsck_clear_inode(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode *inode, int restart_flag, + const char *source) +{ + inode->i_flags = 0; + inode->i_links_count = 0; + ext2fs_icount_store(ctx->inode_link_info, ino, 0); + inode->i_dtime = ctx->now; + + /* + * If a special inode has such rotten block mappings that we + * want to clear the whole inode, be sure to actually zap + * the block maps because i_links_count isn't checked for + * special inodes, and we'll end up right back here the next + * time we run fsck. + */ + if (ino < EXT2_FIRST_INODE(ctx->fs->super)) + memset(inode->i_block, 0, sizeof(inode->i_block)); + + ext2fs_unmark_inode_bitmap2(ctx->inode_dir_map, ino); + ext2fs_unmark_inode_bitmap2(ctx->inode_used_map, ino); + if (ctx->inode_reg_map) + ext2fs_unmark_inode_bitmap2(ctx->inode_reg_map, ino); + if (ctx->inode_bad_map) + ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino); + + /* + * If the inode was partially accounted for before processing + * was aborted, we need to restart the pass 1 scan. + */ + ctx->flags |= restart_flag; + + if (ino == EXT2_BAD_INO) + memset(inode, 0, sizeof(struct ext2_inode)); + + e2fsck_write_inode(ctx, ino, inode, source); +} + +/* + * Use the multiple-blocks reclamation code to fix alignment problems in + * a bigalloc filesystem. We want a logical cluster to map to *only* one + * physical cluster, and we want the block offsets within that cluster to + * line up. + */ +static int has_unaligned_cluster_map(e2fsck_t ctx, + blk64_t last_pblk, blk64_t last_lblk, + blk64_t pblk, blk64_t lblk) +{ + blk64_t cluster_mask; + + if (!ctx->fs->cluster_ratio_bits) + return 0; + cluster_mask = EXT2FS_CLUSTER_MASK(ctx->fs); + + /* + * If the block in the logical cluster doesn't align with the block in + * the physical cluster... + */ + if ((lblk & cluster_mask) != (pblk & cluster_mask)) + return 1; + + /* + * If we cross a physical cluster boundary within a logical cluster... + */ + if (last_pblk && (lblk & cluster_mask) != 0 && + EXT2FS_B2C(ctx->fs, lblk) == EXT2FS_B2C(ctx->fs, last_lblk) && + EXT2FS_B2C(ctx->fs, pblk) != EXT2FS_B2C(ctx->fs, last_pblk)) + return 1; + + return 0; +} + +static void scan_extent_node(e2fsck_t ctx, struct problem_context *pctx, + struct process_block_struct *pb, + blk64_t start_block, blk64_t end_block, + blk64_t eof_block, + ext2_extent_handle_t ehandle, + int try_repairs) +{ + struct ext2fs_extent extent; + blk64_t blk, last_lblk; + unsigned int i, n; + int is_dir, is_leaf; + problem_t problem; + struct ext2_extent_info info; + int failed_csum = 0; + + if (pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) + failed_csum = 1; + + pctx->errcode = ext2fs_extent_get_info(ehandle, &info); + if (pctx->errcode) + return; + if (!(ctx->options & E2F_OPT_FIXES_ONLY) && + !pb->eti.force_rebuild && + info.curr_level < MAX_EXTENT_DEPTH_COUNT) { + struct extent_tree_level *etl; + + etl = pb->eti.ext_info + info.curr_level; + etl->num_extents += info.num_entries; + etl->max_extents += info.max_entries; + /* + * Implementation wart: Splitting extent blocks when appending + * will leave the old block with one free entry. Therefore + * unless the node is totally full, pretend that a non-root + * extent block can hold one fewer entry than it actually does, + * so that we don't repeatedly rebuild the extent tree. + */ + if (info.curr_level && info.num_entries < info.max_entries) + etl->max_extents--; + } + + pctx->errcode = ext2fs_extent_get(ehandle, EXT2_EXTENT_FIRST_SIB, + &extent); + while ((pctx->errcode == 0 || + pctx->errcode == EXT2_ET_EXTENT_CSUM_INVALID) && + info.num_entries-- > 0) { + is_leaf = extent.e_flags & EXT2_EXTENT_FLAGS_LEAF; + is_dir = LINUX_S_ISDIR(pctx->inode->i_mode); + last_lblk = extent.e_lblk + extent.e_len - 1; + + problem = 0; + pctx->blk = extent.e_pblk; + pctx->blk2 = extent.e_lblk; + pctx->num = extent.e_len; + pctx->blkcount = extent.e_lblk + extent.e_len; + + if (extent.e_pblk == 0 || + extent.e_pblk < ctx->fs->super->s_first_data_block || + extent.e_pblk >= ext2fs_blocks_count(ctx->fs->super)) + problem = PR_1_EXTENT_BAD_START_BLK; + else if (extent.e_lblk < start_block) + problem = PR_1_OUT_OF_ORDER_EXTENTS; + else if ((end_block && last_lblk > end_block) && + !(last_lblk > eof_block && + ((extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) || + (pctx->inode->i_flags & EXT4_VERITY_FL)))) + problem = PR_1_EXTENT_END_OUT_OF_BOUNDS; + else if (is_leaf && extent.e_len == 0) + problem = PR_1_EXTENT_LENGTH_ZERO; + else if (is_leaf && + (extent.e_pblk + extent.e_len) > + ext2fs_blocks_count(ctx->fs->super)) + problem = PR_1_EXTENT_ENDS_BEYOND; + else if (is_leaf && is_dir && !pctx->inode->i_size_high && + !ext2fs_has_feature_largedir(ctx->fs->super) && + ((extent.e_lblk + extent.e_len) > + (1U << (21 - ctx->fs->super->s_log_block_size)))) + problem = PR_1_TOOBIG_DIR; + + if (is_leaf && problem == 0 && extent.e_len > 0) { +#if 0 + printf("extent_region(ino=%u, expect=%llu, " + "lblk=%llu, len=%u)\n", pb->ino, + (unsigned long long) pb->next_lblock, + (unsigned long long) extent.e_lblk, + extent.e_len); +#endif + if (extent.e_lblk < pb->next_lblock) + problem = PR_1_EXTENT_COLLISION; + else if (extent.e_lblk + extent.e_len > pb->next_lblock) + pb->next_lblock = extent.e_lblk + extent.e_len; + } + + /* + * Uninitialized blocks in a directory? Clear the flag and + * we'll interpret the blocks later. + */ + if (try_repairs && is_dir && problem == 0 && + (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) && + fix_problem(ctx, PR_1_UNINIT_DBLOCK, pctx)) { + extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT; + pb->inode_modified = 1; + pctx->errcode = ext2fs_extent_replace(ehandle, 0, + &extent); + if (pctx->errcode) + return; + failed_csum = 0; + } +#ifdef CONFIG_DEVELOPER_FEATURES + if (try_repairs && !is_dir && problem == 0 && + (ctx->options & E2F_OPT_CLEAR_UNINIT) && + (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) && + fix_problem(ctx, PR_1_CLEAR_UNINIT_EXTENT, pctx)) { + extent.e_flags &= ~EXT2_EXTENT_FLAGS_UNINIT; + pb->inode_modified = 1; + pctx->errcode = ext2fs_extent_replace(ehandle, 0, + &extent); + if (pctx->errcode) + return; + failed_csum = 0; + } +#endif + if (try_repairs && problem) { +report_problem: + if (fix_problem(ctx, problem, pctx)) { + if (ctx->invalid_bitmaps) { + /* + * If fsck knows the bitmaps are bad, + * skip to the next extent and + * try to clear this extent again + * after fixing the bitmaps, by + * restarting fsck. + */ + pctx->errcode = ext2fs_extent_get( + ehandle, + EXT2_EXTENT_NEXT_SIB, + &extent); + ctx->flags |= E2F_FLAG_RESTART_LATER; + if (pctx->errcode == + EXT2_ET_NO_CURRENT_NODE) { + pctx->errcode = 0; + break; + } + continue; + } + e2fsck_read_bitmaps(ctx); + pb->inode_modified = 1; + pctx->errcode = + ext2fs_extent_delete(ehandle, 0); + if (pctx->errcode) { + pctx->str = "ext2fs_extent_delete"; + return; + } + pctx->errcode = ext2fs_extent_fix_parents(ehandle); + if (pctx->errcode && + pctx->errcode != EXT2_ET_NO_CURRENT_NODE) { + pctx->str = "ext2fs_extent_fix_parents"; + return; + } + pctx->errcode = ext2fs_extent_get(ehandle, + EXT2_EXTENT_CURRENT, + &extent); + if (pctx->errcode == EXT2_ET_NO_CURRENT_NODE) { + pctx->errcode = 0; + break; + } + failed_csum = 0; + continue; + } + goto next; + } + + if (!is_leaf) { + blk64_t lblk = extent.e_lblk; + int next_try_repairs = 1; + + blk = extent.e_pblk; + + /* + * If this lower extent block collides with critical + * metadata, don't try to repair the damage. Pass 1b + * will reallocate the block; then we can try again. + */ + if (pb->ino != EXT2_RESIZE_INO && + extent.e_pblk < ctx->fs->super->s_blocks_count && + ext2fs_test_block_bitmap2(ctx->block_metadata_map, + extent.e_pblk)) { + next_try_repairs = 0; + pctx->blk = blk; + fix_problem(ctx, + PR_1_CRITICAL_METADATA_COLLISION, + pctx); + if ((ctx->options & E2F_OPT_NO) == 0) + ctx->flags |= E2F_FLAG_RESTART_LATER; + } + pctx->errcode = ext2fs_extent_get(ehandle, + EXT2_EXTENT_DOWN, &extent); + if (pctx->errcode && + pctx->errcode != EXT2_ET_EXTENT_CSUM_INVALID) { + pctx->str = "EXT2_EXTENT_DOWN"; + problem = PR_1_EXTENT_HEADER_INVALID; + if (!next_try_repairs) + return; + if (pctx->errcode == EXT2_ET_EXTENT_HEADER_BAD) + goto report_problem; + return; + } + /* The next extent should match this index's logical start */ + if (extent.e_lblk != lblk) { + struct ext2_extent_info e_info; + + pctx->errcode = ext2fs_extent_get_info(ehandle, + &e_info); + if (pctx->errcode) { + pctx->str = "ext2fs_extent_get_info"; + return; + } + pctx->blk = lblk; + pctx->blk2 = extent.e_lblk; + pctx->num = e_info.curr_level - 1; + problem = PR_1_EXTENT_INDEX_START_INVALID; + if (fix_problem(ctx, problem, pctx)) { + pb->inode_modified = 1; + pctx->errcode = + ext2fs_extent_fix_parents(ehandle); + if (pctx->errcode) { + pctx->str = "ext2fs_extent_fix_parents"; + return; + } + } + } + scan_extent_node(ctx, pctx, pb, extent.e_lblk, + last_lblk, eof_block, ehandle, + next_try_repairs); + if (pctx->errcode) + return; + pctx->errcode = ext2fs_extent_get(ehandle, + EXT2_EXTENT_UP, &extent); + if (pctx->errcode) { + pctx->str = "EXT2_EXTENT_UP"; + return; + } + mark_block_used(ctx, blk); + pb->num_blocks++; + goto next; + } + + if ((pb->previous_block != 0) && + (pb->previous_block+1 != extent.e_pblk)) { + if (ctx->options & E2F_OPT_FRAGCHECK) { + char type = '?'; + + if (pb->is_dir) + type = 'd'; + else if (pb->is_reg) + type = 'f'; + + printf(("%6lu(%c): expecting %6lu " + "actual extent " + "phys %6lu log %lu len %lu\n"), + (unsigned long) pctx->ino, type, + (unsigned long) pb->previous_block+1, + (unsigned long) extent.e_pblk, + (unsigned long) extent.e_lblk, + (unsigned long) extent.e_len); + } + pb->fragmented = 1; + } + /* + * If we notice a gap in the logical block mappings of an + * extent-mapped directory, offer to close the hole by + * moving the logical block down, otherwise we'll go mad in + * pass 3 allocating empty directory blocks to fill the hole. + */ + if (try_repairs && is_dir && + pb->last_block + 1 < extent.e_lblk) { + blk64_t new_lblk; + + new_lblk = pb->last_block + 1; + if (EXT2FS_CLUSTER_RATIO(ctx->fs) > 1) + new_lblk = ((new_lblk + + EXT2FS_CLUSTER_RATIO(ctx->fs) - 1) & + ~EXT2FS_CLUSTER_MASK(ctx->fs)) | + (extent.e_pblk & + EXT2FS_CLUSTER_MASK(ctx->fs)); + pctx->blk = extent.e_lblk; + pctx->blk2 = new_lblk; + if (fix_problem(ctx, PR_1_COLLAPSE_DBLOCK, pctx)) { + extent.e_lblk = new_lblk; + pb->inode_modified = 1; + pctx->errcode = ext2fs_extent_replace(ehandle, + 0, &extent); + if (pctx->errcode) { + pctx->errcode = 0; + goto alloc_later; + } + pctx->errcode = ext2fs_extent_fix_parents(ehandle); + if (pctx->errcode) + goto failed_add_dir_block; + pctx->errcode = ext2fs_extent_goto(ehandle, + extent.e_lblk); + if (pctx->errcode) + goto failed_add_dir_block; + last_lblk = extent.e_lblk + extent.e_len - 1; + failed_csum = 0; + } + } +alloc_later: + if (is_dir) { + while (++pb->last_db_block < + (e2_blkcnt_t) extent.e_lblk) { + pctx->errcode = ext2fs_add_dir_block2( + ctx->fs->dblist, + pb->ino, 0, + pb->last_db_block); + if (pctx->errcode) { + pctx->blk = 0; + pctx->num = pb->last_db_block; + goto failed_add_dir_block; + } + } + + for (i = 0; i < extent.e_len; i++) { + pctx->errcode = ext2fs_add_dir_block2( + ctx->fs->dblist, + pctx->ino, + extent.e_pblk + i, + extent.e_lblk + i); + if (pctx->errcode) { + pctx->blk = extent.e_pblk + i; + pctx->num = extent.e_lblk + i; + failed_add_dir_block: + fix_problem(ctx, PR_1_ADD_DBLOCK, pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + if (extent.e_len > 0) + pb->last_db_block = extent.e_lblk + extent.e_len - 1; + } + if (has_unaligned_cluster_map(ctx, pb->previous_block, + pb->last_block, + extent.e_pblk, + extent.e_lblk)) { + for (i = 0; i < extent.e_len; i++) { + pctx->blk = extent.e_lblk + i; + pctx->blk2 = extent.e_pblk + i; + fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx); + mark_block_used(ctx, extent.e_pblk + i); + mark_block_used(ctx, extent.e_pblk + i); + } + } + + /* + * Check whether first cluster got marked in previous iteration. + */ + if (ctx->fs->cluster_ratio_bits && + pb->previous_block && + (EXT2FS_B2C(ctx->fs, extent.e_pblk) == + EXT2FS_B2C(ctx->fs, pb->previous_block))) + /* Set blk to the beginning of next cluster. */ + blk = EXT2FS_C2B( + ctx->fs, + EXT2FS_B2C(ctx->fs, extent.e_pblk) + 1); + else + /* Set blk to the beginning of current cluster. */ + blk = EXT2FS_C2B(ctx->fs, + EXT2FS_B2C(ctx->fs, extent.e_pblk)); + + if (blk < extent.e_pblk + extent.e_len) { + mark_blocks_used(ctx, blk, + extent.e_pblk + extent.e_len - blk); + n = DIV_ROUND_UP(extent.e_pblk + extent.e_len - blk, + EXT2FS_CLUSTER_RATIO(ctx->fs)); + pb->num_blocks += n; + } + pb->last_block = extent.e_lblk + extent.e_len - 1; + pb->previous_block = extent.e_pblk + extent.e_len - 1; + start_block = pb->last_block = last_lblk; + if (is_leaf && !is_dir && + !(extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT)) + pb->last_init_lblock = last_lblk; + next: + pctx->errcode = ext2fs_extent_get(ehandle, + EXT2_EXTENT_NEXT_SIB, + &extent); + } + + /* Failed csum but passes checks? Ask to fix checksum. */ + if (failed_csum && + fix_problem(ctx, PR_1_EXTENT_ONLY_CSUM_INVALID, pctx)) { + pb->inode_modified = 1; + pctx->errcode = ext2fs_extent_replace(ehandle, 0, &extent); + if (pctx->errcode) + return; + } + + if (pctx->errcode == EXT2_ET_EXTENT_NO_NEXT) + pctx->errcode = 0; +} + +static void check_blocks_extents(e2fsck_t ctx, struct problem_context *pctx, + struct process_block_struct *pb) +{ + struct ext2_extent_info info; + struct ext2_inode *inode = pctx->inode; + ext2_extent_handle_t ehandle; + ext2_filsys fs = ctx->fs; + ext2_ino_t ino = pctx->ino; + errcode_t retval; + blk64_t eof_lblk; + struct ext3_extent_header *eh; + + /* Check for a proper extent header... */ + eh = (struct ext3_extent_header *) &inode->i_block[0]; + retval = ext2fs_extent_header_verify(eh, sizeof(inode->i_block)); + if (retval) { + if (fix_problem(ctx, PR_1_MISSING_EXTENT_HEADER, pctx)) + e2fsck_clear_inode(ctx, ino, inode, 0, + "check_blocks_extents"); + pctx->errcode = 0; + return; + } + + /* ...since this function doesn't fail if i_block is zeroed. */ + pctx->errcode = ext2fs_extent_open2(fs, ino, inode, &ehandle); + if (pctx->errcode) { + if (fix_problem(ctx, PR_1_READ_EXTENT, pctx)) + e2fsck_clear_inode(ctx, ino, inode, 0, + "check_blocks_extents"); + pctx->errcode = 0; + return; + } + + retval = ext2fs_extent_get_info(ehandle, &info); + if (retval == 0) { + int max_depth = info.max_depth; + + if (max_depth >= MAX_EXTENT_DEPTH_COUNT) + max_depth = MAX_EXTENT_DEPTH_COUNT-1; + ctx->extent_depth_count[max_depth]++; + } + + /* Check maximum extent depth */ + pctx->blk = info.max_depth; + pctx->blk2 = ext2fs_max_extent_depth(ehandle); + if (pctx->blk2 < pctx->blk && + fix_problem(ctx, PR_1_EXTENT_BAD_MAX_DEPTH, pctx)) + pb->eti.force_rebuild = 1; + + /* Can we collect extent tree level stats? */ + pctx->blk = MAX_EXTENT_DEPTH_COUNT; + if (pctx->blk2 > pctx->blk) + fix_problem(ctx, PR_1E_MAX_EXTENT_TREE_DEPTH, pctx); + memset(pb->eti.ext_info, 0, sizeof(pb->eti.ext_info)); + pb->eti.ino = pb->ino; + + pb->next_lblock = 0; + + eof_lblk = ((EXT2_I_SIZE(inode) + fs->blocksize - 1) >> + EXT2_BLOCK_SIZE_BITS(fs->super)) - 1; + scan_extent_node(ctx, pctx, pb, 0, 0, eof_lblk, ehandle, 1); + if (pctx->errcode && + fix_problem(ctx, PR_1_EXTENT_ITERATE_FAILURE, pctx)) { + pb->num_blocks = 0; + inode->i_blocks = 0; + e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART, + "check_blocks_extents"); + pctx->errcode = 0; + } + ext2fs_extent_free(ehandle); + + /* Rebuild unless it's a dir and we're rehashing it */ + if (LINUX_S_ISDIR(inode->i_mode) && + e2fsck_dir_will_be_rehashed(ctx, ino)) + return; + + if (ctx->options & E2F_OPT_CONVERT_BMAP) + e2fsck_rebuild_extents_later(ctx, ino); + else + e2fsck_should_rebuild_extents(ctx, pctx, &pb->eti, &info); +} + +/* + * In fact we don't need to check blocks for an inode with inline data + * because this inode doesn't have any blocks. In this function all + * we need to do is add this inode into dblist when it is a directory. + */ +static void check_blocks_inline_data(e2fsck_t ctx, struct problem_context *pctx, + struct process_block_struct *pb) +{ + int flags; + size_t inline_data_size = 0; + + if (!pb->is_dir) { + pctx->errcode = 0; + return; + } + + /* Process the dirents in i_block[] as the "first" block. */ + pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 0); + if (pctx->errcode) + goto err; + + /* Process the dirents in the EA as a "second" block. */ + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + pctx->errcode = ext2fs_inline_data_size(ctx->fs, pb->ino, + &inline_data_size); + ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (pctx->errcode) { + pctx->errcode = 0; + return; + } + + if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE) + return; + + pctx->errcode = ext2fs_add_dir_block2(ctx->fs->dblist, pb->ino, 0, 1); + if (pctx->errcode) + goto err; + + return; +err: + pctx->blk = 0; + pctx->num = 0; + fix_problem(ctx, PR_1_ADD_DBLOCK, pctx); + ctx->flags |= E2F_FLAG_ABORT; +} + +/* + * This subroutine is called on each inode to account for all of the + * blocks used by that inode. + */ +static void check_blocks(e2fsck_t ctx, struct problem_context *pctx, + char *block_buf, const struct ea_quota *ea_ibody_quota) +{ + ext2_filsys fs = ctx->fs; + struct process_block_struct pb; + ext2_ino_t ino = pctx->ino; + struct ext2_inode *inode = pctx->inode; + unsigned bad_size = 0; + int dirty_inode = 0; + int extent_fs; + int inlinedata_fs; + __u64 size; + struct ea_quota ea_block_quota; + + pb.ino = ino; + pb.num_blocks = EXT2FS_B2C(ctx->fs, + ea_ibody_quota ? ea_ibody_quota->blocks : 0); + pb.last_block = ~0; + pb.last_init_lblock = -1; + pb.last_db_block = -1; + pb.num_illegal_blocks = 0; + pb.suppress = 0; pb.clear = 0; + pb.fragmented = 0; + pb.compressed = 0; + pb.previous_block = 0; + pb.is_dir = LINUX_S_ISDIR(inode->i_mode); + pb.is_reg = LINUX_S_ISREG(inode->i_mode); + pb.max_blocks = 1U << (31 - fs->super->s_log_block_size); + pb.inode = inode; + pb.pctx = pctx; + pb.ctx = ctx; + pb.inode_modified = 0; + pb.eti.force_rebuild = 0; + pctx->ino = ino; + pctx->errcode = 0; + + extent_fs = ext2fs_has_feature_extents(ctx->fs->super); + inlinedata_fs = ext2fs_has_feature_inline_data(ctx->fs->super); + + if (check_ext_attr(ctx, pctx, block_buf, &ea_block_quota)) { + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto out; + pb.num_blocks += EXT2FS_B2C(ctx->fs, ea_block_quota.blocks); + } + + if (inlinedata_fs && (inode->i_flags & EXT4_INLINE_DATA_FL)) + check_blocks_inline_data(ctx, pctx, &pb); + else if (ext2fs_inode_has_valid_blocks2(fs, inode)) { + if (extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) + check_blocks_extents(ctx, pctx, &pb); + else { + int flags; + /* + * If we've modified the inode, write it out before + * iterate() tries to use it. + */ + if (dirty_inode) { + e2fsck_write_inode(ctx, ino, inode, + "check_blocks"); + dirty_inode = 0; + } + flags = fs->flags; + fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + pctx->errcode = ext2fs_block_iterate3(fs, ino, + pb.is_dir ? BLOCK_FLAG_HOLE : 0, + block_buf, process_block, &pb); + /* + * We do not have uninitialized extents in non extent + * files. + */ + pb.last_init_lblock = pb.last_block; + /* + * If iterate() changed a block mapping, we have to + * re-read the inode. If we decide to clear the + * inode after clearing some stuff, we'll re-write the + * bad mappings into the inode! + */ + if (pb.inode_modified) + e2fsck_read_inode(ctx, ino, inode, + "check_blocks"); + fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + + if (ctx->options & E2F_OPT_CONVERT_BMAP) { +#ifdef DEBUG + printf("bmap rebuild ino=%d\n", ino); +#endif + if (!LINUX_S_ISDIR(inode->i_mode) || + !e2fsck_dir_will_be_rehashed(ctx, ino)) + e2fsck_rebuild_extents_later(ctx, ino); + } + } + } + end_problem_latch(ctx, PR_LATCH_BLOCK); + end_problem_latch(ctx, PR_LATCH_TOOBIG); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto out; + if (pctx->errcode) + fix_problem(ctx, PR_1_BLOCK_ITERATE, pctx); + + if (pb.fragmented && pb.num_blocks < fs->super->s_blocks_per_group) { + if (LINUX_S_ISDIR(inode->i_mode)) + ctx->fs_fragmented_dir++; + else + ctx->fs_fragmented++; + } + + if (pb.clear) { + e2fsck_clear_inode(ctx, ino, inode, E2F_FLAG_RESTART, + "check_blocks"); + return; + } + + if (inode->i_flags & EXT2_INDEX_FL) { + if (handle_htree(ctx, pctx, ino, inode, block_buf)) { + inode->i_flags &= ~EXT2_INDEX_FL; + dirty_inode++; + } else { + e2fsck_add_dx_dir(ctx, ino, inode, pb.last_block+1); + } + } + + if (!pb.num_blocks && pb.is_dir && + !(inode->i_flags & EXT4_INLINE_DATA_FL)) { + if (fix_problem(ctx, PR_1_ZERO_LENGTH_DIR, pctx)) { + e2fsck_clear_inode(ctx, ino, inode, 0, "check_blocks"); + ctx->fs_directory_count--; + return; + } + } + + if (ino != quota_type2inum(PRJQUOTA, fs->super) && + ino != fs->super->s_orphan_file_inum && + (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INODE(ctx->fs->super)) && + !(inode->i_flags & EXT4_EA_INODE_FL)) { + quota_data_add(ctx->qctx, (struct ext2_inode_large *) inode, + ino, + pb.num_blocks * EXT2_CLUSTER_SIZE(fs->super)); + quota_data_inodes(ctx->qctx, (struct ext2_inode_large *) inode, + ino, (ea_ibody_quota ? + ea_ibody_quota->inodes : 0) + + ea_block_quota.inodes + 1); + } + + if (!ext2fs_has_feature_huge_file(fs->super) || + !(inode->i_flags & EXT4_HUGE_FILE_FL)) + pb.num_blocks *= (fs->blocksize / 512); + pb.num_blocks *= EXT2FS_CLUSTER_RATIO(fs); +#if 0 + printf("inode %u, i_size = %u, last_block = %llu, i_blocks=%llu, num_blocks = %llu\n", + ino, inode->i_size, (unsigned long long) pb.last_block, + (unsigned long long) ext2fs_inode_i_blocks(fs, inode), + (unsigned long long) pb.num_blocks); +#endif + size = EXT2_I_SIZE(inode); + if (pb.is_dir) { + unsigned nblock = size >> EXT2_BLOCK_SIZE_BITS(fs->super); + if (inode->i_flags & EXT4_INLINE_DATA_FL) { + int flags; + size_t sz = 0; + errcode_t err; + + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + err = ext2fs_inline_data_size(ctx->fs, pctx->ino, + &sz); + ctx->fs->flags = (flags & + EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & + ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (err || sz != size) { + bad_size = 7; + pctx->num = sz; + } + } else if (size & (fs->blocksize - 1)) + bad_size = 5; + else if (nblock > (pb.last_block + 1)) + bad_size = 1; + else if (nblock < (pb.last_block + 1)) { + if (((pb.last_block + 1) - nblock) > + fs->super->s_prealloc_dir_blocks) + bad_size = 2; + } + } else { + if ((pb.last_init_lblock >= 0) && + /* Do not allow initialized allocated blocks past i_size*/ + (size < (__u64)pb.last_init_lblock * fs->blocksize) && + !(inode->i_flags & EXT4_VERITY_FL)) + bad_size = 3; + else if (!(extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) && + size > ext2_max_sizes[fs->super->s_log_block_size]) + /* too big for a direct/indirect-mapped file */ + bad_size = 4; + else if ((extent_fs && (inode->i_flags & EXT4_EXTENTS_FL)) && + size > + ((1ULL << (32 + EXT2_BLOCK_SIZE_BITS(fs->super))) - 1)) + /* too big for an extent-based file - 32bit ee_block */ + bad_size = 6; + } + /* i_size for symlinks is checked elsewhere */ + if (bad_size && !LINUX_S_ISLNK(inode->i_mode)) { + /* Did inline_data set pctx->num earlier? */ + if (bad_size != 7) + pctx->num = (pb.last_block + 1) * fs->blocksize; + pctx->group = bad_size; + if (fix_problem(ctx, PR_1_BAD_I_SIZE, pctx)) { + ext2fs_inode_size_set(fs, inode, pctx->num); + if (EXT2_I_SIZE(inode) == 0 && + (inode->i_flags & EXT4_INLINE_DATA_FL)) { + memset(inode->i_block, 0, + sizeof(inode->i_block)); + inode->i_flags &= ~EXT4_INLINE_DATA_FL; + } + dirty_inode++; + } + pctx->num = 0; + } + if (LINUX_S_ISREG(inode->i_mode) && + ext2fs_needs_large_file_feature(EXT2_I_SIZE(inode))) + ctx->large_files++; + if ((fs->super->s_creator_os != EXT2_OS_HURD) && + ((pb.num_blocks != ext2fs_inode_i_blocks(fs, inode)) || + (ext2fs_has_feature_huge_file(fs->super) && + (inode->i_flags & EXT4_HUGE_FILE_FL) && + (inode->osd2.linux2.l_i_blocks_hi != 0)))) { + pctx->num = pb.num_blocks; + if (fix_problem(ctx, PR_1_BAD_I_BLOCKS, pctx)) { + inode->i_blocks = pb.num_blocks; + inode->osd2.linux2.l_i_blocks_hi = pb.num_blocks >> 32; + dirty_inode++; + } + pctx->num = 0; + } + + /* + * The kernel gets mad if we ask it to allocate bigalloc clusters to + * a block mapped file, so rebuild it as an extent file. We can skip + * symlinks because they're never rewritten. + */ + if (ext2fs_has_feature_bigalloc(fs->super) && + (LINUX_S_ISREG(inode->i_mode) || LINUX_S_ISDIR(inode->i_mode)) && + ext2fs_inode_data_blocks2(fs, inode) > 0 && + (ino == EXT2_ROOT_INO || ino >= EXT2_FIRST_INO(fs->super)) && + !(inode->i_flags & (EXT4_EXTENTS_FL | EXT4_INLINE_DATA_FL)) && + fix_problem(ctx, PR_1_NO_BIGALLOC_BLOCKMAP_FILES, pctx)) { + pctx->errcode = e2fsck_rebuild_extents_later(ctx, ino); + if (pctx->errcode) + goto out; + } + + if (ctx->dirs_to_hash && pb.is_dir && + !(ctx->lost_and_found && ctx->lost_and_found == ino) && + !(inode->i_flags & EXT2_INDEX_FL) && + ((inode->i_size / fs->blocksize) >= 3)) + e2fsck_rehash_dir_later(ctx, ino); + +out: + if (dirty_inode) + e2fsck_write_inode(ctx, ino, inode, "check_blocks"); +} + +#if 0 +/* + * Helper function called by process block when an illegal block is + * found. It returns a description about why the block is illegal + */ +static char *describe_illegal_block(ext2_filsys fs, blk64_t block) +{ + blk64_t super; + int i; + static char problem[80]; + + super = fs->super->s_first_data_block; + strcpy(problem, "PROGRAMMING ERROR: Unknown reason for illegal block"); + if (block < super) { + sprintf(problem, "< FIRSTBLOCK (%u)", super); + return(problem); + } else if (block >= ext2fs_blocks_count(fs->super)) { + sprintf(problem, "> BLOCKS (%u)", ext2fs_blocks_count(fs->super)); + return(problem); + } + for (i = 0; i < fs->group_desc_count; i++) { + if (block == super) { + sprintf(problem, "is the superblock in group %d", i); + break; + } + if (block > super && + block <= (super + fs->desc_blocks)) { + sprintf(problem, "is in the group descriptors " + "of group %d", i); + break; + } + if (block == ext2fs_block_bitmap_loc(fs, i)) { + sprintf(problem, "is the block bitmap of group %d", i); + break; + } + if (block == ext2fs_inode_bitmap_loc(fs, i)) { + sprintf(problem, "is the inode bitmap of group %d", i); + break; + } + if (block >= ext2fs_inode_table_loc(fs, i) && + (block < ext2fs_inode_table_loc(fs, i) + + fs->inode_blocks_per_group)) { + sprintf(problem, "is in the inode table of group %d", + i); + break; + } + super += fs->super->s_blocks_per_group; + } + return(problem); +} +#endif + +/* + * This is a helper function for check_blocks(). + */ +static int process_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *p; + struct problem_context *pctx; + blk64_t blk = *block_nr; + int ret_code = 0; + problem_t problem = 0; + e2fsck_t ctx; + + p = (struct process_block_struct *) priv_data; + pctx = p->pctx; + ctx = p->ctx; + + /* + * For a directory, add logical block zero for processing even if it's + * not mapped or we'll be perennially stuck with broken "." and ".." + * entries. + */ + if (p->is_dir && blockcnt == 0 && blk == 0) { + pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino, 0, 0); + if (pctx->errcode) { + pctx->blk = blk; + pctx->num = blockcnt; + goto failed_add_dir_block; + } + p->last_db_block++; + } + + if (blk == 0) + return 0; + +#if 0 + printf("Process_block, inode %lu, block %u, #%d\n", p->ino, blk, + blockcnt); +#endif + + /* + * Simplistic fragmentation check. We merely require that the + * file be contiguous. (Which can never be true for really + * big files that are greater than a block group.) + */ + if (p->previous_block && p->ino != EXT2_RESIZE_INO) { + if (p->previous_block+1 != blk) { + if (ctx->options & E2F_OPT_FRAGCHECK) { + char type = '?'; + + if (p->is_dir) + type = 'd'; + else if (p->is_reg) + type = 'f'; + + printf(_("%6lu(%c): expecting %6lu " + "got phys %6lu (blkcnt %lld)\n"), + (unsigned long) pctx->ino, type, + (unsigned long) p->previous_block+1, + (unsigned long) blk, + (long long) blockcnt); + } + p->fragmented = 1; + } + } + + if (p->is_dir && !ext2fs_has_feature_largedir(fs->super) && + !pctx->inode->i_size_high && + blockcnt > (1 << (21 - fs->super->s_log_block_size))) + problem = PR_1_TOOBIG_DIR; + if (p->is_dir && p->num_blocks + 1 >= p->max_blocks) + problem = PR_1_TOOBIG_DIR; + if (p->is_reg && p->num_blocks + 1 >= p->max_blocks) + problem = PR_1_TOOBIG_REG; + if (!p->is_dir && !p->is_reg && blockcnt > 0) + problem = PR_1_TOOBIG_SYMLINK; + + if (blk < fs->super->s_first_data_block || + blk >= ext2fs_blocks_count(fs->super)) + problem = PR_1_ILLEGAL_BLOCK_NUM; + + /* + * If this IND/DIND/TIND block is squatting atop some critical metadata + * (group descriptors, superblock, bitmap, inode table), any write to + * "fix" mapping problems will destroy the metadata. We'll let pass 1b + * fix that and restart fsck. + */ + if (blockcnt < 0 && + p->ino != EXT2_RESIZE_INO && + blk < ctx->fs->super->s_blocks_count && + ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk)) { + pctx->blk = blk; + fix_problem(ctx, PR_1_CRITICAL_METADATA_COLLISION, pctx); + if ((ctx->options & E2F_OPT_NO) == 0) + ctx->flags |= E2F_FLAG_RESTART_LATER; + } + + if (problem) { + p->num_illegal_blocks++; + /* + * A bit of subterfuge here -- we're trying to fix a block + * mapping, but the IND/DIND/TIND block could have collided + * with some critical metadata. So, fix the in-core mapping so + * iterate won't go insane, but return 0 instead of + * BLOCK_CHANGED so that it won't write the remapping out to + * our multiply linked block. + * + * Even if we previously determined that an *IND block + * conflicts with critical metadata, we must still try to + * iterate the *IND block as if it is an *IND block to find and + * mark the blocks it points to. Better to be overly cautious + * with the used_blocks map so that we don't move the *IND + * block to a block that's really in use! + */ + if (p->ino != EXT2_RESIZE_INO && + ref_block != 0 && + ext2fs_test_block_bitmap2(ctx->block_metadata_map, + ref_block)) { + *block_nr = 0; + return 0; + } + if (!p->suppress && (p->num_illegal_blocks % 12) == 0) { + if (fix_problem(ctx, PR_1_TOO_MANY_BAD_BLOCKS, pctx)) { + p->clear = 1; + return BLOCK_ABORT; + } + if (fix_problem(ctx, PR_1_SUPPRESS_MESSAGES, pctx)) { + p->suppress = 1; + set_latch_flags(PR_LATCH_BLOCK, + PRL_SUPPRESS, 0); + } + } + pctx->blk = blk; + pctx->blkcount = blockcnt; + if (fix_problem(ctx, problem, pctx)) { + blk = *block_nr = 0; + ret_code = BLOCK_CHANGED; + p->inode_modified = 1; + /* + * If the directory block is too big and is beyond the + * end of the FS, don't bother trying to add it for + * processing -- the kernel would never have created a + * directory this large, and we risk an ENOMEM abort. + * In any case, the toobig handler for extent-based + * directories also doesn't feed toobig blocks to + * pass 2. + */ + if (problem == PR_1_TOOBIG_DIR) + return ret_code; + goto mark_dir; + } else + return 0; + } + + if (p->ino == EXT2_RESIZE_INO) { + /* + * The resize inode has already be sanity checked + * during pass #0 (the superblock checks). All we + * have to do is mark the double indirect block as + * being in use; all of the other blocks are handled + * by mark_table_blocks()). + */ + if (blockcnt == BLOCK_COUNT_DIND) + mark_block_used(ctx, blk); + p->num_blocks++; + } else if (!(ctx->fs->cluster_ratio_bits && + p->previous_block && + (EXT2FS_B2C(ctx->fs, blk) == + EXT2FS_B2C(ctx->fs, p->previous_block)) && + (blk & EXT2FS_CLUSTER_MASK(ctx->fs)) == + ((unsigned) blockcnt & EXT2FS_CLUSTER_MASK(ctx->fs)))) { + mark_block_used(ctx, blk); + p->num_blocks++; + } else if (has_unaligned_cluster_map(ctx, p->previous_block, + p->last_block, blk, blockcnt)) { + pctx->blk = blockcnt; + pctx->blk2 = blk; + fix_problem(ctx, PR_1_MISALIGNED_CLUSTER, pctx); + mark_block_used(ctx, blk); + mark_block_used(ctx, blk); + } + if (blockcnt >= 0) + p->last_block = blockcnt; + p->previous_block = blk; +mark_dir: + if (p->is_dir && (blockcnt >= 0)) { + while (++p->last_db_block < blockcnt) { + pctx->errcode = ext2fs_add_dir_block2(fs->dblist, + p->ino, 0, + p->last_db_block); + if (pctx->errcode) { + pctx->blk = 0; + pctx->num = p->last_db_block; + goto failed_add_dir_block; + } + } + pctx->errcode = ext2fs_add_dir_block2(fs->dblist, p->ino, + blk, blockcnt); + if (pctx->errcode) { + pctx->blk = blk; + pctx->num = blockcnt; + failed_add_dir_block: + fix_problem(ctx, PR_1_ADD_DBLOCK, pctx); + /* Should never get here */ + ctx->flags |= E2F_FLAG_ABORT; + return BLOCK_ABORT; + } + } + return ret_code; +} + +static int process_bad_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *p; + blk64_t blk = *block_nr; + blk64_t first_block; + dgrp_t i; + struct problem_context *pctx; + e2fsck_t ctx; + + if (!blk) + return 0; + + p = (struct process_block_struct *) priv_data; + ctx = p->ctx; + pctx = p->pctx; + + pctx->ino = EXT2_BAD_INO; + pctx->blk = blk; + pctx->blkcount = blockcnt; + + if ((blk < fs->super->s_first_data_block) || + (blk >= ext2fs_blocks_count(fs->super))) { + if (fix_problem(ctx, PR_1_BB_ILLEGAL_BLOCK_NUM, pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } else + return 0; + } + + if (blockcnt < 0) { + if (ext2fs_test_block_bitmap2(p->fs_meta_blocks, blk)) { + p->bbcheck = 1; + if (fix_problem(ctx, PR_1_BB_FS_BLOCK, pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } + } else if (ext2fs_test_block_bitmap2(ctx->block_found_map, + blk)) { + p->bbcheck = 1; + if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK, + pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return BLOCK_ABORT; + } else + mark_block_used(ctx, blk); + return 0; + } +#if 0 + printf ("DEBUG: Marking %u as bad.\n", blk); +#endif + ctx->fs_badblocks_count++; + /* + * If the block is not used, then mark it as used and return. + * If it is already marked as found, this must mean that + * there's an overlap between the filesystem table blocks + * (bitmaps and inode table) and the bad block list. + */ + if (!ext2fs_test_block_bitmap2(ctx->block_found_map, blk)) { + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); + return 0; + } + /* + * Try to find the where the filesystem block was used... + */ + first_block = fs->super->s_first_data_block; + + for (i = 0; i < fs->group_desc_count; i++ ) { + pctx->group = i; + pctx->blk = blk; + if (!ext2fs_bg_has_super(fs, i)) + goto skip_super; + if (blk == first_block) { + if (i == 0) { + if (fix_problem(ctx, + PR_1_BAD_PRIMARY_SUPERBLOCK, + pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } + return 0; + } + fix_problem(ctx, PR_1_BAD_SUPERBLOCK, pctx); + return 0; + } + if ((blk > first_block) && + (blk <= first_block + fs->desc_blocks)) { + if (i == 0) { + pctx->blk = *block_nr; + if (fix_problem(ctx, + PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR, pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } + return 0; + } + fix_problem(ctx, PR_1_BAD_GROUP_DESCRIPTORS, pctx); + return 0; + } + skip_super: + if (blk == ext2fs_block_bitmap_loc(fs, i)) { + if (fix_problem(ctx, PR_1_BB_BAD_BLOCK, pctx)) { + ctx->invalid_block_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + return 0; + } + if (blk == ext2fs_inode_bitmap_loc(fs, i)) { + if (fix_problem(ctx, PR_1_IB_BAD_BLOCK, pctx)) { + ctx->invalid_inode_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + return 0; + } + if ((blk >= ext2fs_inode_table_loc(fs, i)) && + (blk < (ext2fs_inode_table_loc(fs, i) + + fs->inode_blocks_per_group))) { + /* + * If there are bad blocks in the inode table, + * the inode scan code will try to do + * something reasonable automatically. + */ + return 0; + } + first_block += fs->super->s_blocks_per_group; + } + /* + * If we've gotten to this point, then the only + * possibility is that the bad block inode meta data + * is using a bad block. + */ + if ((blk == p->inode->i_block[EXT2_IND_BLOCK]) || + (blk == p->inode->i_block[EXT2_DIND_BLOCK]) || + (blk == p->inode->i_block[EXT2_TIND_BLOCK])) { + p->bbcheck = 1; + if (fix_problem(ctx, PR_1_BBINODE_BAD_METABLOCK, pctx)) { + *block_nr = 0; + return BLOCK_CHANGED; + } + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return BLOCK_ABORT; + return 0; + } + + pctx->group = -1; + + /* Warn user that the block wasn't claimed */ + fix_problem(ctx, PR_1_PROGERR_CLAIMED_BLOCK, pctx); + + return 0; +} + +static void new_table_block(e2fsck_t ctx, blk64_t first_block, dgrp_t group, + const char *name, int num, blk64_t *new_block) +{ + ext2_filsys fs = ctx->fs; + dgrp_t last_grp; + blk64_t old_block = *new_block; + blk64_t last_block; + dgrp_t flexbg; + unsigned flexbg_size; + int i, is_flexbg; + char *buf; + struct problem_context pctx; + + clear_problem_context(&pctx); + + pctx.group = group; + pctx.blk = old_block; + pctx.str = name; + + /* + * For flex_bg filesystems, first try to allocate the metadata + * within the flex_bg, and if that fails then try finding the + * space anywhere in the filesystem. + */ + is_flexbg = ext2fs_has_feature_flex_bg(fs->super); + if (is_flexbg) { + flexbg_size = 1U << fs->super->s_log_groups_per_flex; + flexbg = group / flexbg_size; + first_block = ext2fs_group_first_block2(fs, + flexbg_size * flexbg); + last_grp = group | (flexbg_size - 1); + if (last_grp >= fs->group_desc_count) + last_grp = fs->group_desc_count - 1; + last_block = ext2fs_group_last_block2(fs, last_grp); + } else + last_block = ext2fs_group_last_block2(fs, group); + pctx.errcode = ext2fs_get_free_blocks2(fs, first_block, last_block, + num, ctx->block_found_map, + new_block); + if (is_flexbg && (pctx.errcode == EXT2_ET_BLOCK_ALLOC_FAIL)) + pctx.errcode = ext2fs_get_free_blocks2(fs, + fs->super->s_first_data_block, + ext2fs_blocks_count(fs->super), + num, ctx->block_found_map, new_block); + if (pctx.errcode) { + pctx.num = num; + fix_problem(ctx, PR_1_RELOC_BLOCK_ALLOCATE, &pctx); + ext2fs_unmark_valid(fs); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + pctx.errcode = ext2fs_get_mem(fs->blocksize, &buf); + if (pctx.errcode) { + fix_problem(ctx, PR_1_RELOC_MEMORY_ALLOCATE, &pctx); + ext2fs_unmark_valid(fs); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + ext2fs_mark_super_dirty(fs); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + pctx.blk2 = *new_block; + fix_problem(ctx, (old_block ? PR_1_RELOC_FROM_TO : + PR_1_RELOC_TO), &pctx); + pctx.blk2 = 0; + for (i = 0; i < num; i++) { + pctx.blk = i; + ext2fs_mark_block_bitmap2(ctx->block_found_map, (*new_block)+i); + if (old_block) { + pctx.errcode = io_channel_read_blk64(fs->io, + old_block + i, 1, buf); + if (pctx.errcode) + fix_problem(ctx, PR_1_RELOC_READ_ERR, &pctx); + pctx.blk = (*new_block) + i; + pctx.errcode = io_channel_write_blk64(fs->io, pctx.blk, + 1, buf); + } else { + pctx.blk = (*new_block) + i; + pctx.errcode = ext2fs_zero_blocks2(fs, pctx.blk, 1, + NULL, NULL); + } + + if (pctx.errcode) + fix_problem(ctx, PR_1_RELOC_WRITE_ERR, &pctx); + } + ext2fs_free_mem(&buf); +} + +/* + * This routine gets called at the end of pass 1 if bad blocks are + * detected in the superblock, group descriptors, inode_bitmaps, or + * block bitmaps. At this point, all of the blocks have been mapped + * out, so we can try to allocate new block(s) to replace the bad + * blocks. + */ +static void handle_fs_bad_blocks(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + dgrp_t i; + blk64_t first_block; + blk64_t new_blk; + + for (i = 0; i < fs->group_desc_count; i++) { + first_block = ext2fs_group_first_block2(fs, i); + + if (ctx->invalid_block_bitmap_flag[i]) { + new_blk = ext2fs_block_bitmap_loc(fs, i); + new_table_block(ctx, first_block, i, _("block bitmap"), + 1, &new_blk); + ext2fs_block_bitmap_loc_set(fs, i, new_blk); + } + if (ctx->invalid_inode_bitmap_flag[i]) { + new_blk = ext2fs_inode_bitmap_loc(fs, i); + new_table_block(ctx, first_block, i, _("inode bitmap"), + 1, &new_blk); + ext2fs_inode_bitmap_loc_set(fs, i, new_blk); + } + if (ctx->invalid_inode_table_flag[i]) { + new_blk = ext2fs_inode_table_loc(fs, i); + new_table_block(ctx, first_block, i, _("inode table"), + fs->inode_blocks_per_group, + &new_blk); + ext2fs_inode_table_loc_set(fs, i, new_blk); + ctx->flags |= E2F_FLAG_RESTART; + } + } + ctx->invalid_bitmaps = 0; +} + +/* + * This routine marks all blocks which are used by the superblock, + * group descriptors, inode bitmaps, and block bitmaps. + */ +static void mark_table_blocks(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t b; + dgrp_t i; + unsigned int j; + struct problem_context pctx; + + clear_problem_context(&pctx); + + for (i = 0; i < fs->group_desc_count; i++) { + pctx.group = i; + + ext2fs_reserve_super_and_bgd(fs, i, ctx->block_found_map); + ext2fs_reserve_super_and_bgd(fs, i, ctx->block_metadata_map); + + /* + * Mark the blocks used for the inode table + */ + if (ext2fs_inode_table_loc(fs, i)) { + for (j = 0, b = ext2fs_inode_table_loc(fs, i); + j < fs->inode_blocks_per_group; + j++, b++) { + if (ext2fs_test_block_bitmap2(ctx->block_found_map, + b)) { + pctx.blk = b; + if (!ctx->invalid_inode_table_flag[i] && + fix_problem(ctx, + PR_1_ITABLE_CONFLICT, &pctx)) { + ctx->invalid_inode_table_flag[i]++; + ctx->invalid_bitmaps++; + } + } else { + ext2fs_mark_block_bitmap2( + ctx->block_found_map, b); + ext2fs_mark_block_bitmap2( + ctx->block_metadata_map, b); + } + } + } + + /* + * Mark block used for the block bitmap + */ + if (ext2fs_block_bitmap_loc(fs, i)) { + if (ext2fs_test_block_bitmap2(ctx->block_found_map, + ext2fs_block_bitmap_loc(fs, i))) { + pctx.blk = ext2fs_block_bitmap_loc(fs, i); + if (fix_problem(ctx, PR_1_BB_CONFLICT, &pctx)) { + ctx->invalid_block_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + } else { + ext2fs_mark_block_bitmap2(ctx->block_found_map, + ext2fs_block_bitmap_loc(fs, i)); + ext2fs_mark_block_bitmap2(ctx->block_metadata_map, + ext2fs_block_bitmap_loc(fs, i)); + } + } + /* + * Mark block used for the inode bitmap + */ + if (ext2fs_inode_bitmap_loc(fs, i)) { + if (ext2fs_test_block_bitmap2(ctx->block_found_map, + ext2fs_inode_bitmap_loc(fs, i))) { + pctx.blk = ext2fs_inode_bitmap_loc(fs, i); + if (fix_problem(ctx, PR_1_IB_CONFLICT, &pctx)) { + ctx->invalid_inode_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + } else { + ext2fs_mark_block_bitmap2(ctx->block_metadata_map, + ext2fs_inode_bitmap_loc(fs, i)); + ext2fs_mark_block_bitmap2(ctx->block_found_map, + ext2fs_inode_bitmap_loc(fs, i)); + } + } + } +} + +/* + * These subroutines short circuits ext2fs_get_blocks and + * ext2fs_check_directory; we use them since we already have the inode + * structure, so there's no point in letting the ext2fs library read + * the inode again. + */ +static errcode_t pass1_get_blocks(ext2_filsys fs, ext2_ino_t ino, + blk_t *blocks) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + int i; + + if ((ino != ctx->stashed_ino) || !ctx->stashed_inode) + return EXT2_ET_CALLBACK_NOTHANDLED; + + for (i=0; i < EXT2_N_BLOCKS; i++) + blocks[i] = ctx->stashed_inode->i_block[i]; + return 0; +} + +static errcode_t pass1_read_inode(ext2_filsys fs, ext2_ino_t ino, + struct ext2_inode *inode) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + if ((ino != ctx->stashed_ino) || !ctx->stashed_inode) + return EXT2_ET_CALLBACK_NOTHANDLED; + *inode = *ctx->stashed_inode; + return 0; +} + +static errcode_t pass1_write_inode(ext2_filsys fs, ext2_ino_t ino, + struct ext2_inode *inode) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + if ((ino == ctx->stashed_ino) && ctx->stashed_inode && + (inode != ctx->stashed_inode)) + *ctx->stashed_inode = *inode; + return EXT2_ET_CALLBACK_NOTHANDLED; +} + +static errcode_t pass1_check_directory(ext2_filsys fs, ext2_ino_t ino) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + if ((ino != ctx->stashed_ino) || !ctx->stashed_inode) + return EXT2_ET_CALLBACK_NOTHANDLED; + + if (!LINUX_S_ISDIR(ctx->stashed_inode->i_mode)) + return EXT2_ET_NO_DIRECTORY; + return 0; +} + +static errcode_t e2fsck_get_alloc_block(ext2_filsys fs, blk64_t goal, + blk64_t *ret) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + errcode_t retval; + blk64_t new_block; + + if (ctx->block_found_map) { + retval = ext2fs_new_block2(fs, goal, ctx->block_found_map, + &new_block); + if (retval) + return retval; + if (fs->block_map) { + ext2fs_mark_block_bitmap2(fs->block_map, new_block); + ext2fs_mark_bb_dirty(fs); + } + } else { + if (!fs->block_map) { + retval = ext2fs_read_block_bitmap(fs); + if (retval) + return retval; + } + + retval = ext2fs_new_block2(fs, goal, fs->block_map, &new_block); + if (retval) + return retval; + } + + *ret = new_block; + return (0); +} + +static errcode_t e2fsck_new_range(ext2_filsys fs, int flags, blk64_t goal, + blk64_t len, blk64_t *pblk, blk64_t *plen) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + errcode_t retval; + + if (ctx->block_found_map) + return ext2fs_new_range(fs, flags, goal, len, + ctx->block_found_map, pblk, plen); + + if (!fs->block_map) { + retval = ext2fs_read_block_bitmap(fs); + if (retval) + return retval; + } + + return ext2fs_new_range(fs, flags, goal, len, fs->block_map, + pblk, plen); +} + +static void e2fsck_block_alloc_stats(ext2_filsys fs, blk64_t blk, int inuse) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + /* Never free a critical metadata block */ + if (ctx->block_found_map && + ctx->block_metadata_map && + inuse < 0 && + ext2fs_test_block_bitmap2(ctx->block_metadata_map, blk)) + return; + + if (ctx->block_found_map) { + if (inuse > 0) + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); + else + ext2fs_unmark_block_bitmap2(ctx->block_found_map, blk); + } +} + +static void e2fsck_block_alloc_stats_range(ext2_filsys fs, blk64_t blk, + blk_t num, int inuse) +{ + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + /* Never free a critical metadata block */ + if (ctx->block_found_map && + ctx->block_metadata_map && + inuse < 0 && + ext2fs_test_block_bitmap_range2(ctx->block_metadata_map, blk, num)) + return; + + if (ctx->block_found_map) { + if (inuse > 0) + ext2fs_mark_block_bitmap_range2(ctx->block_found_map, + blk, num); + else + ext2fs_unmark_block_bitmap_range2(ctx->block_found_map, + blk, num); + } +} + +void e2fsck_use_inode_shortcuts(e2fsck_t ctx, int use_shortcuts) +{ + ext2_filsys fs = ctx->fs; + + if (use_shortcuts) { + fs->get_blocks = pass1_get_blocks; + fs->check_directory = pass1_check_directory; + fs->read_inode = pass1_read_inode; + fs->write_inode = pass1_write_inode; + ctx->stashed_ino = 0; + } else { + fs->get_blocks = 0; + fs->check_directory = 0; + fs->read_inode = 0; + fs->write_inode = 0; + } +} + +void e2fsck_intercept_block_allocations(e2fsck_t ctx) +{ + ext2fs_set_alloc_block_callback(ctx->fs, e2fsck_get_alloc_block, 0); + ext2fs_set_block_alloc_stats_callback(ctx->fs, + e2fsck_block_alloc_stats, 0); + ext2fs_set_new_range_callback(ctx->fs, e2fsck_new_range, NULL); + ext2fs_set_block_alloc_stats_range_callback(ctx->fs, + e2fsck_block_alloc_stats_range, NULL); +} diff --git a/e2fsck/pass1b.c b/e2fsck/pass1b.c new file mode 100644 index 0000000..950af5b --- /dev/null +++ b/e2fsck/pass1b.c @@ -0,0 +1,1046 @@ +/* + * pass1b.c --- Pass #1b of e2fsck + * + * This file contains pass1B, pass1C, and pass1D of e2fsck. They are + * only invoked if pass 1 discovered blocks which are in use by more + * than one inode. + * + * Pass1B scans the data blocks of all the inodes again, generating a + * complete list of duplicate blocks and which inodes have claimed + * them. + * + * Pass1C does a tree-traversal of the filesystem, to determine the + * parent directories of these inodes. This step is necessary so that + * e2fsck can print out the pathnames of affected inodes. + * + * Pass1D is a reconciliation pass. For each inode with duplicate + * blocks, the user is prompted if s/he would like to clone the file + * (so that the file gets a fresh copy of the duplicated blocks) or + * simply to delete the file. + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + */ + +#include "config.h" +#include <time.h> +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#ifdef HAVE_INTTYPES_H +#include <inttypes.h> +#endif + +#ifndef HAVE_INTPTR_T +typedef long intptr_t; +#endif + +/* Needed for architectures where sizeof(int) != sizeof(void *) */ +#define INT_TO_VOIDPTR(val) ((void *)(intptr_t)(val)) +#define VOIDPTR_TO_INT(ptr) ((int)(intptr_t)(ptr)) + +#include <et/com_err.h> +#include "e2fsck.h" + +#include "problem.h" +#include "support/dict.h" + +/* Define an extension to the ext2 library's block count information */ +#define BLOCK_COUNT_EXTATTR (-5) + +struct cluster_el { + blk64_t cluster; + struct cluster_el *next; +}; + +struct inode_el { + ext2_ino_t inode; + struct inode_el *next; +}; + +struct dup_cluster { + int num_bad; + struct inode_el *inode_list; +}; + +/* + * This structure stores information about a particular inode which + * is sharing blocks with other inodes. This information is collected + * to display to the user, so that the user knows what files he or she + * is dealing with, when trying to decide how to resolve the conflict + * of multiply-claimed blocks. + */ +struct dup_inode { + ext2_ino_t dir; + int num_dupblocks; + struct ext2_inode_large inode; + struct cluster_el *cluster_list; +}; + +static int process_pass1b_block(ext2_filsys fs, blk64_t *blocknr, + e2_blkcnt_t blockcnt, blk64_t ref_blk, + int ref_offset, void *priv_data); +static void delete_file(e2fsck_t ctx, ext2_ino_t ino, + struct dup_inode *dp, char *block_buf); +static errcode_t clone_file(e2fsck_t ctx, ext2_ino_t ino, + struct dup_inode *dp, char* block_buf); +static int check_if_fs_block(e2fsck_t ctx, blk64_t block); +static int check_if_fs_cluster(e2fsck_t ctx, blk64_t cluster); + +static void pass1b(e2fsck_t ctx, char *block_buf); +static void pass1c(e2fsck_t ctx, char *block_buf); +static void pass1d(e2fsck_t ctx, char *block_buf); + +static int dup_inode_count = 0; +static int dup_inode_founddir = 0; + +static dict_t clstr_dict, ino_dict; + +static ext2fs_inode_bitmap inode_dup_map; + +static int dict_int_cmp(const void *cmp_ctx EXT2FS_ATTR((unused)), + const void *a, const void *b) +{ + intptr_t ia, ib; + + ia = (intptr_t)a; + ib = (intptr_t)b; + + return (ia-ib); +} + +/* + * Add a duplicate block record + */ +static void add_dupe(e2fsck_t ctx, ext2_ino_t ino, blk64_t cluster, + struct ext2_inode_large *inode) +{ + dnode_t *n; + struct dup_cluster *db; + struct dup_inode *di; + struct cluster_el *cluster_el; + struct inode_el *ino_el; + + n = dict_lookup(&clstr_dict, INT_TO_VOIDPTR(cluster)); + if (n) + db = (struct dup_cluster *) dnode_get(n); + else { + db = (struct dup_cluster *) e2fsck_allocate_memory(ctx, + sizeof(struct dup_cluster), "duplicate cluster header"); + db->num_bad = 0; + db->inode_list = 0; + dict_alloc_insert(&clstr_dict, INT_TO_VOIDPTR(cluster), db); + } + ino_el = (struct inode_el *) e2fsck_allocate_memory(ctx, + sizeof(struct inode_el), "inode element"); + ino_el->inode = ino; + ino_el->next = db->inode_list; + db->inode_list = ino_el; + db->num_bad++; + + n = dict_lookup(&ino_dict, INT_TO_VOIDPTR(ino)); + if (n) + di = (struct dup_inode *) dnode_get(n); + else { + di = (struct dup_inode *) e2fsck_allocate_memory(ctx, + sizeof(struct dup_inode), "duplicate inode header"); + if (ino == EXT2_ROOT_INO) { + di->dir = EXT2_ROOT_INO; + dup_inode_founddir++; + } else + di->dir = 0; + + di->num_dupblocks = 0; + di->cluster_list = 0; + di->inode = *inode; + dict_alloc_insert(&ino_dict, INT_TO_VOIDPTR(ino), di); + } + cluster_el = (struct cluster_el *) e2fsck_allocate_memory(ctx, + sizeof(struct cluster_el), "cluster element"); + cluster_el->cluster = cluster; + cluster_el->next = di->cluster_list; + di->cluster_list = cluster_el; + di->num_dupblocks++; +} + +/* + * Free a duplicate inode record + */ +static void inode_dnode_free(dnode_t *node, + void *context EXT2FS_ATTR((unused))) +{ + struct dup_inode *di; + struct cluster_el *p, *next; + + di = (struct dup_inode *) dnode_get(node); + for (p = di->cluster_list; p; p = next) { + next = p->next; + ext2fs_free_mem(&p); + } + ext2fs_free_mem(&di); + ext2fs_free_mem(&node); +} + +/* + * Free a duplicate cluster record + */ +static void cluster_dnode_free(dnode_t *node, + void *context EXT2FS_ATTR((unused))) +{ + struct dup_cluster *dc; + struct inode_el *p, *next; + + dc = (struct dup_cluster *) dnode_get(node); + for (p = dc->inode_list; p; p = next) { + next = p->next; + ext2fs_free_mem(&p); + } + ext2fs_free_mem(&dc); + ext2fs_free_mem(&node); +} + + +/* + * Main procedure for handling duplicate blocks + */ +void e2fsck_pass1_dupblocks(e2fsck_t ctx, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + struct problem_context pctx; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + + clear_problem_context(&pctx); + + pctx.errcode = e2fsck_allocate_inode_bitmap(fs, + _("multiply claimed inode map"), + EXT2FS_BMAP64_RBTREE, "inode_dup_map", + &inode_dup_map); + if (pctx.errcode) { + fix_problem(ctx, PR_1B_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + dict_init(&ino_dict, DICTCOUNT_T_MAX, dict_int_cmp); + dict_init(&clstr_dict, DICTCOUNT_T_MAX, dict_int_cmp); + dict_set_allocator(&ino_dict, NULL, inode_dnode_free, NULL); + dict_set_allocator(&clstr_dict, NULL, cluster_dnode_free, NULL); + + init_resource_track(&rtrack, ctx->fs->io); + pass1b(ctx, block_buf); + print_resource_track(ctx, "Pass 1b", &rtrack, ctx->fs->io); + + init_resource_track(&rtrack, ctx->fs->io); + pass1c(ctx, block_buf); + print_resource_track(ctx, "Pass 1c", &rtrack, ctx->fs->io); + + init_resource_track(&rtrack, ctx->fs->io); + pass1d(ctx, block_buf); + print_resource_track(ctx, "Pass 1d", &rtrack, ctx->fs->io); + + if (ext2fs_has_feature_shared_blocks(ctx->fs->super) && + (ctx->options & E2F_OPT_UNSHARE_BLOCKS)) { + /* + * If we successfully managed to unshare all blocks, unset the + * shared block feature. + */ + blk64_t next; + int result = ext2fs_find_first_set_block_bitmap2( + ctx->block_dup_map, + ctx->fs->super->s_first_data_block, + ext2fs_blocks_count(ctx->fs->super) - 1, + &next); + if (result == ENOENT && !(ctx->options & E2F_OPT_NO)) { + ext2fs_clear_feature_shared_blocks(ctx->fs->super); + ext2fs_mark_super_dirty(ctx->fs); + } + } + + /* + * Time to free all of the accumulated data structures that we + * don't need anymore. + */ + dict_free_nodes(&ino_dict); + dict_free_nodes(&clstr_dict); + ext2fs_free_inode_bitmap(inode_dup_map); +} + +/* + * Scan the inodes looking for inodes that contain duplicate blocks. + */ +struct process_block_struct { + e2fsck_t ctx; + ext2_ino_t ino; + int dup_blocks; + blk64_t cur_cluster, phys_cluster; + blk64_t last_blk; + struct ext2_inode_large *inode; + struct problem_context *pctx; +}; + +static void pass1b(e2fsck_t ctx, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t ino = 0; + struct ext2_inode_large inode; + ext2_inode_scan scan; + struct process_block_struct pb; + struct problem_context pctx; + problem_t op; + + clear_problem_context(&pctx); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_1B_PASS_HEADER, &pctx); + pctx.errcode = ext2fs_open_inode_scan(fs, ctx->inode_buffer_blocks, + &scan); + if (pctx.errcode) { + fix_problem(ctx, PR_1B_ISCAN_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + ctx->stashed_inode = EXT2_INODE(&inode); + pb.ctx = ctx; + pb.pctx = &pctx; + pctx.str = "pass1b"; + while (1) { + if (ino % (fs->super->s_inodes_per_group * 4) == 1) { + if (e2fsck_mmp_update(fs)) + fatal_error(ctx, 0); + } + pctx.errcode = ext2fs_get_next_inode_full(scan, &ino, + EXT2_INODE(&inode), sizeof(inode)); + if (pctx.errcode == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE) + continue; + if (pctx.errcode) { + pctx.ino = ino; + fix_problem(ctx, PR_1B_ISCAN_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + if (!ino) + break; + pctx.ino = ctx->stashed_ino = ino; + if ((ino != EXT2_BAD_INO) && + !ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino)) + continue; + + pb.ino = ino; + pb.dup_blocks = 0; + pb.inode = &inode; + pb.cur_cluster = ~0; + pb.phys_cluster = ~0; + pb.last_blk = 0; + pb.pctx->blk = pb.pctx->blk2 = 0; + + if (ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&inode)) || + (ino == EXT2_BAD_INO)) + pctx.errcode = ext2fs_block_iterate3(fs, ino, + BLOCK_FLAG_READ_ONLY, block_buf, + process_pass1b_block, &pb); + /* If the feature is not set, attrs will be cleared later anyway */ + if (ext2fs_has_feature_xattr(fs->super) && + ext2fs_file_acl_block(fs, EXT2_INODE(&inode))) { + blk64_t blk = ext2fs_file_acl_block(fs, EXT2_INODE(&inode)); + process_pass1b_block(fs, &blk, + BLOCK_COUNT_EXTATTR, 0, 0, &pb); + ext2fs_file_acl_block_set(fs, EXT2_INODE(&inode), blk); + } + if (pb.dup_blocks) { + if (ino != EXT2_BAD_INO) { + op = pctx.blk == pctx.blk2 ? + PR_1B_DUP_BLOCK : PR_1B_DUP_RANGE; + fix_problem(ctx, op, pb.pctx); + } + end_problem_latch(ctx, PR_LATCH_DBLOCK); + if (ino >= EXT2_FIRST_INODE(fs->super) || + ino == EXT2_ROOT_INO) + dup_inode_count++; + } + if (pctx.errcode) + fix_problem(ctx, PR_1B_BLOCK_ITERATE, &pctx); + } + ext2fs_close_inode_scan(scan); + e2fsck_use_inode_shortcuts(ctx, 0); +} + +static int process_pass1b_block(ext2_filsys fs EXT2FS_ATTR((unused)), + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_blk EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *p; + e2fsck_t ctx; + blk64_t lc, pc; + problem_t op; + + if (*block_nr == 0) + return 0; + p = (struct process_block_struct *) priv_data; + ctx = p->ctx; + lc = EXT2FS_B2C(fs, blockcnt); + pc = EXT2FS_B2C(fs, *block_nr); + + if (!ext2fs_test_block_bitmap2(ctx->block_dup_map, *block_nr)) + goto finish; + + /* OK, this is a duplicate block */ + if (p->ino != EXT2_BAD_INO) { + if (p->last_blk + 1 != *block_nr) { + if (p->last_blk) { + op = p->pctx->blk == p->pctx->blk2 ? + PR_1B_DUP_BLOCK : + PR_1B_DUP_RANGE; + fix_problem(ctx, op, p->pctx); + } + p->pctx->blk = *block_nr; + } + p->pctx->blk2 = *block_nr; + p->last_blk = *block_nr; + } + p->dup_blocks++; + ext2fs_mark_inode_bitmap2(inode_dup_map, p->ino); + + /* + * Qualifications for submitting a block for duplicate processing: + * It's an extent/indirect block (and has a negative logical offset); + * we've crossed a logical cluster boundary; or the physical cluster + * suddenly changed, which indicates that blocks in a logical cluster + * are mapped to multiple physical clusters. + */ + if (blockcnt < 0 || lc != p->cur_cluster || pc != p->phys_cluster) + add_dupe(ctx, p->ino, EXT2FS_B2C(fs, *block_nr), p->inode); + +finish: + p->cur_cluster = lc; + p->phys_cluster = pc; + return 0; +} + +/* + * Pass 1c: Scan directories for inodes with duplicate blocks. This + * is used so that we can print pathnames when prompting the user for + * what to do. + */ +struct search_dir_struct { + int count; + ext2_ino_t first_inode; + ext2_ino_t max_inode; +}; + +static int search_dirent_proc(ext2_ino_t dir, int entry, + struct ext2_dir_entry *dirent, + int offset EXT2FS_ATTR((unused)), + int blocksize EXT2FS_ATTR((unused)), + char *buf EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct search_dir_struct *sd; + struct dup_inode *p; + dnode_t *n; + + sd = (struct search_dir_struct *) priv_data; + + if (dirent->inode > sd->max_inode) + /* Should abort this inode, but not everything */ + return 0; + + if ((dirent->inode < sd->first_inode) || (entry < DIRENT_OTHER_FILE) || + !ext2fs_test_inode_bitmap2(inode_dup_map, dirent->inode)) + return 0; + + n = dict_lookup(&ino_dict, INT_TO_VOIDPTR(dirent->inode)); + if (!n) + return 0; + p = (struct dup_inode *) dnode_get(n); + if (!p->dir) { + p->dir = dir; + sd->count--; + } + + return(sd->count ? 0 : DIRENT_ABORT); +} + + +static void pass1c(e2fsck_t ctx, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + struct search_dir_struct sd; + struct problem_context pctx; + + clear_problem_context(&pctx); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_1C_PASS_HEADER, &pctx); + + /* + * Search through all directories to translate inodes to names + * (by searching for the containing directory for that inode.) + */ + sd.count = dup_inode_count - dup_inode_founddir; + sd.first_inode = EXT2_FIRST_INODE(fs->super); + sd.max_inode = fs->super->s_inodes_count; + ext2fs_dblist_dir_iterate(fs->dblist, 0, block_buf, + search_dirent_proc, &sd); +} + +static void pass1d(e2fsck_t ctx, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + struct dup_inode *p, *t; + struct dup_cluster *q; + ext2_ino_t *shared, ino; + int shared_len; + int i; + int file_ok; + int meta_data = 0; + struct problem_context pctx; + dnode_t *n, *m; + struct cluster_el *s; + struct inode_el *r; + + clear_problem_context(&pctx); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_1D_PASS_HEADER, &pctx); + e2fsck_read_bitmaps(ctx); + + pctx.num = dup_inode_count; /* dict_count(&ino_dict); */ + fix_problem(ctx, PR_1D_NUM_DUP_INODES, &pctx); + shared = (ext2_ino_t *) e2fsck_allocate_memory(ctx, + sizeof(ext2_ino_t) * dict_count(&ino_dict), + "Shared inode list"); + for (n = dict_first(&ino_dict); n; n = dict_next(&ino_dict, n)) { + p = (struct dup_inode *) dnode_get(n); + shared_len = 0; + file_ok = 1; + ino = (ext2_ino_t)VOIDPTR_TO_INT(dnode_getkey(n)); + if (ino == EXT2_BAD_INO || ino == EXT2_RESIZE_INO) + continue; + + /* + * Find all of the inodes which share blocks with this + * one. First we find all of the duplicate blocks + * belonging to this inode, and then search each block + * get the list of inodes, and merge them together. + */ + for (s = p->cluster_list; s; s = s->next) { + m = dict_lookup(&clstr_dict, + INT_TO_VOIDPTR(s->cluster)); + if (!m) + continue; /* Should never happen... */ + q = (struct dup_cluster *) dnode_get(m); + if (q->num_bad > 1) + file_ok = 0; + if (check_if_fs_cluster(ctx, s->cluster)) { + file_ok = 0; + meta_data = 1; + } + + /* + * Add all inodes used by this block to the + * shared[] --- which is a unique list, so + * if an inode is already in shared[], don't + * add it again. + */ + for (r = q->inode_list; r; r = r->next) { + if (r->inode == ino) + continue; + for (i = 0; i < shared_len; i++) + if (shared[i] == r->inode) + break; + if (i == shared_len) { + shared[shared_len++] = r->inode; + } + } + } + + /* + * Report the inode that we are working on + */ + pctx.inode = EXT2_INODE(&p->inode); + pctx.ino = ino; + pctx.dir = p->dir; + pctx.blkcount = p->num_dupblocks; + pctx.num = meta_data ? shared_len+1 : shared_len; + fix_problem(ctx, PR_1D_DUP_FILE, &pctx); + pctx.blkcount = 0; + pctx.num = 0; + + if (meta_data) + fix_problem(ctx, PR_1D_SHARE_METADATA, &pctx); + + for (i = 0; i < shared_len; i++) { + m = dict_lookup(&ino_dict, INT_TO_VOIDPTR(shared[i])); + if (!m) + continue; /* should never happen */ + t = (struct dup_inode *) dnode_get(m); + /* + * Report the inode that we are sharing with + */ + pctx.inode = EXT2_INODE(&t->inode); + pctx.ino = shared[i]; + pctx.dir = t->dir; + fix_problem(ctx, PR_1D_DUP_FILE_LIST, &pctx); + } + /* + * Even if the file shares blocks with itself, we still need to + * clone the blocks. + */ + if (file_ok && (meta_data ? shared_len+1 : shared_len) != 0) { + fix_problem(ctx, PR_1D_DUP_BLOCKS_DEALT, &pctx); + continue; + } + if ((ctx->options & E2F_OPT_UNSHARE_BLOCKS) || + fix_problem(ctx, PR_1D_CLONE_QUESTION, &pctx)) { + pctx.errcode = clone_file(ctx, ino, p, block_buf); + if (pctx.errcode) + fix_problem(ctx, PR_1D_CLONE_ERROR, &pctx); + else + continue; + } + /* + * Note: When unsharing blocks, we don't prompt to delete + * files. If the clone operation fails than the unshare + * operation should fail too. + */ + if (!(ctx->options & E2F_OPT_UNSHARE_BLOCKS) && + fix_problem(ctx, PR_1D_DELETE_QUESTION, &pctx)) + delete_file(ctx, ino, p, block_buf); + else + ext2fs_unmark_valid(fs); + } + ext2fs_free_mem(&shared); +} + +/* + * Drop the refcount on the dup_block structure, and clear the entry + * in the block_dup_map if appropriate. + */ +static void decrement_badcount(e2fsck_t ctx, blk64_t block, + struct dup_cluster *p) +{ + p->num_bad--; + if (p->num_bad <= 0 || + (p->num_bad == 1 && !check_if_fs_block(ctx, block))) { + if (check_if_fs_cluster(ctx, EXT2FS_B2C(ctx->fs, block))) + return; + ext2fs_unmark_block_bitmap2(ctx->block_dup_map, block); + } +} + +static int delete_file_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *pb; + struct dup_cluster *p; + dnode_t *n; + e2fsck_t ctx; + blk64_t c, lc; + + pb = (struct process_block_struct *) priv_data; + ctx = pb->ctx; + + if (*block_nr == 0) + return 0; + + c = EXT2FS_B2C(fs, *block_nr); + lc = EXT2FS_B2C(fs, blockcnt); + if (ext2fs_test_block_bitmap2(ctx->block_dup_map, *block_nr)) { + n = dict_lookup(&clstr_dict, INT_TO_VOIDPTR(c)); + if (n) { + if (lc != pb->cur_cluster) { + p = (struct dup_cluster *) dnode_get(n); + decrement_badcount(ctx, *block_nr, p); + pb->dup_blocks++; + } + } else + com_err("delete_file_block", 0, + _("internal error: can't find dup_blk for %llu\n"), + (unsigned long long) *block_nr); + } else { + if ((*block_nr % EXT2FS_CLUSTER_RATIO(ctx->fs)) == 0) + ext2fs_block_alloc_stats2(fs, *block_nr, -1); + pb->dup_blocks++; + } + pb->cur_cluster = lc; + + return 0; +} + +static void delete_file(e2fsck_t ctx, ext2_ino_t ino, + struct dup_inode *dp, char* block_buf) +{ + ext2_filsys fs = ctx->fs; + struct process_block_struct pb; + struct problem_context pctx; + unsigned int count; + + clear_problem_context(&pctx); + pctx.ino = pb.ino = ino; + pb.dup_blocks = 0; + pb.ctx = ctx; + pctx.str = "delete_file"; + pb.cur_cluster = ~0; + + if (ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&dp->inode))) + pctx.errcode = ext2fs_block_iterate3(fs, ino, + BLOCK_FLAG_READ_ONLY, + block_buf, + delete_file_block, &pb); + if (pctx.errcode) + fix_problem(ctx, PR_1B_BLOCK_ITERATE, &pctx); + if (ctx->inode_bad_map) + ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino); + if (ctx->inode_reg_map) + ext2fs_unmark_inode_bitmap2(ctx->inode_reg_map, ino); + ext2fs_unmark_inode_bitmap2(ctx->inode_dir_map, ino); + ext2fs_unmark_inode_bitmap2(ctx->inode_used_map, ino); + ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(dp->inode.i_mode)); + quota_data_sub(ctx->qctx, &dp->inode, ino, + pb.dup_blocks * fs->blocksize); + quota_data_inodes(ctx->qctx, &dp->inode, ino, -1); + + /* Inode may have changed by block_iterate, so reread it */ + e2fsck_read_inode_full(ctx, ino, EXT2_INODE(&dp->inode), + sizeof(dp->inode), "delete_file"); + e2fsck_clear_inode(ctx, ino, EXT2_INODE(&dp->inode), 0, "delete_file"); + if (ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode)) && + ext2fs_has_feature_xattr(fs->super)) { + blk64_t file_acl_block = ext2fs_file_acl_block(fs, + EXT2_INODE(&dp->inode)); + + count = 1; + pctx.errcode = ext2fs_adjust_ea_refcount3(fs, file_acl_block, + block_buf, -1, &count, ino); + if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) { + pctx.errcode = 0; + count = 1; + } + if (pctx.errcode) { + pctx.blk = file_acl_block; + fix_problem(ctx, PR_1B_ADJ_EA_REFCOUNT, &pctx); + } + /* + * If the count is zero, then arrange to have the + * block deleted. If the block is in the block_dup_map, + * also call delete_file_block since it will take care + * of keeping the accounting straight. + */ + if ((count == 0) || + ext2fs_test_block_bitmap2(ctx->block_dup_map, + file_acl_block)) { + delete_file_block(fs, &file_acl_block, + BLOCK_COUNT_EXTATTR, 0, 0, &pb); + ext2fs_file_acl_block_set(fs, EXT2_INODE(&dp->inode), + file_acl_block); + quota_data_sub(ctx->qctx, &dp->inode, ino, + fs->blocksize); + } + } +} + +struct clone_struct { + errcode_t errcode; + blk64_t dup_cluster; + blk64_t alloc_block; + ext2_ino_t dir, ino; + char *buf; + e2fsck_t ctx; + struct ext2_inode_large *inode; + + struct dup_cluster *save_dup_cluster; + blk64_t save_blocknr; +}; + +/* + * Decrement the bad count *after* we've shown that (a) we can allocate a + * replacement block and (b) remap the file blocks. Unfortunately, there's no + * way to find out if the remap succeeded until either the next + * clone_file_block() call (an error when remapping the block after returning + * BLOCK_CHANGED will halt the iteration) or after block_iterate() returns. + * Otherwise, it's possible that we decrease the badcount once in preparation + * to remap, then the remap fails (either we can't find a replacement block or + * we have to split the extent tree and can't find a new extent block), so we + * delete the file, which decreases the badcount again. + */ +static void deferred_dec_badcount(struct clone_struct *cs) +{ + if (!cs->save_dup_cluster) + return; + decrement_badcount(cs->ctx, cs->save_blocknr, cs->save_dup_cluster); + cs->save_dup_cluster = NULL; +} + +static int clone_file_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct dup_cluster *p = NULL; + blk64_t new_block; + errcode_t retval; + struct clone_struct *cs = (struct clone_struct *) priv_data; + dnode_t *n; + e2fsck_t ctx; + blk64_t c; + int is_meta = 0; + int should_write = 1; + + ctx = cs->ctx; + deferred_dec_badcount(cs); + + if (*block_nr == 0) + return 0; + + if (ext2fs_has_feature_shared_blocks(ctx->fs->super) && + (ctx->options & E2F_OPT_UNSHARE_BLOCKS) && + (ctx->options & E2F_OPT_NO)) + should_write = 0; + + c = EXT2FS_B2C(fs, blockcnt); + + if (c == cs->dup_cluster && cs->alloc_block) { + new_block = cs->alloc_block; + goto got_block; + } + + if (ext2fs_test_block_bitmap2(ctx->block_dup_map, *block_nr)) { + n = dict_lookup(&clstr_dict, + INT_TO_VOIDPTR(EXT2FS_B2C(fs, *block_nr))); + if (!n) { + com_err("clone_file_block", 0, + _("internal error: can't find dup_blk for %llu\n"), + (unsigned long long) *block_nr); + return 0; + } + + p = (struct dup_cluster *) dnode_get(n); + + cs->dup_cluster = c; + /* + * Let's try an implied cluster allocation. If we get the same + * cluster back, then we need to find a new block; otherwise, + * we're merely fixing the problem of one logical cluster being + * mapped to multiple physical clusters. + */ + new_block = 0; + retval = ext2fs_map_cluster_block(fs, cs->ino, + EXT2_INODE(cs->inode), + blockcnt, &new_block); + if (retval == 0 && new_block != 0 && + EXT2FS_B2C(ctx->fs, new_block) != + EXT2FS_B2C(ctx->fs, *block_nr)) + goto cluster_alloc_ok; + retval = ext2fs_new_block2(fs, 0, ctx->block_found_map, + &new_block); + if (retval) { + cs->errcode = retval; + return BLOCK_ABORT; + } + if (ext2fs_has_feature_shared_blocks(fs->super)) { + /* + * Update the block stats so we don't get a prompt to fix block + * counts in the final pass. + */ + ext2fs_block_alloc_stats2(fs, new_block, +1); + } +cluster_alloc_ok: + cs->alloc_block = new_block; + + got_block: + new_block &= ~EXT2FS_CLUSTER_MASK(fs); + new_block += EXT2FS_CLUSTER_MASK(fs) & blockcnt; + if (cs->dir && (blockcnt >= 0)) { + retval = ext2fs_set_dir_block2(fs->dblist, + cs->dir, new_block, blockcnt); + if (retval) { + cs->errcode = retval; + return BLOCK_ABORT; + } + } +#if 0 + printf("Cloning block #%lld from %llu to %llu\n", + blockcnt, (unsigned long long) *block_nr, + (unsigned long long) new_block); +#endif + retval = io_channel_read_blk64(fs->io, *block_nr, 1, cs->buf); + if (retval) { + cs->errcode = retval; + return BLOCK_ABORT; + } + if (should_write) { + retval = io_channel_write_blk64(fs->io, new_block, 1, cs->buf); + if (retval) { + cs->errcode = retval; + return BLOCK_ABORT; + } + } + if (check_if_fs_cluster(ctx, EXT2FS_B2C(fs, *block_nr))) + is_meta = 1; + cs->save_dup_cluster = (is_meta ? NULL : p); + cs->save_blocknr = *block_nr; + *block_nr = new_block; + ext2fs_mark_block_bitmap2(ctx->block_found_map, new_block); + ext2fs_mark_block_bitmap2(fs->block_map, new_block); + + if (!should_write) { + /* Don't try to change extent information; we want e2fsck to + * return success. + */ + return 0; + } + return BLOCK_CHANGED; + } + return 0; +} + +static errcode_t clone_file(e2fsck_t ctx, ext2_ino_t ino, + struct dup_inode *dp, char* block_buf) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + struct clone_struct cs; + struct problem_context pctx; + blk64_t blk, new_blk; + dnode_t *n; + struct inode_el *ino_el; + struct dup_cluster *dc; + struct dup_inode *di; + + clear_problem_context(&pctx); + cs.errcode = 0; + cs.dir = 0; + cs.dup_cluster = ~0; + cs.alloc_block = 0; + cs.ctx = ctx; + cs.ino = ino; + cs.inode = &dp->inode; + cs.save_dup_cluster = NULL; + cs.save_blocknr = 0; + retval = ext2fs_get_mem(fs->blocksize, &cs.buf); + if (retval) + return retval; + + if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino)) + cs.dir = ino; + + pctx.ino = ino; + pctx.str = "clone_file"; + if (ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&dp->inode))) + pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf, + clone_file_block, &cs); + deferred_dec_badcount(&cs); + ext2fs_mark_bb_dirty(fs); + if (pctx.errcode) { + fix_problem(ctx, PR_1B_BLOCK_ITERATE, &pctx); + retval = pctx.errcode; + goto errout; + } + if (cs.errcode) { + com_err("clone_file", cs.errcode, "%s", + _("returned from clone_file_block")); + retval = cs.errcode; + goto errout; + } + /* The inode may have changed on disk, so we have to re-read it */ + e2fsck_read_inode_full(ctx, ino, EXT2_INODE(&dp->inode), + sizeof(dp->inode), "clone file EA"); + blk = ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode)); + new_blk = blk; + if (blk && (clone_file_block(fs, &new_blk, + BLOCK_COUNT_EXTATTR, 0, 0, &cs) == + BLOCK_CHANGED)) { + ext2fs_file_acl_block_set(fs, EXT2_INODE(&dp->inode), new_blk); + e2fsck_write_inode_full(ctx, ino, EXT2_INODE(&dp->inode), + sizeof(dp->inode), "clone file EA"); + /* + * If we cloned the EA block, find all other inodes + * which referred to that EA block, and modify + * them to point to the new EA block. + */ + n = dict_lookup(&clstr_dict, + INT_TO_VOIDPTR(EXT2FS_B2C(fs, blk))); + if (!n) { + com_err("clone_file", 0, + _("internal error: couldn't lookup EA " + "block record for %llu"), + (unsigned long long) blk); + retval = 0; /* OK to stumble on... */ + goto errout; + } + dc = (struct dup_cluster *) dnode_get(n); + for (ino_el = dc->inode_list; ino_el; ino_el = ino_el->next) { + if (ino_el->inode == ino) + continue; + n = dict_lookup(&ino_dict, INT_TO_VOIDPTR(ino_el->inode)); + if (!n) { + com_err("clone_file", 0, + _("internal error: couldn't lookup EA " + "inode record for %u"), + ino_el->inode); + retval = 0; /* OK to stumble on... */ + goto errout; + } + di = (struct dup_inode *) dnode_get(n); + if (ext2fs_file_acl_block(fs, + EXT2_INODE(&di->inode)) == blk) { + ext2fs_file_acl_block_set(fs, + EXT2_INODE(&di->inode), + ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode))); + e2fsck_write_inode_full(ctx, ino_el->inode, + EXT2_INODE(&di->inode), + sizeof(di->inode), "clone file EA"); + decrement_badcount(ctx, blk, dc); + } + } + } + retval = 0; +errout: + ext2fs_free_mem(&cs.buf); + return retval; +} + +/* + * This routine returns 1 if a block overlaps with one of the superblocks, + * group descriptors, inode bitmaps, or block bitmaps. + */ +static int check_if_fs_block(e2fsck_t ctx, blk64_t block) +{ + return ext2fs_test_block_bitmap2(ctx->block_metadata_map, block); +} + +/* + * This routine returns 1 if a cluster overlaps with one of the superblocks, + * group descriptors, inode bitmaps, or block bitmaps. + */ +static int check_if_fs_cluster(e2fsck_t ctx, blk64_t cluster) +{ + ext2_filsys fs = ctx->fs; + blk64_t block = EXT2FS_C2B(fs, cluster); + int i; + + for (i = 0; i < EXT2FS_CLUSTER_RATIO(fs); i++) { + if (ext2fs_test_block_bitmap2(ctx->block_metadata_map, + block + i)) + return 1; + } + + return 0; +} diff --git a/e2fsck/pass2.c b/e2fsck/pass2.c new file mode 100644 index 0000000..410edd1 --- /dev/null +++ b/e2fsck/pass2.c @@ -0,0 +1,2171 @@ +/* + * pass2.c --- check directory structure + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * Pass 2 of e2fsck iterates through all active directory inodes, and + * applies to following tests to each directory entry in the directory + * blocks in the inodes: + * + * - The length of the directory entry (rec_len) should be at + * least 8 bytes, and no more than the remaining space + * left in the directory block. + * - The length of the name in the directory entry (name_len) + * should be less than (rec_len - 8). + * - The inode number in the directory entry should be within + * legal bounds. + * - The inode number should refer to a in-use inode. + * - The first entry should be '.', and its inode should be + * the inode of the directory. + * - The second entry should be '..'. + * + * To minimize disk seek time, the directory blocks are processed in + * sorted order of block numbers. + * + * Pass 2 also collects the following information: + * - The inode numbers of the subdirectories for each directory. + * + * Pass 2 relies on the following information from previous passes: + * - The directory information collected in pass 1. + * - The inode_used_map bitmap + * - The inode_bad_map bitmap + * - The inode_dir_map bitmap + * - The encrypted_file_info + * - The inode_casefold_map bitmap + * + * Pass 2 frees the following data structures + * - The inode_bad_map bitmap + * - The inode_reg_map bitmap + * - The encrypted_file_info + * - The inode_casefold_map bitmap + */ + +#define _GNU_SOURCE 1 /* get strnlen() */ +#include "config.h" +#include <string.h> + +#include "e2fsck.h" +#include "problem.h" +#include "support/dict.h" + +#ifdef NO_INLINE_FUNCS +#define _INLINE_ +#else +#define _INLINE_ inline +#endif + +/* #define DX_DEBUG */ + +/* + * Keeps track of how many times an inode is referenced. + */ +static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf); +static int check_dir_block2(ext2_filsys fs, + struct ext2_db_entry2 *dir_blocks_info, + void *priv_data); +static int check_dir_block(ext2_filsys fs, + struct ext2_db_entry2 *dir_blocks_info, + void *priv_data); +static int allocate_dir_block(e2fsck_t ctx, + struct ext2_db_entry2 *dir_blocks_info, + char *buf, struct problem_context *pctx); +static void clear_htree(e2fsck_t ctx, ext2_ino_t ino); +static short htree_depth(struct dx_dir_info *dx_dir, + struct dx_dirblock_info *dx_db); +static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b); + +struct check_dir_struct { + char *buf; + struct problem_context pctx; + int count, max; + e2fsck_t ctx; + unsigned long long list_offset; + unsigned long long ra_entries; + unsigned long long next_ra_off; +}; + +static void update_parents(struct dx_dir_info *dx_dir, int type) +{ + struct dx_dirblock_info *dx_db, *dx_parent, *dx_previous; + blk_t b; + + for (b = 0, dx_db = dx_dir->dx_block; + b < dx_dir->numblocks; + b++, dx_db++) { + dx_parent = &dx_dir->dx_block[dx_db->parent]; + if (dx_db->type != type) + continue; + + /* + * XXX Make sure dx_parent->min_hash > dx_db->min_hash + */ + if (dx_db->flags & DX_FLAG_FIRST) { + dx_parent->min_hash = dx_db->min_hash; + if (dx_parent->previous) { + dx_previous = + &dx_dir->dx_block[dx_parent->previous]; + dx_previous->node_max_hash = + dx_parent->min_hash; + } + } + /* + * XXX Make sure dx_parent->max_hash < dx_db->max_hash + */ + if (dx_db->flags & DX_FLAG_LAST) { + dx_parent->max_hash = dx_db->max_hash; + } + } +} + +void e2fsck_pass2(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + ext2_filsys fs = ctx->fs; + char *buf = NULL; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct check_dir_struct cd; + struct dx_dir_info *dx_dir; + struct dx_dirblock_info *dx_db; + blk_t b; + ext2_ino_t i; + short depth; + problem_t code; + int bad_dir; + int (*check_dir_func)(ext2_filsys fs, + struct ext2_db_entry2 *dir_blocks_info, + void *priv_data); + + init_resource_track(&rtrack, ctx->fs->io); + clear_problem_context(&cd.pctx); + +#ifdef MTRACE + mtrace_print("Pass 2"); +#endif + + fs->flags |= EXT2_FLAG_IGNORE_SWAP_DIRENT; + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_2_PASS_HEADER, &cd.pctx); + + cd.pctx.errcode = e2fsck_setup_icount(ctx, "inode_count", + EXT2_ICOUNT_OPT_INCREMENT, + ctx->inode_link_info, &ctx->inode_count); + if (cd.pctx.errcode) { + fix_problem(ctx, PR_2_ALLOCATE_ICOUNT, &cd.pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto cleanup; + } + buf = (char *) e2fsck_allocate_memory(ctx, 2*fs->blocksize, + "directory scan buffer"); + + /* + * Set up the parent pointer for the root directory, if + * present. (If the root directory is not present, we will + * create it in pass 3.) + */ + (void) e2fsck_dir_info_set_parent(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO); + + cd.buf = buf; + cd.ctx = ctx; + cd.count = 1; + cd.max = ext2fs_dblist_count2(fs->dblist); + cd.list_offset = 0; + cd.ra_entries = ctx->readahead_kb * 1024 / ctx->fs->blocksize; + cd.next_ra_off = 0; + + if (ctx->progress) + (void) (ctx->progress)(ctx, 2, 0, cd.max); + + if (ext2fs_has_feature_dir_index(fs->super)) + ext2fs_dblist_sort2(fs->dblist, special_dir_block_cmp); + + check_dir_func = cd.ra_entries ? check_dir_block2 : check_dir_block; + cd.pctx.errcode = ext2fs_dblist_iterate2(fs->dblist, check_dir_func, + &cd); + if (ctx->flags & E2F_FLAG_RESTART_LATER) { + ctx->flags |= E2F_FLAG_RESTART; + ctx->flags &= ~E2F_FLAG_RESTART_LATER; + } + + if (ctx->flags & E2F_FLAG_RUN_RETURN) + goto cleanup; + + if (cd.pctx.errcode) { + fix_problem(ctx, PR_2_DBLIST_ITERATE, &cd.pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto cleanup; + } + + for (i=0; (dx_dir = e2fsck_dx_dir_info_iter(ctx, &i)) != 0;) { + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto cleanup; + if (e2fsck_dir_will_be_rehashed(ctx, dx_dir->ino) || + dx_dir->numblocks == 0) + continue; + clear_problem_context(&pctx); + bad_dir = 0; + pctx.dir = dx_dir->ino; + dx_db = dx_dir->dx_block; + if (dx_db->flags & DX_FLAG_REFERENCED) + dx_db->flags |= DX_FLAG_DUP_REF; + else + dx_db->flags |= DX_FLAG_REFERENCED; + /* + * Find all of the first and last leaf blocks, and + * update their parent's min and max hash values + */ + update_parents(dx_dir, DX_DIRBLOCK_LEAF); + + /* for 3 level htree: update 2 level parent's min + * and max hash values */ + update_parents(dx_dir, DX_DIRBLOCK_NODE); + + for (b=0, dx_db = dx_dir->dx_block; + b < dx_dir->numblocks; + b++, dx_db++) { + pctx.blkcount = b; + pctx.group = dx_db->parent; + code = 0; + if (!(dx_db->flags & DX_FLAG_FIRST) && + (dx_db->min_hash < dx_db->node_min_hash)) { + pctx.blk = dx_db->min_hash; + pctx.blk2 = dx_db->node_min_hash; + code = PR_2_HTREE_MIN_HASH; + fix_problem(ctx, code, &pctx); + bad_dir++; + } + if (dx_db->type == DX_DIRBLOCK_LEAF) { + depth = htree_depth(dx_dir, dx_db); + if (depth != dx_dir->depth) { + pctx.num = dx_dir->depth; + code = PR_2_HTREE_BAD_DEPTH; + fix_problem(ctx, code, &pctx); + bad_dir++; + } + } + /* + * This test doesn't apply for the root block + * at block #0 + */ + if (b && + (dx_db->max_hash > dx_db->node_max_hash)) { + pctx.blk = dx_db->max_hash; + pctx.blk2 = dx_db->node_max_hash; + code = PR_2_HTREE_MAX_HASH; + fix_problem(ctx, code, &pctx); + bad_dir++; + } + if (!(dx_db->flags & DX_FLAG_REFERENCED)) { + code = PR_2_HTREE_NOTREF; + fix_problem(ctx, code, &pctx); + bad_dir++; + } else if (dx_db->flags & DX_FLAG_DUP_REF) { + code = PR_2_HTREE_DUPREF; + fix_problem(ctx, code, &pctx); + bad_dir++; + } + } + if (bad_dir && fix_problem(ctx, PR_2_HTREE_CLEAR, &pctx)) { + clear_htree(ctx, dx_dir->ino); + dx_dir->numblocks = 0; + } + } + e2fsck_free_dx_dir_info(ctx); + + ext2fs_free_mem(&buf); + ext2fs_free_dblist(fs->dblist); + + if (ctx->inode_bad_map) { + ext2fs_free_inode_bitmap(ctx->inode_bad_map); + ctx->inode_bad_map = 0; + } + if (ctx->inode_reg_map) { + ext2fs_free_inode_bitmap(ctx->inode_reg_map); + ctx->inode_reg_map = 0; + } + if (ctx->inode_casefold_map) { + ext2fs_free_inode_bitmap(ctx->inode_casefold_map); + ctx->inode_casefold_map = 0; + } + destroy_encrypted_file_info(ctx); + if (ctx->casefolded_dirs) { + ext2fs_u32_list_free(ctx->casefolded_dirs); + ctx->casefolded_dirs = 0; + } + + clear_problem_context(&pctx); + if (ctx->large_files) { + if (!ext2fs_has_feature_large_file(sb) && + fix_problem(ctx, PR_2_FEATURE_LARGE_FILES, &pctx)) { + ext2fs_set_feature_large_file(sb); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + ext2fs_mark_super_dirty(fs); + } + if (sb->s_rev_level == EXT2_GOOD_OLD_REV && + fix_problem(ctx, PR_1_FS_REV_LEVEL, &pctx)) { + ext2fs_update_dynamic_rev(fs); + ext2fs_mark_super_dirty(fs); + } + } + + print_resource_track(ctx, _("Pass 2"), &rtrack, fs->io); +cleanup: + ext2fs_free_mem(&buf); + fs->flags &= ~EXT2_FLAG_IGNORE_SWAP_DIRENT; +} + +#define MAX_DEPTH 32000 +static short htree_depth(struct dx_dir_info *dx_dir, + struct dx_dirblock_info *dx_db) +{ + short depth = 0; + + while (dx_db->type != DX_DIRBLOCK_ROOT && depth < MAX_DEPTH) { + dx_db = &dx_dir->dx_block[dx_db->parent]; + depth++; + } + return depth; +} + +static int dict_de_cmp(const void *cmp_ctx EXT2FS_ATTR((unused)), + const void *a, const void *b) +{ + const struct ext2_dir_entry *de_a, *de_b; + int a_len, b_len; + + de_a = (const struct ext2_dir_entry *) a; + a_len = ext2fs_dirent_name_len(de_a); + de_b = (const struct ext2_dir_entry *) b; + b_len = ext2fs_dirent_name_len(de_b); + + if (a_len != b_len) + return (a_len - b_len); + + return memcmp(de_a->name, de_b->name, a_len); +} + +static int dict_de_cf_cmp(const void *cmp_ctx, const void *a, const void *b) +{ + const struct ext2fs_nls_table *tbl = cmp_ctx; + const struct ext2_dir_entry *de_a, *de_b; + int a_len, b_len; + + de_a = (const struct ext2_dir_entry *) a; + a_len = ext2fs_dirent_name_len(de_a); + de_b = (const struct ext2_dir_entry *) b; + b_len = ext2fs_dirent_name_len(de_b); + + return ext2fs_casefold_cmp(tbl, + (const unsigned char *) de_a->name, a_len, + (const unsigned char *) de_b->name, b_len); +} + +/* + * This is special sort function that makes sure that directory blocks + * with a dirblock of zero are sorted to the beginning of the list. + * This guarantees that the root node of the htree directories are + * processed first, so we know what hash version to use. + */ +static EXT2_QSORT_TYPE special_dir_block_cmp(const void *a, const void *b) +{ + const struct ext2_db_entry2 *db_a = + (const struct ext2_db_entry2 *) a; + const struct ext2_db_entry2 *db_b = + (const struct ext2_db_entry2 *) b; + + if (db_a->blockcnt && !db_b->blockcnt) + return 1; + + if (!db_a->blockcnt && db_b->blockcnt) + return -1; + + if (db_a->blk != db_b->blk) + return (int) (db_a->blk - db_b->blk); + + if (db_a->ino != db_b->ino) + return (int) (db_a->ino - db_b->ino); + + return (int) (db_a->blockcnt - db_b->blockcnt); +} + + +/* + * Make sure the first entry in the directory is '.', and that the + * directory entry is sane. + */ +static int check_dot(e2fsck_t ctx, + struct ext2_dir_entry *dirent, + ext2_ino_t ino, struct problem_context *pctx) +{ + struct ext2_dir_entry *nextdir; + unsigned int rec_len, new_len; + int status = 0; + int created = 0; + problem_t problem = 0; + int ftype = EXT2_FT_DIR; + + if (!dirent->inode) + problem = PR_2_MISSING_DOT; + else if ((ext2fs_dirent_name_len(dirent) != 1) || + (dirent->name[0] != '.')) + problem = PR_2_1ST_NOT_DOT; + else if (dirent->name[1] != '\0') + problem = PR_2_DOT_NULL_TERM; + + (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len); + if (problem) { + if (!ext2fs_has_feature_filetype(ctx->fs->super)) + ftype = EXT2_FT_UNKNOWN; + if (fix_problem(ctx, problem, pctx)) { + if (rec_len < 12) + rec_len = dirent->rec_len = 12; + dirent->inode = ino; + ext2fs_dirent_set_name_len(dirent, 1); + ext2fs_dirent_set_file_type(dirent, ftype); + dirent->name[0] = '.'; + dirent->name[1] = '\0'; + status = 1; + created = 1; + } + } + if (dirent->inode != ino) { + if (fix_problem(ctx, PR_2_BAD_INODE_DOT, pctx)) { + dirent->inode = ino; + status = 1; + } + } + if (rec_len > 12) { + new_len = rec_len - 12; + if (new_len > 12) { + if (created || + fix_problem(ctx, PR_2_SPLIT_DOT, pctx)) { + nextdir = (struct ext2_dir_entry *) + ((char *) dirent + 12); + dirent->rec_len = 12; + /* if the next entry looks like "..", leave it + * and let check_dotdot() verify the dirent, + * otherwise zap the following entry. */ + if (strncmp(nextdir->name, "..", 3) != 0) { + (void)ext2fs_set_rec_len(ctx->fs, + new_len, + nextdir); + nextdir->inode = 0; + ext2fs_dirent_set_name_len(nextdir, 0); + ext2fs_dirent_set_file_type(nextdir, + ftype); +#ifdef WORDS_BIGENDIAN + } else { + (void) ext2fs_dirent_swab_in2(ctx->fs, + (char *) nextdir, + ctx->fs->blocksize - 12, 0); +#endif + } + status = 1; + } + } + } + return status; +} + +/* + * Make sure the second entry in the directory is '..', and that the + * directory entry is sane. We do not check the inode number of '..' + * here; this gets done in pass 3. + */ +static int check_dotdot(e2fsck_t ctx, + struct ext2_dir_entry *dirent, + ext2_ino_t ino, struct problem_context *pctx) +{ + problem_t problem = 0; + unsigned int rec_len; + int ftype = EXT2_FT_DIR; + + if (!dirent->inode) + problem = PR_2_MISSING_DOT_DOT; + else if ((ext2fs_dirent_name_len(dirent) != 2) || + (dirent->name[0] != '.') || + (dirent->name[1] != '.')) + problem = PR_2_2ND_NOT_DOT_DOT; + else if (dirent->name[2] != '\0') + problem = PR_2_DOT_DOT_NULL_TERM; + + (void) ext2fs_get_rec_len(ctx->fs, dirent, &rec_len); + if (problem) { + if (!ext2fs_has_feature_filetype(ctx->fs->super)) + ftype = EXT2_FT_UNKNOWN; + if (fix_problem(ctx, problem, pctx)) { + if (rec_len < 12) + dirent->rec_len = 12; + /* + * Note: we don't have the parent inode just + * yet, so we will fill it in with the root + * inode. This will get fixed in pass 3. + */ + dirent->inode = EXT2_ROOT_INO; + ext2fs_dirent_set_name_len(dirent, 2); + ext2fs_dirent_set_file_type(dirent, ftype); + dirent->name[0] = '.'; + dirent->name[1] = '.'; + dirent->name[2] = '\0'; + return 1; + } + return 0; + } + if (e2fsck_dir_info_set_dotdot(ctx, ino, dirent->inode)) { + fix_problem(ctx, PR_2_NO_DIRINFO, pctx); + return -1; + } + return 0; +} + +/* + * Check to make sure a directory entry doesn't contain any illegal + * characters. + */ +static int check_name(e2fsck_t ctx, + struct ext2_dir_entry *dirent, + struct problem_context *pctx) +{ + int i; + int fixup = -1; + int ret = 0; + + for ( i = 0; i < ext2fs_dirent_name_len(dirent); i++) { + if (dirent->name[i] != '/' && dirent->name[i] != '\0') + continue; + if (fixup < 0) + fixup = fix_problem(ctx, PR_2_BAD_NAME, pctx); + if (fixup == 0) + return 0; + dirent->name[i] = '.'; + ret = 1; + } + return ret; +} + +static int encrypted_check_name(e2fsck_t ctx, + const struct ext2_dir_entry *dirent, + struct problem_context *pctx) +{ + if (ext2fs_dirent_name_len(dirent) < EXT4_CRYPTO_BLOCK_SIZE) { + if (fix_problem(ctx, PR_2_BAD_ENCRYPTED_NAME, pctx)) + return 1; + ext2fs_unmark_valid(ctx->fs); + } + return 0; +} + +static int encoded_check_name(e2fsck_t ctx, + struct ext2_dir_entry *dirent, + struct problem_context *pctx) +{ + const struct ext2fs_nls_table *tbl = ctx->fs->encoding; + int ret; + int len = ext2fs_dirent_name_len(dirent); + char *pos, *end; + + ret = ext2fs_check_encoded_name(tbl, dirent->name, len, &pos); + if (ret < 0) { + fatal_error(ctx, _("NLS is broken.")); + } else if(ret > 0) { + ret = fix_problem(ctx, PR_2_BAD_ENCODED_NAME, pctx); + if (ret) { + end = &dirent->name[len]; + for (; *pos && pos != end; pos++) + *pos = '.'; + } + } + + return (ret || check_name(ctx, dirent, pctx)); +} + +/* + * Check the directory filetype (if present) + */ +static _INLINE_ int check_filetype(e2fsck_t ctx, + struct ext2_dir_entry *dirent, + ext2_ino_t dir_ino EXT2FS_ATTR((unused)), + struct problem_context *pctx) +{ + int filetype = ext2fs_dirent_file_type(dirent); + int should_be = EXT2_FT_UNKNOWN; + struct ext2_inode inode; + + if (!ext2fs_has_feature_filetype(ctx->fs->super)) { + if (filetype == 0 || + !fix_problem(ctx, PR_2_CLEAR_FILETYPE, pctx)) + return 0; + ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN); + return 1; + } + + if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dirent->inode)) { + should_be = EXT2_FT_DIR; + } else if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map, + dirent->inode)) { + should_be = EXT2_FT_REG_FILE; + } else if (ctx->inode_bad_map && + ext2fs_test_inode_bitmap2(ctx->inode_bad_map, + dirent->inode)) + should_be = 0; + else { + e2fsck_read_inode(ctx, dirent->inode, &inode, + "check_filetype"); + should_be = ext2_file_type(inode.i_mode); + } + if (filetype == should_be) + return 0; + pctx->num = should_be; + + if (fix_problem(ctx, filetype ? PR_2_BAD_FILETYPE : PR_2_SET_FILETYPE, + pctx) == 0) + return 0; + + ext2fs_dirent_set_file_type(dirent, should_be); + return 1; +} + +static void parse_int_node(ext2_filsys fs, + struct ext2_db_entry2 *db, + struct check_dir_struct *cd, + struct dx_dir_info *dx_dir, + char *block_buf, int failed_csum) +{ + struct ext2_dx_root_info *root; + struct ext2_dx_entry *ent; + struct ext2_dx_countlimit *limit; + struct dx_dirblock_info *dx_db; + int i, expect_limit, count; + blk_t blk; + ext2_dirhash_t min_hash = 0xffffffff; + ext2_dirhash_t max_hash = 0; + ext2_dirhash_t hash = 0, prev_hash; + int csum_size = 0; + + if (db->blockcnt == 0) { + root = (struct ext2_dx_root_info *) (block_buf + 24); + +#ifdef DX_DEBUG + printf("Root node dump:\n"); + printf("\t Reserved zero: %u\n", root->reserved_zero); + printf("\t Hash Version: %u\n", root->hash_version); + printf("\t Info length: %u\n", root->info_length); + printf("\t Indirect levels: %u\n", root->indirect_levels); + printf("\t Flags: %x\n", root->unused_flags); +#endif + + ent = (struct ext2_dx_entry *) (block_buf + 24 + root->info_length); + + if (failed_csum && + (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) || + fix_problem(cd->ctx, PR_2_HTREE_ROOT_CSUM_INVALID, + &cd->pctx))) + goto clear_and_exit; + } else { + ent = (struct ext2_dx_entry *) (block_buf+8); + + if (failed_csum && + (e2fsck_dir_will_be_rehashed(cd->ctx, cd->pctx.ino) || + fix_problem(cd->ctx, PR_2_HTREE_NODE_CSUM_INVALID, + &cd->pctx))) + goto clear_and_exit; + } + + limit = (struct ext2_dx_countlimit *) ent; + +#ifdef DX_DEBUG + printf("Number of entries (count): %d\n", + ext2fs_le16_to_cpu(limit->count)); + printf("Number of entries (limit): %d\n", + ext2fs_le16_to_cpu(limit->limit)); +#endif + + count = ext2fs_le16_to_cpu(limit->count); + if (ext2fs_has_feature_metadata_csum(fs->super)) + csum_size = sizeof(struct ext2_dx_tail); + expect_limit = (fs->blocksize - + (csum_size + ((char *) ent - block_buf))) / + sizeof(struct ext2_dx_entry); + if (ext2fs_le16_to_cpu(limit->limit) != expect_limit) { + cd->pctx.num = ext2fs_le16_to_cpu(limit->limit); + if (fix_problem(cd->ctx, PR_2_HTREE_BAD_LIMIT, &cd->pctx)) + goto clear_and_exit; + } + if (count > expect_limit) { + cd->pctx.num = count; + if (fix_problem(cd->ctx, PR_2_HTREE_BAD_COUNT, &cd->pctx)) + goto clear_and_exit; + count = expect_limit; + } + + for (i=0; i < count; i++) { + prev_hash = hash; + hash = i ? (ext2fs_le32_to_cpu(ent[i].hash) & ~1) : 0; +#ifdef DX_DEBUG + printf("Entry #%d: Hash 0x%08x, block %u\n", i, + hash, ext2fs_le32_to_cpu(ent[i].block)); +#endif + blk = ext2fs_le32_to_cpu(ent[i].block) & EXT4_DX_BLOCK_MASK; + /* Check to make sure the block is valid */ + if (blk >= dx_dir->numblocks) { + cd->pctx.blk = blk; + if (fix_problem(cd->ctx, PR_2_HTREE_BADBLK, + &cd->pctx)) + goto clear_and_exit; + continue; + } + if (hash < prev_hash && + fix_problem(cd->ctx, PR_2_HTREE_HASH_ORDER, &cd->pctx)) + goto clear_and_exit; + dx_db = &dx_dir->dx_block[blk]; + if (dx_db->flags & DX_FLAG_REFERENCED) { + dx_db->flags |= DX_FLAG_DUP_REF; + } else { + dx_db->flags |= DX_FLAG_REFERENCED; + dx_db->parent = db->blockcnt; + } + + dx_db->previous = + i ? (ext2fs_le32_to_cpu(ent[i-1].block) & + EXT4_DX_BLOCK_MASK) : 0; + + if (hash < min_hash) + min_hash = hash; + if (hash > max_hash) + max_hash = hash; + dx_db->node_min_hash = hash; + if ((i+1) < count) + dx_db->node_max_hash = + ext2fs_le32_to_cpu(ent[i+1].hash) & ~1; + else { + dx_db->node_max_hash = 0xfffffffe; + dx_db->flags |= DX_FLAG_LAST; + } + if (i == 0) + dx_db->flags |= DX_FLAG_FIRST; + } +#ifdef DX_DEBUG + printf("Blockcnt = %d, min hash 0x%08x, max hash 0x%08x\n", + db->blockcnt, min_hash, max_hash); +#endif + dx_db = &dx_dir->dx_block[db->blockcnt]; + dx_db->min_hash = min_hash; + dx_db->max_hash = max_hash; + return; + +clear_and_exit: + clear_htree(cd->ctx, cd->pctx.ino); + dx_dir->numblocks = 0; + e2fsck_rehash_dir_later(cd->ctx, cd->pctx.ino); +} + +/* + * Given a busted directory, try to salvage it somehow. + * + */ +static void salvage_directory(ext2_filsys fs, + struct ext2_dir_entry *dirent, + struct ext2_dir_entry *prev, + unsigned int *offset, + unsigned int block_len, + int hash_in_dirent) +{ + char *cp = (char *) dirent; + int left; + unsigned int rec_len, prev_rec_len; + unsigned int name_len; + + /* + * If the space left for the entry is too small to be an entry, + * we can't access dirent's fields, so plumb in the values needed + * so that the previous entry absorbs this one. + */ + if (block_len - *offset < EXT2_DIR_ENTRY_HEADER_LEN) { + name_len = 0; + rec_len = block_len - *offset; + } else { + name_len = ext2fs_dirent_name_len(dirent); + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + } + left = block_len - *offset - rec_len; + + /* + * Special case of directory entry of size 8: copy what's left + * of the directory block up to cover up the invalid hole. + */ + if ((left >= (int) ext2fs_dir_rec_len(1, hash_in_dirent)) && + (rec_len == EXT2_DIR_ENTRY_HEADER_LEN)) { + memmove(cp, cp+EXT2_DIR_ENTRY_HEADER_LEN, left); + memset(cp + left, 0, EXT2_DIR_ENTRY_HEADER_LEN); + return; + } + /* + * If the directory entry overruns the end of the directory + * block, and the name is small enough to fit, then adjust the + * record length. + */ + if ((left < 0) && + ((int) rec_len + left > EXT2_DIR_ENTRY_HEADER_LEN) && + ((int) ext2fs_dir_rec_len(name_len, hash_in_dirent) <= (int) rec_len + left) && + dirent->inode <= fs->super->s_inodes_count && + strnlen(dirent->name, name_len) == name_len) { + (void) ext2fs_set_rec_len(fs, (int) rec_len + left, dirent); + return; + } + /* + * If the record length of the directory entry is a multiple + * of four, and not too big, such that it is valid, let the + * previous directory entry absorb the invalid one. + */ + if (prev && rec_len && (rec_len % 4) == 0 && + (*offset + rec_len <= block_len)) { + (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len); + prev_rec_len += rec_len; + (void) ext2fs_set_rec_len(fs, prev_rec_len, prev); + *offset += rec_len; + return; + } + /* + * Default salvage method --- kill all of the directory + * entries for the rest of the block. We will either try to + * absorb it into the previous directory entry, or create a + * new empty directory entry the rest of the directory block. + */ + if (prev) { + (void) ext2fs_get_rec_len(fs, prev, &prev_rec_len); + prev_rec_len += block_len - *offset; + (void) ext2fs_set_rec_len(fs, prev_rec_len, prev); + *offset = fs->blocksize; + } else { + rec_len = block_len - *offset; + (void) ext2fs_set_rec_len(fs, rec_len, dirent); + ext2fs_dirent_set_name_len(dirent, 0); + ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN); + dirent->inode = 0; + } +} + +#define NEXT_DIRENT(d) ((void *)((char *)(d) + (d)->rec_len)) +static errcode_t insert_dirent_tail(ext2_filsys fs, void *dirbuf) +{ + struct ext2_dir_entry *d; + void *top; + struct ext2_dir_entry_tail *t; + + d = dirbuf; + top = EXT2_DIRENT_TAIL(dirbuf, fs->blocksize); + + while (d->rec_len && !(d->rec_len & 0x3) && NEXT_DIRENT(d) <= top) + d = NEXT_DIRENT(d); + + if (d != top) { + unsigned int min_size = EXT2_DIR_REC_LEN( + ext2fs_dirent_name_len(dirbuf)); + if (min_size > (char *)top - (char *)d) + return EXT2_ET_DIR_NO_SPACE_FOR_CSUM; + d->rec_len = (char *)top - (char *)d; + } + + t = (struct ext2_dir_entry_tail *)top; + if (t->det_reserved_zero1 || + t->det_rec_len != sizeof(struct ext2_dir_entry_tail) || + t->det_reserved_name_len != EXT2_DIR_NAME_LEN_CSUM) + ext2fs_initialize_dirent_tail(fs, t); + + return 0; +} +#undef NEXT_DIRENT + +static errcode_t fix_inline_dir_size(e2fsck_t ctx, ext2_ino_t ino, + size_t *inline_data_size, + struct problem_context *pctx, + char *buf) +{ + ext2_filsys fs = ctx->fs; + struct ext2_inode inode; + size_t new_size, old_size; + errcode_t retval; + + old_size = *inline_data_size; + /* + * If there's not enough bytes to start the "second" dir block + * (in the EA space) then truncate everything to the first block. + */ + if (old_size > EXT4_MIN_INLINE_DATA_SIZE && + old_size < EXT4_MIN_INLINE_DATA_SIZE + + EXT2_DIR_REC_LEN(1)) { + old_size = EXT4_MIN_INLINE_DATA_SIZE; + new_size = old_size; + } else + /* Increase to the next four-byte boundary for salvaging */ + new_size = old_size + (4 - (old_size & 3)); + memset(buf + old_size, 0, new_size - old_size); + retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size); + if (retval == EXT2_ET_INLINE_DATA_NO_SPACE) { + /* Or we can't, so truncate. */ + new_size -= 4; + retval = ext2fs_inline_data_set(fs, ino, 0, buf, new_size); + if (retval) { + if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED, + pctx)) { + new_size = 0; + goto write_inode; + } + goto err; + } + } else if (retval) { + if (fix_problem(ctx, PR_2_FIX_INLINE_DIR_FAILED, + pctx)) { + new_size = 0; + goto write_inode; + } + goto err; + } + +write_inode: + retval = ext2fs_read_inode(fs, ino, &inode); + if (retval) + goto err; + + retval = ext2fs_inode_size_set(fs, &inode, new_size); + if (retval) + goto err; + if (new_size == 0) + inode.i_flags &= ~EXT4_INLINE_DATA_FL; + retval = ext2fs_write_inode(fs, ino, &inode); + if (retval) + goto err; + *inline_data_size = new_size; + +err: + return retval; +} + +/* Return true if this type of file needs encryption */ +static int needs_encryption(e2fsck_t ctx, const struct ext2_dir_entry *dirent) +{ + int filetype = ext2fs_dirent_file_type(dirent); + ext2_ino_t ino = dirent->inode; + struct ext2_inode inode; + + if (filetype != EXT2_FT_UNKNOWN) + return filetype == EXT2_FT_REG_FILE || + filetype == EXT2_FT_DIR || + filetype == EXT2_FT_SYMLINK; + + if (ext2fs_test_inode_bitmap2(ctx->inode_reg_map, ino) || + ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino)) + return 1; + + e2fsck_read_inode(ctx, ino, &inode, "check_encryption_policy"); + return LINUX_S_ISREG(inode.i_mode) || + LINUX_S_ISDIR(inode.i_mode) || + LINUX_S_ISLNK(inode.i_mode); +} + +/* + * All regular files, directories, and symlinks in encrypted directories must be + * encrypted using the same encryption policy as their directory. + * + * Returns 1 if the dirent should be cleared, otherwise 0. + */ +static int check_encryption_policy(e2fsck_t ctx, + const struct ext2_dir_entry *dirent, + __u32 dir_encpolicy_id, + struct problem_context *pctx) +{ + __u32 file_encpolicy_id = find_encryption_policy(ctx, dirent->inode); + + /* Same policy or both UNRECOGNIZED_ENCRYPTION_POLICY? */ + if (file_encpolicy_id == dir_encpolicy_id) + return 0; + + if (file_encpolicy_id == NO_ENCRYPTION_POLICY) { + if (!needs_encryption(ctx, dirent)) + return 0; + return fix_problem(ctx, PR_2_UNENCRYPTED_FILE, pctx); + } + + return fix_problem(ctx, PR_2_INCONSISTENT_ENCRYPTION_POLICY, pctx); +} + +/* + * Check an encrypted directory entry. + * + * Returns 1 if the dirent should be cleared, otherwise 0. + */ +static int check_encrypted_dirent(e2fsck_t ctx, + const struct ext2_dir_entry *dirent, + __u32 dir_encpolicy_id, + struct problem_context *pctx) +{ + if (encrypted_check_name(ctx, dirent, pctx)) + return 1; + if (check_encryption_policy(ctx, dirent, dir_encpolicy_id, pctx)) + return 1; + return 0; +} + +static int check_dir_block2(ext2_filsys fs, + struct ext2_db_entry2 *db, + void *priv_data) +{ + int err; + struct check_dir_struct *cd = priv_data; + + if (cd->ra_entries && cd->list_offset >= cd->next_ra_off) { + err = e2fsck_readahead_dblist(fs, + E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT, + fs->dblist, + cd->list_offset + cd->ra_entries / 8, + cd->ra_entries); + if (err) + cd->ra_entries = 0; + cd->next_ra_off = cd->list_offset + (cd->ra_entries * 7 / 8); + } + + err = check_dir_block(fs, db, priv_data); + cd->list_offset++; + return err; +} + +static int check_dir_block(ext2_filsys fs, + struct ext2_db_entry2 *db, + void *priv_data) +{ + struct dx_dir_info *dx_dir; + struct dx_dirblock_info *dx_db = 0; + struct ext2_dir_entry *dirent, *prev, dot, dotdot; + ext2_dirhash_t hash; + unsigned int offset = 0; + int dir_modified = 0; + int dot_state; + unsigned int rec_len; + blk64_t block_nr = db->blk; + ext2_ino_t ino = db->ino; + ext2_ino_t subdir_parent; + __u16 links; + struct check_dir_struct *cd; + char *buf, *ibuf; + e2fsck_t ctx; + problem_t problem; + struct ext2_dx_root_info *root; + struct ext2_dx_countlimit *limit; + static dict_t de_dict; + struct problem_context pctx; + int dups_found = 0; + int ret; + int dx_csum_size = 0, de_csum_size = 0; + int failed_csum = 0; + int is_leaf = 1; + size_t inline_data_size = 0; + int filetype = 0; + __u32 dir_encpolicy_id = NO_ENCRYPTION_POLICY; + int hash_in_dirent = 0; + int casefolded = 0; + size_t max_block_size; + int hash_flags = 0; + static char *eop_read_dirblock = NULL; + int cf_dir = 0; + + cd = (struct check_dir_struct *) priv_data; + ibuf = buf = cd->buf; + ctx = cd->ctx; + + /* We only want filename encoding verification on strict + * mode or if explicitly requested by user. */ + if (ext2fs_test_inode_bitmap2(ctx->inode_casefold_map, ino) && + ((ctx->fs->super->s_encoding_flags & EXT4_ENC_STRICT_MODE_FL) || + (ctx->options & E2F_OPT_CHECK_ENCODING))) + cf_dir = 1; + + if (ctx->flags & E2F_FLAG_RUN_RETURN) + return DIRENT_ABORT; + + if (ctx->progress && (ctx->progress)(ctx, 2, cd->count++, cd->max)) + return DIRENT_ABORT; + + if (ext2fs_has_feature_metadata_csum(fs->super)) { + dx_csum_size = sizeof(struct ext2_dx_tail); + de_csum_size = sizeof(struct ext2_dir_entry_tail); + } + + if (ext2fs_has_feature_filetype(fs->super)) + filetype = EXT2_FT_DIR << 8; + + /* + * Make sure the inode is still in use (could have been + * deleted in the duplicate/bad blocks pass. + */ + if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, ino))) + return 0; + + cd->pctx.ino = ino; + cd->pctx.blk = block_nr; + cd->pctx.blkcount = db->blockcnt; + cd->pctx.ino2 = 0; + cd->pctx.dirent = 0; + cd->pctx.num = 0; + + if (ext2fs_has_feature_inline_data(fs->super)) { + errcode_t ec; + + ec = ext2fs_inline_data_size(fs, ino, &inline_data_size); + if (ec && ec != EXT2_ET_NO_INLINE_DATA) + return DIRENT_ABORT; + } + + /* This will allow (at some point in the future) to punch out empty + * directory blocks and reduce the space used by a directory that grows + * very large and then the files are deleted. For now, all that is + * needed is to avoid e2fsck filling in these holes as part of + * feature flag. */ + if (db->blk == 0 && ext2fs_has_feature_largedir(fs->super) && + !ext2fs_has_feature_inline_data(fs->super)) + return 0; + + if (db->blk == 0 && !inline_data_size) { + if (allocate_dir_block(ctx, db, buf, &cd->pctx)) + return 0; + block_nr = db->blk; + } + + if (db->blockcnt) + dot_state = 2; + else + dot_state = 0; + + if (ctx->dirs_to_hash && + ext2fs_u32_list_test(ctx->dirs_to_hash, ino)) + dups_found++; + +#if 0 + printf("In process_dir_block block %lu, #%d, inode %lu\n", block_nr, + db->blockcnt, ino); +#endif + + if (!eop_read_dirblock) + eop_read_dirblock = (char *) _("reading directory block"); + ehandler_operation(eop_read_dirblock); + if (inline_data_size) { + memset(buf, 0, fs->blocksize - inline_data_size); + cd->pctx.errcode = ext2fs_inline_data_get(fs, ino, 0, buf, 0); + if (cd->pctx.errcode) + goto inline_read_fail; +#ifdef WORDS_BIGENDIAN + if (db->blockcnt) + goto skip_first_read_swab; + *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf)); + cd->pctx.errcode = ext2fs_dirent_swab_in2(fs, + buf + EXT4_INLINE_DATA_DOTDOT_SIZE, + EXT4_MIN_INLINE_DATA_SIZE - EXT4_INLINE_DATA_DOTDOT_SIZE, + 0); + if (cd->pctx.errcode) + goto inline_read_fail; +skip_first_read_swab: + if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE || + !db->blockcnt) + goto inline_read_fail; + cd->pctx.errcode = ext2fs_dirent_swab_in2(fs, + buf + EXT4_MIN_INLINE_DATA_SIZE, + inline_data_size - EXT4_MIN_INLINE_DATA_SIZE, + 0); +#endif + } else + cd->pctx.errcode = ext2fs_read_dir_block4(fs, block_nr, + buf, 0, ino); +inline_read_fail: + pctx.ino = ino; + pctx.num = inline_data_size; + if (((inline_data_size & 3) || + (inline_data_size > EXT4_MIN_INLINE_DATA_SIZE && + inline_data_size < EXT4_MIN_INLINE_DATA_SIZE + + EXT2_DIR_REC_LEN(1))) && + fix_problem(ctx, PR_2_BAD_INLINE_DIR_SIZE, &pctx)) { + errcode_t err = fix_inline_dir_size(ctx, ino, + &inline_data_size, &pctx, + buf); + if (err) + return DIRENT_ABORT; + + } + ehandler_operation(0); + if (cd->pctx.errcode == EXT2_ET_DIR_CORRUPTED) + cd->pctx.errcode = 0; /* We'll handle this ourselves */ + else if (cd->pctx.errcode == EXT2_ET_DIR_CSUM_INVALID) { + cd->pctx.errcode = 0; /* We'll handle this ourselves */ + failed_csum = 1; + } + if (cd->pctx.errcode) { + char *buf2; + if (!fix_problem(ctx, PR_2_READ_DIRBLOCK, &cd->pctx)) { + ctx->flags |= E2F_FLAG_ABORT; + return DIRENT_ABORT; + } + ext2fs_new_dir_block(fs, db->blockcnt == 0 ? ino : 0, + EXT2_ROOT_INO, &buf2); + memcpy(buf, buf2, fs->blocksize); + ext2fs_free_mem(&buf2); + } + dx_dir = e2fsck_get_dx_dir_info(ctx, ino); + if (dx_dir && dx_dir->numblocks) { + if (db->blockcnt >= dx_dir->numblocks) { + pctx.dir = ino; + if (fix_problem(ctx, PR_2_UNEXPECTED_HTREE_BLOCK, + &pctx)) { + clear_htree(ctx, ino); + dx_dir->numblocks = 0; + dx_db = 0; + goto out_htree; + } + fatal_error(ctx, _("Can not continue.")); + } + dx_db = &dx_dir->dx_block[db->blockcnt]; + dx_db->type = DX_DIRBLOCK_LEAF; + dx_db->phys = block_nr; + dx_db->min_hash = ~0; + dx_db->max_hash = 0; + + dirent = (struct ext2_dir_entry *) buf; + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + limit = (struct ext2_dx_countlimit *) (buf+8); + if (db->blockcnt == 0) { + root = (struct ext2_dx_root_info *) (buf + 24); + dx_db->type = DX_DIRBLOCK_ROOT; + dx_db->flags |= DX_FLAG_FIRST | DX_FLAG_LAST; + + /* large_dir was set in pass1 if large dirs were found, + * so ext2_dir_htree_level() should now be correct */ + if ((root->reserved_zero || + root->info_length < 8 || + root->indirect_levels >= + ext2_dir_htree_level(fs)) && + fix_problem(ctx, PR_2_HTREE_BAD_ROOT, &cd->pctx)) { + clear_htree(ctx, ino); + dx_dir->numblocks = 0; + dx_db = NULL; + } + dx_dir->hashversion = root->hash_version; + if ((dx_dir->hashversion <= EXT2_HASH_TEA) && + (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH)) + dx_dir->hashversion += 3; + dx_dir->depth = root->indirect_levels + 1; + } else if ((dirent->inode == 0) && + (rec_len == fs->blocksize) && + (ext2fs_dirent_name_len(dirent) == 0) && + (ext2fs_le16_to_cpu(limit->limit) == + ((fs->blocksize - (8 + dx_csum_size)) / + sizeof(struct ext2_dx_entry)))) { + dx_db->type = DX_DIRBLOCK_NODE; + } + is_leaf = dx_db ? (dx_db->type == DX_DIRBLOCK_LEAF) : 0; + } +out_htree: + + /* Leaf node with no space for csum? Rebuild dirs in pass 3A. */ + if (is_leaf && !inline_data_size && failed_csum && + !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) { + de_csum_size = 0; + if (e2fsck_dir_will_be_rehashed(ctx, ino)) { + failed_csum = 0; + goto skip_checksum; + } + if (!fix_problem(cd->ctx, PR_2_LEAF_NODE_MISSING_CSUM, + &cd->pctx)) + goto skip_checksum; + e2fsck_rehash_dir_later(ctx, ino); + failed_csum = 0; + goto skip_checksum; + } + /* htree nodes don't use fake dirents to store checksums */ + if (!is_leaf) + de_csum_size = 0; + +skip_checksum: + if (inline_data_size) { + if (db->blockcnt) { + buf += EXT4_MIN_INLINE_DATA_SIZE; + max_block_size = inline_data_size - EXT4_MIN_INLINE_DATA_SIZE; + /* Zero-length second block, just exit */ + if (max_block_size == 0) + return 0; + } else { + max_block_size = EXT4_MIN_INLINE_DATA_SIZE; + } + } else + max_block_size = fs->blocksize - de_csum_size; + + dir_encpolicy_id = find_encryption_policy(ctx, ino); + + if (cf_dir) { + dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cf_cmp); + dict_set_cmp_context(&de_dict, (const void *)ctx->fs->encoding); + } else { + dict_init(&de_dict, DICTCOUNT_T_MAX, dict_de_cmp); + } + if (ctx->casefolded_dirs) + casefolded = ext2fs_u32_list_test(ctx->casefolded_dirs, ino); + hash_in_dirent = (casefolded && + (dir_encpolicy_id != NO_ENCRYPTION_POLICY)); + + prev = 0; + do { + dgrp_t group; + ext2_ino_t first_unused_inode; + unsigned int name_len; + /* csum entry is not checked here, so don't worry about it */ + int extended = (dot_state > 1) && hash_in_dirent; + unsigned int min_dir_len = ext2fs_dir_rec_len(1, extended); + + problem = 0; + if (!inline_data_size || dot_state > 1) { + dirent = (struct ext2_dir_entry *) (buf + offset); + /* + * If there's not even space for the entry header, + * force salvaging this dir. + */ + if (max_block_size - offset < EXT2_DIR_ENTRY_HEADER_LEN) + rec_len = ext2fs_dir_rec_len(1, extended); + else + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + cd->pctx.dirent = dirent; + cd->pctx.num = offset; + if ((offset + rec_len > max_block_size) || + (rec_len < min_dir_len) || + ((rec_len % 4) != 0) || + ((ext2fs_dir_rec_len(ext2fs_dirent_name_len(dirent), + extended)) > rec_len)) { + if (fix_problem(ctx, PR_2_DIR_CORRUPTED, + &cd->pctx)) { +#ifdef WORDS_BIGENDIAN + /* + * On big-endian systems, if the dirent + * swap routine finds a rec_len that it + * doesn't like, it continues + * processing the block as if rec_len + * == EXT2_DIR_ENTRY_HEADER_LEN. This means that the name + * field gets byte swapped, which means + * that salvage will not detect the + * correct name length (unless the name + * has a length that's an exact + * multiple of four bytes), and it'll + * discard the entry (unnecessarily) + * and the rest of the dirent block. + * Therefore, swap the rest of the + * block back to disk order, run + * salvage, and re-swap anything after + * the salvaged dirent. + */ + int need_reswab = 0; + if (rec_len < EXT2_DIR_ENTRY_HEADER_LEN || rec_len % 4) { + need_reswab = 1; + ext2fs_dirent_swab_in2(fs, + ((char *)dirent) + EXT2_DIR_ENTRY_HEADER_LEN, + max_block_size - offset - EXT2_DIR_ENTRY_HEADER_LEN, + 0); + } +#endif + salvage_directory(fs, dirent, prev, + &offset, + max_block_size, + hash_in_dirent); +#ifdef WORDS_BIGENDIAN + if (need_reswab) { + unsigned int len; + + (void) ext2fs_get_rec_len(fs, + dirent, &len); + len += offset; + if (max_block_size > len) + ext2fs_dirent_swab_in2(fs, + ((char *)dirent) + len, max_block_size - len, 0); + } +#endif + dir_modified++; + continue; + } else + goto abort_free_dict; + } + } else { + if (dot_state == 0) { + memset(&dot, 0, sizeof(dot)); + dirent = ˙ + dirent->inode = ino; + dirent->rec_len = EXT2_DIR_REC_LEN(1); + dirent->name_len = 1 | filetype; + dirent->name[0] = '.'; + } else if (dot_state == 1) { + memset(&dotdot, 0, sizeof(dotdot)); + dirent = &dotdot; + dirent->inode = + ((struct ext2_dir_entry *)buf)->inode; + dirent->rec_len = EXT2_DIR_REC_LEN(2); + dirent->name_len = 2 | filetype; + dirent->name[0] = '.'; + dirent->name[1] = '.'; + } else { + fatal_error(ctx, _("Can not continue.")); + } + cd->pctx.dirent = dirent; + cd->pctx.num = offset; + } + + if (dot_state == 0) { + if (check_dot(ctx, dirent, ino, &cd->pctx)) + dir_modified++; + } else if (dot_state == 1) { + ret = check_dotdot(ctx, dirent, ino, &cd->pctx); + if (ret < 0) + goto abort_free_dict; + if (ret) + dir_modified++; + } else if (dirent->inode == ino) { + problem = PR_2_LINK_DOT; + if (fix_problem(ctx, PR_2_LINK_DOT, &cd->pctx)) { + dirent->inode = 0; + dir_modified++; + goto next; + } + } + if (!dirent->inode) + goto next; + + /* + * Make sure the inode listed is a legal one. + */ + name_len = ext2fs_dirent_name_len(dirent); + if (((dirent->inode != EXT2_ROOT_INO) && + (dirent->inode < EXT2_FIRST_INODE(fs->super))) || + (dirent->inode > fs->super->s_inodes_count) || + (dirent->inode == fs->super->s_usr_quota_inum) || + (dirent->inode == fs->super->s_grp_quota_inum) || + (dirent->inode == fs->super->s_prj_quota_inum) || + (dirent->inode == fs->super->s_orphan_file_inum)) { + problem = PR_2_BAD_INO; + } else if (ctx->inode_bb_map && + (ext2fs_test_inode_bitmap2(ctx->inode_bb_map, + dirent->inode))) { + /* + * If the inode is in a bad block, offer to + * clear it. + */ + problem = PR_2_BB_INODE; + } else if ((dot_state > 1) && (name_len == 1) && + (dirent->name[0] == '.')) { + /* + * If there's a '.' entry in anything other + * than the first directory entry, it's a + * duplicate entry that should be removed. + */ + problem = PR_2_DUP_DOT; + } else if ((dot_state > 1) && (name_len == 2) && + (dirent->name[0] == '.') && + (dirent->name[1] == '.')) { + /* + * If there's a '..' entry in anything other + * than the second directory entry, it's a + * duplicate entry that should be removed. + */ + problem = PR_2_DUP_DOT_DOT; + } else if ((dot_state > 1) && + (dirent->inode == EXT2_ROOT_INO)) { + /* + * Don't allow links to the root directory. + * We check this specially to make sure we + * catch this error case even if the root + * directory hasn't been created yet. + */ + problem = PR_2_LINK_ROOT; + } else if ((dot_state > 1) && (name_len == 0)) { + /* + * Don't allow zero-length directory names. + */ + problem = PR_2_NULL_NAME; + } + + if (problem) { + if (fix_problem(ctx, problem, &cd->pctx)) { + dirent->inode = 0; + dir_modified++; + goto next; + } else { + ext2fs_unmark_valid(fs); + if (problem == PR_2_BAD_INO) + goto next; + } + } + + /* + * If the inode was marked as having bad fields in + * pass1, process it and offer to fix/clear it. + * (We wait until now so that we can display the + * pathname to the user.) + */ + if (ctx->inode_bad_map && + ext2fs_test_inode_bitmap2(ctx->inode_bad_map, + dirent->inode)) { + if (e2fsck_process_bad_inode(ctx, ino, + dirent->inode, + buf + fs->blocksize)) { + dirent->inode = 0; + dir_modified++; + goto next; + } + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return DIRENT_ABORT; + } + + group = ext2fs_group_of_ino(fs, dirent->inode); + first_unused_inode = group * fs->super->s_inodes_per_group + + 1 + fs->super->s_inodes_per_group - + ext2fs_bg_itable_unused(fs, group); + cd->pctx.group = group; + + /* + * Check if the inode was missed out because + * _INODE_UNINIT flag was set or bg_itable_unused was + * incorrect. If so, clear the _INODE_UNINIT flag and + * restart e2fsck. In the future it would be nice if + * we could call a function in pass1.c that checks the + * newly visible inodes. + */ + if (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT)) { + pctx.num = dirent->inode; + if (fix_problem(ctx, PR_2_INOREF_BG_INO_UNINIT, + &cd->pctx)){ + ext2fs_bg_flags_clear(fs, group, + EXT2_BG_INODE_UNINIT); + ext2fs_group_desc_csum_set(fs, group); + ext2fs_mark_super_dirty(fs); + ctx->flags |= E2F_FLAG_RESTART_LATER; + } else { + ext2fs_unmark_valid(fs); + if (problem == PR_2_BAD_INO) + goto next; + } + } else if (dirent->inode >= first_unused_inode) { + pctx.num = dirent->inode; + if (fix_problem(ctx, PR_2_INOREF_IN_UNUSED, &cd->pctx)){ + ext2fs_bg_itable_unused_set(fs, group, 0); + ext2fs_group_desc_csum_set(fs, group); + ext2fs_mark_super_dirty(fs); + ctx->flags |= E2F_FLAG_RESTART_LATER; + } else { + ext2fs_unmark_valid(fs); + if (problem == PR_2_BAD_INO) + goto next; + } + } + + /* + * Offer to clear unused inodes; if we are going to be + * restarting the scan due to bg_itable_unused being + * wrong, then don't clear any inodes to avoid zapping + * inodes that were skipped during pass1 due to an + * incorrect bg_itable_unused; we'll get any real + * problems after we restart. + */ + if (!(ctx->flags & E2F_FLAG_RESTART_LATER) && + !(ext2fs_test_inode_bitmap2(ctx->inode_used_map, + dirent->inode))) + problem = PR_2_UNUSED_INODE; + + if (problem) { + if (fix_problem(ctx, problem, &cd->pctx)) { + dirent->inode = 0; + dir_modified++; + goto next; + } else { + ext2fs_unmark_valid(fs); + if (problem == PR_2_BAD_INO) + goto next; + } + } + + if (check_filetype(ctx, dirent, ino, &cd->pctx)) + dir_modified++; + + if (dir_encpolicy_id != NO_ENCRYPTION_POLICY) { + /* Encrypted directory */ + if (dot_state > 1 && + check_encrypted_dirent(ctx, dirent, + dir_encpolicy_id, + &cd->pctx)) { + dirent->inode = 0; + dir_modified++; + goto next; + } + } else if (cf_dir) { + /* Casefolded directory */ + if (encoded_check_name(ctx, dirent, &cd->pctx)) + dir_modified++; + } else { + /* Unencrypted and uncasefolded directory */ + if (check_name(ctx, dirent, &cd->pctx)) + dir_modified++; + } + + if (dx_db) { + if (dx_dir->casefolded_hash) + hash_flags = EXT4_CASEFOLD_FL; + + if (dx_dir->hashversion == EXT2_HASH_SIPHASH) { + if (dot_state > 1) + hash = EXT2_DIRENT_HASH(dirent); + } else { + ext2fs_dirhash2(dx_dir->hashversion, + dirent->name, + ext2fs_dirent_name_len(dirent), + fs->encoding, hash_flags, + fs->super->s_hash_seed, + &hash, 0); + } + if (hash < dx_db->min_hash) + dx_db->min_hash = hash; + if (hash > dx_db->max_hash) + dx_db->max_hash = hash; + } + + /* + * If this is a directory, then mark its parent in its + * dir_info structure. If the parent field is already + * filled in, then this directory has more than one + * hard link. We assume the first link is correct, + * and ask the user if he/she wants to clear this one. + */ + if ((dot_state > 1) && + (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, + dirent->inode))) { + if (e2fsck_dir_info_get_parent(ctx, dirent->inode, + &subdir_parent)) { + cd->pctx.ino = dirent->inode; + fix_problem(ctx, PR_2_NO_DIRINFO, &cd->pctx); + goto abort_free_dict; + } + if (subdir_parent) { + cd->pctx.ino2 = subdir_parent; + if (fix_problem(ctx, PR_2_LINK_DIR, + &cd->pctx)) { + dirent->inode = 0; + dir_modified++; + goto next; + } + cd->pctx.ino2 = 0; + } else { + (void) e2fsck_dir_info_set_parent(ctx, + dirent->inode, ino); + } + } + + if (dups_found) { + ; + } else if (dict_lookup(&de_dict, dirent)) { + clear_problem_context(&pctx); + pctx.ino = ino; + pctx.dirent = dirent; + fix_problem(ctx, PR_2_REPORT_DUP_DIRENT, &pctx); + e2fsck_rehash_dir_later(ctx, ino); + dups_found++; + } else + dict_alloc_insert(&de_dict, dirent, dirent); + + ext2fs_icount_increment(ctx->inode_count, dirent->inode, + &links); + if (links > 1) + ctx->fs_links_count++; + ctx->fs_total_count++; + next: + prev = dirent; + if (dir_modified) + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + if (!inline_data_size || dot_state > 1) { + offset += rec_len; + } else { + if (dot_state == 1) { + offset = 4; + /* + * If we get here, we're checking an inline + * directory and we've just checked a (fake) + * dotdot entry that we created on the stack. + * Therefore set 'prev' to NULL so that if we + * call salvage_directory on the next entry, + * it won't try to absorb the next entry into + * the on-stack dotdot entry. + */ + prev = NULL; + } + } + dot_state++; + } while (offset < max_block_size); +#if 0 + printf("\n"); +#endif + if (dx_db) { +#ifdef DX_DEBUG + printf("db_block %d, type %d, min_hash 0x%0x, max_hash 0x%0x\n", + db->blockcnt, dx_db->type, + dx_db->min_hash, dx_db->max_hash); +#endif + cd->pctx.dir = cd->pctx.ino; + if ((dx_db->type == DX_DIRBLOCK_ROOT) || + (dx_db->type == DX_DIRBLOCK_NODE)) + parse_int_node(fs, db, cd, dx_dir, buf, failed_csum); + } + + if (offset != max_block_size) { + cd->pctx.num = rec_len + offset - max_block_size; + if (fix_problem(ctx, PR_2_FINAL_RECLEN, &cd->pctx)) { + dirent->rec_len = cd->pctx.num; + dir_modified++; + } + } + if (dir_modified) { + int flags, will_rehash; + /* leaf block with no tail? Rehash dirs later. */ + if (ext2fs_has_feature_metadata_csum(fs->super) && + is_leaf && + !inline_data_size && + !ext2fs_dirent_has_tail(fs, (struct ext2_dir_entry *)buf)) { + if (insert_dirent_tail(fs, buf) == 0) + goto write_and_fix; + e2fsck_rehash_dir_later(ctx, ino); + } + +write_and_fix: + will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino); + if (will_rehash) { + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + } + if (inline_data_size) { + buf = ibuf; +#ifdef WORDS_BIGENDIAN + if (db->blockcnt) + goto skip_first_write_swab; + *((__u32 *)buf) = ext2fs_le32_to_cpu(*((__u32 *)buf)); + cd->pctx.errcode = ext2fs_dirent_swab_out2(fs, + buf + EXT4_INLINE_DATA_DOTDOT_SIZE, + EXT4_MIN_INLINE_DATA_SIZE - + EXT4_INLINE_DATA_DOTDOT_SIZE, + 0); + if (cd->pctx.errcode) + goto skip_second_write_swab; +skip_first_write_swab: + if (inline_data_size <= EXT4_MIN_INLINE_DATA_SIZE || + !db->blockcnt) + goto skip_second_write_swab; + cd->pctx.errcode = ext2fs_dirent_swab_out2(fs, + buf + EXT4_MIN_INLINE_DATA_SIZE, + inline_data_size - + EXT4_MIN_INLINE_DATA_SIZE, + 0); +skip_second_write_swab: + if (cd->pctx.errcode && + !fix_problem(ctx, PR_2_WRITE_DIRBLOCK, &cd->pctx)) + goto abort_free_dict; +#endif + cd->pctx.errcode = + ext2fs_inline_data_set(fs, ino, 0, buf, + inline_data_size); + } else + cd->pctx.errcode = ext2fs_write_dir_block4(fs, block_nr, + buf, 0, ino); + if (will_rehash) + ctx->fs->flags = (flags & + EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & + ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (cd->pctx.errcode) { + if (!fix_problem(ctx, PR_2_WRITE_DIRBLOCK, + &cd->pctx)) + goto abort_free_dict; + } + ext2fs_mark_changed(fs); + } else if (is_leaf && failed_csum && !dir_modified) { + /* + * If a leaf node that fails csum makes it this far without + * alteration, ask the user if the checksum should be fixed. + */ + if (fix_problem(ctx, PR_2_LEAF_NODE_ONLY_CSUM_INVALID, + &cd->pctx)) + goto write_and_fix; + } + dict_free_nodes(&de_dict); + return 0; +abort_free_dict: + ctx->flags |= E2F_FLAG_ABORT; + dict_free_nodes(&de_dict); + return DIRENT_ABORT; +} + +struct del_block { + e2fsck_t ctx; + e2_blkcnt_t num; + blk64_t last_cluster; +}; + +/* + * This function is called to deallocate a block, and is an iterator + * functioned called by deallocate inode via ext2fs_iterate_block(). + */ +static int deallocate_inode_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt EXT2FS_ATTR((unused)), + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct del_block *p = priv_data; + blk64_t cluster = EXT2FS_B2C(fs, *block_nr); + + if (*block_nr == 0) + return 0; + + if (cluster == p->last_cluster) + return 0; + + p->last_cluster = cluster; + if ((*block_nr < fs->super->s_first_data_block) || + (*block_nr >= ext2fs_blocks_count(fs->super))) + return 0; + + ext2fs_block_alloc_stats2(fs, *block_nr, -1); + p->num++; + return 0; +} + +/* + * This function deallocates an inode + */ +static void deallocate_inode(e2fsck_t ctx, ext2_ino_t ino, char* block_buf) +{ + ext2_filsys fs = ctx->fs; + struct ext2_inode inode; + struct problem_context pctx; + __u32 count; + struct del_block del_block; + + e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode"); + clear_problem_context(&pctx); + pctx.ino = ino; + + /* + * Fix up the bitmaps... + */ + e2fsck_read_bitmaps(ctx); + ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(inode.i_mode)); + + if (ext2fs_file_acl_block(fs, &inode) && + ext2fs_has_feature_xattr(fs->super)) { + pctx.errcode = ext2fs_adjust_ea_refcount3(fs, + ext2fs_file_acl_block(fs, &inode), + block_buf, -1, &count, ino); + if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) { + pctx.errcode = 0; + count = 1; + } + if (pctx.errcode) { + pctx.blk = ext2fs_file_acl_block(fs, &inode); + fix_problem(ctx, PR_2_ADJ_EA_REFCOUNT, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + if (count == 0) { + ext2fs_block_alloc_stats2(fs, + ext2fs_file_acl_block(fs, &inode), -1); + } + ext2fs_file_acl_block_set(fs, &inode, 0); + } + + if (!ext2fs_inode_has_valid_blocks2(fs, &inode)) + goto clear_inode; + + /* Inline data inodes don't have blocks to iterate */ + if (inode.i_flags & EXT4_INLINE_DATA_FL) + goto clear_inode; + + if (ext2fs_needs_large_file_feature(EXT2_I_SIZE(&inode))) { + if (LINUX_S_ISREG(inode.i_mode)) + ctx->large_files--; + else if (LINUX_S_ISDIR(inode.i_mode)) + ctx->large_dirs--; + } + + del_block.ctx = ctx; + del_block.num = 0; + del_block.last_cluster = 0; + pctx.errcode = ext2fs_block_iterate3(fs, ino, 0, block_buf, + deallocate_inode_block, + &del_block); + if (pctx.errcode) { + fix_problem(ctx, PR_2_DEALLOC_INODE, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } +clear_inode: + /* Inode may have changed by block_iterate, so reread it */ + e2fsck_read_inode(ctx, ino, &inode, "deallocate_inode"); + e2fsck_clear_inode(ctx, ino, &inode, 0, "deallocate_inode"); +} + +/* + * This function clears the htree flag on an inode + */ +static void clear_htree(e2fsck_t ctx, ext2_ino_t ino) +{ + struct ext2_inode inode; + + e2fsck_read_inode(ctx, ino, &inode, "clear_htree"); + inode.i_flags = inode.i_flags & ~EXT2_INDEX_FL; + e2fsck_write_inode(ctx, ino, &inode, "clear_htree"); + if (ctx->dirs_to_hash) + ext2fs_u32_list_add(ctx->dirs_to_hash, ino); +} + + +int e2fsck_process_bad_inode(e2fsck_t ctx, ext2_ino_t dir, + ext2_ino_t ino, char *buf) +{ + ext2_filsys fs = ctx->fs; + struct ext2_inode inode; + int inode_modified = 0; + int not_fixed = 0; + unsigned char *frag, *fsize; + struct problem_context pctx; + problem_t problem = 0; + + e2fsck_read_inode(ctx, ino, &inode, "process_bad_inode"); + + clear_problem_context(&pctx); + pctx.ino = ino; + pctx.dir = dir; + pctx.inode = &inode; + + if (ext2fs_file_acl_block(fs, &inode) && + !ext2fs_has_feature_xattr(fs->super)) { + if (fix_problem(ctx, PR_2_FILE_ACL_ZERO, &pctx)) { + ext2fs_file_acl_block_set(fs, &inode, 0); + inode_modified++; + } else + not_fixed++; + } + + if (!LINUX_S_ISDIR(inode.i_mode) && !LINUX_S_ISREG(inode.i_mode) && + !LINUX_S_ISCHR(inode.i_mode) && !LINUX_S_ISBLK(inode.i_mode) && + !LINUX_S_ISLNK(inode.i_mode) && !LINUX_S_ISFIFO(inode.i_mode) && + !(LINUX_S_ISSOCK(inode.i_mode))) + problem = PR_2_BAD_MODE; + else if (LINUX_S_ISCHR(inode.i_mode) + && !e2fsck_pass1_check_device_inode(fs, &inode)) + problem = PR_2_BAD_CHAR_DEV; + else if (LINUX_S_ISBLK(inode.i_mode) + && !e2fsck_pass1_check_device_inode(fs, &inode)) + problem = PR_2_BAD_BLOCK_DEV; + else if (LINUX_S_ISFIFO(inode.i_mode) + && !e2fsck_pass1_check_device_inode(fs, &inode)) + problem = PR_2_BAD_FIFO; + else if (LINUX_S_ISSOCK(inode.i_mode) + && !e2fsck_pass1_check_device_inode(fs, &inode)) + problem = PR_2_BAD_SOCKET; + else if (LINUX_S_ISLNK(inode.i_mode) + && !e2fsck_pass1_check_symlink(fs, ino, &inode, buf)) { + problem = PR_2_INVALID_SYMLINK; + } + + if (problem) { + if (fix_problem(ctx, problem, &pctx)) { + deallocate_inode(ctx, ino, 0); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return 0; + return 1; + } else + not_fixed++; + problem = 0; + } + + if (inode.i_faddr) { + if (fix_problem(ctx, PR_2_FADDR_ZERO, &pctx)) { + inode.i_faddr = 0; + inode_modified++; + } else + not_fixed++; + } + + switch (fs->super->s_creator_os) { + case EXT2_OS_HURD: + frag = &inode.osd2.hurd2.h_i_frag; + fsize = &inode.osd2.hurd2.h_i_fsize; + break; + default: + frag = fsize = 0; + } + if (frag && *frag) { + pctx.num = *frag; + if (fix_problem(ctx, PR_2_FRAG_ZERO, &pctx)) { + *frag = 0; + inode_modified++; + } else + not_fixed++; + pctx.num = 0; + } + if (fsize && *fsize) { + pctx.num = *fsize; + if (fix_problem(ctx, PR_2_FSIZE_ZERO, &pctx)) { + *fsize = 0; + inode_modified++; + } else + not_fixed++; + pctx.num = 0; + } + + if ((fs->super->s_creator_os == EXT2_OS_LINUX) && + !ext2fs_has_feature_huge_file(fs->super) && + (inode.osd2.linux2.l_i_blocks_hi != 0)) { + pctx.num = inode.osd2.linux2.l_i_blocks_hi; + if (fix_problem(ctx, PR_2_BLOCKS_HI_ZERO, &pctx)) { + inode.osd2.linux2.l_i_blocks_hi = 0; + inode_modified++; + } + } + + if ((fs->super->s_creator_os == EXT2_OS_LINUX) && + !ext2fs_has_feature_64bit(fs->super) && + inode.osd2.linux2.l_i_file_acl_high != 0) { + pctx.num = inode.osd2.linux2.l_i_file_acl_high; + if (fix_problem(ctx, PR_2_I_FILE_ACL_HI_ZERO, &pctx)) { + inode.osd2.linux2.l_i_file_acl_high = 0; + inode_modified++; + } else + not_fixed++; + } + + if (ext2fs_file_acl_block(fs, &inode) && + ((ext2fs_file_acl_block(fs, &inode) < fs->super->s_first_data_block) || + (ext2fs_file_acl_block(fs, &inode) >= ext2fs_blocks_count(fs->super)))) { + if (fix_problem(ctx, PR_2_FILE_ACL_BAD, &pctx)) { + ext2fs_file_acl_block_set(fs, &inode, 0); + inode_modified++; + } else + not_fixed++; + } + if (inode.i_size_high && !ext2fs_has_feature_largedir(fs->super) && + inode.i_blocks < 1ULL << (29 - EXT2_BLOCK_SIZE_BITS(fs->super)) && + LINUX_S_ISDIR(inode.i_mode)) { + if (fix_problem(ctx, PR_2_DIR_SIZE_HIGH_ZERO, &pctx)) { + inode.i_size_high = 0; + inode_modified++; + } else + not_fixed++; + } + + if (inode_modified) + e2fsck_write_inode(ctx, ino, &inode, "process_bad_inode"); + if (!not_fixed && ctx->inode_bad_map) + ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino); + return 0; +} + +/* + * allocate_dir_block --- this function allocates a new directory + * block for a particular inode; this is done if a directory has + * a "hole" in it, or if a directory has a illegal block number + * that was zeroed out and now needs to be replaced. + */ +static int allocate_dir_block(e2fsck_t ctx, + struct ext2_db_entry2 *db, + char *buf EXT2FS_ATTR((unused)), + struct problem_context *pctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t blk = 0; + char *block; + struct ext2_inode inode; + + if (fix_problem(ctx, PR_2_DIRECTORY_HOLE, pctx) == 0) + return 1; + + /* + * Read the inode and block bitmaps in; we'll be messing with + * them. + */ + e2fsck_read_bitmaps(ctx); + + /* + * First, find a free block + */ + e2fsck_read_inode(ctx, db->ino, &inode, "allocate_dir_block"); + pctx->errcode = ext2fs_map_cluster_block(fs, db->ino, &inode, + db->blockcnt, &blk); + if (pctx->errcode || blk == 0) { + blk = ext2fs_find_inode_goal(fs, db->ino, &inode, db->blockcnt); + pctx->errcode = ext2fs_new_block2(fs, blk, + ctx->block_found_map, &blk); + if (pctx->errcode) { + pctx->str = "ext2fs_new_block"; + fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx); + return 1; + } + } + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); + ext2fs_mark_block_bitmap2(fs->block_map, blk); + ext2fs_mark_bb_dirty(fs); + + /* + * Now let's create the actual data block for the inode + */ + if (db->blockcnt) + pctx->errcode = ext2fs_new_dir_block(fs, 0, 0, &block); + else + pctx->errcode = ext2fs_new_dir_block(fs, db->ino, + EXT2_ROOT_INO, &block); + + if (pctx->errcode) { + pctx->str = "ext2fs_new_dir_block"; + fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx); + return 1; + } + + pctx->errcode = ext2fs_write_dir_block4(fs, blk, block, 0, db->ino); + ext2fs_free_mem(&block); + if (pctx->errcode) { + pctx->str = "ext2fs_write_dir_block"; + fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx); + return 1; + } + + /* + * Update the inode block count + */ + ext2fs_iblk_add_blocks(fs, &inode, 1); + if (EXT2_I_SIZE(&inode) < ((__u64) db->blockcnt+1) * fs->blocksize) { + pctx->errcode = ext2fs_inode_size_set(fs, &inode, + (db->blockcnt+1) * fs->blocksize); + if (pctx->errcode) { + pctx->str = "ext2fs_inode_size_set"; + fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx); + return 1; + } + } + e2fsck_write_inode(ctx, db->ino, &inode, "allocate_dir_block"); + + /* + * Finally, update the block pointers for the inode + */ + db->blk = blk; + pctx->errcode = ext2fs_bmap2(fs, db->ino, &inode, 0, BMAP_SET, + db->blockcnt, 0, &blk); + if (pctx->errcode) { + pctx->str = "ext2fs_block_iterate"; + fix_problem(ctx, PR_2_ALLOC_DIRBOCK, pctx); + return 1; + } + + return 0; +} diff --git a/e2fsck/pass3.c b/e2fsck/pass3.c new file mode 100644 index 0000000..16d243f --- /dev/null +++ b/e2fsck/pass3.c @@ -0,0 +1,921 @@ +/* + * pass3.c -- pass #3 of e2fsck: Check for directory connectivity + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * Pass #3 assures that all directories are connected to the + * filesystem tree, using the following algorithm: + * + * First, the root directory is checked to make sure it exists; if + * not, e2fsck will offer to create a new one. It is then marked as + * "done". + * + * Then, pass3 iterates over all directory inodes; for each directory + * it attempts to trace up the filesystem tree, using dirinfo.parent + * until it reaches a directory which has been marked "done". If it + * can not do so, then the directory must be disconnected, and e2fsck + * will offer to reconnect it to /lost+found. While it is chasing + * parent pointers up the filesystem tree, if pass3 sees a directory + * twice, then it has detected a filesystem loop, and it will again + * offer to reconnect the directory to /lost+found in order to break the + * filesystem loop. + * + * Pass 3 also contains the subroutine, e2fsck_reconnect_file() to + * reconnect inodes to /lost+found; this subroutine is also used by + * pass 4. e2fsck_reconnect_file() calls get_lost_and_found(), which + * is responsible for creating /lost+found if it does not exist. + * + * Pass 3 frees the following data structures: + * - The dirinfo directory information cache. + */ + +#include "config.h" +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "e2fsck.h" +#include "problem.h" + +static void check_root(e2fsck_t ctx); +static int check_directory(e2fsck_t ctx, ext2_ino_t ino, + struct problem_context *pctx); +static void fix_dotdot(e2fsck_t ctx, ext2_ino_t ino, ext2_ino_t parent); + +static ext2fs_inode_bitmap inode_loop_detect = 0; +static ext2fs_inode_bitmap inode_done_map = 0; + +void e2fsck_pass3(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + struct dir_info_iter *iter = NULL; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct problem_context pctx; + struct dir_info *dir; + unsigned long maxdirs, count; + + init_resource_track(&rtrack, ctx->fs->io); + clear_problem_context(&pctx); + +#ifdef MTRACE + mtrace_print("Pass 3"); +#endif + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_3_PASS_HEADER, &pctx); + + /* + * Allocate some bitmaps to do loop detection. + */ + pctx.errcode = e2fsck_allocate_inode_bitmap(fs, _("inode done bitmap"), + EXT2FS_BMAP64_AUTODIR, + "inode_done_map", &inode_done_map); + if (pctx.errcode) { + pctx.num = 2; + fix_problem(ctx, PR_3_ALLOCATE_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto abort_exit; + } + print_resource_track(ctx, _("Peak memory"), &ctx->global_rtrack, NULL); + + check_root(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto abort_exit; + + ext2fs_mark_inode_bitmap2(inode_done_map, EXT2_ROOT_INO); + + maxdirs = e2fsck_get_num_dirinfo(ctx); + count = 1; + + if (ctx->progress) + if ((ctx->progress)(ctx, 3, 0, maxdirs)) + goto abort_exit; + + iter = e2fsck_dir_info_iter_begin(ctx); + while ((dir = e2fsck_dir_info_iter(ctx, iter)) != 0) { + if (ctx->flags & E2F_FLAG_SIGNAL_MASK || + ctx->flags & E2F_FLAG_RESTART) + goto abort_exit; + if (ctx->progress && (ctx->progress)(ctx, 3, count++, maxdirs)) + goto abort_exit; + if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dir->ino)) + if (check_directory(ctx, dir->ino, &pctx)) + goto abort_exit; + } + + /* + * Force the creation of /lost+found if not present + */ + if ((ctx->options & E2F_OPT_READONLY) == 0) + e2fsck_get_lost_and_found(ctx, 1); + + /* + * If there are any directories that need to be indexed or + * optimized, do it here. + */ + e2fsck_rehash_directories(ctx); + +abort_exit: + if (iter) + e2fsck_dir_info_iter_end(ctx, iter); + e2fsck_free_dir_info(ctx); + if (inode_loop_detect) { + ext2fs_free_inode_bitmap(inode_loop_detect); + inode_loop_detect = 0; + } + if (inode_done_map) { + ext2fs_free_inode_bitmap(inode_done_map); + inode_done_map = 0; + } + + if (ctx->lnf_repair_block) { + ext2fs_unmark_block_bitmap2(ctx->block_found_map, + ctx->lnf_repair_block); + ctx->lnf_repair_block = 0; + } + if (ctx->root_repair_block) { + ext2fs_unmark_block_bitmap2(ctx->block_found_map, + ctx->root_repair_block); + ctx->root_repair_block = 0; + } + + print_resource_track(ctx, _("Pass 3"), &rtrack, ctx->fs->io); +} + +/* + * This makes sure the root inode is present; if not, we ask if the + * user wants us to create it. Not creating it is a fatal error. + */ +static void check_root(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t blk; + struct ext2_inode_large inode; + struct ext2_inode *iptr = (struct ext2_inode *) &inode; + char * block; + struct problem_context pctx; + + clear_problem_context(&pctx); + + if (ext2fs_test_inode_bitmap2(ctx->inode_used_map, EXT2_ROOT_INO)) { + /* + * If the root inode is not a directory, die here. The + * user must have answered 'no' in pass1 when we + * offered to clear it. + */ + if (!(ext2fs_test_inode_bitmap2(ctx->inode_dir_map, + EXT2_ROOT_INO))) { + fix_problem(ctx, PR_3_ROOT_NOT_DIR_ABORT, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + } + return; + } + + if (!fix_problem(ctx, PR_3_NO_ROOT_INODE, &pctx)) { + fix_problem(ctx, PR_3_NO_ROOT_INODE_ABORT, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + e2fsck_read_bitmaps(ctx); + + /* + * First, find a free block + */ + if (ctx->root_repair_block) { + blk = ctx->root_repair_block; + ctx->root_repair_block = 0; + goto skip_new_block; + } + pctx.errcode = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk); + if (pctx.errcode) { + pctx.str = "ext2fs_new_block"; + fix_problem(ctx, PR_3_CREATE_ROOT_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); +skip_new_block: + ext2fs_mark_block_bitmap2(fs->block_map, blk); + ext2fs_mark_bb_dirty(fs); + + /* + * Set up the inode structure + */ + memset(&inode, 0, sizeof(inode)); + inode.i_mode = 040755; + inode.i_size = fs->blocksize; + inode.i_atime = inode.i_ctime = inode.i_mtime = ctx->now; + inode.i_links_count = 2; + ext2fs_iblk_set(fs, iptr, 1); + inode.i_block[0] = blk; + inode.i_extra_isize = sizeof(struct ext2_inode_large) - + EXT2_GOOD_OLD_INODE_SIZE; + + /* + * Write out the inode. + */ + pctx.errcode = ext2fs_write_new_inode(fs, EXT2_ROOT_INO, iptr); + if (pctx.errcode) { + pctx.str = "ext2fs_write_inode"; + fix_problem(ctx, PR_3_CREATE_ROOT_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + /* + * Now let's create the actual data block for the inode. + * Due to metadata_csum, we must write the dir blocks AFTER + * the inode has been written to disk! + */ + pctx.errcode = ext2fs_new_dir_block(fs, EXT2_ROOT_INO, EXT2_ROOT_INO, + &block); + if (pctx.errcode) { + pctx.str = "ext2fs_new_dir_block"; + fix_problem(ctx, PR_3_CREATE_ROOT_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + pctx.errcode = ext2fs_write_dir_block4(fs, blk, block, 0, + EXT2_ROOT_INO); + ext2fs_free_mem(&block); + if (pctx.errcode) { + pctx.str = "ext2fs_write_dir_block4"; + fix_problem(ctx, PR_3_CREATE_ROOT_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + /* + * Miscellaneous bookkeeping... + */ + e2fsck_add_dir_info(ctx, EXT2_ROOT_INO, EXT2_ROOT_INO); + ext2fs_icount_store(ctx->inode_count, EXT2_ROOT_INO, 2); + ext2fs_icount_store(ctx->inode_link_info, EXT2_ROOT_INO, 2); + + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, EXT2_ROOT_INO); + ext2fs_mark_inode_bitmap2(ctx->inode_dir_map, EXT2_ROOT_INO); + ext2fs_mark_inode_bitmap2(fs->inode_map, EXT2_ROOT_INO); + ext2fs_mark_ib_dirty(fs); + quota_data_add(ctx->qctx, &inode, EXT2_ROOT_INO, + EXT2_CLUSTER_SIZE(fs->super)); + quota_data_inodes(ctx->qctx, &inode, EXT2_ROOT_INO, +1); +} + +/* + * This subroutine is responsible for making sure that a particular + * directory is connected to the root; if it isn't we trace it up as + * far as we can go, and then offer to connect the resulting parent to + * the lost+found. We have to do loop detection; if we ever discover + * a loop, we treat that as a disconnected directory and offer to + * reparent it to lost+found. + * + * However, loop detection is expensive, because for very large + * filesystems, the inode_loop_detect bitmap is huge, and clearing it + * is non-trivial. Loops in filesystems are also a rare error case, + * and we shouldn't optimize for error cases. So we try two passes of + * the algorithm. The first time, we ignore loop detection and merely + * increment a counter; if the counter exceeds some extreme threshold, + * then we try again with the loop detection bitmap enabled. + */ +static int check_directory(e2fsck_t ctx, ext2_ino_t dir, + struct problem_context *pctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t ino = dir, parent; + int loop_pass = 0, parent_count = 0; + + while (1) { + /* + * Mark this inode as being "done"; by the time we + * return from this function, the inode we either be + * verified as being connected to the directory tree, + * or we will have offered to reconnect this to + * lost+found. + * + * If it was marked done already, then we've reached a + * parent we've already checked. + */ + if (ext2fs_mark_inode_bitmap2(inode_done_map, ino)) + break; + + if (e2fsck_dir_info_get_parent(ctx, ino, &parent)) { + fix_problem(ctx, PR_3_NO_DIRINFO, pctx); + return 0; + } + + /* + * If this directory doesn't have a parent, or we've + * seen the parent once already, then offer to + * reparent it to lost+found + */ + if (!parent || + (loop_pass && + ext2fs_test_inode_bitmap2(inode_loop_detect, parent))) { + pctx->ino = ino; + if (parent) + pctx->dir = parent; + else + (void) ext2fs_lookup(fs, ino, "..", 2, NULL, + &pctx->dir); + if (fix_problem(ctx, !parent ? PR_3_UNCONNECTED_DIR : + PR_3_LOOPED_DIR, pctx)) { + if (e2fsck_reconnect_file(ctx, pctx->ino)) { + ext2fs_unmark_valid(fs); + } else { + fix_dotdot(ctx, pctx->ino, + ctx->lost_and_found); + parent = ctx->lost_and_found; + } + } + break; + } + ino = parent; + if (loop_pass) { + ext2fs_mark_inode_bitmap2(inode_loop_detect, ino); + } else if (parent_count++ > 2048) { + /* + * If we've run into a path depth that's + * greater than 2048, try again with the inode + * loop bitmap turned on and start from the + * top. + */ + loop_pass = 1; + if (inode_loop_detect) + ext2fs_clear_inode_bitmap(inode_loop_detect); + else { + pctx->errcode = e2fsck_allocate_inode_bitmap(fs, _("inode loop detection bitmap"), EXT2FS_BMAP64_AUTODIR, "inode_loop_detect", &inode_loop_detect); + if (pctx->errcode) { + pctx->num = 1; + fix_problem(ctx, + PR_3_ALLOCATE_IBITMAP_ERROR, pctx); + ctx->flags |= E2F_FLAG_ABORT; + return -1; + } + } + ino = dir; + } + } + + /* + * Make sure that .. and the parent directory are the same; + * offer to fix it if not. + */ + pctx->ino = dir; + if (e2fsck_dir_info_get_dotdot(ctx, dir, &pctx->ino2) || + e2fsck_dir_info_get_parent(ctx, dir, &pctx->dir)) { + fix_problem(ctx, PR_3_NO_DIRINFO, pctx); + return 0; + } + if (pctx->ino2 != pctx->dir) { + if (fix_problem(ctx, PR_3_BAD_DOT_DOT, pctx)) + fix_dotdot(ctx, dir, pctx->dir); + } + return 0; +} + +/* + * This routine gets the lost_and_found inode, making it a directory + * if necessary + */ +ext2_ino_t e2fsck_get_lost_and_found(e2fsck_t ctx, int fix) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t ino; + blk64_t blk; + errcode_t retval; + struct ext2_inode_large inode; + char * block; + static const char name[] = "lost+found"; + struct problem_context pctx; + int will_rehash, flags; + + if (ctx->lost_and_found) + return ctx->lost_and_found; + + clear_problem_context(&pctx); + + will_rehash = e2fsck_dir_will_be_rehashed(ctx, EXT2_ROOT_INO); + if (will_rehash) { + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + } + retval = ext2fs_lookup(fs, EXT2_ROOT_INO, name, + sizeof(name)-1, 0, &ino); + if (will_rehash) + ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (retval && !fix) + return 0; + if (!retval) { + /* Lost+found shouldn't have inline data */ + retval = ext2fs_read_inode_full(fs, ino, EXT2_INODE(&inode), + sizeof(inode)); + if (fix && retval) + return 0; + + if (fix && (inode.i_flags & EXT4_INLINE_DATA_FL)) { + if (!fix_problem(ctx, PR_3_LPF_INLINE_DATA, &pctx)) + return 0; + goto unlink; + } + + if (fix && (inode.i_flags & EXT4_ENCRYPT_FL)) { + if (!fix_problem(ctx, PR_3_LPF_ENCRYPTED, &pctx)) + return 0; + goto unlink; + } + + if (ext2fs_check_directory(fs, ino) == 0) { + ctx->lost_and_found = ino; + return ino; + } + + /* Lost+found isn't a directory! */ + if (!fix) + return 0; + pctx.ino = ino; + if (!fix_problem(ctx, PR_3_LPF_NOTDIR, &pctx)) + return 0; + +unlink: + /* OK, unlink the old /lost+found file. */ + pctx.errcode = ext2fs_unlink(fs, EXT2_ROOT_INO, name, ino, 0); + if (pctx.errcode) { + pctx.str = "ext2fs_unlink"; + fix_problem(ctx, PR_3_CREATE_LPF_ERROR, &pctx); + return 0; + } + (void) e2fsck_dir_info_set_parent(ctx, ino, 0); + e2fsck_adjust_inode_count(ctx, ino, -1); + /* + * If the old lost+found was a directory, we've just + * disconnected it from the directory tree, which + * means we need to restart the directory tree scan. + * The simplest way to do this is restart the whole + * e2fsck operation. + */ + if (LINUX_S_ISDIR(inode.i_mode)) + ctx->flags |= E2F_FLAG_RESTART; + } else if (retval != EXT2_ET_FILE_NOT_FOUND) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_ERR_FIND_LPF, &pctx); + } + if (!fix_problem(ctx, PR_3_NO_LF_DIR, 0)) + return 0; + + /* + * Read the inode and block bitmaps in; we'll be messing with + * them. + */ + e2fsck_read_bitmaps(ctx); + + /* + * First, find a free block + */ + if (ctx->lnf_repair_block) { + blk = ctx->lnf_repair_block; + ctx->lnf_repair_block = 0; + goto skip_new_block; + } + retval = ext2fs_new_block2(fs, 0, ctx->block_found_map, &blk); + if (retval == EXT2_ET_BLOCK_ALLOC_FAIL && + fix_problem(ctx, PR_3_LPF_NO_SPACE, &pctx)) { + fix_problem(ctx, PR_3_NO_SPACE_TO_RECOVER, &pctx); + ctx->lost_and_found = EXT2_ROOT_INO; + return 0; + } + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_ERR_LPF_NEW_BLOCK, &pctx); + return 0; + } + ext2fs_mark_block_bitmap2(ctx->block_found_map, blk); +skip_new_block: + ext2fs_block_alloc_stats2(fs, blk, +1); + + /* + * Next find a free inode. + */ + retval = ext2fs_new_inode(fs, EXT2_ROOT_INO, 040700, + ctx->inode_used_map, &ino); + if (retval == EXT2_ET_INODE_ALLOC_FAIL && + fix_problem(ctx, PR_3_LPF_NO_SPACE, &pctx)) { + fix_problem(ctx, PR_3_NO_SPACE_TO_RECOVER, &pctx); + ctx->lost_and_found = EXT2_ROOT_INO; + return 0; + } + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_ERR_LPF_NEW_INODE, &pctx); + return 0; + } + ext2fs_mark_inode_bitmap2(ctx->inode_used_map, ino); + ext2fs_mark_inode_bitmap2(ctx->inode_dir_map, ino); + ext2fs_inode_alloc_stats2(fs, ino, +1, 1); + + /* + * Set up the inode structure + */ + memset(&inode, 0, sizeof(inode)); + inode.i_mode = 040700; + inode.i_size = fs->blocksize; + inode.i_atime = inode.i_ctime = inode.i_mtime = ctx->now; + inode.i_links_count = 2; + ext2fs_iblk_set(fs, EXT2_INODE(&inode), 1); + inode.i_block[0] = blk; + + /* + * Next, write out the inode. + */ + pctx.errcode = ext2fs_write_new_inode(fs, ino, EXT2_INODE(&inode)); + if (pctx.errcode) { + pctx.str = "ext2fs_write_inode"; + fix_problem(ctx, PR_3_CREATE_LPF_ERROR, &pctx); + return 0; + } + + /* + * Now let's create the actual data block for the inode. + * Due to metadata_csum, the directory block MUST be written + * after the inode is written to disk! + */ + retval = ext2fs_new_dir_block(fs, ino, EXT2_ROOT_INO, &block); + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_ERR_LPF_NEW_DIR_BLOCK, &pctx); + return 0; + } + + retval = ext2fs_write_dir_block4(fs, blk, block, 0, ino); + ext2fs_free_mem(&block); + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_ERR_LPF_WRITE_BLOCK, &pctx); + return 0; + } + + /* + * Finally, create the directory link + */ + pctx.errcode = ext2fs_link(fs, EXT2_ROOT_INO, name, ino, EXT2_FT_DIR); + if (pctx.errcode == EXT2_ET_DIR_NO_SPACE) { + pctx.errcode = ext2fs_expand_dir(fs, EXT2_ROOT_INO); + if (pctx.errcode) + goto link_error; + pctx.errcode = ext2fs_link(fs, EXT2_ROOT_INO, name, ino, + EXT2_FT_DIR); + } + if (pctx.errcode) { +link_error: + pctx.str = "ext2fs_link"; + fix_problem(ctx, PR_3_CREATE_LPF_ERROR, &pctx); + return 0; + } + + /* + * Miscellaneous bookkeeping that needs to be kept straight. + */ + e2fsck_add_dir_info(ctx, ino, EXT2_ROOT_INO); + e2fsck_adjust_inode_count(ctx, EXT2_ROOT_INO, 1); + ext2fs_icount_store(ctx->inode_count, ino, 2); + ext2fs_icount_store(ctx->inode_link_info, ino, 2); + ctx->lost_and_found = ino; + quota_data_add(ctx->qctx, &inode, ino, EXT2_CLUSTER_SIZE(fs->super)); + quota_data_inodes(ctx->qctx, &inode, ino, +1); +#if 0 + printf("/lost+found created; inode #%lu\n", ino); +#endif + return ino; +} + +/* + * This routine will connect a file to lost+found + */ +int e2fsck_reconnect_file(e2fsck_t ctx, ext2_ino_t ino) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + char name[80]; + struct problem_context pctx; + struct ext2_inode inode; + int file_type = 0; + + clear_problem_context(&pctx); + pctx.ino = ino; + + if (!ctx->bad_lost_and_found && !ctx->lost_and_found) { + if (e2fsck_get_lost_and_found(ctx, 1) == 0) + ctx->bad_lost_and_found++; + } + if (ctx->bad_lost_and_found) { + fix_problem(ctx, PR_3_NO_LPF, &pctx); + return 1; + } + + sprintf(name, "#%u", ino); + if (ext2fs_read_inode(fs, ino, &inode) == 0) + file_type = ext2_file_type(inode.i_mode); + retval = ext2fs_link(fs, ctx->lost_and_found, name, ino, file_type); + if (retval == EXT2_ET_DIR_NO_SPACE) { + if (!fix_problem(ctx, PR_3_EXPAND_LF_DIR, &pctx)) + return 1; + retval = e2fsck_expand_directory(ctx, ctx->lost_and_found, + 1, 0); + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_CANT_EXPAND_LPF, &pctx); + return 1; + } + retval = ext2fs_link(fs, ctx->lost_and_found, name, + ino, file_type); + } + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3_CANT_RECONNECT, &pctx); + return 1; + } + e2fsck_adjust_inode_count(ctx, ino, 1); + + return 0; +} + +/* + * Utility routine to adjust the inode counts on an inode. + */ +errcode_t e2fsck_adjust_inode_count(e2fsck_t ctx, ext2_ino_t ino, int adj) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + struct ext2_inode inode; + + if (!ino) + return 0; + + retval = ext2fs_read_inode(fs, ino, &inode); + if (retval) + return retval; + +#if 0 + printf("Adjusting link count for inode %lu by %d (from %d)\n", ino, adj, + inode.i_links_count); +#endif + + if (adj == 1) { + ext2fs_icount_increment(ctx->inode_count, ino, 0); + if (inode.i_links_count == (__u16) ~0) + return 0; + ext2fs_icount_increment(ctx->inode_link_info, ino, 0); + inode.i_links_count++; + } else if (adj == -1) { + ext2fs_icount_decrement(ctx->inode_count, ino, 0); + if (inode.i_links_count == 0) + return 0; + ext2fs_icount_decrement(ctx->inode_link_info, ino, 0); + inode.i_links_count--; + } + + retval = ext2fs_write_inode(fs, ino, &inode); + if (retval) + return retval; + + return 0; +} + +/* + * Fix parent --- this routine fixes up the parent of a directory. + */ +struct fix_dotdot_struct { + ext2_filsys fs; + ext2_ino_t parent; + int done; + e2fsck_t ctx; +}; + +static int fix_dotdot_proc(struct ext2_dir_entry *dirent, + int offset EXT2FS_ATTR((unused)), + int blocksize EXT2FS_ATTR((unused)), + char *buf EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct fix_dotdot_struct *fp = (struct fix_dotdot_struct *) priv_data; + errcode_t retval; + struct problem_context pctx; + + if (ext2fs_dirent_name_len(dirent) != 2) + return 0; + if (strncmp(dirent->name, "..", 2)) + return 0; + + clear_problem_context(&pctx); + + retval = e2fsck_adjust_inode_count(fp->ctx, dirent->inode, -1); + if (retval) { + pctx.errcode = retval; + fix_problem(fp->ctx, PR_3_ADJUST_INODE, &pctx); + } + retval = e2fsck_adjust_inode_count(fp->ctx, fp->parent, 1); + if (retval) { + pctx.errcode = retval; + fix_problem(fp->ctx, PR_3_ADJUST_INODE, &pctx); + } + dirent->inode = fp->parent; + if (ext2fs_has_feature_filetype(fp->ctx->fs->super)) + ext2fs_dirent_set_file_type(dirent, EXT2_FT_DIR); + else + ext2fs_dirent_set_file_type(dirent, EXT2_FT_UNKNOWN); + + fp->done++; + return DIRENT_ABORT | DIRENT_CHANGED; +} + +static void fix_dotdot(e2fsck_t ctx, ext2_ino_t ino, ext2_ino_t parent) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + struct fix_dotdot_struct fp; + struct problem_context pctx; + int flags, will_rehash; + + fp.fs = fs; + fp.parent = parent; + fp.done = 0; + fp.ctx = ctx; + +#if 0 + printf("Fixing '..' of inode %lu to be %lu...\n", ino, parent); +#endif + + clear_problem_context(&pctx); + pctx.ino = ino; + will_rehash = e2fsck_dir_will_be_rehashed(ctx, ino); + if (will_rehash) { + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + } + retval = ext2fs_dir_iterate(fs, ino, DIRENT_FLAG_INCLUDE_EMPTY, + 0, fix_dotdot_proc, &fp); + if (will_rehash) + ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (retval || !fp.done) { + pctx.errcode = retval; + fix_problem(ctx, retval ? PR_3_FIX_PARENT_ERR : + PR_3_FIX_PARENT_NOFIND, &pctx); + ext2fs_unmark_valid(fs); + } + (void) e2fsck_dir_info_set_dotdot(ctx, ino, parent); + if (e2fsck_dir_info_set_parent(ctx, ino, ctx->lost_and_found)) + fix_problem(ctx, PR_3_NO_DIRINFO, &pctx); + + return; +} + +/* + * These routines are responsible for expanding a /lost+found if it is + * too small. + */ + +struct expand_dir_struct { + blk64_t num; + e2_blkcnt_t guaranteed_size; + blk64_t newblocks; + blk64_t last_block; + errcode_t err; + e2fsck_t ctx; + ext2_ino_t dir; +}; + +static int expand_dir_proc(ext2_filsys fs, + blk64_t *blocknr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct expand_dir_struct *es = (struct expand_dir_struct *) priv_data; + blk64_t new_blk; + static blk64_t last_blk = 0; + char *block; + errcode_t retval; + e2fsck_t ctx; + + ctx = es->ctx; + + if (es->guaranteed_size && blockcnt >= es->guaranteed_size) + return BLOCK_ABORT; + + if (blockcnt > 0) + es->last_block = blockcnt; + if (*blocknr) { + last_blk = *blocknr; + return 0; + } + + if (blockcnt && + (EXT2FS_B2C(fs, last_blk) == EXT2FS_B2C(fs, last_blk + 1))) + new_blk = last_blk + 1; + else { + last_blk &= ~EXT2FS_CLUSTER_MASK(fs); + retval = ext2fs_new_block2(fs, last_blk, ctx->block_found_map, + &new_blk); + if (retval) { + es->err = retval; + return BLOCK_ABORT; + } + es->newblocks++; + ext2fs_block_alloc_stats2(fs, new_blk, +1); + } + last_blk = new_blk; + + if (blockcnt > 0) { + retval = ext2fs_new_dir_block(fs, 0, 0, &block); + if (retval) { + es->err = retval; + return BLOCK_ABORT; + } + es->num--; + retval = ext2fs_write_dir_block4(fs, new_blk, block, 0, + es->dir); + ext2fs_free_mem(&block); + } else + retval = ext2fs_zero_blocks2(fs, new_blk, 1, NULL, NULL); + if (retval) { + es->err = retval; + return BLOCK_ABORT; + } + *blocknr = new_blk; + ext2fs_mark_block_bitmap2(ctx->block_found_map, new_blk); + + if (es->num == 0) + return (BLOCK_CHANGED | BLOCK_ABORT); + else + return BLOCK_CHANGED; +} + +errcode_t e2fsck_expand_directory(e2fsck_t ctx, ext2_ino_t dir, + int num, int guaranteed_size) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + struct expand_dir_struct es; + struct ext2_inode_large inode; + blk64_t sz; + + if (!(fs->flags & EXT2_FLAG_RW)) + return EXT2_ET_RO_FILSYS; + + /* + * Read the inode and block bitmaps in; we'll be messing with + * them. + */ + e2fsck_read_bitmaps(ctx); + + retval = ext2fs_check_directory(fs, dir); + if (retval) + return retval; + + es.num = num; + es.guaranteed_size = guaranteed_size; + es.last_block = 0; + es.err = 0; + es.newblocks = 0; + es.ctx = ctx; + es.dir = dir; + + retval = ext2fs_block_iterate3(fs, dir, BLOCK_FLAG_APPEND, + 0, expand_dir_proc, &es); + + if (es.err) + return es.err; + + /* + * Update the size and block count fields in the inode. + */ + retval = ext2fs_read_inode_full(fs, dir, + EXT2_INODE(&inode), sizeof(inode)); + if (retval) + return retval; + + sz = (es.last_block + 1) * fs->blocksize; + retval = ext2fs_inode_size_set(fs, EXT2_INODE(&inode), sz); + if (retval) + return retval; + ext2fs_iblk_add_blocks(fs, EXT2_INODE(&inode), es.newblocks); + quota_data_add(ctx->qctx, &inode, dir, + es.newblocks * EXT2_CLUSTER_SIZE(fs->super)); + + e2fsck_write_inode_full(ctx, dir, EXT2_INODE(&inode), + sizeof(inode), "expand_directory"); + + return 0; +} + diff --git a/e2fsck/pass4.c b/e2fsck/pass4.c new file mode 100644 index 0000000..d2dda02 --- /dev/null +++ b/e2fsck/pass4.c @@ -0,0 +1,302 @@ +/* + * pass4.c -- pass #4 of e2fsck: Check reference counts + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * Pass 4 frees the following data structures: + * - A bitmap of which inodes are in bad blocks. (inode_bb_map) + * - A bitmap of which inodes are imagic inodes. (inode_imagic_map) + * - Ref counts for ea_inodes. (ea_inode_refs) + */ + +#include "config.h" +#include "e2fsck.h" +#include "problem.h" +#include <ext2fs/ext2_ext_attr.h> + +/* + * This routine is called when an inode is not connected to the + * directory tree. + * + * This subroutine returns 1 then the caller shouldn't bother with the + * rest of the pass 4 tests. + */ +static int disconnect_inode(e2fsck_t ctx, ext2_ino_t i, ext2_ino_t *last_ino, + struct ext2_inode_large *inode) +{ + ext2_filsys fs = ctx->fs; + struct problem_context pctx; + __u32 eamagic = 0; + int extra_size = 0; + + if (*last_ino != i) { + e2fsck_read_inode_full(ctx, i, EXT2_INODE(inode), + EXT2_INODE_SIZE(fs->super), + "pass4: disconnect_inode"); + *last_ino = i; + } + if (EXT2_INODE_SIZE(fs->super) > EXT2_GOOD_OLD_INODE_SIZE) + extra_size = inode->i_extra_isize; + + clear_problem_context(&pctx); + pctx.ino = i; + pctx.inode = EXT2_INODE(inode); + + if (EXT2_INODE_SIZE(fs->super) -EXT2_GOOD_OLD_INODE_SIZE -extra_size >0) + eamagic = *(__u32 *)(((char *)inode) +EXT2_GOOD_OLD_INODE_SIZE + + extra_size); + /* + * Offer to delete any zero-length files that does not have + * blocks. If there is an EA block, it might have useful + * information, so we won't prompt to delete it, but let it be + * reconnected to lost+found. + */ + if (!inode->i_blocks && eamagic != EXT2_EXT_ATTR_MAGIC && + (LINUX_S_ISREG(inode->i_mode) || LINUX_S_ISDIR(inode->i_mode))) { + if (fix_problem(ctx, PR_4_ZERO_LEN_INODE, &pctx)) { + e2fsck_clear_inode(ctx, i, EXT2_INODE(inode), 0, + "disconnect_inode"); + /* + * Fix up the bitmaps... + */ + e2fsck_read_bitmaps(ctx); + ext2fs_inode_alloc_stats2(fs, i, -1, + LINUX_S_ISDIR(inode->i_mode)); + quota_data_inodes(ctx->qctx, inode, i, -1); + return 0; + } + } + + /* + * Prompt to reconnect. + */ + if (fix_problem(ctx, PR_4_UNATTACHED_INODE, &pctx)) { + if (e2fsck_reconnect_file(ctx, i)) + ext2fs_unmark_valid(fs); + *last_ino = 0; + } else { + /* + * If we don't attach the inode, then skip the + * i_links_test since there's no point in trying to + * force i_links_count to zero. + */ + ext2fs_unmark_valid(fs); + return 1; + } + return 0; +} + +/* + * This function is called when link_counted is zero. So this may not be + * an xattr inode at all. Return immediately if EA_INODE flag is not set. + */ +static void check_ea_inode(e2fsck_t ctx, ext2_ino_t i, ext2_ino_t *last_ino, + struct ext2_inode_large *inode, __u16 *link_counted) +{ + __u64 actual_refs = 0; + __u64 ref_count; + + if (*last_ino != i) { + e2fsck_read_inode_full(ctx, i, EXT2_INODE(inode), + EXT2_INODE_SIZE(ctx->fs->super), + "pass4: check_ea_inode"); + *last_ino = i; + } + if (!(inode->i_flags & EXT4_EA_INODE_FL)) + return; + + if (ctx->ea_inode_refs) + ea_refcount_fetch(ctx->ea_inode_refs, i, &actual_refs); + if (!actual_refs) + return; + + /* + * There are some attribute references, link_counted is now considered + * to be 1. + */ + *link_counted = 1; + + ref_count = ext2fs_get_ea_inode_ref(EXT2_INODE(inode)); + + /* Old Lustre-style xattr inodes do not have a stored refcount. + * However, their i_ctime and i_atime should be the same. + */ + if (ref_count != actual_refs && inode->i_ctime != inode->i_atime) { + struct problem_context pctx; + + clear_problem_context(&pctx); + pctx.ino = i; + pctx.num = ref_count; + pctx.num2 = actual_refs; + if (fix_problem(ctx, PR_4_EA_INODE_REF_COUNT, &pctx)) { + ext2fs_set_ea_inode_ref(EXT2_INODE(inode), actual_refs); + e2fsck_write_inode(ctx, i, EXT2_INODE(inode), "pass4"); + } + } +} + +void e2fsck_pass4(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t i; + struct ext2_inode_large *inode; + int inode_size = EXT2_INODE_SIZE(fs->super); +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct problem_context pctx; + __u16 link_count, link_counted; + int dir_nlink_fs; + char *buf = 0; + dgrp_t group, maxgroup; + + init_resource_track(&rtrack, ctx->fs->io); + +#ifdef MTRACE + mtrace_print("Pass 4"); +#endif + /* + * Since pass4 is mostly CPU bound, start readahead of bitmaps + * ahead of pass 5 if we haven't already loaded them. + */ + if (ctx->readahead_kb && + (fs->block_map == NULL || fs->inode_map == NULL)) + e2fsck_readahead(fs, E2FSCK_READA_BBITMAP | + E2FSCK_READA_IBITMAP, + 0, fs->group_desc_count); + + clear_problem_context(&pctx); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_4_PASS_HEADER, &pctx); + + dir_nlink_fs = ext2fs_has_feature_dir_nlink(fs->super); + + group = 0; + maxgroup = fs->group_desc_count; + if (ctx->progress) + if ((ctx->progress)(ctx, 4, 0, maxgroup)) + return; + + inode = e2fsck_allocate_memory(ctx, inode_size, "scratch inode"); + + /* Protect loop from wrap-around if s_inodes_count maxed */ + for (i = 1; i <= fs->super->s_inodes_count && i > 0; i++) { + ext2_ino_t last_ino = 0; + int isdir; + + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + goto errout; + if ((i % fs->super->s_inodes_per_group) == 0) { + group++; + if (ctx->progress) + if ((ctx->progress)(ctx, 4, group, maxgroup)) + goto errout; + } + if (i == quota_type2inum(PRJQUOTA, ctx->fs->super) || + i == fs->super->s_orphan_file_inum || i == EXT2_BAD_INO || + (i > EXT2_ROOT_INO && i < EXT2_FIRST_INODE(fs->super))) + continue; + if (!(ext2fs_test_inode_bitmap2(ctx->inode_used_map, i)) || + (ctx->inode_imagic_map && + ext2fs_test_inode_bitmap2(ctx->inode_imagic_map, i)) || + (ctx->inode_bb_map && + ext2fs_test_inode_bitmap2(ctx->inode_bb_map, i))) + continue; + ext2fs_icount_fetch(ctx->inode_link_info, i, &link_count); + ext2fs_icount_fetch(ctx->inode_count, i, &link_counted); + + if (link_counted == 0) { + /* + * link_counted is expected to be 0 for an ea_inode. + * check_ea_inode() will update link_counted if + * necessary. + */ + check_ea_inode(ctx, i, &last_ino, inode, &link_counted); + } + + if (link_counted == 0) { + if (!buf) + buf = e2fsck_allocate_memory(ctx, + fs->blocksize, "bad_inode buffer"); + if (e2fsck_process_bad_inode(ctx, 0, i, buf)) + continue; + if (disconnect_inode(ctx, i, &last_ino, inode)) + continue; + ext2fs_icount_fetch(ctx->inode_link_info, i, + &link_count); + ext2fs_icount_fetch(ctx->inode_count, i, + &link_counted); + } + isdir = ext2fs_test_inode_bitmap2(ctx->inode_dir_map, i); + if (isdir && (link_counted > EXT2_LINK_MAX)) { + if (!dir_nlink_fs && + fix_problem(ctx, PR_4_DIR_NLINK_FEATURE, &pctx)) { + ext2fs_set_feature_dir_nlink(fs->super); + ext2fs_mark_super_dirty(fs); + dir_nlink_fs = 1; + } + link_counted = 1; + } + if (link_counted != link_count) { + int fix_nlink = 0; + + if (last_ino != i) { + e2fsck_read_inode_full(ctx, i, + EXT2_INODE(inode), + inode_size, "pass4"); + last_ino = i; + } + pctx.ino = i; + pctx.inode = EXT2_INODE(inode); + if ((link_count != inode->i_links_count) && !isdir && + (inode->i_links_count <= EXT2_LINK_MAX)) { + pctx.num = link_count; + fix_problem(ctx, + PR_4_INCONSISTENT_COUNT, &pctx); + } + pctx.num = link_counted; + /* i_link_count was previously exceeded, but no longer + * is, fix this but don't consider it an error */ + if (isdir && link_counted > 1 && + (inode->i_flags & EXT2_INDEX_FL) && + link_count == 1) { + if ((ctx->options & E2F_OPT_READONLY) == 0) { + fix_nlink = + fix_problem(ctx, + PR_4_DIR_OVERFLOW_REF_COUNT, + &pctx); + } + } else { + fix_nlink = fix_problem(ctx, PR_4_BAD_REF_COUNT, + &pctx); + } + if (fix_nlink) { + inode->i_links_count = link_counted; + e2fsck_write_inode_full(ctx, i, + EXT2_INODE(inode), + inode_size, "pass4"); + } + } + } + ext2fs_free_icount(ctx->inode_link_info); ctx->inode_link_info = 0; + ext2fs_free_icount(ctx->inode_count); ctx->inode_count = 0; + ext2fs_free_inode_bitmap(ctx->inode_bb_map); + ctx->inode_bb_map = 0; + ea_refcount_free(ctx->ea_inode_refs); + ctx->ea_inode_refs = 0; + ext2fs_free_inode_bitmap(ctx->inode_imagic_map); + ctx->inode_imagic_map = 0; +errout: + if (buf) + ext2fs_free_mem(&buf); + + ext2fs_free_mem(&inode); + print_resource_track(ctx, _("Pass 4"), &rtrack, ctx->fs->io); +} + diff --git a/e2fsck/pass5.c b/e2fsck/pass5.c new file mode 100644 index 0000000..c1d45a5 --- /dev/null +++ b/e2fsck/pass5.c @@ -0,0 +1,958 @@ +/* + * pass5.c --- check block and inode bitmaps against on-disk bitmaps + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + */ + +#include "config.h" +#include <stdint.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <fcntl.h> +#include <errno.h> + +#include "e2fsck.h" +#include "problem.h" + +static void check_block_bitmaps(e2fsck_t ctx); +static void check_inode_bitmaps(e2fsck_t ctx); +static void check_inode_end(e2fsck_t ctx); +static void check_block_end(e2fsck_t ctx); +static void check_inode_bitmap_checksum(e2fsck_t ctx); +static void check_block_bitmap_checksum(e2fsck_t ctx); + +void e2fsck_pass5(e2fsck_t ctx) +{ +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct problem_context pctx; + +#ifdef MTRACE + mtrace_print("Pass 5"); +#endif + + init_resource_track(&rtrack, ctx->fs->io); + clear_problem_context(&pctx); + + if (!(ctx->options & E2F_OPT_PREEN)) + fix_problem(ctx, PR_5_PASS_HEADER, &pctx); + + if (ctx->progress) + if ((ctx->progress)(ctx, 5, 0, ctx->fs->group_desc_count*2)) + return; + + e2fsck_read_bitmaps(ctx); + + check_block_bitmaps(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return; + check_inode_bitmaps(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return; + check_inode_end(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return; + check_block_end(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return; + + check_inode_bitmap_checksum(ctx); + check_block_bitmap_checksum(ctx); + + ext2fs_free_inode_bitmap(ctx->inode_used_map); + ctx->inode_used_map = 0; + ext2fs_free_inode_bitmap(ctx->inode_dir_map); + ctx->inode_dir_map = 0; + ext2fs_free_block_bitmap(ctx->block_found_map); + ctx->block_found_map = 0; + ext2fs_free_block_bitmap(ctx->block_metadata_map); + ctx->block_metadata_map = 0; + + print_resource_track(ctx, _("Pass 5"), &rtrack, ctx->fs->io); +} + +static void check_inode_bitmap_checksum(e2fsck_t ctx) +{ + struct problem_context pctx; + char *buf = NULL; + dgrp_t i; + int nbytes; + ext2_ino_t ino_itr; + errcode_t retval; + + if (!ext2fs_has_feature_metadata_csum(ctx->fs->super)) + return; + + /* If bitmap is dirty from being fixed, checksum will be corrected */ + if (ext2fs_test_ib_dirty(ctx->fs)) + return; + + nbytes = (size_t)(EXT2_INODES_PER_GROUP(ctx->fs->super) / 8); + retval = ext2fs_get_mem(ctx->fs->blocksize, &buf); + if (retval) { + com_err(ctx->program_name, 0, "%s", + _("check_inode_bitmap_checksum: Memory allocation error")); + fatal_error(ctx, 0); + } + + clear_problem_context(&pctx); + for (i = 0; i < ctx->fs->group_desc_count; i++) { + if (ext2fs_bg_flags_test(ctx->fs, i, EXT2_BG_INODE_UNINIT)) + continue; + + ino_itr = 1 + (i * (nbytes << 3)); + retval = ext2fs_get_inode_bitmap_range2(ctx->fs->inode_map, + ino_itr, nbytes << 3, + buf); + if (retval) + break; + + if (ext2fs_inode_bitmap_csum_verify(ctx->fs, i, buf, nbytes)) + continue; + pctx.group = i; + if (!fix_problem(ctx, PR_5_INODE_BITMAP_CSUM_INVALID, &pctx)) + continue; + + /* + * Fixing one checksum will rewrite all of them. The bitmap + * will be checked against the one we made during pass1 for + * discrepancies, and fixed if need be. + */ + ext2fs_mark_ib_dirty(ctx->fs); + break; + } + + ext2fs_free_mem(&buf); +} + +static void check_block_bitmap_checksum(e2fsck_t ctx) +{ + struct problem_context pctx; + char *buf = NULL; + dgrp_t i; + int nbytes; + blk64_t blk_itr; + errcode_t retval; + + if (!ext2fs_has_feature_metadata_csum(ctx->fs->super)) + return; + + /* If bitmap is dirty from being fixed, checksum will be corrected */ + if (ext2fs_test_bb_dirty(ctx->fs)) + return; + + nbytes = (size_t)(EXT2_CLUSTERS_PER_GROUP(ctx->fs->super) / 8); + retval = ext2fs_get_mem(ctx->fs->blocksize, &buf); + if (retval) { + com_err(ctx->program_name, 0, "%s", + _("check_block_bitmap_checksum: Memory allocation error")); + fatal_error(ctx, 0); + } + + clear_problem_context(&pctx); + for (i = 0; i < ctx->fs->group_desc_count; i++) { + if (ext2fs_bg_flags_test(ctx->fs, i, EXT2_BG_BLOCK_UNINIT)) + continue; + + blk_itr = EXT2FS_B2C(ctx->fs, + ctx->fs->super->s_first_data_block) + + ((blk64_t) i * (nbytes << 3)); + retval = ext2fs_get_block_bitmap_range2(ctx->fs->block_map, + blk_itr, nbytes << 3, + buf); + if (retval) + break; + + if (ext2fs_block_bitmap_csum_verify(ctx->fs, i, buf, nbytes)) + continue; + pctx.group = i; + if (!fix_problem(ctx, PR_5_BLOCK_BITMAP_CSUM_INVALID, &pctx)) + continue; + + /* + * Fixing one checksum will rewrite all of them. The bitmap + * will be checked against the one we made during pass1 for + * discrepancies, and fixed if need be. + */ + ext2fs_mark_bb_dirty(ctx->fs); + break; + } + + ext2fs_free_mem(&buf); +} + +static void e2fsck_discard_blocks(e2fsck_t ctx, blk64_t start, + blk64_t count) +{ + ext2_filsys fs = ctx->fs; + + /* + * If the filesystem has changed it means that there was an corruption + * which should be repaired, but in some cases just one e2fsck run is + * not enough to fix the problem, hence it is not safe to run discard + * in this case. + */ + if (ext2fs_test_changed(fs)) + ctx->options &= ~E2F_OPT_DISCARD; + + if ((ctx->options & E2F_OPT_DISCARD) && + (io_channel_discard(fs->io, start, count))) + ctx->options &= ~E2F_OPT_DISCARD; +} + +/* + * This will try to discard number 'count' inodes starting at + * inode number 'start' within the 'group'. Note that 'start' + * is 1-based, it means that we need to adjust it by -1 in this + * function to compute right offset in the particular inode table. + */ +static void e2fsck_discard_inodes(e2fsck_t ctx, dgrp_t group, + ext2_ino_t start, int count) +{ + ext2_filsys fs = ctx->fs; + blk64_t blk, num; + + /* + * Sanity check for 'start' + */ + if ((start < 1) || (start > EXT2_INODES_PER_GROUP(fs->super))) { + printf("PROGRAMMING ERROR: Got start %d outside of group %d!" + " Disabling discard\n", + start, group); + ctx->options &= ~E2F_OPT_DISCARD; + } + + /* + * Do not attempt to discard if E2F_OPT_DISCARD is not set. And also + * skip the discard on this group if discard does not zero data. + * The reason is that if the inode table is not zeroed discard would + * no help us since we need to zero it anyway, or if the inode table + * is zeroed then the read after discard would not be deterministic + * anyway and we would not be able to assume that this inode table + * was zeroed anymore so we would have to zero it again, which does + * not really make sense. + */ + if (!(ctx->options & E2F_OPT_DISCARD) || + !io_channel_discard_zeroes_data(fs->io)) + return; + + /* + * Start is inode number within the group which starts + * counting from 1, so we need to adjust it. + */ + start -= 1; + + /* + * We can discard only blocks containing only unused + * inodes in the table. + */ + blk = DIV_ROUND_UP(start, + EXT2_INODES_PER_BLOCK(fs->super)); + count -= (blk * EXT2_INODES_PER_BLOCK(fs->super) - start); + blk += ext2fs_inode_table_loc(fs, group); + num = count / EXT2_INODES_PER_BLOCK(fs->super); + + if (num > 0) + e2fsck_discard_blocks(ctx, blk, num); +} + +#define NO_BLK ((blk64_t) -1) + +static void print_bitmap_problem(e2fsck_t ctx, problem_t problem, + struct problem_context *pctx) +{ + switch (problem) { + case PR_5_BLOCK_UNUSED: + if (pctx->blk == pctx->blk2) + pctx->blk2 = 0; + else + problem = PR_5_BLOCK_RANGE_UNUSED; + break; + case PR_5_BLOCK_USED: + if (pctx->blk == pctx->blk2) + pctx->blk2 = 0; + else + problem = PR_5_BLOCK_RANGE_USED; + break; + case PR_5_INODE_UNUSED: + if (pctx->ino == pctx->ino2) + pctx->ino2 = 0; + else + problem = PR_5_INODE_RANGE_UNUSED; + break; + case PR_5_INODE_USED: + if (pctx->ino == pctx->ino2) + pctx->ino2 = 0; + else + problem = PR_5_INODE_RANGE_USED; + break; + } + fix_problem(ctx, problem, pctx); + pctx->blk = pctx->blk2 = NO_BLK; + pctx->ino = pctx->ino2 = 0; +} + +/* Just to be more succinct */ +#define B2C(x) EXT2FS_B2C(fs, (x)) +#define EQ_CLSTR(x, y) (B2C(x) == B2C(y)) +#define LE_CLSTR(x, y) (B2C(x) <= B2C(y)) +#define GE_CLSTR(x, y) (B2C(x) >= B2C(y)) + +static void check_block_bitmaps(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t i; + unsigned int *free_array; + dgrp_t g, group = 0; + unsigned int blocks = 0; + blk64_t free_blocks = 0; + blk64_t first_free = ext2fs_blocks_count(fs->super); + unsigned int group_free = 0; + int actual, bitmap; + struct problem_context pctx; + problem_t problem, save_problem; + int fixit, had_problem; + errcode_t retval; + int redo_flag = 0; + char *actual_buf, *bitmap_buf; + + actual_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize, + "actual bitmap buffer"); + bitmap_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize, + "bitmap block buffer"); + + clear_problem_context(&pctx); + free_array = (unsigned int *) e2fsck_allocate_memory(ctx, + fs->group_desc_count * sizeof(unsigned int), "free block count array"); + + if ((B2C(fs->super->s_first_data_block) < + ext2fs_get_block_bitmap_start2(ctx->block_found_map)) || + (B2C(ext2fs_blocks_count(fs->super)-1) > + ext2fs_get_block_bitmap_end2(ctx->block_found_map))) { + pctx.num = 1; + pctx.blk = B2C(fs->super->s_first_data_block); + pctx.blk2 = B2C(ext2fs_blocks_count(fs->super) - 1); + pctx.ino = ext2fs_get_block_bitmap_start2(ctx->block_found_map); + pctx.ino2 = ext2fs_get_block_bitmap_end2(ctx->block_found_map); + fix_problem(ctx, PR_5_BMAP_ENDPOINTS, &pctx); + + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + goto errout; + } + + if ((B2C(fs->super->s_first_data_block) < + ext2fs_get_block_bitmap_start2(fs->block_map)) || + (B2C(ext2fs_blocks_count(fs->super)-1) > + ext2fs_get_block_bitmap_end2(fs->block_map))) { + pctx.num = 2; + pctx.blk = B2C(fs->super->s_first_data_block); + pctx.blk2 = B2C(ext2fs_blocks_count(fs->super) - 1); + pctx.ino = ext2fs_get_block_bitmap_start2(fs->block_map); + pctx.ino2 = ext2fs_get_block_bitmap_end2(fs->block_map); + fix_problem(ctx, PR_5_BMAP_ENDPOINTS, &pctx); + + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + goto errout; + } + +redo_counts: + had_problem = 0; + save_problem = 0; + pctx.blk = pctx.blk2 = NO_BLK; + for (i = B2C(fs->super->s_first_data_block); + i < ext2fs_blocks_count(fs->super); + i += EXT2FS_CLUSTER_RATIO(fs)) { + int first_block_in_bg = (B2C(i) - + B2C(fs->super->s_first_data_block)) % + fs->super->s_clusters_per_group == 0; + int n, nbytes = fs->super->s_clusters_per_group / 8; + + actual = ext2fs_fast_test_block_bitmap2(ctx->block_found_map, i); + + /* + * Try to optimize pass5 by extracting a bitmap block + * as expected from what we have on disk, and then + * comparing the two. If they are identical, then + * update the free block counts and go on to the next + * block group. This is much faster than doing the + * individual bit-by-bit comparison. The one downside + * is that this doesn't work if we are asking e2fsck + * to do a discard operation. + */ + if (!first_block_in_bg || + (group == fs->group_desc_count - 1) || + (ctx->options & E2F_OPT_DISCARD)) + goto no_optimize; + + retval = ext2fs_get_block_bitmap_range2(ctx->block_found_map, + B2C(i), fs->super->s_clusters_per_group, + actual_buf); + if (retval) + goto no_optimize; + retval = ext2fs_get_block_bitmap_range2(fs->block_map, + B2C(i), fs->super->s_clusters_per_group, + bitmap_buf); + if (retval) + goto no_optimize; + if (memcmp(actual_buf, bitmap_buf, nbytes) != 0) + goto no_optimize; + n = ext2fs_bitcount(actual_buf, nbytes); + group_free = fs->super->s_clusters_per_group - n; + free_blocks += group_free; + i += EXT2FS_C2B(fs, fs->super->s_clusters_per_group - 1); + goto next_group; + no_optimize: + + if (redo_flag) + bitmap = actual; + else + bitmap = ext2fs_fast_test_block_bitmap2(fs->block_map, i); + + if (!actual == !bitmap) + goto do_counts; + + if (!actual && bitmap) { + /* + * Block not used, but marked in use in the bitmap. + */ + problem = PR_5_BLOCK_UNUSED; + } else { + /* + * Block used, but not marked in use in the bitmap. + */ + problem = PR_5_BLOCK_USED; + + if (ext2fs_bg_flags_test(fs, group, + EXT2_BG_BLOCK_UNINIT)) { + struct problem_context pctx2; + pctx2.blk = i; + pctx2.group = group; + if (fix_problem(ctx, PR_5_BLOCK_UNINIT, + &pctx2)) + ext2fs_bg_flags_clear(fs, group, + EXT2_BG_BLOCK_UNINIT); + } + } + if (pctx.blk == NO_BLK) { + pctx.blk = pctx.blk2 = i; + save_problem = problem; + } else { + if ((problem == save_problem) && + (pctx.blk2 == i - EXT2FS_CLUSTER_RATIO(fs))) + pctx.blk2 += EXT2FS_CLUSTER_RATIO(fs); + else { + print_bitmap_problem(ctx, save_problem, &pctx); + pctx.blk = pctx.blk2 = i; + save_problem = problem; + } + } + ctx->flags |= E2F_FLAG_PROG_SUPPRESS; + had_problem++; + + /* + * If there a problem we should turn off the discard so we + * do not compromise the filesystem. + */ + ctx->options &= ~E2F_OPT_DISCARD; + + do_counts: + if (!bitmap) { + group_free++; + free_blocks++; + if (first_free > i) + first_free = i; + } else if (i > first_free) { + e2fsck_discard_blocks(ctx, first_free, + (i - first_free)); + first_free = ext2fs_blocks_count(fs->super); + } + blocks ++; + if ((blocks == fs->super->s_clusters_per_group) || + (EXT2FS_B2C(fs, i) == + EXT2FS_B2C(fs, ext2fs_blocks_count(fs->super)-1))) { + /* + * If the last block of this group is free, then we can + * discard it as well. + */ + if (!bitmap && i >= first_free) + e2fsck_discard_blocks(ctx, first_free, + (i - first_free) + 1); + next_group: + first_free = ext2fs_blocks_count(fs->super); + + free_array[group] = group_free; + group ++; + blocks = 0; + group_free = 0; + if (ctx->progress) + if ((ctx->progress)(ctx, 5, group, + fs->group_desc_count*2)) + goto errout; + } + } + if (pctx.blk != NO_BLK) + print_bitmap_problem(ctx, save_problem, &pctx); + if (had_problem) + fixit = end_problem_latch(ctx, PR_LATCH_BBITMAP); + else + fixit = -1; + ctx->flags &= ~E2F_FLAG_PROG_SUPPRESS; + + if (fixit == 1) { + ext2fs_free_block_bitmap(fs->block_map); + retval = ext2fs_copy_bitmap(ctx->block_found_map, + &fs->block_map); + if (retval) { + clear_problem_context(&pctx); + fix_problem(ctx, PR_5_COPY_BBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto errout; + } + ext2fs_set_bitmap_padding(fs->block_map); + ext2fs_mark_bb_dirty(fs); + + /* Redo the counts */ + blocks = 0; free_blocks = 0; group_free = 0; group = 0; + memset(free_array, 0, fs->group_desc_count * sizeof(int)); + redo_flag++; + goto redo_counts; + } else if (fixit == 0) + ext2fs_unmark_valid(fs); + + for (g = 0; g < fs->group_desc_count; g++) { + if (free_array[g] != ext2fs_bg_free_blocks_count(fs, g)) { + pctx.group = g; + pctx.blk = ext2fs_bg_free_blocks_count(fs, g); + pctx.blk2 = free_array[g]; + + if (fix_problem(ctx, PR_5_FREE_BLOCK_COUNT_GROUP, + &pctx)) { + ext2fs_bg_free_blocks_count_set(fs, g, free_array[g]); + ext2fs_mark_super_dirty(fs); + } else + ext2fs_unmark_valid(fs); + } + } + free_blocks = EXT2FS_C2B(fs, free_blocks); + if (free_blocks != ext2fs_free_blocks_count(fs->super)) { + pctx.group = 0; + pctx.blk = ext2fs_free_blocks_count(fs->super); + pctx.blk2 = free_blocks; + + if (fix_problem(ctx, PR_5_FREE_BLOCK_COUNT, &pctx)) { + ext2fs_free_blocks_count_set(fs->super, free_blocks); + ext2fs_mark_super_dirty(fs); + } + } +errout: + ext2fs_free_mem(&free_array); + ext2fs_free_mem(&actual_buf); + ext2fs_free_mem(&bitmap_buf); +} + +static void check_inode_bitmaps(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t i; + unsigned int free_inodes = 0; + int group_free = 0; + int dirs_count = 0; + dgrp_t group = 0; + unsigned int inodes = 0; + ext2_ino_t *free_array; + ext2_ino_t *dir_array; + int actual, bitmap; + errcode_t retval; + struct problem_context pctx; + problem_t problem, save_problem; + int fixit, had_problem; + int csum_flag; + int skip_group = 0; + int redo_flag = 0; + ext2_ino_t first_free = fs->super->s_inodes_per_group + 1; + + clear_problem_context(&pctx); + free_array = (ext2_ino_t *) e2fsck_allocate_memory(ctx, + fs->group_desc_count * sizeof(ext2_ino_t), "free inode count array"); + + dir_array = (ext2_ino_t *) e2fsck_allocate_memory(ctx, + fs->group_desc_count * sizeof(ext2_ino_t), "directory count array"); + + if ((1 < ext2fs_get_inode_bitmap_start2(ctx->inode_used_map)) || + (fs->super->s_inodes_count > + ext2fs_get_inode_bitmap_end2(ctx->inode_used_map))) { + pctx.num = 3; + pctx.blk = 1; + pctx.blk2 = fs->super->s_inodes_count; + pctx.ino = ext2fs_get_inode_bitmap_start2(ctx->inode_used_map); + pctx.ino2 = ext2fs_get_inode_bitmap_end2(ctx->inode_used_map); + fix_problem(ctx, PR_5_BMAP_ENDPOINTS, &pctx); + + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + goto errout; + } + if ((1 < ext2fs_get_inode_bitmap_start2(fs->inode_map)) || + (fs->super->s_inodes_count > + ext2fs_get_inode_bitmap_end2(fs->inode_map))) { + pctx.num = 4; + pctx.blk = 1; + pctx.blk2 = fs->super->s_inodes_count; + pctx.ino = ext2fs_get_inode_bitmap_start2(fs->inode_map); + pctx.ino2 = ext2fs_get_inode_bitmap_end2(fs->inode_map); + fix_problem(ctx, PR_5_BMAP_ENDPOINTS, &pctx); + + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + goto errout; + } + + csum_flag = ext2fs_has_group_desc_csum(fs); +redo_counts: + had_problem = 0; + save_problem = 0; + pctx.ino = pctx.ino2 = 0; + if (csum_flag && + (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT))) + skip_group++; + + /* Protect loop from wrap-around if inodes_count is maxed */ + for (i = 1; i <= fs->super->s_inodes_count && i > 0; i++) { + bitmap = 0; + if (skip_group && + i % fs->super->s_inodes_per_group == 1) { + /* + * Current inode is the first inode + * in the current block group. + */ + if (ext2fs_test_inode_bitmap_range( + ctx->inode_used_map, i, + fs->super->s_inodes_per_group)) { + /* + * When the compared inodes in inodes bitmap + * are 0, count the free inode, + * skip the current block group. + */ + first_free = 1; + inodes = fs->super->s_inodes_per_group - 1; + group_free = inodes; + free_inodes += inodes; + i += inodes; + skip_group = 0; + goto do_counts; + } + } + + actual = ext2fs_fast_test_inode_bitmap2(ctx->inode_used_map, i); + if (redo_flag) + bitmap = actual; + else if (!skip_group) + bitmap = ext2fs_fast_test_inode_bitmap2(fs->inode_map, i); + if (!actual == !bitmap) + goto do_counts; + + if (!actual && bitmap) { + /* + * Inode wasn't used, but marked in bitmap + */ + problem = PR_5_INODE_UNUSED; + } else /* if (actual && !bitmap) */ { + /* + * Inode used, but not in bitmap + */ + problem = PR_5_INODE_USED; + + /* We should never hit this, because it means that + * inodes were marked in use that weren't noticed + * in pass1 or pass 2. It is easier to fix the problem + * than to kill e2fsck and leave the user stuck. */ + if (skip_group) { + struct problem_context pctx2; + pctx2.blk = i; + pctx2.group = group; + if (fix_problem(ctx, PR_5_INODE_UNINIT,&pctx2)){ + ext2fs_bg_flags_clear(fs, group, EXT2_BG_INODE_UNINIT); + skip_group = 0; + } + } + } + if (pctx.ino == 0) { + pctx.ino = pctx.ino2 = i; + save_problem = problem; + } else { + if ((problem == save_problem) && + (pctx.ino2 == i-1)) + pctx.ino2++; + else { + print_bitmap_problem(ctx, save_problem, &pctx); + pctx.ino = pctx.ino2 = i; + save_problem = problem; + } + } + ctx->flags |= E2F_FLAG_PROG_SUPPRESS; + had_problem++; + /* + * If there a problem we should turn off the discard so we + * do not compromise the filesystem. + */ + ctx->options &= ~E2F_OPT_DISCARD; + +do_counts: + inodes++; + if (bitmap) { + if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, i)) + dirs_count++; + if (inodes > first_free) { + e2fsck_discard_inodes(ctx, group, first_free, + inodes - first_free); + first_free = fs->super->s_inodes_per_group + 1; + } + } else { + group_free++; + free_inodes++; + if (first_free > inodes) + first_free = inodes; + } + + if ((inodes == fs->super->s_inodes_per_group) || + (i == fs->super->s_inodes_count)) { + /* + * If the last inode is free, we can discard it as well. + */ + if (!bitmap && inodes >= first_free) + e2fsck_discard_inodes(ctx, group, first_free, + inodes - first_free + 1); + /* + * If discard zeroes data and the group inode table + * was not zeroed yet, set itable as zeroed + */ + if ((ctx->options & E2F_OPT_DISCARD) && + io_channel_discard_zeroes_data(fs->io) && + !(ext2fs_bg_flags_test(fs, group, + EXT2_BG_INODE_ZEROED))) { + ext2fs_bg_flags_set(fs, group, + EXT2_BG_INODE_ZEROED); + ext2fs_group_desc_csum_set(fs, group); + } + + first_free = fs->super->s_inodes_per_group + 1; + free_array[group] = group_free; + dir_array[group] = dirs_count; + group ++; + inodes = 0; + skip_group = 0; + group_free = 0; + dirs_count = 0; + if (ctx->progress) + if ((ctx->progress)(ctx, 5, + group + fs->group_desc_count, + fs->group_desc_count*2)) + goto errout; + if (csum_flag && + (i != fs->super->s_inodes_count) && + (ext2fs_bg_flags_test(fs, group, EXT2_BG_INODE_UNINIT) + )) + skip_group++; + } + } + if (pctx.ino) + print_bitmap_problem(ctx, save_problem, &pctx); + + if (had_problem) + fixit = end_problem_latch(ctx, PR_LATCH_IBITMAP); + else + fixit = -1; + ctx->flags &= ~E2F_FLAG_PROG_SUPPRESS; + + if (fixit == 1) { + ext2fs_free_inode_bitmap(fs->inode_map); + retval = ext2fs_copy_bitmap(ctx->inode_used_map, + &fs->inode_map); + if (retval) { + clear_problem_context(&pctx); + fix_problem(ctx, PR_5_COPY_IBITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + goto errout; + } + ext2fs_set_bitmap_padding(fs->inode_map); + ext2fs_mark_ib_dirty(fs); + + /* redo counts */ + inodes = 0; free_inodes = 0; group_free = 0; + dirs_count = 0; group = 0; + memset(free_array, 0, fs->group_desc_count * sizeof(int)); + memset(dir_array, 0, fs->group_desc_count * sizeof(int)); + redo_flag++; + goto redo_counts; + } else if (fixit == 0) + ext2fs_unmark_valid(fs); + + for (i = 0; i < fs->group_desc_count; i++) { + if (free_array[i] != ext2fs_bg_free_inodes_count(fs, i)) { + pctx.group = i; + pctx.ino = ext2fs_bg_free_inodes_count(fs, i); + pctx.ino2 = free_array[i]; + if (fix_problem(ctx, PR_5_FREE_INODE_COUNT_GROUP, + &pctx)) { + ext2fs_bg_free_inodes_count_set(fs, i, free_array[i]); + ext2fs_mark_super_dirty(fs); + } else + ext2fs_unmark_valid(fs); + } + if (dir_array[i] != ext2fs_bg_used_dirs_count(fs, i)) { + pctx.group = i; + pctx.ino = ext2fs_bg_used_dirs_count(fs, i); + pctx.ino2 = dir_array[i]; + + if (fix_problem(ctx, PR_5_FREE_DIR_COUNT_GROUP, + &pctx)) { + ext2fs_bg_used_dirs_count_set(fs, i, dir_array[i]); + ext2fs_mark_super_dirty(fs); + } else + ext2fs_unmark_valid(fs); + } + } + if (free_inodes != fs->super->s_free_inodes_count) { + pctx.group = -1; + pctx.ino = fs->super->s_free_inodes_count; + pctx.ino2 = free_inodes; + + if (fix_problem(ctx, PR_5_FREE_INODE_COUNT, &pctx)) { + fs->super->s_free_inodes_count = free_inodes; + ext2fs_mark_super_dirty(fs); + } + } +errout: + ext2fs_free_mem(&free_array); + ext2fs_free_mem(&dir_array); +} + +static void check_inode_end(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t end, save_inodes_count, i; + struct problem_context pctx; + int asked = 0; + + clear_problem_context(&pctx); + + end = (__u64)EXT2_INODES_PER_GROUP(fs->super) * fs->group_desc_count; + pctx.errcode = ext2fs_fudge_inode_bitmap_end(fs->inode_map, end, + &save_inodes_count); + if (pctx.errcode) { + pctx.num = 1; + fix_problem(ctx, PR_5_FUDGE_BITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + return; + } + if (save_inodes_count == end) + goto check_intra_bg_tail; + + /* protect loop from wrap-around if end is maxed */ + for (i = save_inodes_count + 1; i <= end && i > save_inodes_count; i++) { + if (!ext2fs_test_inode_bitmap(fs->inode_map, i)) { + asked = 1; + if (fix_problem(ctx, PR_5_INODE_BMAP_PADDING, &pctx)) { + for (; i <= end; i++) + ext2fs_mark_inode_bitmap(fs->inode_map, + i); + ext2fs_mark_ib_dirty(fs); + } else + ext2fs_unmark_valid(fs); + break; + } + } + + pctx.errcode = ext2fs_fudge_inode_bitmap_end(fs->inode_map, + save_inodes_count, 0); + if (pctx.errcode) { + pctx.num = 2; + fix_problem(ctx, PR_5_FUDGE_BITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + return; + } + /* + * If the number of inodes per block group != blocksize, we + * can also have a potential problem with the tail bits in + * each individual inode bitmap block. If there is a problem, + * it would have been noticed when the bitmap was loaded. And + * fixing this is easy; all we need to do force the bitmap to + * be written back to disk. + */ +check_intra_bg_tail: + if (!asked && fs->flags & EXT2_FLAG_IBITMAP_TAIL_PROBLEM) { + if (fix_problem(ctx, PR_5_INODE_BMAP_PADDING, &pctx)) + ext2fs_mark_ib_dirty(fs); + else + ext2fs_unmark_valid(fs); + } +} + +static void check_block_end(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t end, save_blocks_count, i; + struct problem_context pctx; + int asked = 0; + + clear_problem_context(&pctx); + + end = ext2fs_get_block_bitmap_start2(fs->block_map) + + EXT2_GROUPS_TO_CLUSTERS(fs->super, fs->group_desc_count) - 1; + pctx.errcode = ext2fs_fudge_block_bitmap_end2(fs->block_map, end, + &save_blocks_count); + if (pctx.errcode) { + pctx.num = 3; + fix_problem(ctx, PR_5_FUDGE_BITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + return; + } + if (save_blocks_count == end) + goto check_intra_bg_tail; + + /* Protect loop from wrap-around if end is maxed */ + for (i = save_blocks_count + 1; i <= end && i > save_blocks_count; i++) { + if (!ext2fs_test_block_bitmap2(fs->block_map, + EXT2FS_C2B(fs, i))) { + asked = 1; + if (fix_problem(ctx, PR_5_BLOCK_BMAP_PADDING, &pctx)) { + for (; i <= end; i++) + ext2fs_mark_block_bitmap2(fs->block_map, + EXT2FS_C2B(fs, i)); + ext2fs_mark_bb_dirty(fs); + } else + ext2fs_unmark_valid(fs); + break; + } + } + + pctx.errcode = ext2fs_fudge_block_bitmap_end2(fs->block_map, + save_blocks_count, 0); + if (pctx.errcode) { + pctx.num = 4; + fix_problem(ctx, PR_5_FUDGE_BITMAP_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; /* fatal */ + return; + } + /* + * If the number of blocks per block group != blocksize, we + * can also have a potential problem with the tail bits in + * each individual block bitmap block. If there is a problem, + * it would have been noticed when the bitmap was loaded. And + * fixing this is easy; all we need to do force the bitmap to + * be written back to disk. + */ +check_intra_bg_tail: + if (!asked && fs->flags & EXT2_FLAG_BBITMAP_TAIL_PROBLEM) { + if (fix_problem(ctx, PR_5_BLOCK_BMAP_PADDING, &pctx)) + ext2fs_mark_bb_dirty(fs); + else + ext2fs_unmark_valid(fs); + } +} diff --git a/e2fsck/problem.c b/e2fsck/problem.c new file mode 100644 index 0000000..6ad6fb8 --- /dev/null +++ b/e2fsck/problem.c @@ -0,0 +1,2756 @@ +/* + * problem.c --- report filesystem problems to the user + * + * Copyright 1996, 1997 by Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <ctype.h> +#include <termios.h> + +#include "e2fsck.h" + +#include "problem.h" +#include "problemP.h" + +#define PROMPT_NONE 0 +#define PROMPT_FIX 1 +#define PROMPT_CLEAR 2 +#define PROMPT_RELOCATE 3 +#define PROMPT_ALLOCATE 4 +#define PROMPT_EXPAND 5 +#define PROMPT_CONNECT 6 +#define PROMPT_CREATE 7 +#define PROMPT_SALVAGE 8 +#define PROMPT_TRUNCATE 9 +#define PROMPT_CLEAR_INODE 10 +#define PROMPT_ABORT 11 +#define PROMPT_SPLIT 12 +#define PROMPT_CONTINUE 13 +#define PROMPT_CLONE 14 +#define PROMPT_DELETE 15 +#define PROMPT_SUPPRESS 16 +#define PROMPT_UNLINK 17 +#define PROMPT_CLEAR_HTREE 18 +#define PROMPT_RECREATE 19 +#define PROMPT_OPTIMIZE 20 +#define PROMPT_CLEAR_FLAG 21 +#define PROMPT_NULL 22 + +/* + * These are the prompts which are used to ask the user if they want + * to fix a problem. + */ +static const char *prompt[] = { + N_("(no prompt)"), /* PROMPT_NONE = 0 */ + N_("Fix"), /* PROMPT_FIX = 1 */ + N_("Clear"), /* PROMPT_CLEAR = 2 */ + N_("Relocate"), /* PROMPT_RELOCATE = 3 */ + N_("Allocate"), /* PROMPT_CREATE = 4 */ + N_("Expand"), /* PROMPT_EXPAND = 5 */ + N_("Connect to /lost+found"), /* PROMPT_CONNECT = 6 */ + N_("Create"), /* PROMPT_CREATE = 7 */ + N_("Salvage"), /* PROMPT_SALVAGE = 8 */ + N_("Truncate"), /* PROMPT_TRUNCATE = 9 */ + N_("Clear inode"), /* PROMPT_CLEAR_INODE = 10 */ + N_("Abort"), /* PROMPT_ABORT = 11 */ + N_("Split"), /* PROMPT_SPLIT = 12 */ + N_("Continue"), /* PROMPT_CONTINUE = 13 */ + N_("Clone multiply-claimed blocks"), /* PROMPT_CLONE = 14 */ + N_("Delete file"), /* PROMPT_DELETE = 15 */ + N_("Suppress messages"), /* PROMPT_SUPPRESS = 16 */ + N_("Unlink"), /* PROMPT_UNLINK = 17 */ + N_("Clear HTree index"), /* PROMPT_CLEAR_HTREE = 18 */ + N_("Recreate"), /* PROMPT_RECREATE = 19 */ + N_("Optimize"), /* PROMPT_OPTIMIZE = 20 */ + N_("Clear flag"), /* PROMPT_CLEAR_FLAG = 21 */ + "", /* PROMPT_NULL = 22 */ +}; + +/* + * These messages are printed when we are preen mode and we will be + * automatically fixing the problem. + */ +static const char *preen_msg[] = { + N_("(NONE)"), /* 0 */ + N_("FIXED"), /* 1 */ + N_("CLEARED"), /* 2 */ + N_("RELOCATED"), /* 3 */ + N_("ALLOCATED"), /* 4 */ + N_("EXPANDED"), /* 5 */ + N_("RECONNECTED"), /* 6 */ + N_("CREATED"), /* 7 */ + N_("SALVAGED"), /* 8 */ + N_("TRUNCATED"), /* 9 */ + N_("INODE CLEARED"), /* 10 */ + N_("ABORTED"), /* 11 */ + N_("SPLIT"), /* 12 */ + N_("CONTINUING"), /* 13 */ + N_("MULTIPLY-CLAIMED BLOCKS CLONED"), /* 14 */ + N_("FILE DELETED"), /* 15 */ + N_("SUPPRESSED"), /* 16 */ + N_("UNLINKED"), /* 17 */ + N_("HTREE INDEX CLEARED"),/* 18 */ + N_("WILL RECREATE"), /* 19 */ + N_("WILL OPTIMIZE"), /* 20 */ + N_("FLAG CLEARED"), /* 21 */ + "", /* 22 */ +}; + +#if __GNUC_PREREQ (4, 6) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +static struct e2fsck_problem problem_table[] = { + + /* Pre-Pass 1 errors */ + + /* Block bitmap for group is not in group */ + { PR_0_BB_NOT_GROUP, N_("@b @B for @g %g is not in @g. (@b %b)\n"), + PROMPT_RELOCATE, PR_LATCH_RELOC, 0, 0, 0 }, + + /* Inode bitmap for group is not in group */ + { PR_0_IB_NOT_GROUP, N_("@i @B for @g %g is not in @g. (@b %b)\n"), + PROMPT_RELOCATE, PR_LATCH_RELOC, 0, 0, 0 }, + + /* Inode table for group is not in group. (block nnnn) */ + { PR_0_ITABLE_NOT_GROUP, + N_("@i table for @g %g is not in @g. (@b %b)\n" + "WARNING: SEVERE DATA LOSS POSSIBLE.\n"), + PROMPT_RELOCATE, PR_LATCH_RELOC, 0, 0, 0 }, + + /* Superblock corrupt */ + { PR_0_SB_CORRUPT, + N_("\nThe @S could not be read or does not describe a valid ext2/ext3/ext4\n" + "@f. If the @v is valid and it really contains an ext2/ext3/ext4\n" + "@f (and not swap or ufs or something else), then the @S\n" + "is corrupt, and you might try running e2fsck with an alternate @S:\n" + " e2fsck -b 8193 <@v>\n" + " or\n" + " e2fsck -b 32768 <@v>\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Filesystem size is wrong */ + { PR_0_FS_SIZE_WRONG, + N_("The @f size (according to the @S) is %b @bs\n" + "The physical size of the @v is %c @bs\n" + "Either the @S or the partition table is likely to be corrupt!\n"), + PROMPT_ABORT, 0, 0, 0, 0 }, + + /* Fragments not supported */ + { PR_0_NO_FRAGMENTS, + N_("@S @b_size = %b, fragsize = %c.\n" + "This version of e2fsck does not support fragment sizes different\n" + "from the @b size.\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Superblock blocks_per_group = bbbb, should have been cccc */ + { PR_0_BLOCKS_PER_GROUP, + N_("@S @bs_per_group = %b, should have been %c\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_0_SB_CORRUPT, 0, 0 }, + + /* Superblock first_data_block = bbbb, should have been cccc */ + { PR_0_FIRST_DATA_BLOCK, + N_("@S first_data_@b = %b, should have been %c\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_0_SB_CORRUPT, 0, 0 }, + + /* Filesystem did not have a UUID; generating one */ + { PR_0_ADD_UUID, + N_("@f did not have a UUID; generating one.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Relocate hint */ + { PR_0_RELOCATE_HINT, + /* xgettext:no-c-format */ + N_("Note: if several inode or block bitmap blocks or part\n" + "of the inode table require relocation, you may wish to try\n" + "running e2fsck with the '-b %S' option first. The problem\n" + "may lie only with the primary block group descriptors, and\n" + "the backup block group descriptors may be OK.\n\n"), + PROMPT_NONE, PR_PREEN_OK | PR_NOCOLLATE, 0, 0, 0 }, + + /* Miscellaneous superblock corruption */ + { PR_0_MISC_CORRUPT_SUPER, + N_("Corruption found in @S. (%s = %N).\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_0_SB_CORRUPT, 0, 0 }, + + /* Error determining physical device size of filesystem */ + { PR_0_GETSIZE_ERROR, + /* xgettext:no-c-format */ + N_("Error determining size of the physical @v: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Inode count in superblock is incorrect */ + { PR_0_INODE_COUNT_WRONG, + N_("@i count in @S is %i, @s %j.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + { PR_0_HURD_CLEAR_FILETYPE, + N_("The Hurd does not support the filetype feature.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Superblock has an invalid journal (inode inum) */ + { PR_0_JOURNAL_BAD_INODE, + /* xgettext:no-c-format */ + N_("@S has an @n @j (@i %i).\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* External journal has multiple filesystem users (unsupported) */ + { PR_0_JOURNAL_UNSUPP_MULTIFS, + N_("External @j has multiple @f users (unsupported).\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Can't find external journal */ + { PR_0_CANT_FIND_JOURNAL, + N_("Can't find external @j\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* External journal has bad superblock */ + { PR_0_EXT_JOURNAL_BAD_SUPER, + N_("External @j has bad @S\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Superblock has a bad journal UUID */ + { PR_0_JOURNAL_BAD_UUID, + N_("External @j does not support this @f\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Filesystem journal superblock is an unknown type */ + { PR_0_JOURNAL_UNSUPP_SUPER, + N_("@f @j @S is unknown type %N (unsupported).\n" + "It is likely that your copy of e2fsck is old and/or doesn't " + "support this @j format.\n" + "It is also possible the @j @S is corrupt.\n"), + PROMPT_ABORT, PR_NO_OK | PR_AFTER_CODE, PR_0_JOURNAL_BAD_SUPER, + 0, 0 }, + + /* Journal superblock is corrupt */ + { PR_0_JOURNAL_BAD_SUPER, + N_("@j @S is corrupt.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock has_journal flag is clear but has a journal */ + { PR_0_JOURNAL_HAS_JOURNAL, + N_("@S has_@j flag is clear, but a @j is present.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock needs_recovery flag is set but no journal is present */ + { PR_0_JOURNAL_RECOVER_SET, + N_("@S needs_recovery flag is set, but no @j is present.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock needs_recovery flag is set, but journal has data */ + { PR_0_JOURNAL_RECOVERY_CLEAR, + N_("@S needs_recovery flag is clear, but @j has data.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Ask if we should clear the journal */ + { PR_0_JOURNAL_RESET_JOURNAL, + N_("Clear @j"), + PROMPT_NULL, PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Filesystem revision is 0, but feature flags are set */ + { PR_0_FS_REV_LEVEL, + N_("@f has feature flag(s) set, but is a revision 0 @f. "), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Clearing orphan inode */ + { PR_0_ORPHAN_CLEAR_INODE, + N_("%s @o @i %i (uid=%Iu, gid=%Ig, mode=%Im, size=%Is)\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Illegal block found in orphaned inode */ + { PR_0_ORPHAN_ILLEGAL_BLOCK_NUM, + N_("@I %B (%b) found in @o @i %i.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Already cleared block found in orphaned inode */ + { PR_0_ORPHAN_ALREADY_CLEARED_BLOCK, + N_("Already cleared %B (%b) found in @o @i %i.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Illegal orphan inode in superblock */ + { PR_0_ORPHAN_ILLEGAL_HEAD_INODE, + /* xgettext:no-c-format */ + N_("@I @o @i %i in @S.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Illegal inode in orphaned inode list */ + { PR_0_ORPHAN_ILLEGAL_INODE, + /* xgettext:no-c-format */ + N_("@I @i %i in @o @i list.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Journal superblock has an unknown read-only feature flag set */ + { PR_0_JOURNAL_UNSUPP_ROCOMPAT, + N_("@j @S has an unknown read-only feature flag set.\n"), + PROMPT_ABORT, 0, 0, 0, 0 }, + + /* Journal superblock has an unknown incompatible feature flag set */ + { PR_0_JOURNAL_UNSUPP_INCOMPAT, + N_("@j @S has an unknown incompatible feature flag set.\n"), + PROMPT_ABORT, 0, 0, 0, 0 }, + + /* Journal version not supported by this e2fsck */ + { PR_0_JOURNAL_UNSUPP_VERSION, + N_("@j version not supported by this e2fsck.\n"), + PROMPT_ABORT, 0, 0, 0, 0 }, + + /* Moving journal from /file to hidden inode */ + { PR_0_MOVE_JOURNAL, + /* xgettext:no-c-format */ + N_("Moving @j from /%s to hidden @i.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error moving journal to hidden file */ + { PR_0_ERR_MOVE_JOURNAL, + /* xgettext:no-c-format */ + N_("Error moving @j: %m\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Found invalid V2 journal superblock fields */ + { PR_0_CLEAR_V2_JOURNAL, + N_("Found @n V2 @j @S fields (from V1 @j).\n" + "Clearing fields beyond the V1 @j @S...\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Ask if we should run the journal anyway */ + { PR_0_JOURNAL_RUN, + N_("Run @j anyway"), + PROMPT_NULL, 0, 0, 0, 0 }, + + /* Run the journal by default */ + { PR_0_JOURNAL_RUN_DEFAULT, + N_("Recovery flag not set in backup @S, so running @j anyway.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Backing up journal inode block information */ + { PR_0_BACKUP_JNL, + N_("Backing up @j @i @b information.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Filesystem does not have resize_inode enabled, but + * s_reserved_gdt_blocks is nnnn; should be zero */ + { PR_0_NONZERO_RESERVED_GDT_BLOCKS, + N_("@f does not have resize_@i enabled, but s_reserved_gdt_@bs\n" + "is %N; @s zero. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Resize_inode not enabled, but the resize inode is non-zero */ + { PR_0_CLEAR_RESIZE_INODE, + N_("Resize_@i not enabled, but the resize @i is non-zero. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Resize inode not valid */ + { PR_0_RESIZE_INODE_INVALID, + N_("Resize @i not valid. "), + PROMPT_RECREATE, 0, 0, 0, 0 }, + + /* Superblock last mount time is in the future */ + { PR_0_FUTURE_SB_LAST_MOUNT, + N_("@S last mount time (%t,\n\tnow = %T) is in the future.\n"), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Superblock last write time is in the future */ + { PR_0_FUTURE_SB_LAST_WRITE, + N_("@S last write time (%t,\n\tnow = %T) is in the future.\n"), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Superblock hint for external superblock should be xxxx */ + { PR_0_EXTERNAL_JOURNAL_HINT, + /* xgettext:no-c-format */ + N_("@S hint for external superblock @s %X. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Adding dirhash hint to filesystem */ + { PR_0_DIRHASH_HINT, + N_("Adding dirhash hint to @f.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* group descriptor N checksum is invalid, should be yyyy. */ + { PR_0_GDT_CSUM, + N_("@g descriptor %g checksum is %04x, should be %04y. "), + PROMPT_FIX, PR_PREEN_OK | PR_LATCH_BG_CHECKSUM, 0, 0, 0 }, + + /* group descriptor N marked uninitialized without feature set. */ + { PR_0_GDT_UNINIT, + /* xgettext:no-c-format */ + N_("@g descriptor %g marked uninitialized without feature set.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Group descriptor N has invalid unused inodes count. */ + { PR_0_GDT_ITABLE_UNUSED, + N_("@g descriptor %g has invalid unused inodes count %b. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Last group block bitmap uninitialized. */ + { PR_0_BB_UNINIT_LAST, + N_("Last @g @b @B uninitialized. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Journal transaction was corrupt, replay was aborted */ + { PR_0_JNL_TXN_CORRUPT, + /* xgettext:no-c-format */ + N_("Journal transaction %i was corrupt, replay was aborted.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* The test_fs filesystem flag is set (and ext4 is available) */ + { PR_0_CLEAR_TESTFS_FLAG, + N_("The test_fs flag is set (and ext4 is available). "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Last mount time is in the future (fudged) */ + { PR_0_FUTURE_SB_LAST_MOUNT_FUDGED, + N_("@S last mount time is in the future.\n\t(by less than a day, " + "probably due to the hardware clock being incorrectly set)\n"), + PROMPT_NONE, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Last write time is in the future (fudged) */ + { PR_0_FUTURE_SB_LAST_WRITE_FUDGED, + N_("@S last write time is in the future.\n\t(by less than a day, " + "probably due to the hardware clock being incorrectly set)\n"), + PROMPT_NONE, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* One or more block group descriptor checksums are invalid (latch) */ + { PR_0_GDT_CSUM_LATCH, + N_("One or more @b @g descriptor checksums are invalid. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Setting free inodes count to right (was wrong) */ + { PR_0_FREE_INODE_COUNT, + N_("Setting free @is count to %j (was %i)\n"), + PROMPT_NONE, PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Setting free blocks count to right (was wrong) */ + { PR_0_FREE_BLOCK_COUNT, + N_("Setting free @bs count to %c (was %b)\n"), + PROMPT_NONE, PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Making quota inode hidden */ + { PR_0_HIDE_QUOTA, + N_("Hiding %U @q @i %i (%Q).\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock has invalid MMP block. */ + { PR_0_MMP_INVALID_BLK, + N_("@S has invalid MMP block. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock has invalid MMP magic. */ + { PR_0_MMP_INVALID_MAGIC, + N_("@S has invalid MMP magic. "), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Opening file system failed */ + { PR_0_OPEN_FAILED, + /* xgettext:no-c-format */ + N_("ext2fs_open2: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Checking group descriptor failed */ + { PR_0_CHECK_DESC_FAILED, + /* xgettext:no-c-format */ + N_("ext2fs_check_desc: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Superblock metadata_csum supersedes uninit_bg; both feature + * bits cannot be set simultaneously. */ + { PR_0_META_AND_GDT_CSUM_SET, + N_("@S metadata_csum supersedes uninit_bg; both feature " + "bits cannot be set simultaneously."), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Superblock MMP block checksum does not match MMP block. */ + { PR_0_MMP_CSUM_INVALID, + N_("@S MMP @b checksum does not match. "), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Superblock 64bit filesystem needs extents to access the whole disk */ + { PR_0_64BIT_WITHOUT_EXTENTS, + N_("@S 64bit @f needs extents to access the whole disk. "), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* The first_meta_bg is too big */ + { PR_0_FIRST_META_BG_TOO_BIG, + N_("First_meta_bg is too big. (%N, max value %g). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* External journal superblock checksum does not match superblock */ + { PR_0_EXT_JOURNAL_SUPER_CSUM_INVALID, + N_("External @j @S checksum does not match @S. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Superblock metadata_csum_seed means nothing without metadata_csum */ + { PR_0_CSUM_SEED_WITHOUT_META_CSUM, + N_("@S metadata_csum_seed is not necessary without metadata_csum."), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Error initializing quota context */ + { PR_0_QUOTA_INIT_CTX, + /* xgettext:no-c-format */ + N_("Error initializing quota context in support library: %m\n"), + PROMPT_NULL, PR_FATAL, 0, 0, 0 }, + + /* Bad required extra isize in superblock */ + { PR_0_BAD_MIN_EXTRA_ISIZE, + N_("Bad required extra isize in @S (%N). "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Bad desired extra isize in superblock */ + { PR_0_BAD_WANT_EXTRA_ISIZE, + N_("Bad desired extra isize in @S (%N). "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Invalid quota inode number */ + { PR_0_INVALID_QUOTA_INO, + N_("Invalid %U @q @i %i. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Too many inodes in the filesystem */ + { PR_0_INODE_COUNT_BIG, + N_("@S would have too many inodes (%N).\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_0_SB_CORRUPT, 0, 0 }, + + /* Meta_bg and resize_inode are not compatible, disable resize_inode*/ + { PR_0_DISABLE_RESIZE_INODE, + N_("Resize_@i and meta_bg features are enabled. Those features are\n" + "not compatible. Resize @i should be disabled. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Orphan file contains holes */ + { PR_0_ORPHAN_FILE_HOLE, + N_("Orphan file (@i %i) contains hole at @b %b. Terminating orphan file recovery.\n"), + PROMPT_NONE, 0 }, + + /* Orphan file block has wrong magic */ + { PR_0_ORPHAN_FILE_BAD_MAGIC, + N_("Orphan file (@i %i) @b %b contains wrong magic. Terminating orphan file recovery.\n"), + PROMPT_NONE, 0 }, + + /* Orphan file block has wrong checksum */ + { PR_0_ORPHAN_FILE_BAD_CHECKSUM, + N_("Orphan file (@i %i) @b %b contains wrong checksum. Terminating orphan file recovery.\n"), + PROMPT_NONE, 0 }, + + /* Orphan file size isn't multiple of blocks size */ + { PR_0_ORPHAN_FILE_WRONG_SIZE, + N_("Orphan file (@i %i) size is not multiple of block size. Terminating orphan file recovery.\n"), + PROMPT_NONE, 0 }, + + /* Pass 1 errors */ + + /* Pass 1: Checking inodes, blocks, and sizes */ + { PR_1_PASS_HEADER, + N_("Pass 1: Checking @is, @bs, and sizes\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Root inode is not a directory */ + { PR_1_ROOT_NO_DIR, N_("@r is not a @d. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Root inode has dtime set */ + { PR_1_ROOT_DTIME, + N_("@r has dtime set (probably due to old mke2fs). "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Reserved inode has bad mode */ + { PR_1_RESERVED_BAD_MODE, + N_("Reserved @i %i (%Q) has @n mode. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Deleted inode inum has zero dtime */ + { PR_1_ZERO_DTIME, + /* xgettext:no-c-format */ + N_("@D @i %i has zero dtime. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode inum is in use, but has dtime set */ + { PR_1_SET_DTIME, + /* xgettext:no-c-format */ + N_("@i %i is in use, but has dtime set. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode inum is a zero-length directory */ + { PR_1_ZERO_LENGTH_DIR, + /* xgettext:no-c-format */ + N_("@i %i is a @z @d. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Group block bitmap at block conflicts with some other fs block */ + { PR_1_BB_CONFLICT, + N_("@g %g's @b @B at %b @C.\n"), + PROMPT_RELOCATE, 0, 0, 0, 0 }, + + /* Group inode bitmap at block conflicts with some other fs block */ + { PR_1_IB_CONFLICT, + N_("@g %g's @i @B at %b @C.\n"), + PROMPT_RELOCATE, 0, 0, 0, 0 }, + + /* Group inode table at block conflicts with some other fs block */ + { PR_1_ITABLE_CONFLICT, + N_("@g %g's @i table at %b @C.\n"), + PROMPT_RELOCATE, 0, 0, 0, 0 }, + + /* Group block bitmap (block) is bad */ + { PR_1_BB_BAD_BLOCK, + N_("@g %g's @b @B (%b) is bad. "), + PROMPT_RELOCATE, 0, 0, 0, 0 }, + + /* Group inode bitmap (block) is bad */ + { PR_1_IB_BAD_BLOCK, + N_("@g %g's @i @B (%b) is bad. "), + PROMPT_RELOCATE, 0, 0, 0, 0 }, + + /* Inode inum, i_size is small, should be larger */ + { PR_1_BAD_I_SIZE, + N_("@i %i, i_size is %Is, @s %N. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode inum, i_blocks is small, should be larger */ + { PR_1_BAD_I_BLOCKS, + N_("@i %i, i_@bs is %Ib, @s %N. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Illegal block number in inode */ + { PR_1_ILLEGAL_BLOCK_NUM, + N_("@I %B (%b) in @i %i. "), + PROMPT_CLEAR, PR_LATCH_BLOCK, 0, 0, 0 }, + + /* Block number overlaps filesystem metadata in inode */ + { PR_1_BLOCK_OVERLAPS_METADATA, + N_("%B (%b) overlaps @f metadata in @i %i. "), + PROMPT_CLEAR, PR_LATCH_BLOCK, 0, 0, 0 }, + + /* Inode has illegal blocks (latch question) */ + { PR_1_INODE_BLOCK_LATCH, + /* xgettext:no-c-format */ + N_("@i %i has illegal @b(s). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Too many illegal blocks in inode */ + { PR_1_TOO_MANY_BAD_BLOCKS, + /* xgettext:no-c-format */ + N_("Too many illegal @bs in @i %i.\n"), + PROMPT_CLEAR_INODE, PR_NO_OK, 0, 0, 0 }, + + /* Illegal block number in bad block inode */ + { PR_1_BB_ILLEGAL_BLOCK_NUM, + N_("@I %B (%b) in bad @b @i. "), + PROMPT_CLEAR, PR_LATCH_BBLOCK, 0, 0, 0 }, + + /* Bad block inode has illegal blocks (latch question) */ + { PR_1_INODE_BBLOCK_LATCH, + N_("Bad @b @i has illegal @b(s). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Duplicate or bad blocks in use! */ + { PR_1_DUP_BLOCKS_PREENSTOP, + N_("Duplicate or bad @b in use!\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Bad block number used as bad block inode indirect block */ + { PR_1_BBINODE_BAD_METABLOCK, + N_("Bad @b %b used as bad @b @i indirect @b. "), + PROMPT_CLEAR, PR_LATCH_BBLOCK, 0, 0, 0 }, + + /* Inconsistency can't be fixed prompt */ + { PR_1_BBINODE_BAD_METABLOCK_PROMPT, + N_("\nThe bad @b @i has probably been corrupted. You probably\n" + "should stop now and run ""e2fsck -c"" to scan for bad blocks\n" + "in the @f.\n"), + PROMPT_CONTINUE, PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Bad primary block */ + { PR_1_BAD_PRIMARY_BLOCK, + N_("\nIf the @b is really bad, the @f can not be fixed.\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_1_BAD_PRIMARY_BLOCK_PROMPT, 0, 0 }, + + /* Bad primary block prompt */ + { PR_1_BAD_PRIMARY_BLOCK_PROMPT, + N_("You can remove this @b from the bad @b list and hope\n" + "that the @b is really OK. But there are no guarantees.\n\n"), + PROMPT_CLEAR, PR_PREEN_NOMSG, 0, 0, 0 }, + + /* The primary superblock block is on the bad block list */ + { PR_1_BAD_PRIMARY_SUPERBLOCK, + N_("The primary @S (%b) is on the bad @b list.\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_1_BAD_PRIMARY_BLOCK, 0, 0 }, + + /* Bad primary block group descriptors */ + { PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR, + N_("Block %b in the primary @g descriptors " + "is on the bad @b list\n"), + PROMPT_NONE, PR_AFTER_CODE, PR_1_BAD_PRIMARY_BLOCK, 0, 0 }, + + /* Warning: Group number's superblock (block) is bad */ + { PR_1_BAD_SUPERBLOCK, + N_("Warning: Group %g's @S (%b) is bad.\n"), + PROMPT_NONE, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Warning: Group number's copy of the group descriptors has a bad + * block */ + { PR_1_BAD_GROUP_DESCRIPTORS, + N_("Warning: Group %g's copy of the @g descriptors has a bad " + "@b (%b).\n"), + PROMPT_NONE, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Block number claimed for no reason in process_bad_blocks */ + { PR_1_PROGERR_CLAIMED_BLOCK, + N_("Programming error? @b #%b claimed for no reason in " + "process_bad_@b.\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Allocating number contiguous block(s) in block group number */ + { PR_1_RELOC_BLOCK_ALLOCATE, + N_("@A %N contiguous @b(s) in @b @g %g for %s: %m\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Allocating block buffer for relocating process */ + { PR_1_RELOC_MEMORY_ALLOCATE, + /* xgettext:no-c-format */ + N_("@A @b buffer for relocating %s\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Relocating group number's information from X to Y */ + { PR_1_RELOC_FROM_TO, + N_("Relocating @g %g's %s from %b to %c...\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Relocating group number's information to X */ + { PR_1_RELOC_TO, + /* xgettext:no-c-format */ + N_("Relocating @g %g's %s to %c...\n"), /* xgettext:no-c-format */ + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Warning: could not read block number of relocation process */ + { PR_1_RELOC_READ_ERR, + N_("Warning: could not read @b %b of %s: %m\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Warning: could not write block number of relocation process */ + { PR_1_RELOC_WRITE_ERR, + N_("Warning: could not write @b %b for %s: %m\n"), + PROMPT_NONE, PR_PREEN_OK, 0, 0, 0 }, + + /* Error allocating inode bitmap */ + { PR_1_ALLOCATE_IBITMAP_ERROR, + N_("@A @i @B (%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error allocating block bitmap */ + { PR_1_ALLOCATE_BBITMAP_ERROR, + N_("@A @b @B (%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error allocating icount link information */ + { PR_1_ALLOCATE_ICOUNT, + /* xgettext:no-c-format */ + N_("@A icount link information: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error allocating directory block array */ + { PR_1_ALLOCATE_DBCOUNT, + /* xgettext:no-c-format */ + N_("@A @d @b array: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error while scanning inodes */ + { PR_1_ISCAN_ERROR, + /* xgettext:no-c-format */ + N_("Error while scanning @is (%i): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error while iterating over blocks in inode */ + { PR_1_BLOCK_ITERATE, + /* xgettext:no-c-format */ + N_("Error while iterating over @bs in @i %i: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error storing inode count information */ + { PR_1_ICOUNT_STORE, + N_("Error storing @i count information (@i=%i, count=%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error storing directory block information */ + { PR_1_ADD_DBLOCK, + N_("Error storing @d @b information " + "(@i=%i, @b=%b, num=%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error reading inode (for clearing) */ + { PR_1_READ_INODE, + /* xgettext:no-c-format */ + N_("Error reading @i %i: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Suppress messages prompt */ + { PR_1_SUPPRESS_MESSAGES, "", PROMPT_SUPPRESS, PR_NO_OK, 0, 0, 0 }, + + /* Imagic number has imagic flag set when fs doesn't support it */ + { PR_1_SET_IMAGIC, + /* xgettext:no-c-format */ + N_("@i %i has imagic flag set. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Immutable flag set on a device or socket inode */ + { PR_1_SET_IMMUTABLE, + /* xgettext:no-c-format */ + N_("Special (@v/socket/fifo/symlink) file (@i %i) has immutable\n" + "or append-only flag set. "), + PROMPT_CLEAR, PR_PREEN_OK | PR_PREEN_NO | PR_NO_OK, 0, 0, 0 }, + + /* Non-zero size for device, fifo or socket inode */ + { PR_1_SET_NONZSIZE, + /* xgettext:no-c-format */ + N_("Special (@v/socket/fifo) @i %i has non-zero size. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Filesystem has feature flag(s) set, but is a revision 0 filesystem */ + { PR_1_FS_REV_LEVEL, + N_("@f has feature flag(s) set, but is a revision 0 @f. "), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Journal inode is not in use, but contains data */ + { PR_1_JOURNAL_INODE_NOT_CLEAR, + N_("@j @i is not in use, but contains data. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Journal is not a regular file */ + { PR_1_JOURNAL_BAD_MODE, + N_("@j is not regular file. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode that was part of the orphan list */ + { PR_1_LOW_DTIME, + /* xgettext:no-c-format */ + N_("@i %i was part of the @o @i list. "), + PROMPT_FIX, PR_LATCH_LOW_DTIME, 0, 0, 0 }, + + /* Inodes that were part of a corrupted orphan linked list found + * (latch question) */ + { PR_1_ORPHAN_LIST_REFUGEES, + N_("@is that were part of a corrupted orphan linked list found. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Error allocating refcount structure */ + { PR_1_ALLOCATE_REFCOUNT, + N_("@A refcount structure (%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error reading extended attribute block */ + { PR_1_READ_EA_BLOCK, + N_("Error reading @a @b %b for @i %i. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Inode number has a bad extended attribute block */ + { PR_1_BAD_EA_BLOCK, + N_("@i %i has a bad @a @b %b. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Error reading Extended Attribute block while fixing refcount */ + { PR_1_EXTATTR_READ_ABORT, + N_("Error reading @a @b %b (%m). "), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Extended attribute number has reference count incorrect */ + { PR_1_EXTATTR_REFCOUNT, + N_("@a @b %b has reference count %r, @s %N. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Error writing Extended Attribute block while fixing refcount */ + { PR_1_EXTATTR_WRITE_ABORT, + N_("Error writing @a @b %b (%m). "), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Extended attribute block has h_blocks > 1 */ + { PR_1_EA_MULTI_BLOCK, + N_("@a @b %b has h_@bs > 1. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Allocating extended attribute region allocation structure */ + { PR_1_EA_ALLOC_REGION_ABORT, + N_("@A @a region allocation structure. "), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Extended Attribute block number is corrupt (allocation collision) */ + { PR_1_EA_ALLOC_COLLISION, + N_("@a @b %b is corrupt (allocation collision). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Extended attribute block number is corrupt (invalid name) */ + { PR_1_EA_BAD_NAME, + N_("@a @b %b is corrupt (@n name). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Extended attribute block number is corrupt (invalid value) */ + { PR_1_EA_BAD_VALUE, + N_("@a @b %b is corrupt (@n value). "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Inode number is too big (latch question) */ + { PR_1_INODE_TOOBIG, + /* xgettext:no-c-format */ + N_("@i %i is too big. "), PROMPT_TRUNCATE, 0, 0, 0, 0 }, + + /* Problem causes directory to be too big */ + { PR_1_TOOBIG_DIR, + N_("%B (%b) causes @d to be too big. "), + PROMPT_CLEAR, PR_LATCH_TOOBIG, 0, 0, 0 }, + + /* Problem causes file to be too big */ + { PR_1_TOOBIG_REG, + N_("%B (%b) causes file to be too big. "), + PROMPT_CLEAR, PR_LATCH_TOOBIG, 0, 0, 0 }, + + /* Problem causes symlink to be too big */ + { PR_1_TOOBIG_SYMLINK, + N_("%B (%b) causes symlink to be too big. "), + PROMPT_CLEAR, PR_LATCH_TOOBIG, 0, 0, 0 }, + + /* Inode has INDEX_FL flag set on filesystem without htree support */ + { PR_1_HTREE_SET, + /* xgettext:no-c-format */ + N_("@i %i has INDEX_FL flag set on @f without htree support.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode number has INDEX_FL flag set but is on a directory */ + { PR_1_HTREE_NODIR, + /* xgettext:no-c-format */ + N_("@i %i has INDEX_FL flag set but is not a @d.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* htree directory has an invalid root node */ + { PR_1_HTREE_BADROOT, + /* xgettext:no-c-format */ + N_("@h %i has an @n root node.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Htree directory has an unsupported hash version */ + { PR_1_HTREE_HASHV, + N_("@h %i has an unsupported hash version (%N)\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Htree directory uses an Incompatible htree root node flag */ + { PR_1_HTREE_INCOMPAT, + /* xgettext:no-c-format */ + N_("@h %i uses an incompatible htree root node flag.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Htree directory has a tree depth which is too big */ + { PR_1_HTREE_DEPTH, + N_("@h %i has a tree depth (%N) which is too big\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Bad block inode has an indirect block number that conflicts with + * filesystem metadata */ + { PR_1_BB_FS_BLOCK, + N_("Bad @b @i has an indirect @b (%b) that conflicts with\n" + "@f metadata. "), + PROMPT_CLEAR, PR_LATCH_BBLOCK, 0, 0, 0 }, + + /* Resize inode (re)creation failed */ + { PR_1_RESIZE_INODE_CREATE, + /* xgettext:no-c-format */ + N_("Resize @i (re)creation failed: %m."), + PROMPT_CONTINUE, 0, 0, 0, 0 }, + + /* inode has a extra size i_extra_isize which is invalid */ + { PR_1_EXTRA_ISIZE, + N_("@i %i has a extra size (%IS) which is @n\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Extended attribute in inode has a namelen which is invalid */ + { PR_1_ATTR_NAME_LEN, + N_("@a in @i %i has a namelen (%N) which is @n\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Extended attribute in inode has a value offset which is invalid */ + { PR_1_ATTR_VALUE_OFFSET, + N_("@a in @i %i has a value offset (%N) which is @n\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* extended attribute in inode has a value block which is invalid */ + { PR_1_ATTR_VALUE_BLOCK, + N_("@a in @i %i has a value @b (%N) which is @n (must be 0)\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* extended attribute in inode has a value size which is invalid */ + { PR_1_ATTR_VALUE_SIZE, + N_("@a in @i %i has a value size (%N) which is @n\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* extended attribute in inode has a hash which is invalid */ + { PR_1_ATTR_HASH, + N_("@a in @i %i has a hash (%N) which is @n\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* inode is a type but it looks like it is really a directory */ + { PR_1_TREAT_AS_DIRECTORY, + N_("@i %i is a %It but it looks like it is really a directory.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Error while reading extent tree in inode */ + { PR_1_READ_EXTENT, + /* xgettext:no-c-format */ + N_("Error while reading over @x tree in @i %i: %m\n"), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Failure to iterate extents in inode */ + { PR_1_EXTENT_ITERATE_FAILURE, + N_("Failed to iterate extents in @i %i\n" + "\t(op %s, blk %b, lblk %c): %m\n"), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Inode has an invalid extent starting block */ + { PR_1_EXTENT_BAD_START_BLK, + N_("@i %i has an @n extent\n\t(logical @b %c, @n physical @b %b, len %N)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Inode has an invalid extent that ends beyond filesystem */ + { PR_1_EXTENT_ENDS_BEYOND, + N_("@i %i has an @n extent\n\t(logical @b %c, physical @b %b, @n len %N)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* inode has EXTENTS_FL flag set on filesystem without extents support*/ + { PR_1_EXTENTS_SET, + /* xgettext:no-c-format */ + N_("@i %i has EXTENTS_FL flag set on @f without extents support.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* inode is in extents format, but superblock is missing EXTENTS feature */ + { PR_1_EXTENT_FEATURE, + /* xgettext:no-c-format */ + N_("@i %i is in extent format, but @S is missing EXTENTS feature\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* inode missing EXTENTS_FL, but is an extent inode */ + { PR_1_UNSET_EXTENT_FL, + /* xgettext:no-c-format */ + N_("@i %i missing EXTENT_FL, but is in extents format\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Fast symlink has EXTENTS_FL set */ + { PR_1_FAST_SYMLINK_EXTENT_FL, + /* xgettext:no-c-format */ + N_("Fast symlink %i has EXTENT_FL set. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Extents are out of order */ + { PR_1_OUT_OF_ORDER_EXTENTS, + N_("@i %i has out of order extents\n\t(@n logical @b %c, physical @b %b, len %N)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + { PR_1_EXTENT_HEADER_INVALID, + N_("@i %i has an invalid extent node (blk %b, lblk %c)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Failed to convert subcluster block bitmap */ + { PR_1_CONVERT_SUBCLUSTER, + /* xgettext:no-c-format */ + N_("Error converting subcluster @b @B: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Quota inode is not a regular file */ + { PR_1_QUOTA_BAD_MODE, + N_("@q @i is not a regular file. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Quota inode is not in use, but contains data */ + { PR_1_QUOTA_INODE_NOT_CLEAR, + N_("@q @i is not in use, but contains data. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Quota inode is visible to the user */ + { PR_1_QUOTA_INODE_NOT_HIDDEN, + N_("@q @i is visible to the user. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* The bad block inode looks invalid */ + { PR_1_INVALID_BAD_INODE, + N_("The bad @b @i looks @n. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Extent has zero length extent */ + { PR_1_EXTENT_LENGTH_ZERO, + N_("@i %i has zero length extent\n\t(@n logical @b %c, physical @b %b)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* inode seems to contain garbage */ + { PR_1_INODE_IS_GARBAGE, + /* xgettext:no-c-format */ + N_("@i %i seems to contain garbage. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* inode passes checks, but checksum does not match inode */ + { PR_1_INODE_ONLY_CSUM_INVALID, + /* xgettext:no-c-format */ + N_("@i %i passes checks, but checksum does not match @i. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode extended attribute is corrupt (allocation collision) */ + { PR_1_INODE_EA_ALLOC_COLLISION, + /* xgettext:no-c-format */ + N_("@i %i @a is corrupt (allocation collision). "), + PROMPT_CLEAR, 0, 0, 0, 0}, + + /* + * Inode extent block passes checks, but checksum does not match + * extent + */ + { PR_1_EXTENT_ONLY_CSUM_INVALID, + N_("@i %i extent block passes checks, but checksum does not match " + "extent\n\t(logical @b %c, physical @b %b, len %N)\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* + * Inode extended attribute block passes checks, but checksum does not + * match block. + */ + { PR_1_EA_BLOCK_ONLY_CSUM_INVALID, + N_("@i %i @a @b %b passes checks, but checksum does not match @b. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Interior extent node level number of inode doesn't first node down */ + { PR_1_EXTENT_INDEX_START_INVALID, + N_("Interior @x node level %N of @i %i:\n" + "Logical start %b does not match logical start %c at next level. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Inode end of extent exceeds allowed value */ + { PR_1_EXTENT_END_OUT_OF_BOUNDS, + N_("@i %i, end of extent exceeds allowed value\n\t(logical @b %c, physical @b %b, len %N)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Inode has inline data, but superblock is missing INLINE_DATA feature */ + { PR_1_INLINE_DATA_FEATURE, + /* xgettext:no-c-format */ + N_("@i %i has inline data, but @S is missing INLINE_DATA feature\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* inode has INLINE_DATA_FL flag on filesystem without inline data */ + { PR_1_INLINE_DATA_SET, + /* xgettext:no-c-format */ + N_("@i %i has INLINE_DATA_FL flag on @f without inline data support.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* + * Inode block conflicts with critical metadata, skipping block checks + */ + { PR_1_CRITICAL_METADATA_COLLISION, + /* xgettext:no-c-format */ + N_("@i %i block %b conflicts with critical metadata, skipping block checks.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Directory inode block <block> should be at block <otherblock> */ + { PR_1_COLLAPSE_DBLOCK, + N_("@d @i %i @b %b should be at @b %c. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Extents/inlinedata flag set on a device or socket inode */ + { PR_1_UNINIT_DBLOCK, + /* xgettext:no-c-format */ + N_("@d @i %i has @x marked uninitialized at @b %c. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode logical block (physical block) violates cluster allocation */ + { PR_1_MISALIGNED_CLUSTER, + N_("@i %i logical @b %b (physical @b %c) violates cluster allocation rules.\nWill fix in pass 1B.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Inode has INLINE_DATA_FL flag but extended attribute not found */ + { PR_1_INLINE_DATA_NO_ATTR, + /* xgettext:no-c-format */ + N_("@i %i has INLINE_DATA_FL flag but @a not found. "), + PROMPT_TRUNCATE, 0, 0, 0, 0 }, + + /* Special (device/socket/fifo) file (inode num) has extents + * or inline-data flag set */ + { PR_1_SPECIAL_EXTENTS_IDATA, + /* xgettext:no-c-format */ + N_("Special (@v/socket/fifo) file (@i %i) has extents\n" + "or inline-data flag set. "), + PROMPT_CLEAR, PR_PREEN_OK | PR_PREEN_NO | PR_NO_OK, 0, 0, 0 }, + + /* Inode has extent header but inline data flag is set */ + { PR_1_CLEAR_INLINE_DATA_FOR_EXTENT, + /* xgettext:no-c-format */ + N_("@i %i has @x header but inline data flag is set.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Inode seems to have inline data but extent flag is set */ + { PR_1_CLEAR_EXTENT_FOR_INLINE_DATA, + /* xgettext:no-c-format */ + N_("@i %i seems to have inline data but @x flag is set.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Inode seems to have block map but inline data and extent flags set */ + { PR_1_CLEAR_EXTENT_INLINE_DATA_FLAGS, + /* xgettext:no-c-format */ + N_("@i %i seems to have @b map but inline data and @x flags set.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Inode has inline data and extent flags but i_block contains junk */ + { PR_1_CLEAR_EXTENT_INLINE_DATA_INODE, + /* xgettext:no-c-format */ + N_("@i %i has inline data and @x flags set but i_block contains junk.\n"), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Bad block list says the bad block list inode is bad */ + { PR_1_BADBLOCKS_IN_BADBLOCKS, + N_("Bad block list says the bad block list @i is bad. "), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Error allocating extent region allocation structure */ + { PR_1_EXTENT_ALLOC_REGION_ABORT, + N_("@A @x region allocation structure. "), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Inode leaf has a duplicate extent mapping */ + { PR_1_EXTENT_COLLISION, + N_("@i %i has a duplicate @x mapping\n\t(logical @b %c, @n physical @b %b, len %N)\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Error allocating memory for encrypted inode list */ + { PR_1_ALLOCATE_ENCRYPTED_INODE_LIST, + N_("@A %N bytes of memory for encrypted @i list\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Inode extent tree could be more shallow */ + { PR_1_EXTENT_BAD_MAX_DEPTH, + N_("@i %i @x tree could be more shallow (%b; could be <= %c)\n"), + PROMPT_FIX, PR_NO_OK | PR_PREEN_NO | PR_PREEN_OK, 0, 0, 0 }, + + /* inode num on bigalloc filesystem cannot be block mapped */ + { PR_1_NO_BIGALLOC_BLOCKMAP_FILES, + /* xgettext:no-c-format */ + N_("@i %i on bigalloc @f cannot be @b mapped. "), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Inode has corrupt extent header */ + { PR_1_MISSING_EXTENT_HEADER, + /* xgettext:no-c-format */ + N_("@i %i has corrupt @x header. "), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Timestamp(s) on inode beyond 2310-04-04 are likely pre-1970. */ + { PR_1_EA_TIME_OUT_OF_RANGE, + /* xgettext:no-c-format */ + N_("Timestamp(s) on @i %i beyond 2310-04-04 are likely pre-1970.\n"), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Inode has illegal extended attribute value inode */ + { PR_1_ATTR_VALUE_EA_INODE, + N_("@i %i has @I @a value @i %N.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode has invalid extended attribute. EA inode missing + * EA_INODE flag. */ + { PR_1_ATTR_NO_EA_INODE_FL, + N_("@i %i has @n @a. EA @i %N missing EA_INODE flag.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* EA inode for parent inode missing EA_INODE flag. */ + { PR_1_ATTR_SET_EA_INODE_FL, + N_("EA @i %N for parent @i %i missing EA_INODE flag.\n "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Offer to clear uninitialized flag on an extent */ + { PR_1_CLEAR_UNINIT_EXTENT, + /* xgettext:no-c-format */ + N_("@i %i has @x marked uninitialized at @b %c (len %N). "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Casefold flag set on a non-directory */ + { PR_1_CASEFOLD_NONDIR, + N_("@i %i has the casefold flag set but is not a directory. "), + PROMPT_CLEAR_FLAG, 0, 0, 0, 0 }, + + /* Casefold flag set, but file system is missing the casefold feature */ + { PR_1_CASEFOLD_FEATURE, + N_("@d %p has the casefold flag, but the\ncasefold feature is not enabled. "), + PROMPT_CLEAR_FLAG, 0, 0, 0, 0 }, + + /* Inode has encrypt flag but no encryption extended attribute */ + { PR_1_MISSING_ENCRYPTION_XATTR, + N_("@i %i has encrypt flag but no encryption @a.\n"), + PROMPT_CLEAR_FLAG, 0, 0, 0, 0 }, + + /* Encrypted inode has corrupt encryption extended attribute */ + { PR_1_CORRUPT_ENCRYPTION_XATTR, + N_("Encrypted @i %i has corrupt encryption @a.\n"), + PROMPT_CLEAR_INODE, 0, 0, 0, 0 }, + + /* Htree directory should use SipHash but does not */ + { PR_1_HTREE_NEEDS_SIPHASH, + N_("@h %i uses hash version (%N), but should use SipHash (6) \n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Htree directory uses SipHash but should not */ + { PR_1_HTREE_CANNOT_SIPHASH, + N_("@h %i uses SipHash, but should not. "), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Orphan file has bad mode */ + { PR_1_ORPHAN_FILE_BAD_MODE, + N_("Orphan file @i %i is not regular file. "), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* Orphan file inode is not in use, but contains data */ + { PR_1_ORPHAN_FILE_NOT_CLEAR, + N_("Orphan file @i %i is not in use, but contains data. "), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* Pass 1b errors */ + + /* Pass 1B: Rescan for duplicate/bad blocks */ + { PR_1B_PASS_HEADER, + N_("\nRunning additional passes to resolve @bs claimed by more than one @i...\n" + "Pass 1B: Rescanning for @m @bs\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Duplicate/bad block(s) header */ + { PR_1B_DUP_BLOCK_HEADER, + /* xgettext:no-c-format */ + N_("@m @b(s) in @i %i:"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Duplicate/bad block(s) in inode */ + { PR_1B_DUP_BLOCK, + " %b", + PROMPT_NONE, PR_LATCH_DBLOCK | PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Duplicate/bad block(s) end */ + { PR_1B_DUP_BLOCK_END, + "\n", + PROMPT_NONE, PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Error while scanning inodes */ + { PR_1B_ISCAN_ERROR, + /* xgettext:no-c-format */ + N_("Error while scanning inodes (%i): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error allocating inode bitmap */ + { PR_1B_ALLOCATE_IBITMAP_ERROR, + /* xgettext:no-c-format */ + N_("@A @i @B (@i_dup_map): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error while iterating over blocks */ + { PR_1B_BLOCK_ITERATE, + /* xgettext:no-c-format */ + N_("Error while iterating over @bs in @i %i (%s): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error adjusting EA refcount */ + { PR_1B_ADJ_EA_REFCOUNT, + N_("Error adjusting refcount for @a @b %b (@i %i): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Duplicate/bad block range in inode */ + { PR_1B_DUP_RANGE, + " %b--%c", + PROMPT_NONE, PR_LATCH_DBLOCK | PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Pass 1C: Scan directories for inodes with multiply-claimed blocks. */ + { PR_1C_PASS_HEADER, + N_("Pass 1C: Scanning directories for @is with @m @bs\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + + /* Pass 1D: Reconciling multiply-claimed blocks */ + { PR_1D_PASS_HEADER, + N_("Pass 1D: Reconciling @m @bs\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* File has duplicate blocks */ + { PR_1D_DUP_FILE, + N_("File %Q (@i #%i, mod time %IM) \n" + " has %r @m @b(s), shared with %N file(s):\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* List of files sharing duplicate blocks */ + { PR_1D_DUP_FILE_LIST, + N_("\t%Q (@i #%i, mod time %IM)\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* File sharing blocks with filesystem metadata */ + { PR_1D_SHARE_METADATA, + N_("\t<@f metadata>\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Report of how many duplicate/bad inodes */ + { PR_1D_NUM_DUP_INODES, + N_("(There are %N @is containing @m @bs.)\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Duplicated blocks already reassigned or cloned. */ + { PR_1D_DUP_BLOCKS_DEALT, + N_("@m @bs already reassigned or cloned.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Clone duplicate/bad blocks? */ + { PR_1D_CLONE_QUESTION, + "", PROMPT_CLONE, PR_NO_OK, 0, 0, 0 }, + + /* Delete file? */ + { PR_1D_DELETE_QUESTION, + "", PROMPT_DELETE, 0, 0, 0, 0 }, + + /* Couldn't clone file (error) */ + { PR_1D_CLONE_ERROR, + /* xgettext:no-c-format */ + N_("Couldn't clone file: %m\n"), PROMPT_NONE, 0, 0, 0, 0 }, + + /* Pass 1E Extent tree optimization */ + + /* Pass 1E: Optimizing extent trees */ + { PR_1E_PASS_HEADER, + N_("Pass 1E: Optimizing @x trees\n"), + PROMPT_NONE, PR_HEADER | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Failed to optimize extent tree */ + { PR_1E_OPTIMIZE_EXT_ERR, + /* xgettext:no-c-format */ + N_("Failed to optimize @x tree %p (%i): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Optimizing extent trees */ + { PR_1E_OPTIMIZE_EXT_HEADER, + N_("Optimizing @x trees: "), + PROMPT_NONE, PR_MSG_ONLY, 0, 0, 0 }, + + /* Rebuilding extent tree %d */ + { PR_1E_OPTIMIZE_EXT, + " %i", + PROMPT_NONE, PR_LATCH_OPTIMIZE_EXT | PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Rebuilding extent tree end */ + { PR_1E_OPTIMIZE_EXT_END, + "\n", + PROMPT_NONE, PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Internal error: extent tree depth too large */ + { PR_1E_MAX_EXTENT_TREE_DEPTH, + N_("Internal error: max extent tree depth too large (%b; expected=%c).\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Inode extent tree could be shorter */ + { PR_1E_CAN_COLLAPSE_EXTENT_TREE, + N_("@i %i @x tree (at level %b) could be shorter. "), + PROMPT_OPTIMIZE, PR_NO_OK | PR_PREEN_NO | PR_PREEN_OK | PR_NOT_A_FIX, 0, 0, 0 }, + + /* Inode extent tree could be narrower */ + { PR_1E_CAN_NARROW_EXTENT_TREE, + N_("@i %i @x tree (at level %b) could be narrower. "), + PROMPT_OPTIMIZE, PR_NO_OK | PR_PREEN_NO | PR_PREEN_OK | PR_NOT_A_FIX, 0, 0, 0 }, + + /* Pass 2 errors */ + + /* Pass 2: Checking directory structure */ + { PR_2_PASS_HEADER, + N_("Pass 2: Checking @d structure\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Bad inode number for '.' */ + { PR_2_BAD_INODE_DOT, + /* xgettext:no-c-format */ + N_("@n @i number for '.' in @d @i %i.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Entry 'xxxx' in /a/b/c has bad inode number.*/ + { PR_2_BAD_INO, + N_("@E has @n @i #: %Di.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Entry 'xxxx' in /a/b/c has deleted/unused inode nnnnn.*/ + { PR_2_UNUSED_INODE, + N_("@E has @D/unused @i %Di. "), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Directory entry is link to '.' */ + { PR_2_LINK_DOT, + N_("@E @L to '.' "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Directory entry points to inode now located in a bad block */ + { PR_2_BB_INODE, + N_("@E points to @i (%Di) located in a bad @b.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Directory entry contains a link to a directory */ + { PR_2_LINK_DIR, + N_("@E @L to @d %P (%Di).\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Directory entry contains a link to the root directory */ + { PR_2_LINK_ROOT, + N_("@E @L to the @r.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Directory entry has illegal characters in its name */ + { PR_2_BAD_NAME, + N_("@E has illegal characters in its name.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Missing '.' in directory inode */ + { PR_2_MISSING_DOT, + /* xgettext:no-c-format */ + N_("Missing '.' in @d @i %i.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Missing '..' in directory inode */ + { PR_2_MISSING_DOT_DOT, + /* xgettext:no-c-format */ + N_("Missing '..' in @d @i %i.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* First entry in directory inode doesn't contain '.' */ + { PR_2_1ST_NOT_DOT, + N_("First @e '%Dn' (@i=%Di) in @d @i %i (%p) @s '.'\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Second entry in directory inode doesn't contain '..' */ + { PR_2_2ND_NOT_DOT_DOT, + N_("Second @e '%Dn' (@i=%Di) in @d @i %i @s '..'\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* i_faddr should be zero */ + { PR_2_FADDR_ZERO, + N_("i_faddr @F %IF, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* i_file_acl should be zero */ + { PR_2_FILE_ACL_ZERO, + N_("i_file_acl @F %If, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* i_size_high should be zero */ + { PR_2_DIR_SIZE_HIGH_ZERO, + N_("i_size_high @F %Id, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* i_frag should be zero */ + { PR_2_FRAG_ZERO, + N_("i_frag @F %N, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* i_fsize should be zero */ + { PR_2_FSIZE_ZERO, + N_("i_fsize @F %N, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* inode has bad mode */ + { PR_2_BAD_MODE, + N_("@i %i (%Q) has @n mode (%Im).\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* directory corrupted */ + { PR_2_DIR_CORRUPTED, + N_("@d @i %i, %B, offset %N: @d corrupted\n"), + PROMPT_SALVAGE, 0, 0, 0, 0 }, + + /* filename too long */ + { PR_2_FILENAME_LONG, + N_("@d @i %i, %B, offset %N: filename too long\n"), + PROMPT_TRUNCATE, 0, 0, 0, 0 }, + + /* Directory inode has a missing block (hole) */ + { PR_2_DIRECTORY_HOLE, + N_("@d @i %i has an unallocated %B. "), + PROMPT_ALLOCATE, 0, 0, 0, 0 }, + + /* '.' is not NULL terminated */ + { PR_2_DOT_NULL_TERM, + /* xgettext:no-c-format */ + N_("'.' @d @e in @d @i %i is not NULL terminated\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* '..' is not NULL terminated */ + { PR_2_DOT_DOT_NULL_TERM, + /* xgettext:no-c-format */ + N_("'..' @d @e in @d @i %i is not NULL terminated\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Illegal character device inode */ + { PR_2_BAD_CHAR_DEV, + N_("@i %i (%Q) is an @I character @v.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Illegal block device inode */ + { PR_2_BAD_BLOCK_DEV, + N_("@i %i (%Q) is an @I @b @v.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Duplicate '.' entry */ + { PR_2_DUP_DOT, + N_("@E is duplicate '.' @e.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Duplicate '..' entry */ + { PR_2_DUP_DOT_DOT, + N_("@E is duplicate '..' @e.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Internal error: couldn't find dir_info */ + { PR_2_NO_DIRINFO, + /* xgettext:no-c-format */ + N_("Internal error: couldn't find dir_info for %i.\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Final rec_len is wrong */ + { PR_2_FINAL_RECLEN, + N_("@E has rec_len of %Dr, @s %N.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Error allocating icount structure */ + { PR_2_ALLOCATE_ICOUNT, + /* xgettext:no-c-format */ + N_("@A icount structure: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error iterating over directory blocks */ + { PR_2_DBLIST_ITERATE, + /* xgettext:no-c-format */ + N_("Error iterating over @d @bs: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error reading directory block */ + { PR_2_READ_DIRBLOCK, + N_("Error reading @d @b %b (@i %i): %m\n"), + PROMPT_CONTINUE, 0, 0, 0, 0 }, + + /* Error writing directory block */ + { PR_2_WRITE_DIRBLOCK, + N_("Error writing @d @b %b (@i %i): %m\n"), + PROMPT_CONTINUE, 0, 0, 0, 0 }, + + /* Error allocating new directory block */ + { PR_2_ALLOC_DIRBOCK, + /* xgettext:no-c-format */ + N_("@A new @d @b for @i %i (%s): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error deallocating inode */ + { PR_2_DEALLOC_INODE, + /* xgettext:no-c-format */ + N_("Error deallocating @i %i: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Directory entry for '.' is big. Split? */ + { PR_2_SPLIT_DOT, + /* xgettext:no-c-format */ + N_("@d @e for '.' in %p (%i) is big.\n"), + PROMPT_SPLIT, PR_NO_OK, 0, 0, 0 }, + + /* Illegal FIFO inode */ + { PR_2_BAD_FIFO, + N_("@i %i (%Q) is an @I FIFO.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Illegal socket inode */ + { PR_2_BAD_SOCKET, + N_("@i %i (%Q) is an @I socket.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Directory filetype not set */ + { PR_2_SET_FILETYPE, + N_("Setting filetype for @E to %N.\n"), + PROMPT_NONE, PR_PREEN_OK | PR_NO_OK | PR_NO_NOMSG, 0, 0, 0 }, + + /* Directory filetype incorrect */ + { PR_2_BAD_FILETYPE, + N_("@E has an incorrect filetype (was %Dt, @s %N).\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Directory filetype set on filesystem */ + { PR_2_CLEAR_FILETYPE, + N_("@E has filetype set.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* Directory filename is null */ + { PR_2_NULL_NAME, + N_("@E has a @z name.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Invalid symlink */ + { PR_2_INVALID_SYMLINK, + N_("Symlink %Q (@i #%i) is @n.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* i_file_acl (extended attribute block) is bad */ + { PR_2_FILE_ACL_BAD, + N_("@a @b @F @n (%If).\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Filesystem contains large files, but has no such flag in sb */ + { PR_2_FEATURE_LARGE_FILES, + N_("@f contains large files, but lacks LARGE_FILE flag in @S.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Node in HTREE directory not referenced */ + { PR_2_HTREE_NOTREF, + N_("@p @h %d: %B not referenced\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Node in HTREE directory referenced twice */ + { PR_2_HTREE_DUPREF, + N_("@p @h %d: %B referenced twice\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Node in HTREE directory has bad min hash */ + { PR_2_HTREE_MIN_HASH, + N_("@p @h %d: %B has bad min hash\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Node in HTREE directory has bad max hash */ + { PR_2_HTREE_MAX_HASH, + N_("@p @h %d: %B has bad max hash\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Clear invalid HTREE directory */ + { PR_2_HTREE_CLEAR, + N_("@n @h %d (%q). "), PROMPT_CLEAR_HTREE, 0, 0, 0, 0 }, + + /* Filesystem has large directories, but has no such flag in sb */ + { PR_2_FEATURE_LARGE_DIRS, + N_("@f has large directories, but lacks LARGE_DIR flag in @S.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Bad block in htree interior node */ + { PR_2_HTREE_BADBLK, + N_("@p @h %d (%q): bad @b number %b.\n"), + PROMPT_CLEAR_HTREE, 0, 0, 0, 0 }, + + /* Error adjusting EA refcount */ + { PR_2_ADJ_EA_REFCOUNT, + N_("Error adjusting refcount for @a @b %b (@i %i): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Problem in HTREE directory inode: root node is invalid */ + { PR_2_HTREE_BAD_ROOT, + /* xgettext:no-c-format */ + N_("@p @h %d: root node is @n\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Invalid HTREE limit */ + { PR_2_HTREE_BAD_LIMIT, + N_("@p @h %d: %B has @n limit (%N)\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Invalid HTREE count */ + { PR_2_HTREE_BAD_COUNT, + N_("@p @h %d: %B has @n count (%N)\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* HTREE interior node has out-of-order hashes in table */ + { PR_2_HTREE_HASH_ORDER, + N_("@p @h %d: %B has an unordered hash table\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* Node in HTREE directory has invalid depth */ + { PR_2_HTREE_BAD_DEPTH, + N_("@p @h %d: %B has @n depth (%N)\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Duplicate directory entry found */ + { PR_2_DUPLICATE_DIRENT, + N_("Duplicate @E found. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Non-unique filename found */ + { PR_2_NON_UNIQUE_FILE, /* xgettext: no-c-format */ + N_("@E has a non-unique filename.\nRename to %s"), + PROMPT_NULL, 0, 0, 0, 0 }, + + /* Duplicate directory entry found */ + { PR_2_REPORT_DUP_DIRENT, + N_("Duplicate @e '%Dn' found.\n\tMarking %p (%i) to be rebuilt.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* i_blocks_hi should be zero */ + { PR_2_BLOCKS_HI_ZERO, + N_("i_blocks_hi @F %N, @s zero.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Unexpected HTREE block */ + { PR_2_UNEXPECTED_HTREE_BLOCK, + N_("Unexpected @b in @h %d (%q).\n"), PROMPT_CLEAR_HTREE, 0, + 0, 0, 0 }, + + /* Inode found in group where _INODE_UNINIT is set */ + { PR_2_INOREF_BG_INO_UNINIT, + N_("@E references @i %Di in @g %g where _INODE_UNINIT is set.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Inode found in group unused inodes area */ + { PR_2_INOREF_IN_UNUSED, + N_("@E references @i %Di found in @g %g's unused inodes area.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* i_blocks_hi should be zero */ + { PR_2_I_FILE_ACL_HI_ZERO, + N_("i_file_acl_hi @F %N, @s zero.\n"), + PROMPT_CLEAR, PR_PREEN_OK, 0, 0, 0 }, + + /* htree root node fails checksum */ + { PR_2_HTREE_ROOT_CSUM_INVALID, + /* xgettext:no-c-format */ + N_("@p @h %d: root node fails checksum.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* htree internal node fails checksum */ + { PR_2_HTREE_NODE_CSUM_INVALID, + /* xgettext:no-c-format */ + N_("@p @h %d: internal node fails checksum.\n"), + PROMPT_CLEAR_HTREE, PR_PREEN_OK, 0, 0, 0 }, + + /* leaf node has no checksum */ + { PR_2_LEAF_NODE_MISSING_CSUM, + N_("@d @i %i, %B, offset %N: @d has no checksum.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* leaf node passes checks but fails checksum */ + { PR_2_LEAF_NODE_ONLY_CSUM_INVALID, + N_("@d @i %i, %B: @d passes checks but fails checksum.\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* inline directory inode size must be a multiple of 4 */ + { PR_2_BAD_INLINE_DIR_SIZE, + N_("Inline @d @i %i size (%N) must be a multiple of 4.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* fixing size of inline directory inode failed */ + { PR_2_FIX_INLINE_DIR_FAILED, + /* xgettext:no-c-format */ + N_("Fixing size of inline @d @i %i failed.\n"), + PROMPT_TRUNCATE, 0, 0, 0, 0 }, + + /* Encrypted directory entry is too short */ + { PR_2_BAD_ENCRYPTED_NAME, + N_("Encrypted @E is too short.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Encrypted directory contains unencrypted file */ + { PR_2_UNENCRYPTED_FILE, + N_("Encrypted @E references unencrypted @i %Di.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Encrypted directory contains file with different encryption policy */ + { PR_2_INCONSISTENT_ENCRYPTION_POLICY, + N_("Encrypted @E references @i %Di, which has a different encryption policy.\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Casefolded directory entry has illegal characters in its name */ + { PR_2_BAD_ENCODED_NAME, + N_("@E has illegal UTF-8 characters in its name.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Non-unique filename found, but can't rename */ + { PR_2_NON_UNIQUE_FILE_NO_RENAME, + N_("Duplicate filename @E found. "), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + + /* Pass 3 errors */ + + /* Pass 3: Checking directory connectivity */ + { PR_3_PASS_HEADER, + N_("Pass 3: Checking @d connectivity\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Root inode not allocated */ + { PR_3_NO_ROOT_INODE, + N_("@r not allocated. "), + PROMPT_ALLOCATE, 0, 0, 0, 0 }, + + /* No room in lost+found */ + { PR_3_EXPAND_LF_DIR, + N_("No room in @l @d. "), + PROMPT_EXPAND, 0, 0, 0, 0 }, + + /* Unconnected directory inode */ + { PR_3_UNCONNECTED_DIR, + /* xgettext:no-c-format */ + N_("Unconnected @d @i %i (was in %q)\n"), + PROMPT_CONNECT, 0, 0, 0, 0 }, + + /* /lost+found not found */ + { PR_3_NO_LF_DIR, + N_("/@l not found. "), + PROMPT_CREATE, PR_PREEN_OK, 0, 0, 0 }, + + /* .. entry is incorrect */ + { PR_3_BAD_DOT_DOT, + N_("'..' in %Q (%i) is %P (%j), @s %q (%d).\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Bad or non-existent /lost+found. Cannot reconnect */ + { PR_3_NO_LPF, + /* xgettext:no-c-format */ + N_("Bad or non-existent /@l. Cannot reconnect.\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Could not expand /lost+found */ + { PR_3_CANT_EXPAND_LPF, + /* xgettext:no-c-format */ + N_("Could not expand /@l: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Could not reconnect inode */ + { PR_3_CANT_RECONNECT, + /* xgettext:no-c-format */ + N_("Could not reconnect %i: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error while trying to find /lost+found */ + { PR_3_ERR_FIND_LPF, + /* xgettext:no-c-format */ + N_("Error while trying to find /@l: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error in ext2fs_new_block while creating /lost+found */ + { PR_3_ERR_LPF_NEW_BLOCK, + /* xgettext:no-c-format */ + N_("ext2fs_new_@b: %m while trying to create /@l @d\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error in ext2fs_new_inode while creating /lost+found */ + { PR_3_ERR_LPF_NEW_INODE, + /* xgettext:no-c-format */ + N_("ext2fs_new_@i: %m while trying to create /@l @d\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error in ext2fs_new_dir_block while creating /lost+found */ + { PR_3_ERR_LPF_NEW_DIR_BLOCK, + /* xgettext:no-c-format */ + N_("ext2fs_new_dir_@b: %m while creating new @d @b\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error while writing directory block for /lost+found */ + { PR_3_ERR_LPF_WRITE_BLOCK, + /* xgettext:no-c-format */ + N_("ext2fs_write_dir_@b: %m while writing the @d @b for /@l\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error while adjusting inode count */ + { PR_3_ADJUST_INODE, + /* xgettext:no-c-format */ + N_("Error while adjusting @i count on @i %i\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Couldn't fix parent directory -- error */ + { PR_3_FIX_PARENT_ERR, + /* xgettext:no-c-format */ + N_("Couldn't fix parent of @i %i: %m\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Couldn't fix parent directory -- couldn't find it */ + { PR_3_FIX_PARENT_NOFIND, + /* xgettext:no-c-format */ + N_("Couldn't fix parent of @i %i: Couldn't find parent @d @e\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error allocating inode bitmap */ + { PR_3_ALLOCATE_IBITMAP_ERROR, + N_("@A @i @B (%N): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error creating root directory */ + { PR_3_CREATE_ROOT_ERROR, + /* xgettext:no-c-format */ + N_("Error creating root @d (%s): %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error creating lost and found directory */ + { PR_3_CREATE_LPF_ERROR, + /* xgettext:no-c-format */ + N_("Error creating /@l @d (%s): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Root inode is not directory; aborting */ + { PR_3_ROOT_NOT_DIR_ABORT, + N_("@r is not a @d; aborting.\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Cannot proceed without a root inode. */ + { PR_3_NO_ROOT_INODE_ABORT, + N_("Cannot proceed without a @r.\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Internal error: couldn't find dir_info */ + { PR_3_NO_DIRINFO, + N_("Internal error: couldn't find dir_info for %i.\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Lost+found not a directory */ + { PR_3_LPF_NOTDIR, + /* xgettext:no-c-format */ + N_("/@l is not a @d (ino=%i)\n"), + PROMPT_UNLINK, 0, 0, 0, 0 }, + + /* Lost+found has inline data */ + { PR_3_LPF_INLINE_DATA, + N_("/@l has inline data\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Cannot allocate /lost+found. */ + { PR_3_LPF_NO_SPACE, + N_("Cannot allocate space for /@l.\nPlace lost files in root directory instead"), + PROMPT_NULL, 0, 0, 0, 0 }, + + /* Delete some files and re-run e2fsck. */ + { PR_3_NO_SPACE_TO_RECOVER, + N_("Insufficient space to recover lost files!\nMove data off the @f and re-run e2fsck.\n\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Lost+found is encrypted */ + { PR_3_LPF_ENCRYPTED, + N_("/@l is encrypted\n"), + PROMPT_CLEAR, 0, 0, 0, 0 }, + + /* Recursively looped directory inode */ + { PR_3_LOOPED_DIR, + /* xgettext:no-c-format */ + N_("Recursively looped @d @i %i (%p)\n"), + PROMPT_CONNECT, 0, 0, 0, 0 }, + + /* Pass 3A Directory Optimization */ + + /* Pass 3A: Optimizing directories */ + { PR_3A_PASS_HEADER, + N_("Pass 3A: Optimizing directories\n"), + PROMPT_NONE, PR_HEADER | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Error iterating over directories */ + { PR_3A_OPTIMIZE_ITER, + /* xgettext:no-c-format */ + N_("Failed to create dirs_to_hash iterator: %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Error rehash directory */ + { PR_3A_OPTIMIZE_DIR_ERR, + N_("Failed to optimize directory %q (%d): %m\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + /* Rehashing dir header */ + { PR_3A_OPTIMIZE_DIR_HEADER, + N_("Optimizing directories: "), + PROMPT_NONE, PR_MSG_ONLY, 0, 0, 0 }, + + /* Rehashing directory %d */ + { PR_3A_OPTIMIZE_DIR, + " %d", + PROMPT_NONE, PR_LATCH_OPTIMIZE_DIR | PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Rehashing dir end */ + { PR_3A_OPTIMIZE_DIR_END, + "\n", + PROMPT_NONE, PR_PREEN_NOHDR, 0, 0, 0 }, + + /* Pass 4 errors */ + + /* Pass 4: Checking reference counts */ + { PR_4_PASS_HEADER, + N_("Pass 4: Checking reference counts\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Unattached zero-length inode */ + { PR_4_ZERO_LEN_INODE, + /* xgettext:no-c-format */ + N_("@u @z @i %i. "), + PROMPT_CLEAR, PR_PREEN_OK|PR_NO_OK, 0, 0, 0 }, + + /* Unattached inode */ + { PR_4_UNATTACHED_INODE, + /* xgettext:no-c-format */ + N_("@u @i %i\n"), + PROMPT_CONNECT, 0, 0, 0, 0 }, + + /* Inode ref count wrong */ + { PR_4_BAD_REF_COUNT, + N_("@i %i ref count is %Il, @s %N. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + { PR_4_INCONSISTENT_COUNT, + N_("WARNING: PROGRAMMING BUG IN E2FSCK!\n" + "\tOR SOME BONEHEAD (YOU) IS CHECKING A MOUNTED (LIVE) FILESYSTEM.\n" + "@i_link_info[%i] is %N, @i.i_links_count is %Il. " + "They @s the same!\n"), + PROMPT_NONE, 0, 0, 0, 0 }, + + { PR_4_EA_INODE_REF_COUNT, + N_("@a @i %i ref count is %N, @s %n. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* directory exceeds max links, but no DIR_NLINK feature in superblock*/ + { PR_4_DIR_NLINK_FEATURE, + N_("@d exceeds max links, but no DIR_NLINK feature in @S.\n"), + PROMPT_FIX, 0, 0, 0, 0 }, + + /* Directory inode ref count set to overflow but could be exact value */ + { PR_4_DIR_OVERFLOW_REF_COUNT, + N_("@d @i %i ref count set to overflow but could be exact value %N. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Pass 5 errors */ + + /* Pass 5: Checking group summary information */ + { PR_5_PASS_HEADER, + N_("Pass 5: Checking @g summary information\n"), + PROMPT_NONE, PR_HEADER, 0, 0, 0 }, + + /* Padding at end of inode bitmap is not set. */ + { PR_5_INODE_BMAP_PADDING, + N_("Padding at end of @i @B is not set. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Padding at end of block bitmap is not set. */ + { PR_5_BLOCK_BMAP_PADDING, + N_("Padding at end of @b @B is not set. "), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Block bitmap differences header */ + { PR_5_BLOCK_BITMAP_HEADER, + N_("@b @B differences: "), + PROMPT_NONE, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Block not used, but marked in bitmap */ + { PR_5_BLOCK_UNUSED, + " -%b", + PROMPT_NONE, PR_LATCH_BBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Block used, but not marked used in bitmap */ + { PR_5_BLOCK_USED, + " +%b", + PROMPT_NONE, PR_LATCH_BBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Block bitmap differences end */ + { PR_5_BLOCK_BITMAP_END, + "\n", + PROMPT_FIX, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Inode bitmap differences header */ + { PR_5_INODE_BITMAP_HEADER, + N_("@i @B differences: "), + PROMPT_NONE, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Inode not used, but marked in bitmap */ + { PR_5_INODE_UNUSED, + " -%i", + PROMPT_NONE, PR_LATCH_IBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Inode used, but not marked used in bitmap */ + { PR_5_INODE_USED, + " +%i", + PROMPT_NONE, PR_LATCH_IBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Inode bitmap differences end */ + { PR_5_INODE_BITMAP_END, + "\n", + PROMPT_FIX, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Free inodes count for group wrong */ + { PR_5_FREE_INODE_COUNT_GROUP, + N_("Free @is count wrong for @g #%g (%i, counted=%j).\n"), + PROMPT_FIX, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Directories count for group wrong */ + { PR_5_FREE_DIR_COUNT_GROUP, + N_("Directories count wrong for @g #%g (%i, counted=%j).\n"), + PROMPT_FIX, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Free inodes count wrong */ + { PR_5_FREE_INODE_COUNT, + N_("Free @is count wrong (%i, counted=%j).\n"), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Free blocks count for group wrong */ + { PR_5_FREE_BLOCK_COUNT_GROUP, + N_("Free @bs count wrong for @g #%g (%b, counted=%c).\n"), + PROMPT_FIX, PR_PREEN_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Free blocks count wrong */ + { PR_5_FREE_BLOCK_COUNT, + N_("Free @bs count wrong (%b, counted=%c).\n"), + PROMPT_FIX, PR_PREEN_OK | PR_NO_OK | PR_PREEN_NOMSG, 0, 0, 0 }, + + /* Programming error: bitmap endpoints don't match */ + { PR_5_BMAP_ENDPOINTS, + N_("PROGRAMMING ERROR: @f (#%N) @B endpoints (%b, %c) don't " + "match calculated @B endpoints (%i, %j)\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Internal error: fudging end of bitmap */ + { PR_5_FUDGE_BITMAP_ERROR, + N_("Internal error: fudging end of bitmap (%N)\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error copying in replacement inode bitmap */ + { PR_5_COPY_IBITMAP_ERROR, + /* xgettext:no-c-format */ + N_("Error copying in replacement @i @B: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Error copying in replacement block bitmap */ + { PR_5_COPY_BBITMAP_ERROR, + /* xgettext:no-c-format */ + N_("Error copying in replacement @b @B: %m\n"), + PROMPT_NONE, PR_FATAL, 0, 0, 0 }, + + /* Block range not used, but marked in bitmap */ + { PR_5_BLOCK_RANGE_UNUSED, + " -(%b--%c)", + PROMPT_NONE, PR_LATCH_BBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Block range used, but not marked used in bitmap */ + { PR_5_BLOCK_RANGE_USED, + " +(%b--%c)", + PROMPT_NONE, PR_LATCH_BBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Inode range not used, but marked in bitmap */ + { PR_5_INODE_RANGE_UNUSED, + " -(%i--%j)", + PROMPT_NONE, PR_LATCH_IBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Inode range used, but not marked used in bitmap */ + { PR_5_INODE_RANGE_USED, + " +(%i--%j)", + PROMPT_NONE, PR_LATCH_IBITMAP | PR_PREEN_OK | PR_PREEN_NOMSG, + 0, 0, 0 }, + + /* Group N block(s) in use but group is marked BLOCK_UNINIT */ + { PR_5_BLOCK_UNINIT, + /* xgettext:no-c-format */ + N_("@g %g @b(s) in use but @g is marked BLOCK_UNINIT\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Group N inode(s) in use but group is marked INODE_UNINIT */ + { PR_5_INODE_UNINIT, + /* xgettext:no-c-format */ + N_("@g %g @i(s) in use but @g is marked INODE_UNINIT\n"), + PROMPT_FIX, PR_PREEN_OK, 0, 0, 0 }, + + /* Group N inode bitmap does not match checksum */ + { PR_5_INODE_BITMAP_CSUM_INVALID, + /* xgettext:no-c-format */ + N_("@g %g @i @B does not match checksum.\n"), + PROMPT_FIX, PR_LATCH_IBITMAP | PR_PREEN_OK, 0, 0, 0 }, + + /* Group N block bitmap does not match checksum */ + { PR_5_BLOCK_BITMAP_CSUM_INVALID, + /* xgettext:no-c-format */ + N_("@g %g @b @B does not match checksum.\n"), + PROMPT_FIX, PR_LATCH_BBITMAP | PR_PREEN_OK, 0, 0, 0 }, + + /* Post-Pass 5 errors */ + + /* Recreate journal if E2F_FLAG_JOURNAL_INODE flag is set */ + { PR_6_RECREATE_JOURNAL, + N_("Recreate @j"), + PROMPT_NULL, PR_PREEN_OK | PR_NO_OK, 0, 0, 0 }, + + /* Update quota information if it is inconsistent */ + { PR_6_UPDATE_QUOTAS, + N_("Update quota info for quota type %N"), + PROMPT_NULL, PR_PREEN_OK, 0, 0, 0 }, + + /* Error setting block group checksum info */ + { PR_6_SET_BG_CHECKSUM, + /* xgettext:no-c-format */ + N_("Error setting @b @g checksum info: %m\n"), + PROMPT_NULL, PR_FATAL, 0, 0, 0 }, + + /* Error writing file system info */ + { PR_6_FLUSH_FILESYSTEM, + /* xgettext:no-c-format */ + N_("Error writing file system info: %m\n"), + PROMPT_NULL, PR_FATAL, 0, 0, 0 }, + + /* Error flushing writes to storage device */ + { PR_6_IO_FLUSH, + /* xgettext:no-c-format */ + N_("Error flushing writes to storage device: %m\n"), + PROMPT_NULL, PR_FATAL, 0, 0, 0 }, + + /* Error writing quota information */ + { PR_6_WRITE_QUOTAS, + N_("Error writing quota info for quota type %N: %m\n"), + PROMPT_NULL, 0, 0, 0, 0 }, + + /* Orphan file without a journal */ + { PR_6_ORPHAN_FILE_WITHOUT_JOURNAL, + N_("@S has orphan file without @j.\n"), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* Orphan file truncation failed */ + { PR_6_ORPHAN_FILE_TRUNC_FAILED, + N_("Failed to truncate orphan file.\n"), + PROMPT_NONE, 0 }, + + /* Failed to initialize orphan file */ + { PR_6_ORPHAN_FILE_CORRUPTED, + N_("Failed to initialize orphan file.\n"), + PROMPT_RECREATE, PR_PREEN_OK }, + + /* Cannot fix corrupted orphan file with invalid bitmaps */ + { PR_6_ORPHAN_FILE_BITMAP_INVALID, + N_("Cannot fix corrupted orphan file with invalid bitmaps.\n"), + PROMPT_NONE, 0 }, + + /* Orphan file creation failed */ + { PR_6_ORPHAN_FILE_CREATE_FAILED, + N_("Failed to truncate orphan file (@i %i).\n"), + PROMPT_NONE, 0 }, + + /* Orphan file block contains data */ + { PR_6_ORPHAN_BLOCK_DIRTY, + N_("Orphan file (@i %i) @b %b is not clean.\n"), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* orphan_present set but orphan file is empty */ + { PR_6_ORPHAN_PRESENT_CLEAN_FILE, + N_("Feature orphan_present is set but orphan file is clean.\n"), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* orphan_present set but orphan_file is not */ + { PR_6_ORPHAN_PRESENT_NO_FILE, + N_("Feature orphan_present is set but feature orphan_file is not.\n"), + PROMPT_CLEAR, PR_PREEN_OK }, + + /* Orphan file size isn't multiple of blocks size */ + { PR_6_ORPHAN_FILE_WRONG_SIZE, + N_("Orphan file (@i %i) size is not multiple of block size.\n"), + PROMPT_NONE, 0 }, + + /* Orphan file contains holes */ + { PR_6_ORPHAN_FILE_HOLE, + N_("Orphan file (@i %i) contains hole at @b %b.\n"), + PROMPT_NONE, 0 }, + + { 0 } +}; + +/* + * This is the latch flags register. It allows several problems to be + * "latched" together. This means that the user has to answer but one + * question for the set of problems, and all of the associated + * problems will be either fixed or not fixed. + */ +static struct latch_descr pr_latch_info[] = { + { PR_LATCH_BLOCK, PR_1_INODE_BLOCK_LATCH, 0, 0 }, + { PR_LATCH_BBLOCK, PR_1_INODE_BBLOCK_LATCH, 0, 0 }, + { PR_LATCH_IBITMAP, PR_5_INODE_BITMAP_HEADER, PR_5_INODE_BITMAP_END, 0 }, + { PR_LATCH_BBITMAP, PR_5_BLOCK_BITMAP_HEADER, PR_5_BLOCK_BITMAP_END, 0 }, + { PR_LATCH_RELOC, PR_0_RELOCATE_HINT, 0, 0 }, + { PR_LATCH_DBLOCK, PR_1B_DUP_BLOCK_HEADER, PR_1B_DUP_BLOCK_END, 0 }, + { PR_LATCH_LOW_DTIME, PR_1_ORPHAN_LIST_REFUGEES, 0, 0 }, + { PR_LATCH_TOOBIG, PR_1_INODE_TOOBIG, 0, 0 }, + { PR_LATCH_OPTIMIZE_DIR, PR_3A_OPTIMIZE_DIR_HEADER, PR_3A_OPTIMIZE_DIR_END, 0 }, + { PR_LATCH_BG_CHECKSUM, PR_0_GDT_CSUM_LATCH, 0, 0 }, + { PR_LATCH_OPTIMIZE_EXT, PR_1E_OPTIMIZE_EXT_HEADER, PR_1E_OPTIMIZE_EXT_END, 0 }, + { -1, 0, 0, 0 }, +}; +#if __GNUC_PREREQ (4, 6) +#pragma GCC diagnostic pop +#endif + +static struct e2fsck_problem *find_problem(problem_t code) +{ + int i; + + for (i=0; problem_table[i].e2p_code; i++) { + if (problem_table[i].e2p_code == code) + return &problem_table[i]; + } + return 0; +} + +static struct latch_descr *find_latch(int code) +{ + int i; + + for (i=0; pr_latch_info[i].latch_code >= 0; i++) { + if (pr_latch_info[i].latch_code == code) + return &pr_latch_info[i]; + } + return 0; +} + +int end_problem_latch(e2fsck_t ctx, int mask) +{ + struct latch_descr *ldesc; + struct problem_context pctx; + int answer = -1; + + ldesc = find_latch(mask); + if (!ldesc) + return answer; + if (ldesc->end_message && (ldesc->flags & PRL_LATCHED)) { + clear_problem_context(&pctx); + answer = fix_problem(ctx, ldesc->end_message, &pctx); + } + ldesc->flags &= ~(PRL_VARIABLE); + return answer; +} + +int set_latch_flags(int mask, int setflags, int clearflags) +{ + struct latch_descr *ldesc; + + ldesc = find_latch(mask); + if (!ldesc) + return -1; + ldesc->flags |= setflags; + ldesc->flags &= ~clearflags; + return 0; +} + +int get_latch_flags(int mask, int *value) +{ + struct latch_descr *ldesc; + + ldesc = find_latch(mask); + if (!ldesc) + return -1; + *value = ldesc->flags; + return 0; +} + +void clear_problem_context(struct problem_context *ctx) +{ + memset(ctx, 0, sizeof(struct problem_context)); + ctx->blkcount = -1; + ctx->group = -1; +} + +static void reconfigure_bool(e2fsck_t ctx, struct e2fsck_problem *ptr, + const char *key, int mask, const char *name) +{ + int val; + + val = (ptr->flags & mask); + profile_get_boolean(ctx->profile, "problems", key, name, val, &val); + if (val) + ptr->flags |= mask; + else + ptr->flags &= ~mask; +} + +static void print_problem(FILE *f, problem_t code, int answer, int fixed, + struct e2fsck_problem *ptr, + struct problem_context *pctx) +{ + if (ptr->flags & PR_HEADER) { + fprintf(f, "<header code=\"0x%06x\"/>\n", code); + return; + } + fprintf(f, "<problem code=\"0x%06x\" answer=\"%d\"", code, answer); + if (pctx->errcode) + fprintf(f, " errcode=\"%lu\"", pctx->errcode); + if (fixed) + fputs(" fixed=\"1\"", f); + if (pctx->ino) + fprintf(f, " ino=\"%u\"", pctx->ino); + if (pctx->ino2) + fprintf(f, " ino2=\"%u\"", pctx->ino2); + if (pctx->dir) + fprintf(f, " dir=\"%u\"", pctx->dir); + if (pctx->blk) + fprintf(f, " blk=\"%llu\"", (unsigned long long) pctx->blk); + if (pctx->blk2) + fprintf(f, " blk2=\"%llu\"", (unsigned long long) pctx->blk2); + if (pctx->blkcount != (e2_blkcnt_t) -1) + fprintf(f, " blkcount=\"%lld\"", (unsigned long long) pctx->blkcount); + if (pctx->group != (dgrp_t) -1) + fprintf(f, " group=\"%u\"", pctx->group); + if (pctx->csum1) + fprintf(f, " csum1=\"%u\"", pctx->csum1); + if (pctx->csum2) + fprintf(f, " csum2=\"%u\"", pctx->csum2); + if (pctx->num) + fprintf(f, " num=\"%llu\"", (unsigned long long) pctx->num); + if (pctx->num2) + fprintf(f, " num2=\"%llu\"", (unsigned long long) pctx->num2); + if (pctx->str) + fprintf(f, " str=\"%s\"", pctx->str); + fputs("/>\n", f); +} + +int fix_problem(e2fsck_t ctx, problem_t code, struct problem_context *pctx) +{ + ext2_filsys fs = ctx->fs; + struct e2fsck_problem *ptr; + struct latch_descr *ldesc = 0; + const char *message; + int def_yn, answer, ans; + int print_answer = 0; + int suppress = 0; + int fixed = 0; + + ptr = find_problem(code); + if (!ptr) { + printf(_("Unhandled error code (0x%x)!\n"), code); + return 0; + } + if (!(ptr->flags & PR_CONFIG)) { + char key[9], *new_desc = NULL; + + sprintf(key, "0x%06x", code); + + profile_get_string(ctx->profile, "problems", key, + "description", 0, &new_desc); + if (new_desc) + ptr->e2p_description = new_desc; + + reconfigure_bool(ctx, ptr, key, PR_PREEN_OK, "preen_ok"); + reconfigure_bool(ctx, ptr, key, PR_NO_OK, "no_ok"); + reconfigure_bool(ctx, ptr, key, PR_NO_DEFAULT, "no_default"); + reconfigure_bool(ctx, ptr, key, PR_MSG_ONLY, "print_message_only"); + reconfigure_bool(ctx, ptr, key, PR_PREEN_NOMSG, "preen_nomessage"); + reconfigure_bool(ctx, ptr, key, PR_NOCOLLATE, "no_collate"); + reconfigure_bool(ctx, ptr, key, PR_NO_NOMSG, "no_nomsg"); + reconfigure_bool(ctx, ptr, key, PR_PREEN_NOHDR, "preen_noheader"); + reconfigure_bool(ctx, ptr, key, PR_FORCE_NO, "force_no"); + reconfigure_bool(ctx, ptr, key, PR_NOT_A_FIX, "not_a_fix"); + profile_get_integer(ctx->profile, "options", + "max_count_problems", 0, 0, + &ptr->max_count); + profile_get_integer(ctx->profile, "problems", key, "max_count", + ptr->max_count, &ptr->max_count); + + ptr->flags |= PR_CONFIG; + } + def_yn = 1; + ptr->count++; + if ((ptr->flags & PR_NO_DEFAULT) || + ((ptr->flags & PR_PREEN_NO) && (ctx->options & E2F_OPT_PREEN)) || + (ctx->options & E2F_OPT_NO)) + def_yn= 0; + + /* + * Do special latch processing. This is where we ask the + * latch question, if it exists + */ + if (ptr->flags & PR_LATCH_MASK && + (ldesc = find_latch(ptr->flags & PR_LATCH_MASK)) != NULL) { + if (ldesc->question && !(ldesc->flags & PRL_LATCHED)) { + ans = fix_problem(ctx, ldesc->question, pctx); + if (ans == 1) + ldesc->flags |= PRL_YES; + if (ans == 0) + ldesc->flags |= PRL_NO; + ldesc->flags |= PRL_LATCHED; + } + if (ldesc->flags & PRL_SUPPRESS) + suppress++; + } + if ((ptr->flags & PR_PREEN_NOMSG) && + (ctx->options & E2F_OPT_PREEN)) + suppress++; + if ((ptr->flags & PR_NO_NOMSG) && + ((ctx->options & E2F_OPT_NO) || (ptr->flags & PR_FORCE_NO))) + suppress++; + if (ptr->max_count && (ptr->count > ptr->max_count)) { + if (ctx->options & (E2F_OPT_NO | E2F_OPT_YES)) + suppress++; + if ((ctx->options & E2F_OPT_PREEN) && + (ptr->flags & PR_PREEN_OK)) + suppress++; + if (ldesc && (ldesc->flags & (PRL_YES | PRL_NO))) + suppress++; + if (ptr->count == ptr->max_count + 1) { + if (ctx->problem_logf) + fprintf(ctx->problem_logf, + "<suppressed code=\"0x%06x\"/>\n", + code); + printf("...problem 0x%06x suppressed\n", + ptr->e2p_code); + fflush(stdout); + } + } + message = ptr->e2p_description; + if (*message) + message = _(message); + if (!suppress) { + if ((ctx->options & E2F_OPT_PREEN) && + !(ptr->flags & PR_PREEN_NOHDR)) { + printf("%s: ", ctx->device_name ? + ctx->device_name : ctx->filesystem_name); + } + if (*message) + print_e2fsck_message(stdout, ctx, message, pctx, 1, 0); + } + if (ctx->logf && message) + print_e2fsck_message(ctx->logf, ctx, message, pctx, 1, 0); + if (!(ptr->flags & PR_PREEN_OK) && (ptr->prompt != PROMPT_NONE)) + preenhalt(ctx); + + if (ptr->flags & PR_FATAL) + fatal_error(ctx, 0); + + if (ptr->prompt == PROMPT_NONE) { + if (ptr->flags & PR_NOCOLLATE) + answer = -1; + else + answer = def_yn; + } else { + if (ptr->flags & PR_FORCE_NO) { + answer = 0; + print_answer = 1; + } else if (ctx->options & E2F_OPT_PREEN) { + answer = def_yn; + if (!(ptr->flags & PR_PREEN_NOMSG)) + print_answer = 1; + } else if (ldesc && (ldesc->flags & (PRL_YES | PRL_NO))) { + print_answer = 1; + if (ldesc->flags & PRL_YES) + answer = 1; + else + answer = 0; + } else + answer = ask(ctx, (ptr->prompt == PROMPT_NULL) ? "" : + _(prompt[(int) ptr->prompt]), def_yn); + if (!answer && !(ptr->flags & PR_NO_OK)) + ext2fs_unmark_valid(fs); + + if (print_answer) { + if (!suppress) + printf("%s.\n", answer ? + _(preen_msg[(int) ptr->prompt]) : + _("IGNORED")); + if (ctx->logf) + fprintf(ctx->logf, "%s.\n", answer ? + _(preen_msg[(int) ptr->prompt]) : + _("IGNORED")); + } + } + + if ((ptr->prompt == PROMPT_ABORT) && answer) + fatal_error(ctx, 0); + + if (ptr->flags & PR_AFTER_CODE) + answer = fix_problem(ctx, ptr->second_code, pctx); + + if (answer && (ptr->prompt != PROMPT_NONE) && + !(ptr->flags & PR_NOT_A_FIX)) { + fixed = 1; + ctx->flags |= E2F_FLAG_PROBLEMS_FIXED; + } + + if (ctx->problem_logf) + print_problem(ctx->problem_logf, code, answer, fixed, + ptr, pctx); + + return answer; +} + +#ifdef UNITTEST + +#include <stdlib.h> +#include <stdio.h> + +errcode_t +profile_get_boolean(profile_t profile, const char *name, const char *subname, + const char *subsubname, int def_val, int *ret_boolean) +{ + return 0; +} + +errcode_t +profile_get_integer(profile_t profile, const char *name, const char *subname, + const char *subsubname, int def_val, int *ret_int) +{ + return 0; +} + +void print_e2fsck_message(FILE *f, e2fsck_t ctx, const char *msg, + struct problem_context *pctx, int first, + int recurse) +{ + return; +} + +void fatal_error(e2fsck_t ctx, const char *msg) +{ + return; +} + +void preenhalt(e2fsck_t ctx) +{ + return; +} + +errcode_t +profile_get_string(profile_t profile, const char *name, const char *subname, + const char *subsubname, const char *def_val, + char **ret_string) +{ + return 0; +} + +int ask (e2fsck_t ctx, const char * string, int def) +{ + return 0; +} + +int verify_problem_table(e2fsck_t ctx) +{ + struct e2fsck_problem *curr, *prev = NULL; + int rc = 0; + + for (prev = NULL, curr = problem_table; curr->e2p_code; prev = curr++) { + if (prev == NULL) + continue; + + if (curr->e2p_code > prev->e2p_code) + continue; + + if (curr->e2p_code == prev->e2p_code) + fprintf(stderr, "*** Duplicate in problem table:\n"); + else + fprintf(stderr, "*** Unordered problem table:\n"); + + fprintf(stderr, "curr code = 0x%08x: %s\n", + curr->e2p_code, curr->e2p_description); + fprintf(stderr, "*** prev code = 0x%08x: %s\n", + prev->e2p_code, prev->e2p_description); + + fprintf(stderr, "*** This is a %sprogramming error in e2fsck\n", + (curr->e2p_code == prev->e2p_code) ? "fatal " : ""); + + rc = 1; + } + + return rc; +} + +int main(int argc, char *argv[]) +{ + e2fsck_t ctx; + int rc; + + memset(&ctx, 0, sizeof(ctx)); /* just to quiet compiler */ + rc = verify_problem_table(ctx); + if (rc == 0) + printf("e2fsck problem table verified\n"); + + return rc; +} +#endif /* UNITTEST */ diff --git a/e2fsck/problem.h b/e2fsck/problem.h new file mode 100644 index 0000000..b47b0c6 --- /dev/null +++ b/e2fsck/problem.h @@ -0,0 +1,1359 @@ +/* + * problem.h --- e2fsck problem error codes + * + * Copyright 1996 by Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +typedef __u32 problem_t; + +struct problem_context { + errcode_t errcode; + ext2_ino_t ino, ino2, dir; + struct ext2_inode *inode; + struct ext2_dir_entry *dirent; + blk64_t blk, blk2; + e2_blkcnt_t blkcount; + dgrp_t group; + __u32 csum1, csum2; + __u64 num, num2; + const char *str; +}; + +/* + * We define a set of "latch groups"; these are problems which are + * handled as a set. The user answers once for a particular latch + * group. + */ +#define PR_LATCH_MASK 0x0ff0 /* Latch mask */ +#define PR_LATCH_BLOCK 0x0010 /* Latch for illegal blocks (pass 1) */ +#define PR_LATCH_BBLOCK 0x0020 /* Latch for bad block inode blocks (pass 1) */ +#define PR_LATCH_IBITMAP 0x0030 /* Latch for pass 5 inode bitmap proc. */ +#define PR_LATCH_BBITMAP 0x0040 /* Latch for pass 5 inode bitmap proc. */ +#define PR_LATCH_RELOC 0x0050 /* Latch for superblock relocate hint */ +#define PR_LATCH_DBLOCK 0x0060 /* Latch for pass 1b dup block headers */ +#define PR_LATCH_LOW_DTIME 0x0070 /* Latch for pass1 orphaned list refugees */ +#define PR_LATCH_TOOBIG 0x0080 /* Latch for file to big errors */ +#define PR_LATCH_OPTIMIZE_DIR 0x0090 /* Latch for optimize directories */ +#define PR_LATCH_BG_CHECKSUM 0x00A0 /* Latch for block group checksums */ +#define PR_LATCH_OPTIMIZE_EXT 0x00B0 /* Latch for rebuild extents */ + +#define PR_LATCH(x) ((((x) & PR_LATCH_MASK) >> 4) - 1) + +/* + * Latch group descriptor flags + */ +#define PRL_YES 0x0001 /* Answer yes */ +#define PRL_NO 0x0002 /* Answer no */ +#define PRL_LATCHED 0x0004 /* The latch group is latched */ +#define PRL_SUPPRESS 0x0008 /* Suppress all latch group questions */ + +#define PRL_VARIABLE 0x000f /* All the flags that need to be reset */ + +/* + * Pre-Pass 1 errors + */ + +/* Block bitmap for group gggg is not in group */ +#define PR_0_BB_NOT_GROUP 0x000001 + +/* Inode bitmap for group gggg is not in group */ +#define PR_0_IB_NOT_GROUP 0x000002 + +/* Inode table for group gggg is not in group. (block nnnn) */ +#define PR_0_ITABLE_NOT_GROUP 0x000003 + +/* Superblock corrupt */ +#define PR_0_SB_CORRUPT 0x000004 + +/* Filesystem size is wrong */ +#define PR_0_FS_SIZE_WRONG 0x000005 + +/* Fragments not supported */ +#define PR_0_NO_FRAGMENTS 0x000006 + +/* Superblock blocks_per_group = bbbb, should have been cccc */ +#define PR_0_BLOCKS_PER_GROUP 0x000007 + +/* Superblock first_data_block = bbbb, should have been cccc */ +#define PR_0_FIRST_DATA_BLOCK 0x000008 + +/* Filesystem did not have a UUID; generating one */ +#define PR_0_ADD_UUID 0x000009 + +/* Relocate hint */ +#define PR_0_RELOCATE_HINT 0x00000A + +/* Miscellaneous superblock corruption */ +#define PR_0_MISC_CORRUPT_SUPER 0x00000B + +/* Error determining physical device size of filesystem */ +#define PR_0_GETSIZE_ERROR 0x00000C + +/* Inode count in the superblock incorrect */ +#define PR_0_INODE_COUNT_WRONG 0x00000D + +/* The Hurd does not support the filetype feature */ +#define PR_0_HURD_CLEAR_FILETYPE 0x00000E + +/* Superblock has an invalid journal (inode inum) */ +#define PR_0_JOURNAL_BAD_INODE 0x00000F + +/* External journal has multiple filesystem users (unsupported) */ +#define PR_0_JOURNAL_UNSUPP_MULTIFS 0x000010 + +/* Can't find external journal */ +#define PR_0_CANT_FIND_JOURNAL 0x000011 + +/* External journal has bad superblock */ +#define PR_0_EXT_JOURNAL_BAD_SUPER 0x000012 + +/* Superblock has a bad journal UUID */ +#define PR_0_JOURNAL_BAD_UUID 0x000013 + +/* Filesystem journal superblock is an unknown type */ +#define PR_0_JOURNAL_UNSUPP_SUPER 0x000014 + +/* Journal superblock is corrupt */ +#define PR_0_JOURNAL_BAD_SUPER 0x000015 + +/* Superblock has_journal flag is clear but has a journal */ +#define PR_0_JOURNAL_HAS_JOURNAL 0x000016 + +/* Superblock needs_recovery flag is set but no journal is present */ +#define PR_0_JOURNAL_RECOVER_SET 0x000017 + +/* Journal has data, but recovery flag is clear */ +#define PR_0_JOURNAL_RECOVERY_CLEAR 0x000018 + +/* Ask if we should clear the journal */ +#define PR_0_JOURNAL_RESET_JOURNAL 0x000019 + +/* Filesystem revision is 0, but feature flags are set */ +#define PR_0_FS_REV_LEVEL 0x00001A + +/* Clearing orphan inode */ +#define PR_0_ORPHAN_CLEAR_INODE 0x000020 + +/* Illegal block found in orphaned inode */ +#define PR_0_ORPHAN_ILLEGAL_BLOCK_NUM 0x000021 + +/* Already cleared block found in orphaned inode */ +#define PR_0_ORPHAN_ALREADY_CLEARED_BLOCK 0x000022 + +/* Illegal orphan inode in superblock */ +#define PR_0_ORPHAN_ILLEGAL_HEAD_INODE 0x000023 + +/* Illegal inode in orphaned inode list */ +#define PR_0_ORPHAN_ILLEGAL_INODE 0x000024 + +/* Journal has unsupported read-only feature - abort */ +#define PR_0_JOURNAL_UNSUPP_ROCOMPAT 0x000025 + +/* Journal has unsupported incompatible feature - abort */ +#define PR_0_JOURNAL_UNSUPP_INCOMPAT 0x000026 + +/* Journal version not supported by this e2fsck */ +#define PR_0_JOURNAL_UNSUPP_VERSION 0x000027 + +/* Moving journal from /file to hidden inode */ +#define PR_0_MOVE_JOURNAL 0x000028 + +/* Error moving journal to hidden file */ +#define PR_0_ERR_MOVE_JOURNAL 0x000029 + +/* Found invalid V2 journal superblock fields */ +#define PR_0_CLEAR_V2_JOURNAL 0x00002A + +/* Run journal anyway */ +#define PR_0_JOURNAL_RUN 0x00002B + +/* Run journal anyway by default */ +#define PR_0_JOURNAL_RUN_DEFAULT 0x00002C + +/* Backing up journal inode block information */ +#define PR_0_BACKUP_JNL 0x00002D + +/* Filesystem does not have resize_inode enabled, but + * s_reserved_gdt_blocks is nnnn; should be zero */ +#define PR_0_NONZERO_RESERVED_GDT_BLOCKS 0x00002E + +/* Resize_inode not enabled, but the resize inode is non-zero */ +#define PR_0_CLEAR_RESIZE_INODE 0x00002F + +/* Resize inode not valid */ +#define PR_0_RESIZE_INODE_INVALID 0x000030 + +/* Superblock last mount time is in the future */ +#define PR_0_FUTURE_SB_LAST_MOUNT 0x000031 + +/* Superblock last write time is in the future */ +#define PR_0_FUTURE_SB_LAST_WRITE 0x000032 + +/* Superblock hint for external superblock should be xxxx */ +#define PR_0_EXTERNAL_JOURNAL_HINT 0x000033 + +/* Adding dirhash hint to filesystem */ +#define PR_0_DIRHASH_HINT 0x000034 + +/* group descriptor N checksum is invalid, should be yyyy. */ +#define PR_0_GDT_CSUM 0x000035 + +/* Group descriptor N marked uninitialized without feature set. */ +#define PR_0_GDT_UNINIT 0x000036 + +/* Block bitmap is not initialised and Inode bitmap is -- NO LONGER USED */ +/* #define PR_0_BB_UNINIT_IB_INIT 0x000037 */ + +/* Group descriptor N has invalid unused inodes count. */ +#define PR_0_GDT_ITABLE_UNUSED 0x000038 + +/* Last group block bitmap is uninitialized. */ +#define PR_0_BB_UNINIT_LAST 0x000039 + +/* Journal transaction was corrupt, replay was aborted */ +#define PR_0_JNL_TXN_CORRUPT 0x00003A + +/* The test_fs filesystem flag is set and ext4 is available */ +#define PR_0_CLEAR_TESTFS_FLAG 0x00003B + +/* Last mount time is in the future (fudged) */ +#define PR_0_FUTURE_SB_LAST_MOUNT_FUDGED 0x00003C + +/* Last write time is in the future (fudged) */ +#define PR_0_FUTURE_SB_LAST_WRITE_FUDGED 0x00003D + +/* One or more block group descriptor checksums are invalid (latch) */ +#define PR_0_GDT_CSUM_LATCH 0x00003E + +/* Setting free inodes count to right (was wrong) */ +#define PR_0_FREE_INODE_COUNT 0x00003F + +/* Setting free blocks count to right (was wrong) */ +#define PR_0_FREE_BLOCK_COUNT 0x000040 + +/* Making quota inode hidden */ +#define PR_0_HIDE_QUOTA 0x000041 + +/* Superblock has invalid MMP block. */ +#define PR_0_MMP_INVALID_BLK 0x000042 + +/* Superblock has invalid MMP magic. */ +#define PR_0_MMP_INVALID_MAGIC 0x000043 + +/* Opening file system failed */ +#define PR_0_OPEN_FAILED 0x000044 + +/* Checking group descriptor failed */ +#define PR_0_CHECK_DESC_FAILED 0x000045 + +/* Superblock metadata_csum supersedes uninit_bg; both feature + * bits cannot be set simultaneously. */ +#define PR_0_META_AND_GDT_CSUM_SET 0x000046 + +/* Superblock MMP block checksum does not match MMP block. */ +#define PR_0_MMP_CSUM_INVALID 0x000047 + +/* Superblock 64bit filesystem needs extents to access the whole disk */ +#define PR_0_64BIT_WITHOUT_EXTENTS 0x000048 + +/* The first_meta_bg is too big */ +#define PR_0_FIRST_META_BG_TOO_BIG 0x000049 + +/* External journal superblock checksum does not match superblock */ +#define PR_0_EXT_JOURNAL_SUPER_CSUM_INVALID 0x00004A + +/* metadata_csum_seed means nothing without metadata_csum */ +#define PR_0_CSUM_SEED_WITHOUT_META_CSUM 0x00004B + +/* Error initializing quota context */ +#define PR_0_QUOTA_INIT_CTX 0x00004C + +/* Bad required extra isize in superblock */ +#define PR_0_BAD_MIN_EXTRA_ISIZE 0x00004D + +/* Bad desired extra isize in superblock */ +#define PR_0_BAD_WANT_EXTRA_ISIZE 0x00004E + +/* Invalid quota inode number */ +#define PR_0_INVALID_QUOTA_INO 0x00004F + +/* Inode count in the superblock incorrect */ +#define PR_0_INODE_COUNT_BIG 0x000050 + +/* Meta_bg and resize_inode are not compatible, remove resize_inode*/ +#define PR_0_DISABLE_RESIZE_INODE 0x000051 + +/* Orphan file contains holes */ +#define PR_0_ORPHAN_FILE_HOLE 0x000052 + +/* Orphan file block has wrong magic */ +#define PR_0_ORPHAN_FILE_BAD_MAGIC 0x000053 + +/* Orphan file block has wrong checksum */ +#define PR_0_ORPHAN_FILE_BAD_CHECKSUM 0x000054 + +/* Orphan file size isn't multiple of blocks size */ +#define PR_0_ORPHAN_FILE_WRONG_SIZE 0x000055 + +/* + * Pass 1 errors + */ + +/* Pass 1: Checking inodes, blocks, and sizes */ +#define PR_1_PASS_HEADER 0x010000 + +/* Root inode is not a directory */ +#define PR_1_ROOT_NO_DIR 0x010001 + +/* Root inode has dtime set */ +#define PR_1_ROOT_DTIME 0x010002 + +/* Reserved inode has bad mode */ +#define PR_1_RESERVED_BAD_MODE 0x010003 + +/* Deleted inode inum has zero dtime */ +#define PR_1_ZERO_DTIME 0x010004 + +/* Inode inum is in use, but has dtime set */ +#define PR_1_SET_DTIME 0x010005 + +/* Inode inum is a zero-length directory */ +#define PR_1_ZERO_LENGTH_DIR 0x010006 + +/* Group block bitmap at block conflicts with some other fs block */ +#define PR_1_BB_CONFLICT 0x010007 + +/* Group inode bitmap at block conflicts with some other fs block */ +#define PR_1_IB_CONFLICT 0x010008 + +/* Group inode table at block conflicts with some other fs block */ +#define PR_1_ITABLE_CONFLICT 0x010009 + +/* Group block bitmap (block) is bad */ +#define PR_1_BB_BAD_BLOCK 0x01000A + +/* Group inode bitmap (block) is bad */ +#define PR_1_IB_BAD_BLOCK 0x01000B + +/* Inode i_size is small, should be larger */ +#define PR_1_BAD_I_SIZE 0x01000C + +/* Inode i_blocks is small, should be larger */ +#define PR_1_BAD_I_BLOCKS 0x01000D + +/* Illegal block number in inode */ +#define PR_1_ILLEGAL_BLOCK_NUM 0x01000E + +/* Block number overlaps filesystem metadata in inode */ +#define PR_1_BLOCK_OVERLAPS_METADATA 0x01000F + +/* Inode has illegal blocks (latch question) */ +#define PR_1_INODE_BLOCK_LATCH 0x010010 + +/* Too many illegal blocks in inode */ +#define PR_1_TOO_MANY_BAD_BLOCKS 0x010011 + +/* Illegal block number in bad block inode */ +#define PR_1_BB_ILLEGAL_BLOCK_NUM 0x010012 + +/* Bad block inode has illegal blocks (latch question) */ +#define PR_1_INODE_BBLOCK_LATCH 0x010013 + +/* Duplicate or bad blocks in use! */ +#define PR_1_DUP_BLOCKS_PREENSTOP 0x010014 + +/* Bad block number used as bad block inode indirect block */ +#define PR_1_BBINODE_BAD_METABLOCK 0x010015 + +/* Inconsistency can't be fixed prompt */ +#define PR_1_BBINODE_BAD_METABLOCK_PROMPT 0x010016 + +/* Bad primary block */ +#define PR_1_BAD_PRIMARY_BLOCK 0x010017 + +/* Bad primary block prompt */ +#define PR_1_BAD_PRIMARY_BLOCK_PROMPT 0x010018 + +/* The primary superblock block is on the bad block list */ +#define PR_1_BAD_PRIMARY_SUPERBLOCK 0x010019 + +/* Bad primary block group descriptors */ +#define PR_1_BAD_PRIMARY_GROUP_DESCRIPTOR 0x01001A + +/* Warning: Group number's superblock (block) is bad */ +#define PR_1_BAD_SUPERBLOCK 0x01001B + +/* Warning: Group number's copy of the group descriptors has a bad block */ +#define PR_1_BAD_GROUP_DESCRIPTORS 0x01001C + +/* Block number claimed for no reason in process_bad_blocks */ +#define PR_1_PROGERR_CLAIMED_BLOCK 0x01001D + +/* Allocating number contiguous block(s) in block group number */ +#define PR_1_RELOC_BLOCK_ALLOCATE 0x01001E + +/* Allocating block buffer for relocating process */ +#define PR_1_RELOC_MEMORY_ALLOCATE 0x01001F + +/* Relocating group number's information from X to Y */ +#define PR_1_RELOC_FROM_TO 0x010020 + +/* Relocating group number's information to X */ +#define PR_1_RELOC_TO 0x010021 + +/* Warning: could not read block number of relocation process */ +#define PR_1_RELOC_READ_ERR 0x010022 + +/* Warning: could not write block number of relocation process */ +#define PR_1_RELOC_WRITE_ERR 0x010023 + +/* Error allocating inode bitmap */ +#define PR_1_ALLOCATE_IBITMAP_ERROR 0x010024 + +/* Error allocating block bitmap */ +#define PR_1_ALLOCATE_BBITMAP_ERROR 0x010025 + +/* Error allocating icount link information */ +#define PR_1_ALLOCATE_ICOUNT 0x010026 + +/* Error allocating directory block array */ +#define PR_1_ALLOCATE_DBCOUNT 0x010027 + +/* Error while scanning inodes */ +#define PR_1_ISCAN_ERROR 0x010028 + +/* Error while iterating over blocks in inode */ +#define PR_1_BLOCK_ITERATE 0x010029 + +/* Error storing inode count information */ +#define PR_1_ICOUNT_STORE 0x01002A + +/* Error storing directory block information */ +#define PR_1_ADD_DBLOCK 0x01002B + +/* Error reading inode (for clearing) */ +#define PR_1_READ_INODE 0x01002C + +/* Suppress messages prompt */ +#define PR_1_SUPPRESS_MESSAGES 0x01002D + +/* Imagic number has imagic flag set when fs doesn't support it */ +#define PR_1_SET_IMAGIC 0x01002F + +/* Immutable flag set on a device or socket inode */ +#define PR_1_SET_IMMUTABLE 0x010030 + +/* Compression flag set on a non-compressed filesystem -- no longer used*/ +/* #define PR_1_COMPR_SET 0x010031 */ + +/* Non-zero size on on device, fifo or socket inode */ +#define PR_1_SET_NONZSIZE 0x010032 + +/* Filesystem has feature flag(s) set, but is a revision 0 filesystem */ +#define PR_1_FS_REV_LEVEL 0x010033 + +/* Journal inode is not in use, but contains data */ +#define PR_1_JOURNAL_INODE_NOT_CLEAR 0x010034 + +/* Journal is not a regular file */ +#define PR_1_JOURNAL_BAD_MODE 0x010035 + +/* Inode that was part of the orphan list */ +#define PR_1_LOW_DTIME 0x010036 + +/* Inodes that were part of a corrupted orphan linked list found + * (latch question) */ +#define PR_1_ORPHAN_LIST_REFUGEES 0x010037 + +/* Error allocating refcount structure */ +#define PR_1_ALLOCATE_REFCOUNT 0x010038 + +/* Error reading extended attribute block */ +#define PR_1_READ_EA_BLOCK 0x010039 + +/* Inode number has a bad extended attribute block */ +#define PR_1_BAD_EA_BLOCK 0x01003A + +/* Error reading Extended Attribute block while fixing refcount -- abort */ +#define PR_1_EXTATTR_READ_ABORT 0x01003B + +/* Extended attribute number has reference count incorrect, should be */ +#define PR_1_EXTATTR_REFCOUNT 0x01003C + +/* Error writing Extended Attribute block while fixing refcount */ +#define PR_1_EXTATTR_WRITE_ABORT 0x01003D + +/* Extended attribute block has h_blocks > 1 */ +#define PR_1_EA_MULTI_BLOCK 0x01003E + +/* Allocating extended attribute region allocation structure */ +#define PR_1_EA_ALLOC_REGION_ABORT 0x01003F + +/* Extended Attribute block number is corrupt (allocation collision) */ +#define PR_1_EA_ALLOC_COLLISION 0x010040 + +/* Extended attribute block number is corrupt (invalid name) */ +#define PR_1_EA_BAD_NAME 0x010041 + +/* Extended attribute block number is corrupt (invalid value) */ +#define PR_1_EA_BAD_VALUE 0x010042 + +/* Inode number is too big (latch question) */ +#define PR_1_INODE_TOOBIG 0x010043 + +/* Problem causes directory to be too big */ +#define PR_1_TOOBIG_DIR 0x010044 + +/* Problem causes file to be too big */ +#define PR_1_TOOBIG_REG 0x010045 + +/* Problem causes symlink to be too big */ +#define PR_1_TOOBIG_SYMLINK 0x010046 + +/* Inode has INDEX_FL flag set on filesystem without htree support */ +#define PR_1_HTREE_SET 0x010047 + +/* Inode number has INDEX_FL flag set but is on a directory */ +#define PR_1_HTREE_NODIR 0x010048 + +/* htree directory has an invalid root node */ +#define PR_1_HTREE_BADROOT 0x010049 + +/* Htree directory has an unsupported hash version */ +#define PR_1_HTREE_HASHV 0x01004A + +/* Htree directory uses an Incompatible htree root node flag */ +#define PR_1_HTREE_INCOMPAT 0x01004B + +/* Htree directory has a tree depth which is too big */ +#define PR_1_HTREE_DEPTH 0x01004C + +/* Bad block inode has an indirect block number that conflicts with + * filesystem metadata */ +#define PR_1_BB_FS_BLOCK 0x01004D + +/* Resize inode (re)creation failed */ +#define PR_1_RESIZE_INODE_CREATE 0x01004E + +/* inode has a extra size i_extra_isize which is invalid */ +#define PR_1_EXTRA_ISIZE 0x01004F + +/* Extended attribute in inode has a namelen which is invalid */ +#define PR_1_ATTR_NAME_LEN 0x010050 + +/* Extended attribute in inode has a value offset which is invalid */ +#define PR_1_ATTR_VALUE_OFFSET 0x010051 + +/* extended attribute in inode has a value block which is invalid */ +#define PR_1_ATTR_VALUE_BLOCK 0x010052 + +/* extended attribute in inode has a value size which is invalid */ +#define PR_1_ATTR_VALUE_SIZE 0x010053 + +/* extended attribute in inode has a hash which is invalid */ +#define PR_1_ATTR_HASH 0x010054 + +/* inode is a type but it looks like it is really a directory */ +#define PR_1_TREAT_AS_DIRECTORY 0x010055 + +/* Error while reading extent tree in inode */ +#define PR_1_READ_EXTENT 0x010056 + +/* Failure to iterate extents in inode */ +#define PR_1_EXTENT_ITERATE_FAILURE 0x010057 + +/* Inode has an invalid extent starting block */ +#define PR_1_EXTENT_BAD_START_BLK 0x010058 + +/* Inode has an invalid extent that ends beyond filesystem */ +#define PR_1_EXTENT_ENDS_BEYOND 0x010059 + +/* inode has EXTENTS_FL flag set on filesystem without extents support */ +#define PR_1_EXTENTS_SET 0x01005A + +/* inode is in extents format, but superblock is missing EXTENTS feature */ +#define PR_1_EXTENT_FEATURE 0x01005B + +/* inode missing EXTENTS_FL, but is an extent inode */ +#define PR_1_UNSET_EXTENT_FL 0x01005C + +/* Fast symlink has EXTENTS_FL set */ +#define PR_1_FAST_SYMLINK_EXTENT_FL 0x01005D + +/* Extents are out of order */ +#define PR_1_OUT_OF_ORDER_EXTENTS 0x01005E + +/* Extent node header invalid */ +#define PR_1_EXTENT_HEADER_INVALID 0x01005F + +/* PR_1_EOFBLOCKS_FL_SET 0x010060 was here */ + +/* Failed to convert subcluster block bitmap */ +#define PR_1_CONVERT_SUBCLUSTER 0x010061 + +/* Quota inode is not a regular file */ +#define PR_1_QUOTA_BAD_MODE 0x010062 + +/* Quota inode is not in use, but contains data */ +#define PR_1_QUOTA_INODE_NOT_CLEAR 0x010063 + +/* Quota inode is visible to the user */ +#define PR_1_QUOTA_INODE_NOT_HIDDEN 0x010064 + +/* The bad block inode looks invalid */ +#define PR_1_INVALID_BAD_INODE 0x010065 + +/* Extent has zero length extent */ +#define PR_1_EXTENT_LENGTH_ZERO 0x010066 + +/* inode seems to contain garbage */ +#define PR_1_INODE_IS_GARBAGE 0x010067 + +/* inode passes checks, but checksum does not match inode */ +#define PR_1_INODE_ONLY_CSUM_INVALID 0x010068 + +/* Inode extended attribute is corrupt (allocation collision) */ +#define PR_1_INODE_EA_ALLOC_COLLISION 0x010069 + +/* Inode extent block passes checks, but checksum does not match extent */ +#define PR_1_EXTENT_ONLY_CSUM_INVALID 0x01006A + +/* Inode extended attribute block passes checks, but checksum does not + * match block. */ +#define PR_1_EA_BLOCK_ONLY_CSUM_INVALID 0x01006C + +/* Interior extent node level number of inode doesn't first node down */ +#define PR_1_EXTENT_INDEX_START_INVALID 0x01006D + +/* Inode end of extent exceeds allowed value */ +#define PR_1_EXTENT_END_OUT_OF_BOUNDS 0x01006E + +/* inode has INLINE_DATA_FL flag on filesystem without inline data */ +#define PR_1_INLINE_DATA_FEATURE 0x01006F + +/* inode has INLINE_DATA_FL flag on filesystem without inline data */ +#define PR_1_INLINE_DATA_SET 0x010070 + +/* Inode block conflicts with critical metadata, skipping block checks */ +#define PR_1_CRITICAL_METADATA_COLLISION 0x010071 + +/* Directory inode block <block> should be at block <otherblock> */ +#define PR_1_COLLAPSE_DBLOCK 0x010072 + +/* Directory inode block <block> should be at block <otherblock> */ +#define PR_1_UNINIT_DBLOCK 0x010073 + +/* Inode logical block (physical block) violates cluster allocation */ +#define PR_1_MISALIGNED_CLUSTER 0x010074 + +/* Inode has INLINE_DATA_FL flag but extended attribute not found */ +#define PR_1_INLINE_DATA_NO_ATTR 0x010075 + +/* Special (device/socket/fifo) file (inode num) has extents + * or inline-data flag set */ +#define PR_1_SPECIAL_EXTENTS_IDATA 0x010076 + +/* Inode has extent header but inline data flag is set */ +#define PR_1_CLEAR_INLINE_DATA_FOR_EXTENT 0x010077 + +/* Inode seems to have inline data but extent flag is set */ +#define PR_1_CLEAR_EXTENT_FOR_INLINE_DATA 0x010078 + +/* Inode seems to have block map but inline data and extent flags set */ +#define PR_1_CLEAR_EXTENT_INLINE_DATA_FLAGS 0x010079 + +/* Inode has inline data and extent flags but i_block contains junk */ +#define PR_1_CLEAR_EXTENT_INLINE_DATA_INODE 0x01007A + +/* Bad block list says the bad block list inode is bad */ +#define PR_1_BADBLOCKS_IN_BADBLOCKS 0x01007B + +/* Error allocating extent region allocation structure */ +#define PR_1_EXTENT_ALLOC_REGION_ABORT 0x01007C + +/* Inode leaf has a duplicate extent mapping */ +#define PR_1_EXTENT_COLLISION 0x01007D + +/* Error allocating memory for encrypted inode list */ +#define PR_1_ALLOCATE_ENCRYPTED_INODE_LIST 0x01007E + +/* Inode extent tree could be more shallow */ +#define PR_1_EXTENT_BAD_MAX_DEPTH 0x01007F + +/* inode num on bigalloc filesystem cannot be block mapped */ +#define PR_1_NO_BIGALLOC_BLOCKMAP_FILES 0x010080 + +/* Inode has corrupt extent header */ +#define PR_1_MISSING_EXTENT_HEADER 0x010081 + +/* Timestamp(s) on inode beyond 2310-04-04 are likely pre-1970. */ +#define PR_1_EA_TIME_OUT_OF_RANGE 0x010082 + +/* Inode has illegal EA value inode */ +#define PR_1_ATTR_VALUE_EA_INODE 0x010083 + +/* Parent inode has invalid EA entry. EA inode does not have + * EXT4_EA_INODE_FL flag. Delete EA entry? */ +#define PR_1_ATTR_NO_EA_INODE_FL 0x010085 + +/* EA inode for parent inode does not have EXT4_EA_INODE_FL flag */ +#define PR_1_ATTR_SET_EA_INODE_FL 0x010086 + +/* Offer to clear uninitialized flag on an extent */ +#define PR_1_CLEAR_UNINIT_EXTENT 0x010087 + +/* Casefold flag set on a non-directory */ +#define PR_1_CASEFOLD_NONDIR 0x010088 + +/* Casefold flag set, but file system is missing the casefold feature */ +#define PR_1_CASEFOLD_FEATURE 0x010089 + +/* Inode has encrypt flag but no encryption extended attribute */ +#define PR_1_MISSING_ENCRYPTION_XATTR 0x01008A + +/* Encrypted inode has corrupt encryption extended attribute */ +#define PR_1_CORRUPT_ENCRYPTION_XATTR 0x01008B + +/* Error allocating memory for casefolded directory list */ +#define PR_1_ALLOCATE_CASEFOLDED_DIRLIST 0x01008C + +/* Htree directory should use SipHash but does not */ +#define PR_1_HTREE_NEEDS_SIPHASH 0x01008D + +/* Htree directory uses SipHash but should not */ +#define PR_1_HTREE_CANNOT_SIPHASH 0x01008E + +/* Orphan file inode is not a regular file */ +#define PR_1_ORPHAN_FILE_BAD_MODE 0x01008F + +/* Orphan file inode is not in use, but contains data */ +#define PR_1_ORPHAN_FILE_NOT_CLEAR 0x010090 + +/* + * Pass 1b errors + */ + +/* Pass 1B: Rescan for duplicate/bad blocks */ +#define PR_1B_PASS_HEADER 0x011000 + +/* Duplicate/bad block(s) header */ +#define PR_1B_DUP_BLOCK_HEADER 0x011001 + +/* Duplicate/bad block(s) in inode */ +#define PR_1B_DUP_BLOCK 0x011002 + +/* Duplicate/bad block(s) end */ +#define PR_1B_DUP_BLOCK_END 0x011003 + +/* Error while scanning inodes */ +#define PR_1B_ISCAN_ERROR 0x011004 + +/* Error allocating inode bitmap */ +#define PR_1B_ALLOCATE_IBITMAP_ERROR 0x011005 + +/* Error while iterating over blocks */ +#define PR_1B_BLOCK_ITERATE 0x011006 + +/* Error adjusting EA refcount */ +#define PR_1B_ADJ_EA_REFCOUNT 0x011007 + +/* Duplicate/bad block range in inode */ +#define PR_1B_DUP_RANGE 0x011008 + +/* Pass 1C: Scan directories for inodes with dup blocks. */ +#define PR_1C_PASS_HEADER 0x012000 + + +/* Pass 1D: Reconciling duplicate blocks */ +#define PR_1D_PASS_HEADER 0x013000 + +/* File has duplicate blocks */ +#define PR_1D_DUP_FILE 0x013001 + +/* List of files sharing duplicate blocks */ +#define PR_1D_DUP_FILE_LIST 0x013002 + +/* File sharing blocks with filesystem metadata */ +#define PR_1D_SHARE_METADATA 0x013003 + +/* Report of how many duplicate/bad inodes */ +#define PR_1D_NUM_DUP_INODES 0x013004 + +/* Duplicated blocks already reassigned or cloned. */ +#define PR_1D_DUP_BLOCKS_DEALT 0x013005 + +/* Clone duplicate/bad blocks? */ +#define PR_1D_CLONE_QUESTION 0x013006 + +/* Delete file? */ +#define PR_1D_DELETE_QUESTION 0x013007 + +/* Couldn't clone file (error) */ +#define PR_1D_CLONE_ERROR 0x013008 + +/* + * Pass 1e --- rebuilding extent trees + */ +/* Pass 1e: Rebuilding extent trees */ +#define PR_1E_PASS_HEADER 0x014000 + +/* Error rehash directory */ +#define PR_1E_OPTIMIZE_EXT_ERR 0x014001 + +/* Rebuilding extent trees */ +#define PR_1E_OPTIMIZE_EXT_HEADER 0x014002 + +/* Rebuilding extent %d */ +#define PR_1E_OPTIMIZE_EXT 0x014003 + +/* Rebuilding extent tree end */ +#define PR_1E_OPTIMIZE_EXT_END 0x014004 + +/* Internal error: extent tree depth too large */ +#define PR_1E_MAX_EXTENT_TREE_DEPTH 0x014005 + +/* Inode extent tree could be shorter */ +#define PR_1E_CAN_COLLAPSE_EXTENT_TREE 0x014006 + +/* Inode extent tree could be narrower */ +#define PR_1E_CAN_NARROW_EXTENT_TREE 0x014007 + +/* + * Pass 2 errors + */ + +/* Pass 2: Checking directory structure */ +#define PR_2_PASS_HEADER 0x020000 + +/* Bad inode number for '.' */ +#define PR_2_BAD_INODE_DOT 0x020001 + +/* Directory entry has bad inode number */ +#define PR_2_BAD_INO 0x020002 + +/* Directory entry has deleted or unused inode */ +#define PR_2_UNUSED_INODE 0x020003 + +/* Directory entry is link to '.' */ +#define PR_2_LINK_DOT 0x020004 + +/* Directory entry points to inode now located in a bad block */ +#define PR_2_BB_INODE 0x020005 + +/* Directory entry contains a link to a directory */ +#define PR_2_LINK_DIR 0x020006 + +/* Directory entry contains a link to the root directory */ +#define PR_2_LINK_ROOT 0x020007 + +/* Directory entry has illegal characters in its name */ +#define PR_2_BAD_NAME 0x020008 + +/* Missing '.' in directory inode */ +#define PR_2_MISSING_DOT 0x020009 + +/* Missing '..' in directory inode */ +#define PR_2_MISSING_DOT_DOT 0x02000A + +/* First entry in directory inode doesn't contain '.' */ +#define PR_2_1ST_NOT_DOT 0x02000B + +/* Second entry in directory inode doesn't contain '..' */ +#define PR_2_2ND_NOT_DOT_DOT 0x02000C + +/* i_faddr should be zero */ +#define PR_2_FADDR_ZERO 0x02000D + +/* i_file_acl should be zero */ +#define PR_2_FILE_ACL_ZERO 0x02000E + +/* i_size_high should be zero */ +#define PR_2_DIR_SIZE_HIGH_ZERO 0x02000F + +/* i_frag should be zero */ +#define PR_2_FRAG_ZERO 0x020010 + +/* i_fsize should be zero */ +#define PR_2_FSIZE_ZERO 0x020011 + +/* inode has bad mode */ +#define PR_2_BAD_MODE 0x020012 + +/* directory corrupted */ +#define PR_2_DIR_CORRUPTED 0x020013 + +/* filename too long */ +#define PR_2_FILENAME_LONG 0x020014 + +/* Directory inode has a missing block (hole) */ +#define PR_2_DIRECTORY_HOLE 0x020015 + +/* '.' is not NULL terminated */ +#define PR_2_DOT_NULL_TERM 0x020016 + +/* '..' is not NULL terminated */ +#define PR_2_DOT_DOT_NULL_TERM 0x020017 + +/* Illegal character device in inode */ +#define PR_2_BAD_CHAR_DEV 0x020018 + +/* Illegal block device in inode */ +#define PR_2_BAD_BLOCK_DEV 0x020019 + +/* Duplicate '.' entry */ +#define PR_2_DUP_DOT 0x02001A + +/* Duplicate '..' entry */ +#define PR_2_DUP_DOT_DOT 0x02001B + +/* Internal error: couldn't find dir_info */ +#define PR_2_NO_DIRINFO 0x02001C + +/* Final rec_len is wrong */ +#define PR_2_FINAL_RECLEN 0x02001D + +/* Error allocating icount structure */ +#define PR_2_ALLOCATE_ICOUNT 0x02001E + +/* Error iterating over directory blocks */ +#define PR_2_DBLIST_ITERATE 0x02001F + +/* Error reading directory block */ +#define PR_2_READ_DIRBLOCK 0x020020 + +/* Error writing directory block */ +#define PR_2_WRITE_DIRBLOCK 0x020021 + +/* Error allocating new directory block */ +#define PR_2_ALLOC_DIRBOCK 0x020022 + +/* Error deallocating inode */ +#define PR_2_DEALLOC_INODE 0x020023 + +/* Directory entry for '.' is big. Split? */ +#define PR_2_SPLIT_DOT 0x020024 + +/* Illegal FIFO */ +#define PR_2_BAD_FIFO 0x020025 + +/* Illegal socket */ +#define PR_2_BAD_SOCKET 0x020026 + +/* Directory filetype not set */ +#define PR_2_SET_FILETYPE 0x020027 + +/* Directory filetype incorrect */ +#define PR_2_BAD_FILETYPE 0x020028 + +/* Directory filetype set when it shouldn't be */ +#define PR_2_CLEAR_FILETYPE 0x020029 + +/* Directory filename can't be zero-length */ +#define PR_2_NULL_NAME 0x020030 + +/* Invalid symlink */ +#define PR_2_INVALID_SYMLINK 0x020031 + +/* i_file_acl (extended attribute) is bad */ +#define PR_2_FILE_ACL_BAD 0x020032 + +/* Filesystem contains large files, but has no such flag in sb */ +#define PR_2_FEATURE_LARGE_FILES 0x020033 + +/* Node in HTREE directory not referenced */ +#define PR_2_HTREE_NOTREF 0x020034 + +/* Node in HTREE directory referenced twice */ +#define PR_2_HTREE_DUPREF 0x020035 + +/* Node in HTREE directory has bad min hash */ +#define PR_2_HTREE_MIN_HASH 0x020036 + +/* Node in HTREE directory has bad max hash */ +#define PR_2_HTREE_MAX_HASH 0x020037 + +/* Clear invalid HTREE directory */ +#define PR_2_HTREE_CLEAR 0x020038 + +/* Filesystem has large directories, but has no such flag in superblock */ +#define PR_2_FEATURE_LARGE_DIRS 0x020039 + +/* Bad block in htree interior node */ +#define PR_2_HTREE_BADBLK 0x02003A + +/* Error adjusting EA refcount */ +#define PR_2_ADJ_EA_REFCOUNT 0x02003B + +/* Invalid HTREE root node */ +#define PR_2_HTREE_BAD_ROOT 0x02003C + +/* Invalid HTREE limit */ +#define PR_2_HTREE_BAD_LIMIT 0x02003D + +/* Invalid HTREE count */ +#define PR_2_HTREE_BAD_COUNT 0x02003E + +/* HTREE interior node has out-of-order hashes in table */ +#define PR_2_HTREE_HASH_ORDER 0x02003F + +/* Node in HTREE directory has bad depth */ +#define PR_2_HTREE_BAD_DEPTH 0x020040 + +/* Duplicate directory entry found */ +#define PR_2_DUPLICATE_DIRENT 0x020041 + +/* Non-unique filename found */ +#define PR_2_NON_UNIQUE_FILE 0x020042 + +/* Duplicate directory entry found */ +#define PR_2_REPORT_DUP_DIRENT 0x020043 + +/* i_blocks_hi should be zero */ +#define PR_2_BLOCKS_HI_ZERO 0x020044 + +/* Unexpected HTREE block */ +#define PR_2_UNEXPECTED_HTREE_BLOCK 0x020045 + +/* Inode found in group where _INODE_UNINIT is set */ +#define PR_2_INOREF_BG_INO_UNINIT 0x020046 + +/* Inode found in group unused inodes area */ +#define PR_2_INOREF_IN_UNUSED 0x020047 + +/* i_file_acl_hi should be zero */ +#define PR_2_I_FILE_ACL_HI_ZERO 0x020048 + +/* htree root node fails checksum */ +#define PR_2_HTREE_ROOT_CSUM_INVALID 0x020049 + +/* htree node fails checksum */ +#define PR_2_HTREE_NODE_CSUM_INVALID 0x02004A + +/* no space in leaf for checksum */ +#define PR_2_LEAF_NODE_MISSING_CSUM 0x02004C + +/* dir leaf node passes checks, but fails checksum */ +#define PR_2_LEAF_NODE_ONLY_CSUM_INVALID 0x02004D + +/* bad inline directory size */ +#define PR_2_BAD_INLINE_DIR_SIZE 0x02004E + +/* fixing inline dir size failed */ +#define PR_2_FIX_INLINE_DIR_FAILED 0x02004F + +/* Encrypted directory entry is too short */ +#define PR_2_BAD_ENCRYPTED_NAME 0x020050 + +/* Encrypted directory contains unencrypted file */ +#define PR_2_UNENCRYPTED_FILE 0x020051 + +/* Encrypted directory contains file with different encryption policy */ +#define PR_2_INCONSISTENT_ENCRYPTION_POLICY 0x020052 + +/* Encoded directory entry has illegal characters in its name */ +#define PR_2_BAD_ENCODED_NAME 0x020053 + +/* Non-unique filename found, but can't rename */ +#define PR_2_NON_UNIQUE_FILE_NO_RENAME 0x020054 + +/* + * Pass 3 errors + */ + +/* Pass 3: Checking directory connectivity */ +#define PR_3_PASS_HEADER 0x030000 + +/* Root inode not allocated */ +#define PR_3_NO_ROOT_INODE 0x030001 + +/* No room in lost+found */ +#define PR_3_EXPAND_LF_DIR 0x030002 + +/* Unconnected directory inode */ +#define PR_3_UNCONNECTED_DIR 0x030003 + +/* /lost+found not found */ +#define PR_3_NO_LF_DIR 0x030004 + +/* .. entry is incorrect */ +#define PR_3_BAD_DOT_DOT 0x030005 + +/* Bad or non-existent /lost+found. Cannot reconnect */ +#define PR_3_NO_LPF 0x030006 + +/* Could not expand /lost+found */ +#define PR_3_CANT_EXPAND_LPF 0x030007 + +/* Could not reconnect inode */ +#define PR_3_CANT_RECONNECT 0x030008 + +/* Error while trying to find /lost+found */ +#define PR_3_ERR_FIND_LPF 0x030009 + +/* Error in ext2fs_new_block while creating /lost+found */ +#define PR_3_ERR_LPF_NEW_BLOCK 0x03000A + +/* Error in ext2fs_new_inode while creating /lost+found */ +#define PR_3_ERR_LPF_NEW_INODE 0x03000B + +/* Error in ext2fs_new_dir_block while creating /lost+found */ +#define PR_3_ERR_LPF_NEW_DIR_BLOCK 0x03000C + +/* Error while writing directory block for /lost+found */ +#define PR_3_ERR_LPF_WRITE_BLOCK 0x03000D + +/* Error while adjusting inode count */ +#define PR_3_ADJUST_INODE 0x03000E + +/* Couldn't fix parent directory -- error */ +#define PR_3_FIX_PARENT_ERR 0x03000F + +/* Couldn't fix parent directory -- couldn't find it */ +#define PR_3_FIX_PARENT_NOFIND 0x030010 + +/* Error allocating inode bitmap */ +#define PR_3_ALLOCATE_IBITMAP_ERROR 0x030011 + +/* Error creating root directory */ +#define PR_3_CREATE_ROOT_ERROR 0x030012 + +/* Error creating lost and found directory */ +#define PR_3_CREATE_LPF_ERROR 0x030013 + +/* Root inode is not directory; aborting */ +#define PR_3_ROOT_NOT_DIR_ABORT 0x030014 + +/* Cannot proceed without a root inode. */ +#define PR_3_NO_ROOT_INODE_ABORT 0x030015 + +/* Internal error: couldn't find dir_info */ +#define PR_3_NO_DIRINFO 0x030016 + +/* Lost+found is not a directory */ +#define PR_3_LPF_NOTDIR 0x030017 + +/* Lost+found has inline data */ +#define PR_3_LPF_INLINE_DATA 0x030018 + +/* Cannot allocate lost+found */ +#define PR_3_LPF_NO_SPACE 0x030019 + +/* Insufficient space to recover lost files */ +#define PR_3_NO_SPACE_TO_RECOVER 0x03001A + +/* Lost+found is encrypted */ +#define PR_3_LPF_ENCRYPTED 0x03001B + +/* Recursively looped directory inode */ +#define PR_3_LOOPED_DIR 0x03001D + +/* + * Pass 3a --- rehashing directories + */ +/* Pass 3a: Reindexing directories */ +#define PR_3A_PASS_HEADER 0x031000 + +/* Error iterating over directories */ +#define PR_3A_OPTIMIZE_ITER 0x031001 + +/* Error rehash directory */ +#define PR_3A_OPTIMIZE_DIR_ERR 0x031002 + +/* Rehashing dir header */ +#define PR_3A_OPTIMIZE_DIR_HEADER 0x031003 + +/* Rehashing directory %d */ +#define PR_3A_OPTIMIZE_DIR 0x031004 + +/* Rehashing dir end */ +#define PR_3A_OPTIMIZE_DIR_END 0x031005 + +/* Pass 3B is really just 1E */ + +/* + * Pass 4 errors + */ + +/* Pass 4: Checking reference counts */ +#define PR_4_PASS_HEADER 0x040000 + +/* Unattached zero-length inode */ +#define PR_4_ZERO_LEN_INODE 0x040001 + +/* Unattached inode */ +#define PR_4_UNATTACHED_INODE 0x040002 + +/* Inode ref count wrong */ +#define PR_4_BAD_REF_COUNT 0x040003 + +/* Inconsistent inode count information cached */ +#define PR_4_INCONSISTENT_COUNT 0x040004 + +/* Extended attribute inode ref count wrong */ +#define PR_4_EA_INODE_REF_COUNT 0x040005 + +/* directory exceeds max links, but no DIR_NLINK feature in superblock */ +#define PR_4_DIR_NLINK_FEATURE 0x040006 + +/* Directory ref count set to overflow but it doesn't have to be */ +#define PR_4_DIR_OVERFLOW_REF_COUNT 0x040007 + +/* + * Pass 5 errors + */ + +/* Pass 5: Checking group summary information */ +#define PR_5_PASS_HEADER 0x050000 + +/* Padding at end of inode bitmap is not set. */ +#define PR_5_INODE_BMAP_PADDING 0x050001 + +/* Padding at end of block bitmap is not set. */ +#define PR_5_BLOCK_BMAP_PADDING 0x050002 + +/* Block bitmap differences header */ +#define PR_5_BLOCK_BITMAP_HEADER 0x050003 + +/* Block not used, but marked in bitmap */ +#define PR_5_BLOCK_UNUSED 0x050004 + +/* Block used, but not marked used in bitmap */ +#define PR_5_BLOCK_USED 0x050005 + +/* Block bitmap differences end */ +#define PR_5_BLOCK_BITMAP_END 0x050006 + +/* Inode bitmap differences header */ +#define PR_5_INODE_BITMAP_HEADER 0x050007 + +/* Inode not used, but marked in bitmap */ +#define PR_5_INODE_UNUSED 0x050008 + +/* Inode used, but not marked used in bitmap */ +#define PR_5_INODE_USED 0x050009 + +/* Inode bitmap differences end */ +#define PR_5_INODE_BITMAP_END 0x05000A + +/* Free inodes count for group wrong */ +#define PR_5_FREE_INODE_COUNT_GROUP 0x05000B + +/* Directories count for group wrong */ +#define PR_5_FREE_DIR_COUNT_GROUP 0x05000C + +/* Free inodes count wrong */ +#define PR_5_FREE_INODE_COUNT 0x05000D + +/* Free blocks count for group wrong */ +#define PR_5_FREE_BLOCK_COUNT_GROUP 0x05000E + +/* Free blocks count wrong */ +#define PR_5_FREE_BLOCK_COUNT 0x05000F + +/* Programming error: bitmap endpoints don't match */ +#define PR_5_BMAP_ENDPOINTS 0x050010 + +/* Internal error: fudging end of bitmap */ +#define PR_5_FUDGE_BITMAP_ERROR 0x050011 + +/* Error copying in replacement inode bitmap */ +#define PR_5_COPY_IBITMAP_ERROR 0x050012 + +/* Error copying in replacement block bitmap */ +#define PR_5_COPY_BBITMAP_ERROR 0x050013 + +/* Block range not used, but marked in bitmap */ +#define PR_5_BLOCK_RANGE_UNUSED 0x050014 + +/* Block range used, but not marked used in bitmap */ +#define PR_5_BLOCK_RANGE_USED 0x050015 + +/* Inode range not used, but marked in bitmap */ +#define PR_5_INODE_RANGE_UNUSED 0x050016 + +/* Inode range used, but not marked used in bitmap */ +#define PR_5_INODE_RANGE_USED 0x050017 + +/* Block in use but group is marked BLOCK_UNINIT */ +#define PR_5_BLOCK_UNINIT 0x050018 + +/* Inode in use but group is marked INODE_UNINIT */ +#define PR_5_INODE_UNINIT 0x050019 + +/* Inode bitmap checksum does not match */ +#define PR_5_INODE_BITMAP_CSUM_INVALID 0x05001A + +/* Block bitmap checksum does not match */ +#define PR_5_BLOCK_BITMAP_CSUM_INVALID 0x05001B + +/* + * Post-Pass 5 errors + */ + +/* Recreate the journal if E2F_FLAG_JOURNAL_INODE flag is set */ +#define PR_6_RECREATE_JOURNAL 0x060001 + +/* Update quota information if it is inconsistent */ +#define PR_6_UPDATE_QUOTAS 0x060002 + +/* Error setting block group checksum info */ +#define PR_6_SET_BG_CHECKSUM 0x060003 + +/* Error writing file system info */ +#define PR_6_FLUSH_FILESYSTEM 0x060004 + +/* Error flushing writes to storage device */ +#define PR_6_IO_FLUSH 0x060005 + +/* Error updating quota information */ +#define PR_6_WRITE_QUOTAS 0x060006 + +/* Orphan file without a journal */ +#define PR_6_ORPHAN_FILE_WITHOUT_JOURNAL 0x060007 + +/* Orphan file truncation failed */ +#define PR_6_ORPHAN_FILE_TRUNC_FAILED 0x060008 + +/* Failed to initialize orphan file */ +#define PR_6_ORPHAN_FILE_CORRUPTED 0x060009 + +/* Cannot fix corrupted orphan file with invalid bitmaps */ +#define PR_6_ORPHAN_FILE_BITMAP_INVALID 0x06000A + +/* Orphan file creation failed */ +#define PR_6_ORPHAN_FILE_CREATE_FAILED 0x06000B + +/* Orphan file block contains data */ +#define PR_6_ORPHAN_BLOCK_DIRTY 0x06000C + +/* orphan_present set but orphan file is empty */ +#define PR_6_ORPHAN_PRESENT_CLEAN_FILE 0x06000D + +/* orphan_present set but orphan_file is not */ +#define PR_6_ORPHAN_PRESENT_NO_FILE 0x06000E + +/* Orphan file size isn't multiple of blocks size */ +#define PR_6_ORPHAN_FILE_WRONG_SIZE 0x06000F + +/* Orphan file contains holes */ +#define PR_6_ORPHAN_FILE_HOLE 0x060010 + +/* + * Function declarations + */ +int fix_problem(e2fsck_t ctx, problem_t code, struct problem_context *pctx); +int end_problem_latch(e2fsck_t ctx, int mask); +int set_latch_flags(int mask, int setflags, int clearflags); +int get_latch_flags(int mask, int *value); +void clear_problem_context(struct problem_context *pctx); + +/* message.c */ +void print_e2fsck_message(FILE *f, e2fsck_t ctx, const char *msg, + struct problem_context *pctx, int first, + int recurse); + diff --git a/e2fsck/problemP.h b/e2fsck/problemP.h new file mode 100644 index 0000000..95c1a70 --- /dev/null +++ b/e2fsck/problemP.h @@ -0,0 +1,48 @@ +/* + * problemP.h --- Private header file for fix_problem() + * + * Copyright 1997 by Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +struct e2fsck_problem { + problem_t e2p_code; + const char * e2p_description; + char prompt; + int flags; + problem_t second_code; + int count; + int max_count; +}; + +struct latch_descr { + int latch_code; + problem_t question; + problem_t end_message; + int flags; +}; + +#define PR_PREEN_OK 0x000001 /* Don't need to do preenhalt */ +#define PR_NO_OK 0x000002 /* If user answers no, don't make fs invalid */ +#define PR_NO_DEFAULT 0x000004 /* Default to no */ +#define PR_MSG_ONLY 0x000008 /* Print message only */ + +/* Bit positions 0x000ff0 are reserved for the PR_LATCH flags */ + +#define PR_FATAL 0x001000 /* Fatal error */ +#define PR_AFTER_CODE 0x002000 /* After asking the first question, */ + /* ask another */ +#define PR_PREEN_NOMSG 0x004000 /* Don't print a message if we're preening */ +#define PR_NOCOLLATE 0x008000 /* Don't collate answers for this latch */ +#define PR_NO_NOMSG 0x010000 /* Don't print a message if e2fsck -n */ +#define PR_PREEN_NO 0x020000 /* Use No as an answer if preening */ +#define PR_PREEN_NOHDR 0x040000 /* Don't print the preen header */ +#define PR_CONFIG 0x080000 /* This problem has been customized + from the config file */ +#define PR_FORCE_NO 0x100000 /* Force the answer to be no */ +#define PR_NOT_A_FIX 0x200000 /* Yes doesn't mean a problem was fixed */ +#define PR_HEADER 0x400000 /* Problem is a header marker */ diff --git a/e2fsck/quota.c b/e2fsck/quota.c new file mode 100644 index 0000000..f9b68c9 --- /dev/null +++ b/e2fsck/quota.c @@ -0,0 +1,127 @@ +/* + * quota.c --- code for handling ext4 quota inodes + * + */ + +#include "config.h" +#ifdef HAVE_SYS_MOUNT_H +#include <sys/param.h> +#include <sys/mount.h> +#define MNT_FL (MS_MGC_VAL | MS_RDONLY) +#endif +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif + +#include "e2fsck.h" +#include "problem.h" + +static errcode_t move_quota_inode(ext2_filsys fs, ext2_ino_t from_ino, + ext2_ino_t to_ino, enum quota_type qtype) +{ + struct ext2_inode inode; + errcode_t retval; + char qf_name[QUOTA_NAME_LEN]; + + /* We need the inode bitmap to be loaded */ + retval = ext2fs_read_bitmaps(fs); + if (retval) { + com_err("ext2fs_read_bitmaps", retval, "%s", + _("in move_quota_inode")); + return retval; + } + + retval = ext2fs_read_inode(fs, from_ino, &inode); + if (retval) { + com_err("ext2fs_read_inode", retval, "%s", + _("in move_quota_inode")); + return retval; + } + + inode.i_links_count = 1; + inode.i_mode = LINUX_S_IFREG | 0600; + inode.i_flags = EXT2_IMMUTABLE_FL; + if (ext2fs_has_feature_extents(fs->super)) + inode.i_flags |= EXT4_EXTENTS_FL; + + retval = ext2fs_write_new_inode(fs, to_ino, &inode); + if (retval) { + com_err("ext2fs_write_new_inode", retval, "%s", + _("in move_quota_inode")); + return retval; + } + + /* unlink the old inode */ + quota_get_qf_name(qtype, QFMT_VFS_V1, qf_name); + retval = ext2fs_unlink(fs, EXT2_ROOT_INO, qf_name, from_ino, 0); + if (retval) { + com_err("ext2fs_unlink", retval, "%s", + _("in move_quota_inode")); + return retval; + } + ext2fs_inode_alloc_stats(fs, from_ino, -1); + /* Clear out the original inode in the inode-table block. */ + memset(&inode, 0, sizeof(struct ext2_inode)); + ext2fs_write_inode(fs, from_ino, &inode); + return 0; +} + +void e2fsck_hide_quota(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + ext2_filsys fs = ctx->fs; + enum quota_type qtype; + ext2_ino_t quota_ino; + + clear_problem_context(&pctx); + + if ((ctx->options & E2F_OPT_READONLY) || + !ext2fs_has_feature_quota(sb)) + return; + + for (qtype = 0; qtype < MAXQUOTAS; qtype++) { + pctx.dir = 2; /* This is a guess, but it's a good one */ + pctx.ino = *quota_sb_inump(sb, qtype); + pctx.num = qtype; + quota_ino = quota_type2inum(qtype, fs->super); + if (pctx.ino && (pctx.ino != quota_ino) && + fix_problem(ctx, PR_0_HIDE_QUOTA, &pctx)) { + if (move_quota_inode(fs, pctx.ino, quota_ino, qtype)) + continue; + *quota_sb_inump(sb, qtype) = quota_ino; + ext2fs_mark_super_dirty(fs); + } + } + + return; +} + +void e2fsck_validate_quota_inodes(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + ext2_filsys fs = ctx->fs; + enum quota_type qtype; + + clear_problem_context(&pctx); + + for (qtype = 0; qtype < MAXQUOTAS; qtype++) { + pctx.ino = *quota_sb_inump(sb, qtype); + pctx.num = qtype; + if (pctx.ino && + ((pctx.ino == EXT2_BAD_INO) || + (pctx.ino == EXT2_ROOT_INO) || + (pctx.ino == EXT2_BOOT_LOADER_INO) || + (pctx.ino == EXT2_UNDEL_DIR_INO) || + (pctx.ino == EXT2_RESIZE_INO) || + (pctx.ino == EXT2_JOURNAL_INO) || + (pctx.ino == EXT2_EXCLUDE_INO) || + (pctx.ino == EXT4_REPLICA_INO) || + (pctx.ino > fs->super->s_inodes_count)) && + fix_problem(ctx, PR_0_INVALID_QUOTA_INO, &pctx)) { + *quota_sb_inump(sb, qtype) = 0; + ext2fs_mark_super_dirty(fs); + } + } +} diff --git a/e2fsck/readahead.c b/e2fsck/readahead.c new file mode 100644 index 0000000..38d4ec4 --- /dev/null +++ b/e2fsck/readahead.c @@ -0,0 +1,254 @@ +/* + * readahead.c -- Prefetch filesystem metadata to speed up fsck. + * + * Copyright (C) 2014 Oracle. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Library + * General Public License, version 2. + * %End-Header% + */ + +#include "config.h" +#include <string.h> + +#include "e2fsck.h" + +#undef DEBUG + +#ifdef DEBUG +# define dbg_printf(f, a...) do {printf(f, ## a); fflush(stdout); } while (0) +#else +# define dbg_printf(f, a...) +#endif + +struct read_dblist { + errcode_t err; + blk64_t run_start; + blk64_t run_len; + int flags; +}; + +static int readahead_dir_block(ext2_filsys fs, struct ext2_db_entry2 *db, + void *priv_data) +{ + struct read_dblist *pr = priv_data; + e2_blkcnt_t count = (pr->flags & E2FSCK_RA_DBLIST_IGNORE_BLOCKCNT ? + 1 : db->blockcnt); + + if (!pr->run_len || db->blk != pr->run_start + pr->run_len) { + if (pr->run_len) { + pr->err = io_channel_cache_readahead(fs->io, + pr->run_start, + pr->run_len); + dbg_printf("readahead start=%llu len=%llu err=%d\n", + pr->run_start, pr->run_len, + (int)pr->err); + } + pr->run_start = db->blk; + pr->run_len = 0; + } + pr->run_len += count; + + return pr->err ? DBLIST_ABORT : 0; +} + +errcode_t e2fsck_readahead_dblist(ext2_filsys fs, int flags, + ext2_dblist dblist, + unsigned long long start, + unsigned long long count) +{ + errcode_t err; + struct read_dblist pr; + + dbg_printf("%s: flags=0x%x\n", __func__, flags); + if (flags & ~E2FSCK_RA_DBLIST_ALL_FLAGS) + return EXT2_ET_INVALID_ARGUMENT; + + memset(&pr, 0, sizeof(pr)); + pr.flags = flags; + err = ext2fs_dblist_iterate3(dblist, readahead_dir_block, start, + count, &pr); + if (pr.err) + return pr.err; + if (err) + return err; + + if (pr.run_len) + err = io_channel_cache_readahead(fs->io, pr.run_start, + pr.run_len); + + return err; +} + +static errcode_t e2fsck_readahead_bitmap(ext2_filsys fs, + ext2fs_block_bitmap ra_map) +{ + blk64_t start, end, out; + errcode_t err; + + start = 1; + end = ext2fs_blocks_count(fs->super) - 1; + + err = ext2fs_find_first_set_block_bitmap2(ra_map, start, end, &out); + while (err == 0) { + start = out; + err = ext2fs_find_first_zero_block_bitmap2(ra_map, start, end, + &out); + if (err == ENOENT) { + out = end; + err = 0; + if (out == start) + break; + } else if (err) + break; + + err = io_channel_cache_readahead(fs->io, start, out - start); + if (err) + break; + start = out; + err = ext2fs_find_first_set_block_bitmap2(ra_map, start, end, + &out); + } + + if (err == ENOENT) + err = 0; + + return err; +} + +/* Try not to spew bitmap range errors for readahead */ +static errcode_t mark_bmap_range(ext2fs_block_bitmap map, + blk64_t blk, unsigned int num) +{ + if (blk >= ext2fs_get_generic_bmap_start(map) && + blk + num <= ext2fs_get_generic_bmap_end(map)) + ext2fs_mark_block_bitmap_range2(map, blk, num); + else + return EXT2_ET_INVALID_ARGUMENT; + return 0; +} + +static errcode_t mark_bmap(ext2fs_block_bitmap map, blk64_t blk) +{ + if (blk >= ext2fs_get_generic_bmap_start(map) && + blk <= ext2fs_get_generic_bmap_end(map)) + ext2fs_mark_block_bitmap2(map, blk); + else + return EXT2_ET_INVALID_ARGUMENT; + return 0; +} + +errcode_t e2fsck_readahead(ext2_filsys fs, int flags, dgrp_t start, + dgrp_t ngroups) +{ + blk64_t super, old_gdt, new_gdt; + blk_t blocks; + dgrp_t i; + ext2fs_block_bitmap ra_map = NULL; + dgrp_t end = start + ngroups; + errcode_t err = 0; + + dbg_printf("%s: flags=0x%x start=%d groups=%d\n", __func__, flags, + start, ngroups); + if (flags & ~E2FSCK_READA_ALL_FLAGS) + return EXT2_ET_INVALID_ARGUMENT; + + if (end > fs->group_desc_count) + end = fs->group_desc_count; + + if (flags == 0) + return 0; + + err = ext2fs_allocate_block_bitmap(fs, "readahead bitmap", + &ra_map); + if (err) + return err; + + for (i = start; i < end; i++) { + err = ext2fs_super_and_bgd_loc2(fs, i, &super, &old_gdt, + &new_gdt, &blocks); + if (err) + break; + + if (flags & E2FSCK_READA_SUPER) { + err = mark_bmap(ra_map, super); + if (err) + break; + } + + if (flags & E2FSCK_READA_GDT) { + err = mark_bmap_range(ra_map, + old_gdt ? old_gdt : new_gdt, + blocks); + if (err) + break; + } + + if ((flags & E2FSCK_READA_BBITMAP) && + !ext2fs_bg_flags_test(fs, i, EXT2_BG_BLOCK_UNINIT) && + ext2fs_bg_free_blocks_count(fs, i) < + fs->super->s_blocks_per_group) { + super = ext2fs_block_bitmap_loc(fs, i); + err = mark_bmap(ra_map, super); + if (err) + break; + } + + if ((flags & E2FSCK_READA_IBITMAP) && + !ext2fs_bg_flags_test(fs, i, EXT2_BG_INODE_UNINIT) && + ext2fs_bg_free_inodes_count(fs, i) < + fs->super->s_inodes_per_group) { + super = ext2fs_inode_bitmap_loc(fs, i); + err = mark_bmap(ra_map, super); + if (err) + break; + } + + if ((flags & E2FSCK_READA_ITABLE) && + ext2fs_bg_free_inodes_count(fs, i) < + fs->super->s_inodes_per_group) { + super = ext2fs_inode_table_loc(fs, i); + blocks = fs->inode_blocks_per_group - + (ext2fs_bg_itable_unused(fs, i) * + EXT2_INODE_SIZE(fs->super) / fs->blocksize); + err = mark_bmap_range(ra_map, super, blocks); + if (err) + break; + } + } + + if (!err) + err = e2fsck_readahead_bitmap(fs, ra_map); + + ext2fs_free_block_bitmap(ra_map); + return err; +} + +int e2fsck_can_readahead(ext2_filsys fs) +{ + errcode_t err; + + err = io_channel_cache_readahead(fs->io, 0, 1); + dbg_printf("%s: supp=%d\n", __func__, err != EXT2_ET_OP_NOT_SUPPORTED); + return err != EXT2_ET_OP_NOT_SUPPORTED; +} + +unsigned long long e2fsck_guess_readahead(ext2_filsys fs) +{ + unsigned long long guess; + + /* + * The optimal readahead sizes were experimentally determined by + * djwong in August 2014. Setting the RA size to two block groups' + * worth of inode table blocks seems to yield the largest reductions + * in e2fsck runtime. + */ + guess = 2ULL * fs->blocksize * fs->inode_blocks_per_group; + + /* Disable RA if it'd use more 1/50th of RAM. */ + if (get_memory_size() > (guess * 50)) + return guess / 1024; + + return 0; +} diff --git a/e2fsck/recovery.c b/e2fsck/recovery.c new file mode 100644 index 0000000..8ca3527 --- /dev/null +++ b/e2fsck/recovery.c @@ -0,0 +1,931 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * linux/fs/jbd2/recovery.c + * + * Written by Stephen C. Tweedie <sct@redhat.com>, 1999 + * + * Copyright 1999-2000 Red Hat Software --- All Rights Reserved + * + * Journal recovery routines for the generic filesystem journaling code; + * part of the ext2fs journaling system. + */ + +#ifndef __KERNEL__ +#include "jfs_user.h" +#else +#include <linux/time.h> +#include <linux/fs.h> +#include <linux/jbd2.h> +#include <linux/errno.h> +#include <linux/crc32.h> +#include <linux/blkdev.h> +#endif + +/* + * Maintain information about the progress of the recovery job, so that + * the different passes can carry information between them. + */ +struct recovery_info +{ + tid_t start_transaction; + tid_t end_transaction; + + int nr_replays; + int nr_revokes; + int nr_revoke_hits; +}; + +static int do_one_pass(journal_t *journal, + struct recovery_info *info, enum passtype pass); +static int scan_revoke_records(journal_t *, struct buffer_head *, + tid_t, struct recovery_info *); + +#ifdef __KERNEL__ + +/* Release readahead buffers after use */ +static void journal_brelse_array(struct buffer_head *b[], int n) +{ + while (--n >= 0) + brelse (b[n]); +} + + +/* + * When reading from the journal, we are going through the block device + * layer directly and so there is no readahead being done for us. We + * need to implement any readahead ourselves if we want it to happen at + * all. Recovery is basically one long sequential read, so make sure we + * do the IO in reasonably large chunks. + * + * This is not so critical that we need to be enormously clever about + * the readahead size, though. 128K is a purely arbitrary, good-enough + * fixed value. + */ + +#define MAXBUF 8 +static int do_readahead(journal_t *journal, unsigned int start) +{ + int err; + unsigned int max, nbufs, next; + unsigned long long blocknr; + struct buffer_head *bh; + + struct buffer_head * bufs[MAXBUF]; + + /* Do up to 128K of readahead */ + max = start + (128 * 1024 / journal->j_blocksize); + if (max > journal->j_total_len) + max = journal->j_total_len; + + /* Do the readahead itself. We'll submit MAXBUF buffer_heads at + * a time to the block device IO layer. */ + + nbufs = 0; + + for (next = start; next < max; next++) { + err = jbd2_journal_bmap(journal, next, &blocknr); + + if (err) { + printk(KERN_ERR "JBD2: bad block at offset %u\n", + next); + goto failed; + } + + bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize); + if (!bh) { + err = -ENOMEM; + goto failed; + } + + if (!buffer_uptodate(bh) && !buffer_locked(bh)) { + bufs[nbufs++] = bh; + if (nbufs == MAXBUF) { + ll_rw_block(REQ_OP_READ, 0, nbufs, bufs); + journal_brelse_array(bufs, nbufs); + nbufs = 0; + } + } else + brelse(bh); + } + + if (nbufs) + ll_rw_block(REQ_OP_READ, 0, nbufs, bufs); + err = 0; + +failed: + if (nbufs) + journal_brelse_array(bufs, nbufs); + return err; +} + +#endif /* __KERNEL__ */ + + +/* + * Read a block from the journal + */ + +static int jread(struct buffer_head **bhp, journal_t *journal, + unsigned int offset) +{ + int err; + unsigned long long blocknr; + struct buffer_head *bh; + + *bhp = NULL; + + if (offset >= journal->j_total_len) { + printk(KERN_ERR "JBD2: corrupted journal superblock\n"); + return -EFSCORRUPTED; + } + + err = jbd2_journal_bmap(journal, offset, &blocknr); + + if (err) { + printk(KERN_ERR "JBD2: bad block at offset %u\n", + offset); + return err; + } + + bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize); + if (!bh) + return -ENOMEM; + + if (!buffer_uptodate(bh)) { + /* If this is a brand new buffer, start readahead. + Otherwise, we assume we are already reading it. */ + if (!buffer_req(bh)) + do_readahead(journal, offset); + wait_on_buffer(bh); + } + + if (!buffer_uptodate(bh)) { + printk(KERN_ERR "JBD2: Failed to read block at offset %u\n", + offset); + brelse(bh); + return -EIO; + } + + *bhp = bh; + return 0; +} + +static int jbd2_descriptor_block_csum_verify(journal_t *j, void *buf) +{ + struct jbd2_journal_block_tail *tail; + __be32 provided; + __u32 calculated; + + if (!jbd2_journal_has_csum_v2or3(j)) + return 1; + + tail = (struct jbd2_journal_block_tail *)((char *)buf + + j->j_blocksize - sizeof(struct jbd2_journal_block_tail)); + provided = tail->t_checksum; + tail->t_checksum = 0; + calculated = jbd2_chksum(j, j->j_csum_seed, buf, j->j_blocksize); + tail->t_checksum = provided; + + return provided == cpu_to_be32(calculated); +} + +/* + * Count the number of in-use tags in a journal descriptor block. + */ + +static int count_tags(journal_t *journal, struct buffer_head *bh) +{ + char * tagp; + journal_block_tag_t tag; + int nr = 0, size = journal->j_blocksize; + int tag_bytes = journal_tag_bytes(journal); + + if (jbd2_journal_has_csum_v2or3(journal)) + size -= sizeof(struct jbd2_journal_block_tail); + + tagp = &bh->b_data[sizeof(journal_header_t)]; + + while ((tagp - bh->b_data + tag_bytes) <= size) { + memcpy(&tag, tagp, sizeof(tag)); + + nr++; + tagp += tag_bytes; + if (!(tag.t_flags & cpu_to_be16(JBD2_FLAG_SAME_UUID))) + tagp += 16; + + if (tag.t_flags & cpu_to_be16(JBD2_FLAG_LAST_TAG)) + break; + } + + return nr; +} + + +/* Make sure we wrap around the log correctly! */ +#define wrap(journal, var) \ +do { \ + unsigned long _wrap_last = \ + jbd2_has_feature_fast_commit(journal) ? \ + (journal)->j_fc_last : (journal)->j_last; \ + \ + if (var >= _wrap_last) \ + var -= (_wrap_last - (journal)->j_first); \ +} while (0) + +static int fc_do_one_pass(journal_t *journal, + struct recovery_info *info, enum passtype pass) +{ + unsigned int expected_commit_id = info->end_transaction; + unsigned long next_fc_block; + struct buffer_head *bh; + int err = 0; + + next_fc_block = journal->j_fc_first; + if (!journal->j_fc_replay_callback) + return 0; + + while (next_fc_block <= journal->j_fc_last) { + jbd_debug(3, "Fast commit replay: next block %ld\n", + next_fc_block); + err = jread(&bh, journal, next_fc_block); + if (err) { + jbd_debug(3, "Fast commit replay: read error\n"); + break; + } + + err = journal->j_fc_replay_callback(journal, bh, pass, + next_fc_block - journal->j_fc_first, + expected_commit_id); + next_fc_block++; + if (err < 0 || err == JBD2_FC_REPLAY_STOP) + break; + err = 0; + } + + if (err) + jbd_debug(3, "Fast commit replay failed, err = %d\n", err); + + return err; +} + +/** + * jbd2_journal_recover - recovers a on-disk journal + * @journal: the journal to recover + * + * The primary function for recovering the log contents when mounting a + * journaled device. + * + * Recovery is done in three passes. In the first pass, we look for the + * end of the log. In the second, we assemble the list of revoke + * blocks. In the third and final pass, we replay any un-revoked blocks + * in the log. + */ +int jbd2_journal_recover(journal_t *journal) +{ + int err, err2; + journal_superblock_t * sb; + + struct recovery_info info; + + memset(&info, 0, sizeof(info)); + sb = journal->j_superblock; + + /* + * The journal superblock's s_start field (the current log head) + * is always zero if, and only if, the journal was cleanly + * unmounted. + */ + + if (!sb->s_start) { + jbd_debug(1, "No recovery required, last transaction %d\n", + be32_to_cpu(sb->s_sequence)); + journal->j_transaction_sequence = be32_to_cpu(sb->s_sequence) + 1; + return 0; + } + + err = do_one_pass(journal, &info, PASS_SCAN); + if (!err) + err = do_one_pass(journal, &info, PASS_REVOKE); + if (!err) + err = do_one_pass(journal, &info, PASS_REPLAY); + + jbd_debug(1, "JBD2: recovery, exit status %d, " + "recovered transactions %u to %u\n", + err, info.start_transaction, info.end_transaction); + jbd_debug(1, "JBD2: Replayed %d and revoked %d/%d blocks\n", + info.nr_replays, info.nr_revoke_hits, info.nr_revokes); + + /* Restart the log at the next transaction ID, thus invalidating + * any existing commit records in the log. */ + journal->j_transaction_sequence = ++info.end_transaction; + + jbd2_journal_clear_revoke(journal); + err2 = sync_blockdev(journal->j_fs_dev); + if (!err) + err = err2; + /* Make sure all replayed data is on permanent storage */ + if (journal->j_flags & JBD2_BARRIER) { + err2 = blkdev_issue_flush(journal->j_fs_dev); + if (!err) + err = err2; + } + return err; +} + +/** + * jbd2_journal_skip_recovery - Start journal and wipe exiting records + * @journal: journal to startup + * + * Locate any valid recovery information from the journal and set up the + * journal structures in memory to ignore it (presumably because the + * caller has evidence that it is out of date). + * This function doesn't appear to be exported.. + * + * We perform one pass over the journal to allow us to tell the user how + * much recovery information is being erased, and to let us initialise + * the journal transaction sequence numbers to the next unused ID. + */ +int jbd2_journal_skip_recovery(journal_t *journal) +{ + int err; + + struct recovery_info info; + + memset (&info, 0, sizeof(info)); + + err = do_one_pass(journal, &info, PASS_SCAN); + + if (err) { + printk(KERN_ERR "JBD2: error %d scanning journal\n", err); + ++journal->j_transaction_sequence; + } else { +#ifdef CONFIG_JBD2_DEBUG + int dropped = info.end_transaction - + be32_to_cpu(journal->j_superblock->s_sequence); + jbd_debug(1, + "JBD2: ignoring %d transaction%s from the journal.\n", + dropped, (dropped == 1) ? "" : "s"); +#endif + journal->j_transaction_sequence = ++info.end_transaction; + } + + journal->j_tail = 0; + return err; +} + +static inline unsigned long long read_tag_block(journal_t *journal, + journal_block_tag_t *tag) +{ + unsigned long long block = be32_to_cpu(tag->t_blocknr); + if (jbd2_has_feature_64bit(journal)) + block |= (u64)be32_to_cpu(tag->t_blocknr_high) << 32; + return block; +} + +/* + * calc_chksums calculates the checksums for the blocks described in the + * descriptor block. + */ +static int calc_chksums(journal_t *journal, struct buffer_head *bh, + unsigned long *next_log_block, __u32 *crc32_sum) +{ + int i, num_blks, err; + unsigned long io_block; + struct buffer_head *obh; + + num_blks = count_tags(journal, bh); + /* Calculate checksum of the descriptor block. */ + *crc32_sum = crc32_be(*crc32_sum, (void *)bh->b_data, bh->b_size); + + for (i = 0; i < num_blks; i++) { + io_block = (*next_log_block)++; + wrap(journal, *next_log_block); + err = jread(&obh, journal, io_block); + if (err) { + printk(KERN_ERR "JBD2: IO error %d recovering block " + "%lu in log\n", err, io_block); + return 1; + } else { + *crc32_sum = crc32_be(*crc32_sum, (void *)obh->b_data, + obh->b_size); + } + put_bh(obh); + } + return 0; +} + +static int jbd2_commit_block_csum_verify(journal_t *j, void *buf) +{ + struct commit_header *h; + __be32 provided; + __u32 calculated; + + if (!jbd2_journal_has_csum_v2or3(j)) + return 1; + + h = buf; + provided = h->h_chksum[0]; + h->h_chksum[0] = 0; + calculated = jbd2_chksum(j, j->j_csum_seed, buf, j->j_blocksize); + h->h_chksum[0] = provided; + + return provided == cpu_to_be32(calculated); +} + +static int jbd2_block_tag_csum_verify(journal_t *j, journal_block_tag_t *tag, + journal_block_tag3_t *tag3, + void *buf, __u32 sequence) +{ + __u32 csum32; + __be32 seq; + + if (!jbd2_journal_has_csum_v2or3(j)) + return 1; + + seq = cpu_to_be32(sequence); + csum32 = jbd2_chksum(j, j->j_csum_seed, (__u8 *)&seq, sizeof(seq)); + csum32 = jbd2_chksum(j, csum32, buf, j->j_blocksize); + + if (jbd2_has_feature_csum3(j)) + return tag3->t_checksum == cpu_to_be32(csum32); + else + return tag->t_checksum == cpu_to_be16(csum32); +} + +static int do_one_pass(journal_t *journal, + struct recovery_info *info, enum passtype pass) +{ + unsigned int first_commit_ID, next_commit_ID; + unsigned long next_log_block; + int err, success = 0; + journal_superblock_t * sb; + journal_header_t * tmp; + struct buffer_head * bh; + unsigned int sequence; + int blocktype; + int tag_bytes = journal_tag_bytes(journal); + __u32 crc32_sum = ~0; /* Transactional Checksums */ + int descr_csum_size = 0; + int block_error = 0; + bool need_check_commit_time = false; + __u64 last_trans_commit_time = 0, commit_time; + + /* + * First thing is to establish what we expect to find in the log + * (in terms of transaction IDs), and where (in terms of log + * block offsets): query the superblock. + */ + + sb = journal->j_superblock; + next_commit_ID = be32_to_cpu(sb->s_sequence); + next_log_block = be32_to_cpu(sb->s_start); + + first_commit_ID = next_commit_ID; + if (pass == PASS_SCAN) + info->start_transaction = first_commit_ID; + + jbd_debug(1, "Starting recovery pass %d\n", pass); + + /* + * Now we walk through the log, transaction by transaction, + * making sure that each transaction has a commit block in the + * expected place. Each complete transaction gets replayed back + * into the main filesystem. + */ + + while (1) { + int flags; + char * tagp; + journal_block_tag_t tag; + struct buffer_head * obh; + struct buffer_head * nbh; + + cond_resched(); + + /* If we already know where to stop the log traversal, + * check right now that we haven't gone past the end of + * the log. */ + + if (pass != PASS_SCAN) + if (tid_geq(next_commit_ID, info->end_transaction)) + break; + + jbd_debug(2, "Scanning for sequence ID %u at %lu/%lu\n", + next_commit_ID, next_log_block, + jbd2_has_feature_fast_commit(journal) ? + journal->j_fc_last : journal->j_last); + + /* Skip over each chunk of the transaction looking + * either the next descriptor block or the final commit + * record. */ + + jbd_debug(3, "JBD2: checking block %ld\n", next_log_block); + err = jread(&bh, journal, next_log_block); + if (err) + goto failed; + + next_log_block++; + wrap(journal, next_log_block); + + /* What kind of buffer is it? + * + * If it is a descriptor block, check that it has the + * expected sequence number. Otherwise, we're all done + * here. */ + + tmp = (journal_header_t *)bh->b_data; + + if (tmp->h_magic != cpu_to_be32(JBD2_MAGIC_NUMBER)) { + brelse(bh); + break; + } + + blocktype = be32_to_cpu(tmp->h_blocktype); + sequence = be32_to_cpu(tmp->h_sequence); + jbd_debug(3, "Found magic %d, sequence %d\n", + blocktype, sequence); + + if (sequence != next_commit_ID) { + brelse(bh); + break; + } + + /* OK, we have a valid descriptor block which matches + * all of the sequence number checks. What are we going + * to do with it? That depends on the pass... */ + + switch(blocktype) { + case JBD2_DESCRIPTOR_BLOCK: + /* Verify checksum first */ + if (jbd2_journal_has_csum_v2or3(journal)) + descr_csum_size = + sizeof(struct jbd2_journal_block_tail); + if (descr_csum_size > 0 && + !jbd2_descriptor_block_csum_verify(journal, + bh->b_data)) { + /* + * PASS_SCAN can see stale blocks due to lazy + * journal init. Don't error out on those yet. + */ + if (pass != PASS_SCAN) { + pr_err("JBD2: Invalid checksum recovering block %lu in log\n", + next_log_block); + err = -EFSBADCRC; + brelse(bh); + goto failed; + } + need_check_commit_time = true; + jbd_debug(1, + "invalid descriptor block found in %lu\n", + next_log_block); + } + + /* If it is a valid descriptor block, replay it + * in pass REPLAY; if journal_checksums enabled, then + * calculate checksums in PASS_SCAN, otherwise, + * just skip over the blocks it describes. */ + if (pass != PASS_REPLAY) { + if (pass == PASS_SCAN && + jbd2_has_feature_checksum(journal) && + !need_check_commit_time && + !info->end_transaction) { + if (calc_chksums(journal, bh, + &next_log_block, + &crc32_sum)) { + put_bh(bh); + break; + } + put_bh(bh); + continue; + } + next_log_block += count_tags(journal, bh); + wrap(journal, next_log_block); + put_bh(bh); + continue; + } + + /* A descriptor block: we can now write all of + * the data blocks. Yay, useful work is finally + * getting done here! */ + + tagp = &bh->b_data[sizeof(journal_header_t)]; + while ((tagp - bh->b_data + tag_bytes) + <= journal->j_blocksize - descr_csum_size) { + unsigned long io_block; + + memcpy(&tag, tagp, sizeof(tag)); + flags = be16_to_cpu(tag.t_flags); + + io_block = next_log_block++; + wrap(journal, next_log_block); + err = jread(&obh, journal, io_block); + if (err) { + /* Recover what we can, but + * report failure at the end. */ + success = err; + printk(KERN_ERR + "JBD2: IO error %d recovering " + "block %ld in log\n", + err, io_block); + } else { + unsigned long long blocknr; + + J_ASSERT(obh != NULL); + blocknr = read_tag_block(journal, + &tag); + + /* If the block has been + * revoked, then we're all done + * here. */ + if (jbd2_journal_test_revoke + (journal, blocknr, + next_commit_ID)) { + brelse(obh); + ++info->nr_revoke_hits; + goto skip_write; + } + + /* Look for block corruption */ + if (!jbd2_block_tag_csum_verify( + journal, &tag, (journal_block_tag3_t *)tagp, + obh->b_data, be32_to_cpu(tmp->h_sequence))) { + brelse(obh); + success = -EFSBADCRC; + printk(KERN_ERR "JBD2: Invalid " + "checksum recovering " + "data block %llu in " + "log\n", blocknr); + block_error = 1; + goto skip_write; + } + + /* Find a buffer for the new + * data being restored */ + nbh = __getblk(journal->j_fs_dev, + blocknr, + journal->j_blocksize); + if (nbh == NULL) { + printk(KERN_ERR + "JBD2: Out of memory " + "during recovery.\n"); + err = -ENOMEM; + brelse(bh); + brelse(obh); + goto failed; + } + + lock_buffer(nbh); + memcpy(nbh->b_data, obh->b_data, + journal->j_blocksize); + if (flags & JBD2_FLAG_ESCAPE) { + *((__be32 *)nbh->b_data) = + cpu_to_be32(JBD2_MAGIC_NUMBER); + } + + BUFFER_TRACE(nbh, "marking dirty"); + set_buffer_uptodate(nbh); + mark_buffer_dirty(nbh); + BUFFER_TRACE(nbh, "marking uptodate"); + ++info->nr_replays; + /* ll_rw_block(WRITE, 1, &nbh); */ + unlock_buffer(nbh); + brelse(obh); + brelse(nbh); + } + + skip_write: + tagp += tag_bytes; + if (!(flags & JBD2_FLAG_SAME_UUID)) + tagp += 16; + + if (flags & JBD2_FLAG_LAST_TAG) + break; + } + + brelse(bh); + continue; + + case JBD2_COMMIT_BLOCK: + /* How to differentiate between interrupted commit + * and journal corruption ? + * + * {nth transaction} + * Checksum Verification Failed + * | + * ____________________ + * | | + * async_commit sync_commit + * | | + * | GO TO NEXT "Journal Corruption" + * | TRANSACTION + * | + * {(n+1)th transanction} + * | + * _______|______________ + * | | + * Commit block found Commit block not found + * | | + * "Journal Corruption" | + * _____________|_________ + * | | + * nth trans corrupt OR nth trans + * and (n+1)th interrupted interrupted + * before commit block + * could reach the disk. + * (Cannot find the difference in above + * mentioned conditions. Hence assume + * "Interrupted Commit".) + */ + commit_time = be64_to_cpu( + ((struct commit_header *)bh->b_data)->h_commit_sec); + /* + * If need_check_commit_time is set, it means we are in + * PASS_SCAN and csum verify failed before. If + * commit_time is increasing, it's the same journal, + * otherwise it is stale journal block, just end this + * recovery. + */ + if (need_check_commit_time) { + if (commit_time >= last_trans_commit_time) { + pr_err("JBD2: Invalid checksum found in transaction %u\n", + next_commit_ID); + err = -EFSBADCRC; + brelse(bh); + goto failed; + } + ignore_crc_mismatch: + /* + * It likely does not belong to same journal, + * just end this recovery with success. + */ + jbd_debug(1, "JBD2: Invalid checksum ignored in transaction %u, likely stale data\n", + next_commit_ID); + brelse(bh); + goto done; + } + + /* + * Found an expected commit block: if checksums + * are present, verify them in PASS_SCAN; else not + * much to do other than move on to the next sequence + * number. + */ + if (pass == PASS_SCAN && + jbd2_has_feature_checksum(journal)) { + struct commit_header *cbh = + (struct commit_header *)bh->b_data; + unsigned found_chksum = + be32_to_cpu(cbh->h_chksum[0]); + + if (info->end_transaction) { + journal->j_failed_commit = + info->end_transaction; + brelse(bh); + break; + } + + /* Neither checksum match nor unused? */ + if (!((crc32_sum == found_chksum && + cbh->h_chksum_type == + JBD2_CRC32_CHKSUM && + cbh->h_chksum_size == + JBD2_CRC32_CHKSUM_SIZE) || + (cbh->h_chksum_type == 0 && + cbh->h_chksum_size == 0 && + found_chksum == 0))) + goto chksum_error; + + crc32_sum = ~0; + } + if (pass == PASS_SCAN && + !jbd2_commit_block_csum_verify(journal, + bh->b_data)) { + chksum_error: + if (commit_time < last_trans_commit_time) + goto ignore_crc_mismatch; + info->end_transaction = next_commit_ID; + + if (!jbd2_has_feature_async_commit(journal)) { + journal->j_failed_commit = + next_commit_ID; + brelse(bh); + break; + } + } + if (pass == PASS_SCAN) + last_trans_commit_time = commit_time; + brelse(bh); + next_commit_ID++; + continue; + + case JBD2_REVOKE_BLOCK: + /* + * Check revoke block crc in pass_scan, if csum verify + * failed, check commit block time later. + */ + if (pass == PASS_SCAN && + !jbd2_descriptor_block_csum_verify(journal, + bh->b_data)) { + jbd_debug(1, "JBD2: invalid revoke block found in %lu\n", + next_log_block); + need_check_commit_time = true; + } + /* If we aren't in the REVOKE pass, then we can + * just skip over this block. */ + if (pass != PASS_REVOKE) { + brelse(bh); + continue; + } + + err = scan_revoke_records(journal, bh, + next_commit_ID, info); + brelse(bh); + if (err) + goto failed; + continue; + + default: + jbd_debug(3, "Unrecognised magic %d, end of scan.\n", + blocktype); + brelse(bh); + goto done; + } + } + + done: + /* + * We broke out of the log scan loop: either we came to the + * known end of the log or we found an unexpected block in the + * log. If the latter happened, then we know that the "current" + * transaction marks the end of the valid log. + */ + + if (pass == PASS_SCAN) { + if (!info->end_transaction) + info->end_transaction = next_commit_ID; + } else { + /* It's really bad news if different passes end up at + * different places (but possible due to IO errors). */ + if (info->end_transaction != next_commit_ID) { + printk(KERN_ERR "JBD2: recovery pass %d ended at " + "transaction %u, expected %u\n", + pass, next_commit_ID, info->end_transaction); + if (!success) + success = -EIO; + } + } + + if (jbd2_has_feature_fast_commit(journal) && pass != PASS_REVOKE) { + err = fc_do_one_pass(journal, info, pass); + if (err) + success = err; + } + + if (block_error && success == 0) + success = -EIO; + return success; + + failed: + return err; +} + +/* Scan a revoke record, marking all blocks mentioned as revoked. */ + +static int scan_revoke_records(journal_t *journal, struct buffer_head *bh, + tid_t sequence, struct recovery_info *info) +{ + jbd2_journal_revoke_header_t *header; + int offset, max; + unsigned csum_size = 0; + __u32 rcount; + int record_len = 4; + + header = (jbd2_journal_revoke_header_t *) bh->b_data; + offset = sizeof(jbd2_journal_revoke_header_t); + rcount = be32_to_cpu(header->r_count); + + if (jbd2_journal_has_csum_v2or3(journal)) + csum_size = sizeof(struct jbd2_journal_block_tail); + if (rcount > journal->j_blocksize - csum_size) + return -EINVAL; + max = rcount; + + if (jbd2_has_feature_64bit(journal)) + record_len = 8; + + while (offset + record_len <= max) { + unsigned long long blocknr; + int err; + + if (record_len == 4) + blocknr = be32_to_cpu(* ((__be32 *) (bh->b_data+offset))); + else + blocknr = be64_to_cpu(* ((__be64 *) (bh->b_data+offset))); + offset += record_len; + err = jbd2_journal_set_revoke(journal, blocknr, sequence); + if (err) + return err; + ++info->nr_revokes; + } + return 0; +} diff --git a/e2fsck/region.c b/e2fsck/region.c new file mode 100644 index 0000000..698f7bd --- /dev/null +++ b/e2fsck/region.c @@ -0,0 +1,236 @@ +/* + * region.c --- code which manages allocations within a region. + * + * Copyright (C) 2001 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#if HAVE_UNISTD_H +#include <unistd.h> +#endif +#include <string.h> + +#ifdef TEST_PROGRAM +#undef ENABLE_NLS +#endif +#include "e2fsck.h" + +struct region_el { + region_addr_t start; + region_addr_t end; + struct region_el *next; +}; + +struct region_struct { + region_addr_t min; + region_addr_t max; + struct region_el *allocated; + struct region_el *last; +}; + +region_t region_create(region_addr_t min, region_addr_t max) +{ + region_t region; + errcode_t retval; + + retval = ext2fs_get_memzero(sizeof(struct region_struct), ®ion); + if (retval) + return NULL; + + region->min = min; + region->max = max; + region->last = NULL; + return region; +} + +void region_free(region_t region) +{ + struct region_el *r, *next; + + for (r = region->allocated; r; r = next) { + next = r->next; + ext2fs_free_mem(&r); + } + memset(region, 0, sizeof(struct region_struct)); + ext2fs_free_mem(®ion); +} + +int region_allocate(region_t region, region_addr_t start, int n) +{ + struct region_el *r, *new_region, *prev, *next; + region_addr_t end; + errcode_t retval; + + end = start+n; + if ((start < region->min) || (end > region->max)) + return -1; + if (n == 0) + return 1; + + if (region->last && region->last->end == start && + !region->last->next) { + region->last->end = end; + return 0; + } + if (region->last && start > region->last->end && + !region->last->next) { + r = NULL; + prev = region->last; + goto append_to_list; + } + + /* + * Search through the linked list. If we find that it + * conflicts with something that's already allocated, return + * 1; if we can find an existing region which we can grow, do + * so. Otherwise, stop when we find the appropriate place + * insert a new region element into the linked list. + */ + for (r = region->allocated, prev=NULL; r; prev = r, r = r->next) { + if (((start >= r->start) && (start < r->end)) || + ((end > r->start) && (end <= r->end)) || + ((start <= r->start) && (end >= r->end))) + return 1; + if (end == r->start) { + r->start = start; + return 0; + } + if (start == r->end) { + if ((next = r->next)) { + if (end > next->start) + return 1; + if (end == next->start) { + r->end = next->end; + r->next = next->next; + ext2fs_free_mem(&next); + if (!r->next) + region->last = r; + return 0; + } + } + r->end = end; + return 0; + } + if (start < r->start) + break; + } + /* + * Insert a new region element structure into the linked list + */ +append_to_list: + retval = ext2fs_get_mem(sizeof(struct region_el), &new_region); + if (retval) + return -1; + new_region->start = start; + new_region->end = start + n; + new_region->next = r; + if (!new_region->next) + region->last = new_region; + if (prev) + prev->next = new_region; + else + region->allocated = new_region; + return 0; +} + +#ifdef TEST_PROGRAM +#include <stdio.h> + +#define BCODE_END 0 +#define BCODE_CREATE 1 +#define BCODE_FREE 2 +#define BCODE_ALLOCATE 3 +#define BCODE_PRINT 4 + +int bcode_program[] = { + BCODE_CREATE, 1, 1001, + BCODE_PRINT, + BCODE_ALLOCATE, 10, 10, + BCODE_ALLOCATE, 30, 10, + BCODE_PRINT, + BCODE_ALLOCATE, 1, 15, + BCODE_ALLOCATE, 15, 8, + BCODE_ALLOCATE, 1, 20, + BCODE_ALLOCATE, 1, 8, + BCODE_PRINT, + BCODE_ALLOCATE, 40, 10, + BCODE_PRINT, + BCODE_ALLOCATE, 22, 5, + BCODE_PRINT, + BCODE_ALLOCATE, 27, 3, + BCODE_PRINT, + BCODE_ALLOCATE, 20, 2, + BCODE_PRINT, + BCODE_ALLOCATE, 49, 1, + BCODE_ALLOCATE, 50, 5, + BCODE_ALLOCATE, 9, 2, + BCODE_ALLOCATE, 9, 1, + BCODE_PRINT, + BCODE_FREE, + BCODE_END +}; + +void region_print(region_t region, FILE *f) +{ + struct region_el *r; + int i = 0; + + fprintf(f, "Printing region (min=%llu. max=%llu)\n\t", + (unsigned long long) region->min, + (unsigned long long) region->max); + for (r = region->allocated; r; r = r->next) { + fprintf(f, "(%llu, %llu) ", + (unsigned long long) r->start, + (unsigned long long) r->end); + if (++i >= 8) + fprintf(f, "\n\t"); + } + fprintf(f, "\n"); +} + +int main(int argc, char **argv) +{ + region_t r = NULL; + int pc = 0, ret; + region_addr_t start, end; + + + while (1) { + switch (bcode_program[pc++]) { + case BCODE_END: + exit(0); + case BCODE_CREATE: + start = bcode_program[pc++]; + end = bcode_program[pc++]; + printf("Creating region with args(%llu, %llu)\n", + (unsigned long long) start, + (unsigned long long) end); + r = region_create(start, end); + if (!r) { + fprintf(stderr, "Couldn't create region.\n"); + exit(1); + } + break; + case BCODE_ALLOCATE: + start = bcode_program[pc++]; + end = bcode_program[pc++]; + ret = region_allocate(r, start, end); + printf("Region_allocate(%llu, %llu) returns %d\n", + (unsigned long long) start, + (unsigned long long) end, ret); + break; + case BCODE_PRINT: + region_print(r, stdout); + break; + } + } + if (r) + region_free(r); +} + +#endif /* TEST_PROGRAM */ diff --git a/e2fsck/rehash.c b/e2fsck/rehash.c new file mode 100644 index 0000000..c1da7d5 --- /dev/null +++ b/e2fsck/rehash.c @@ -0,0 +1,1189 @@ +/* + * rehash.c --- rebuild hash tree directories + * + * Copyright (C) 2002 Theodore Ts'o + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + * + * This algorithm is designed for simplicity of implementation and to + * pack the directory as much as possible. It however requires twice + * as much memory as the size of the directory. The maximum size + * directory supported using a 4k blocksize is roughly a gigabyte, and + * so there may very well be problems with machines that don't have + * virtual memory, and obscenely large directories. + * + * An alternate algorithm which is much more disk intensive could be + * written, and probably will need to be written in the future. The + * design goals of such an algorithm are: (a) use (roughly) constant + * amounts of memory, no matter how large the directory, (b) the + * directory must be safe at all times, even if e2fsck is interrupted + * in the middle, (c) we must use minimal amounts of extra disk + * blocks. This pretty much requires an incremental approach, where + * we are reading from one part of the directory, and inserting into + * the front half. So the algorithm will have to keep track of a + * moving block boundary between the new tree and the old tree, and + * files will need to be moved from the old directory and inserted + * into the new tree. If the new directory requires space which isn't + * yet available, blocks from the beginning part of the old directory + * may need to be moved to the end of the directory to make room for + * the new tree: + * + * -------------------------------------------------------- + * | new tree | | old tree | + * -------------------------------------------------------- + * ^ ptr ^ptr + * tail new head old + * + * This is going to be a pain in the tuckus to implement, and will + * require a lot more disk accesses. So I'm going to skip it for now; + * it's only really going to be an issue for really, really big + * filesystems (when we reach the level of tens of millions of files + * in a single directory). It will probably be easier to simply + * require that e2fsck use VM first. + */ + +#include "config.h" +#include <string.h> +#include <ctype.h> +#include <errno.h> +#include "e2fsck.h" +#include "problem.h" +#include "support/sort_r.h" + +/* Schedule a dir to be rebuilt during pass 3A. */ +void e2fsck_rehash_dir_later(e2fsck_t ctx, ext2_ino_t ino) +{ + if (!ctx->dirs_to_hash) + ext2fs_u32_list_create(&ctx->dirs_to_hash, 50); + if (ctx->dirs_to_hash) + ext2fs_u32_list_add(ctx->dirs_to_hash, ino); +} + +/* Ask if a dir will be rebuilt during pass 3A. */ +int e2fsck_dir_will_be_rehashed(e2fsck_t ctx, ext2_ino_t ino) +{ + if (ctx->options & E2F_OPT_COMPRESS_DIRS) + return 1; + if (!ctx->dirs_to_hash) + return 0; + return ext2fs_u32_list_test(ctx->dirs_to_hash, ino); +} + +#undef REHASH_DEBUG + +struct fill_dir_struct { + char *buf; + struct ext2_inode *inode; + ext2_ino_t ino; + errcode_t err; + e2fsck_t ctx; + struct hash_entry *harray; + blk_t max_array, num_array; + ext2_off64_t dir_size; + int compress; + ext2_ino_t parent; + ext2_ino_t dir; +}; + +struct hash_entry { + ext2_dirhash_t hash; + ext2_dirhash_t minor_hash; + ext2_ino_t ino; + struct ext2_dir_entry *dir; +}; + +struct out_dir { + blk_t num; + blk_t max; + char *buf; + ext2_dirhash_t *hashes; +}; + +#define DOTDOT_OFFSET 12 + +static int is_fake_entry(ext2_filsys fs, int lblk, unsigned int offset) +{ + /* Entries in the first block before this value refer to . or .. */ + if (lblk == 0 && offset <= DOTDOT_OFFSET) + return 1; + /* Check if this is likely the csum entry */ + if (ext2fs_has_feature_metadata_csum(fs->super) && + (offset & (fs->blocksize - 1)) == + fs->blocksize - sizeof(struct ext2_dir_entry_tail)) + return 1; + return 0; +} + +static int fill_dir_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct fill_dir_struct *fd = (struct fill_dir_struct *) priv_data; + struct hash_entry *ent; + struct ext2_dir_entry *dirent; + char *dir; + unsigned int offset, dir_offset, rec_len, name_len; + int hash_alg, hash_flags, hash_in_entry; + + if (blockcnt < 0) + return 0; + + offset = blockcnt * fs->blocksize; + if (offset + fs->blocksize > fd->inode->i_size) { + fd->err = EXT2_ET_DIR_CORRUPTED; + return BLOCK_ABORT; + } + + dir = (fd->buf+offset); + if (*block_nr == 0) { + memset(dir, 0, fs->blocksize); + dirent = (struct ext2_dir_entry *) dir; + (void) ext2fs_set_rec_len(fs, fs->blocksize, dirent); + } else { + int flags = fs->flags; + fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + fd->err = ext2fs_read_dir_block4(fs, *block_nr, dir, 0, + fd->dir); + fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + if (fd->err) + return BLOCK_ABORT; + } + hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL; + hash_in_entry = ext4_hash_in_dirent(fd->inode); + hash_alg = fs->super->s_def_hash_version; + if ((hash_alg <= EXT2_HASH_TEA) && + (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH)) + hash_alg += 3; + /* While the directory block is "hot", index it. */ + dir_offset = 0; + while (dir_offset < fs->blocksize) { + unsigned int min_rec = EXT2_DIR_ENTRY_HEADER_LEN; + int extended = hash_in_entry && !is_fake_entry(fs, blockcnt, dir_offset); + + if (extended) + min_rec += EXT2_DIR_ENTRY_HASH_LEN; + dirent = (struct ext2_dir_entry *) (dir + dir_offset); + (void) ext2fs_get_rec_len(fs, dirent, &rec_len); + name_len = ext2fs_dirent_name_len(dirent); + if (((dir_offset + rec_len) > fs->blocksize) || + (rec_len < min_rec) || + ((rec_len % 4) != 0) || + (name_len + min_rec > rec_len)) { + fd->err = EXT2_ET_DIR_CORRUPTED; + return BLOCK_ABORT; + } + dir_offset += rec_len; + if (dirent->inode == 0) + continue; + if ((name_len) == 0) { + fd->err = EXT2_ET_DIR_CORRUPTED; + return BLOCK_ABORT; + } + if (!fd->compress && (name_len == 1) && + (dirent->name[0] == '.')) + continue; + if (!fd->compress && (name_len == 2) && + (dirent->name[0] == '.') && (dirent->name[1] == '.')) { + fd->parent = dirent->inode; + continue; + } + if (fd->num_array >= fd->max_array) { + errcode_t retval; + + retval = ext2fs_resize_array(sizeof(struct hash_entry), + fd->max_array, + fd->max_array + 500, + &fd->harray); + if (retval) { + fd->err = retval; + return BLOCK_ABORT; + } + fd->max_array += 500; + } + ent = fd->harray + fd->num_array++; + ent->dir = dirent; + fd->dir_size += ext2fs_dir_rec_len(name_len, extended); + ent->ino = dirent->inode; + if (extended) { + ent->hash = EXT2_DIRENT_HASH(dirent); + ent->minor_hash = EXT2_DIRENT_MINOR_HASH(dirent); + } else if (fd->compress) { + ent->hash = ent->minor_hash = 0; + } else { + fd->err = ext2fs_dirhash2(hash_alg, + dirent->name, name_len, + fs->encoding, hash_flags, + fs->super->s_hash_seed, + &ent->hash, &ent->minor_hash); + if (fd->err) + return BLOCK_ABORT; + } + } + + return 0; +} + +/* Used for sorting the hash entry */ +static EXT2_QSORT_TYPE ino_cmp(const void *a, const void *b) +{ + const struct hash_entry *he_a = (const struct hash_entry *) a; + const struct hash_entry *he_b = (const struct hash_entry *) b; + + return (he_a->ino - he_b->ino); +} + +struct name_cmp_ctx +{ + int casefold; + const struct ext2fs_nls_table *tbl; +}; + +static int same_name(const struct name_cmp_ctx *cmp_ctx, char *s1, + int len1, char *s2, int len2) +{ + if (!cmp_ctx->casefold) + return (len1 == len2 && !memcmp(s1, s2, len1)); + else + return !ext2fs_casefold_cmp(cmp_ctx->tbl, + (unsigned char *) s1, len1, + (unsigned char *) s2, len2); +} + +/* Used for sorting the hash entry */ +static EXT2_QSORT_TYPE name_cmp(const void *a, const void *b) +{ + const struct hash_entry *he_a = (const struct hash_entry *) a; + const struct hash_entry *he_b = (const struct hash_entry *) b; + unsigned int he_a_len, he_b_len, min_len; + int ret; + + he_a_len = ext2fs_dirent_name_len(he_a->dir); + he_b_len = ext2fs_dirent_name_len(he_b->dir); + min_len = he_a_len; + if (min_len > he_b_len) + min_len = he_b_len; + + ret = memcmp(he_a->dir->name, he_b->dir->name, min_len); + if (ret == 0) { + if (he_a_len > he_b_len) + ret = 1; + else if (he_a_len < he_b_len) + ret = -1; + else + ret = he_b->dir->inode - he_a->dir->inode; + } + return ret; +} + +static EXT2_QSORT_TYPE name_cf_cmp(const struct name_cmp_ctx *ctx, + const void *a, const void *b) +{ + const struct hash_entry *he_a = (const struct hash_entry *) a; + const struct hash_entry *he_b = (const struct hash_entry *) b; + unsigned int he_a_len, he_b_len; + int ret; + + he_a_len = ext2fs_dirent_name_len(he_a->dir); + he_b_len = ext2fs_dirent_name_len(he_b->dir); + + ret = ext2fs_casefold_cmp(ctx->tbl, + (unsigned char *) he_a->dir->name, he_a_len, + (unsigned char *) he_b->dir->name, he_b_len); + if (ret == 0) { + if (he_a_len > he_b_len) + ret = 1; + else if (he_a_len < he_b_len) + ret = -1; + else + ret = he_b->dir->inode - he_a->dir->inode; + } + return ret; +} + +/* Used for sorting the hash entry */ +static EXT2_QSORT_TYPE hash_cmp(const void *a, const void *b, void *arg) +{ + const struct name_cmp_ctx *ctx = (struct name_cmp_ctx *) arg; + const struct hash_entry *he_a = (const struct hash_entry *) a; + const struct hash_entry *he_b = (const struct hash_entry *) b; + int ret; + + if (he_a->hash > he_b->hash) + ret = 1; + else if (he_a->hash < he_b->hash) + ret = -1; + else { + if (he_a->minor_hash > he_b->minor_hash) + ret = 1; + else if (he_a->minor_hash < he_b->minor_hash) + ret = -1; + else { + if (ctx->casefold) + ret = name_cf_cmp(ctx, a, b); + else + ret = name_cmp(a, b); + } + } + return ret; +} + +static errcode_t alloc_size_dir(ext2_filsys fs, struct out_dir *outdir, + blk_t blocks) +{ + errcode_t retval; + + if (outdir->max) { + retval = ext2fs_resize_array(fs->blocksize, outdir->max, blocks, + &outdir->buf); + if (retval) + return retval; + retval = ext2fs_resize_array(sizeof(ext2_dirhash_t), + outdir->max, blocks, + &outdir->hashes); + if (retval) + return retval; + } else { + retval = ext2fs_get_array(fs->blocksize, blocks, &outdir->buf); + if (retval) + return retval; + retval = ext2fs_get_array(sizeof(ext2_dirhash_t), blocks, + &outdir->hashes); + if (retval) + return retval; + outdir->num = 0; + } + outdir->max = blocks; + return 0; +} + +static void free_out_dir(struct out_dir *outdir) +{ + free(outdir->buf); + free(outdir->hashes); + outdir->max = 0; + outdir->num =0; +} + +static errcode_t get_next_block(ext2_filsys fs, struct out_dir *outdir, + char ** ret) +{ + errcode_t retval; + + if (outdir->num >= outdir->max) { + int increment = outdir->max / 10; + + if (increment < 50) + increment = 50; + retval = alloc_size_dir(fs, outdir, outdir->max + increment); + if (retval) + return retval; + } + *ret = outdir->buf + (size_t)outdir->num++ * fs->blocksize; + memset(*ret, 0, fs->blocksize); + return 0; +} + +/* + * This function is used to make a unique filename. We do this by + * appending ~0, and then incrementing the number. However, we cannot + * expand the length of the filename beyond the padding available in + * the directory entry. + */ +static void mutate_name(char *str, unsigned int *len) +{ + int i; + unsigned int l = *len; + + /* + * First check to see if it looks the name has been mutated + * already + */ + for (i = l-1; i > 0; i--) { + if (!isdigit(str[i])) + break; + } + if ((i == (int)l - 1) || (str[i] != '~')) { + if (((l-1) & 3) < 2) + l += 2; + else + l = (l+3) & ~3; + if (l > 255) + l = 255; + str[l-2] = '~'; + str[l-1] = '0'; + *len = l; + return; + } + for (i = l-1; i >= 0; i--) { + if (isdigit(str[i])) { + if (str[i] == '9') + str[i] = '0'; + else { + str[i]++; + return; + } + continue; + } + if (i == 1) { + if (str[0] == 'z') + str[0] = 'A'; + else if (str[0] == 'Z') { + str[0] = '~'; + str[1] = '0'; + } else + str[0]++; + } else if (i > 0) { + str[i] = '1'; + str[i-1] = '~'; + } else { + if (str[0] == '~') + str[0] = 'a'; + else + str[0]++; + } + break; + } +} + +static int duplicate_search_and_fix(e2fsck_t ctx, ext2_filsys fs, + ext2_ino_t ino, + struct fill_dir_struct *fd, + const struct name_cmp_ctx *cmp_ctx) +{ + struct problem_context pctx; + struct hash_entry *ent, *prev; + blk_t i, j; + int fixed = 0; + char new_name[256]; + unsigned int new_len; + int hash_alg; + int hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL; + + clear_problem_context(&pctx); + pctx.ino = ino; + + hash_alg = fs->super->s_def_hash_version; + if ((hash_alg <= EXT2_HASH_TEA) && + (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH)) + hash_alg += 3; + + for (i=1; i < fd->num_array; i++) { + ent = fd->harray + i; + prev = ent - 1; + if (!ent->dir->inode || + !same_name(cmp_ctx, ent->dir->name, + ext2fs_dirent_name_len(ent->dir), + prev->dir->name, + ext2fs_dirent_name_len(prev->dir))) + continue; + pctx.dirent = ent->dir; + if ((ent->dir->inode == prev->dir->inode) && + fix_problem(ctx, PR_2_DUPLICATE_DIRENT, &pctx)) { + e2fsck_adjust_inode_count(ctx, ent->dir->inode, -1); + ent->dir->inode = 0; + fixed++; + continue; + } + /* Can't alter encrypted name without key, so just drop it */ + if (fd->inode->i_flags & EXT4_ENCRYPT_FL) { + if (fix_problem(ctx, PR_2_NON_UNIQUE_FILE_NO_RENAME, &pctx)) { + e2fsck_adjust_inode_count(ctx, ent->dir->inode, -1); + ent->dir->inode = 0; + fixed++; + continue; + } + } + new_len = ext2fs_dirent_name_len(ent->dir); + if (new_len == 0) { + /* should never happen */ + ext2fs_unmark_valid(fs); + continue; + } + memcpy(new_name, ent->dir->name, new_len); + mutate_name(new_name, &new_len); + for (j=0; j < fd->num_array; j++) { + if ((i==j) || + !same_name(cmp_ctx, new_name, new_len, + fd->harray[j].dir->name, + ext2fs_dirent_name_len(fd->harray[j].dir))) { + continue; + } + mutate_name(new_name, &new_len); + + j = -1; + } + new_name[new_len] = 0; + pctx.str = new_name; + if (fix_problem(ctx, PR_2_NON_UNIQUE_FILE, &pctx)) { + memcpy(ent->dir->name, new_name, new_len); + ext2fs_dirent_set_name_len(ent->dir, new_len); + ext2fs_dirhash2(hash_alg, new_name, new_len, + fs->encoding, hash_flags, + fs->super->s_hash_seed, + &ent->hash, &ent->minor_hash); + fixed++; + } + } + return fixed; +} + + +static errcode_t copy_dir_entries(e2fsck_t ctx, + struct fill_dir_struct *fd, + struct out_dir *outdir) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + char *block_start; + struct hash_entry *ent; + struct ext2_dir_entry *dirent; + unsigned int rec_len, prev_rec_len, left, slack, offset; + blk_t i; + ext2_dirhash_t prev_hash; + int csum_size = 0; + struct ext2_dir_entry_tail *t; + int hash_in_entry = ext4_hash_in_dirent(fd->inode); + unsigned int min_rec_len = ext2fs_dir_rec_len(1, hash_in_entry); + + if (ctx->htree_slack_percentage == 255) { + profile_get_uint(ctx->profile, "options", + "indexed_dir_slack_percentage", + 0, 20, + &ctx->htree_slack_percentage); + if (ctx->htree_slack_percentage > 100) + ctx->htree_slack_percentage = 20; + } + + if (ext2fs_has_feature_metadata_csum(fs->super)) + csum_size = sizeof(struct ext2_dir_entry_tail); + + outdir->max = 0; + retval = alloc_size_dir(fs, outdir, + (fd->dir_size / fs->blocksize) + 2); + if (retval) + return retval; + outdir->num = fd->compress ? 0 : 1; + offset = 0; + outdir->hashes[0] = 0; + prev_hash = 1; + if ((retval = get_next_block(fs, outdir, &block_start))) + return retval; + dirent = (struct ext2_dir_entry *) block_start; + prev_rec_len = 0; + rec_len = 0; + left = fs->blocksize - csum_size; + slack = fd->compress ? min_rec_len : + ((fs->blocksize - csum_size) * ctx->htree_slack_percentage)/100; + if (slack < min_rec_len) + slack = min_rec_len; + for (i = 0; i < fd->num_array; i++) { + ent = fd->harray + i; + if (ent->dir->inode == 0) + continue; + rec_len = ext2fs_dir_rec_len(ext2fs_dirent_name_len(ent->dir), + hash_in_entry); + if (rec_len > left) { + if (left) { + left += prev_rec_len; + retval = ext2fs_set_rec_len(fs, left, dirent); + if (retval) + return retval; + } + if (csum_size) { + t = EXT2_DIRENT_TAIL(block_start, + fs->blocksize); + ext2fs_initialize_dirent_tail(fs, t); + } + if ((retval = get_next_block(fs, outdir, + &block_start))) + return retval; + offset = 0; + } + left = (fs->blocksize - csum_size) - offset; + dirent = (struct ext2_dir_entry *) (block_start + offset); + if (offset == 0) { + if (ent->hash == prev_hash) + outdir->hashes[outdir->num-1] = ent->hash | 1; + else + outdir->hashes[outdir->num-1] = ent->hash; + } + dirent->inode = ent->dir->inode; + ext2fs_dirent_set_name_len(dirent, + ext2fs_dirent_name_len(ent->dir)); + ext2fs_dirent_set_file_type(dirent, + ext2fs_dirent_file_type(ent->dir)); + retval = ext2fs_set_rec_len(fs, rec_len, dirent); + if (retval) + return retval; + prev_rec_len = rec_len; + memcpy(dirent->name, ent->dir->name, + ext2fs_dirent_name_len(dirent)); + if (hash_in_entry) { + EXT2_DIRENT_HASHES(dirent)->hash = ext2fs_cpu_to_le32(ent->hash); + EXT2_DIRENT_HASHES(dirent)->minor_hash = + ext2fs_cpu_to_le32(ent->minor_hash); + } + offset += rec_len; + left -= rec_len; + if (left < slack) { + prev_rec_len += left; + retval = ext2fs_set_rec_len(fs, prev_rec_len, dirent); + if (retval) + return retval; + offset += left; + left = 0; + } + prev_hash = ent->hash; + } + if (left) + retval = ext2fs_set_rec_len(fs, rec_len + left, dirent); + if (csum_size) { + t = EXT2_DIRENT_TAIL(block_start, fs->blocksize); + ext2fs_initialize_dirent_tail(fs, t); + } + + return retval; +} + + +static struct ext2_dx_root_info *set_root_node(ext2_filsys fs, char *buf, + ext2_ino_t ino, ext2_ino_t parent, + struct ext2_inode *inode) +{ + struct ext2_dir_entry *dir; + struct ext2_dx_root_info *root; + struct ext2_dx_countlimit *limits; + int filetype = 0; + int csum_size = 0; + + if (ext2fs_has_feature_filetype(fs->super)) + filetype = EXT2_FT_DIR; + + memset(buf, 0, fs->blocksize); + dir = (struct ext2_dir_entry *) buf; + dir->inode = ino; + dir->name[0] = '.'; + ext2fs_dirent_set_name_len(dir, 1); + ext2fs_dirent_set_file_type(dir, filetype); + dir->rec_len = 12; + dir = (struct ext2_dir_entry *) (buf + 12); + dir->inode = parent; + dir->name[0] = '.'; + dir->name[1] = '.'; + ext2fs_dirent_set_name_len(dir, 2); + ext2fs_dirent_set_file_type(dir, filetype); + dir->rec_len = fs->blocksize - 12; + + root = (struct ext2_dx_root_info *) (buf+24); + root->reserved_zero = 0; + if (ext4_hash_in_dirent(inode)) + root->hash_version = EXT2_HASH_SIPHASH; + else + root->hash_version = fs->super->s_def_hash_version; + root->info_length = 8; + root->indirect_levels = 0; + root->unused_flags = 0; + + if (ext2fs_has_feature_metadata_csum(fs->super)) + csum_size = sizeof(struct ext2_dx_tail); + + limits = (struct ext2_dx_countlimit *) (buf+32); + limits->limit = (fs->blocksize - (32 + csum_size)) / + sizeof(struct ext2_dx_entry); + limits->count = 0; + + return root; +} + + +static struct ext2_dx_entry *set_int_node(ext2_filsys fs, char *buf) +{ + struct ext2_dir_entry *dir; + struct ext2_dx_countlimit *limits; + int csum_size = 0; + + memset(buf, 0, fs->blocksize); + dir = (struct ext2_dir_entry *) buf; + dir->inode = 0; + (void) ext2fs_set_rec_len(fs, fs->blocksize, dir); + + if (ext2fs_has_feature_metadata_csum(fs->super)) + csum_size = sizeof(struct ext2_dx_tail); + + limits = (struct ext2_dx_countlimit *) (buf+8); + limits->limit = (fs->blocksize - (8 + csum_size)) / + sizeof(struct ext2_dx_entry); + limits->count = 0; + + return (struct ext2_dx_entry *) limits; +} + +static int alloc_blocks(ext2_filsys fs, + struct ext2_dx_countlimit **limit, + struct ext2_dx_entry **prev_ent, + struct ext2_dx_entry **next_ent, + int *prev_offset, int *next_offset, + struct out_dir *outdir, int i, + int *prev_count, int *next_count) +{ + errcode_t retval; + char *block_start; + + if (*limit) + (*limit)->limit = (*limit)->count = + ext2fs_cpu_to_le16((*limit)->limit); + *prev_ent = (struct ext2_dx_entry *) (outdir->buf + *prev_offset); + (*prev_ent)->block = ext2fs_cpu_to_le32(outdir->num); + + if (i != 1) + (*prev_ent)->hash = + ext2fs_cpu_to_le32(outdir->hashes[i]); + + retval = get_next_block(fs, outdir, &block_start); + if (retval) + return retval; + + /* outdir->buf might be reallocated */ + *prev_ent = (struct ext2_dx_entry *) (outdir->buf + *prev_offset); + + *next_ent = set_int_node(fs, block_start); + *limit = (struct ext2_dx_countlimit *)(*next_ent); + if (next_offset) + *next_offset = ((char *) *next_ent - outdir->buf); + + *next_count = (*limit)->limit; + (*prev_offset) += sizeof(struct ext2_dx_entry); + (*prev_count)--; + + return 0; +} + +/* + * This function takes the leaf nodes which have been written in + * outdir, and populates the root node and any necessary interior nodes. + */ +static errcode_t calculate_tree(ext2_filsys fs, + struct out_dir *outdir, + ext2_ino_t ino, + ext2_ino_t parent, + struct ext2_inode *inode) +{ + struct ext2_dx_root_info *root_info; + struct ext2_dx_entry *root, *int_ent, *dx_ent = 0; + struct ext2_dx_countlimit *root_limit, *int_limit, *limit; + errcode_t retval; + int i, c1, c2, c3, nblks; + int limit_offset, int_offset, root_offset; + + root_info = set_root_node(fs, outdir->buf, ino, parent, inode); + root_offset = limit_offset = ((char *) root_info - outdir->buf) + + root_info->info_length; + root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset); + c1 = root_limit->limit; + nblks = outdir->num; + + /* Write out the pointer blocks */ + if (nblks - 1 <= c1) { + /* Just write out the root block, and we're done */ + root = (struct ext2_dx_entry *) (outdir->buf + root_offset); + for (i=1; i < nblks; i++) { + root->block = ext2fs_cpu_to_le32(i); + if (i != 1) + root->hash = + ext2fs_cpu_to_le32(outdir->hashes[i]); + root++; + c1--; + } + } else if (nblks - 1 <= ext2fs_htree_intnode_maxrecs(fs, c1)) { + c2 = 0; + limit = NULL; + root_info->indirect_levels = 1; + for (i=1; i < nblks; i++) { + if (c2 == 0 && c1 == 0) + return ENOSPC; + if (c2 == 0) { + retval = alloc_blocks(fs, &limit, &root, + &dx_ent, &root_offset, + NULL, outdir, i, &c1, + &c2); + if (retval) + return retval; + } + dx_ent->block = ext2fs_cpu_to_le32(i); + if (c2 != limit->limit) + dx_ent->hash = + ext2fs_cpu_to_le32(outdir->hashes[i]); + dx_ent++; + c2--; + } + limit->count = ext2fs_cpu_to_le16(limit->limit - c2); + limit->limit = ext2fs_cpu_to_le16(limit->limit); + } else { + c2 = 0; + c3 = 0; + limit = NULL; + int_limit = 0; + root_info->indirect_levels = 2; + for (i = 1; i < nblks; i++) { + if (c3 == 0 && c2 == 0 && c1 == 0) + return ENOSPC; + if (c3 == 0 && c2 == 0) { + retval = alloc_blocks(fs, &int_limit, &root, + &int_ent, &root_offset, + &int_offset, outdir, i, + &c1, &c2); + if (retval) + return retval; + } + if (c3 == 0) { + int delta1 = (char *)int_limit - outdir->buf; + int delta2 = (char *)root - outdir->buf; + + retval = alloc_blocks(fs, &limit, &int_ent, + &dx_ent, &int_offset, + NULL, outdir, i, &c2, + &c3); + if (retval) + return retval; + + /* outdir->buf might be reallocated */ + int_limit = (struct ext2_dx_countlimit *) + (outdir->buf + delta1); + root = (struct ext2_dx_entry *) + (outdir->buf + delta2); + } + dx_ent->block = ext2fs_cpu_to_le32(i); + if (c3 != limit->limit) + dx_ent->hash = + ext2fs_cpu_to_le32(outdir->hashes[i]); + dx_ent++; + c3--; + } + int_limit->count = ext2fs_cpu_to_le16(limit->limit - c2); + int_limit->limit = ext2fs_cpu_to_le16(limit->limit); + + limit->count = ext2fs_cpu_to_le16(limit->limit - c3); + limit->limit = ext2fs_cpu_to_le16(limit->limit); + + } + root_limit = (struct ext2_dx_countlimit *) (outdir->buf + limit_offset); + root_limit->count = ext2fs_cpu_to_le16(root_limit->limit - c1); + root_limit->limit = ext2fs_cpu_to_le16(root_limit->limit); + + return 0; +} + +struct write_dir_struct { + struct out_dir *outdir; + errcode_t err; + ext2_ino_t ino; + e2fsck_t ctx; + ext2_ino_t dir; +}; + +/* + * Helper function which writes out a directory block. + */ +static int write_dir_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_block EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct write_dir_struct *wd = (struct write_dir_struct *) priv_data; + char *dir, *buf = 0; + +#ifdef REHASH_DEBUG + printf("%u: write_dir_block %lld:%lld", wd->ino, blockcnt, *block_nr); +#endif + if ((*block_nr == 0) || (blockcnt < 0)) { +#ifdef REHASH_DEBUG + printf(" - skip\n"); +#endif + return 0; + } + if (blockcnt < wd->outdir->num) + dir = wd->outdir->buf + (blockcnt * fs->blocksize); + else if (wd->ctx->lost_and_found == wd->dir) { + /* Don't release any extra directory blocks for lost+found */ + wd->err = ext2fs_new_dir_block(fs, 0, 0, &buf); + if (wd->err) + return BLOCK_ABORT; + dir = buf; + wd->outdir->num++; + } else { + /* Don't free blocks at the end of the directory, they + * will be truncated by the caller. */ +#ifdef REHASH_DEBUG + printf(" - not freed\n"); +#endif + return 0; + } + wd->err = ext2fs_write_dir_block4(fs, *block_nr, dir, 0, wd->dir); + if (buf) + ext2fs_free_mem(&buf); + +#ifdef REHASH_DEBUG + printf(" - write (%d)\n", wd->err); +#endif + if (wd->err) + return BLOCK_ABORT; + return 0; +} + +static errcode_t write_directory(e2fsck_t ctx, ext2_filsys fs, + struct out_dir *outdir, + ext2_ino_t ino, struct ext2_inode *inode, + int compress) +{ + struct write_dir_struct wd; + errcode_t retval; + + retval = e2fsck_expand_directory(ctx, ino, -1, outdir->num); + if (retval) + return retval; + + wd.outdir = outdir; + wd.err = 0; + wd.ino = ino; + wd.ctx = ctx; + wd.dir = ino; + + retval = ext2fs_block_iterate3(fs, ino, 0, NULL, + write_dir_block, &wd); + if (retval) + return retval; + if (wd.err) + return wd.err; + + e2fsck_read_inode(ctx, ino, inode, "rehash_dir"); + if (compress) + inode->i_flags &= ~EXT2_INDEX_FL; + else + inode->i_flags |= EXT2_INDEX_FL; +#ifdef REHASH_DEBUG + printf("%u: set inode size to %u blocks = %u bytes\n", + ino, outdir->num, outdir->num * fs->blocksize); +#endif + retval = ext2fs_inode_size_set(fs, inode, (ext2_off64_t)outdir->num * + fs->blocksize); + if (retval) + return retval; + + /* ext2fs_punch() calls ext2fs_write_inode() which writes the size */ + return ext2fs_punch(fs, ino, inode, NULL, outdir->num, ~0ULL); +} + +errcode_t e2fsck_rehash_dir(e2fsck_t ctx, ext2_ino_t ino, + struct problem_context *pctx) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + struct ext2_inode inode; + char *dir_buf = 0; + struct fill_dir_struct fd = { NULL, NULL, 0, 0, 0, NULL, + 0, 0, 0, 0, 0, 0 }; + struct out_dir outdir = { 0, 0, 0, 0 }; + struct name_cmp_ctx name_cmp_ctx = {0, NULL}; + + e2fsck_read_inode(ctx, ino, &inode, "rehash_dir"); + + if (ext2fs_has_feature_inline_data(fs->super) && + (inode.i_flags & EXT4_INLINE_DATA_FL)) + return 0; + + retval = ext2fs_get_mem(inode.i_size, &dir_buf); + if (retval) + goto errout; + + fd.max_array = inode.i_size / 32; + retval = ext2fs_get_array(sizeof(struct hash_entry), + fd.max_array, &fd.harray); + if (retval) + goto errout; + + fd.ino = ino; + fd.ctx = ctx; + fd.buf = dir_buf; + fd.inode = &inode; + fd.dir = ino; + if (!ext2fs_has_feature_dir_index(fs->super) || + (inode.i_size / fs->blocksize) < 2) + fd.compress = 1; + fd.parent = 0; + + if (fs->encoding && (inode.i_flags & EXT4_CASEFOLD_FL)) { + name_cmp_ctx.casefold = 1; + name_cmp_ctx.tbl = fs->encoding; + } + +retry_nohash: + /* Read in the entire directory into memory */ + retval = ext2fs_block_iterate3(fs, ino, 0, 0, + fill_dir_block, &fd); + if (fd.err) { + retval = fd.err; + goto errout; + } + + /* + * If the entries read are less than a block, then don't index + * the directory + */ + if (!fd.compress && (fd.dir_size < (fs->blocksize - 24))) { + fd.compress = 1; + fd.dir_size = 0; + fd.num_array = 0; + goto retry_nohash; + } + +#if 0 + printf("%d entries (%d bytes) found in inode %d\n", + fd.num_array, fd.dir_size, ino); +#endif + + /* Sort the list */ +resort: + if (fd.compress && fd.num_array > 1) + sort_r(fd.harray+2, fd.num_array-2, sizeof(struct hash_entry), + hash_cmp, &name_cmp_ctx); + else + sort_r(fd.harray, fd.num_array, sizeof(struct hash_entry), + hash_cmp, &name_cmp_ctx); + + /* + * Look for duplicates + */ + if (duplicate_search_and_fix(ctx, fs, ino, &fd, &name_cmp_ctx)) + goto resort; + + if (ctx->options & E2F_OPT_NO) { + retval = 0; + goto errout; + } + + /* Sort non-hashed directories by inode number */ + if (fd.compress && fd.num_array > 1) + qsort(fd.harray+2, fd.num_array-2, + sizeof(struct hash_entry), ino_cmp); + + /* + * Copy the directory entries. In a htree directory these + * will become the leaf nodes. + */ + retval = copy_dir_entries(ctx, &fd, &outdir); + if (retval) + goto errout; + + free(dir_buf); dir_buf = 0; + + if (!fd.compress) { + /* Calculate the interior nodes */ + retval = calculate_tree(fs, &outdir, ino, fd.parent, fd.inode); + if (retval) + goto errout; + } + + retval = write_directory(ctx, fs, &outdir, ino, &inode, fd.compress); + if (retval) + goto errout; + + if (ctx->options & E2F_OPT_CONVERT_BMAP) + retval = e2fsck_rebuild_extents_later(ctx, ino); + else + retval = e2fsck_check_rebuild_extents(ctx, ino, &inode, pctx); +errout: + ext2fs_free_mem(&dir_buf); + ext2fs_free_mem(&fd.harray); + + free_out_dir(&outdir); + return retval; +} + +void e2fsck_rehash_directories(e2fsck_t ctx) +{ + struct problem_context pctx; +#ifdef RESOURCE_TRACK + struct resource_track rtrack; +#endif + struct dir_info *dir; + ext2_u32_iterate iter; + struct dir_info_iter * dirinfo_iter = 0; + ext2_ino_t ino; + errcode_t retval; + int cur, max, all_dirs, first = 1; + + init_resource_track(&rtrack, ctx->fs->io); + all_dirs = ctx->options & E2F_OPT_COMPRESS_DIRS; + + if (!ctx->dirs_to_hash && !all_dirs) + return; + + (void) e2fsck_get_lost_and_found(ctx, 0); + + clear_problem_context(&pctx); + + cur = 0; + if (all_dirs) { + dirinfo_iter = e2fsck_dir_info_iter_begin(ctx); + max = e2fsck_get_num_dirinfo(ctx); + } else { + retval = ext2fs_u32_list_iterate_begin(ctx->dirs_to_hash, + &iter); + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_3A_OPTIMIZE_ITER, &pctx); + return; + } + max = ext2fs_u32_list_count(ctx->dirs_to_hash); + } + while (1) { + if (all_dirs) { + if ((dir = e2fsck_dir_info_iter(ctx, + dirinfo_iter)) == 0) + break; + ino = dir->ino; + } else { + if (!ext2fs_u32_list_iterate(iter, &ino)) + break; + } + if (!ext2fs_test_inode_bitmap2(ctx->inode_dir_map, ino)) + continue; + + pctx.dir = ino; + if (first) { + fix_problem(ctx, PR_3A_PASS_HEADER, &pctx); + first = 0; + } +#if 0 + fix_problem(ctx, PR_3A_OPTIMIZE_DIR, &pctx); +#endif + pctx.errcode = e2fsck_rehash_dir(ctx, ino, &pctx); + if (pctx.errcode) { + end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR); + fix_problem(ctx, PR_3A_OPTIMIZE_DIR_ERR, &pctx); + } + if (ctx->progress && !ctx->progress_fd) + e2fsck_simple_progress(ctx, "Rebuilding directory", + 100.0 * (float) (++cur) / (float) max, ino); + } + end_problem_latch(ctx, PR_LATCH_OPTIMIZE_DIR); + if (all_dirs) + e2fsck_dir_info_iter_end(ctx, dirinfo_iter); + else + ext2fs_u32_list_iterate_end(iter); + + if (ctx->dirs_to_hash) + ext2fs_u32_list_free(ctx->dirs_to_hash); + ctx->dirs_to_hash = 0; + + print_resource_track(ctx, "Pass 3A", &rtrack, ctx->fs->io); +} diff --git a/e2fsck/revoke.c b/e2fsck/revoke.c new file mode 100644 index 0000000..fa60878 --- /dev/null +++ b/e2fsck/revoke.c @@ -0,0 +1,743 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * linux/fs/jbd2/revoke.c + * + * Written by Stephen C. Tweedie <sct@redhat.com>, 2000 + * + * Copyright 2000 Red Hat corp --- All Rights Reserved + * + * Journal revoke routines for the generic filesystem journaling code; + * part of the ext2fs journaling system. + * + * Revoke is the mechanism used to prevent old log records for deleted + * metadata from being replayed on top of newer data using the same + * blocks. The revoke mechanism is used in two separate places: + * + * + Commit: during commit we write the entire list of the current + * transaction's revoked blocks to the journal + * + * + Recovery: during recovery we record the transaction ID of all + * revoked blocks. If there are multiple revoke records in the log + * for a single block, only the last one counts, and if there is a log + * entry for a block beyond the last revoke, then that log entry still + * gets replayed. + * + * We can get interactions between revokes and new log data within a + * single transaction: + * + * Block is revoked and then journaled: + * The desired end result is the journaling of the new block, so we + * cancel the revoke before the transaction commits. + * + * Block is journaled and then revoked: + * The revoke must take precedence over the write of the block, so we + * need either to cancel the journal entry or to write the revoke + * later in the log than the log block. In this case, we choose the + * latter: journaling a block cancels any revoke record for that block + * in the current transaction, so any revoke for that block in the + * transaction must have happened after the block was journaled and so + * the revoke must take precedence. + * + * Block is revoked and then written as data: + * The data write is allowed to succeed, but the revoke is _not_ + * cancelled. We still need to prevent old log records from + * overwriting the new data. We don't even need to clear the revoke + * bit here. + * + * We cache revoke status of a buffer in the current transaction in b_states + * bits. As the name says, revokevalid flag indicates that the cached revoke + * status of a buffer is valid and we can rely on the cached status. + * + * Revoke information on buffers is a tri-state value: + * + * RevokeValid clear: no cached revoke status, need to look it up + * RevokeValid set, Revoked clear: + * buffer has not been revoked, and cancel_revoke + * need do nothing. + * RevokeValid set, Revoked set: + * buffer has been revoked. + * + * Locking rules: + * We keep two hash tables of revoke records. One hashtable belongs to the + * running transaction (is pointed to by journal->j_revoke), the other one + * belongs to the committing transaction. Accesses to the second hash table + * happen only from the kjournald and no other thread touches this table. Also + * journal_switch_revoke_table() which switches which hashtable belongs to the + * running and which to the committing transaction is called only from + * kjournald. Therefore we need no locks when accessing the hashtable belonging + * to the committing transaction. + * + * All users operating on the hash table belonging to the running transaction + * have a handle to the transaction. Therefore they are safe from kjournald + * switching hash tables under them. For operations on the lists of entries in + * the hash table j_revoke_lock is used. + * + * Finally, also replay code uses the hash tables but at this moment no one else + * can touch them (filesystem isn't mounted yet) and hence no locking is + * needed. + */ + +#ifndef __KERNEL__ +#include "jfs_user.h" +#else +#include <linux/time.h> +#include <linux/fs.h> +#include <linux/jbd2.h> +#include <linux/errno.h> +#include <linux/slab.h> +#include <linux/list.h> +#include <linux/init.h> +#include <linux/bio.h> +#include <linux/log2.h> +#include <linux/hash.h> +#endif + +static struct kmem_cache *jbd2_revoke_record_cache; +static struct kmem_cache *jbd2_revoke_table_cache; + +/* Each revoke record represents one single revoked block. During + journal replay, this involves recording the transaction ID of the + last transaction to revoke this block. */ + +struct jbd2_revoke_record_s +{ + struct list_head hash; + tid_t sequence; /* Used for recovery only */ + unsigned long long blocknr; +}; + + +/* The revoke table is just a simple hash table of revoke records. */ +struct jbd2_revoke_table_s +{ + /* It is conceivable that we might want a larger hash table + * for recovery. Must be a power of two. */ + int hash_size; + int hash_shift; + struct list_head *hash_table; +}; + + +#ifdef __KERNEL__ +static void write_one_revoke_record(transaction_t *, + struct list_head *, + struct buffer_head **, int *, + struct jbd2_revoke_record_s *); +static void flush_descriptor(journal_t *, struct buffer_head *, int); +#endif + +/* Utility functions to maintain the revoke table */ + +static inline int hash(journal_t *journal, unsigned long long block) +{ + return hash_64(block, journal->j_revoke->hash_shift); +} + +static int insert_revoke_hash(journal_t *journal, unsigned long long blocknr, + tid_t seq) +{ + struct list_head *hash_list; + struct jbd2_revoke_record_s *record; + gfp_t gfp_mask = GFP_NOFS; + + if (journal_oom_retry) + gfp_mask |= __GFP_NOFAIL; + record = kmem_cache_alloc(jbd2_revoke_record_cache, gfp_mask); + if (!record) + return -ENOMEM; + + record->sequence = seq; + record->blocknr = blocknr; + hash_list = &journal->j_revoke->hash_table[hash(journal, blocknr)]; + spin_lock(&journal->j_revoke_lock); + list_add(&record->hash, hash_list); + spin_unlock(&journal->j_revoke_lock); + return 0; +} + +/* Find a revoke record in the journal's hash table. */ + +static struct jbd2_revoke_record_s *find_revoke_record(journal_t *journal, + unsigned long long blocknr) +{ + struct list_head *hash_list; + struct jbd2_revoke_record_s *record; + + hash_list = &journal->j_revoke->hash_table[hash(journal, blocknr)]; + + spin_lock(&journal->j_revoke_lock); + record = (struct jbd2_revoke_record_s *) hash_list->next; + while (&(record->hash) != hash_list) { + if (record->blocknr == blocknr) { + spin_unlock(&journal->j_revoke_lock); + return record; + } + record = (struct jbd2_revoke_record_s *) record->hash.next; + } + spin_unlock(&journal->j_revoke_lock); + return NULL; +} + +void jbd2_journal_destroy_revoke_record_cache(void) +{ + kmem_cache_destroy(jbd2_revoke_record_cache); + jbd2_revoke_record_cache = NULL; +} + +void jbd2_journal_destroy_revoke_table_cache(void) +{ + kmem_cache_destroy(jbd2_revoke_table_cache); + jbd2_revoke_table_cache = NULL; +} + +int __init jbd2_journal_init_revoke_record_cache(void) +{ + J_ASSERT(!jbd2_revoke_record_cache); + jbd2_revoke_record_cache = KMEM_CACHE(jbd2_revoke_record_s, + SLAB_HWCACHE_ALIGN|SLAB_TEMPORARY); + + if (!jbd2_revoke_record_cache) { + pr_emerg("JBD2: failed to create revoke_record cache\n"); + return -ENOMEM; + } + return 0; +} + +int __init jbd2_journal_init_revoke_table_cache(void) +{ + J_ASSERT(!jbd2_revoke_table_cache); + jbd2_revoke_table_cache = KMEM_CACHE(jbd2_revoke_table_s, + SLAB_TEMPORARY); + if (!jbd2_revoke_table_cache) { + pr_emerg("JBD2: failed to create revoke_table cache\n"); + return -ENOMEM; + } + return 0; +} + +static struct jbd2_revoke_table_s *jbd2_journal_init_revoke_table(int hash_size) +{ + int shift = 0; + int tmp = hash_size; + struct jbd2_revoke_table_s *table; + + table = kmem_cache_alloc(jbd2_revoke_table_cache, GFP_KERNEL); + if (!table) + goto out; + + while((tmp >>= 1UL) != 0UL) + shift++; + + table->hash_size = hash_size; + table->hash_shift = shift; + table->hash_table = + kmalloc_array(hash_size, sizeof(struct list_head), GFP_KERNEL); + if (!table->hash_table) { + kmem_cache_free(jbd2_revoke_table_cache, table); + table = NULL; + goto out; + } + + for (tmp = 0; tmp < hash_size; tmp++) + INIT_LIST_HEAD(&table->hash_table[tmp]); + +out: + return table; +} + +static void jbd2_journal_destroy_revoke_table(struct jbd2_revoke_table_s *table) +{ + int i; + struct list_head *hash_list; + + for (i = 0; i < table->hash_size; i++) { + hash_list = &table->hash_table[i]; + J_ASSERT(list_empty(hash_list)); + } + + kfree(table->hash_table); + kmem_cache_free(jbd2_revoke_table_cache, table); +} + +/* Initialise the revoke table for a given journal to a given size. */ +int jbd2_journal_init_revoke(journal_t *journal, int hash_size) +{ + J_ASSERT(journal->j_revoke_table[0] == NULL); + J_ASSERT(is_power_of_2(hash_size)); + + journal->j_revoke_table[0] = jbd2_journal_init_revoke_table(hash_size); + if (!journal->j_revoke_table[0]) + goto fail0; + + journal->j_revoke_table[1] = jbd2_journal_init_revoke_table(hash_size); + if (!journal->j_revoke_table[1]) + goto fail1; + + journal->j_revoke = journal->j_revoke_table[1]; + + spin_lock_init(&journal->j_revoke_lock); + + return 0; + +fail1: + jbd2_journal_destroy_revoke_table(journal->j_revoke_table[0]); + journal->j_revoke_table[0] = NULL; +fail0: + return -ENOMEM; +} + +/* Destroy a journal's revoke table. The table must already be empty! */ +void jbd2_journal_destroy_revoke(journal_t *journal) +{ + journal->j_revoke = NULL; + if (journal->j_revoke_table[0]) + jbd2_journal_destroy_revoke_table(journal->j_revoke_table[0]); + if (journal->j_revoke_table[1]) + jbd2_journal_destroy_revoke_table(journal->j_revoke_table[1]); +} + + +#ifdef __KERNEL__ + +/* + * jbd2_journal_revoke: revoke a given buffer_head from the journal. This + * prevents the block from being replayed during recovery if we take a + * crash after this current transaction commits. Any subsequent + * metadata writes of the buffer in this transaction cancel the + * revoke. + * + * Note that this call may block --- it is up to the caller to make + * sure that there are no further calls to journal_write_metadata + * before the revoke is complete. In ext3, this implies calling the + * revoke before clearing the block bitmap when we are deleting + * metadata. + * + * Revoke performs a jbd2_journal_forget on any buffer_head passed in as a + * parameter, but does _not_ forget the buffer_head if the bh was only + * found implicitly. + * + * bh_in may not be a journalled buffer - it may have come off + * the hash tables without an attached journal_head. + * + * If bh_in is non-zero, jbd2_journal_revoke() will decrement its b_count + * by one. + */ + +int jbd2_journal_revoke(handle_t *handle, unsigned long long blocknr, + struct buffer_head *bh_in) +{ + struct buffer_head *bh = NULL; + journal_t *journal; + struct block_device *bdev; + int err; + + might_sleep(); + if (bh_in) + BUFFER_TRACE(bh_in, "enter"); + + journal = handle->h_transaction->t_journal; + if (!jbd2_journal_set_features(journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)){ + J_ASSERT (!"Cannot set revoke feature!"); + return -EINVAL; + } + + bdev = journal->j_fs_dev; + bh = bh_in; + + if (!bh) { + bh = __find_get_block(bdev, blocknr, journal->j_blocksize); + if (bh) + BUFFER_TRACE(bh, "found on hash"); + } +#ifdef JBD2_EXPENSIVE_CHECKING + else { + struct buffer_head *bh2; + + /* If there is a different buffer_head lying around in + * memory anywhere... */ + bh2 = __find_get_block(bdev, blocknr, journal->j_blocksize); + if (bh2) { + /* ... and it has RevokeValid status... */ + if (bh2 != bh && buffer_revokevalid(bh2)) + /* ...then it better be revoked too, + * since it's illegal to create a revoke + * record against a buffer_head which is + * not marked revoked --- that would + * risk missing a subsequent revoke + * cancel. */ + J_ASSERT_BH(bh2, buffer_revoked(bh2)); + put_bh(bh2); + } + } +#endif + + if (WARN_ON_ONCE(handle->h_revoke_credits <= 0)) { + if (!bh_in) + brelse(bh); + return -EIO; + } + /* We really ought not ever to revoke twice in a row without + first having the revoke cancelled: it's illegal to free a + block twice without allocating it in between! */ + if (bh) { + if (!J_EXPECT_BH(bh, !buffer_revoked(bh), + "inconsistent data on disk")) { + if (!bh_in) + brelse(bh); + return -EIO; + } + set_buffer_revoked(bh); + set_buffer_revokevalid(bh); + if (bh_in) { + BUFFER_TRACE(bh_in, "call jbd2_journal_forget"); + jbd2_journal_forget(handle, bh_in); + } else { + BUFFER_TRACE(bh, "call brelse"); + __brelse(bh); + } + } + handle->h_revoke_credits--; + + jbd_debug(2, "insert revoke for block %llu, bh_in=%p\n",blocknr, bh_in); + err = insert_revoke_hash(journal, blocknr, + handle->h_transaction->t_tid); + BUFFER_TRACE(bh_in, "exit"); + return err; +} + +/* + * Cancel an outstanding revoke. For use only internally by the + * journaling code (called from jbd2_journal_get_write_access). + * + * We trust buffer_revoked() on the buffer if the buffer is already + * being journaled: if there is no revoke pending on the buffer, then we + * don't do anything here. + * + * This would break if it were possible for a buffer to be revoked and + * discarded, and then reallocated within the same transaction. In such + * a case we would have lost the revoked bit, but when we arrived here + * the second time we would still have a pending revoke to cancel. So, + * do not trust the Revoked bit on buffers unless RevokeValid is also + * set. + */ +int jbd2_journal_cancel_revoke(handle_t *handle, struct journal_head *jh) +{ + struct jbd2_revoke_record_s *record; + journal_t *journal = handle->h_transaction->t_journal; + int need_cancel; + int did_revoke = 0; /* akpm: debug */ + struct buffer_head *bh = jh2bh(jh); + + jbd_debug(4, "journal_head %p, cancelling revoke\n", jh); + + /* Is the existing Revoke bit valid? If so, we trust it, and + * only perform the full cancel if the revoke bit is set. If + * not, we can't trust the revoke bit, and we need to do the + * full search for a revoke record. */ + if (test_set_buffer_revokevalid(bh)) { + need_cancel = test_clear_buffer_revoked(bh); + } else { + need_cancel = 1; + clear_buffer_revoked(bh); + } + + if (need_cancel) { + record = find_revoke_record(journal, bh->b_blocknr); + if (record) { + jbd_debug(4, "cancelled existing revoke on " + "blocknr %llu\n", (unsigned long long)bh->b_blocknr); + spin_lock(&journal->j_revoke_lock); + list_del(&record->hash); + spin_unlock(&journal->j_revoke_lock); + kmem_cache_free(jbd2_revoke_record_cache, record); + did_revoke = 1; + } + } + +#ifdef JBD2_EXPENSIVE_CHECKING + /* There better not be one left behind by now! */ + record = find_revoke_record(journal, bh->b_blocknr); + J_ASSERT_JH(jh, record == NULL); +#endif + + /* Finally, have we just cleared revoke on an unhashed + * buffer_head? If so, we'd better make sure we clear the + * revoked status on any hashed alias too, otherwise the revoke + * state machine will get very upset later on. */ + if (need_cancel) { + struct buffer_head *bh2; + bh2 = __find_get_block(bh->b_bdev, bh->b_blocknr, bh->b_size); + if (bh2) { + if (bh2 != bh) + clear_buffer_revoked(bh2); + __brelse(bh2); + } + } + return did_revoke; +} + +/* + * journal_clear_revoked_flag clears revoked flag of buffers in + * revoke table to reflect there is no revoked buffers in the next + * transaction which is going to be started. + */ +void jbd2_clear_buffer_revoked_flags(journal_t *journal) +{ + struct jbd2_revoke_table_s *revoke = journal->j_revoke; + int i = 0; + + for (i = 0; i < revoke->hash_size; i++) { + struct list_head *hash_list; + struct list_head *list_entry; + hash_list = &revoke->hash_table[i]; + + list_for_each(list_entry, hash_list) { + struct jbd2_revoke_record_s *record; + struct buffer_head *bh; + record = (struct jbd2_revoke_record_s *)list_entry; + bh = __find_get_block(journal->j_fs_dev, + record->blocknr, + journal->j_blocksize); + if (bh) { + clear_buffer_revoked(bh); + __brelse(bh); + } + } + } +} + +/* journal_switch_revoke table select j_revoke for next transaction + * we do not want to suspend any processing until all revokes are + * written -bzzz + */ +void jbd2_journal_switch_revoke_table(journal_t *journal) +{ + int i; + + if (journal->j_revoke == journal->j_revoke_table[0]) + journal->j_revoke = journal->j_revoke_table[1]; + else + journal->j_revoke = journal->j_revoke_table[0]; + + for (i = 0; i < journal->j_revoke->hash_size; i++) + INIT_LIST_HEAD(&journal->j_revoke->hash_table[i]); +} + +/* + * Write revoke records to the journal for all entries in the current + * revoke hash, deleting the entries as we go. + */ +void jbd2_journal_write_revoke_records(transaction_t *transaction, + struct list_head *log_bufs) +{ + journal_t *journal = transaction->t_journal; + struct buffer_head *descriptor; + struct jbd2_revoke_record_s *record; + struct jbd2_revoke_table_s *revoke; + struct list_head *hash_list; + int i, offset, count; + + descriptor = NULL; + offset = 0; + count = 0; + + /* select revoke table for committing transaction */ + revoke = journal->j_revoke == journal->j_revoke_table[0] ? + journal->j_revoke_table[1] : journal->j_revoke_table[0]; + + for (i = 0; i < revoke->hash_size; i++) { + hash_list = &revoke->hash_table[i]; + + while (!list_empty(hash_list)) { + record = (struct jbd2_revoke_record_s *) + hash_list->next; + write_one_revoke_record(transaction, log_bufs, + &descriptor, &offset, record); + count++; + list_del(&record->hash); + kmem_cache_free(jbd2_revoke_record_cache, record); + } + } + if (descriptor) + flush_descriptor(journal, descriptor, offset); + jbd_debug(1, "Wrote %d revoke records\n", count); +} + +/* + * Write out one revoke record. We need to create a new descriptor + * block if the old one is full or if we have not already created one. + */ + +static void write_one_revoke_record(transaction_t *transaction, + struct list_head *log_bufs, + struct buffer_head **descriptorp, + int *offsetp, + struct jbd2_revoke_record_s *record) +{ + journal_t *journal = transaction->t_journal; + int csum_size = 0; + struct buffer_head *descriptor; + int sz, offset; + + /* If we are already aborting, this all becomes a noop. We + still need to go round the loop in + jbd2_journal_write_revoke_records in order to free all of the + revoke records: only the IO to the journal is omitted. */ + if (is_journal_aborted(journal)) + return; + + descriptor = *descriptorp; + offset = *offsetp; + + /* Do we need to leave space at the end for a checksum? */ + if (jbd2_journal_has_csum_v2or3(journal)) + csum_size = sizeof(struct jbd2_journal_block_tail); + + if (jbd2_has_feature_64bit(journal)) + sz = 8; + else + sz = 4; + + /* Make sure we have a descriptor with space left for the record */ + if (descriptor) { + if (offset + sz > journal->j_blocksize - csum_size) { + flush_descriptor(journal, descriptor, offset); + descriptor = NULL; + } + } + + if (!descriptor) { + descriptor = jbd2_journal_get_descriptor_buffer(transaction, + JBD2_REVOKE_BLOCK); + if (!descriptor) + return; + + /* Record it so that we can wait for IO completion later */ + BUFFER_TRACE(descriptor, "file in log_bufs"); + jbd2_file_log_bh(log_bufs, descriptor); + + offset = sizeof(jbd2_journal_revoke_header_t); + *descriptorp = descriptor; + } + + if (jbd2_has_feature_64bit(journal)) + * ((__be64 *)(&descriptor->b_data[offset])) = + cpu_to_be64(record->blocknr); + else + * ((__be32 *)(&descriptor->b_data[offset])) = + cpu_to_be32(record->blocknr); + offset += sz; + + *offsetp = offset; +} + +/* + * Flush a revoke descriptor out to the journal. If we are aborting, + * this is a noop; otherwise we are generating a buffer which needs to + * be waited for during commit, so it has to go onto the appropriate + * journal buffer list. + */ + +static void flush_descriptor(journal_t *journal, + struct buffer_head *descriptor, + int offset) +{ + jbd2_journal_revoke_header_t *header; + + if (is_journal_aborted(journal)) + return; + + header = (jbd2_journal_revoke_header_t *)descriptor->b_data; + header->r_count = cpu_to_be32(offset); + jbd2_descriptor_block_csum_set(journal, descriptor); + + set_buffer_jwrite(descriptor); + BUFFER_TRACE(descriptor, "write"); + set_buffer_dirty(descriptor); + write_dirty_buffer(descriptor, REQ_SYNC); +} +#endif + +/* + * Revoke support for recovery. + * + * Recovery needs to be able to: + * + * record all revoke records, including the tid of the latest instance + * of each revoke in the journal + * + * check whether a given block in a given transaction should be replayed + * (ie. has not been revoked by a revoke record in that or a subsequent + * transaction) + * + * empty the revoke table after recovery. + */ + +/* + * First, setting revoke records. We create a new revoke record for + * every block ever revoked in the log as we scan it for recovery, and + * we update the existing records if we find multiple revokes for a + * single block. + */ + +int jbd2_journal_set_revoke(journal_t *journal, + unsigned long long blocknr, + tid_t sequence) +{ + struct jbd2_revoke_record_s *record; + + record = find_revoke_record(journal, blocknr); + if (record) { + /* If we have multiple occurrences, only record the + * latest sequence number in the hashed record */ + if (tid_gt(sequence, record->sequence)) + record->sequence = sequence; + return 0; + } + return insert_revoke_hash(journal, blocknr, sequence); +} + +/* + * Test revoke records. For a given block referenced in the log, has + * that block been revoked? A revoke record with a given transaction + * sequence number revokes all blocks in that transaction and earlier + * ones, but later transactions still need replayed. + */ + +int jbd2_journal_test_revoke(journal_t *journal, + unsigned long long blocknr, + tid_t sequence) +{ + struct jbd2_revoke_record_s *record; + + record = find_revoke_record(journal, blocknr); + if (!record) + return 0; + if (tid_gt(sequence, record->sequence)) + return 0; + return 1; +} + +/* + * Finally, once recovery is over, we need to clear the revoke table so + * that it can be reused by the running filesystem. + */ + +void jbd2_journal_clear_revoke(journal_t *journal) +{ + int i; + struct list_head *hash_list; + struct jbd2_revoke_record_s *record; + struct jbd2_revoke_table_s *revoke; + + revoke = journal->j_revoke; + + for (i = 0; i < revoke->hash_size; i++) { + hash_list = &revoke->hash_table[i]; + while (!list_empty(hash_list)) { + record = (struct jbd2_revoke_record_s*) hash_list->next; + list_del(&record->hash); + kmem_cache_free(jbd2_revoke_record_cache, record); + } + } +} diff --git a/e2fsck/scantest.c b/e2fsck/scantest.c new file mode 100644 index 0000000..ed3595f --- /dev/null +++ b/e2fsck/scantest.c @@ -0,0 +1,141 @@ +/* + * scantest.c - test the speed of the inode scan routine + */ + +#include "config.h" +#include <string.h> +#include <fcntl.h> +#include <ctype.h> +#include <termios.h> +#include <time.h> +#ifdef HAVE_GETOPT_H +#include <getopt.h> +#endif +#include <unistd.h> +#include <sys/ioctl.h> +#ifdef HAVE_MALLOC_H +#include <malloc.h> +#endif +#include <sys/resource.h> + +#include "et/com_err.h" +#include "../version.h" + +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <stdlib.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <sys/time.h> + +#include "ext2fs/ext2_fs.h" +#include "ext2fs/ext2fs.h" + + +extern int isatty(int); + +const char * device_name = NULL; + +/* + * This structure is used for keeping track of how much resources have + * been used for a particular pass of e2fsck. + */ +struct resource_track { + struct timeval time_start; + struct timeval user_start; + struct timeval system_start; + void *brk_start; +}; + +struct resource_track global_rtrack; + +void init_resource_track(struct resource_track *track) +{ + struct rusage r; + + track->brk_start = sbrk(0); + gettimeofday(&track->time_start, 0); + getrusage(RUSAGE_SELF, &r); + track->user_start = r.ru_utime; + track->system_start = r.ru_stime; +} + +static __inline__ float timeval_subtract(struct timeval *tv1, + struct timeval *tv2) +{ + return ((tv1->tv_sec - tv2->tv_sec) + + ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000); +} + +static void print_resource_track(struct resource_track *track) +{ + struct rusage r; + struct timeval time_end; + + gettimeofday(&time_end, 0); + getrusage(RUSAGE_SELF, &r); + + printf(_("Memory used: %lu, elapsed time: %6.3f/%6.3f/%6.3f\n"), + (unsigned long)((char *)sbrk(0) - (char *)track->brk_start), + timeval_subtract(&time_end, &track->time_start), + timeval_subtract(&r.ru_utime, &track->user_start), + timeval_subtract(&r.ru_stime, &track->system_start)); +} + + + +int main (int argc, char *argv[]) +{ + errcode_t retval = 0; + int exit_value = 0; + int i; + ext2_filsys fs; + ext2_inode_scan scan; + ext2_ino_t ino; + struct ext2_inode inode; + + printf(_("size of inode=%d\n"), sizeof(inode)); + + device_name = "/dev/hda3"; + + init_resource_track(&global_rtrack); + + retval = ext2fs_open(device_name, 0, + 0, 0, unix_io_manager, &fs); + if (retval) { + com_err(argv[0], retval, _("while trying to open %s"), + device_name); + exit(1); + } + + retval = ext2fs_open_inode_scan(fs, 0, &scan); + if (retval) { + com_err(argv[0], retval, _("while opening inode scan")); + exit(1); + } + retval = ext2fs_get_next_inode(scan, &ino, &inode); + if (retval) { + com_err(argv[0], retval, _("while starting inode scan")); + exit(1); + } + while (ino) { + if (!inode.i_links_count) + goto next; + printf("%lu\n", inode.i_blocks); + next: + retval = ext2fs_get_next_inode(scan, &ino, &inode); + if (retval) { + com_err(argv[0], retval, + _("while doing inode scan")); + exit(1); + } + } + + + ext2fs_close_free(&fs); + + print_resource_track(&global_rtrack); + + return exit_value; +} diff --git a/e2fsck/sigcatcher.c b/e2fsck/sigcatcher.c new file mode 100644 index 0000000..a9d3b7f --- /dev/null +++ b/e2fsck/sigcatcher.c @@ -0,0 +1,446 @@ +/* + * sigcatcher.c --- print a backtrace on a SIGSEGV, et. al + * + * Copyright (C) 2011 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#include <stdio.h> +#include <stdlib.h> +#include <signal.h> +#include <string.h> +#ifdef HAVE_EXECINFO_H +#include <execinfo.h> +#endif + +#include "e2fsck.h" + +struct str_table { + int num; + const char *name; +}; + +#define DEFINE_ENTRY(SYM) { SYM, #SYM }, +#define END_TABLE { 0, 0 } + +static struct str_table sig_table[] = { +#ifdef SIGHUP + DEFINE_ENTRY(SIGHUP) +#endif +#ifdef SIGINT + DEFINE_ENTRY(SIGINT) +#endif +#ifdef SIGQUIT + DEFINE_ENTRY(SIGQUIT) +#endif +#ifdef SIGILL + DEFINE_ENTRY(SIGILL) +#endif +#ifdef SIGTRAP + DEFINE_ENTRY(SIGTRAP) +#endif +#ifdef SIGABRT + DEFINE_ENTRY(SIGABRT) +#endif +#ifdef SIGIOT + DEFINE_ENTRY(SIGIOT) +#endif +#ifdef SIGBUS + DEFINE_ENTRY(SIGBUS) +#endif +#ifdef SIGFPE + DEFINE_ENTRY(SIGFPE) +#endif +#ifdef SIGKILL + DEFINE_ENTRY(SIGKILL) +#endif +#ifdef SIGUSR1 + DEFINE_ENTRY(SIGUSR1) +#endif +#ifdef SIGSEGV + DEFINE_ENTRY(SIGSEGV) +#endif +#ifdef SIGUSR2 + DEFINE_ENTRY(SIGUSR2) +#endif +#ifdef SIGPIPE + DEFINE_ENTRY(SIGPIPE) +#endif +#ifdef SIGALRM + DEFINE_ENTRY(SIGALRM) +#endif +#ifdef SIGTERM + DEFINE_ENTRY(SIGTERM) +#endif +#ifdef SIGSTKFLT + DEFINE_ENTRY(SIGSTKFLT) +#endif +#ifdef SIGCHLD + DEFINE_ENTRY(SIGCHLD) +#endif +#ifdef SIGCONT + DEFINE_ENTRY(SIGCONT) +#endif +#ifdef SIGSTOP + DEFINE_ENTRY(SIGSTOP) +#endif +#ifdef SIGTSTP + DEFINE_ENTRY(SIGTSTP) +#endif +#ifdef SIGTTIN + DEFINE_ENTRY(SIGTTIN) +#endif +#ifdef SIGTTOU + DEFINE_ENTRY(SIGTTOU) +#endif +#ifdef SIGURG + DEFINE_ENTRY(SIGURG) +#endif +#ifdef SIGXCPU + DEFINE_ENTRY(SIGXCPU) +#endif +#ifdef SIGXFSZ + DEFINE_ENTRY(SIGXFSZ) +#endif +#ifdef SIGVTALRM + DEFINE_ENTRY(SIGVTALRM) +#endif +#ifdef SIGPROF + DEFINE_ENTRY(SIGPROF) +#endif +#ifdef SIGWINCH + DEFINE_ENTRY(SIGWINCH) +#endif +#ifdef SIGIO + DEFINE_ENTRY(SIGIO) +#endif +#ifdef SIGPOLL + DEFINE_ENTRY(SIGPOLL) +#endif +#ifdef SIGPWR + DEFINE_ENTRY(SIGPWR) +#endif +#ifdef SIGSYS + DEFINE_ENTRY(SIGSYS) +#endif + END_TABLE +}; + +static struct str_table generic_code_table[] = { +#ifdef SI_ASYNCNL + DEFINE_ENTRY(SI_ASYNCNL) +#endif +#ifdef SI_TKILL + DEFINE_ENTRY(SI_TKILL) +#endif +#ifdef SI_SIGIO + DEFINE_ENTRY(SI_SIGIO) +#endif +#ifdef SI_ASYNCIO + DEFINE_ENTRY(SI_ASYNCIO) +#endif +#ifdef SI_MESGQ + DEFINE_ENTRY(SI_MESGQ) +#endif +#ifdef SI_TIMER + DEFINE_ENTRY(SI_TIMER) +#endif +#ifdef SI_QUEUE + DEFINE_ENTRY(SI_QUEUE) +#endif +#ifdef SI_USER + DEFINE_ENTRY(SI_USER) +#endif +#ifdef SI_KERNEL + DEFINE_ENTRY(SI_KERNEL) +#endif + END_TABLE +}; + +static struct str_table sigill_code_table[] = { +#ifdef ILL_ILLOPC + DEFINE_ENTRY(ILL_ILLOPC) +#endif +#ifdef ILL_ILLOPN + DEFINE_ENTRY(ILL_ILLOPN) +#endif +#ifdef ILL_ILLADR + DEFINE_ENTRY(ILL_ILLADR) +#endif +#ifdef ILL_ILLTRP + DEFINE_ENTRY(ILL_ILLTRP) +#endif +#ifdef ILL_PRVOPC + DEFINE_ENTRY(ILL_PRVOPC) +#endif +#ifdef ILL_PRVREG + DEFINE_ENTRY(ILL_PRVREG) +#endif +#ifdef ILL_COPROC + DEFINE_ENTRY(ILL_COPROC) +#endif +#ifdef ILL_BADSTK + DEFINE_ENTRY(ILL_BADSTK) +#endif +#ifdef BUS_ADRALN + DEFINE_ENTRY(BUS_ADRALN) +#endif +#ifdef BUS_ADRERR + DEFINE_ENTRY(BUS_ADRERR) +#endif +#ifdef BUS_OBJERR + DEFINE_ENTRY(BUS_OBJERR) +#endif + END_TABLE +}; + +static struct str_table sigfpe_code_table[] = { +#ifdef FPE_INTDIV + DEFINE_ENTRY(FPE_INTDIV) +#endif +#ifdef FPE_INTOVF + DEFINE_ENTRY(FPE_INTOVF) +#endif +#ifdef FPE_FLTDIV + DEFINE_ENTRY(FPE_FLTDIV) +#endif +#ifdef FPE_FLTOVF + DEFINE_ENTRY(FPE_FLTOVF) +#endif +#ifdef FPE_FLTUND + DEFINE_ENTRY(FPE_FLTUND) +#endif +#ifdef FPE_FLTRES + DEFINE_ENTRY(FPE_FLTRES) +#endif +#ifdef FPE_FLTINV + DEFINE_ENTRY(FPE_FLTINV) +#endif +#ifdef FPE_FLTSUB + DEFINE_ENTRY(FPE_FLTSUB) +#endif + END_TABLE +}; + +static struct str_table sigsegv_code_table[] = { +#ifdef SEGV_MAPERR + DEFINE_ENTRY(SEGV_MAPERR) +#endif +#ifdef SEGV_ACCERR + DEFINE_ENTRY(SEGV_ACCERR) +#endif + END_TABLE +}; + + +static struct str_table sigbus_code_table[] = { +#ifdef BUS_ADRALN + DEFINE_ENTRY(BUS_ADRALN) +#endif +#ifdef BUS_ADRERR + DEFINE_ENTRY(BUS_ADRERR) +#endif +#ifdef BUS_OBJERR + DEFINE_ENTRY(BUS_OBJERR) +#endif + END_TABLE +}; + +#if 0 /* should this be hooked in somewhere? */ +static struct str_table sigstrap_code_table[] = { +#ifdef TRAP_BRKPT + DEFINE_ENTRY(TRAP_BRKPT) +#endif +#ifdef TRAP_TRACE + DEFINE_ENTRY(TRAP_TRACE) +#endif + END_TABLE +}; +#endif + +static struct str_table sigcld_code_table[] = { +#ifdef CLD_EXITED + DEFINE_ENTRY(CLD_EXITED) +#endif +#ifdef CLD_KILLED + DEFINE_ENTRY(CLD_KILLED) +#endif +#ifdef CLD_DUMPED + DEFINE_ENTRY(CLD_DUMPED) +#endif +#ifdef CLD_TRAPPED + DEFINE_ENTRY(CLD_TRAPPED) +#endif +#ifdef CLD_STOPPED + DEFINE_ENTRY(CLD_STOPPED) +#endif +#ifdef CLD_CONTINUED + DEFINE_ENTRY(CLD_CONTINUED) +#endif + END_TABLE +}; + +#if 0 /* should this be hooked in somewhere? */ +static struct str_table sigpoll_code_table[] = { +#ifdef POLL_IN + DEFINE_ENTRY(POLL_IN) +#endif +#ifdef POLL_OUT + DEFINE_ENTRY(POLL_OUT) +#endif +#ifdef POLL_MSG + DEFINE_ENTRY(POLL_MSG) +#endif +#ifdef POLL_ERR + DEFINE_ENTRY(POLL_ERR) +#endif +#ifdef POLL_PRI + DEFINE_ENTRY(POLL_PRI) +#endif +#ifdef POLL_HUP + DEFINE_ENTRY(POLL_HUP) +#endif + END_TABLE +}; +#endif + +static const char *lookup_table(int num, struct str_table *table) +{ + struct str_table *p; + + for (p=table; p->name; p++) + if (num == p->num) + return(p->name); + return NULL; +} + +static const char *lookup_table_fallback(int num, struct str_table *table) +{ + static char buf[32]; + const char *ret = lookup_table(num, table); + + if (ret) + return ret; + snprintf(buf, sizeof(buf), "%d", num); + buf[sizeof(buf)-1] = 0; + return buf; +} + +static void die_signal_handler(int signum, siginfo_t *siginfo, + void *context EXT2FS_ATTR((unused))) +{ + const char *cp; + + fprintf(stderr, "Signal (%d) %s ", signum, + lookup_table_fallback(signum, sig_table)); + if (siginfo->si_code == SI_USER) + fprintf(stderr, "(sent from pid %u) ", siginfo->si_pid); + cp = lookup_table(siginfo->si_code, generic_code_table); + if (cp) + fprintf(stderr, "si_code=%s ", cp); + else if (signum == SIGILL) + fprintf(stderr, "si_code=%s ", + lookup_table_fallback(siginfo->si_code, + sigill_code_table)); + else if (signum == SIGFPE) + fprintf(stderr, "si_code=%s ", + lookup_table_fallback(siginfo->si_code, + sigfpe_code_table)); + else if (signum == SIGSEGV) + fprintf(stderr, "si_code=%s ", + lookup_table_fallback(siginfo->si_code, + sigsegv_code_table)); + else if (signum == SIGBUS) + fprintf(stderr, "si_code=%s ", + lookup_table_fallback(siginfo->si_code, + sigbus_code_table)); + else if (signum == SIGCHLD) + fprintf(stderr, "si_code=%s ", + lookup_table_fallback(siginfo->si_code, + sigcld_code_table)); + else + fprintf(stderr, "si code=%d ", siginfo->si_code); + if ((siginfo->si_code != SI_USER) && + (signum == SIGILL || signum == SIGFPE || + signum == SIGSEGV || signum == SIGBUS)) + fprintf(stderr, "fault addr=%p", siginfo->si_addr); + fprintf(stderr, "\n"); + +#if defined(HAVE_BACKTRACE) && !defined(DISABLE_BACKTRACE) + { + void *stack_syms[32]; + int frames; + + frames = backtrace(stack_syms, 32); + backtrace_symbols_fd(stack_syms, frames, 2); + } +#endif + exit(FSCK_ERROR); +} + +void sigcatcher_setup(void) +{ + struct sigaction sa; + + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_sigaction = die_signal_handler; + sa.sa_flags = SA_SIGINFO; + + sigaction(SIGFPE, &sa, 0); + sigaction(SIGILL, &sa, 0); + sigaction(SIGBUS, &sa, 0); + sigaction(SIGSEGV, &sa, 0); + sigaction(SIGABRT, &sa, 0); +} + + +#ifdef DEBUG +#include <getopt.h> + +void usage(void) +{ + fprintf(stderr, "tst_sigcatcher: [-akfn]\n"); + exit(1); +} + +int main(int argc, char** argv) +{ + struct sigaction sa; + char *p = 0; + int i, c; + volatile x=0; + + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_sigaction = die_signal_handler; + sa.sa_flags = SA_SIGINFO; + for (i=1; i < 31; i++) + sigaction(i, &sa, 0); + + while ((c = getopt (argc, argv, "afkn")) != EOF) + switch (c) { + case 'a': + abort(); + break; + case 'f': + printf("%d\n", 42/x); + case 'k': + kill(getpid(), SIGTERM); + break; + case 'n': + *p = 42; + default: + usage (); + } + + printf("Sleeping for 10 seconds, send kill signal to pid %u...\n", + getpid()); + fflush(stdout); + sleep(10); + exit(0); +} +#endif diff --git a/e2fsck/super.c b/e2fsck/super.c new file mode 100644 index 0000000..9495e02 --- /dev/null +++ b/e2fsck/super.c @@ -0,0 +1,1461 @@ +/* + * e2fsck.c - superblock checks + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#ifndef EXT2_SKIP_UUID +#include "uuid/uuid.h" +#endif +#include "e2fsck.h" +#include "problem.h" + +#define MIN_CHECK 1 +#define MAX_CHECK 2 +#define LOG2_CHECK 4 + +static int check_super_value(e2fsck_t ctx, const char *descr, + unsigned long value, int flags, + unsigned long min_val, unsigned long max_val) +{ + struct problem_context pctx; + + if ((flags & MIN_CHECK && value < min_val) || + (flags & MAX_CHECK && value > max_val) || + (flags & LOG2_CHECK && (value & (value - 1)) != 0)) { + clear_problem_context(&pctx); + pctx.num = value; + pctx.str = descr; + fix_problem(ctx, PR_0_MISC_CORRUPT_SUPER, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + return 1; +} + +static int check_super_value64(e2fsck_t ctx, const char *descr, + __u64 value, int flags, + __u64 min_val, __u64 max_val) +{ + struct problem_context pctx; + + if ((flags & MIN_CHECK && value < min_val) || + (flags & MAX_CHECK && value > max_val) || + (flags & LOG2_CHECK && (value & (value - 1)) != 0)) { + clear_problem_context(&pctx); + pctx.num = value; + pctx.str = descr; + fix_problem(ctx, PR_0_MISC_CORRUPT_SUPER, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return 0; + } + return 1; +} + +/* + * helper function to release an inode + */ +struct process_block_struct { + e2fsck_t ctx; + char *buf; + struct problem_context *pctx; + int truncating; + int truncate_offset; + e2_blkcnt_t truncate_block; + int truncated_blocks; + int abort; + errcode_t errcode; + blk64_t last_cluster; + struct ext2_inode_large *inode; +}; + +static int release_inode_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_blk EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_block_struct *pb; + e2fsck_t ctx; + struct problem_context *pctx; + blk64_t blk = *block_nr; + blk64_t cluster = EXT2FS_B2C(fs, *block_nr); + int retval = 0; + + pb = (struct process_block_struct *) priv_data; + ctx = pb->ctx; + pctx = pb->pctx; + + pctx->blk = blk; + pctx->blkcount = blockcnt; + + if (blk == 0) + return 0; + + if (pb->last_cluster == cluster) + return 0; + + pb->last_cluster = cluster; + + if ((blk < fs->super->s_first_data_block) || + (blk >= ext2fs_blocks_count(fs->super))) { + fix_problem(ctx, PR_0_ORPHAN_ILLEGAL_BLOCK_NUM, pctx); + return_abort: + pb->abort = 1; + return BLOCK_ABORT; + } + + if (!ext2fs_test_block_bitmap2(fs->block_map, blk)) { + fix_problem(ctx, PR_0_ORPHAN_ALREADY_CLEARED_BLOCK, pctx); + goto return_abort; + } + + /* + * If we are deleting an orphan, then we leave the fields alone. + * If we are truncating an orphan, then update the inode fields + * and clean up any partial block data. + */ + if (pb->truncating) { + /* + * We only remove indirect blocks if they are + * completely empty. + */ + if (blockcnt < 0) { + int i, limit; + blk_t *bp; + + pb->errcode = io_channel_read_blk64(fs->io, blk, 1, + pb->buf); + if (pb->errcode) + goto return_abort; + + limit = fs->blocksize >> 2; + for (i = 0, bp = (blk_t *) pb->buf; + i < limit; i++, bp++) + if (*bp) + return 0; + } + /* + * We don't remove direct blocks until we've reached + * the truncation block. + */ + if (blockcnt >= 0 && blockcnt < pb->truncate_block) + return 0; + /* + * If part of the last block needs truncating, we do + * it here. + */ + if ((blockcnt == pb->truncate_block) && pb->truncate_offset) { + pb->errcode = io_channel_read_blk64(fs->io, blk, 1, + pb->buf); + if (pb->errcode) + goto return_abort; + memset(pb->buf + pb->truncate_offset, 0, + fs->blocksize - pb->truncate_offset); + pb->errcode = io_channel_write_blk64(fs->io, blk, 1, + pb->buf); + if (pb->errcode) + goto return_abort; + } + pb->truncated_blocks++; + *block_nr = 0; + retval |= BLOCK_CHANGED; + } + + if (ctx->qctx) + quota_data_sub(ctx->qctx, pb->inode, 0, ctx->fs->blocksize); + ext2fs_block_alloc_stats2(fs, blk, -1); + ctx->free_blocks++; + return retval; +} + +/* + * This function releases an inode. Returns 1 if an inconsistency was + * found. If the inode has a link count, then it is being truncated and + * not deleted. + */ +static int release_inode_blocks(e2fsck_t ctx, ext2_ino_t ino, + struct ext2_inode_large *inode, char *block_buf, + struct problem_context *pctx) +{ + struct process_block_struct pb; + ext2_filsys fs = ctx->fs; + blk64_t blk; + errcode_t retval; + __u32 count; + + if (!ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(inode))) + return 0; + + pb.buf = block_buf + 3 * ctx->fs->blocksize; + pb.ctx = ctx; + pb.abort = 0; + pb.errcode = 0; + pb.pctx = pctx; + pb.last_cluster = 0; + pb.inode = inode; + if (inode->i_links_count) { + pb.truncating = 1; + pb.truncate_block = (e2_blkcnt_t) + ((EXT2_I_SIZE(inode) + fs->blocksize - 1) / + fs->blocksize); + pb.truncate_offset = inode->i_size % fs->blocksize; + } else { + pb.truncating = 0; + pb.truncate_block = 0; + pb.truncate_offset = 0; + } + pb.truncated_blocks = 0; + retval = ext2fs_block_iterate3(fs, ino, BLOCK_FLAG_DEPTH_TRAVERSE, + block_buf, release_inode_block, &pb); + if (retval) { + com_err("release_inode_blocks", retval, + _("while calling ext2fs_block_iterate for inode %u"), + ino); + return 1; + } + if (pb.abort) + return 1; + + /* Refresh the inode since ext2fs_block_iterate may have changed it */ + e2fsck_read_inode_full(ctx, ino, EXT2_INODE(inode), sizeof(*inode), + "release_inode_blocks"); + + if (pb.truncated_blocks) + ext2fs_iblk_sub_blocks(fs, EXT2_INODE(inode), + pb.truncated_blocks); + + blk = ext2fs_file_acl_block(fs, EXT2_INODE(inode)); + if (blk) { + retval = ext2fs_adjust_ea_refcount3(fs, blk, block_buf, -1, + &count, ino); + if (retval == EXT2_ET_BAD_EA_BLOCK_NUM) { + retval = 0; + count = 1; + } + if (retval) { + com_err("release_inode_blocks", retval, + _("while calling ext2fs_adjust_ea_refcount2 for inode %u"), + ino); + return 1; + } + if (count == 0) { + if (ctx->qctx) + quota_data_sub(ctx->qctx, inode, 0, + ctx->fs->blocksize); + ext2fs_block_alloc_stats2(fs, blk, -1); + ctx->free_blocks++; + } + ext2fs_file_acl_block_set(fs, EXT2_INODE(inode), 0); + } + return 0; +} + +/* Load all quota data in preparation for orphan clearing. */ +static errcode_t e2fsck_read_all_quotas(e2fsck_t ctx) +{ + ext2_ino_t qf_ino; + enum quota_type qtype; + errcode_t retval = 0; + + if (!ext2fs_has_feature_quota(ctx->fs->super)) + return retval; + + retval = quota_init_context(&ctx->qctx, ctx->fs, 0); + if (retval) + return retval; + + for (qtype = 0 ; qtype < MAXQUOTAS; qtype++) { + qf_ino = *quota_sb_inump(ctx->fs->super, qtype); + if (qf_ino == 0) + continue; + + retval = quota_read_all_dquots(ctx->qctx, qf_ino, qtype, + QREAD_USAGE | QREAD_LIMITS); + if (retval) + break; + } + if (retval) + quota_release_context(&ctx->qctx); + return retval; +} + +/* Write all the quota info to disk. */ +static errcode_t e2fsck_write_all_quotas(e2fsck_t ctx) +{ + struct problem_context pctx; + enum quota_type qtype; + + if (!ext2fs_has_feature_quota(ctx->fs->super)) + return 0; + + clear_problem_context(&pctx); + for (qtype = 0 ; qtype < MAXQUOTAS; qtype++) { + pctx.num = qtype; + pctx.errcode = quota_write_inode(ctx->qctx, 1 << qtype); + if (pctx.errcode) { + fix_problem(ctx, PR_6_WRITE_QUOTAS, &pctx); + break; + } + } + + quota_release_context(&ctx->qctx); + return pctx.errcode; +} + +static int release_orphan_inode(e2fsck_t ctx, ext2_ino_t *ino, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + struct problem_context pctx; + struct ext2_inode_large inode; + ext2_ino_t next_ino; + + e2fsck_read_inode_full(ctx, *ino, EXT2_INODE(&inode), + sizeof(inode), "release_orphan_inode"); + clear_problem_context(&pctx); + pctx.ino = *ino; + pctx.inode = EXT2_INODE(&inode); + pctx.str = inode.i_links_count ? _("Truncating") : _("Clearing"); + + fix_problem(ctx, PR_0_ORPHAN_CLEAR_INODE, &pctx); + + next_ino = inode.i_dtime; + if (next_ino && + ((next_ino < EXT2_FIRST_INODE(fs->super)) || + (next_ino > fs->super->s_inodes_count))) { + pctx.ino = next_ino; + fix_problem(ctx, PR_0_ORPHAN_ILLEGAL_INODE, &pctx); + return 1; + } + + if (release_inode_blocks(ctx, *ino, &inode, block_buf, &pctx)) + return 1; + + if (!inode.i_links_count) { + if (ctx->qctx) + quota_data_inodes(ctx->qctx, &inode, *ino, -1); + ext2fs_inode_alloc_stats2(fs, *ino, -1, + LINUX_S_ISDIR(inode.i_mode)); + ctx->free_inodes++; + inode.i_dtime = ctx->now; + } else { + inode.i_dtime = 0; + } + e2fsck_write_inode_full(ctx, *ino, EXT2_INODE(&inode), + sizeof(inode), "delete_file"); + *ino = next_ino; + return 0; +} + +struct process_orphan_block_data { + e2fsck_t ctx; + char *buf; + char *block_buf; + e2_blkcnt_t blocks; + int abort; + int clear; + errcode_t errcode; + ext2_ino_t ino; + __u32 generation; +}; + +static int process_orphan_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_blk EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_orphan_block_data *pd; + e2fsck_t ctx; + struct problem_context pctx; + blk64_t blk = *block_nr; + struct ext4_orphan_block_tail *tail; + int j; + int inodes_per_ob; + __u32 *bdata; + ext2_ino_t ino; + + pd = priv_data; + ctx = pd->ctx; + clear_problem_context(&pctx); + pctx.ino = fs->super->s_orphan_file_inum; + pctx.blk = blockcnt; + + /* Orphan file must not have holes */ + if (!blk) { + if (blockcnt == pd->blocks) + return BLOCK_ABORT; + fix_problem(ctx, PR_0_ORPHAN_FILE_HOLE, &pctx); +return_abort: + pd->abort = 1; + return BLOCK_ABORT; + } + inodes_per_ob = ext2fs_inodes_per_orphan_block(fs); + pd->errcode = io_channel_read_blk64(fs->io, blk, 1, pd->buf); + if (pd->errcode) + goto return_abort; + tail = ext2fs_orphan_block_tail(fs, pd->buf); + if (ext2fs_le32_to_cpu(tail->ob_magic) != + EXT4_ORPHAN_BLOCK_MAGIC) { + fix_problem(ctx, PR_0_ORPHAN_FILE_BAD_MAGIC, &pctx); + goto return_abort; + } + if (!ext2fs_orphan_file_block_csum_verify(fs, + fs->super->s_orphan_file_inum, blk, pd->buf)) { + fix_problem(ctx, PR_0_ORPHAN_FILE_BAD_CHECKSUM, &pctx); + goto return_abort; + } + bdata = (__u32 *)pd->buf; + for (j = 0; j < inodes_per_ob; j++) { + if (!bdata[j]) + continue; + ino = ext2fs_le32_to_cpu(bdata[j]); + if (release_orphan_inode(ctx, &ino, pd->block_buf)) + goto return_abort; + } + return 0; +} + +static int process_orphan_file(e2fsck_t ctx, char *block_buf) +{ + ext2_filsys fs = ctx->fs; + char *orphan_buf; + struct process_orphan_block_data pd; + int ret = 0; + ext2_ino_t orphan_inum = fs->super->s_orphan_file_inum; + struct ext2_inode orphan_inode; + struct problem_context pctx; + errcode_t retval; + + if (!ext2fs_has_feature_orphan_file(fs->super)) + return 0; + + clear_problem_context(&pctx); + pctx.ino = orphan_inum; + + orphan_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 4, + "orphan block buffer"); + retval = ext2fs_read_inode(fs, orphan_inum, &orphan_inode); + if (retval < 0) { + com_err("process_orphan_file", retval, + _("while reading inode %d"), orphan_inum); + ret = 1; + goto out; + } + if (EXT2_I_SIZE(&orphan_inode) & (fs->blocksize - 1)) { + fix_problem(ctx, PR_0_ORPHAN_FILE_WRONG_SIZE, &pctx); + ret = 1; + goto out; + } + pd.buf = orphan_buf + 3 * fs->blocksize; + pd.block_buf = block_buf; + pd.blocks = EXT2_I_SIZE(&orphan_inode) / fs->blocksize; + pd.ctx = ctx; + pd.abort = 0; + pd.errcode = 0; + retval = ext2fs_block_iterate3(fs, orphan_inum, + BLOCK_FLAG_DATA_ONLY | BLOCK_FLAG_HOLE, + orphan_buf, process_orphan_block, &pd); + if (retval) { + com_err("process_orphan_block", retval, + _("while calling ext2fs_block_iterate for inode %d"), + orphan_inum); + ret = 1; + goto out; + } + if (pd.abort) { + if (pd.errcode) { + com_err("process_orphan_block", pd.errcode, + _("while reading blocks of inode %d"), + orphan_inum); + } + ret = 1; + } +out: + ext2fs_free_mem(&orphan_buf); + return ret; +} + +/* + * This function releases all of the orphan inodes. It returns 1 if + * it hit some error, and 0 on success. + */ +static int release_orphan_inodes(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t ino; + struct problem_context pctx; + char *block_buf; + + if (fs->super->s_last_orphan == 0 && + !ext2fs_has_feature_orphan_present(fs->super)) + return 0; + + clear_problem_context(&pctx); + ino = fs->super->s_last_orphan; + pctx.ino = ino; + pctx.errcode = e2fsck_read_all_quotas(ctx); + if (pctx.errcode) { + fix_problem(ctx, PR_0_QUOTA_INIT_CTX, &pctx); + return 1; + } + + /* + * Win or lose, we won't be using the head of the orphan inode + * list again. + */ + fs->super->s_last_orphan = 0; + ext2fs_mark_super_dirty(fs); + + /* + * If the filesystem contains errors, don't process the orphan list + * or orphan file, since neither can be trusted; and we're going to + * be running a full e2fsck run anyway... We clear orphan file contents + * after filesystem is checked to avoid clearing someone else's data. + */ + if (fs->super->s_state & EXT2_ERROR_FS) { + if (ctx->qctx) + quota_release_context(&ctx->qctx); + return 0; + } + + if (ino && ((ino < EXT2_FIRST_INODE(fs->super)) || + (ino > fs->super->s_inodes_count))) { + fix_problem(ctx, PR_0_ORPHAN_ILLEGAL_HEAD_INODE, &pctx); + goto err_qctx; + } + + block_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 4, + "block iterate buffer"); + e2fsck_read_bitmaps(ctx); + + /* First process orphan list */ + while (ino) { + if (release_orphan_inode(ctx, &ino, block_buf)) + goto err_buf; + } + + /* Next process orphan file */ + if (ext2fs_has_feature_orphan_present(fs->super) && + !ext2fs_has_feature_orphan_file(fs->super)) + goto err_buf; + if (process_orphan_file(ctx, block_buf)) + goto err_buf; + + ext2fs_free_mem(&block_buf); + pctx.errcode = e2fsck_write_all_quotas(ctx); + if (pctx.errcode) + goto err; + return 0; +err_buf: + ext2fs_free_mem(&block_buf); +err_qctx: + if (ctx->qctx) + quota_release_context(&ctx->qctx); +err: + return 1; +} + +static int reinit_orphan_block(ext2_filsys fs, + blk64_t *block_nr, + e2_blkcnt_t blockcnt, + blk64_t ref_blk EXT2FS_ATTR((unused)), + int ref_offset EXT2FS_ATTR((unused)), + void *priv_data) +{ + struct process_orphan_block_data *pd; + e2fsck_t ctx; + blk64_t blk = *block_nr; + struct problem_context pctx; + + pd = priv_data; + ctx = pd->ctx; + + /* Orphan file must not have holes */ + if (!blk) { + if (blockcnt == pd->blocks) + return BLOCK_ABORT; + + clear_problem_context(&pctx); + pctx.ino = fs->super->s_orphan_file_inum; + pctx.blk = blockcnt; + fix_problem(ctx, PR_6_ORPHAN_FILE_HOLE, &pctx); +return_abort: + pd->abort = 1; + return BLOCK_ABORT; + } + + if (ext2fs_has_feature_metadata_csum(fs->super)) { + struct ext4_orphan_block_tail *tail; + + tail = ext2fs_orphan_block_tail(fs, pd->buf); + /* + * Update checksum to match expected buffer contents with + * appropriate block number. + */ + tail->ob_checksum = ext2fs_do_orphan_file_block_csum(fs, + pd->ino, pd->generation, blk, pd->buf); + } + if (!pd->clear) { + pd->errcode = io_channel_read_blk64(fs->io, blk, 1, + pd->block_buf); + /* Block is already cleanly initialized? */ + if (!memcmp(pd->block_buf, pd->buf, fs->blocksize)) + return 0; + + clear_problem_context(&pctx); + pctx.ino = fs->super->s_orphan_file_inum; + pctx.blk = blockcnt; + if (!fix_problem(ctx, PR_6_ORPHAN_BLOCK_DIRTY, &pctx)) + goto return_abort; + pd->clear = 1; + } + pd->errcode = io_channel_write_blk64(fs->io, blk, 1, pd->buf); + if (pd->errcode) + goto return_abort; + return 0; +} + +/* + * Check and clear orphan file. We just return non-zero if we hit some + * inconsistency. Caller will truncate & recreate new orphan file. + */ +int check_init_orphan_file(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + char *orphan_buf; + struct process_orphan_block_data pd; + struct ext4_orphan_block_tail *tail; + ext2_ino_t orphan_inum = fs->super->s_orphan_file_inum; + struct ext2_inode orphan_inode; + int ret = 0; + errcode_t retval; + + orphan_buf = (char *) e2fsck_allocate_memory(ctx, fs->blocksize * 5, + "orphan block buffer"); + e2fsck_read_inode(ctx, orphan_inum, &orphan_inode, "orphan inode"); + if (EXT2_I_SIZE(&orphan_inode) & (fs->blocksize - 1)) { + struct problem_context pctx; + + clear_problem_context(&pctx); + pctx.ino = orphan_inum; + fix_problem(ctx, PR_6_ORPHAN_FILE_WRONG_SIZE, &pctx); + ret = 1; + goto out; + } + pd.buf = orphan_buf + 3 * fs->blocksize; + pd.block_buf = orphan_buf + 4 * fs->blocksize; + pd.blocks = EXT2_I_SIZE(&orphan_inode) / fs->blocksize; + pd.ctx = ctx; + pd.abort = 0; + pd.clear = 0; + pd.errcode = 0; + pd.ino = orphan_inum; + pd.generation = orphan_inode.i_generation; + /* Initialize buffer to write */ + memset(pd.buf, 0, fs->blocksize); + tail = ext2fs_orphan_block_tail(fs, pd.buf); + tail->ob_magic = ext2fs_cpu_to_le32(EXT4_ORPHAN_BLOCK_MAGIC); + + retval = ext2fs_block_iterate3(fs, orphan_inum, + BLOCK_FLAG_DATA_ONLY | BLOCK_FLAG_HOLE, + orphan_buf, reinit_orphan_block, &pd); + if (retval) { + com_err("reinit_orphan_block", retval, + _("while calling ext2fs_block_iterate for inode %d"), + orphan_inum); + ret = 1; + goto out; + } + if (pd.abort) { + if (pd.errcode) { + com_err("process_orphan_block", pd.errcode, + _("while reading blocks of inode %d"), + orphan_inum); + } + ret = 1; + } + + /* We had to clear some blocks. Report it up. */ + if (ret == 0 && pd.clear) + ret = 2; +out: + ext2fs_free_mem(&orphan_buf); + return ret; +} + +/* + * Check the resize inode to make sure it is sane. We check both for + * the case where on-line resizing is not enabled (in which case the + * resize inode should be cleared) as well as the case where on-line + * resizing is enabled. + */ +void check_resize_inode(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + struct ext2_inode inode; + struct problem_context pctx; + int i, gdt_off, ind_off; + dgrp_t j; + blk_t blk, pblk; + blk_t expect; /* for resize inode, which is 32-bit only */ + __u32 *dind_buf = 0, *ind_buf; + errcode_t retval; + + clear_problem_context(&pctx); + + if (ext2fs_has_feature_resize_inode(fs->super) && + ext2fs_has_feature_meta_bg(fs->super) && + fix_problem(ctx, PR_0_DISABLE_RESIZE_INODE, &pctx)) { + ext2fs_clear_feature_resize_inode(fs->super); + fs->super->s_reserved_gdt_blocks = 0; + ext2fs_mark_super_dirty(fs); + } + + /* + * If the resize inode feature isn't set, then + * s_reserved_gdt_blocks must be zero. + */ + if (!ext2fs_has_feature_resize_inode(fs->super)) { + if (fs->super->s_reserved_gdt_blocks) { + pctx.num = fs->super->s_reserved_gdt_blocks; + if (fix_problem(ctx, PR_0_NONZERO_RESERVED_GDT_BLOCKS, + &pctx)) { + fs->super->s_reserved_gdt_blocks = 0; + ext2fs_mark_super_dirty(fs); + } + } + } + + /* Read the resize inode */ + pctx.ino = EXT2_RESIZE_INO; + retval = ext2fs_read_inode(fs, EXT2_RESIZE_INO, &inode); + if (retval) { + if (ext2fs_has_feature_resize_inode(fs->super)) + ctx->flags |= E2F_FLAG_RESIZE_INODE; + return; + } + + /* + * If the resize inode feature isn't set, check to make sure + * the resize inode is cleared; then we're done. + */ + if (!ext2fs_has_feature_resize_inode(fs->super)) { + for (i=0; i < EXT2_N_BLOCKS; i++) { + if (inode.i_block[i]) + break; + } + if ((i < EXT2_N_BLOCKS) && + fix_problem(ctx, PR_0_CLEAR_RESIZE_INODE, &pctx)) { + memset(&inode, 0, sizeof(inode)); + e2fsck_write_inode(ctx, EXT2_RESIZE_INO, &inode, + "clear_resize"); + } + return; + } + + /* + * The resize inode feature is enabled; check to make sure the + * only block in use is the double indirect block + */ + blk = inode.i_block[EXT2_DIND_BLOCK]; + for (i=0; i < EXT2_N_BLOCKS; i++) { + if (i != EXT2_DIND_BLOCK && inode.i_block[i]) + break; + } + if ((i < EXT2_N_BLOCKS) || !blk || !inode.i_links_count || + !(inode.i_mode & LINUX_S_IFREG) || + (blk < fs->super->s_first_data_block || + blk >= ext2fs_blocks_count(fs->super))) { + resize_inode_invalid: + if (fix_problem(ctx, PR_0_RESIZE_INODE_INVALID, &pctx)) { + memset(&inode, 0, sizeof(inode)); + e2fsck_write_inode(ctx, EXT2_RESIZE_INO, &inode, + "clear_resize"); + ctx->flags |= E2F_FLAG_RESIZE_INODE; + } + if (!(ctx->options & E2F_OPT_READONLY)) { + fs->super->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(fs); + } + goto cleanup; + } + dind_buf = (__u32 *) e2fsck_allocate_memory(ctx, fs->blocksize * 2, + "resize dind buffer"); + ind_buf = (__u32 *) ((char *) dind_buf + fs->blocksize); + + retval = ext2fs_read_ind_block(fs, blk, dind_buf); + if (retval) + goto resize_inode_invalid; + + gdt_off = fs->desc_blocks; + pblk = fs->super->s_first_data_block + 1 + fs->desc_blocks; + if (fs->blocksize == 1024 && fs->super->s_first_data_block == 0) + pblk++; /* Deal with 1024 blocksize bigalloc fs */ + for (i = 0; i < fs->super->s_reserved_gdt_blocks / 4; + i++, gdt_off++, pblk++) { + gdt_off %= fs->blocksize/4; + if (dind_buf[gdt_off] != pblk) + goto resize_inode_invalid; + retval = ext2fs_read_ind_block(fs, pblk, ind_buf); + if (retval) + goto resize_inode_invalid; + ind_off = 0; + for (j = 1; j < fs->group_desc_count; j++) { + if (!ext2fs_bg_has_super(fs, j)) + continue; + expect = pblk + EXT2_GROUPS_TO_BLOCKS(fs->super, j); + if (ind_buf[ind_off] != expect) + goto resize_inode_invalid; + ind_off++; + } + } + +cleanup: + if (dind_buf) + ext2fs_free_mem(&dind_buf); + + } + +/* + * This function checks the dirhash signed/unsigned hint if necessary. + */ +static void e2fsck_fix_dirhash_hint(e2fsck_t ctx) +{ + struct ext2_super_block *sb = ctx->fs->super; + struct problem_context pctx; + char c; + + if ((ctx->options & E2F_OPT_READONLY) || + !ext2fs_has_feature_dir_index(sb) || + (sb->s_flags & (EXT2_FLAGS_SIGNED_HASH|EXT2_FLAGS_UNSIGNED_HASH))) + return; + + c = (char) 255; + + clear_problem_context(&pctx); + if (fix_problem(ctx, PR_0_DIRHASH_HINT, &pctx)) { + if (((int) c) == -1) { + sb->s_flags |= EXT2_FLAGS_SIGNED_HASH; + } else { + sb->s_flags |= EXT2_FLAGS_UNSIGNED_HASH; + } + ext2fs_mark_super_dirty(ctx->fs); + } +} + + +void check_super_block(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + blk64_t first_block, last_block; + struct ext2_super_block *sb = fs->super; + unsigned int ipg_max; + problem_t problem; + blk64_t blocks_per_group = fs->super->s_blocks_per_group; + __u32 bpg_max, cpg_max; + __u64 blks_max; + int inodes_per_block; + int inode_size; + int accept_time_fudge; + int broken_system_clock; + dgrp_t i; + blk64_t should_be; + struct problem_context pctx; + blk64_t free_blocks = 0; + ext2_ino_t free_inodes = 0; + int csum_flag, clear_test_fs_flag; + + inodes_per_block = EXT2_INODES_PER_BLOCK(fs->super); + ipg_max = inodes_per_block * (blocks_per_group - 4); + if (ipg_max > EXT2_MAX_INODES_PER_GROUP(sb)) + ipg_max = EXT2_MAX_INODES_PER_GROUP(sb); + cpg_max = 8 * EXT2_BLOCK_SIZE(sb); + if (cpg_max > EXT2_MAX_CLUSTERS_PER_GROUP(sb)) + cpg_max = EXT2_MAX_CLUSTERS_PER_GROUP(sb); + bpg_max = 8 * EXT2_BLOCK_SIZE(sb) * EXT2FS_CLUSTER_RATIO(fs); + if (bpg_max > EXT2_MAX_BLOCKS_PER_GROUP(sb)) + bpg_max = EXT2_MAX_BLOCKS_PER_GROUP(sb); + + ctx->invalid_inode_bitmap_flag = (int *) e2fsck_allocate_memory(ctx, + sizeof(int) * fs->group_desc_count, "invalid_inode_bitmap"); + ctx->invalid_block_bitmap_flag = (int *) e2fsck_allocate_memory(ctx, + sizeof(int) * fs->group_desc_count, "invalid_block_bitmap"); + ctx->invalid_inode_table_flag = (int *) e2fsck_allocate_memory(ctx, + sizeof(int) * fs->group_desc_count, "invalid_inode_table"); + + blks_max = (1ULL << 32) * EXT2_MAX_BLOCKS_PER_GROUP(fs->super); + if (ext2fs_has_feature_64bit(fs->super)) { + if (blks_max > ((1ULL << 48) - 1)) + blks_max = (1ULL << 48) - 1; + } else { + if (blks_max > ((1ULL << 32) - 1)) + blks_max = (1ULL << 32) - 1; + } + + clear_problem_context(&pctx); + + /* + * Verify the super block constants... + */ + if (!check_super_value(ctx, "inodes_count", sb->s_inodes_count, + MIN_CHECK, 1, 0)) + return; + if (!check_super_value64(ctx, "blocks_count", ext2fs_blocks_count(sb), + MIN_CHECK | MAX_CHECK, 1, blks_max)) + return; + if (!check_super_value(ctx, "first_data_block", sb->s_first_data_block, + MAX_CHECK, 0, ext2fs_blocks_count(sb))) + return; + if (!check_super_value(ctx, "log_block_size", sb->s_log_block_size, + MIN_CHECK | MAX_CHECK, 0, + EXT2_MAX_BLOCK_LOG_SIZE - EXT2_MIN_BLOCK_LOG_SIZE)) + return; + if (!check_super_value(ctx, "log_cluster_size", + sb->s_log_cluster_size, + MIN_CHECK | MAX_CHECK, sb->s_log_block_size, + (EXT2_MAX_CLUSTER_LOG_SIZE - + EXT2_MIN_CLUSTER_LOG_SIZE))) + return; + if (!check_super_value(ctx, "clusters_per_group", + sb->s_clusters_per_group, + MIN_CHECK | MAX_CHECK, 8, cpg_max)) + return; + if (!check_super_value(ctx, "blocks_per_group", sb->s_blocks_per_group, + MIN_CHECK | MAX_CHECK, 8, bpg_max)) + return; + if (!check_super_value(ctx, "inodes_per_group", sb->s_inodes_per_group, + MIN_CHECK | MAX_CHECK, inodes_per_block, ipg_max)) + return; + if (!check_super_value(ctx, "r_blocks_count", ext2fs_r_blocks_count(sb), + MAX_CHECK, 0, ext2fs_blocks_count(sb) / 2)) + return; + if (!check_super_value(ctx, "reserved_gdt_blocks", + sb->s_reserved_gdt_blocks, MAX_CHECK, 0, + fs->blocksize / sizeof(__u32))) + return; + if (!check_super_value(ctx, "desc_size", + sb->s_desc_size, MAX_CHECK | LOG2_CHECK, 0, + EXT2_MAX_DESC_SIZE)) + return; + + should_be = (__u64)sb->s_inodes_per_group * fs->group_desc_count; + if (should_be > ~0U) { + pctx.num = should_be; + fix_problem(ctx, PR_0_INODE_COUNT_BIG, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + if (sb->s_inodes_count != should_be) { + pctx.ino = sb->s_inodes_count; + pctx.ino2 = should_be; + if (fix_problem(ctx, PR_0_INODE_COUNT_WRONG, &pctx)) { + sb->s_inodes_count = should_be; + ext2fs_mark_super_dirty(fs); + } else { + pctx.num = sb->s_inodes_count; + pctx.str = "inodes_count"; + fix_problem(ctx, PR_0_MISC_CORRUPT_SUPER, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + if (sb->s_rev_level > EXT2_GOOD_OLD_REV && + !check_super_value(ctx, "first_ino", sb->s_first_ino, + MIN_CHECK | MAX_CHECK, + EXT2_GOOD_OLD_FIRST_INO, sb->s_inodes_count)) + return; + inode_size = EXT2_INODE_SIZE(sb); + if (!check_super_value(ctx, "inode_size", + inode_size, MIN_CHECK | MAX_CHECK | LOG2_CHECK, + EXT2_GOOD_OLD_INODE_SIZE, fs->blocksize)) + return; + if (sb->s_blocks_per_group != (sb->s_clusters_per_group * + EXT2FS_CLUSTER_RATIO(fs))) { + pctx.num = sb->s_clusters_per_group * EXT2FS_CLUSTER_RATIO(fs); + pctx.str = "block_size"; + fix_problem(ctx, PR_0_MISC_CORRUPT_SUPER, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + if ((ctx->flags & E2F_FLAG_GOT_DEVSIZE) && + (ctx->num_blocks < ext2fs_blocks_count(sb))) { + pctx.blk = ext2fs_blocks_count(sb); + pctx.blk2 = ctx->num_blocks; + if (fix_problem(ctx, PR_0_FS_SIZE_WRONG, &pctx)) { + ctx->flags |= E2F_FLAG_ABORT; + return; + } + } + + should_be = (sb->s_log_block_size == 0 && + EXT2FS_CLUSTER_RATIO(fs) == 1) ? 1 : 0; + if (sb->s_first_data_block != should_be) { + pctx.blk = sb->s_first_data_block; + pctx.blk2 = should_be; + fix_problem(ctx, PR_0_FIRST_DATA_BLOCK, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + return; + } + + if (EXT2_INODE_SIZE(sb) > EXT2_GOOD_OLD_INODE_SIZE) { + unsigned min = + sizeof(((struct ext2_inode_large *) 0)->i_extra_isize) + + sizeof(((struct ext2_inode_large *) 0)->i_checksum_hi); + unsigned max = EXT2_INODE_SIZE(sb) - EXT2_GOOD_OLD_INODE_SIZE; + pctx.num = sb->s_min_extra_isize; + if (sb->s_min_extra_isize && + (sb->s_min_extra_isize < min || + sb->s_min_extra_isize > max || + sb->s_min_extra_isize & 3) && + fix_problem(ctx, PR_0_BAD_MIN_EXTRA_ISIZE, &pctx)) { + sb->s_min_extra_isize = + (sizeof(struct ext2_inode_large) - + EXT2_GOOD_OLD_INODE_SIZE); + ext2fs_mark_super_dirty(fs); + } + pctx.num = sb->s_want_extra_isize; + if (sb->s_want_extra_isize && + (sb->s_want_extra_isize < min || + sb->s_want_extra_isize > max || + sb->s_want_extra_isize & 3) && + fix_problem(ctx, PR_0_BAD_WANT_EXTRA_ISIZE, &pctx)) { + sb->s_want_extra_isize = + (sizeof(struct ext2_inode_large) - + EXT2_GOOD_OLD_INODE_SIZE); + ext2fs_mark_super_dirty(fs); + } + } + + /* Are metadata_csum and uninit_bg both set? */ + if (ext2fs_has_feature_metadata_csum(fs->super) && + ext2fs_has_feature_gdt_csum(fs->super) && + fix_problem(ctx, PR_0_META_AND_GDT_CSUM_SET, &pctx)) { + ext2fs_clear_feature_gdt_csum(fs->super); + ext2fs_mark_super_dirty(fs); + for (i = 0; i < fs->group_desc_count; i++) + ext2fs_group_desc_csum_set(fs, i); + } + + /* We can't have ^metadata_csum,metadata_csum_seed */ + if (!ext2fs_has_feature_metadata_csum(fs->super) && + ext2fs_has_feature_csum_seed(fs->super) && + fix_problem(ctx, PR_0_CSUM_SEED_WITHOUT_META_CSUM, &pctx)) { + ext2fs_clear_feature_csum_seed(fs->super); + fs->super->s_checksum_seed = 0; + ext2fs_mark_super_dirty(fs); + } + + /* Is 64bit set and extents unset? */ + if (ext2fs_has_feature_64bit(fs->super) && + !ext2fs_has_feature_extents(fs->super) && + fix_problem(ctx, PR_0_64BIT_WITHOUT_EXTENTS, &pctx)) { + ext2fs_set_feature_extents(fs->super); + ext2fs_mark_super_dirty(fs); + } + + /* Did user ask us to convert files to extents? */ + if (ctx->options & E2F_OPT_CONVERT_BMAP) { + ext2fs_set_feature_extents(fs->super); + ext2fs_mark_super_dirty(fs); + } + + if (ext2fs_has_feature_meta_bg(fs->super) && + (fs->super->s_first_meta_bg > fs->desc_blocks)) { + pctx.group = fs->desc_blocks; + pctx.num = fs->super->s_first_meta_bg; + if (fix_problem(ctx, PR_0_FIRST_META_BG_TOO_BIG, &pctx)) { + ext2fs_clear_feature_meta_bg(fs->super); + fs->super->s_first_meta_bg = 0; + ext2fs_mark_super_dirty(fs); + } + } + + /* + * Verify the group descriptors.... + */ + first_block = sb->s_first_data_block; + last_block = ext2fs_blocks_count(sb)-1; + + csum_flag = ext2fs_has_group_desc_csum(fs); + for (i = 0; i < fs->group_desc_count; i++) { + pctx.group = i; + + if (!ext2fs_has_feature_flex_bg(fs->super)) { + first_block = ext2fs_group_first_block2(fs, i); + last_block = ext2fs_group_last_block2(fs, i); + } + + if ((ext2fs_block_bitmap_loc(fs, i) < first_block) || + (ext2fs_block_bitmap_loc(fs, i) > last_block)) { + pctx.blk = ext2fs_block_bitmap_loc(fs, i); + if (fix_problem(ctx, PR_0_BB_NOT_GROUP, &pctx)) + ext2fs_block_bitmap_loc_set(fs, i, 0); + } + if (ext2fs_block_bitmap_loc(fs, i) == 0) { + ctx->invalid_block_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + if ((ext2fs_inode_bitmap_loc(fs, i) < first_block) || + (ext2fs_inode_bitmap_loc(fs, i) > last_block)) { + pctx.blk = ext2fs_inode_bitmap_loc(fs, i); + if (fix_problem(ctx, PR_0_IB_NOT_GROUP, &pctx)) + ext2fs_inode_bitmap_loc_set(fs, i, 0); + } + if (ext2fs_inode_bitmap_loc(fs, i) == 0) { + ctx->invalid_inode_bitmap_flag[i]++; + ctx->invalid_bitmaps++; + } + if ((ext2fs_inode_table_loc(fs, i) < first_block) || + ((ext2fs_inode_table_loc(fs, i) + + fs->inode_blocks_per_group - 1) > last_block)) { + pctx.blk = ext2fs_inode_table_loc(fs, i); + if (fix_problem(ctx, PR_0_ITABLE_NOT_GROUP, &pctx)) + ext2fs_inode_table_loc_set(fs, i, 0); + } + if (ext2fs_inode_table_loc(fs, i) == 0) { + ctx->invalid_inode_table_flag[i]++; + ctx->invalid_bitmaps++; + } + free_blocks += ext2fs_bg_free_blocks_count(fs, i); + free_inodes += ext2fs_bg_free_inodes_count(fs, i); + + if ((ext2fs_bg_free_blocks_count(fs, i) > sb->s_blocks_per_group) || + (ext2fs_bg_free_inodes_count(fs, i) > sb->s_inodes_per_group) || + (ext2fs_bg_used_dirs_count(fs, i) > sb->s_inodes_per_group)) + ext2fs_unmark_valid(fs); + + should_be = 0; + if (!ext2fs_group_desc_csum_verify(fs, i)) { + pctx.csum1 = ext2fs_bg_checksum(fs, i); + pctx.csum2 = ext2fs_group_desc_csum(fs, i); + if (fix_problem(ctx, PR_0_GDT_CSUM, &pctx)) { + ext2fs_bg_flags_clear(fs, i, EXT2_BG_BLOCK_UNINIT); + ext2fs_bg_flags_clear(fs, i, EXT2_BG_INODE_UNINIT); + ext2fs_bg_itable_unused_set(fs, i, 0); + should_be = 1; + } + ext2fs_unmark_valid(fs); + } + + if (!csum_flag && + (ext2fs_bg_flags_test(fs, i, EXT2_BG_BLOCK_UNINIT) || + ext2fs_bg_flags_test(fs, i, EXT2_BG_INODE_UNINIT) || + ext2fs_bg_itable_unused(fs, i) != 0)) { + if (fix_problem(ctx, PR_0_GDT_UNINIT, &pctx)) { + ext2fs_bg_flags_clear(fs, i, EXT2_BG_BLOCK_UNINIT); + ext2fs_bg_flags_clear(fs, i, EXT2_BG_INODE_UNINIT); + ext2fs_bg_itable_unused_set(fs, i, 0); + should_be = 1; + } + ext2fs_unmark_valid(fs); + } + + if (i == fs->group_desc_count - 1 && + ext2fs_bg_flags_test(fs, i, EXT2_BG_BLOCK_UNINIT)) { + if (fix_problem(ctx, PR_0_BB_UNINIT_LAST, &pctx)) { + ext2fs_bg_flags_clear(fs, i, EXT2_BG_BLOCK_UNINIT); + should_be = 1; + } + ext2fs_unmark_valid(fs); + } + + if (csum_flag && + (ext2fs_bg_itable_unused(fs, i) > ext2fs_bg_free_inodes_count(fs, i) || + ext2fs_bg_itable_unused(fs, i) > sb->s_inodes_per_group)) { + pctx.blk = ext2fs_bg_itable_unused(fs, i); + if (fix_problem(ctx, PR_0_GDT_ITABLE_UNUSED, &pctx)) { + ext2fs_bg_itable_unused_set(fs, i, 0); + should_be = 1; + } + ext2fs_unmark_valid(fs); + } + + if (should_be) + ext2fs_group_desc_csum_set(fs, i); + /* If the user aborts e2fsck by typing ^C, stop right away */ + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + return; + } + + ctx->free_blocks = EXT2FS_C2B(fs, free_blocks); + ctx->free_inodes = free_inodes; + + if ((ext2fs_free_blocks_count(sb) > ext2fs_blocks_count(sb)) || + (sb->s_free_inodes_count > sb->s_inodes_count)) + ext2fs_unmark_valid(fs); + + + /* + * If we have invalid bitmaps, set the error state of the + * filesystem. + */ + if (ctx->invalid_bitmaps && !(ctx->options & E2F_OPT_READONLY)) { + sb->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(fs); + } + + clear_problem_context(&pctx); + +#ifndef EXT2_SKIP_UUID + /* + * If the UUID field isn't assigned, assign it. + * Skip if checksums are enabled and the filesystem is mounted, + * if the id changes under the kernel remounting rw may fail. + */ + if (!(ctx->options & E2F_OPT_READONLY) && uuid_is_null(sb->s_uuid) && + !ext2fs_has_feature_metadata_csum(ctx->fs->super) && + (!csum_flag || !(ctx->mount_flags & EXT2_MF_MOUNTED))) { + if (fix_problem(ctx, PR_0_ADD_UUID, &pctx)) { + uuid_generate(sb->s_uuid); + ext2fs_init_csum_seed(fs); + fs->flags |= EXT2_FLAG_DIRTY; + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } + } +#endif + + /* + * Check to see if we should disable the test_fs flag + */ + profile_get_boolean(ctx->profile, "options", + "clear_test_fs_flag", 0, 1, + &clear_test_fs_flag); + if (!(ctx->options & E2F_OPT_READONLY) && + clear_test_fs_flag && + (fs->super->s_flags & EXT2_FLAGS_TEST_FILESYS) && + (fs_proc_check("ext4") || check_for_modules("ext4"))) { + if (fix_problem(ctx, PR_0_CLEAR_TESTFS_FLAG, &pctx)) { + fs->super->s_flags &= ~EXT2_FLAGS_TEST_FILESYS; + fs->flags |= EXT2_FLAG_DIRTY; + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } + } + + /* + * For the Hurd, check to see if the filetype option is set, + * since it doesn't support it. + */ + if (!(ctx->options & E2F_OPT_READONLY) && + fs->super->s_creator_os == EXT2_OS_HURD && + ext2fs_has_feature_filetype(fs->super)) { + if (fix_problem(ctx, PR_0_HURD_CLEAR_FILETYPE, &pctx)) { + ext2fs_clear_feature_filetype(fs->super); + ext2fs_mark_super_dirty(fs); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } + } + + /* + * If we have any of the compatibility flags set, we need to have a + * revision 1 filesystem. Most kernels will not check the flags on + * a rev 0 filesystem and we may have corruption issues because of + * the incompatible changes to the filesystem. + */ + if (!(ctx->options & E2F_OPT_READONLY) && + fs->super->s_rev_level == EXT2_GOOD_OLD_REV && + (fs->super->s_feature_compat || + fs->super->s_feature_ro_compat || + fs->super->s_feature_incompat) && + fix_problem(ctx, PR_0_FS_REV_LEVEL, &pctx)) { + ext2fs_update_dynamic_rev(fs); + ext2fs_mark_super_dirty(fs); + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } + + /* + * Clean up any orphan inodes, if present. + */ + if (!(ctx->options & E2F_OPT_READONLY) && release_orphan_inodes(ctx)) { + fs->super->s_state &= ~EXT2_VALID_FS; + ext2fs_mark_super_dirty(fs); + } + + /* + * Unfortunately, due to Windows' unfortunate design decision + * to configure the hardware clock to tick localtime, instead + * of the more proper and less error-prone UTC time, many + * users end up in the situation where the system clock is + * incorrectly set at the time when e2fsck is run. + * + * Historically this was usually due to some distributions + * having buggy init scripts and/or installers that didn't + * correctly detect this case and take appropriate + * countermeasures. However, it's still possible, despite the + * best efforts of init script and installer authors to not be + * able to detect this misconfiguration, usually due to a + * buggy or misconfigured virtualization manager or the + * installer not having access to a network time server during + * the installation process. So by default, we allow the + * superblock times to be fudged by up to 24 hours. This can + * be disabled by setting options.accept_time_fudge to the + * boolean value of false in e2fsck.conf. We also support + * options.buggy_init_scripts for backwards compatibility. + */ + profile_get_boolean(ctx->profile, "options", "accept_time_fudge", + 0, 1, &accept_time_fudge); + profile_get_boolean(ctx->profile, "options", "buggy_init_scripts", + 0, accept_time_fudge, &accept_time_fudge); + ctx->time_fudge = accept_time_fudge ? 86400 : 0; + + profile_get_boolean(ctx->profile, "options", "broken_system_clock", + 0, 0, &broken_system_clock); + + /* + * Check to see if the superblock last mount time or last + * write time is in the future. + */ + if (((ctx->options & E2F_OPT_FORCE) || fs->super->s_checkinterval) && + !broken_system_clock && !(ctx->flags & E2F_FLAG_TIME_INSANE) && + (fs->super->s_mtime > (__u32) ctx->now)) { + pctx.num = fs->super->s_mtime; + problem = PR_0_FUTURE_SB_LAST_MOUNT; + if (fs->super->s_mtime <= (__u32) ctx->now + ctx->time_fudge) + problem = PR_0_FUTURE_SB_LAST_MOUNT_FUDGED; + if (fix_problem(ctx, problem, &pctx)) { + fs->super->s_mtime = ctx->now; + fs->flags |= EXT2_FLAG_DIRTY; + } + } + if (((ctx->options & E2F_OPT_FORCE) || fs->super->s_checkinterval) && + !broken_system_clock && !(ctx->flags & E2F_FLAG_TIME_INSANE) && + (fs->super->s_wtime > (__u32) ctx->now)) { + pctx.num = fs->super->s_wtime; + problem = PR_0_FUTURE_SB_LAST_WRITE; + if (fs->super->s_wtime <= (__u32) ctx->now + ctx->time_fudge) + problem = PR_0_FUTURE_SB_LAST_WRITE_FUDGED; + if (fix_problem(ctx, problem, &pctx)) { + fs->super->s_wtime = ctx->now; + fs->flags |= EXT2_FLAG_DIRTY; + } + } + + e2fsck_validate_quota_inodes(ctx); + + /* + * Move the ext3 journal file, if necessary. + */ + e2fsck_move_ext3_journal(ctx); + + /* + * Fix journal hint, if necessary + */ + e2fsck_fix_ext3_journal_hint(ctx); + + /* + * Add dirhash hint if necessary + */ + e2fsck_fix_dirhash_hint(ctx); + + /* + * Hide quota inodes if necessary. + */ + e2fsck_hide_quota(ctx); + + return; +} + +/* + * Check to see if we should backup the master sb to the backup super + * blocks. Returns non-zero if the sb should be backed up. + */ + +/* + * A few flags are set on the fly by the kernel, but only in the + * primary superblock. This is actually a bad thing, and we should + * try to discourage it in the future. In particular, for the newer + * ext4 files, especially EXT4_FEATURE_RO_COMPAT_DIR_NLINK and + * EXT3_FEATURE_INCOMPAT_EXTENTS. So some of these may go away in the + * future. EXT3_FEATURE_INCOMPAT_RECOVER may also get set when + * copying the primary superblock during online resize. + * + * The kernel will set EXT2_FEATURE_COMPAT_EXT_ATTR, but + * unfortunately, we shouldn't ignore it since if it's not set in the + * backup, the extended attributes in the filesystem will be stripped + * away. + */ +#define FEATURE_RO_COMPAT_IGNORE (EXT2_FEATURE_RO_COMPAT_LARGE_FILE| \ + EXT4_FEATURE_RO_COMPAT_DIR_NLINK) +#define FEATURE_INCOMPAT_IGNORE (EXT3_FEATURE_INCOMPAT_EXTENTS| \ + EXT3_FEATURE_INCOMPAT_RECOVER) + +int check_backup_super_block(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + dgrp_t g; + blk64_t sb; + int ret = 0; + char buf[SUPERBLOCK_SIZE]; + struct ext2_super_block *backup_sb; + + /* + * If we are already writing out the backup blocks, then we + * don't need to test. Also, if the filesystem is invalid, or + * the check was aborted or cancelled, we also don't want to + * do the backup. If the filesystem was opened read-only then + * we can't do the backup. + */ + if (((fs->flags & EXT2_FLAG_MASTER_SB_ONLY) == 0) || + !ext2fs_test_valid(fs) || + (fs->super->s_state & EXT2_ERROR_FS) || + (ctx->flags & (E2F_FLAG_ABORT | E2F_FLAG_CANCEL)) || + (ctx->options & E2F_OPT_READONLY)) + return 0; + + for (g = 1; g < fs->group_desc_count; g++) { + if (!ext2fs_bg_has_super(fs, g)) + continue; + + sb = ext2fs_group_first_block2(fs, g); + + retval = io_channel_read_blk(fs->io, sb, -SUPERBLOCK_SIZE, + buf); + if (retval) + continue; + backup_sb = (struct ext2_super_block *) buf; +#ifdef WORDS_BIGENDIAN + ext2fs_swap_super(backup_sb); +#endif + if ((backup_sb->s_magic != EXT2_SUPER_MAGIC) || + (backup_sb->s_rev_level > EXT2_LIB_CURRENT_REV) || + ((backup_sb->s_log_block_size + EXT2_MIN_BLOCK_LOG_SIZE) > + EXT2_MAX_BLOCK_LOG_SIZE) || + (EXT2_INODE_SIZE(backup_sb) < EXT2_GOOD_OLD_INODE_SIZE)) + continue; + +#define SUPER_INCOMPAT_DIFFERENT(x) \ + ((fs->super->x & ~FEATURE_INCOMPAT_IGNORE) != \ + (backup_sb->x & ~FEATURE_INCOMPAT_IGNORE)) +#define SUPER_RO_COMPAT_DIFFERENT(x) \ + ((fs->super->x & ~FEATURE_RO_COMPAT_IGNORE) != \ + (backup_sb->x & ~FEATURE_RO_COMPAT_IGNORE)) +#define SUPER_DIFFERENT(x) \ + (fs->super->x != backup_sb->x) + + if (SUPER_DIFFERENT(s_feature_compat) || + SUPER_INCOMPAT_DIFFERENT(s_feature_incompat) || + SUPER_RO_COMPAT_DIFFERENT(s_feature_ro_compat) || + SUPER_DIFFERENT(s_blocks_count) || + SUPER_DIFFERENT(s_blocks_count_hi) || + SUPER_DIFFERENT(s_inodes_count) || + memcmp(fs->super->s_uuid, backup_sb->s_uuid, + sizeof(fs->super->s_uuid))) + ret = 1; + break; + } + return ret; +} diff --git a/e2fsck/unix.c b/e2fsck/unix.c new file mode 100644 index 0000000..e5b672a --- /dev/null +++ b/e2fsck/unix.c @@ -0,0 +1,2171 @@ +/* + * unix.c - The unix-specific code for e2fsck + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#define _XOPEN_SOURCE 600 /* for inclusion of sa_handler in Solaris */ + +#include "config.h" +#include <stdio.h> +#ifdef HAVE_STDLIB_H +#include <stdlib.h> +#endif +#include <string.h> +#include <fcntl.h> +#include <ctype.h> +#include <time.h> +#ifdef HAVE_SIGNAL_H +#include <signal.h> +#endif +#ifdef HAVE_GETOPT_H +#include <getopt.h> +#else +extern char *optarg; +extern int optind; +#endif +#include <unistd.h> +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_MALLOC_H +#include <malloc.h> +#endif +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_DIRENT_H +#include <dirent.h> +#endif +#include <libgen.h> + +#include "e2p/e2p.h" +#include "et/com_err.h" +#include "e2p/e2p.h" +#include "uuid/uuid.h" +#include "support/plausible.h" +#include "support/devname.h" +#include "e2fsck.h" +#include "problem.h" +#include "jfs_user.h" +#include "../version.h" + +/* Command line options */ +static int cflag; /* check disk */ +static int show_version_only; +static int verbose; + +static int replace_bad_blocks; +static int keep_bad_blocks; +static char *bad_blocks_file; + +e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */ + +#ifdef CONFIG_JBD_DEBUG /* Enabled by configure --enable-jbd-debug */ +int journal_enable_debug = -1; +#endif + +static void usage(e2fsck_t ctx) +{ + fprintf(stderr, + _("Usage: %s [-panyrcdfktvDFV] [-b superblock] [-B blocksize]\n" + "\t\t[-l|-L bad_blocks_file] [-C fd] [-j external_journal]\n" + "\t\t[-E extended-options] [-z undo_file] device\n"), + ctx->program_name ? ctx->program_name : "e2fsck"); + + fprintf(stderr, "%s", _("\nEmergency help:\n" + " -p Automatic repair (no questions)\n" + " -n Make no changes to the filesystem\n" + " -y Assume \"yes\" to all questions\n" + " -c Check for bad blocks and add them to the badblock list\n" + " -f Force checking even if filesystem is marked clean\n")); + fprintf(stderr, "%s", _("" + " -v Be verbose\n" + " -b superblock Use alternative superblock\n" + " -B blocksize Force blocksize when looking for superblock\n" + " -j external_journal Set location of the external journal\n" + " -l bad_blocks_file Add to badblocks list\n" + " -L bad_blocks_file Set badblocks list\n" + " -z undo_file Create an undo file\n" + )); + + exit(FSCK_USAGE); +} + +static void show_stats(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + ext2_ino_t inodes, inodes_used; + blk64_t blocks, blocks_used; + unsigned int dir_links; + unsigned int num_files, num_links; + __u32 *mask, m; + int frag_percent_file = 0, frag_percent_dir = 0, frag_percent_total = 0; + int i, j, printed = 0; + + dir_links = 2 * ctx->fs_directory_count - 1; + num_files = ctx->fs_total_count - dir_links; + num_links = ctx->fs_links_count - dir_links; + inodes = fs->super->s_inodes_count; + inodes_used = (fs->super->s_inodes_count - + fs->super->s_free_inodes_count); + blocks = ext2fs_blocks_count(fs->super); + blocks_used = (ext2fs_blocks_count(fs->super) - + ext2fs_free_blocks_count(fs->super)); + + if (inodes_used > 0) { + frag_percent_file = (10000 * ctx->fs_fragmented) / inodes_used; + frag_percent_file = (frag_percent_file + 5) / 10; + + frag_percent_dir = (10000 * ctx->fs_fragmented_dir) / inodes_used; + frag_percent_dir = (frag_percent_dir + 5) / 10; + + frag_percent_total = ((10000 * (ctx->fs_fragmented + + ctx->fs_fragmented_dir)) + / inodes_used); + frag_percent_total = (frag_percent_total + 5) / 10; + } + + if (!verbose) { + log_out(ctx, _("%s: %u/%u files (%0d.%d%% non-contiguous), " + "%llu/%llu blocks\n"), + ctx->device_name, inodes_used, inodes, + frag_percent_total / 10, frag_percent_total % 10, + (unsigned long long) blocks_used, + (unsigned long long) blocks); + return; + } + profile_get_boolean(ctx->profile, "options", "report_features", 0, 0, + &i); + if (verbose && i) { + log_out(ctx, "\nFilesystem features:"); + mask = &ctx->fs->super->s_feature_compat; + for (i = 0; i < 3; i++, mask++) { + for (j = 0, m = 1; j < 32; j++, m <<= 1) { + if (*mask & m) { + log_out(ctx, " %s", + e2p_feature2string(i, m)); + printed++; + } + } + } + if (printed == 0) + log_out(ctx, " (none)"); + log_out(ctx, "\n"); + } + + log_out(ctx, P_("\n%12u inode used (%2.2f%%, out of %u)\n", + "\n%12u inodes used (%2.2f%%, out of %u)\n", + inodes_used), inodes_used, + 100.0 * inodes_used / inodes, inodes); + log_out(ctx, P_("%12u non-contiguous file (%0d.%d%%)\n", + "%12u non-contiguous files (%0d.%d%%)\n", + ctx->fs_fragmented), + ctx->fs_fragmented, frag_percent_file / 10, + frag_percent_file % 10); + log_out(ctx, P_("%12u non-contiguous directory (%0d.%d%%)\n", + "%12u non-contiguous directories (%0d.%d%%)\n", + ctx->fs_fragmented_dir), + ctx->fs_fragmented_dir, frag_percent_dir / 10, + frag_percent_dir % 10); + log_out(ctx, _(" # of inodes with ind/dind/tind blocks: " + "%u/%u/%u\n"), + ctx->fs_ind_count, ctx->fs_dind_count, ctx->fs_tind_count); + + for (j=MAX_EXTENT_DEPTH_COUNT-1; j >=0; j--) + if (ctx->extent_depth_count[j]) + break; + if (++j) { + log_out(ctx, "%s", _(" Extent depth histogram: ")); + for (i=0; i < j; i++) { + if (i) + fputc('/', stdout); + log_out(ctx, "%u", ctx->extent_depth_count[i]); + } + log_out(ctx, "\n"); + } + + log_out(ctx, P_("%12llu block used (%2.2f%%, out of %llu)\n", + "%12llu blocks used (%2.2f%%, out of %llu)\n", + blocks_used), + (unsigned long long) blocks_used, 100.0 * blocks_used / blocks, + (unsigned long long) blocks); + log_out(ctx, P_("%12u bad block\n", "%12u bad blocks\n", + ctx->fs_badblocks_count), ctx->fs_badblocks_count); + log_out(ctx, P_("%12u large file\n", "%12u large files\n", + ctx->large_files), ctx->large_files); + log_out(ctx, P_("\n%12u regular file\n", "\n%12u regular files\n", + ctx->fs_regular_count), ctx->fs_regular_count); + log_out(ctx, P_("%12u directory\n", "%12u directories\n", + ctx->fs_directory_count), ctx->fs_directory_count); + log_out(ctx, P_("%12u character device file\n", + "%12u character device files\n", ctx->fs_chardev_count), + ctx->fs_chardev_count); + log_out(ctx, P_("%12u block device file\n", "%12u block device files\n", + ctx->fs_blockdev_count), ctx->fs_blockdev_count); + log_out(ctx, P_("%12u fifo\n", "%12u fifos\n", ctx->fs_fifo_count), + ctx->fs_fifo_count); + log_out(ctx, P_("%12u link\n", "%12u links\n", num_links), + ctx->fs_links_count - dir_links); + log_out(ctx, P_("%12u symbolic link", "%12u symbolic links", + ctx->fs_symlinks_count), ctx->fs_symlinks_count); + log_out(ctx, P_(" (%u fast symbolic link)\n", + " (%u fast symbolic links)\n", + ctx->fs_fast_symlinks_count), + ctx->fs_fast_symlinks_count); + log_out(ctx, P_("%12u socket\n", "%12u sockets\n", + ctx->fs_sockets_count), + ctx->fs_sockets_count); + log_out(ctx, "------------\n"); + log_out(ctx, P_("%12u file\n", "%12u files\n", num_files), + num_files); +} + +static void check_mount(e2fsck_t ctx) +{ + errcode_t retval; + int cont; + + retval = ext2fs_check_if_mounted(ctx->filesystem_name, + &ctx->mount_flags); + if (retval) { + com_err("ext2fs_check_if_mount", retval, + _("while determining whether %s is mounted."), + ctx->filesystem_name); + return; + } + + /* + * If the filesystem isn't mounted, or it's the root + * filesystem and it's mounted read-only, and we're not doing + * a read/write check, then everything's fine. + */ + if ((!(ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY))) || + ((ctx->mount_flags & EXT2_MF_ISROOT) && + (ctx->mount_flags & EXT2_MF_READONLY) && + !(ctx->options & E2F_OPT_WRITECHECK))) + return; + + if (((ctx->options & E2F_OPT_READONLY) || + ((ctx->options & E2F_OPT_FORCE) && + (ctx->mount_flags & EXT2_MF_READONLY))) && + !(ctx->options & E2F_OPT_WRITECHECK)) { + if (ctx->mount_flags & EXT2_MF_MOUNTED) + log_out(ctx, _("Warning! %s is mounted.\n"), + ctx->filesystem_name); + else + log_out(ctx, _("Warning! %s is in use.\n"), + ctx->filesystem_name); + return; + } + + if (ctx->mount_flags & EXT2_MF_MOUNTED) + log_out(ctx, _("%s is mounted.\n"), ctx->filesystem_name); + else + log_out(ctx, _("%s is in use.\n"), ctx->filesystem_name); + if (!ctx->interactive || ctx->mount_flags & EXT2_MF_BUSY) + fatal_error(ctx, _("Cannot continue, aborting.\n\n")); + puts("\007\007\007\007"); + log_out(ctx, "%s", _("\n\nWARNING!!! " + "The filesystem is mounted. " + "If you continue you ***WILL***\n" + "cause ***SEVERE*** filesystem damage.\n\n")); + puts("\007\007\007"); + cont = ask_yn(ctx, _("Do you really want to continue"), 0); + if (!cont) { + printf("%s", _("check aborted.\n")); + exit (0); + } + return; +} + +static int is_on_batt(void) +{ + FILE *f; + DIR *d; + char tmp[80], tmp2[80], fname[NAME_MAX+30]; + unsigned int acflag; + struct dirent* de; + + f = fopen("/sys/class/power_supply/AC/online", "r"); + if (f) { + if (fscanf(f, "%u\n", &acflag) == 1) { + fclose(f); + return (!acflag); + } + fclose(f); + } + f = fopen("/proc/apm", "r"); + if (f) { + if (fscanf(f, "%79s %79s %79s %x", tmp, tmp, tmp, &acflag) != 4) + acflag = 1; + fclose(f); + return (acflag != 1); + } + d = opendir("/proc/acpi/ac_adapter"); + if (d) { + while ((de=readdir(d)) != NULL) { + if (!strncmp(".", de->d_name, 1)) + continue; + snprintf(fname, sizeof(fname), + "/proc/acpi/ac_adapter/%s/state", + de->d_name); + f = fopen(fname, "r"); + if (!f) + continue; + if (fscanf(f, "%79s %79s", tmp2, tmp) != 2) + tmp[0] = 0; + fclose(f); + if (strncmp(tmp, "off-line", 8) == 0) { + closedir(d); + return 1; + } + } + closedir(d); + } + return 0; +} + +/* + * This routine checks to see if a filesystem can be skipped; if so, + * it will exit with E2FSCK_OK. Under some conditions it will print a + * message explaining why a check is being forced. + */ +static void check_if_skip(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + struct problem_context pctx; + const char *reason = NULL; + unsigned int reason_arg = 0; + long next_check; + int batt = is_on_batt(); + int defer_check_on_battery; + int broken_system_clock; + time_t lastcheck; + + if (ctx->flags & E2F_FLAG_PROBLEMS_FIXED) + return; + + profile_get_boolean(ctx->profile, "options", "broken_system_clock", + 0, 0, &broken_system_clock); + if (ctx->flags & E2F_FLAG_TIME_INSANE) + broken_system_clock = 1; + profile_get_boolean(ctx->profile, "options", + "defer_check_on_battery", 0, 1, + &defer_check_on_battery); + if (!defer_check_on_battery) + batt = 0; + + if ((ctx->options & E2F_OPT_FORCE) || bad_blocks_file || cflag) + return; + + if (ctx->options & E2F_OPT_JOURNAL_ONLY) + goto skip; + + lastcheck = fs->super->s_lastcheck; + if (lastcheck > ctx->now) + lastcheck -= ctx->time_fudge; + if ((fs->super->s_state & EXT2_ERROR_FS) || + !ext2fs_test_valid(fs)) + reason = _(" contains a file system with errors"); + else if ((fs->super->s_state & EXT2_VALID_FS) == 0) + reason = _(" was not cleanly unmounted"); + else if (check_backup_super_block(ctx)) + reason = _(" primary superblock features different from backup"); + else if ((fs->super->s_max_mnt_count > 0) && + (fs->super->s_mnt_count >= + (unsigned) fs->super->s_max_mnt_count)) { + reason = _(" has been mounted %u times without being checked"); + reason_arg = fs->super->s_mnt_count; + if (batt && (fs->super->s_mnt_count < + (unsigned) fs->super->s_max_mnt_count*2)) + reason = 0; + } else if (!broken_system_clock && fs->super->s_checkinterval && + (ctx->now < lastcheck)) { + reason = _(" has filesystem last checked time in the future"); + if (batt) + reason = 0; + } else if (!broken_system_clock && fs->super->s_checkinterval && + ((ctx->now - lastcheck) >= + ((time_t) fs->super->s_checkinterval))) { + reason = _(" has gone %u days without being checked"); + reason_arg = (ctx->now - fs->super->s_lastcheck)/(3600*24); + if (batt && ((ctx->now - fs->super->s_lastcheck) < + fs->super->s_checkinterval*2)) + reason = 0; + } else if (broken_system_clock && fs->super->s_checkinterval) { + log_out(ctx, "%s: ", ctx->device_name); + log_out(ctx, "%s", + _("ignoring check interval, broken_system_clock set\n")); + } + + if (reason) { + log_out(ctx, "%s", ctx->device_name); + log_out(ctx, reason, reason_arg); + log_out(ctx, "%s", _(", check forced.\n")); + return; + } + + /* + * Update the global counts from the block group counts. This + * is needed since modern kernels don't update the global + * counts so as to avoid locking the entire file system. So + * if the filesystem is not unmounted cleanly, the global + * counts may not be accurate. Update them here if we can, + * for the benefit of users who might examine the file system + * using dumpe2fs. (This is for cosmetic reasons only.) + */ + clear_problem_context(&pctx); + pctx.ino = fs->super->s_free_inodes_count; + pctx.ino2 = ctx->free_inodes; + if ((pctx.ino != pctx.ino2) && + !(ctx->options & E2F_OPT_READONLY) && + fix_problem(ctx, PR_0_FREE_INODE_COUNT, &pctx)) { + fs->super->s_free_inodes_count = ctx->free_inodes; + ext2fs_mark_super_dirty(fs); + } + clear_problem_context(&pctx); + pctx.blk = ext2fs_free_blocks_count(fs->super); + pctx.blk2 = ctx->free_blocks; + if ((pctx.blk != pctx.blk2) && + !(ctx->options & E2F_OPT_READONLY) && + fix_problem(ctx, PR_0_FREE_BLOCK_COUNT, &pctx)) { + ext2fs_free_blocks_count_set(fs->super, ctx->free_blocks); + ext2fs_mark_super_dirty(fs); + } + + /* Print the summary message when we're skipping a full check */ + log_out(ctx, _("%s: clean, %u/%u files, %llu/%llu blocks"), + ctx->device_name, + fs->super->s_inodes_count - fs->super->s_free_inodes_count, + fs->super->s_inodes_count, + (unsigned long long) ext2fs_blocks_count(fs->super) - + ext2fs_free_blocks_count(fs->super), + (unsigned long long) ext2fs_blocks_count(fs->super)); + next_check = 100000; + if (fs->super->s_max_mnt_count > 0) { + next_check = fs->super->s_max_mnt_count - fs->super->s_mnt_count; + if (next_check <= 0) + next_check = 1; + } + if (!broken_system_clock && fs->super->s_checkinterval && + ((ctx->now - fs->super->s_lastcheck) >= fs->super->s_checkinterval)) + next_check = 1; + if (next_check <= 5) { + if (next_check == 1) { + if (batt) + log_out(ctx, "%s", + _(" (check deferred; on battery)")); + else + log_out(ctx, "%s", + _(" (check after next mount)")); + } else + log_out(ctx, _(" (check in %ld mounts)"), + next_check); + } + log_out(ctx, "\n"); +skip: + ext2fs_close_free(&ctx->fs); + e2fsck_free_context(ctx); + exit(FSCK_OK); +} + +/* + * For completion notice + */ +struct percent_tbl { + int max_pass; + int table[32]; +}; +static struct percent_tbl e2fsck_tbl = { + 5, { 0, 70, 90, 92, 95, 100 } +}; +static char bar[128], spaces[128]; + +static float calc_percent(struct percent_tbl *tbl, int pass, int curr, + int max) +{ + float percent; + + if (pass <= 0) + return 0.0; + if (pass > tbl->max_pass || max == 0) + return 100.0; + percent = ((float) curr) / ((float) max); + return ((percent * (tbl->table[pass] - tbl->table[pass-1])) + + tbl->table[pass-1]); +} + +void e2fsck_clear_progbar(e2fsck_t ctx) +{ + if (!(ctx->flags & E2F_FLAG_PROG_BAR)) + return; + + printf("%s%s\r%s", ctx->start_meta, spaces + (sizeof(spaces) - 80), + ctx->stop_meta); + fflush(stdout); + ctx->flags &= ~E2F_FLAG_PROG_BAR; +} + +int e2fsck_simple_progress(e2fsck_t ctx, const char *label, float percent, + unsigned int dpynum) +{ + static const char spinner[] = "\\|/-"; + int i; + unsigned int tick; + struct timeval tv; + int dpywidth; + int fixed_percent; + + if (ctx->flags & E2F_FLAG_PROG_SUPPRESS) + return 0; + + /* + * Calculate the new progress position. If the + * percentage hasn't changed, then we skip out right + * away. + */ + fixed_percent = (int) ((10 * percent) + 0.5); + if (ctx->progress_last_percent == fixed_percent) + return 0; + ctx->progress_last_percent = fixed_percent; + + /* + * If we've already updated the spinner once within + * the last 1/8th of a second, no point doing it + * again. + */ + gettimeofday(&tv, NULL); + tick = (tv.tv_sec << 3) + (tv.tv_usec / (1000000 / 8)); + if ((tick == ctx->progress_last_time) && + (fixed_percent != 0) && (fixed_percent != 1000)) + return 0; + ctx->progress_last_time = tick; + + /* + * Advance the spinner, and note that the progress bar + * will be on the screen + */ + ctx->progress_pos = (ctx->progress_pos+1) & 3; + ctx->flags |= E2F_FLAG_PROG_BAR; + + dpywidth = 66 - strlen(label); + dpywidth = 8 * (dpywidth / 8); + if (dpynum) + dpywidth -= 8; + + i = ((percent * dpywidth) + 50) / 100; + printf("%s%s: |%s%s", ctx->start_meta, label, + bar + (sizeof(bar) - (i+1)), + spaces + (sizeof(spaces) - (dpywidth - i + 1))); + if (fixed_percent == 1000) + fputc('|', stdout); + else + fputc(spinner[ctx->progress_pos & 3], stdout); + printf(" %4.1f%% ", percent); + if (dpynum) + printf("%u\r", dpynum); + else + fputs(" \r", stdout); + fputs(ctx->stop_meta, stdout); + + if (fixed_percent == 1000) + e2fsck_clear_progbar(ctx); + fflush(stdout); + + return 0; +} + +static int e2fsck_update_progress(e2fsck_t ctx, int pass, + unsigned long cur, unsigned long max) +{ + char buf[1024]; + float percent; + + if (pass == 0) + return 0; + + if (ctx->progress_fd) { + snprintf(buf, sizeof(buf), "%d %lu %lu %s\n", + pass, cur, max, ctx->device_name); + write_all(ctx->progress_fd, buf, strlen(buf)); + } else { + percent = calc_percent(&e2fsck_tbl, pass, cur, max); + e2fsck_simple_progress(ctx, ctx->device_name, + percent, 0); + } + return 0; +} + +#define PATH_SET "PATH=/sbin" + +/* + * Make sure 0,1,2 file descriptors are open, so that we don't open + * the filesystem using the same file descriptor as stdout or stderr. + */ +static void reserve_stdio_fds(void) +{ + int fd = 0; + + while (fd <= 2) { + fd = open("/dev/null", O_RDWR); + if (fd < 0) { + fprintf(stderr, _("ERROR: Couldn't open " + "/dev/null (%s)\n"), + strerror(errno)); + return; + } + } + (void) close(fd); +} + +#ifdef HAVE_SIGNAL_H +static void signal_progress_on(int sig EXT2FS_ATTR((unused))) +{ + e2fsck_t ctx = e2fsck_global_ctx; + + if (!ctx) + return; + + ctx->progress = e2fsck_update_progress; +} + +static void signal_progress_off(int sig EXT2FS_ATTR((unused))) +{ + e2fsck_t ctx = e2fsck_global_ctx; + + if (!ctx) + return; + + e2fsck_clear_progbar(ctx); + ctx->progress = 0; +} + +static void signal_cancel(int sig EXT2FS_ATTR((unused))) +{ + e2fsck_t ctx = e2fsck_global_ctx; + + if (!ctx) + exit(FSCK_CANCELED); + + ctx->flags |= E2F_FLAG_CANCEL; +} +#endif + +static void parse_extended_opts(e2fsck_t ctx, const char *opts) +{ + char *buf, *token, *next, *p, *arg; + int ea_ver; + int extended_usage = 0; + unsigned long long reada_kb; + + buf = string_copy(ctx, opts, 0); + for (token = buf; token && *token; token = next) { + p = strchr(token, ','); + next = 0; + if (p) { + *p = 0; + next = p+1; + } + arg = strchr(token, '='); + if (arg) { + *arg = 0; + arg++; + } + if (strcmp(token, "ea_ver") == 0) { + if (!arg) { + extended_usage++; + continue; + } + ea_ver = strtoul(arg, &p, 0); + if (*p || + ((ea_ver != 1) && (ea_ver != 2))) { + fprintf(stderr, "%s", + _("Invalid EA version.\n")); + extended_usage++; + continue; + } + ctx->ext_attr_ver = ea_ver; + } else if (strcmp(token, "readahead_kb") == 0) { + if (!arg) { + extended_usage++; + continue; + } + reada_kb = strtoull(arg, &p, 0); + if (*p) { + fprintf(stderr, "%s", + _("Invalid readahead buffer size.\n")); + extended_usage++; + continue; + } + ctx->readahead_kb = reada_kb; + } else if (strcmp(token, "fragcheck") == 0) { + ctx->options |= E2F_OPT_FRAGCHECK; + continue; + } else if (strcmp(token, "journal_only") == 0) { + if (arg) { + extended_usage++; + continue; + } + ctx->options |= E2F_OPT_JOURNAL_ONLY; + } else if (strcmp(token, "discard") == 0) { + ctx->options |= E2F_OPT_DISCARD; + continue; + } else if (strcmp(token, "nodiscard") == 0) { + ctx->options &= ~E2F_OPT_DISCARD; + continue; + } else if (strcmp(token, "optimize_extents") == 0) { + ctx->options &= ~E2F_OPT_NOOPT_EXTENTS; + continue; + } else if (strcmp(token, "no_optimize_extents") == 0) { + ctx->options |= E2F_OPT_NOOPT_EXTENTS; + continue; + } else if (strcmp(token, "inode_count_fullmap") == 0) { + ctx->options |= E2F_OPT_ICOUNT_FULLMAP; + continue; + } else if (strcmp(token, "no_inode_count_fullmap") == 0) { + ctx->options &= ~E2F_OPT_ICOUNT_FULLMAP; + continue; + } else if (strcmp(token, "log_filename") == 0) { + if (!arg) + extended_usage++; + else + ctx->log_fn = string_copy(ctx, arg, 0); + continue; + } else if (strcmp(token, "problem_log") == 0) { + if (!arg) + extended_usage++; + else + ctx->problem_log_fn = string_copy(ctx, arg, 0); + continue; + } else if (strcmp(token, "bmap2extent") == 0) { + ctx->options |= E2F_OPT_CONVERT_BMAP; + continue; + } else if (strcmp(token, "fixes_only") == 0) { + ctx->options |= E2F_OPT_FIXES_ONLY; + continue; + } else if (strcmp(token, "unshare_blocks") == 0) { + ctx->options |= E2F_OPT_UNSHARE_BLOCKS; + ctx->options |= E2F_OPT_FORCE; + continue; + } else if (strcmp(token, "check_encoding") == 0) { + ctx->options |= E2F_OPT_CHECK_ENCODING; + continue; +#ifdef CONFIG_DEVELOPER_FEATURES + } else if (strcmp(token, "clear_all_uninit_bits") == 0) { + ctx->options |= E2F_OPT_CLEAR_UNINIT; + continue; +#endif + } else { + fprintf(stderr, _("Unknown extended option: %s\n"), + token); + extended_usage++; + } + } + free(buf); + + if (extended_usage) { + fputs(_("\nExtended options are separated by commas, " + "and may take an argument which\n" + "is set off by an equals ('=') sign. " + "Valid extended options are:\n\n"), stderr); + fputs(_("\tea_ver=<ea_version (1 or 2)>\n"), stderr); + fputs("\tfragcheck\n", stderr); + fputs("\tjournal_only\n", stderr); + fputs("\tdiscard\n", stderr); + fputs("\tnodiscard\n", stderr); + fputs("\toptimize_extents\n", stderr); + fputs("\tno_optimize_extents\n", stderr); + fputs("\tinode_count_fullmap\n", stderr); + fputs("\tno_inode_count_fullmap\n", stderr); + fputs(_("\treadahead_kb=<buffer size>\n"), stderr); + fputs("\tbmap2extent\n", stderr); + fputs("\tunshare_blocks\n", stderr); + fputs("\tfixes_only\n", stderr); + fputs("\tcheck_encoding\n", stderr); + fputc('\n', stderr); + exit(1); + } +} + +static void syntax_err_report(const char *filename, long err, int line_num) +{ + fprintf(stderr, + _("Syntax error in e2fsck config file (%s, line #%d)\n\t%s\n"), + filename, line_num, error_message(err)); + exit(FSCK_ERROR); +} + +static const char *config_fn[] = { ROOT_SYSCONFDIR "/e2fsck.conf", 0 }; + +static errcode_t PRS(int argc, char *argv[], e2fsck_t *ret_ctx) +{ + int flush = 0; + int c, fd; +#ifdef MTRACE + extern void *mallwatch; +#endif + e2fsck_t ctx; + errcode_t retval; +#ifdef HAVE_SIGNAL_H + struct sigaction sa; +#endif + char *extended_opts = 0; + char *cp; + int res; /* result of sscanf */ +#ifdef CONFIG_JBD_DEBUG + char *jbd_debug; +#endif + unsigned long long phys_mem_kb, blk; + + retval = e2fsck_allocate_context(&ctx); + if (retval) + return retval; + + *ret_ctx = ctx; + e2fsck_global_ctx = ctx; + + setvbuf(stdout, NULL, _IONBF, BUFSIZ); + setvbuf(stderr, NULL, _IONBF, BUFSIZ); + if (getenv("E2FSCK_FORCE_INTERACTIVE") || (isatty(0) && isatty(1))) { + ctx->interactive = 1; + } else { + ctx->start_meta[0] = '\001'; + ctx->stop_meta[0] = '\002'; + } + memset(bar, '=', sizeof(bar)-1); + memset(spaces, ' ', sizeof(spaces)-1); + add_error_table(&et_ext2_error_table); + add_error_table(&et_prof_error_table); + blkid_get_cache(&ctx->blkid, NULL); + + if (argc && *argv) + ctx->program_name = *argv; + else + usage(NULL); + + phys_mem_kb = get_memory_size() / 1024; + ctx->readahead_kb = ~0ULL; + while ((c = getopt(argc, argv, "panyrcC:B:dE:fvtFVM:b:I:j:P:l:L:N:SsDkz:")) != EOF) + switch (c) { + case 'C': + ctx->progress = e2fsck_update_progress; + res = sscanf(optarg, "%d", &ctx->progress_fd); + if (res != 1) + goto sscanf_err; + + if (ctx->progress_fd < 0) { + ctx->progress = 0; + ctx->progress_fd = ctx->progress_fd * -1; + } + if (!ctx->progress_fd) + break; + /* Validate the file descriptor to avoid disasters */ + fd = dup(ctx->progress_fd); + if (fd < 0) { + fprintf(stderr, + _("Error validating file descriptor %d: %s\n"), + ctx->progress_fd, + error_message(errno)); + fatal_error(ctx, + _("Invalid completion information file descriptor")); + } else + close(fd); + break; + case 'D': + ctx->options |= E2F_OPT_COMPRESS_DIRS; + break; + case 'E': + extended_opts = optarg; + break; + case 'p': + case 'a': + if (ctx->options & (E2F_OPT_YES|E2F_OPT_NO)) { + conflict_opt: + fatal_error(ctx, + _("Only one of the options -p/-a, -n or -y may be specified.")); + } + ctx->options |= E2F_OPT_PREEN; + break; + case 'n': + if (ctx->options & (E2F_OPT_YES|E2F_OPT_PREEN)) + goto conflict_opt; + ctx->options |= E2F_OPT_NO; + break; + case 'y': + if (ctx->options & (E2F_OPT_PREEN|E2F_OPT_NO)) + goto conflict_opt; + ctx->options |= E2F_OPT_YES; + break; + case 't': +#ifdef RESOURCE_TRACK + if (ctx->options & E2F_OPT_TIME) + ctx->options |= E2F_OPT_TIME2; + else + ctx->options |= E2F_OPT_TIME; +#else + fprintf(stderr, _("The -t option is not " + "supported on this version of e2fsck.\n")); +#endif + break; + case 'c': + if (cflag++) + ctx->options |= E2F_OPT_WRITECHECK; + ctx->options |= E2F_OPT_CHECKBLOCKS; + break; + case 'r': + /* What we do by default, anyway! */ + break; + case 'b': + res = sscanf(optarg, "%llu", &blk); + ctx->use_superblock = blk; + if (res != 1) + goto sscanf_err; + ctx->flags |= E2F_FLAG_SB_SPECIFIED; + break; + case 'B': + ctx->blocksize = atoi(optarg); + break; + case 'I': + res = sscanf(optarg, "%d", &ctx->inode_buffer_blocks); + if (res != 1) + goto sscanf_err; + break; + case 'j': + ctx->journal_name = get_devname(ctx->blkid, + optarg, NULL); + if (!ctx->journal_name) { + com_err(ctx->program_name, 0, + _("Unable to resolve '%s'"), + optarg); + fatal_error(ctx, 0); + } + break; + case 'P': + res = sscanf(optarg, "%d", &ctx->process_inode_size); + if (res != 1) + goto sscanf_err; + break; + case 'L': + replace_bad_blocks++; + /* fall through */ + case 'l': + if (bad_blocks_file) + free(bad_blocks_file); + bad_blocks_file = string_copy(ctx, optarg, 0); + break; + case 'd': + ctx->options |= E2F_OPT_DEBUG; + break; + case 'f': + ctx->options |= E2F_OPT_FORCE; + break; + case 'F': + flush = 1; + break; + case 'v': + verbose = 1; + break; + case 'V': + show_version_only = 1; + break; +#ifdef MTRACE + case 'M': + mallwatch = (void *) strtol(optarg, NULL, 0); + break; +#endif + case 'N': + ctx->device_name = string_copy(ctx, optarg, 0); + break; + case 'k': + keep_bad_blocks++; + break; + case 'z': + ctx->undo_file = optarg; + break; + default: + usage(ctx); + } + if (show_version_only) + return 0; + if (optind != argc - 1) + usage(ctx); + if ((ctx->options & E2F_OPT_NO) && + (ctx->options & E2F_OPT_COMPRESS_DIRS)) { + com_err(ctx->program_name, 0, "%s", + _("The -n and -D options are incompatible.")); + fatal_error(ctx, 0); + } + if ((ctx->options & E2F_OPT_NO) && cflag) { + com_err(ctx->program_name, 0, "%s", + _("The -n and -c options are incompatible.")); + fatal_error(ctx, 0); + } + if ((ctx->options & E2F_OPT_NO) && bad_blocks_file) { + com_err(ctx->program_name, 0, "%s", + _("The -n and -l/-L options are incompatible.")); + fatal_error(ctx, 0); + } + if (ctx->options & E2F_OPT_NO) + ctx->options |= E2F_OPT_READONLY; + + ctx->io_options = strchr(argv[optind], '?'); + if (ctx->io_options) + *ctx->io_options++ = 0; + ctx->filesystem_name = get_devname(ctx->blkid, argv[optind], 0); + if (!ctx->filesystem_name) { + com_err(ctx->program_name, 0, _("Unable to resolve '%s'"), + argv[optind]); + fatal_error(ctx, 0); + } + if (extended_opts) + parse_extended_opts(ctx, extended_opts); + + /* Complain about mutually exclusive rebuilding activities */ + if (getenv("E2FSCK_FIXES_ONLY")) + ctx->options |= E2F_OPT_FIXES_ONLY; + if ((ctx->options & E2F_OPT_COMPRESS_DIRS) && + (ctx->options & E2F_OPT_FIXES_ONLY)) { + com_err(ctx->program_name, 0, "%s", + _("The -D and -E fixes_only options are incompatible.")); + fatal_error(ctx, 0); + } + if ((ctx->options & E2F_OPT_CONVERT_BMAP) && + (ctx->options & E2F_OPT_FIXES_ONLY)) { + com_err(ctx->program_name, 0, "%s", + _("The -E bmap2extent and fixes_only options are incompatible.")); + fatal_error(ctx, 0); + } + + if ((cp = getenv("E2FSCK_CONFIG")) != NULL) + config_fn[0] = cp; + profile_set_syntax_err_cb(syntax_err_report); + profile_init(config_fn, &ctx->profile); + + profile_get_boolean(ctx->profile, "options", "report_time", 0, 0, + &c); + if (c) + ctx->options |= E2F_OPT_TIME | E2F_OPT_TIME2; + profile_get_boolean(ctx->profile, "options", "report_verbose", 0, 0, + &c); + if (c) + verbose = 1; + + profile_get_boolean(ctx->profile, "options", "no_optimize_extents", + 0, 0, &c); + if (c) + ctx->options |= E2F_OPT_NOOPT_EXTENTS; + + profile_get_boolean(ctx->profile, "options", "inode_count_fullmap", + 0, 0, &c); + if (c) + ctx->options |= E2F_OPT_ICOUNT_FULLMAP; + + if (ctx->readahead_kb == ~0ULL) { + profile_get_integer(ctx->profile, "options", + "readahead_mem_pct", 0, -1, &c); + if (c >= 0 && c <= 100) + ctx->readahead_kb = phys_mem_kb * c / 100; + profile_get_integer(ctx->profile, "options", + "readahead_kb", 0, -1, &c); + if (c >= 0) + ctx->readahead_kb = c; + if (ctx->readahead_kb != ~0ULL && + ctx->readahead_kb > phys_mem_kb) + ctx->readahead_kb = phys_mem_kb; + } + + /* Turn off discard in read-only mode */ + if ((ctx->options & E2F_OPT_NO) && + (ctx->options & E2F_OPT_DISCARD)) + ctx->options &= ~E2F_OPT_DISCARD; + + if (flush) { + fd = open(ctx->filesystem_name, O_RDONLY, 0); + if (fd < 0) { + com_err("open", errno, + _("while opening %s for flushing"), + ctx->filesystem_name); + fatal_error(ctx, 0); + } + if ((retval = ext2fs_sync_device(fd, 1))) { + com_err("ext2fs_sync_device", retval, + _("while trying to flush %s"), + ctx->filesystem_name); + fatal_error(ctx, 0); + } + close(fd); + } + if (cflag && bad_blocks_file) { + fprintf(stderr, "%s", _("The -c and the -l/-L options may not " + "be both used at the same time.\n")); + exit(FSCK_USAGE); + } +#ifdef HAVE_SIGNAL_H + /* + * Set up signal action + */ + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_handler = signal_cancel; + sigaction(SIGINT, &sa, 0); + sigaction(SIGTERM, &sa, 0); +#ifdef SA_RESTART + sa.sa_flags = SA_RESTART; +#endif + sa.sa_handler = signal_progress_on; + sigaction(SIGUSR1, &sa, 0); + sa.sa_handler = signal_progress_off; + sigaction(SIGUSR2, &sa, 0); +#endif + + /* Update our PATH to include /sbin if we need to run badblocks */ + if (cflag) { + char *oldpath = getenv("PATH"); + char *newpath; + int len = sizeof(PATH_SET) + 1; + + if (oldpath) + len += strlen(oldpath); + + newpath = malloc(len); + if (!newpath) + fatal_error(ctx, "Couldn't malloc() newpath"); + strcpy(newpath, PATH_SET); + + if (oldpath) { + strcat(newpath, ":"); + strcat(newpath, oldpath); + } + putenv(newpath); + } +#ifdef CONFIG_JBD_DEBUG + jbd_debug = getenv("E2FSCK_JBD_DEBUG"); + if (jbd_debug) { + res = sscanf(jbd_debug, "%d", &journal_enable_debug); + if (res != 1) { + fprintf(stderr, + _("E2FSCK_JBD_DEBUG \"%s\" not an integer\n\n"), + jbd_debug); + exit (1); + } + } +#endif + return 0; + +sscanf_err: + fprintf(stderr, _("\nInvalid non-numeric argument to -%c (\"%s\")\n\n"), + c, optarg); + exit (1); +} + +static errcode_t try_open_fs(e2fsck_t ctx, int flags, io_manager io_ptr, + ext2_filsys *ret_fs) +{ + errcode_t retval; + + *ret_fs = NULL; + + if (ctx->superblock) { + unsigned long blocksize = ctx->blocksize; + + if (!blocksize) { + for (blocksize = EXT2_MIN_BLOCK_SIZE; + blocksize <= EXT2_MAX_BLOCK_SIZE; blocksize *= 2) { + + retval = ext2fs_open2(ctx->filesystem_name, + ctx->io_options, flags, + ctx->superblock, blocksize, + unix_io_manager, ret_fs); + if (*ret_fs) { + ext2fs_free(*ret_fs); + *ret_fs = NULL; + } + if (!retval) + break; + } + if (retval) + return retval; + } + + retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options, + flags, ctx->superblock, blocksize, + io_ptr, ret_fs); + } else + retval = ext2fs_open2(ctx->filesystem_name, ctx->io_options, + flags, 0, 0, io_ptr, ret_fs); + + if (retval == 0) { + (*ret_fs)->priv_data = ctx; + e2fsck_set_bitmap_type(*ret_fs, EXT2FS_BMAP64_RBTREE, + "default", NULL); + } + return retval; +} + +static const char *my_ver_string = E2FSPROGS_VERSION; +static const char *my_ver_date = E2FSPROGS_DATE; + +static errcode_t e2fsck_check_mmp(ext2_filsys fs, e2fsck_t ctx) +{ + struct mmp_struct *mmp_s; + unsigned int mmp_check_interval; + errcode_t retval = 0; + struct problem_context pctx; + unsigned int wait_time = 0; + + clear_problem_context(&pctx); + if (fs->mmp_buf == NULL) { + retval = ext2fs_get_mem(fs->blocksize, &fs->mmp_buf); + if (retval) + goto check_error; + } + + retval = ext2fs_mmp_read(fs, fs->super->s_mmp_block, fs->mmp_buf); + if (retval) + goto check_error; + + mmp_s = fs->mmp_buf; + + mmp_check_interval = fs->super->s_mmp_update_interval; + if (mmp_check_interval < EXT4_MMP_MIN_CHECK_INTERVAL) + mmp_check_interval = EXT4_MMP_MIN_CHECK_INTERVAL; + + /* + * If check_interval in MMP block is larger, use that instead of + * check_interval from the superblock. + */ + if (mmp_s->mmp_check_interval > mmp_check_interval) + mmp_check_interval = mmp_s->mmp_check_interval; + + wait_time = mmp_check_interval * 2 + 1; + + if (mmp_s->mmp_seq == EXT4_MMP_SEQ_CLEAN) + retval = 0; + else if (mmp_s->mmp_seq == EXT4_MMP_SEQ_FSCK) + retval = EXT2_ET_MMP_FSCK_ON; + else if (mmp_s->mmp_seq > EXT4_MMP_SEQ_MAX) + retval = EXT2_ET_MMP_UNKNOWN_SEQ; + + if (retval) + goto check_error; + + /* Print warning if e2fsck will wait for more than 20 secs. */ + if (verbose || wait_time > EXT4_MMP_MIN_CHECK_INTERVAL * 4) { + log_out(ctx, _("MMP interval is %u seconds and total wait " + "time is %u seconds. Please wait...\n"), + mmp_check_interval, wait_time * 2); + } + + return 0; + +check_error: + + if (retval == EXT2_ET_MMP_BAD_BLOCK) { + if (fix_problem(ctx, PR_0_MMP_INVALID_BLK, &pctx)) { + fs->super->s_mmp_block = 0; + ext2fs_mark_super_dirty(fs); + retval = 0; + } + } else if (retval == EXT2_ET_MMP_FAILED) { + com_err(ctx->program_name, retval, "%s", + _("while checking MMP block")); + dump_mmp_msg(fs->mmp_buf, NULL); + } else if (retval == EXT2_ET_MMP_FSCK_ON || + retval == EXT2_ET_MMP_UNKNOWN_SEQ) { + com_err(ctx->program_name, retval, "%s", + _("while checking MMP block")); + dump_mmp_msg(fs->mmp_buf, + _("If you are sure the filesystem is not " + "in use on any node, run:\n" + "'tune2fs -f -E clear_mmp %s'\n"), + ctx->device_name); + } else if (retval == EXT2_ET_MMP_MAGIC_INVALID) { + if (fix_problem(ctx, PR_0_MMP_INVALID_MAGIC, &pctx)) { + ext2fs_mmp_clear(fs); + retval = 0; + } + } else if (retval == EXT2_ET_MMP_CSUM_INVALID) { + if (fix_problem(ctx, PR_0_MMP_CSUM_INVALID, &pctx)) { + ext2fs_mmp_clear(fs); + retval = 0; + } + } else + com_err(ctx->program_name, retval, "%s", + _("while reading MMP block")); + return retval; +} + +static int e2fsck_setup_tdb(e2fsck_t ctx, io_manager *io_ptr) +{ + errcode_t retval = ENOMEM; + char *tdb_dir = NULL, *tdb_file = NULL; + char *dev_name, *tmp_name; + int free_tdb_dir = 0; + + /* (re)open a specific undo file */ + if (ctx->undo_file && ctx->undo_file[0] != 0) { + retval = set_undo_io_backing_manager(*io_ptr); + if (retval) + goto err; + *io_ptr = undo_io_manager; + retval = set_undo_io_backup_file(ctx->undo_file); + if (retval) + goto err; + printf(_("Overwriting existing filesystem; this can be undone " + "using the command:\n" + " e2undo %s %s\n\n"), + ctx->undo_file, ctx->filesystem_name); + return retval; + } + + /* + * Configuration via a conf file would be + * nice + */ + tdb_dir = getenv("E2FSPROGS_UNDO_DIR"); + if (!tdb_dir) { + profile_get_string(ctx->profile, "defaults", + "undo_dir", 0, "/var/lib/e2fsprogs", + &tdb_dir); + free_tdb_dir = 1; + } + + if (!strcmp(tdb_dir, "none") || (tdb_dir[0] == 0) || + access(tdb_dir, W_OK)) { + if (free_tdb_dir) + free(tdb_dir); + return 0; + } + + tmp_name = strdup(ctx->filesystem_name); + if (!tmp_name) + goto errout; + dev_name = basename(tmp_name); + tdb_file = malloc(strlen(tdb_dir) + 8 + strlen(dev_name) + 7 + 1); + if (!tdb_file) { + free(tmp_name); + goto errout; + } + sprintf(tdb_file, "%s/e2fsck-%s.e2undo", tdb_dir, dev_name); + free(tmp_name); + + if ((unlink(tdb_file) < 0) && (errno != ENOENT)) { + retval = errno; + com_err(ctx->program_name, retval, + _("while trying to delete %s"), tdb_file); + goto errout; + } + + retval = set_undo_io_backing_manager(*io_ptr); + if (retval) + goto errout; + *io_ptr = undo_io_manager; + retval = set_undo_io_backup_file(tdb_file); + if (retval) + goto errout; + printf(_("Overwriting existing filesystem; this can be undone " + "using the command:\n" + " e2undo %s %s\n\n"), tdb_file, ctx->filesystem_name); + + if (free_tdb_dir) + free(tdb_dir); + free(tdb_file); + return 0; + +errout: + if (free_tdb_dir) + free(tdb_dir); + free(tdb_file); +err: + com_err(ctx->program_name, retval, "%s", + _("while trying to setup undo file\n")); + return retval; +} + +int main (int argc, char *argv[]) +{ + errcode_t retval = 0, retval2 = 0, orig_retval = 0; + int exit_value = FSCK_OK; + ext2_filsys fs = 0; + io_manager io_ptr; + struct ext2_super_block *sb; + const char *lib_ver_date; + int my_ver, lib_ver; + e2fsck_t ctx; + blk64_t orig_superblock = ~(blk64_t)0; + struct problem_context pctx; + int flags, run_result, was_changed; + int journal_size; + int sysval, sys_page_size = 4096; + int old_bitmaps; + __u32 features[3]; + char *cp; + enum quota_type qtype; + struct ext2fs_journal_params jparams; + + clear_problem_context(&pctx); + sigcatcher_setup(); +#ifdef MTRACE + mtrace(); +#endif +#ifdef MCHECK + mcheck(0); +#endif +#ifdef ENABLE_NLS + setlocale(LC_MESSAGES, ""); + setlocale(LC_CTYPE, ""); + bindtextdomain(NLS_CAT_NAME, LOCALEDIR); + textdomain(NLS_CAT_NAME); + set_com_err_gettext(gettext); +#endif + my_ver = ext2fs_parse_version_string(my_ver_string); + lib_ver = ext2fs_get_library_version(0, &lib_ver_date); + if (my_ver > lib_ver) { + fprintf( stderr, "%s", + _("Error: ext2fs library version out of date!\n")); + show_version_only++; + } + + retval = PRS(argc, argv, &ctx); + if (retval) { + com_err("e2fsck", retval, "%s", + _("while trying to initialize program")); + exit(FSCK_ERROR); + } + reserve_stdio_fds(); + + set_up_logging(ctx); + if (ctx->logf) { + int i; + + fputs("E2fsck run: ", ctx->logf); + for (i = 0; i < argc; i++) { + if (i) + fputc(' ', ctx->logf); + fputs(argv[i], ctx->logf); + } + fputc('\n', ctx->logf); + } + if (ctx->problem_logf) { + int i; + + fputs("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n", + ctx->problem_logf); + fprintf(ctx->problem_logf, "<problem_log time=\"%lu\">\n", + (unsigned long) ctx->now); + fprintf(ctx->problem_logf, "<invocation prog=\"%s\"", + argv[0]); + for (i = 1; i < argc; i++) + fprintf(ctx->problem_logf, " arg%d=\"%s\"", i, argv[i]); + fputs("/>\n", ctx->problem_logf); + } + + init_resource_track(&ctx->global_rtrack, NULL); + if (!(ctx->options & E2F_OPT_PREEN) || show_version_only) + log_err(ctx, "e2fsck %s (%s)\n", my_ver_string, + my_ver_date); + + if (show_version_only) { + log_err(ctx, _("\tUsing %s, %s\n"), + error_message(EXT2_ET_BASE), lib_ver_date); + exit(FSCK_OK); + } + + check_mount(ctx); + + if (!(ctx->options & E2F_OPT_PREEN) && + !(ctx->options & E2F_OPT_NO) && + !(ctx->options & E2F_OPT_YES)) { + if (!ctx->interactive) + fatal_error(ctx, + _("need terminal for interactive repairs")); + } + ctx->superblock = ctx->use_superblock; + + flags = EXT2_FLAG_SKIP_MMP | EXT2_FLAG_THREADS; +restart: +#ifdef CONFIG_TESTIO_DEBUG + if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) { + io_ptr = test_io_manager; + test_io_backing_manager = unix_io_manager; + } else +#endif + io_ptr = unix_io_manager; + flags |= EXT2_FLAG_NOFREE_ON_ERROR; + profile_get_boolean(ctx->profile, "options", "old_bitmaps", 0, 0, + &old_bitmaps); + if (!old_bitmaps) + flags |= EXT2_FLAG_64BITS; + if ((ctx->options & E2F_OPT_READONLY) == 0) { + flags |= EXT2_FLAG_RW; + if (!(ctx->mount_flags & EXT2_MF_ISROOT && + ctx->mount_flags & EXT2_MF_READONLY)) + flags |= EXT2_FLAG_EXCLUSIVE; + if ((ctx->mount_flags & EXT2_MF_READONLY) && + (ctx->options & E2F_OPT_FORCE)) + flags &= ~EXT2_FLAG_EXCLUSIVE; + } + + if (ctx->undo_file) { + retval = e2fsck_setup_tdb(ctx, &io_ptr); + if (retval) + exit(FSCK_ERROR); + } + + ctx->openfs_flags = flags; + retval = try_open_fs(ctx, flags, io_ptr, &fs); + + if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) && + !(ctx->flags & E2F_FLAG_SB_SPECIFIED) && + ((retval == EXT2_ET_BAD_MAGIC) || + (retval == EXT2_ET_SB_CSUM_INVALID) || + (retval == EXT2_ET_CORRUPT_SUPERBLOCK) || + ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) { + if (retval) { + pctx.errcode = retval; + fix_problem(ctx, PR_0_OPEN_FAILED, &pctx); + } + if (retval2) { + pctx.errcode = retval2; + fix_problem(ctx, PR_0_CHECK_DESC_FAILED, &pctx); + } + pctx.errcode = 0; + if (retval2 == ENOMEM || retval2 == EXT2_ET_NO_MEMORY) { + retval = retval2; + goto failure; + } + if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) { + ext2fs_free(fs); + fs = NULL; + } + if (!fs || (fs->group_desc_count > 1)) { + log_out(ctx, _("%s: %s trying backup blocks...\n"), + ctx->program_name, + retval ? _("Superblock invalid,") : + _("Group descriptors look bad...")); + orig_superblock = ctx->superblock; + get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr); + if (fs) + ext2fs_close_free(&fs); + orig_retval = retval; + retval = try_open_fs(ctx, flags, io_ptr, &fs); + if ((orig_retval == 0) && retval != 0) { + if (fs) + ext2fs_close_free(&fs); + log_out(ctx, _("%s: %s while using the " + "backup blocks"), + ctx->program_name, + error_message(retval)); + log_out(ctx, _("%s: going back to original " + "superblock\n"), + ctx->program_name); + ctx->superblock = orig_superblock; + retval = try_open_fs(ctx, flags, io_ptr, &fs); + } + } + } + if (((retval == EXT2_ET_UNSUPP_FEATURE) || + (retval == EXT2_ET_RO_UNSUPP_FEATURE)) && + fs && fs->super) { + sb = fs->super; + features[0] = (sb->s_feature_compat & + ~EXT2_LIB_FEATURE_COMPAT_SUPP); + features[1] = (sb->s_feature_incompat & + ~EXT2_LIB_FEATURE_INCOMPAT_SUPP); + features[2] = (sb->s_feature_ro_compat & + ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP); + if (features[0] || features[1] || features[2]) + goto print_unsupp_features; + } +failure: + if (retval) { + if (orig_retval) + retval = orig_retval; + com_err(ctx->program_name, retval, _("while trying to open %s"), + ctx->filesystem_name); + if (retval == EXT2_ET_REV_TOO_HIGH) { + log_out(ctx, "%s", + _("The filesystem revision is apparently " + "too high for this version of e2fsck.\n" + "(Or the filesystem superblock " + "is corrupt)\n\n")); + fix_problem(ctx, PR_0_SB_CORRUPT, &pctx); + } else if (retval == EXT2_ET_SHORT_READ) + log_out(ctx, "%s", + _("Could this be a zero-length partition?\n")); + else if ((retval == EPERM) || (retval == EACCES)) + log_out(ctx, _("You must have %s access to the " + "filesystem or be root\n"), + (ctx->options & E2F_OPT_READONLY) ? + "r/o" : "r/w"); + else if (retval == ENXIO) + log_out(ctx, "%s", + _("Possibly non-existent or swap device?\n")); + else if (retval == EBUSY) + log_out(ctx, "%s", _("Filesystem mounted or opened " + "exclusively by another program?\n")); + else if (retval == ENOENT) + log_out(ctx, "%s", + _("Possibly non-existent device?\n")); +#ifdef EROFS + else if (retval == EROFS) + log_out(ctx, "%s", _("Disk write-protected; use the " + "-n option to do a read-only\n" + "check of the device.\n")); +#endif + else { + /* + * Let's try once more will less consistency checking + * so that we are able to recover from more errors + * (e.g. some tool messing up some value in the sb). + */ + if (((retval == EXT2_ET_CORRUPT_SUPERBLOCK) || + (retval == EXT2_ET_BAD_DESC_SIZE)) && + !(flags & EXT2_FLAG_IGNORE_SB_ERRORS)) { + if (fs) + ext2fs_close_free(&fs); + log_out(ctx, _("%s: Trying to load superblock " + "despite errors...\n"), + ctx->program_name); + flags |= EXT2_FLAG_IGNORE_SB_ERRORS; + /* + * If we tried backup sb, revert to the + * original one now. + */ + if (orig_superblock != ~(blk64_t)0) + ctx->superblock = orig_superblock; + goto restart; + } + fix_problem(ctx, PR_0_SB_CORRUPT, &pctx); + if (retval == EXT2_ET_BAD_MAGIC) + check_plausibility(ctx->filesystem_name, + CHECK_FS_EXIST, NULL); + } + fatal_error(ctx, 0); + } + /* + * We only update the master superblock because (a) paranoia; + * we don't want to corrupt the backup superblocks, and (b) we + * don't need to update the mount count and last checked + * fields in the backup superblock (the kernel doesn't update + * the backup superblocks anyway). With newer versions of the + * library this flag is set by ext2fs_open2(), but we set this + * here just to be sure. (No, we don't support e2fsck running + * with some other libext2fs than the one that it was shipped + * with, but just in case....) + */ + fs->flags |= EXT2_FLAG_MASTER_SB_ONLY; + + if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) { + __u32 blocksize = EXT2_BLOCK_SIZE(fs->super); + int need_restart = 0; + + pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name, + blocksize, + &ctx->num_blocks); + /* + * The floppy driver refuses to allow anyone else to + * open the device if has been opened with O_EXCL; + * this is unlike other block device drivers in Linux. + * To handle this, we close the filesystem and then + * reopen the filesystem after we get the device size. + */ + if (pctx.errcode == EBUSY) { + ext2fs_close_free(&fs); + need_restart++; + pctx.errcode = + ext2fs_get_device_size2(ctx->filesystem_name, + blocksize, + &ctx->num_blocks); + } + if (pctx.errcode == EXT2_ET_UNIMPLEMENTED) + ctx->num_blocks = 0; + else if (pctx.errcode) { + fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx); + ctx->flags |= E2F_FLAG_ABORT; + fatal_error(ctx, 0); + } + ctx->flags |= E2F_FLAG_GOT_DEVSIZE; + if (need_restart) + goto restart; + } + + ctx->fs = fs; + fs->now = ctx->now; + sb = fs->super; + + if (sb->s_rev_level > E2FSCK_CURRENT_REV) { + com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH, + _("while trying to open %s"), + ctx->filesystem_name); + get_newer: + fatal_error(ctx, _("Get a newer version of e2fsck!")); + } + + /* + * Set the device name, which is used whenever we print error + * or informational messages to the user. + */ + if (ctx->device_name == 0 && sb->s_volume_name[0]) + ctx->device_name = string_copy(ctx, (char *) sb->s_volume_name, + sizeof(sb->s_volume_name)); + + if (ctx->device_name == 0) + ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0); + for (cp = ctx->device_name; *cp; cp++) + if (isspace(*cp) || *cp == ':') + *cp = '_'; + + if (ctx->problem_logf) { + + fprintf(ctx->problem_logf, "<filesystem dev=\"%s\"", + ctx->filesystem_name); + if (!uuid_is_null(sb->s_uuid)) { + char buf[48]; + + uuid_unparse(sb->s_uuid, buf); + fprintf(ctx->problem_logf, " uuid=\"%s\"", buf); + } + if (sb->s_volume_name[0]) + fprintf(ctx->problem_logf, " label=\"%.*s\"", + EXT2_LEN_STR(sb->s_volume_name)); + + fputs("/>\n", ctx->problem_logf); + } + + ehandler_init(fs->io); + + if (ext2fs_has_feature_mmp(fs->super) && + (flags & EXT2_FLAG_SKIP_MMP)) { + if (e2fsck_check_mmp(fs, ctx)) + fatal_error(ctx, 0); + + /* + * Restart in order to reopen fs but this time start mmp. + */ + ext2fs_close_free(&ctx->fs); + flags &= ~EXT2_FLAG_SKIP_MMP; + goto restart; + } + + if (ctx->logf) + fprintf(ctx->logf, "Filesystem UUID: %s\n", + e2p_uuid2str(sb->s_uuid)); + + /* + * Make sure the ext3 superblock fields are consistent. + */ + if ((ctx->mount_flags & (EXT2_MF_MOUNTED | EXT2_MF_BUSY)) == 0) { + retval = e2fsck_check_ext3_journal(ctx); + if (retval) { + com_err(ctx->program_name, retval, + _("while checking journal for %s"), + ctx->device_name); + fatal_error(ctx, + _("Cannot proceed with file system check")); + } + } + + /* + * Check to see if we need to do ext3-style recovery. If so, + * do it, and then restart the fsck. + */ + if (ext2fs_has_feature_journal_needs_recovery(sb)) { + if (ctx->options & E2F_OPT_READONLY) { + log_out(ctx, "%s", + _("Warning: skipping journal recovery because " + "doing a read-only filesystem check.\n")); + io_channel_flush(ctx->fs->io); + } else { + if (ctx->flags & E2F_FLAG_RESTARTED) { + /* + * Whoops, we attempted to run the + * journal twice. This should never + * happen, unless the hardware or + * device driver is being bogus. + */ + com_err(ctx->program_name, 0, + _("unable to set superblock flags " + "on %s\n"), ctx->device_name); + fatal_error(ctx, 0); + } + retval = e2fsck_run_ext3_journal(ctx); + if (retval == EFSBADCRC) { + log_out(ctx, _("Journal checksum error " + "found in %s\n"), + ctx->device_name); + } else if (retval == EFSCORRUPTED) { + log_out(ctx, _("Journal corrupted in %s\n"), + ctx->device_name); + } else if (retval) { + com_err(ctx->program_name, retval, + _("while recovering journal of %s"), + ctx->device_name); + } + ext2fs_close_free(&ctx->fs); + ctx->flags |= E2F_FLAG_RESTARTED; + goto restart; + } + } + + /* + * Check for compatibility with the feature sets. We need to + * be more stringent than ext2fs_open(). + */ + features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP; + features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP; + features[2] = (sb->s_feature_ro_compat & + ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP); +print_unsupp_features: + if (features[0] || features[1] || features[2]) { + int i, j; + __u32 *mask = features, m; + + log_err(ctx, _("%s has unsupported feature(s):"), + ctx->filesystem_name); + + for (i=0; i <3; i++,mask++) { + for (j=0,m=1; j < 32; j++, m<<=1) { + if (*mask & m) + log_err(ctx, " %s", + e2p_feature2string(i, m)); + } + } + log_err(ctx, "\n"); + goto get_newer; + } + + if (ext2fs_has_feature_casefold(sb) && !fs->encoding) { + log_err(ctx, _("%s has unsupported encoding: %0x\n"), + ctx->filesystem_name, sb->s_encoding); + goto get_newer; + } + + /* + * If the user specified a specific superblock, presumably the + * master superblock has been trashed. So we mark the + * superblock as dirty, so it can be written out. + */ + if (ctx->superblock && + !(ctx->options & E2F_OPT_READONLY)) + ext2fs_mark_super_dirty(fs); + + /* + * Calculate the number of filesystem blocks per pagesize. If + * fs->blocksize > page_size, set the number of blocks per + * pagesize to 1 to avoid division by zero errors. + */ +#ifdef _SC_PAGESIZE + sysval = sysconf(_SC_PAGESIZE); + if (sysval > 0) + sys_page_size = sysval; +#endif /* _SC_PAGESIZE */ + ctx->blocks_per_page = sys_page_size / fs->blocksize; + if (ctx->blocks_per_page == 0) + ctx->blocks_per_page = 1; + + if (ctx->superblock) + set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0); + ext2fs_mark_valid(fs); + check_super_block(ctx); + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + fatal_error(ctx, 0); + check_if_skip(ctx); + check_resize_inode(ctx); + if (bad_blocks_file) + read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks); + else if (cflag) + read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */ + if (ctx->flags & E2F_FLAG_SIGNAL_MASK) + fatal_error(ctx, 0); + + /* + * Mark the system as valid, 'til proven otherwise + */ + ext2fs_mark_valid(fs); + + retval = ext2fs_read_bb_inode(fs, &fs->badblocks); + if (retval) { + log_out(ctx, _("%s: %s while reading bad blocks inode\n"), + ctx->program_name, error_message(retval)); + preenhalt(ctx); + log_out(ctx, "%s", _("This doesn't bode well, " + "but we'll try to go on...\n")); + } + + /* + * Save the journal size in megabytes. + * Try and use the journal size from the backup else let e2fsck + * find the default journal size. If fast commit feature is enabled, + * it is not clear how many of the journal blocks were fast commit + * blocks. So, ignore the size of journal found in backup. + * + * TODO: Add a new backup type that captures fast commit info as + * well. + */ + if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS && + !ext2fs_has_feature_fast_commit(sb)) + journal_size = (sb->s_jnl_blocks[15] << (32 - 20)) | + (sb->s_jnl_blocks[16] >> 20); + else + journal_size = -1; + + if (ext2fs_has_feature_quota(sb)) { + /* Quotas were enabled. Do quota accounting during fsck. */ + clear_problem_context(&pctx); + pctx.errcode = quota_init_context(&ctx->qctx, ctx->fs, 0); + if (pctx.errcode) { + fix_problem(ctx, PR_0_QUOTA_INIT_CTX, &pctx); + fatal_error(ctx, 0); + } + } + + run_result = e2fsck_run(ctx); + e2fsck_clear_progbar(ctx); + + if (!ctx->invalid_bitmaps && + (ctx->flags & E2F_FLAG_JOURNAL_INODE)) { + if (fix_problem(ctx, PR_6_RECREATE_JOURNAL, &pctx)) { + if (journal_size < 1024) { + ext2fs_get_journal_params(&jparams, fs); + } else { + jparams.num_journal_blocks = journal_size; + jparams.num_fc_blocks = 0; + } + log_out(ctx, _("Creating journal (%d blocks): "), + jparams.num_journal_blocks); + fflush(stdout); + retval = ext2fs_add_journal_inode3(fs, &jparams, ~0ULL, 0); + if (retval) { + log_out(ctx, "%s: while trying to create " + "journal\n", error_message(retval)); + goto no_journal; + } + log_out(ctx, "%s", _(" Done.\n")); + log_out(ctx, "%s", + _("\n*** journal has been regenerated ***\n")); + } + } + +no_journal: + if (run_result & E2F_FLAG_ABORT) { + fatal_error(ctx, _("aborted")); + } else if (run_result & E2F_FLAG_CANCEL) { + log_out(ctx, _("%s: e2fsck canceled.\n"), ctx->device_name ? + ctx->device_name : ctx->filesystem_name); + exit_value |= FSCK_CANCELED; + goto cleanup; + } + + if (ext2fs_has_feature_orphan_file(fs->super)) { + int ret; + + /* No point in orphan file without a journal... */ + if (!ext2fs_has_feature_journal(fs->super) && + fix_problem(ctx, PR_6_ORPHAN_FILE_WITHOUT_JOURNAL, &pctx)) { + retval = ext2fs_truncate_orphan_file(fs); + if (retval) { + /* Huh, failed to delete file */ + fix_problem(ctx, PR_6_ORPHAN_FILE_TRUNC_FAILED, + &pctx); + goto check_quotas; + } + ext2fs_clear_feature_orphan_file(fs->super); + ext2fs_mark_super_dirty(fs); + goto check_quotas; + } + ret = check_init_orphan_file(ctx); + if (ret == 2 || + (ret == 0 && ext2fs_has_feature_orphan_present(fs->super) && + fix_problem(ctx, PR_6_ORPHAN_PRESENT_CLEAN_FILE, &pctx))) { + ext2fs_clear_feature_orphan_present(fs->super); + ext2fs_mark_super_dirty(fs); + } else if (ret == 1 && + fix_problem(ctx, PR_6_ORPHAN_FILE_CORRUPTED, &pctx)) { + int orphan_file_blocks; + + if (ctx->invalid_bitmaps) { + fix_problem(ctx, + PR_6_ORPHAN_FILE_BITMAP_INVALID, + &pctx); + goto check_quotas; + } + + retval = ext2fs_truncate_orphan_file(fs); + if (retval) { + /* Huh, failed to truncate file */ + fix_problem(ctx, PR_6_ORPHAN_FILE_TRUNC_FAILED, + &pctx); + goto check_quotas; + } + + orphan_file_blocks = + ext2fs_default_orphan_file_blocks(fs); + log_out(ctx, _("Creating orphan file (%d blocks): "), + orphan_file_blocks); + fflush(stdout); + retval = ext2fs_create_orphan_file(fs, + orphan_file_blocks); + if (retval) { + log_out(ctx, "%s: while trying to create " + "orphan file\n", error_message(retval)); + fix_problem(ctx, PR_6_ORPHAN_FILE_CREATE_FAILED, + &pctx); + goto check_quotas; + } + log_out(ctx, "%s", _(" Done.\n")); + } + } else if (ext2fs_has_feature_orphan_present(fs->super) && + fix_problem(ctx, PR_6_ORPHAN_PRESENT_NO_FILE, &pctx)) { + ext2fs_clear_feature_orphan_present(fs->super); + ext2fs_mark_super_dirty(fs); + } +check_quotas: + if (ctx->qctx && !ctx->invalid_bitmaps) { + int needs_writeout; + + for (qtype = 0; qtype < MAXQUOTAS; qtype++) { + if (*quota_sb_inump(sb, qtype) == 0) + continue; + needs_writeout = 0; + pctx.num = qtype; + retval = quota_compare_and_update(ctx->qctx, qtype, + &needs_writeout); + if ((retval || needs_writeout) && + fix_problem(ctx, PR_6_UPDATE_QUOTAS, &pctx)) { + pctx.errcode = quota_write_inode(ctx->qctx, + 1 << qtype); + if (pctx.errcode) + (void) fix_problem(ctx, + PR_6_WRITE_QUOTAS, &pctx); + } + } + quota_release_context(&ctx->qctx); + } + + if (run_result == E2F_FLAG_RESTART) { + log_out(ctx, "%s", + _("Restarting e2fsck from the beginning...\n")); + retval = e2fsck_reset_context(ctx); + if (retval) { + com_err(ctx->program_name, retval, "%s", + _("while resetting context")); + fatal_error(ctx, 0); + } + ext2fs_close_free(&ctx->fs); + goto restart; + } + +cleanup: +#ifdef MTRACE + mtrace_print("Cleanup"); +#endif + was_changed = ext2fs_test_changed(fs); + if (!(ctx->flags & E2F_FLAG_RUN_RETURN) && + !(ctx->options & E2F_OPT_READONLY)) { + if (ext2fs_test_valid(fs)) { + if (!(sb->s_state & EXT2_VALID_FS)) + exit_value |= FSCK_NONDESTRUCT; + sb->s_state = EXT2_VALID_FS; + if (check_backup_super_block(ctx)) + fs->flags &= ~EXT2_FLAG_MASTER_SB_ONLY; + } else + sb->s_state &= ~EXT2_VALID_FS; + if (!(ctx->flags & E2F_FLAG_TIME_INSANE)) + sb->s_lastcheck = ctx->now; + sb->s_mnt_count = 0; + memset(((char *) sb) + EXT4_S_ERR_START, 0, EXT4_S_ERR_LEN); + pctx.errcode = ext2fs_set_gdt_csum(ctx->fs); + if (pctx.errcode) + fix_problem(ctx, PR_6_SET_BG_CHECKSUM, &pctx); + ext2fs_mark_super_dirty(fs); + } + + if (ext2fs_has_feature_shared_blocks(ctx->fs->super) && + (ctx->options & E2F_OPT_UNSHARE_BLOCKS) && + (ctx->options & E2F_OPT_NO)) + /* Don't try to write or flush I/O, we just wanted to know whether or + * not there were enough free blocks to undo deduplication. + */ + goto skip_write; + + if (!(ctx->options & E2F_OPT_READONLY)) { + e2fsck_write_bitmaps(ctx); + if (fs->flags & EXT2_FLAG_DIRTY) { + pctx.errcode = ext2fs_flush(ctx->fs); + if (pctx.errcode) + fix_problem(ctx, PR_6_FLUSH_FILESYSTEM, &pctx); + } + pctx.errcode = io_channel_flush(ctx->fs->io); + if (pctx.errcode) + fix_problem(ctx, PR_6_IO_FLUSH, &pctx); + } + + if (was_changed) { + int fs_fixed = (ctx->flags & E2F_FLAG_PROBLEMS_FIXED); + + if (fs_fixed) + exit_value |= FSCK_NONDESTRUCT; + if (!(ctx->options & E2F_OPT_PREEN)) { +#if 0 /* Do this later; it breaks too many tests' golden outputs */ + log_out(ctx, fs_fixed ? + _("\n%s: ***** FILE SYSTEM ERRORS " + "CORRECTED *****\n") : + _("%s: File system was modified.\n"), + ctx->device_name); +#else + log_out(ctx, + _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"), + ctx->device_name); +#endif + } + if (ctx->mount_flags & EXT2_MF_ISROOT) { + log_out(ctx, _("%s: ***** REBOOT SYSTEM *****\n"), + ctx->device_name); + exit_value |= FSCK_REBOOT; + } + } + +skip_write: + if (!ext2fs_test_valid(fs) || + ((exit_value & FSCK_CANCELED) && + (sb->s_state & EXT2_ERROR_FS))) { + log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has " + "errors **********\n\n"), ctx->device_name); + exit_value |= FSCK_UNCORRECTED; + exit_value &= ~FSCK_NONDESTRUCT; + } + if (exit_value & FSCK_CANCELED) { + int allow_cancellation; + + profile_get_boolean(ctx->profile, "options", + "allow_cancellation", 0, 0, + &allow_cancellation); + exit_value &= ~FSCK_NONDESTRUCT; + if (allow_cancellation && ext2fs_test_valid(fs) && + (sb->s_state & EXT2_VALID_FS) && + !(sb->s_state & EXT2_ERROR_FS)) + exit_value = 0; + } else + show_stats(ctx); + + print_resource_track(ctx, NULL, &ctx->global_rtrack, ctx->fs->io); + + ext2fs_close_free(&ctx->fs); + free(ctx->journal_name); + + if (ctx->logf) + fprintf(ctx->logf, "Exit status: %d\n", exit_value); + e2fsck_free_context(ctx); + remove_error_table(&et_ext2_error_table); + remove_error_table(&et_prof_error_table); + return exit_value; +} diff --git a/e2fsck/util.c b/e2fsck/util.c new file mode 100644 index 0000000..42740d9 --- /dev/null +++ b/e2fsck/util.c @@ -0,0 +1,900 @@ +/* + * util.c --- miscellaneous utilities + * + * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Public + * License. + * %End-Header% + */ + +#include "config.h" +#include <stdlib.h> +#include <stdio.h> +#include <unistd.h> +#include <string.h> +#include <ctype.h> +#ifdef __linux__ +#include <sys/utsname.h> +#endif + +#ifdef HAVE_CONIO_H +#undef HAVE_TERMIOS_H +#include <conio.h> +#define read_a_char() getch() +#else +#ifdef HAVE_TERMIOS_H +#include <termios.h> +#endif +#endif + +#ifdef HAVE_MALLOC_H +#include <malloc.h> +#endif + +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif + +#include "e2fsck.h" + +extern e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */ + +#include <stdarg.h> +#include <time.h> +#include <sys/time.h> +#include <sys/resource.h> + +void fatal_error(e2fsck_t ctx, const char *msg) +{ + ext2_filsys fs = ctx->fs; + int exit_value = FSCK_ERROR; + + if (msg) + fprintf (stderr, "e2fsck: %s\n", msg); + if (!fs) + goto out; + if (fs->io && fs->super) { + ext2fs_mmp_stop(ctx->fs); + if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL) + io_channel_flush(ctx->fs->io); + else + log_err(ctx, "e2fsck: io manager magic bad!\n"); + } + if (ext2fs_test_changed(fs)) { + exit_value |= FSCK_NONDESTRUCT; + log_out(ctx, _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"), + ctx->device_name); + if (ctx->mount_flags & EXT2_MF_ISROOT) + exit_value |= FSCK_REBOOT; + } + if (!ext2fs_test_valid(fs)) { + log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has " + "errors **********\n\n"), ctx->device_name); + exit_value |= FSCK_UNCORRECTED; + exit_value &= ~FSCK_NONDESTRUCT; + } +out: + ctx->flags |= E2F_FLAG_ABORT; + if (ctx->flags & E2F_FLAG_SETJMP_OK) + longjmp(ctx->abort_loc, 1); + if (ctx->logf) + fprintf(ctx->logf, "Exit status: %d\n", exit_value); + exit(exit_value); +} + +void log_out(e2fsck_t ctx, const char *fmt, ...) +{ + va_list pvar; + + va_start(pvar, fmt); + vprintf(fmt, pvar); + va_end(pvar); + if (ctx->logf) { + va_start(pvar, fmt); + vfprintf(ctx->logf, fmt, pvar); + va_end(pvar); + } +} + +void log_err(e2fsck_t ctx, const char *fmt, ...) +{ + va_list pvar; + + va_start(pvar, fmt); + vfprintf(stderr, fmt, pvar); + va_end(pvar); + if (ctx->logf) { + va_start(pvar, fmt); + vfprintf(ctx->logf, fmt, pvar); + va_end(pvar); + } +} + +void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size, + const char *description) +{ + void *ret; + char buf[256]; + +#ifdef DEBUG_ALLOCATE_MEMORY + printf("Allocating %lu bytes for %s...\n", size, description); +#endif + if (ext2fs_get_memzero(size, &ret)) { + sprintf(buf, "Can't allocate %lu bytes for %s\n", + size, description); + fatal_error(ctx, buf); + } + + return ret; +} + +char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)), + const char *str, size_t len) +{ + char *ret; + + if (!str) + return NULL; + if (!len) + len = strlen(str); + ret = malloc(len+1); + if (ret) { + strncpy(ret, str, len); + ret[len] = 0; + } + return ret; +} + +#ifndef HAVE_STRNLEN +/* + * Incredibly, libc5 doesn't appear to have strnlen. So we have to + * provide our own. + */ +int e2fsck_strnlen(const char * s, int count) +{ + const char *cp = s; + + while (count-- && *cp) + cp++; + return cp - s; +} +#endif + +#ifndef HAVE_CONIO_H +static int read_a_char(void) +{ + char c; + int r; + int fail = 0; + + while(1) { + if (e2fsck_global_ctx && + (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) { + return 3; + } + r = read(0, &c, 1); + if (r == 1) + return c; + if (fail++ > 100) + break; + } + return EOF; +} +#endif + +int ask_yn(e2fsck_t ctx, const char * string, int def) +{ + int c; + const char *defstr; + const char *short_yes = _("yY"); + const char *short_no = _("nN"); + const char *short_yesall = _("aA"); + const char *english_yes = "yY"; + const char *english_no = "nN"; + const char *english_yesall = "aA"; + const char *yesall_prompt = _(" ('a' enables 'yes' to all) "); + const char *extra_prompt = ""; + static int yes_answers; + +#ifdef HAVE_TERMIOS_H + struct termios termios, tmp; + + if (tcgetattr (0, &termios) < 0) + memset(&termios, 0, sizeof(termios)); + tmp = termios; + tmp.c_lflag &= ~(ICANON | ECHO); + tmp.c_cc[VMIN] = 1; + tmp.c_cc[VTIME] = 0; + tcsetattr (0, TCSANOW, &tmp); +#endif + + if (def == 1) + defstr = _(_("<y>")); + else if (def == 0) + defstr = _(_("<n>")); + else + defstr = _(" (y/n)"); + /* + * If the user presses 'y' more than 8 (but less than 12) times in + * succession without pressing anything else, display a hint about + * yes-to-all mode. + */ + if (yes_answers > 12) + yes_answers = -1; + else if (yes_answers > 8) + extra_prompt = yesall_prompt; + log_out(ctx, "%s%s%s? ", string, extra_prompt, defstr); + while (1) { + fflush (stdout); + if ((c = read_a_char()) == EOF) + break; + if (c == 3) { +#ifdef HAVE_TERMIOS_H + tcsetattr (0, TCSANOW, &termios); +#endif + if (ctx->flags & E2F_FLAG_SETJMP_OK) { + log_out(ctx, "\n"); + longjmp(e2fsck_global_ctx->abort_loc, 1); + } + log_out(ctx, "%s", _("cancelled!\n")); + yes_answers = 0; + return 0; + } + if (strchr(short_yes, (char) c)) { + do_yes: + def = 1; + if (yes_answers >= 0) + yes_answers++; + break; + } else if (strchr(short_no, (char) c)) { + do_no: + def = 0; + yes_answers = -1; + break; + } else if (strchr(short_yesall, (char)c)) { + do_all: + def = 2; + yes_answers = -1; + ctx->options |= E2F_OPT_YES; + break; + } else if (strchr(english_yes, (char) c)) { + goto do_yes; + } else if (strchr(english_no, (char) c)) { + goto do_no; + } else if (strchr(english_yesall, (char) c)) { + goto do_all; + } else if ((c == 27 || c == ' ' || c == '\n') && (def != -1)) { + yes_answers = -1; + break; + } + } + if (def == 2) + log_out(ctx, "%s", _("yes to all\n")); + else if (def) + log_out(ctx, "%s", _("yes\n")); + else + log_out(ctx, "%s", _("no\n")); +#ifdef HAVE_TERMIOS_H + tcsetattr (0, TCSANOW, &termios); +#endif + return def; +} + +int ask (e2fsck_t ctx, const char * string, int def) +{ + if (ctx->options & E2F_OPT_NO) { + log_out(ctx, _("%s? no\n\n"), string); + return 0; + } + if (ctx->options & E2F_OPT_YES) { + log_out(ctx, _("%s? yes\n\n"), string); + return 1; + } + if (ctx->options & E2F_OPT_PREEN) { + log_out(ctx, "%s? %s\n\n", string, def ? _("yes") : _("no")); + return def; + } + return ask_yn(ctx, string, def); +} + +void e2fsck_read_bitmaps(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + const char *old_op; + unsigned int save_type; + int flags; + + if (ctx->invalid_bitmaps) { + com_err(ctx->program_name, 0, + _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"), + ctx->device_name); + fatal_error(ctx, 0); + } + + old_op = ehandler_operation(_("reading inode and block bitmaps")); + e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE, "fs_bitmaps", + &save_type); + flags = ctx->fs->flags; + ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS; + retval = ext2fs_read_bitmaps(fs); + ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) | + (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS); + fs->default_bitmap_type = save_type; + ehandler_operation(old_op); + if (retval) { + com_err(ctx->program_name, retval, + _("while retrying to read bitmaps for %s"), + ctx->device_name); + fatal_error(ctx, 0); + } +} + +void e2fsck_write_bitmaps(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + errcode_t retval; + const char *old_op; + + old_op = ehandler_operation(_("writing block and inode bitmaps")); + retval = ext2fs_write_bitmaps(fs); + ehandler_operation(old_op); + if (retval) { + com_err(ctx->program_name, retval, + _("while rewriting block and inode bitmaps for %s"), + ctx->device_name); + fatal_error(ctx, 0); + } +} + +void preenhalt(e2fsck_t ctx) +{ + ext2_filsys fs = ctx->fs; + + if (!(ctx->options & E2F_OPT_PREEN)) + return; + log_err(ctx, _("\n\n%s: UNEXPECTED INCONSISTENCY; " + "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"), + ctx->device_name); + ctx->flags |= E2F_FLAG_EXITING; + if (fs != NULL) { + fs->super->s_state |= EXT2_ERROR_FS; + ext2fs_mark_super_dirty(fs); + ext2fs_close_free(&fs); + } + exit(FSCK_UNCORRECTED); +} + +#ifdef RESOURCE_TRACK +void init_resource_track(struct resource_track *track, io_channel channel) +{ +#ifdef HAVE_GETRUSAGE + struct rusage r; +#endif + io_stats io_start = 0; + + track->brk_start = sbrk(0); + gettimeofday(&track->time_start, 0); +#ifdef HAVE_GETRUSAGE +#ifdef sun + memset(&r, 0, sizeof(struct rusage)); +#endif + getrusage(RUSAGE_SELF, &r); + track->user_start = r.ru_utime; + track->system_start = r.ru_stime; +#else + track->user_start.tv_sec = track->user_start.tv_usec = 0; + track->system_start.tv_sec = track->system_start.tv_usec = 0; +#endif + track->bytes_read = 0; + track->bytes_written = 0; + if (channel && channel->manager && channel->manager->get_stats) + channel->manager->get_stats(channel, &io_start); + if (io_start) { + track->bytes_read = io_start->bytes_read; + track->bytes_written = io_start->bytes_written; + } +} + +#ifdef __GNUC__ +#define _INLINE_ __inline__ +#else +#define _INLINE_ +#endif + +static _INLINE_ float timeval_subtract(struct timeval *tv1, + struct timeval *tv2) +{ + return ((tv1->tv_sec - tv2->tv_sec) + + ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000); +} + +void print_resource_track(e2fsck_t ctx, const char *desc, + struct resource_track *track, io_channel channel) +{ +#ifdef HAVE_GETRUSAGE + struct rusage r; +#endif + struct timeval time_end; + + if ((desc && !(ctx->options & E2F_OPT_TIME2)) || + (!desc && !(ctx->options & E2F_OPT_TIME))) + return; + + e2fsck_clear_progbar(ctx); + gettimeofday(&time_end, 0); + + if (desc) + log_out(ctx, "%s: ", desc); + +#define kbytes(x) (((unsigned long long)(x) + 1023) / 1024) +#ifdef HAVE_MALLINFO2 + if (1) { + struct mallinfo2 malloc_info = mallinfo2(); + + log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "), + kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd), + kbytes(malloc_info.uordblks), + kbytes(malloc_info.fordblks)); + } else +#elif defined HAVE_MALLINFO + /* don't use mallinfo() if over 2GB used, since it returns "int" */ + if ((char *)sbrk(0) - (char *)track->brk_start < 2LL << 30) { + struct mallinfo malloc_info = mallinfo(); + + log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "), + kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd), + kbytes(malloc_info.uordblks), + kbytes(malloc_info.fordblks)); + } else +#endif + log_out(ctx, _("Memory used: %lluk, "), + kbytes(((char *)sbrk(0)) - ((char *)track->brk_start))); + +#ifdef HAVE_GETRUSAGE + getrusage(RUSAGE_SELF, &r); + + log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"), + timeval_subtract(&time_end, &track->time_start), + timeval_subtract(&r.ru_utime, &track->user_start), + timeval_subtract(&r.ru_stime, &track->system_start)); +#else + log_out(ctx, _("elapsed time: %6.3f\n"), + timeval_subtract(&time_end, &track->time_start)); +#endif +#define mbytes(x) (((x) + 1048575) / 1048576) + if (channel && channel->manager && channel->manager->get_stats) { + io_stats delta = 0; + unsigned long long bytes_read = 0; + unsigned long long bytes_written = 0; + + if (desc) + log_out(ctx, "%s: ", desc); + + channel->manager->get_stats(channel, &delta); + if (delta) { + bytes_read = delta->bytes_read - track->bytes_read; + bytes_written = delta->bytes_written - + track->bytes_written; + } + log_out(ctx, "I/O read: %lluMB, write: %lluMB, " + "rate: %.2fMB/s\n", + mbytes(bytes_read), mbytes(bytes_written), + (double)mbytes(bytes_read + bytes_written) / + timeval_subtract(&time_end, &track->time_start)); + } +} +#endif /* RESOURCE_TRACK */ + +void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, const char *proc) +{ + errcode_t retval; + + retval = ext2fs_read_inode(ctx->fs, ino, inode); + if (retval) { + com_err("ext2fs_read_inode", retval, + _("while reading inode %lu in %s"), ino, proc); + fatal_error(ctx, 0); + } +} + +void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino, + struct ext2_inode *inode, int bufsize, + const char *proc) +{ + errcode_t retval; + + retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize); + if (retval) { + com_err("ext2fs_read_inode_full", retval, + _("while reading inode %lu in %s"), ino, proc); + fatal_error(ctx, 0); + } +} + +void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, int bufsize, + const char *proc) +{ + errcode_t retval; + + retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize); + if (retval) { + com_err("ext2fs_write_inode", retval, + _("while writing inode %lu in %s"), ino, proc); + fatal_error(ctx, 0); + } +} + +void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino, + struct ext2_inode * inode, const char *proc) +{ + errcode_t retval; + + retval = ext2fs_write_inode(ctx->fs, ino, inode); + if (retval) { + com_err("ext2fs_write_inode", retval, + _("while writing inode %lu in %s"), ino, proc); + fatal_error(ctx, 0); + } +} + +#ifdef MTRACE +void mtrace_print(char *mesg) +{ + FILE *malloc_get_mallstream(); + FILE *f = malloc_get_mallstream(); + + if (f) + fprintf(f, "============= %s\n", mesg); +} +#endif + +blk64_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name, + io_manager manager) +{ + struct ext2_super_block *sb; + io_channel io = NULL; + void *buf = NULL; + int blocksize; + blk64_t superblock, ret_sb = 8193; + + if (fs && fs->super) { + ret_sb = (fs->super->s_blocks_per_group + + fs->super->s_first_data_block); + if (ctx) { + ctx->superblock = ret_sb; + ctx->blocksize = fs->blocksize; + } + return ret_sb; + } + + if (ctx) { + if (ctx->blocksize) { + ret_sb = ctx->blocksize * 8; + if (ctx->blocksize == 1024) + ret_sb++; + ctx->superblock = ret_sb; + return ret_sb; + } + ctx->superblock = ret_sb; + ctx->blocksize = 1024; + } + + if (!name || !manager) + goto cleanup; + + if (manager->open(name, 0, &io) != 0) + goto cleanup; + + if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf)) + goto cleanup; + sb = (struct ext2_super_block *) buf; + + for (blocksize = EXT2_MIN_BLOCK_SIZE; + blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) { + superblock = blocksize*8; + if (blocksize == 1024) + superblock++; + io_channel_set_blksize(io, blocksize); + if (io_channel_read_blk64(io, superblock, + -SUPERBLOCK_SIZE, buf)) + continue; +#ifdef WORDS_BIGENDIAN + if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC)) + ext2fs_swap_super(sb); +#endif + if ((sb->s_magic == EXT2_SUPER_MAGIC) && + (EXT2_BLOCK_SIZE(sb) == blocksize)) { + ret_sb = superblock; + if (ctx) { + ctx->superblock = superblock; + ctx->blocksize = blocksize; + } + break; + } + } + +cleanup: + if (io) + io_channel_close(io); + if (buf) + ext2fs_free_mem(&buf); + return (ret_sb); +} + +/* + * Given a mode, return the ext2 file type + */ +int ext2_file_type(unsigned int mode) +{ + if (LINUX_S_ISREG(mode)) + return EXT2_FT_REG_FILE; + + if (LINUX_S_ISDIR(mode)) + return EXT2_FT_DIR; + + if (LINUX_S_ISCHR(mode)) + return EXT2_FT_CHRDEV; + + if (LINUX_S_ISBLK(mode)) + return EXT2_FT_BLKDEV; + + if (LINUX_S_ISLNK(mode)) + return EXT2_FT_SYMLINK; + + if (LINUX_S_ISFIFO(mode)) + return EXT2_FT_FIFO; + + if (LINUX_S_ISSOCK(mode)) + return EXT2_FT_SOCK; + + return 0; +} + +/* + * Check to see if a filesystem is in /proc/filesystems. + * Returns 1 if found, 0 if not + */ +int fs_proc_check(const char *fs_name) +{ + FILE *f; + char buf[80], *cp, *t; + + f = fopen("/proc/filesystems", "r"); + if (!f) + return (0); + while (!feof(f)) { + if (!fgets(buf, sizeof(buf), f)) + break; + cp = buf; + if (!isspace(*cp)) { + while (*cp && !isspace(*cp)) + cp++; + } + while (*cp && isspace(*cp)) + cp++; + if ((t = strchr(cp, '\n')) != NULL) + *t = 0; + if ((t = strchr(cp, '\t')) != NULL) + *t = 0; + if ((t = strchr(cp, ' ')) != NULL) + *t = 0; + if (!strcmp(fs_name, cp)) { + fclose(f); + return (1); + } + } + fclose(f); + return (0); +} + +/* + * Check to see if a filesystem is available as a module + * Returns 1 if found, 0 if not + */ +int check_for_modules(const char *fs_name) +{ +#ifdef __linux__ + struct utsname uts; + FILE *f; + char buf[1024], *cp, *t; + int i; + + if (uname(&uts)) + return (0); + snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release); + + f = fopen(buf, "r"); + if (!f) + return (0); + while (!feof(f)) { + if (!fgets(buf, sizeof(buf), f)) + break; + if ((cp = strchr(buf, ':')) != NULL) + *cp = 0; + else + continue; + if ((cp = strrchr(buf, '/')) != NULL) + cp++; + else + cp = buf; + i = strlen(cp); + if (i > 3) { + t = cp + i - 3; + if (!strcmp(t, ".ko")) + *t = 0; + } + if (!strcmp(cp, fs_name)) { + fclose(f); + return (1); + } + } + fclose(f); +#endif /* __linux__ */ + return (0); +} + +/* + * Helper function that does the right thing if write returns a + * partial write, or an EAGAIN/EINTR error. + */ +int write_all(int fd, char *buf, size_t count) +{ + ssize_t ret; + int c = 0; + + while (count > 0) { + ret = write(fd, buf, count); + if (ret < 0) { + if ((errno == EAGAIN) || (errno == EINTR)) + continue; + return -1; + } + count -= ret; + buf += ret; + c += ret; + } + return c; +} + +void dump_mmp_msg(struct mmp_struct *mmp, const char *fmt, ...) +{ + va_list pvar; + + if (fmt) { + printf("MMP check failed: "); + va_start(pvar, fmt); + vprintf(fmt, pvar); + va_end(pvar); + } + if (mmp) { + time_t t = mmp->mmp_time; + + printf("MMP_block:\n"); + printf(" mmp_magic: 0x%x\n", mmp->mmp_magic); + printf(" mmp_check_interval: %d\n", + mmp->mmp_check_interval); + printf(" mmp_sequence: %08x\n", mmp->mmp_seq); + printf(" mmp_update_date: %s", ctime(&t)); + printf(" mmp_update_time: %lld\n", + (long long) mmp->mmp_time); + printf(" mmp_node_name: %.*s\n", + EXT2_LEN_STR(mmp->mmp_nodename)); + printf(" mmp_device_name: %.*s\n", + EXT2_LEN_STR(mmp->mmp_bdevname)); + } +} + +errcode_t e2fsck_mmp_update(ext2_filsys fs) +{ + errcode_t retval; + + retval = ext2fs_mmp_update(fs); + if (retval == EXT2_ET_MMP_CHANGE_ABORT) + dump_mmp_msg(fs->mmp_cmp, + _("UNEXPECTED INCONSISTENCY: the filesystem is " + "being modified while fsck is running.\n")); + + return retval; +} + +void e2fsck_set_bitmap_type(ext2_filsys fs, unsigned int default_type, + const char *profile_name, unsigned int *old_type) +{ + unsigned type; + e2fsck_t ctx = (e2fsck_t) fs->priv_data; + + if (old_type) + *old_type = fs->default_bitmap_type; + profile_get_uint(ctx->profile, "bitmaps", profile_name, 0, + default_type, &type); + profile_get_uint(ctx->profile, "bitmaps", "all", 0, type, &type); + fs->default_bitmap_type = type ? type : default_type; +} + +errcode_t e2fsck_allocate_inode_bitmap(ext2_filsys fs, const char *descr, + int deftype, + const char *name, + ext2fs_inode_bitmap *ret) +{ + errcode_t retval; + unsigned int save_type; + + e2fsck_set_bitmap_type(fs, deftype, name, &save_type); + retval = ext2fs_allocate_inode_bitmap(fs, descr, ret); + fs->default_bitmap_type = save_type; + return retval; +} + +errcode_t e2fsck_allocate_block_bitmap(ext2_filsys fs, const char *descr, + int deftype, + const char *name, + ext2fs_block_bitmap *ret) +{ + errcode_t retval; + unsigned int save_type; + + e2fsck_set_bitmap_type(fs, deftype, name, &save_type); + retval = ext2fs_allocate_block_bitmap(fs, descr, ret); + fs->default_bitmap_type = save_type; + return retval; +} + +errcode_t e2fsck_allocate_subcluster_bitmap(ext2_filsys fs, const char *descr, + int deftype, + const char *name, + ext2fs_block_bitmap *ret) +{ + errcode_t retval; + unsigned int save_type; + + e2fsck_set_bitmap_type(fs, deftype, name, &save_type); + retval = ext2fs_allocate_subcluster_bitmap(fs, descr, ret); + fs->default_bitmap_type = save_type; + return retval; +} + +/* Return memory size in bytes */ +unsigned long long get_memory_size(void) +{ +#if defined(_SC_PHYS_PAGES) +# if defined(_SC_PAGESIZE) + return (unsigned long long)sysconf(_SC_PHYS_PAGES) * + (unsigned long long)sysconf(_SC_PAGESIZE); +# elif defined(_SC_PAGE_SIZE) + return (unsigned long long)sysconf(_SC_PHYS_PAGES) * + (unsigned long long)sysconf(_SC_PAGE_SIZE); +# endif +#elif defined(CTL_HW) +# if (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64)) +# define CTL_HW_INT64 +# elif (defined(HW_PHYSMEM) || defined(HW_REALMEM)) +# define CTL_HW_UINT +# endif + int mib[2]; + + mib[0] = CTL_HW; +# if defined(HW_MEMSIZE) + mib[1] = HW_MEMSIZE; +# elif defined(HW_PHYSMEM64) + mib[1] = HW_PHYSMEM64; +# elif defined(HW_REALMEM) + mib[1] = HW_REALMEM; +# elif defined(HW_PYSMEM) + mib[1] = HW_PHYSMEM; +# endif +# if defined(CTL_HW_INT64) + unsigned long long size = 0; +# elif defined(CTL_HW_UINT) + unsigned int size = 0; +# endif + return 0; +#else +# warning "Don't know how to detect memory on your platform?" + return 0; +#endif +} |