ext4: lots of misc bug fixes
Theodore Ts'o
maintainercover ext4: lots of misc bug fixes
While an LLM was creating a whole batch of KUnit tests for ext4[1], the AI found a large number of potential bugs. After validating the list of bugs using a smarter LLM, and adding further fixes found from Sashiko review feedback on the v1 KUnit series, the fixes for the valid bugs are in this patch set. A summary of the bugs, how they are fixed, their criticality level --- e.g., "Critical (data loss)", "High (metadata corruption)", "Low (32-bit compat)", etc. --- as well as notes on the fixes dropped or trimmed during the rebase onto dev can be found in report-bugfixes.md[2].
[1] https://lore.kernel.org/r/[email protected]
[2] https://drive.google.com/file/d/1pnTKAVf9pAoCK27619uP4_3_hpE04SkR/view
The patches in this series are available at the ext4.git tree on the branch pu[3], which is based on the ext4-kunit-tests branch[4] (commit 4deecb8567ff), itself based on the ext4.git dev branch[5] (commit 008aad6508e3, on top of v7.4-rc2).
[3] https://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git/log/?h=pu
[4] https://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git/log/?h=ext4-kunit-tests
[5] https://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git/log/?h=dev
I've dropped or trimmed all of the bug fixes which already fixed by patches submitted and in the dev branch. I've checked the still-open patches at https://patchwork.ozlabs.org/project/linux-ext4 and I think there aren't any more duplicates.
Changes since v1[6]:
- Rebased from the v1 KUnit series (on v7.3-rc4) onto the v2 ext4-kunit-tests branch (on ext4.git dev / v7.4-rc2).
- Dropped three ext4_ext_migrate() fixes now superseded by dev (their KUnit regression tests were moved into ext4-kunit-tests as "ext4: add KUnit regression tests for inode migration fixes"):
* "ext4: cap migrated extents at EXT_INIT_MAX_LEN" (superseded by commit b0a3f2c102e8).
* "ext4: don't treat a handle restart as an error in finish_range()" (superseded by commit 3b6aee59883c).
* "ext4: don't clobber the migration result in ext4_ext_migrate()" (superseded by commit 82e2a5743b6a).
(The ext4_ext_migrate() extent-tree ownership bug previously listed as a known issue in report-bugfixes.md is also now fixed in dev by commits 047061e6a6da, ed8c07b7692c, and 7c1f0eea4a9b.)
- Trimmed two fixes partially superseded upstream or in dev:
* Retitled and trimmed "ext4: only update s_mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set" to "ext4: only validate mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set", as commit 981eec6c300b ("ext4: only update tune mount options when requested") in v7.4-rc1 already guards the copy in ext4_sb_setparams().
* Dropped the bigalloc buffer_head leak fix from "ext4: don't allocate over indirect branches that failed to load", now fixed in dev by commit 79dd565874b3 ("ext4: fix buffer_head leak in ext4_ind_map_blocks() error path").
- Added 10 new core ext4 bug fixes (with KUnit regression tests) uncovered from Sashiko review feedback on the v1 KUnit series and follow-up inspection:
* Skipping EXT4_DIRENT_HASH() / EXT4_DIRENT_MINOR_HASH() reads on fake directory entries and rejecting crafted EXT4_FT_DIR_CSUM entries with nonzero inode or name_len.
* Using loff_t for i_size in ext4_inline_data_truncate() to avoid 32-bit truncation at >= 4 GiB.
* Initializing converted inline directory blocks under the buffer lock and before raising i_size.
* Propagating blkdev_issue_flush() errors from ext4_fc_replay_inode() (the other flush sites in ialloc and ext4_fc_perform_commit() are fixed in dev by commits baf9a298bdd7 and 49ac01dd7d43).
* Validating child dx_node limit and count in ext4_htree_next_block().
* Flushing s_ea_inode_work before clearing EXT4_FC_REPLAY in ext4_fc_replay_cleanup().
* Zeroing dirty EOF folio tails before raising i_size in ext4_setattr().
* Using atomic i_version accessors in swap_inode_data().
* Rejecting multi-block atomic writes split by fscrypt_limit_io_blocks() with -EINVAL without triggering WARN_ON_ONCE(1).
* Protecting extent status shrinker statistics updates and seq_file reads with s_es_lock (updated for SHRINK_STOP from dev commit ec14be6c39ce).
- Added two KUnit test fixes at the end of the series uncovered during tracepoint and RTC-less VM verification:
* "ext4: set bh->b_bdev on mock buffers in resize-test" (fixes a NULL dereference with block:block_dirty_buffer tracing enabled).
* "ext4: avoid zero i_dtime wrap in ialloc-test on RTC-less VMs".
- Verified the full series across UML and x86_64 KUnit runs (579/579 passing, including CONFIG_IA32_EMULATION=y), clean sparse C=2 checks, per-commit CONFIG_EXT4_KUNIT_TESTS=m modular builds with KCFLAGS=-Werror, and checkpatch.pl.
[6] https://lore.kernel.org/r/[email protected]
Theodore Ts'o (32):
ext4: only validate mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set
ext4: return -EFSBADCRC when skipping a corrupt backup superblock
ext4: don't allow enabling casefold via EXT4_IOC_SET_TUNE_SB_PARAM
ext4: persist the htree hash seed when enabling dir_index online
ext4: enforce feature prerequisites when tuning a mounted fs
ext4: handle s_lastcheck_hi in the get/set tune superblock ioctls
ext4: pass missing ioctls through ext4_compat_ioctl
ext4: fix inverted err_report_sec check in ext4_update_super()
ext4: fix err_report_sec_store() timer and value handling
ext4: fix inode table accounting in count_overhead()
ext4: handle flex groups straddling s_first_meta_bg in online resize
ext4: reject EXT4_IOC_GROUP_ADD inputs larger than a block group
ext4: propagate ext4_alloc_group_tables() errors from ext4_resize_fs()
ext4: reject online shrink before probing the device size
ext4: fix EOF clamping of the range in mext_check_adjust_range()
ext4: bound the MMP update and check intervals
ext4: fix MMP claim of a cleanly unmounted filesystem
ext4: fix device comparison overflow in ext4_getfsmap_dev_compare()
ext4: don't allocate over indirect branches that failed to load
ext4: don't stop EXT4_IOC_GET_ES_CACHE at uncached ranges
ext4: don't read dirent hashes from fake directory entries
ext4: use loff_t for i_size in ext4_inline_data_truncate()
ext4: initialize inline dir block under buffer lock before raising
i_size
ext4: propagate cache flush errors from ext4_fc_replay_inode()
ext4: validate child dx_node limit and count in
ext4_htree_next_block()
ext4: flush s_ea_inode_work before clearing EXT4_FC_REPLAY
ext4: zero dirty EOF folio tail before raising i_size in
ext4_setattr() ext4: use atomic iversion accessors in swap_inode_data()
ext4: reject atomic writes split by fscrypt without warning
ext4: protect extent status shrinker stats with s_es_lock
ext4: set bh->b_bdev on mock buffers in resize-test
ext4: avoid zero i_dtime wrap in ialloc-test on RTC-less VMs
fs/ext4/dir-test.c | 157 +++++++++++++++ fs/ext4/dir.c | 19 +- fs/ext4/ext4.h | 31 +++ fs/ext4/extents-test.c | 30 +++ fs/ext4/extents.c | 9 +- fs/ext4/extents_status-test.c | 44 +++- fs/ext4/extents_status.c | 44 +++- fs/ext4/fast_commit-test.c | 101 +++++++++- fs/ext4/fast_commit.c | 8 +- fs/ext4/fsmap-test.c | 56 +++++ fs/ext4/fsmap.c | 2 +- fs/ext4/ialloc-test.c | 30 ++- fs/ext4/indirect-test.c | 90 ++++++++- fs/ext4/indirect.c | 17 +- fs/ext4/inline-test.c | 150 +++++++++++++- fs/ext4/inline.c | 31 ++- fs/ext4/inode-test.c | 141 +++++++++++++ fs/ext4/inode.c | 64 +++++- fs/ext4/ioctl-test.c | 370 ++++++++++++++++++++++++++++++++-- fs/ext4/ioctl.c | 147 +++++++++----- fs/ext4/mmp-test.c | 222 +++++++++++++++++++- fs/ext4/mmp.c | 67 ++++-- fs/ext4/move_extent-test.c | 21 ++ fs/ext4/move_extent.c | 4 +- fs/ext4/namei-test.c | 189 +++++++++++++++++ fs/ext4/namei.c | 86 +++++--- fs/ext4/resize-test.c | 129 +++++++++++- fs/ext4/resize.c | 70 +++++-- fs/ext4/super-test.c | 37 ++++ fs/ext4/super.c | 28 ++- fs/ext4/sysfs-test.c | 55 +++++ fs/ext4/sysfs.c | 21 +- 32 files changed, 2260 insertions(+), 210 deletions(-)
base-commit: 4deecb8567ffe0167209b34c2183e18795c05fc6
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 1/32 ext4: only validate mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set
Commit 981eec6c300b ("ext4: only update tune mount options when requested") guarded the s_mount_opts copy in ext4_sb_setparams() with EXT4_TUNE_FL_MOUNT_OPTS, but ext4_validate_tune_sb_params() still rejects an unterminated mount_opts string even when the caller is not asking to change it. A caller that tunes an unrelated field and leaves mount_opts uninitialized can therefore get a spurious -E2BIG.
Only validate mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set, and add a KUnit test covering both the validation and copy guards.
--- fs/ext4/ioctl-test.c | 40 ++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 3 ++- 2 files changed, 42 insertions(+), 1 deletion(-)
fs/ext4/ioctl-test.c +40 -0
@@ -609,6 +609,7 @@ static void test_validate_tune_sb_params(struct kunit *test)/* Unterminated mount_opts -> -E2BIG */ memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_MOUNT_OPTS ;memset (params.mount_opts,'a' ,sizeof (params.mount_opts));KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), -E2BIG );
@@ -702,6 +703,44 @@ static void test_validate_tune_sb_params(struct kunit *test)KUNIT_EXPECT_EQ (test, params.encoding_flags,0 ); } +/* +* Verify that s_mount_opts is only validated and rewritten when +* EXT4_TUNE_FL_MOUNT_OPTS is set, so that tuning an unrelated field does +* not wipe the mount options stored in the superblock. +*/ +static void test_tune_sb_mount_opts_guard (struct kunit *test) +{ +struct ioctl_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *es = ctx->es; +struct ext4_tune_sb_params params; + +strscpy_pad (es->s_mount_opts,"journal_checksum" ); + +/* Garbage in mount_opts is ignored without EXT4_TUNE_FL_MOUNT_OPTS */ +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_ERRORS_BEHAVIOR ; + params.errors_behavior =EXT4_ERRORS_RO ; +memset (params.mount_opts,'a' ,sizeof (params.mount_opts)); +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), +0 ); + +/* Tuning another field leaves s_mount_opts untouched */ +memset (params.mount_opts,0 ,sizeof (params.mount_opts)); +ext4_sb_setparams_test (sbi, es, ¶ms); +KUNIT_EXPECT_EQ (test,le16_to_cpu (es->s_errors),EXT4_ERRORS_RO ); +KUNIT_EXPECT_STREQ (test, (char *)es->s_mount_opts,"journal_checksum" ); + +/* With EXT4_TUNE_FL_MOUNT_OPTS the new value is written */ + params.set_flags =EXT4_TUNE_FL_MOUNT_OPTS ; +strscpy (params.mount_opts,"nodelalloc" ,sizeof (params.mount_opts)); +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), +0 ); +ext4_sb_setparams_test (sbi, es, ¶ms); +KUNIT_EXPECT_STREQ (test, (char *)es->s_mount_opts,"nodelalloc" ); +} +/* * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3,
@@ -1179,6 +1218,7 @@ static void test_force_shutdown_and_ioctl_dispatch(struct kunit *test)static struct kunit_case ioctl_test_cases[] = {KUNIT_CASE (test_sb_callbacks_and_setparams),KUNIT_CASE (test_validate_tune_sb_params), +KUNIT_CASE (test_tune_sb_mount_opts_guard),KUNIT_CASE (test_update_superblocks_and_overhead),KUNIT_CASE (test_swap_inode_data_and_seed),KUNIT_CASE (test_immutable_dax_and_fileattr),
fs/ext4/ioctl.c +2 -1
@@ -1409,7 +1409,8 @@ static int ext4_validate_tune_sb_params(struct super_block *sb,struct ext4_super_block *es = sbi->s_es;int enabling_casefold =0 ; -if (strnlen (params->mount_opts,sizeof (params->mount_opts)) == +if ((params->set_flags &EXT4_TUNE_FL_MOUNT_OPTS ) && +strnlen (params->mount_opts,sizeof (params->mount_opts)) ==sizeof (params->mount_opts))return -E2BIG ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 2/32 ext4: return -EFSBADCRC when skipping a corrupt backup superblock
In reply to Theodore Ts'oCommit 9a8c5b0d0615 ("ext4: update the backup superblock's at the end of the online resize") stopped setting err = -EFSBADCRC when ext4_update_backup_sb() finds a backup superblock with an invalid checksum, so that ext4_std_error() would not mark the file system as corrupted. However, it left err at 0, so the function now returns 1, claiming that the backup superblock was successfully updated.
This makes the "Ignore bad checksum; try to update next sb" check in ext4_update_superblocks_fn() dead code, and the skipped backup is counted towards the two backup superblocks which are supposed to be updated through the journal. If one of the first backups is corrupt, fewer than two backup superblocks get journalled updates.
Release the buffer and return -EFSBADCRC directly, bypassing ext4_std_error(), so the caller skips the corrupt backup without counting it and without aborting the update.
--- fs/ext4/ioctl-test.c | 47 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 10 ++++++++-- 2 files changed, 55 insertions(+), 2 deletions(-)
fs/ext4/ioctl-test.c +47 -0
@@ -829,6 +829,52 @@ static void test_update_superblocks_and_overhead(struct kunit *test)KUNIT_EXPECT_EQ (test, ctx->sync_bh_calls,5 ); } +/* +* Verify that a backup superblock with an invalid checksum is reported as +* -EFSBADCRC (and left untouched) rather than counted as updated, and that +* ext4_update_superblocks_fn still updates the remaining backups. +*/ +static void test_update_backup_sb_bad_csum (struct kunit *test) +{ +struct ioctl_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +static const ext4_group_t good_grps[] = {1 ,5 ,7 }; +char new_label[EXT4_LABEL_MAX ] ="csum_label" ; +struct ext4_super_block *bad; +int i; + + bad = (struct ext4_super_block *)ctx->backup_sb_bufs[3 ]; + bad->s_checksum =cpu_to_le32 (~le32_to_cpu (bad->s_checksum)); + + ctx->sync_bh_calls =0 ; +KUNIT_EXPECT_EQ (test, +ext4_update_backup_sb_test (sb,NULL ,3 , + ext4_sb_setlabel_test, + new_label), + -EFSBADCRC ); +KUNIT_EXPECT_EQ (test, ctx->sync_bh_calls,0 ); +KUNIT_EXPECT_MEMNEQ (test, bad->s_volume_name, new_label, +EXT4_LABEL_MAX ); + +/* Primary + backups 1, 5 and 7 are updated; backup 3 is skipped */ +KUNIT_EXPECT_EQ (test, +ext4_update_superblocks_fn_test (sb, + ext4_sb_setlabel_test, + new_label), +0 ); +KUNIT_EXPECT_EQ (test, ctx->sync_bh_calls,4 ); +KUNIT_EXPECT_MEMNEQ (test, bad->s_volume_name, new_label, +EXT4_LABEL_MAX ); +for (i =0 ; i <ARRAY_SIZE (good_grps); i++) { +struct ext4_super_block *bes; + + bes = (struct ext4_super_block *) + ctx->backup_sb_bufs[good_grps[i]]; +KUNIT_EXPECT_MEMEQ (test, bes->s_volume_name, new_label, +EXT4_LABEL_MAX ); + } +} +/* * Verify swap_inode_data swaps i_data, i_disksize, i_size, i_version, * atime/mtime, and EXT4_FL_SHOULD_SWAP flags while preserving non-swapped
@@ -1220,6 +1266,7 @@ static struct kunit_case ioctl_test_cases[] = {KUNIT_CASE (test_validate_tune_sb_params),KUNIT_CASE (test_tune_sb_mount_opts_guard),KUNIT_CASE (test_update_superblocks_and_overhead), +KUNIT_CASE (test_update_backup_sb_bad_csum),KUNIT_CASE (test_swap_inode_data_and_seed),KUNIT_CASE (test_immutable_dax_and_fileattr), KUNIT_CASE(test_force_shutdown_and_ioctl_dispatch),
fs/ext4/ioctl.c +8 -2
@@ -110,7 +110,8 @@ int ext4_update_primary_sb(struct super_block *sb, handle_t *handle,* * Returns: 0 when no modification was done (no superblock in the group) * 1 when the modification was successful -* <0 on error +* <0 on error (-EFSBADCRC if the backup superblock has an invalid +* checksum and was skipped) */ static int ext4_update_backup_sb(struct super_block *sb, handle_t *handle, ext4_group_t grp,
@@ -159,7 +160,12 @@ static int ext4_update_backup_sb(struct super_block *sb,ext4_msg (sb,KERN_ERR ,"Invalid checksum for backup " "superblock %llu" , sb_block);unlock_buffer (bh); - goto out_bh; +/* +* Let the caller skip this backup; don't report it via +* ext4_std_error() since it must not abort the update. +*/ +brelse (bh); +return -EFSBADCRC ; }func (EXT4_SB (sb), es, arg);if (ext4_has_feature_metadata_csum (sb))
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 3/32 ext4: don't allow enabling casefold via EXT4_IOC_SET_TUNE_SB_PARAM
In reply to Theodore Ts'oEXT4_IOC_SET_TUNE_SB_PARAM allows setting the casefold feature (along with s_encoding and s_encoding_flags) on a mounted file system, but it only updates the on-disk superblock. The in-memory state needed by casefolding is set up exclusively at mount time:
- sb->s_encoding is loaded by ext4_encoding_init(), so it stays NULL;
- the casefolding dentry operations are installed before the root dentry is created, and can't be retrofitted onto a live dcache;
- nothing checks for CONFIG_UNICODE, so a kernel without it can set a feature that then prevents the file system from being mounted.
Since ext4_has_feature_casefold() becomes true as soon as the primary superblock is updated, userspace can then set EXT4_CASEFOLD_FL on an empty directory, and the next lookup or create in it passes the NULL sb->s_encoding to utf8_casefold(), crashing the kernel.
Casefolding has to be enabled while the file system is unmounted, so stop advertising and accepting the casefold feature and the EXT4_TUNE_FL_ENCODING{,_FLAGS} operations, and remove the code that handled them.
--- fs/ext4/ioctl-test.c | 35 ++++++++++++++++++++------------- fs/ext4/ioctl.c | 47 +++++++------------------------------------- 2 files changed, 28 insertions(+), 54 deletions(-)
fs/ext4/ioctl-test.c +21 -14
@@ -534,8 +534,6 @@ static void test_sb_callbacks_and_setparams(struct kunit *test)EXT4_TUNE_FL_DEF_HASH_ALG |EXT4_TUNE_FL_RAID_STRIDE |EXT4_TUNE_FL_RAID_STRIPE_WIDTH | -EXT4_TUNE_FL_ENCODING | -EXT4_TUNE_FL_ENCODING_FLAGS |EXT4_TUNE_FL_MOUNT_OPTS |EXT4_TUNE_FL_EDIT_FEATURES |EXT4_TUNE_FL_FORCE_FSCK ;
@@ -551,8 +549,6 @@ static void test_sb_callbacks_and_setparams(struct kunit *test) params.def_hash_alg =DX_HASH_HALF_MD4 ; params.raid_stride =16 ; params.raid_stripe_width =128 ; - params.encoding =EXT4_ENC_UTF8_12_1 ; - params.encoding_flags =SB_ENC_STRICT_MODE_FL ;strscpy (params.mount_opts,"nodelalloc,noatime" ,sizeof (params.mount_opts)); params.set_feature_compat_mask =EXT4_FEATURE_COMPAT_DIR_INDEX ;
@@ -575,9 +571,6 @@ static void test_sb_callbacks_and_setparams(struct kunit *test)KUNIT_EXPECT_EQ (test, es->s_def_hash_version,DX_HASH_TEA );KUNIT_EXPECT_EQ (test,le16_to_cpu (es->s_raid_stride),16 );KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_raid_stripe_width),128U ); -KUNIT_EXPECT_EQ (test,le16_to_cpu (es->s_encoding),EXT4_ENC_UTF8_12_1 ); -KUNIT_EXPECT_EQ (test,le16_to_cpu (es->s_encoding_flags), -SB_ENC_STRICT_MODE_FL );KUNIT_EXPECT_STREQ (test, (char *)es->s_mount_opts,"nodelalloc,noatime" ); KUNIT_EXPECT_NE(test,
@@ -595,8 +588,9 @@ static void test_sb_callbacks_and_setparams(struct kunit *test)/* * Verify ext4_validate_tune_sb_params rejects malformed mount_opts, invalid -* flags, out-of-range parameters, unsupported feature edits, and standalone -* encoding updates, while normalizing DIR_INDEX and CASEFOLD enablement. +* flags, out-of-range parameters, unsupported feature edits, encoding +* updates and online casefold enablement, while normalizing DIR_INDEX +* enablement. */ static void test_validate_tune_sb_params (struct kunit *test) {
@@ -687,20 +681,33 @@ static void test_validate_tune_sb_params(struct kunit *test)KUNIT_EXPECT_FALSE (test,uuid_is_null (&uu));KUNIT_EXPECT_EQ (test, sbi->s_def_hash_version,DX_HASH_HALF_MD4 ); -/* Encoding without CASEFOLD -> -EINVAL; with CASEFOLD -> UTF8_12_1 */ +/* Encoding changes and online casefold enablement -> -EOPNOTSUPP */ memset (¶ms,0 ,sizeof (params)); params.set_flags =EXT4_TUNE_FL_ENCODING ; params.encoding =EXT4_ENC_UTF8_12_1 ;KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), - -EINVAL ); + -EOPNOTSUPP ); + +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_ENCODING_FLAGS ; +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), + -EOPNOTSUPP );memset (¶ms,0 ,sizeof (params)); params.set_flags =EXT4_TUNE_FL_EDIT_FEATURES ; params.set_feature_incompat_mask =EXT4_FEATURE_INCOMPAT_CASEFOLD ;KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), -0 ); -KUNIT_EXPECT_EQ (test, params.encoding,EXT4_ENC_UTF8_12_1 ); -KUNIT_EXPECT_EQ (test, params.encoding_flags,0 ); + -EOPNOTSUPP ); + +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_FEATURES ; + params.feature_compat =le32_to_cpu (es->s_feature_compat); + params.feature_incompat =le32_to_cpu (es->s_feature_incompat) | +EXT4_FEATURE_INCOMPAT_CASEFOLD ; + params.feature_ro_compat =le32_to_cpu (es->s_feature_ro_compat); +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), + -EOPNOTSUPP ); +KUNIT_EXPECT_FALSE (test,ext4_has_feature_casefold (sb)); }/*
fs/ext4/ioctl.c +7 -40
90 lines not on this page · raw message
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 4/32 ext4: persist the htree hash seed when enabling dir_index online
In reply to Theodore Ts'oWhen EXT4_IOC_SET_TUNE_SB_PARAM enables the dir_index feature, ext4_validate_tune_sb_params() generates a random sbi->s_hash_seed if the current one is all zeroes, and picks the hash signedness in sbi->s_hash_unsigned. However, ext4_sb_setparams() only copies s_def_hash_version to the superblocks; the hash seed and the EXT2_FLAGS_{UNSIGNED,SIGNED}_HASH flag are never written out.
Any directory converted to an htree before the next unmount has its names hashed with the random in-memory seed. After a remount the seed is reloaded from the (still all-zero) on-disk superblock, so lookups in those directories compute different hashes and fail with -ENOENT, and new entries are inserted into the wrong leaf blocks.
In addition, if the superblock already has EXT2_FLAGS_UNSIGNED_HASH set (e.g. it was created by mke2fs on an unsigned-char platform with dir_index disabled), sbi->s_hash_unsigned is left at 0, so names containing bytes >= 0x80 are hashed differently than they will be after the next mount, which honors the flag.
Write the hash seed and, if neither flag is present, the signedness flag matching sbi->s_hash_unsigned to the primary and backup superblocks, and set sbi->s_hash_unsigned from an existing EXT2_FLAGS_UNSIGNED_HASH flag just like ext4_fill_super() does.
The in-memory values are still set up before the superblocks are updated, since htree directories may be created as soon as the feature bit is visible in the primary superblock.
--- fs/ext4/ioctl-test.c | 60 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 23 +++++++++++++---- 2 files changed, 78 insertions(+), 5 deletions(-)
fs/ext4/ioctl-test.c +60 -0
@@ -748,6 +748,65 @@ static void test_tune_sb_mount_opts_guard(struct kunit *test)KUNIT_EXPECT_STREQ (test, (char *)es->s_mount_opts,"nodelalloc" ); } +/* +* Verify that enabling DIR_INDEX online persists the (possibly freshly +* generated) hash seed and the hash signedness flag to the superblock, and +* that an existing signedness flag in s_flags is honored in memory. +*/ +static void test_tune_sb_dir_index_hash_state (struct kunit *test) +{ +struct ioctl_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *es = ctx->es; +struct ext4_tune_sb_params params; +__le32 hash_flags; +uuid_t uu; +int i; + +memset (sbi->s_hash_seed,0 ,sizeof (sbi->s_hash_seed)); +memset (es->s_hash_seed,0 ,sizeof (es->s_hash_seed)); + sbi->s_def_hash_version =0 ; + es->s_flags =0 ; + +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_FEATURES ; + params.feature_compat =le32_to_cpu (es->s_feature_compat) | +EXT4_FEATURE_COMPAT_DIR_INDEX ; + params.feature_incompat =le32_to_cpu (es->s_feature_incompat); + params.feature_ro_compat =le32_to_cpu (es->s_feature_ro_compat); +KUNIT_ASSERT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), +0 ); +ext4_sb_setparams_test (sbi, es, ¶ms); + +KUNIT_EXPECT_TRUE (test,ext4_has_feature_dir_index (sb)); +KUNIT_EXPECT_EQ (test, es->s_def_hash_version,DX_HASH_HALF_MD4 ); +memcpy (&uu, es->s_hash_seed,UUID_SIZE ); +KUNIT_EXPECT_FALSE (test,uuid_is_null (&uu)); +for (i =0 ; i <ARRAY_SIZE (es->s_hash_seed); i++) +KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_hash_seed[i]), + sbi->s_hash_seed[i]); + hash_flags = es->s_flags &cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH | +EXT2_FLAGS_SIGNED_HASH ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (hash_flags), + sbi->s_hash_unsigned ?EXT2_FLAGS_UNSIGNED_HASH : +EXT2_FLAGS_SIGNED_HASH ); + +/* An existing unsigned-hash flag must be honored in memory */ +ext4_clear_feature_dir_index (sb); + es->s_flags =cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH ); + sbi->s_hash_unsigned =0 ; +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_EDIT_FEATURES ; + params.set_feature_compat_mask =EXT4_FEATURE_COMPAT_DIR_INDEX ; +KUNIT_ASSERT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), +0 ); +KUNIT_EXPECT_EQ (test, sbi->s_hash_unsigned,3U ); +ext4_sb_setparams_test (sbi, es, ¶ms); +KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_flags), +EXT2_FLAGS_UNSIGNED_HASH ); +} +/* * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3,
@@ -1272,6 +1331,7 @@ static struct kunit_case ioctl_test_cases[] = {KUNIT_CASE (test_sb_callbacks_and_setparams),KUNIT_CASE (test_validate_tune_sb_params),KUNIT_CASE (test_tune_sb_mount_opts_guard), +KUNIT_CASE (test_tune_sb_dir_index_hash_state),KUNIT_CASE (test_update_superblocks_and_overhead),KUNIT_CASE (test_update_backup_sb_bad_csum), KUNIT_CASE(test_swap_inode_data_and_seed),
fs/ext4/ioctl.c +18 -5
@@ -1392,8 +1392,20 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, es->s_feature_ro_compat &= ~cpu_to_le32 (params->clear_feature_ro_compat_mask);if (params->set_feature_compat_mask & -EXT4_FEATURE_COMPAT_DIR_INDEX ) +EXT4_FEATURE_COMPAT_DIR_INDEX ) { +int i; + es->s_def_hash_version = sbi->s_def_hash_version; +for (i =0 ; i <ARRAY_SIZE (es->s_hash_seed); i++) + es->s_hash_seed[i] = +cpu_to_le32 (sbi->s_hash_seed[i]); +if (!(es->s_flags & +cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH | +EXT2_FLAGS_SIGNED_HASH ))) + es->s_flags |= sbi->s_hash_unsigned ? +cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH ) : +cpu_to_le32 (EXT2_FLAGS_SIGNED_HASH ); + }if (params->set_feature_incompat_mask &EXT4_FEATURE_INCOMPAT_CSUM_SEED ) es->s_checksum_seed =cpu_to_le32 (sbi->s_csum_seed);
@@ -1490,10 +1502,11 @@ static int ext4_validate_tune_sb_params(struct super_block *sb, sbi->s_def_hash_version = params->def_hash_alg; else if (sbi->s_def_hash_version == 0) sbi->s_def_hash_version = DX_HASH_HALF_MD4; -if (!(es->s_flags & -cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH )) && - !(es->s_flags & -cpu_to_le32 (EXT2_FLAGS_SIGNED_HASH ))) { +if (es->s_flags & +cpu_to_le32 (EXT2_FLAGS_UNSIGNED_HASH )) { + sbi->s_hash_unsigned =3 ; + }else if (!(es->s_flags & +cpu_to_le32 (EXT2_FLAGS_SIGNED_HASH ))) {#ifdef __CHAR_UNSIGNED__ sbi->s_hash_unsigned =3 ;#else
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 5/32 ext4: enforce feature prerequisites when tuning a mounted fs
In reply to Theodore Ts'oEXT4_IOC_SET_TUNE_SB_PARAM lets userspace enable a number of features on a mounted file system, but it skips prerequisites that are otherwise enforced when the file system is mounted (or by tune2fs), leading to corrupted metadata or file systems that can no longer be mounted read-write:
- metadata_csum_seed: ext4_sb_setparams() stores sbi->s_csum_seed in s_checksum_seed, but that is only initialized when metadata_csum (or ea_inode) is enabled; otherwise a zero seed is written. tune2fs likewise requires metadata_csum for this feature.
- ea_inode: EA inode hashes are seeded with sbi->s_csum_seed, which is zero unless metadata_csum or csum_seed was enabled at mount time. After a remount the seed is computed from the UUID, so all EA inodes written before the remount fail hash verification. The feature is also refused at mount time in Hurd compat mode.
- encrypt: ext4 disables large folios at mount time when encryption is enabled, since fscrypt can't handle them. Enabling it online while large folios are in use lets new encrypted files use large folios, tripping VM_BUG_ON_FOLIO() in fscrypt_encrypt_pagecache_blocks().
- project: a kernel built without CONFIG_QUOTA and CONFIG_QFMT_V2 refuses to mount a file system with this feature read-write. Project ids (like the fields covered by extra_isize) also need inodes larger than 128 bytes; tune2fs refuses to enable project quotas otherwise.
Reject these cases with -EINVAL or -EOPNOTSUPP, and when ea_inode is enabled on a file system without metadata_csum or csum_seed, compute sbi->s_csum_seed the same way the next mount will.
--- fs/ext4/ioctl-test.c | 95 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 42 ++++++++++++++++++++ 2 files changed, 137 insertions(+)
fs/ext4/ioctl-test.c +95 -0
@@ -807,6 +807,100 @@ static void test_tune_sb_dir_index_hash_state(struct kunit *test) EXT2_FLAGS_UNSIGNED_HASH); } +static int ioctl_test_set_features (struct super_block *sb,u32 incompat, +u32 ro_compat) +{ +struct ext4_tune_sb_params params; + +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_EDIT_FEATURES ; + params.set_feature_incompat_mask = incompat; + params.set_feature_ro_compat_mask = ro_compat; +return ext4_validate_tune_sb_params_test (sb, ¶ms); +} + +/* +* Verify that features whose prerequisites are otherwise only enforced at +* mount time are rejected when they can't be satisfied, and that enabling +* ea_inode online initializes the checksum seed used for EA inode hashes. +*/ +static void test_tune_sb_feature_prereqs (struct kunit *test) +{ +struct ioctl_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *es = ctx->es; +u32 seed =ext4_chksum (~0 , es->s_uuid,sizeof (es->s_uuid)); +int expected; + +/* csum_seed requires metadata_csum */ +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_CSUM_SEED ,0 ), +0 ); + +/* ea_inode is refused in Hurd compat mode */ +set_opt2 (sb,HURD_COMPAT ); +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_EA_INODE ,0 ), + -EINVAL ); +clear_opt2 (sb,HURD_COMPAT ); + +/* encrypt is refused while large folios are in use */ + sbi->s_max_folio_order =2 ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_ENCRYPT ,0 ), + -EOPNOTSUPP ); + sbi->s_max_folio_order =0 ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_ENCRYPT ,0 ), +0 ); + +/* project needs quota support and large inodes */ + expected =IS_ENABLED (CONFIG_QUOTA ) &&IS_ENABLED (CONFIG_QFMT_V2 ) ? +0 : -EOPNOTSUPP ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb,0 , +EXT4_FEATURE_RO_COMPAT_PROJECT ), + expected); + +ext4_clear_feature_extra_isize (sb); + es->s_inode_size =cpu_to_le16 (EXT4_GOOD_OLD_INODE_SIZE ); + sbi->s_inode_size =EXT4_GOOD_OLD_INODE_SIZE ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb,0 , +EXT4_FEATURE_RO_COMPAT_PROJECT ), + -EINVAL ); +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb,0 , +EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE ), + -EINVAL ); + es->s_inode_size =cpu_to_le16 (IOCTL_TEST_INODE_SIZE ); + sbi->s_inode_size =IOCTL_TEST_INODE_SIZE ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb,0 , +EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE ), +0 ); + +/* Without metadata_csum, csum_seed is refused ... */ +ext4_clear_feature_metadata_csum (sb); +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_CSUM_SEED ,0 ), + -EINVAL ); + +/* ... and enabling ea_inode sets up the checksum seed */ + sbi->s_csum_seed =0 ; +KUNIT_EXPECT_EQ (test, +ioctl_test_set_features (sb, +EXT4_FEATURE_INCOMPAT_EA_INODE ,0 ), +0 ); +KUNIT_EXPECT_EQ (test, sbi->s_csum_seed, seed); +} +/* * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3,
@@ -1332,6 +1426,7 @@ static struct kunit_case ioctl_test_cases[] = {KUNIT_CASE (test_validate_tune_sb_params),KUNIT_CASE (test_tune_sb_mount_opts_guard),KUNIT_CASE (test_tune_sb_dir_index_hash_state), +KUNIT_CASE (test_tune_sb_feature_prereqs),KUNIT_CASE (test_update_superblocks_and_overhead),KUNIT_CASE (test_update_backup_sb_bad_csum), KUNIT_CASE(test_swap_inode_data_and_seed),
fs/ext4/ioctl.c +42 -0
48 lines not on this page · raw message
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 6/32 ext4: handle s_lastcheck_hi in the get/set tune superblock ioctls
In reply to Theodore Ts'ostruct ext4_tune_sb_params exposes last_check_time as a __u64, and the superblock stores the time of the last check as a 40-bit value split between s_lastcheck and s_lastcheck_hi. However, EXT4_IOC_GET_TUNE_SB_PARAM only reports s_lastcheck, and EXT4_IOC_SET_TUNE_SB_PARAM only writes s_lastcheck, leaving any existing s_lastcheck_hi in place.
So timestamps past 2106 are truncated when read, and setting the last check time on a file system whose s_lastcheck_hi is non-zero results in a timestamp that is off by a multiple of 2^32 seconds, which confuses the time-based fsck check in ext4_setup_super() and e2fsck.
Read and write s_lastcheck_hi along with s_lastcheck, and reject values which don't fit in the 40-bit on-disk representation.
--- fs/ext4/ioctl-test.c | 62 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 12 +++++++-- 2 files changed, 72 insertions(+), 2 deletions(-)
fs/ext4/ioctl-test.c +62 -0
@@ -17,6 +17,7 @@#include <linux/iversion.h> #include <linux/kernel.h> #include <linux/mm.h> +#include <linux/mman.h> #include <linux/module.h> #include <linux/mount.h> #include <linux/part_stat.h>
@@ -27,6 +28,7 @@#include <linux/slab.h> #include <linux/string.h> #include <linux/timer.h> +#include <linux/uaccess.h> #include <linux/uuid.h> #include <linux/workqueue.h>
@@ -901,6 +903,65 @@ static void test_tune_sb_feature_prereqs(struct kunit *test)KUNIT_EXPECT_EQ (test, sbi->s_csum_seed, seed); } +/* +* Verify that last_check_time is validated against, stored to, and +* reported from the 40-bit s_lastcheck / s_lastcheck_hi timestamp. +*/ +static void test_tune_sb_last_check_time (struct kunit *test) +{ +struct ioctl_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *es = ctx->es; +struct ext4_tune_sb_params params; +struct vfsmount mnt = { + .mnt_root = sb->s_root, + .mnt_sb = sb, + .mnt_idmap = &nop_mnt_idmap, + }; +struct file filp = { + .f_inode =d_inode (sb->s_root), + .f_path = { + .mnt = &mnt, + .dentry = sb->s_root, + }, + .f_mode =FMODE_READ , + }; +unsigned long uaddr; + +memset (¶ms,0 ,sizeof (params)); + params.set_flags =EXT4_TUNE_FL_LAST_CHECK_TIME ; + params.last_check_time =1ULL <<40 ; +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), + -EINVAL ); + + params.last_check_time =0x123456789aULL ; +KUNIT_EXPECT_EQ (test,ext4_validate_tune_sb_params_test (sb, ¶ms), +0 ); + es->s_lastcheck_hi =0xff ; +ext4_sb_setparams_test (sbi, es, ¶ms); +KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_lastcheck),0x3456789aU ); +KUNIT_EXPECT_EQ (test, es->s_lastcheck_hi,0x12 ); + +/* EXT4_IOC_GET_TUNE_SB_PARAM reports all 40 bits */ + uaddr =kunit_vm_mmap (test,NULL ,0 ,PAGE_SIZE , +PROT_READ |PROT_WRITE , +MAP_ANONYMOUS |MAP_PRIVATE ,0 ); +KUNIT_ASSERT_NE_MSG (test, uaddr,0UL ,"Could not create user mm" ); +KUNIT_ASSERT_LT_MSG (test, uaddr, (unsigned long )TASK_SIZE , +"Failed to allocate user memory" ); + +KUNIT_ASSERT_EQ (test, +ext4_ioctl (&filp,EXT4_IOC_GET_TUNE_SB_PARAM , uaddr), +0 ); +memset (¶ms,0 ,sizeof (params)); +KUNIT_ASSERT_EQ (test, +copy_from_user (¶ms, (void __user *)uaddr, +sizeof (params)), +0UL ); +KUNIT_EXPECT_EQ (test, params.last_check_time,0x123456789aULL ); +} +/* * Verify ext4_update_backup_sb, ext4_update_superblocks_fn, and * ext4_update_overhead across primary + 4 sparse_super backup groups (1, 3,
@@ -1427,6 +1488,7 @@ static struct kunit_case ioctl_test_cases[] = {KUNIT_CASE (test_tune_sb_mount_opts_guard),KUNIT_CASE (test_tune_sb_dir_index_hash_state),KUNIT_CASE (test_tune_sb_feature_prereqs), +KUNIT_CASE (test_tune_sb_last_check_time),KUNIT_CASE (test_update_superblocks_and_overhead),KUNIT_CASE (test_update_backup_sb_bad_csum), KUNIT_CASE(test_swap_inode_data_and_seed),
fs/ext4/ioctl.c +10 -2
@@ -1308,7 +1308,8 @@ static int ext4_ioctl_get_tune_sb(struct ext4_sb_info *sbi, ret.mnt_count =le16_to_cpu (es->s_mnt_count); ret.max_mnt_count =le16_to_cpu (es->s_max_mnt_count); ret.checkinterval =le32_to_cpu (es->s_checkinterval); - ret.last_check_time =le32_to_cpu (es->s_lastcheck); + ret.last_check_time = ((u64 )es->s_lastcheck_hi <<32 ) | +le32_to_cpu (es->s_lastcheck); ret.reserved_blocks =ext4_r_blocks_count (es); ret.blocks_count =ext4_blocks_count (es); ret.reserved_uid =ext4_get_resuid (es);
@@ -1347,8 +1348,10 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, es->s_max_mnt_count =cpu_to_le16 (params->max_mnt_count);if (params->set_flags &EXT4_TUNE_FL_CHECKINTRVAL ) es->s_checkinterval =cpu_to_le32 (params->checkinterval); -if (params->set_flags &EXT4_TUNE_FL_LAST_CHECK_TIME ) +if (params->set_flags &EXT4_TUNE_FL_LAST_CHECK_TIME ) { es->s_lastcheck =cpu_to_le32 (params->last_check_time); + es->s_lastcheck_hi =upper_32_bits (params->last_check_time); + }if (params->set_flags &EXT4_TUNE_FL_RESERVED_BLOCKS ) {ext4_fsblk_t blk = params->reserved_blocks;
@@ -1434,6 +1437,11 @@ static int ext4_validate_tune_sb_params(struct super_block *sb, (params->errors_behavior > EXT4_ERRORS_PANIC))return -EINVAL ; +/* s_lastcheck{,_hi} hold a 40-bit timestamp */ +if ((params->set_flags &EXT4_TUNE_FL_LAST_CHECK_TIME ) && + (params->last_check_time >>40 )) +return -EINVAL ; +if ((params->set_flags &EXT4_TUNE_FL_RESERVED_BLOCKS ) && (params->reserved_blocks >ext4_blocks_count (sbi->s_es) /2 ))return -EINVAL ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 7/32 ext4: pass missing ioctls through ext4_compat_ioctl
In reply to Theodore Ts'oext4_compat_ioctl() only forwards an explicit allow-list of commands to ext4_ioctl() and returns -ENOIOCTLCMD for everything else. Several commands were never added to that list:
EXT4_IOC_MIGRATE
EXT4_IOC_ALLOC_DA_BLKS
EXT4_IOC_SWAP_BOOT
EXT4_IOC_GET_TUNE_SB_PARAM
EXT4_IOC_SET_TUNE_SB_PARAM
As a result, 32-bit userspace running on a 64-bit kernel (for example a 32-bit tune2fs or e4defrag) gets -ENOTTY for these ioctls, even though they work for native 64-bit callers.
None of these commands needs any translation: MIGRATE, ALLOC_DA_BLKS and SWAP_BOOT are _IO() commands that ignore their argument, and struct ext4_tune_sb_params consists only of fixed-size __u8/__u16/ __u32/__u64 members whose layout is identical for 32-bit and 64-bit ABIs (its __u64 members are naturally aligned at offsets 16, 24 and 32, and the structure size is 232 bytes on both). The ioctl numbers therefore encode the same size, and the commands can simply be passed through to ext4_ioctl() with compat_ptr() applied to the argument.
Add the missing commands to the pass-through list and extend the ioctl dispatch KUnit test to check that the compat handler forwards them (when CONFIG_COMPAT is enabled).
--- fs/ext4/ioctl-test.c | 19 +++++++++++++++++++ fs/ext4/ioctl.c | 5 +++++ 2 files changed, 24 insertions(+)
fs/ext4/ioctl-test.c +19 -0
@@ -1452,6 +1452,25 @@ static void test_force_shutdown_and_ioctl_dispatch(struct kunit *test) -EBADF);KUNIT_EXPECT_EQ (test,ext4_ioctl (&filp,EXT4_IOC_SWAP_BOOT ,0 ), -EBADF ); +#ifdef CONFIG_COMPAT +/* +* Architecture-neutral commands must be passed through by +* the compat handler instead of failing with -ENOIOCTLCMD. +*/ +KUNIT_EXPECT_EQ (test, +ext4_compat_ioctl (&filp,EXT4_IOC_SWAP_BOOT ,0 ), + -EBADF ); +KUNIT_EXPECT_EQ (test, +ext4_compat_ioctl (&filp, +EXT4_IOC_GET_TUNE_SB_PARAM , +0 ), + -EFAULT ); +KUNIT_EXPECT_EQ (test, +ext4_compat_ioctl (&filp, +EXT4_IOC_SET_TUNE_SB_PARAM , +0 ), + -EFAULT ); +#endif filp.f_mode =FMODE_READ |FMODE_WRITE ;/* EXT4_IOC_CLEAR_ES_CACHE empties inode extent status tree */
fs/ext4/ioctl.c +5 -0
@@ -2066,6 +2066,11 @@ long ext4_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)case FS_IOC_SETFSLABEL :case EXT4_IOC_GETFSUUID :case EXT4_IOC_SETFSUUID : +case EXT4_IOC_GET_TUNE_SB_PARAM : +case EXT4_IOC_SET_TUNE_SB_PARAM : +case EXT4_IOC_MIGRATE : +case EXT4_IOC_ALLOC_DA_BLKS : +case EXT4_IOC_SWAP_BOOT :break ;default :return -ENOIOCTLCMD ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 8/32 ext4: fix inverted err_report_sec check in ext4_update_super()
In reply to Theodore Ts'oWhen the first error is copied into the on-disk superblock, ext4_update_super() is supposed to start the periodic error reporting timer if it is not already running and err_report_sec is non-zero, as the comment above the code says. However, the check was inverted:
if (!es->s_error_count && !sbi->s_err_report_sec)
With the default err_report_sec of 86400 the timer is therefore never started when a clean file system records its first error, so the "error count since last fsck" messages are not printed until the file system is remounted. Conversely, if the administrator disabled the report by writing 0 to /sys/fs/ext4/<dev>/err_report_sec, the first error arms the timer to fire immediately.
Drop the stray negation. Also read s_err_report_sec only once, with READ_ONCE(), since it can be changed concurrently via sysfs, so that the value tested is the value used to arm the timer.
--- fs/ext4/super-test.c | 12 ++++++++++++ fs/ext4/super.c | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-)
fs/ext4/super-test.c +12 -0
@@ -1308,6 +1308,18 @@ static void test_error_recording_and_update_super(struct kunit *test)KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_checksum),le32_to_cpu (ext4_superblock_csum (es))); +/* First recorded error arms the periodic error report timer */ +KUNIT_EXPECT_TRUE (test,timer_pending (&sbi->s_err_report)); + +/* err_report_sec == 0 disables the timer even for a first error */ +timer_delete_sync (&sbi->s_err_report); + es->s_error_count =0 ; + sbi->s_err_report_sec =0 ; +ext4_save_error_info_test (sb,EIO ,31 ,4096 ,"third_fn" ,333 ); +ext4_update_super_test (sb); +KUNIT_EXPECT_EQ (test,le32_to_cpu (es->s_error_count),1U ); +KUNIT_EXPECT_FALSE (test,timer_pending (&sbi->s_err_report)); +/* Read-only superblock update must not touch s_wtime */ es->s_wtime =cpu_to_le32 (123456U ); saved_wtime = es->s_wtime;
fs/ext4/super.c +4 -2
@@ -6370,6 +6370,7 @@ static void ext4_update_super(struct super_block *sb)struct ext4_sb_info *sbi =EXT4_SB (sb);struct ext4_super_block *es = sbi->s_es;struct buffer_head *sbh = sbi->s_sbh; +unsigned long err_report_sec;lock_buffer (sbh);/*
@@ -6428,9 +6429,10 @@ static void ext4_update_super(struct super_block *sb)* Start the daily error reporting function if it hasn't been * started already and sbi->s_err_report_sec is not zero */ -if (!es->s_error_count && !sbi->s_err_report_sec) + err_report_sec =READ_ONCE (sbi->s_err_report_sec); +if (!es->s_error_count && err_report_sec)mod_timer (&sbi->s_err_report, - jiffies +secs_to_jiffies (sbi->s_err_report_sec)); + jiffies +secs_to_jiffies (err_report_sec));le32_add_cpu (&es->s_error_count, sbi->s_add_error_count); sbi->s_add_error_count =0 ; }
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 9/32 ext4: fix err_report_sec_store() timer and value handling
In reply to Theodore Ts'oerr_report_sec_store() has several problems:
- Writing 0 calls timer_delete_sync() and then jumps past the assignment, so s_err_report_sec keeps its old value. Reading the attribute still returns the old interval, writing the old interval back to re-enable reporting is treated as a no-op, and the periodic report is restarted by the next error even though it was disabled.
- Changing the interval from 0 to a non-zero value calls timer_setup() on s_err_report. The timer is already initialized at mount time, and it may still be pending (e.g. armed by ext4_update_super() or the timer callback racing with the store), in which case re-initializing it corrupts the timer list.
- Any non-zero write arms the timer even if no errors have ever been recorded, so print_daily_error_info() wakes up and re-arms itself forever without having anything to report.
- Concurrent writers are not serialized, so the timer state can end up inconsistent with the stored interval.
Rework the function to always store the new value (with WRITE_ONCE(), since the timer callback and ext4_update_super() read it locklessly), drop the timer_setup() call, delete the timer when the interval is set to 0, and otherwise only (re)arm it when errors have been recorded; ext4_update_super() starts it when the first error is recorded. Serialize writers with a function-local mutex. s_error_notify_mutex cannot be used for this, since ext4_unregister_sysfs() holds it across kobject_del(), which waits for active sysfs store callbacks to finish.
Also read s_err_report_sec once with READ_ONCE() in print_daily_error_info(), so the value tested is the value used to re-arm the timer.
--- fs/ext4/super.c | 7 ++++-- fs/ext4/sysfs-test.c | 55 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/sysfs.c | 21 ++++++++++------- 3 files changed, 73 insertions(+), 10 deletions(-)
fs/ext4/super.c +5 -2
@@ -3798,6 +3798,7 @@ void print_daily_error_info(struct timer_list *t)struct ext4_sb_info *sbi =timer_container_of (sbi, t, s_err_report);struct super_block *sb = sbi->s_sb;struct ext4_super_block *es = sbi->s_es; +unsigned long err_report_sec;if (es->s_error_count)/* fsck newer than v1.41.13 is needed to clean this condition. */
@@ -3834,8 +3835,10 @@ void print_daily_error_info(struct timer_list *t)printk (KERN_CONT "\n" ); } -if (sbi->s_err_report_sec) -mod_timer (&sbi->s_err_report, jiffies +secs_to_jiffies (sbi->s_err_report_sec)); + err_report_sec =READ_ONCE (sbi->s_err_report_sec); +if (err_report_sec) +mod_timer (&sbi->s_err_report, + jiffies +secs_to_jiffies (err_report_sec)); }/* Find next suitable group and run ext4_init_inode_table */
fs/ext4/sysfs-test.c +55 -0
67 lines not on this page · raw message
fs/ext4/sysfs.c +13 -8
@@ -134,6 +134,7 @@ static ssize_t trigger_test_error(struct ext4_sb_info *sbi,static ssize_t err_report_sec_store (struct ext4_sb_info *sbi,const char *buf,size_t count) { +static DEFINE_MUTEX (err_report_sec_mutex);unsigned long t;int ret;
@@ -145,19 +146,23 @@ static ssize_t err_report_sec_store(struct ext4_sb_info *sbi,if (t > (365 *24 *60 *60 ))return -EINVAL ; +mutex_lock (&err_report_sec_mutex);if (sbi->s_err_report_sec == t)/*nothing to do*/ goto out; -else if (!sbi->s_err_report_sec && t) { -timer_setup (&sbi->s_err_report, print_daily_error_info,0 ); - }else if (sbi->s_err_report_sec && !t) { -timer_delete_sync (&sbi->s_err_report); - goto out; - } - sbi->s_err_report_sec = t; -mod_timer (&sbi->s_err_report, jiffies +secs_to_jiffies (sbi->s_err_report_sec)); +WRITE_ONCE (sbi->s_err_report_sec, t); +/* +* The timer is initialized at mount time. Only (re)arm it if errors +* have been recorded; otherwise ext4_update_super() will start it +* when the first error is written to the superblock. +*/ +if (!t) +timer_delete_sync (&sbi->s_err_report); +else if (sbi->s_es->s_error_count) +mod_timer (&sbi->s_err_report, jiffies +secs_to_jiffies (t)); out: +mutex_unlock (&err_report_sec_mutex);return count; }
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 10/32 ext4: fix inode table accounting in count_overhead()
In reply to Theodore Ts'ocount_overhead() computes the per-group overhead of bigalloc file systems which do not have s_overhead_clusters set in the superblock. It only counts a group's inode table if the whole table lies inside the block group being examined, using
b >= first_block && b + sbi->s_itb_per_group <= last_block
where last_block is the (inclusive) last block of the group. This has two problems:
- The end check is off by one: an inode table occupying the last s_itb_per_group blocks of the group is not counted at all.
- With flex_bg, mke2fs and online resize pack the inode tables of a flex group back to back, so an inode table can straddle the boundary between two block groups. Such a table is not entirely contained in either group and so is not counted in either.
In both cases the overhead is underestimated, so statfs(2) reports f_blocks (and thus the file system size and used space shown by df) as larger than it should be.
Fix this by counting the intersection of the inode table with the block group, which handles both cases.
--- fs/ext4/super-test.c | 25 +++++++++++++++++++++++++ fs/ext4/super.c | 15 +++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-)
fs/ext4/super-test.c +25 -0
@@ -1079,6 +1079,31 @@ static void test_overhead_and_statfs(struct kunit *test)/* Cluster 0 holds super+gdb+bbitmap+ibitmap; clusters 1..2 hold itb */ KUNIT_EXPECT_EQ (test,ext4_count_overhead_test (sb,0 , buf),3 ); +/* Inode table ending on the group's last block: clusters 254..255 */ +ext4_inode_table_set (sb, &ctx->gdps[0 ],SUPER_TEST_BLOCKS_PER_GRP -8 ); +memset (buf,0 ,SUPER_TEST_BLK_SIZE ); +KUNIT_EXPECT_EQ (test,ext4_count_overhead_test (sb,0 , buf),3 ); + +/* +* flex_bg style layout where group 1's inode table (2044..2051) +* straddles the boundary between group 1 (1024..2047) and group 2 +* (2048..3071); each group must count its own part of it. +*/ + sbi->s_groups_count =3 ; +ext4_inode_table_set (sb, &ctx->gdps[0 ],4 ); +ext4_block_bitmap_set (sb, &ctx->gdps[1 ],1028 ); +ext4_inode_bitmap_set (sb, &ctx->gdps[1 ],1029 ); +ext4_inode_table_set (sb, &ctx->gdps[1 ],2044 ); +ext4_block_bitmap_set (sb, &ctx->gdps[2 ],2056 ); +ext4_inode_bitmap_set (sb, &ctx->gdps[2 ],2057 ); +ext4_inode_table_set (sb, &ctx->gdps[2 ],2060 ); +/* Group 1: super+gdb, bitmaps, and the head of its inode table */ +memset (buf,0 ,SUPER_TEST_BLK_SIZE ); +KUNIT_EXPECT_EQ (test,ext4_count_overhead_test (sb,1 , buf),3 ); +/* Group 2: tail of group 1's inode table, bitmaps, own inode table */ +memset (buf,0 ,SUPER_TEST_BLK_SIZE ); +KUNIT_EXPECT_EQ (test,ext4_count_overhead_test (sb,2 , buf),4 ); +/* Restore 1:1 geometry and verify ext4_statfs accounting & clamping */ ext4_clear_feature_bigalloc (sb); ctx->es.s_first_data_block =cpu_to_le32 (SUPER_TEST_FIRST_DATA_BLK );
fs/ext4/super.c +13 -2
@@ -4309,12 +4309,23 @@ static int count_overhead(struct super_block *sb, ext4_group_t grp, count++; } b =ext4_inode_table (sb, gdp); -if (b >= first_block && b + sbi->s_itb_per_group <= last_block) -for (j =0 ; j < sbi->s_itb_per_group; j++, b++) { +/* +* The inode table is s_itb_per_group blocks long and, with +* flex_bg, may straddle a block group boundary. Only count +* the part of it which lies inside this block group. +*/ +if (b <= last_block && + b + sbi->s_itb_per_group -1 >= first_block) { +ext4_fsblk_t start =max (b, first_block); +ext4_fsblk_t end =min (b + sbi->s_itb_per_group -1 , + last_block); + +for (b = start; b <= end; b++) {int c =EXT4_B2C (sbi, b - first_block);ext4_set_bit (c, buf); count++; } + }if (i != grp)continue ; s =0 ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 11/32 ext4: handle flex groups straddling s_first_meta_bg in online resize
In reply to Theodore Ts'oWhen a file system without resize_inode is grown online past the last GDT block, ext4_resize_fs() converts it to meta_bg and sets s_first_meta_bg to the current number of GDT blocks. Descriptor blocks below s_first_meta_bg keep the traditional layout (backed up right after each backup superblock in groups < s_first_meta_bg * EXT4_DESC_PER_BLOCK), the later ones use the meta_bg layout. The online resize code does not handle this boundary correctly:
- ext4_flex_group_add() decides meta_bg and padding_blocks once, from the first descriptor block touched by the flex group. When a flex group straddles s_first_meta_bg (possible whenever the flex_bg size exceeds EXT4_DESC_PER_BLOCK, e.g. 1k blocks, 64bit and -G 32), the meta_bg descriptor blocks are passed to update_backups() as traditional ones, so their physical block number is used as an in-group offset. This writes descriptor blocks over free or data blocks (and over backup superblocks) of unrelated groups, or past the end of the file system, while the real meta_bg backups are never written.
- Even with the layout known per block, update_backups() copies a traditional GDT block into every sparse group below s_groups_count, including the newly added groups beyond s_first_meta_bg, which have no traditional GDT backup area. This again overwrites blocks that are free (or meta_bg descriptor backups) in those groups.
- setup_new_flex_group_blocks() skips copying the GDT blocks into a new backup group whenever the meta_bg feature is set. Sparse groups added below s_first_meta_bg still have a traditional backup area of s_first_meta_bg blocks (reserved in the block bitmap), but only the last traditional GDT block gets written there later by update_backups(), leaving stale contents in the backup copies of all earlier GDT blocks.
Add ext4_gdb_is_meta_bg() and use it to decide the layout per descriptor block in ext4_flex_group_add() and per group in setup_new_flex_group_blocks(), and limit the backups of traditional GDT blocks in update_backups() to the groups below s_first_meta_bg.
ext4_add_new_descs() does not need changing: a new descriptor block is always number s_gdb_count, and s_first_meta_bg can never exceed it (it is checked at mount time and set to the current GDT block count during online conversion).
--- fs/ext4/resize-test.c | 80 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/resize.c | 55 ++++++++++++++++++++++------- 2 files changed, 122 insertions(+), 13 deletions(-)
fs/ext4/resize-test.c +80 -0
@@ -1312,6 +1312,85 @@ static void test_resize_fs_across_resize_inode_to_meta_bg(struct kunit *test) 34U * RESIZE_TEST_INODES_PER_GRP); } +static bool resize_blk_matches (struct resize_test_ctx *ctx,ext4_fsblk_t blk, +struct buffer_head *src) +{ +struct buffer_head *bh =resize_lookup_bh (ctx, blk); + +return bh && !memcmp (bh->b_data, src->b_data, src->b_size); +} + +/* +* Test 9: ext4_resize_fs() on a file system without resize_inode, where a +* single 64-group flex batch (groups 20..63) straddles s_first_meta_bg (2). +* GDT blocks 0 and 1 use the traditional layout and must be backed up only +* into sparse groups below 32 (including new groups 25 and 27); GDT blocks +* 2 and 3 use the meta_bg layout and must be backed up into the second and +* last group of their meta group, without scribbling over other blocks. +*/ +static void test_resize_fs_flex_group_straddles_first_meta_bg (struct kunit *test) +{ +struct resize_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *backup_es; +struct buffer_head *gdb[4 ], *bh; +ext4_fsblk_t target_blks; +unsigned int i; + +/* 20 groups: GDT block 0 full, GDT block 1 holds groups 16..19 */ +resize_configure_fs (test,20 ,0 ,6 ,RESIZE_TEST_BLOCKS_PER_GRP ); + target_blks =RESIZE_TEST_FIRST_DATA_BLK + +64ULL *RESIZE_TEST_BLOCKS_PER_GRP ; + +KUNIT_ASSERT_EQ (test,ext4_resize_fs (sb, target_blks),0 ); +KUNIT_ASSERT_EQ (test, sbi->s_groups_count,64U ); +KUNIT_ASSERT_EQ (test, sbi->s_gdb_count,4UL ); +KUNIT_ASSERT_TRUE (test,ext4_has_feature_meta_bg (sb)); +KUNIT_ASSERT_EQ (test,le32_to_cpu (ctx->es->s_first_meta_bg),2U ); + +for (i =0 ; i <ARRAY_SIZE (gdb); i++) + gdb[i] =sbi_array_rcu_deref (sbi, s_group_desc, i); + +/* Traditional GDT backups in the new sparse groups 25 and 27 */ +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,25 ) +1 , gdb[0 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,25 ) +2 , gdb[1 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,27 ) +1 , gdb[0 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,27 ) +2 , gdb[1 ])); + +/* meta_bg descriptor backups in groups 33/47 and 49/63 */ +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,33 ), gdb[2 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,47 ), gdb[2 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,49 ) +1 , gdb[3 ])); +KUNIT_EXPECT_TRUE (test,resize_blk_matches (ctx, +ext4_group_first_block_no (sb,63 ), gdb[3 ])); + +/* Backup superblock in group 49 must not be overwritten */ + bh =resize_lookup_bh (ctx,ext4_group_first_block_no (sb,49 )); +KUNIT_ASSERT_NOT_NULL (test, bh); + backup_es = (struct ext4_super_block *)bh->b_data; +KUNIT_EXPECT_EQ (test,le16_to_cpu (backup_es->s_magic), +EXT4_SUPER_MAGIC ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (backup_es->s_block_group_nr),49U ); + +/* +* Free blocks must not be written: the start of group 35 (meta_bg +* GDT block 2 treated as a traditional offset) and the block after +* group 49's meta_bg backup (traditional GDT block 1 copy). +*/ +KUNIT_EXPECT_NULL (test,resize_lookup_bh (ctx, +ext4_group_first_block_no (sb,35 ))); +KUNIT_EXPECT_NULL (test,resize_lookup_bh (ctx, +ext4_group_first_block_no (sb,49 ) +2 )); +} +static struct kunit_case ext4_resize_test_cases[] = {KUNIT_CASE (test_resize_begin_and_end_guards),KUNIT_CASE (test_list_backups_and_verify_reserved_gdb),
@@ -1321,6 +1400,7 @@ static struct kunit_case ext4_resize_test_cases[] = {KUNIT_CASE (test_group_add_with_resize_inode_and_backup_gdb),KUNIT_CASE (test_convert_meta_bg_validation_and_conversion),KUNIT_CASE (test_resize_fs_across_resize_inode_to_meta_bg), + KUNIT_CASE(test_resize_fs_flex_group_straddles_first_meta_bg), {} };
fs/ext4/resize.c +42 -13
104 lines not on this page · raw message
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 12/32 ext4: reject EXT4_IOC_GROUP_ADD inputs larger than a block group
In reply to Theodore Ts'overify_group_input() checks that the group described by EXT4_IOC_GROUP_ADD lies on the device and that its bitmaps and inode table are inside [start, start + blocks_count), but never checks that blocks_count does not exceed EXT4_BLOCKS_PER_GROUP(). A blocks_count covering several groups is therefore accepted, and the metadata may be placed in the second (or later) group of that range.
ext4_group_add() then hands ext4_flex_group_add() a flex group made of the single on-stack input and bg_flags entries. When setup_new_flex_group_blocks() marks the group tables in the block bitmap, set_flexbg_block_bitmap() derives the group index from the metadata block number and uses it to index flex_gd->bg_flags[] and flex_gd->groups[], reading past those single-entry stack objects and modifying whatever block number it finds there. Even without that, adding a "group" larger than a block group leaves s_blocks_count inconsistent with s_groups_count.
Treat blocks_count > EXT4_BLOCKS_PER_GROUP() as a bad blocks count, before the device read. A zero blocks_count is already rejected by the free_blocks_count < 0 check, and the start + blocks_count addition cannot overflow because ext4_group_add() checks it beforehand.
--- fs/ext4/resize-test.c | 12 ++++++++++++ fs/ext4/resize.c | 3 ++- 2 files changed, 14 insertions(+), 1 deletion(-)
fs/ext4/resize-test.c +12 -0
@@ -944,6 +944,18 @@ static void test_verify_group_input_rejections_and_acceptance(struct kunit *test -EINVAL); input.blocks_count =RESIZE_TEST_BLOCKS_PER_GRP ; +/* +* 4b. blocks_count spanning two groups, with the block bitmap in the +* second one, would make ext4_flex_group_add() index past the +* single-entry flex group arrays. +*/ + input.blocks_count =2 *RESIZE_TEST_BLOCKS_PER_GRP ; + input.block_bitmap = start +RESIZE_TEST_BLOCKS_PER_GRP ; +KUNIT_EXPECT_EQ (test,ext4_verify_group_input_test (sb, &input), + -EINVAL ); + input.block_bitmap = start + overhead; + input.blocks_count =RESIZE_TEST_BLOCKS_PER_GRP ; +/* 5. Last block beyond underlying device -> -EIO */ ctx->device_blocks = start +100 ;KUNIT_EXPECT_EQ (test,ext4_verify_group_input_test (sb, &input), -EIO );
fs/ext4/resize.c +2 -1
@@ -181,7 +181,8 @@ static int verify_group_input(struct super_block *sb,else if (input->reserved_blocks > input->blocks_count /5 )ext4_warning (sb,"Reserved blocks too high (%u)" , input->reserved_blocks); -else if (free_blocks_count <0 ) +else if (input->blocks_count >EXT4_BLOCKS_PER_GROUP (sb) || + free_blocks_count <0 )ext4_warning (sb,"Bad blocks count %u" , input->blocks_count);else if (IS_ERR (bh =ext4_sb_bread (sb, end -1 ,0 ))) {
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 13/32 ext4: propagate ext4_alloc_group_tables() errors from ext4_resize_fs()
In reply to Theodore Ts'oWhen ext4_alloc_group_tables() cannot place the bitmaps and inode tables of the next flex group, ext4_resize_fs() just breaks out of its loop without recording the error. err is still 0 (from its initialization or from the previous successful ext4_flex_group_add()), so:
- EXT4_IOC_RESIZE_FS returns success to resize2fs although the file system was not grown to the requested size, and
- if the first pass was capped by the reserved GDT blocks (n_blocks_count_retry != 0), the "!err && n_blocks_count_retry" test jumps back to retry and carries on as if nothing had happened.
Ignoring the failure was introduced to avoid a BUG_ON() when the last block group was too small for its metadata. That case has since been handled up front by trimming such a final group in ext4_resize_fs() (commit f0a459dec549 ("ext4: fix online resize's handling of a too-small final block group")), so a failure here is a real error that should be reported. Store the return value in err.
--- fs/ext4/resize-test.c | 24 ++++++++++++++++++++++++ fs/ext4/resize.c | 3 ++- 2 files changed, 26 insertions(+), 1 deletion(-)
fs/ext4/resize-test.c +24 -0
@@ -1403,6 +1403,29 @@ static void test_resize_fs_flex_group_straddles_first_meta_bg(struct kunit *test ext4_group_first_block_no(sb, 49) + 2)); } +/* +* Test 10: ext4_resize_fs() must report a failure of ext4_alloc_group_tables() +* instead of returning success without growing the file system. With one +* reserved GDT block, sparse group 3 has 1021 usable blocks, which cannot +* hold two bitmaps plus a 1020-block inode table. +*/ +static void test_resize_fs_alloc_group_tables_enospc (struct kunit *test) +{ +struct resize_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +ext4_fsblk_t o_blks, target_blks; + +resize_configure_fs (test,3 ,1 ,0 ,RESIZE_TEST_BLOCKS_PER_GRP ); + ctx->sbi.s_itb_per_group =1020 ; + o_blks =ext4_blocks_count (ctx->es); + target_blks =RESIZE_TEST_FIRST_DATA_BLK + +5ULL *RESIZE_TEST_BLOCKS_PER_GRP ; + +KUNIT_EXPECT_EQ (test,ext4_resize_fs (sb, target_blks), -ENOSPC ); +KUNIT_EXPECT_EQ (test, ctx->sbi.s_groups_count,3U ); +KUNIT_EXPECT_EQ (test,ext4_blocks_count (ctx->es), o_blks); +} +static struct kunit_case ext4_resize_test_cases[] = {KUNIT_CASE (test_resize_begin_and_end_guards),KUNIT_CASE (test_list_backups_and_verify_reserved_gdb),
@@ -1413,6 +1436,7 @@ static struct kunit_case ext4_resize_test_cases[] = {KUNIT_CASE (test_convert_meta_bg_validation_and_conversion),KUNIT_CASE (test_resize_fs_across_resize_inode_to_meta_bg),KUNIT_CASE (test_resize_fs_flex_group_straddles_first_meta_bg), + KUNIT_CASE(test_resize_fs_alloc_group_tables_enospc), {} };
fs/ext4/resize.c +2 -1
@@ -2192,7 +2192,8 @@ int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count) ext4_blocks_count(es)); last_update_time = jiffies; } -if (ext4_alloc_group_tables (sb, flex_gd, flexbg_size) !=0 ) + err =ext4_alloc_group_tables (sb, flex_gd, flexbg_size); +if (err)break ; err =ext4_flex_group_add (sb, resize_inode, flex_gd);if (unlikely (err))
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 14/32 ext4: reject online shrink before probing the device size
In reply to Theodore Ts'oext4_resize_fs() reads block n_blocks_count - 1 to check that the device is large enough before it checks whether the request would shrink the file system. EXT4_IOC_RESIZE_FS passes the user supplied 64-bit value straight through, so n_blocks_count == 0 underflows to reading block ~0ULL. That read fails (the block layer also logs an "out-of-range block" error), and the ioctl returns -ENOSPC with a misleading "can't read last block" warning instead of the -EINVAL every other shrink request gets.
Reject requests smaller than the current block count before probing the device. Since a mounted file system never has zero blocks, this also guarantees n_blocks_count - 1 cannot underflow. The check after the retry label is kept, as the retry path can lower n_blocks_count.
--- fs/ext4/resize-test.c | 2 ++ fs/ext4/resize.c | 9 +++++++++ 2 files changed, 11 insertions(+)
fs/ext4/resize-test.c +2 -0
@@ -1300,6 +1300,8 @@ static void test_resize_fs_across_resize_inode_to_meta_bg(struct kunit *test) -ENOSPC);KUNIT_EXPECT_EQ (test,ext4_resize_fs (sb, o_blks -100 ), -EINVAL );KUNIT_EXPECT_EQ (test,ext4_resize_fs (sb, o_blks),0 ); +/* n_blocks_count == 0 is a shrink, not a read of block ~0ULL */ +KUNIT_EXPECT_EQ (test,ext4_resize_fs (sb,0 ), -EINVAL );/* 2. Simultaneous resize_inode + meta_bg -> -EINVAL */ ext4_set_feature_meta_bg (sb);
fs/ext4/resize.c +9 -0
@@ -2045,6 +2045,15 @@ int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count)int meta_bg;unsigned int flexbg_size =ext4_flex_bg_size (sbi); +/* +* Reject shrinking before probing the device; this also keeps +* n_blocks_count - 1 below from underflowing for n_blocks_count == 0. +*/ +if (n_blocks_count <ext4_blocks_count (es)) { +ext4_warning (sb,"can't shrink FS - resize aborted" ); +return -EINVAL ; + } +/* See if the device is actually as big as what was requested */ bh =ext4_sb_bread (sb, n_blocks_count -1 ,0 );if (IS_ERR (bh)) {
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 15/32 ext4: fix EOF clamping of the range in mext_check_adjust_range()
In reply to Theodore Ts'omext_check_adjust_range() clamps the requested EXT4_IOC_MOVE_EXT range to the end of the original and donor files with:
else if (orig_eof < orig_start + *len - 1) *len = orig_eof - orig_start;
orig_eof and donor_eof are exclusive (the first logical block past i_size), so the range [start, start + len) runs past EOF as soon as start + len > eof. The extra "- 1" has two consequences:
- A range that ends exactly one block past EOF is not clamped, so e.g. orig_start = 0, len = 2 on a one-block file walks and swaps a block beyond i_size.
- A zero length makes the unsigned "start + len - 1" wrap to ULLONG_MAX when start is 0. The comparison is then always true and len is "clamped" to the full file size, so the later !*len check never fires and a request to move zero blocks moves every block of the file instead of failing with -EINVAL.
Compare against start + len instead. With that, a zero length is left untouched by the clamping (eof > start in that branch) and is rejected by the existing !*len check, so no separate check is needed. The sums cannot overflow because start and len were already bounded by EXT_MAX_BLOCKS above.
Extend test_mext_check_adjust_range to cover a zero length and ranges that end exactly one block past EOF.
--- fs/ext4/move_extent-test.c | 21 +++++++++++++++++++++ fs/ext4/move_extent.c | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-)
fs/ext4/move_extent-test.c +21 -0
@@ -805,6 +805,27 @@ static void test_mext_check_adjust_range(struct kunit *test) ret =ext4_mext_check_adjust_range_test (orig, donor,4 ,4 , &len);KUNIT_EXPECT_EQ (test, ret, -EINVAL );KUNIT_EXPECT_EQ (test, len,0ULL ); + +/* A zero length must be rejected, not wrapped to the whole file */ + len =0 ; + ret =ext4_mext_check_adjust_range_test (orig, donor,0 ,0 , &len); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); +KUNIT_EXPECT_EQ (test, len,0ULL ); + +/* A range ending exactly one block past EOF must be clamped */ +i_size_write (orig,MEXT_TEST_BLK_SIZE );/* orig_eof = 1 */ +i_size_write (donor,MEXT_TEST_BLK_SIZE );/* donor_eof = 1 */ + len =2 ; + ret =ext4_mext_check_adjust_range_test (orig, donor,0 ,0 , &len); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, len,1ULL ); + +i_size_write (orig,4 *MEXT_TEST_BLK_SIZE );/* orig_eof = 4 */ +i_size_write (donor,8 *MEXT_TEST_BLK_SIZE );/* donor_eof = 8 */ + len =4 ; + ret =ext4_mext_check_adjust_range_test (orig, donor,1 ,1 , &len); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, len,3ULL ); }static void test_move_extents_holes_and_unwritten (struct kunit *test)
fs/ext4/move_extent.c +2 -2
@@ -556,11 +556,11 @@ static int mext_check_adjust_range(struct inode *orig_inode, donor_eof =EXT4_B_TO_LBLK (donor_inode,i_size_read (donor_inode));if (orig_eof <= orig_start) *len =0 ; -else if (orig_eof < orig_start + *len -1 ) +else if (orig_eof < orig_start + *len) *len = orig_eof - orig_start;if (donor_eof <= donor_start) *len =0 ; -else if (donor_eof < donor_start + *len -1 ) +else if (donor_eof < donor_start + *len) *len = donor_eof - donor_start;if (!*len) { ext4_debug("ext4 move extent: len should not be 0 [ino:orig %llu, donor %llu]\n",
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 16/32 ext4: bound the MMP update and check intervals
In reply to Theodore Ts'oNeither kmmpd() nor ext4_multi_mount_protect() validate the s_mmp_update_interval value from the superblock or the mmp_check_interval value from the MMP block:
- With s_mmp_update_interval == 0, the "diff < mmp_update_interval * HZ" test in kmmpd() is never true, so kmmpd never sleeps. It rewrites the MMP block with REQ_SYNC | REQ_META | REQ_PRIO writes in a tight loop until the filesystem is unmounted. e2fsprogs treats a zero interval as "use the default" (5 seconds), so such a value is not even necessarily the result of corruption.
- Both fields are 16 bits wide and only have a lower bound applied at mount time. A value of 65535 in either of them makes ext4_multi_mount_protect() sleep min(2 * 65535 + 1, 65535 + 60) seconds, i.e. more than 18 hours, up to twice, before mount(2) completes. kmmpd() itself already caps the check interval it advertises to EXT4_MMP_MAX_CHECK_INTERVAL once it is running, and e2fsprogs refuses to set an update interval larger than 300 seconds.
Add a helper that returns s_mmp_update_interval with zero mapped to the e2fsprogs default and larger values capped to the e2fsprogs maximum, and use it in both kmmpd() and ext4_multi_mount_protect(). Also cap the check interval used at mount time, and the initial one advertised by kmmpd(), to EXT4_MMP_MAX_CHECK_INTERVAL, matching what kmmpd() already does after its first update. Since kmmpd now updates the MMP block at least every EXT4_MMP_MAX_UPDATE_INTERVAL seconds, the resulting maximum mount wait of 360 seconds is still long enough to notice another node that is actively using the filesystem.
Add KUnit tests covering both the mount-time wait and, by running the real kmmpd() in a thread with the I/O and sleep helpers stubbed out, the kmmpd() update cadence.
--- fs/ext4/ext4.h | 8 +++ fs/ext4/mmp-test.c | 170 +++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/mmp.c | 31 +++++++-- 3 files changed, 205 insertions(+), 4 deletions(-)
fs/ext4/ext4.h +8 -0
@@ -2890,6 +2890,13 @@ struct mmpd_data {*/ #define EXT4_MMP_MAX_CHECK_INTERVAL 300UL +/* +* Default and maximum interval between MMP block updates in seconds, as +* used by e2fsprogs for s_mmp_update_interval. +*/ +#define EXT4_MMP_UPDATE_INTERVAL 5UL +#define EXT4_MMP_MAX_UPDATE_INTERVAL 300UL +/* * Function prototypes */
@@ -4311,6 +4318,7 @@ extern int ext4_read_mmp_block_test(struct super_block *sb, ext4_fsblk_t mmp_block);extern int ext4_write_mmp_block_test (struct super_block *sb,struct buffer_head *bh); +extern int ext4_kmmpd_test (void *data);#endif /* verity.c */
fs/ext4/mmp-test.c +170 -0
224 lines not on this page · raw message
fs/ext4/mmp.c +27 -4
@@ -151,6 +151,20 @@ void __dump_mmp_msg(struct super_block *sb, struct mmp_struct *mmp, (int)sizeof(mmp->mmp_bdevname), mmp->mmp_bdevname); } +/* +* Return s_mmp_update_interval, using the default if it is zero and capping +* it to the maximum that e2fsprogs allows, so that a bogus value can neither +* make kmmpd rewrite the MMP block in a busy loop nor stall mount for hours. +*/ +static unsigned int ext4_mmp_update_interval (struct ext4_super_block *es) +{ +unsigned int interval =le16_to_cpu (es->s_mmp_update_interval); + +if (!interval) +return EXT4_MMP_UPDATE_INTERVAL ; + return min_t(unsigned int, interval, EXT4_MMP_MAX_UPDATE_INTERVAL); +} +/* * kmmpd will update the MMP sequence every s_mmp_update_interval seconds */
@@ -163,7 +177,7 @@ static int kmmpd(void *data)ext4_fsblk_t mmp_block;u32 seq =0 ;unsigned long failed_writes =0 ; -int mmp_update_interval =le16_to_cpu (es->s_mmp_update_interval); +unsigned int mmp_update_interval =ext4_mmp_update_interval (es);unsigned mmp_check_interval;unsigned long last_update_time;unsigned long diff;
@@ -176,8 +190,9 @@ static int kmmpd(void *data)* Start with the higher mmp_check_interval and reduce it if * the MMP block is being updated on time. */ - mmp_check_interval =max (EXT4_MMP_CHECK_MULT * mmp_update_interval, -EXT4_MMP_MIN_CHECK_INTERVAL ); + mmp_check_interval =clamp (EXT4_MMP_CHECK_MULT * mmp_update_interval, +EXT4_MMP_MIN_CHECK_INTERVAL , +EXT4_MMP_MAX_CHECK_INTERVAL ); mmp->mmp_check_interval =cpu_to_le16 (mmp_check_interval); memcpy(mmp->mmp_nodename, init_utsname()->nodename,
@@ -314,7 +329,7 @@ int ext4_multi_mount_protect(struct super_block *sb,struct buffer_head *bh =NULL ;struct mmp_struct *mmp =NULL ;u32 seq; -unsigned int mmp_check_interval =le16_to_cpu (es->s_mmp_update_interval); +unsigned int mmp_check_interval =ext4_mmp_update_interval (es);unsigned int wait_time =0 ;int retval;
@@ -340,6 +355,8 @@ int ext4_multi_mount_protect(struct super_block *sb,*/ if (le16_to_cpu (mmp->mmp_check_interval) > mmp_check_interval) mmp_check_interval =le16_to_cpu (mmp->mmp_check_interval); +if (mmp_check_interval >EXT4_MMP_MAX_CHECK_INTERVAL ) + mmp_check_interval =EXT4_MMP_MAX_CHECK_INTERVAL ; seq =le32_to_cpu (mmp->mmp_seq);if (seq ==EXT4_MMP_SEQ_CLEAN )
@@ -463,4 +480,10 @@ int ext4_write_mmp_block_test(struct super_block *sb, struct buffer_head *bh) return write_mmp_block(sb, bh); }EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_write_mmp_block_test); + +int ext4_kmmpd_test (void *data) +{ +return kmmpd (data); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_kmmpd_test);#endif
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 17/32 ext4: fix MMP claim of a cleanly unmounted filesystem
In reply to Theodore Ts'oext4_multi_mount_protect() has several problems:
- wait_time is initialised to 0 and only computed after the EXT4_MMP_SEQ_CLEAN check jumps to "skip". For a cleanly unmounted filesystem the wait between writing our new sequence number and re-reading it to verify the claim is therefore zero. If two nodes mount a clean shared device at about the same time, both read EXT4_MMP_SEQ_CLEAN, both write their own sequence and both immediately read back their own value, so both mount the filesystem read-write. kmmpd only re-reads the MMP block when its own write was delayed, so this is not caught later either. e2fsprogs waits after claiming a clean MMP block for exactly this reason.
- The comment above EXT4_MMP_SEQ_MAX states that any unknown value above EXT4_MMP_SEQ_MAX must be treated as unsafe, like EXT4_MMP_SEQ_FSCK, and e2fsprogs refuses such values. The kernel treats them as an ordinary stale sequence number instead and takes over the filesystem.
- The claim is written with the node name, device name and time of the previous owner, so a racing mounter that now notices the claim reports stale information about who is using the device.
- If starting kmmpd fails, s_mmp_bh is left pointing to the buffer head that is released on the error path, and our sequence number is left on disk, so the next mount attempt has to wait for it to go stale.
Compute wait_time before checking for EXT4_MMP_SEQ_CLEAN so that the post-claim wait is always done, reject unknown sequence values with -EBUSY like EXT4_MMP_SEQ_FSCK, fill in mmp_time, mmp_nodename and mmp_bdevname before writing the claim, and on kmmpd creation failure clear s_mmp_bh and mark the MMP block clean again, as kmmpd does on unmount.
Note that this makes mounting a clean MMP-enabled filesystem wait for wait_time (11 seconds with the default interval), which is the documented behaviour of MMP and matches e2fsprogs.
Extend the KUnit tests to check the post-claim wait for a clean MMP block, detection of a racing mounter, rejection of unknown sequence values, the contents of the claim and the kmmpd failure cleanup.
--- fs/ext4/mmp-test.c | 52 ++++++++++++++++++++++++++++++++++++++++++++-- fs/ext4/mmp.c | 36 +++++++++++++++++++++++++------- 2 files changed, 78 insertions(+), 10 deletions(-)
fs/ext4/mmp-test.c +50 -2
@@ -18,6 +18,7 @@#include <linux/slab.h> #include <linux/string.h> #include <linux/timer.h> +#include <linux/utsname.h> #include <linux/workqueue.h> #include "ext4.h"
@@ -578,7 +579,9 @@ static void test_mmp_clean_and_fsck_sequences(struct kunit *test)/* * EXT4_MMP_SEQ_CLEAN skips pre-claim wait, writes a valid sequence -* <= EXT4_MMP_SEQ_MAX, starts kmmpd, and ext4_stop_mmpd() cleans up. +* <= EXT4_MMP_SEQ_MAX along with our node and device names, still +* waits the full wait_time (2 * 5 + 1 = 11s) before verifying the +* claim, starts kmmpd, and ext4_stop_mmpd() cleans up. */ mmp_init_disk_block (ctx,EXT4_MMP_SEQ_CLEAN ,5 );mmp_reset_counters (ctx);
@@ -587,9 +590,14 @@ static void test_mmp_clean_and_fsck_sequences(struct kunit *test) ret =ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK );KUNIT_ASSERT_EQ (test, ret,0 );KUNIT_EXPECT_EQ (test, ctx->wait_calls,1U ); +KUNIT_EXPECT_EQ (test, ctx->wait_timeouts[0 ], (long )(11 *HZ ));KUNIT_EXPECT_EQ (test, ctx->write_calls,1U );KUNIT_EXPECT_EQ (test, ctx->run_thread_calls,1U );KUNIT_EXPECT_LE (test,le32_to_cpu (disk_mmp->mmp_seq),EXT4_MMP_SEQ_MAX ); +KUNIT_EXPECT_EQ (test,memcmp (disk_mmp->mmp_nodename, +init_utsname ()->nodename, +sizeof (disk_mmp->mmp_nodename)),0 ); +KUNIT_EXPECT_STREQ (test, disk_mmp->mmp_bdevname,"mmp_bdev" );KUNIT_EXPECT_NOT_NULL (test, ctx->sbi.s_mmp_tsk);KUNIT_EXPECT_PTR_EQ (test, ctx->sbi.s_mmp_bh, &ctx->mmp_bh); KUNIT_EXPECT_STREQ(test,
@@ -600,6 +608,38 @@ static void test_mmp_clean_and_fsck_sequences(struct kunit *test)KUNIT_EXPECT_NULL (test, ctx->sbi.s_mmp_tsk);KUNIT_EXPECT_EQ (test,atomic_read (&ctx->mmp_bh.b_count), base_ref); ctx->sbi.s_mmp_bh =NULL ; + +/* A racing mounter claiming a clean MMP block is detected */ +mmp_init_disk_block (ctx,EXT4_MMP_SEQ_CLEAN ,5 ); +mmp_reset_counters (ctx); + ctx->mutate_seq_on_wait_call =1 ; + ctx->mutated_seq =0x1234U ; + + ret =ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK ); +KUNIT_EXPECT_EQ (test, ret, -EBUSY ); +KUNIT_EXPECT_EQ (test, ctx->wait_calls,1U ); +KUNIT_EXPECT_EQ (test, ctx->wait_timeouts[0 ], (long )(11 *HZ )); +KUNIT_EXPECT_EQ (test, ctx->run_thread_calls,0U ); + +/* +* Unknown sequence values above EXT4_MMP_SEQ_MAX are reserved and +* must be treated like EXT4_MMP_SEQ_FSCK, not as a stale sequence. +*/ +mmp_init_disk_block (ctx,EXT4_MMP_SEQ_FSCK +1 ,5 ); +mmp_reset_counters (ctx); + ret =ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK ); +KUNIT_EXPECT_EQ (test, ret, -EBUSY ); +KUNIT_EXPECT_EQ (test, ctx->wait_calls,0U ); +KUNIT_EXPECT_EQ (test, ctx->write_calls,0U ); + +/* EXT4_MMP_SEQ_MAX itself is a valid (stale) sequence */ +mmp_init_disk_block (ctx,EXT4_MMP_SEQ_MAX ,5 ); +mmp_reset_counters (ctx); + ret =ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ctx->wait_calls,2U ); +ext4_stop_mmpd (&ctx->sbi); + ctx->sbi.s_mmp_bh =NULL ; }static void test_mmp_active_seq_conflict_and_claim (struct kunit *test)
@@ -660,6 +700,7 @@ static void test_mmp_active_seq_conflict_and_claim(struct kunit *test)static void test_mmp_interrupted_waits_and_kthread_failure (struct kunit *test) {struct mmp_test_ctx *ctx =mmp_setup_ctx (test); +struct mmp_struct *disk_mmp = (struct mmp_struct *)ctx->disk_buf;/* Signal interruption on pre-claim wait returns -ETIMEDOUT */ mmp_init_disk_block (ctx,77 ,5 );
@@ -679,7 +720,10 @@ static void test_mmp_interrupted_waits_and_kthread_failure(struct kunit *test)ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK ), -ETIMEDOUT); -/* kthread creation failure returns -ENOMEM and leaves s_mmp_tsk NULL */ +/* +* kthread creation failure returns -ENOMEM, leaves s_mmp_tsk and +* s_mmp_bh NULL, and marks the MMP block clean again. +*/ mmp_init_disk_block (ctx,EXT4_MMP_SEQ_CLEAN ,5 );mmp_reset_counters (ctx); ctx->run_thread_err = -ENOMEM ;
@@ -687,6 +731,10 @@ static void test_mmp_interrupted_waits_and_kthread_failure(struct kunit *test)ext4_multi_mount_protect (ctx->sb,MMP_TEST_VALID_BLK ), -ENOMEM);KUNIT_EXPECT_NULL (test, ctx->sbi.s_mmp_tsk); +KUNIT_EXPECT_NULL (test, ctx->sbi.s_mmp_bh); +KUNIT_EXPECT_EQ (test, ctx->write_calls,2U ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (disk_mmp->mmp_seq), +EXT4_MMP_SEQ_CLEAN ); ctx->sbi.s_mmp_bh =NULL ; }
fs/ext4/mmp.c +28 -8
@@ -330,7 +330,7 @@ int ext4_multi_mount_protect(struct super_block *sb,struct mmp_struct *mmp =NULL ;u32 seq;unsigned int mmp_check_interval =ext4_mmp_update_interval (es); -unsigned int wait_time =0 ; +unsigned int wait_time;int retval; if (mmp_block < le32_to_cpu(es->s_first_data_block) ||
@@ -358,6 +358,14 @@ int ext4_multi_mount_protect(struct super_block *sb,if (mmp_check_interval >EXT4_MMP_MAX_CHECK_INTERVAL ) mmp_check_interval =EXT4_MMP_MAX_CHECK_INTERVAL ; +/* +* Even if the MMP block was released cleanly, another node may be +* claiming it at the same time, so the wait after writing our own +* sequence number below is needed in all cases. +*/ + wait_time =min (mmp_check_interval *2 +1 , + mmp_check_interval +60 ); + seq =le32_to_cpu (mmp->mmp_seq);if (seq ==EXT4_MMP_SEQ_CLEAN ) goto skip;
@@ -368,8 +376,12 @@ int ext4_multi_mount_protect(struct super_block *sb, goto failed; } - wait_time =min (mmp_check_interval *2 +1 , - mmp_check_interval +60 ); +if (seq >EXT4_MMP_SEQ_MAX ) { +dump_mmp_msg (sb, mmp, +"Unknown MMP sequence, filesystem may be in use" ); + retval = -EBUSY ; + goto failed; + }/* Print MMP interval if more than 20 secs. */ if (wait_time >EXT4_MMP_MIN_CHECK_INTERVAL *4 )
@@ -395,10 +407,17 @@ int ext4_multi_mount_protect(struct super_block *sb, skip:/* -* write a new random sequence number. +* write a new random sequence number, and identify ourselves to +* anybody who finds the MMP block in use while we wait. */ seq =mmp_new_seq (); mmp->mmp_seq =cpu_to_le32 (seq); + mmp->mmp_time =cpu_to_le64 (ktime_get_real_seconds ()); +memcpy (mmp->mmp_nodename,init_utsname ()->nodename, +sizeof (mmp->mmp_nodename)); +BUILD_BUG_ON (sizeof (mmp->mmp_bdevname) <BDEVNAME_SIZE ); +snprintf (mmp->mmp_bdevname,sizeof (mmp->mmp_bdevname), +"%pg" , bh->b_bdev);/* * On mount / remount we are protected against fs freezing (by s_umount
@@ -430,10 +449,6 @@ int ext4_multi_mount_protect(struct super_block *sb,EXT4_SB (sb)->s_mmp_bh = bh; -BUILD_BUG_ON (sizeof (mmp->mmp_bdevname) <BDEVNAME_SIZE ); -snprintf (mmp->mmp_bdevname,sizeof (mmp->mmp_bdevname), -"%pg" , bh->b_bdev); -/* * Start a kernel thread to update the MMP block periodically. */
@@ -441,8 +456,13 @@ int ext4_multi_mount_protect(struct super_block *sb, (int)sizeof(mmp->mmp_bdevname));if (IS_ERR (EXT4_SB (sb)->s_mmp_tsk)) {EXT4_SB (sb)->s_mmp_tsk =NULL ; +EXT4_SB (sb)->s_mmp_bh =NULL ;ext4_warning (sb,"Unable to create kmmpd thread for %s." , sb->s_id); +/* Release the MMP block again, as kmmpd does on unmount. */ + mmp->mmp_seq =cpu_to_le32 (EXT4_MMP_SEQ_CLEAN ); + mmp->mmp_time =cpu_to_le64 (ktime_get_real_seconds ()); +write_mmp_block_thawed (sb, bh); retval = -ENOMEM ; goto failed; }
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 18/32 ext4: fix device comparison overflow in ext4_getfsmap_dev_compare()
In reply to Theodore Ts'oext4_getfsmap_dev_compare() returns the difference of two u32 encoded device numbers as an int. new_encode_dev() places bits 8-19 of the minor number in bits 20-31, so any device with a minor number of 0x80000 or higher encodes to a value with bit 31 set, and the difference of such a value and a smaller one does not fit in an int. The comparison then has the wrong sign.
With an external journal on a low-numbered device and the filesystem on such a high-minor device, sort() orders the handlers as [data device, log device]. ext4_getfsmap() relies on the handlers being sorted in ascending device order: a query covering only the log device hits "fmh_keys[1].fmr_device < handlers[i].gfd_dev" on the data device first and breaks out of the loop, so no mappings are returned for the journal device, and a full query reports the devices in descending order, which breaks pagination with the last returned record as the next low key.
Use cmp_int() so that the comparison cannot overflow.
Add a KUnit test with a high-minor data device and an external journal device.
--- fs/ext4/fsmap-test.c | 56 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/fsmap.c | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-)
fs/ext4/fsmap-test.c +56 -0
@@ -774,6 +774,61 @@ static void test_getfsmap_external_logdev_and_multi_device(struct kunit *test)KUNIT_EXPECT_EQ (test, head.fmh_entries,0U ); } +/* +* A data device whose encoded dev_t has bit 31 set (minor >= 0x80000) must +* still sort after a lower-numbered external journal device, so that devices +* are reported in ascending order and log-device-only queries work. +*/ +static void test_getfsmap_high_encoded_datadev_order (struct kunit *test) +{ +struct fsmap_test_ctx *ctx; +struct ext4_fsmap_head head; +struct fsmap_rec_sink *sink; +u32 datadev, logdev =new_encode_dev (FSMAP_TEST_LOGDEV ); +int err; + + sink =kunit_kzalloc (test,sizeof (*sink),GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, sink); + ctx =fsmap_create_ctx (test,12 ,0 ,1 ,128 ); +fsmap_set_group_tables (ctx,0 ,2 ,3 ,4 ); +fsmap_mark_clusters_used (ctx,0 ,0 ,12 ); + + ctx->data_bdev.bdev.bd_dev =MKDEV (259 ,0x80000 ); + datadev =new_encode_dev (ctx->data_bdev.bdev.bd_dev); +KUNIT_ASSERT_GE (test, datadev,0x80000000U ); +KUNIT_ASSERT_LT (test, logdev, datadev); + + ctx->mock_journal.j_blk_offset =16 ; + ctx->mock_journal.j_total_len =64 ; + ctx->sbi.s_journal = &ctx->mock_journal; + ctx->sbi.s_journal_bdev_file = &ctx->log_bdev_file; + +/* Multi-device query reports logdev (2 recs) before datadev (6) */ +fsmap_init_full_range_head (&head,FSMAP_TEST_MAX_RECS ); + err =ext4_getfsmap (ctx->sb, &head, fsmap_collect_cb, sink); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_ASSERT_EQ (test, head.fmh_entries,8U ); +fsmap_expect_rec (test, &sink->recs[0 ], logdev,0 ,16 , +EXT4_FMR_OWN_UNKNOWN ); +fsmap_expect_rec (test, &sink->recs[1 ], logdev,16 ,64 , +EXT4_FMR_OWN_LOG ); +KUNIT_EXPECT_EQ (test, (u32 )sink->recs[2 ].fmr_device, datadev); +KUNIT_EXPECT_EQ (test, (u32 )sink->recs[7 ].fmr_device, datadev); + +/* Targeted query against only logdev */ +memset (sink,0 ,sizeof (*sink)); +fsmap_init_full_range_head (&head,FSMAP_TEST_MAX_RECS ); + head.fmh_keys[0 ].fmr_device = logdev; + head.fmh_keys[1 ].fmr_device = logdev; + err =ext4_getfsmap (ctx->sb, &head, fsmap_collect_cb, sink); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_ASSERT_EQ (test, head.fmh_entries,2U ); +fsmap_expect_rec (test, &sink->recs[0 ], logdev,0 ,16 , +EXT4_FMR_OWN_UNKNOWN ); +fsmap_expect_rec (test, &sink->recs[1 ], logdev,16 ,64 , +EXT4_FMR_OWN_LOG ); +} +static struct kunit_case fsmap_test_cases[] = {KUNIT_CASE (test_fsmap_unit_conversions),KUNIT_CASE (test_getfsmap_invalid_flags_devices_and_keys),
@@ -782,6 +837,7 @@ static struct kunit_case fsmap_test_cases[] = {KUNIT_CASE (test_getfsmap_1k_bofs_bigalloc_and_meta_bg),KUNIT_CASE (test_getfsmap_count_only_pagination_and_abort),KUNIT_CASE (test_getfsmap_external_logdev_and_multi_device), + KUNIT_CASE(test_getfsmap_high_encoded_datadev_order), {} };
fs/ext4/fsmap.c +1 -1
@@ -69,7 +69,7 @@ static int ext4_getfsmap_dev_compare(const void *p1, const void *p2)const struct ext4_getfsmap_dev *d1 = p1;const struct ext4_getfsmap_dev *d2 = p2; -return d1->gfd_dev - d2->gfd_dev; +return cmp_int (d1->gfd_dev, d2->gfd_dev); }/* Compare a record against our starting point */
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 19/32 ext4: don't allocate over indirect branches that failed to load
In reply to Theodore Ts'oext4_get_branch() stops walking an indirect block chain either because it found an unallocated pointer (*err == 0) or because it failed to load an indirect block whose pointer is non-zero: -EFSCORRUPTED when the pointer is beyond the end of the filesystem, -ENOMEM when ext4_sb_getblk() fails, and -EIO when the read fails or when ext4_check_indirect_blockref() rejects the block contents.
ext4_ind_map_blocks() only checks for -EIO before starting allocation. For -EFSCORRUPTED and -ENOMEM it treats the still populated slot as a hole, allocates a new branch and has ext4_splice_branch() store it over the existing pointer. Every block reachable from the old indirect block is then silently dropped from the file and leaked, and the corruption is never reported to the caller.
Bail out on any error from ext4_get_branch() before using the partial chain on both the lookup and the allocation paths, and return -EFSCORRUPTED rather than -EIO when an indirect block fails ext4_check_indirect_blockref(), so that it is reported consistently with other indirect block corruption.
Extend the indirect KUnit suite to cover allocation through a branch that hits -ENOMEM or -EFSCORRUPTED, and the buffer_head reference count on the bigalloc rejection path, whose leak was fixed by commit 79dd565874b3 ("ext4: fix buffer_head leak in ext4_ind_map_blocks() error path").
--- fs/ext4/indirect-test.c | 90 ++++++++++++++++++++++++++++++++++++++++- fs/ext4/indirect.c | 17 ++++++-- 2 files changed, 101 insertions(+), 6 deletions(-)
fs/ext4/indirect-test.c +88 -2
@@ -80,6 +80,7 @@ struct ind_test_ctx {unsigned int fail_alloc_on_call;int fail_alloc_err;int read_bh_err; +ext4_fsblk_t getblk_fail_blk;ext4_fsblk_t freed_blks[IND_TEST_MAX_FREED_REC ];unsigned int freed_cnt;bool rwsem_inited;
@@ -231,6 +232,9 @@ static struct buffer_head *ind_sb_getblk_stub(struct super_block *sb, ctx = test->priv;if (!ctx || sb != ctx->sb)return NULL ; +/* Simulate sb_getblk() failure for one specific block */ +if (ctx->getblk_fail_blk && block == ctx->getblk_fail_blk) +return NULL ;return ind_get_or_create_bh (ctx, block); }
@@ -967,14 +971,15 @@ static void test_ind_map_blocks_errors_and_alloc_branch_unwind(struct kunit *tes/* * 5. Non-uptodate IND block containing invalid blockref (block 1 == -* s_first_data_block) fails ext4_check_indirect_blockref() -> -EIO. +* s_first_data_block) fails ext4_check_indirect_blockref() -> +* -EFSCORRUPTED. */ ((__le32 *)ind_bh->b_data)[0 ] =cpu_to_le32 (IND_TEST_FIRST_DATA_BLK );clear_buffer_uptodate (ind_bh);down_read (&EXT4_I (inode)->i_data_sem); ret =ext4_ind_map_blocks (NULL , inode, &map,0 );up_read (&EXT4_I (inode)->i_data_sem); -KUNIT_EXPECT_EQ (test, ret, -EIO ); +KUNIT_EXPECT_EQ (test, ret, -EFSCORRUPTED );brelse (ind_bh);EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =0 ;
@@ -1270,6 +1275,86 @@ static void test_ind_free_corrupt_block_numbers(struct kunit *test)iput (inode); } +/* +* Test 8: ext4_ind_map_blocks(EXT4_GET_BLOCKS_CREATE) must fail, rather than +* treat the branch as a hole and splice a new one over the existing pointer, +* when ext4_get_branch() fails with -ENOMEM or -EFSCORRUPTED, and must not +* leak indirect buffer_heads when rejecting allocation on bigalloc. +*/ +static void test_ind_map_blocks_create_branch_errors (struct kunit *test) +{ +struct ind_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct inode *inode =ind_make_test_inode (test,19 ); +struct ext4_map_blocks map; +struct buffer_head *ind_bh; +ext4_fsblk_t bad_blk =IND_TEST_TOTAL_BLKS +10 ; +handle_t *handle; +int count, ret; + + handle =ext4_journal_start (inode,EXT4_HT_MAP_BLOCKS ,8 ); +KUNIT_ASSERT_FALSE (test,IS_ERR (handle)); + +/* Populated IND block 300 mapping IND_BASE -> data block 400 */ +ind_blk_ptrs (test,300 )[0 ] =cpu_to_le32 (400 ); +EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =cpu_to_le32 (300 ); + +/* 1. sb_getblk() of the IND block fails -> -ENOMEM, IND preserved */ + ctx->getblk_fail_blk =300 ; + ctx->alloc_calls =0 ; +memset (&map,0 ,sizeof (map)); + map.m_lblk =IND_TEST_IND_BASE +1 ; + map.m_len =1 ; +down_write (&EXT4_I (inode)->i_data_sem); + ret =ext4_ind_map_blocks (handle, inode, &map,EXT4_GET_BLOCKS_CREATE ); +up_write (&EXT4_I (inode)->i_data_sem); + ctx->getblk_fail_blk =0 ; +KUNIT_EXPECT_EQ (test, ret, -ENOMEM ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT4_I (inode)->i_data[EXT4_IND_BLOCK ]), +300U ); +KUNIT_EXPECT_EQ (test, ctx->alloc_calls,0U ); +KUNIT_EXPECT_FALSE (test, map.m_flags &EXT4_MAP_NEW ); + +/* 2. Out-of-range IND pointer -> -EFSCORRUPTED, pointer preserved */ +EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =cpu_to_le32 (bad_blk); + ctx->alloc_calls =0 ; +memset (&map,0 ,sizeof (map)); + map.m_lblk =IND_TEST_IND_BASE ; + map.m_len =1 ; +down_write (&EXT4_I (inode)->i_data_sem); + ret =ext4_ind_map_blocks (handle, inode, &map,EXT4_GET_BLOCKS_CREATE ); +up_write (&EXT4_I (inode)->i_data_sem); +KUNIT_EXPECT_EQ (test, ret, -EFSCORRUPTED ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT4_I (inode)->i_data[EXT4_IND_BLOCK ]), + (u32 )bad_blk); +KUNIT_EXPECT_EQ (test, ctx->alloc_calls,0U ); + +/* +* 3. bigalloc rejection after ext4_get_branch() has read the IND +* block must drop the IND buffer_head reference it holds. +*/ +EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =cpu_to_le32 (300 ); + ind_bh =ind_lookup_bh (ctx,300 ); +KUNIT_ASSERT_NOT_NULL (test, ind_bh); + count =atomic_read (&ind_bh->b_count); + ctx->alloc_calls =0 ; +ext4_set_feature_bigalloc (sb); +memset (&map,0 ,sizeof (map)); + map.m_lblk =IND_TEST_IND_BASE +1 ; + map.m_len =1 ; +down_write (&EXT4_I (inode)->i_data_sem); + ret =ext4_ind_map_blocks (handle, inode, &map,EXT4_GET_BLOCKS_CREATE ); +up_write (&EXT4_I (inode)->i_data_sem); +ext4_clear_feature_bigalloc (sb); +KUNIT_EXPECT_EQ (test, ret, -EFSCORRUPTED ); +KUNIT_EXPECT_EQ (test,atomic_read (&ind_bh->b_count), count); +KUNIT_EXPECT_EQ (test, ctx->alloc_calls,0U ); + +EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =0 ; +ext4_journal_stop (handle); +iput (inode); +} +static struct kunit_case ext4_indirect_test_cases[] = {KUNIT_CASE (test_block_to_path_and_trans_blocks),KUNIT_CASE (test_ind_map_blocks_lookup_mapped_and_holes),
@@ -1278,6 +1363,7 @@ static struct kunit_case ext4_indirect_test_cases[] = {KUNIT_CASE (test_ind_truncate_partial_and_full),KUNIT_CASE (test_ind_remove_space_levels_and_convergence),KUNIT_CASE (test_ind_free_corrupt_block_numbers), + KUNIT_CASE(test_ind_map_blocks_create_branch_errors), {} };
fs/ext4/indirect.c +13 -4
@@ -135,6 +135,10 @@ static int ext4_block_to_path(struct inode *inode,* (pointer to last triple returned, *@err == 0) * or when it gets an IO error reading an indirect block * (ditto, *@err == -EIO) +* or when it finds a corrupted indirect block reference +* (ditto, *@err == -EFSCORRUPTED) +* or when it fails to get a buffer for an indirect block +* (ditto, *@err == -ENOMEM) * or when it reads all @depth-1 indirect blocks successfully and finds * the whole chain, all way to the data (returns %NULL, *err == 0). *
@@ -177,6 +181,7 @@ static Indirect *ext4_get_branch(struct inode *inode, int depth,/* validate block references */ if (ext4_check_indirect_blockref (inode, bh)) {put_bh (bh); + ret = -EFSCORRUPTED ; goto failure; } }
@@ -572,6 +577,14 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, goto got_it; } +/* +* Failed to read the indirect branch (-EIO, -ENOMEM, -EFSCORRUPTED). +* Never treat this as a hole: allocating here would overwrite the +* existing, still referenced, indirect block pointer. +*/ +if (err) + goto cleanup; +/* Next simple case - plain lookup failed */ if ((flags &EXT4_GET_BLOCKS_CREATE ) ==0 ) {unsigned epb = inode->i_sb->s_blocksize /sizeof (u32);
@@ -610,10 +623,6 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode, goto cleanup; } -/* Failed read of indirect block */ -if (err == -EIO ) - goto cleanup; -/* * Okay, we need to do block allocation. */
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 20/32 ext4: don't stop EXT4_IOC_GET_ES_CACHE at uncached ranges
In reply to Theodore Ts'oext4_fill_es_cache_info() walks the extent status tree by calling ext4_es_lookup_extent() with a next_lblk pointer and stops as soon as the lookup misses. ext4_es_lookup_extent() only fills in *next_lblk on a hit, so any block in the requested range that is not covered by an extent status entry terminates the walk.
The extent status tree commonly has such gaps, since entries are only added for ranges that have been mapped and can be reclaimed by the shrinker. As a result EXT4_IOC_GET_ES_CACHE reports no extents at all when the query starts in an uncached range, even if cached extents follow, and a paginated query that resumes after an extent preceding an uncached gap returns zero extents without FIEMAP_EXTENT_LAST, which ends the iteration early and hides the rest of the cache.
Make ext4_es_lookup_extent() also report the start of the next cached extent on a miss, derived from the last node visited during the tree walk in the same way as __es_tree_search(), and have ext4_fill_es_cache_info() skip ahead to it instead of giving up. The returned block is always greater than the looked up one, so the walk still terminates, and 0 still means there are no further extents.
Extend the KUnit tests to check next_lblk on lookup misses and ext4_get_es_cache() on a tree with leading and interior gaps.
--- fs/ext4/extents-test.c | 30 ++++++++++++++++++++++++++++++ fs/ext4/extents.c | 9 +++++++-- fs/ext4/extents_status-test.c | 17 ++++++++++++++++- fs/ext4/extents_status.c | 23 +++++++++++++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-)
fs/ext4/extents-test.c +30 -0
@@ -2974,6 +2974,36 @@ static void test_ext_fiemap_and_get_es_cache(struct kunit *test)KUNIT_ASSERT_EQ (test, err,0 );KUNIT_EXPECT_EQ (test, fieinfo.fi_flags &FIEMAP_FLAG_CACHE ,0U );KUNIT_EXPECT_GE (test, fieinfo.fi_extents_mapped,5U ); + +/* +* ES tree with uncached ranges [0, 10), [20, 50) and beyond 60: +* ext4_get_es_cache() must skip over them instead of stopping, both +* when the query starts in a leading uncached range and when a +* paginated query resumes inside an uncached gap. +*/ +down_write (&EXT4_I (inode)->i_data_sem); +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +ext4_es_insert_extent (inode,10 ,10 ,400 ,EXTENT_STATUS_WRITTEN ,0 ); +ext4_es_insert_extent (inode,50 ,10 ,500 ,EXTENT_STATUS_WRITTEN ,0 ); +up_write (&EXT4_I (inode)->i_data_sem); + inode->i_size =100LL *4096 ; +EXT4_I (inode)->i_disksize =100LL *4096 ; + +memset (&fieinfo,0 ,sizeof (fieinfo)); + err =ext4_get_es_cache (inode, &fieinfo,0 ,100 *4096 ); +KUNIT_EXPECT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,2U ); + +memset (&fieinfo,0 ,sizeof (fieinfo)); + err =ext4_get_es_cache (inode, &fieinfo,20 *4096 ,80 *4096 ); +KUNIT_EXPECT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,1U ); + +/* A query range entirely inside an uncached gap reports nothing */ +memset (&fieinfo,0 ,sizeof (fieinfo)); + err =ext4_get_es_cache (inode, &fieinfo,20 *4096 ,30 *4096 ); +KUNIT_EXPECT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,0U ); }static const struct kunit_ext_test_param test_split_convert_params[] = {
fs/ext4/extents.c +7 -2
@@ -2251,8 +2251,13 @@ static int ext4_fill_es_cache_info(struct inode *inode,while (block <= end) { next =0 ; flags =0 ; -if (!ext4_es_lookup_extent (inode, block, &next, &es,NULL )) -break ; +if (!ext4_es_lookup_extent (inode, block, &next, &es,NULL )) { +/* Skip over an uncached range to the next extent */ +if (next ==0 ) +break ; + block = next; +continue ; + }if (ext4_es_is_unwritten (&es)) flags |=FIEMAP_EXTENT_UNWRITTEN ;if (ext4_es_is_delayed (&es))
fs/ext4/extents_status-test.c +16 -1
@@ -513,6 +513,7 @@ static void test_es_lookup_empty_tree_returns_miss(struct kunit *test) &ctx->sbi->s_es_stats.es_stats_cache_misses); ret =ext4_es_lookup_extent (inode,10 , &next_lblk, &es,NULL );KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, next_lblk,0U );KUNIT_EXPECT_EQ (test,percpu_counter_sum_positive ( &ctx->sbi->s_es_stats.es_stats_cache_misses), misses_before +1 );
@@ -585,9 +586,23 @@ test_es_lookup_hits_cache_and_rbtree_with_next_lblk(struct kunit *test) &ctx->sbi->s_es_stats.es_stats_cache_hits), hits_before + 4); -/* Lookup in gap [15..19] returns 0 */ +/* Lookup in gap [15..19] returns 0 and points next_lblk at [20, 5) */ + next_lblk =0xdead ; ret =ext4_es_lookup_extent (inode,15 , &next_lblk, &es,NULL );KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, next_lblk,20U ); + +/* Miss before the first extent points next_lblk at [10, 5) */ + next_lblk =0xdead ; + ret =ext4_es_lookup_extent (inode,5 , &next_lblk, &es,NULL ); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, next_lblk,10U ); + +/* Miss after the last extent sets next_lblk to 0 */ + next_lblk =0xdead ; + ret =ext4_es_lookup_extent (inode,30 , &next_lblk, &es,NULL ); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, next_lblk,0U ); }static void test_es_fc_replay_bypasses_tree_operations (struct kunit *test)
fs/ext4/extents_status.c +23 -0
@@ -1087,6 +1087,10 @@ void ext4_es_cache_extent(struct inode *inode, ext4_lblk_t lblk,* * ext4_es_lookup_extent is called by ext4_map_blocks/ext4_da_map_blocks. * +* If @next_lblk is not NULL, it is set to the starting block of the first +* extent after @lblk in the tree, or 0 if there is none, regardless of +* whether @lblk itself was found. +* * Return: 1 on found, 0 on not */ int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk,
@@ -1157,6 +1161,25 @@ int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk, *pseq =EXT4_I (inode)->i_es_seq; }else {percpu_counter_inc (&stats->es_stats_cache_misses); +if (next_lblk) { +/* +* es1 is the last node visited by the tree walk, so +* it is either the successor or the predecessor of +* @lblk (see __es_tree_search()). +*/ + *next_lblk =0 ; +if (es1 && lblk < es1->es_lblk) { + *next_lblk = es1->es_lblk; + }else if (es1) { + node =rb_next (&es1->rb_node); +if (node) { + es1 =rb_entry (node, + struct extent_status, + rb_node); + *next_lblk = es1->es_lblk; + } + } + } }read_unlock (&EXT4_I (inode)->i_es_lock);
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 21/32 ext4: don't read dirent hashes from fake directory entries
In reply to Theodore Ts'o__ext4_check_dir_entry() exempts fake directory entries ('.', '..', and EXT4_FT_DIR_CSUM checksum tails) from the 8-byte ext4_dir_entry_hash trailer required by casefolded encrypted directories. However, every reader of EXT4_DIRENT_HASH() / EXT4_DIRENT_MINOR_HASH() failed to check whether the entry is a fake entry before reading the stored hash:
- On a crafted filesystem without metadata_csum, a 12-byte '..' or an EXT4_FT_DIR_CSUM entry with a nonzero inode placed at the exact end of a directory block causes ext4_readdir(), htree_dirblock_to_tree(), dx_make_map(), and ext4_match() (via ext4_find_dest_de()) to read up to 8 bytes past the end of the directory block buffer. On a keyless encrypted directory, those over-read bytes can leak into the no-key filename presented to userspace.
- Even on a valid casefolded encrypted directory, dx_make_map() reads the header of the adjacent entry as the hash for '.' and '..'.
- ext4_inlinedir_to_tree() reads uninitialized stack bytes from the synthetic '.' and '..' entries and reads past dir_buf for trailing fake or empty entries.
- __ext4_check_dir_entry() did not reject EXT4_FT_DIR_CSUM entries with a nonzero inode or name_len, even though a real directory checksum tail always has both fields set to zero.
Promote ext4_is_fake_dir_entry() (tightened so it only inspects bytes within name_len) and add ext4_dirent_has_hash() to fs/ext4/ext4.h. Reject EXT4_FT_DIR_CSUM entries with a nonzero inode or name_len in __ext4_check_dir_entry(), and skip EXT4_DIRENT_HASH() / EXT4_DIRENT_MINOR_HASH() on fake entries across dir.c, namei.c, and inline.c (using 0 where a hash value is needed rather than falling back to ext4fs_dirhash(), which fails with -EINVAL for DX_HASH_SIPHASH without a key).
Add KUnit regression tests in dir-test.c, namei-test.c, and inline-test.c covering crafted EXT4_FT_DIR_CSUM entries and exact-end fake entries on casefolded encrypted directories.
--- fs/ext4/dir-test.c | 157 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/dir.c | 19 ++--- fs/ext4/ext4.h | 18 +++++ fs/ext4/inline-test.c | 14 ++++ fs/ext4/inline.c | 10 ++- fs/ext4/namei-test.c | 129 ++++++++++++++++++++++++++++++++++ fs/ext4/namei.c | 19 +++-- 7 files changed, 343 insertions(+), 23 deletions(-)
fs/ext4/dir-test.c +157 -0
@@ -87,6 +87,21 @@ enum dir_htree_stub_mode {static const struct super_operations dir_test_sops = { }; +#ifdef CONFIG_FS_ENCRYPTION +static int dir_test_get_context (struct inode *inode,void *ctx,size_t len) +{ +return -ERANGE ; +} + +static const struct fscrypt_operations dir_test_cryptops = { + .inode_info_offs = (int )offsetof(struct ext4_inode_info , + i_crypt_info) - + (int )offsetof(struct ext4_inode_info , + vfs_inode), + .get_context = dir_test_get_context, +}; +#endif +static void init_mock_dir_file (struct dir_test_ctx *ctx,fmode_t extra_mode) {struct inode *dir = &ctx->dir_ei.vfs_inode;
@@ -971,6 +986,147 @@ static void test_dx_readdir(struct kunit *test) ctx->filp.private_data =NULL ; } +/* +* Test 7: Verify fake directory entries ('.', '..', EXT4_FT_DIR_CSUM) never +* trigger out-of-bounds EXT4_DIRENT_HASH() reads in encrypted+casefolded dirs, +* and crafted EXT4_FT_DIR_CSUM entries with nonzero inode/name_len are rejected. +*/ +static void test_fake_dirent_hash_bounds (struct kunit *test) +{ +struct dir_test_ctx *ctx = test->priv; +struct inode *dir = &ctx->dir_ei.vfs_inode; +struct buffer_head *bh; +struct ext4_dir_entry_2 *de; +char *exact_buf, *saved_data; + + exact_buf =kunit_kzalloc (test,DIR_TEST_BLK_SIZE ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, exact_buf); + + bh =alloc_dir_lblk (ctx,0 ); +KUNIT_ASSERT_NOT_NULL (test, bh); + saved_data = bh->b_data; + bh->b_data = exact_buf; + +ext4_clear_feature_metadata_csum (&ctx->sb); +ext4_clear_inode_flag (dir,EXT4_INODE_INDEX ); + dir->i_flags |=S_CASEFOLD |S_ENCRYPTED ; +i_size_write (dir,DIR_TEST_BLK_SIZE ); + dir->i_blocks =DIR_TEST_BLK_SIZE >>9 ; + +/* Helper checks */ +write_de (exact_buf,0 ,DIR_TEST_DIR_INO ,12 ,EXT4_FT_DIR ,"." ); + de = (struct ext4_dir_entry_2 *)exact_buf; +KUNIT_EXPECT_TRUE (test,ext4_is_fake_dir_entry (de)); +KUNIT_EXPECT_FALSE (test,ext4_dirent_has_hash (dir, de)); + +write_de (exact_buf,12 ,DIR_TEST_ROOT_INO ,12 ,EXT4_FT_DIR ,".." ); + de = (struct ext4_dir_entry_2 *)(exact_buf +12 ); +KUNIT_EXPECT_TRUE (test,ext4_is_fake_dir_entry (de)); +KUNIT_EXPECT_FALSE (test,ext4_dirent_has_hash (dir, de)); + +write_de (exact_buf,24 ,15 ,24 ,EXT4_FT_REG_FILE ,"file" ); + de = (struct ext4_dir_entry_2 *)(exact_buf +24 ); +KUNIT_EXPECT_FALSE (test,ext4_is_fake_dir_entry (de)); +KUNIT_EXPECT_TRUE (test,ext4_dirent_has_hash (dir, de)); + +/* +* 1. Crafted EXT4_FT_DIR_CSUM at exact block end (DIR_TEST_BLK_SIZE - 20) +* with nonzero inode and name_len=12 must be rejected. +*/ +memset (exact_buf,0 ,DIR_TEST_BLK_SIZE ); +write_de (exact_buf,0 ,DIR_TEST_DIR_INO ,DIR_TEST_BLK_SIZE -20 , +EXT4_FT_DIR ,"." ); +write_de (exact_buf,DIR_TEST_BLK_SIZE -20 ,15 ,20 , +EXT4_FT_DIR_CSUM ,"crafted_csum" ); + de = (struct ext4_dir_entry_2 *)(exact_buf +DIR_TEST_BLK_SIZE -20 ); +KUNIT_EXPECT_TRUE (test,ext4_is_fake_dir_entry (de)); +KUNIT_EXPECT_FALSE (test,ext4_dirent_has_hash (dir, de)); +KUNIT_EXPECT_EQ (test,__ext4_check_dir_entry (__func__, __LINE__, dir, +NULL , de, bh, exact_buf, +DIR_TEST_BLK_SIZE , +DIR_TEST_BLK_SIZE -20 ), +1 ); + +/* Nonzero inode alone or nonzero name_len alone on CSUM entry rejected */ + de->name_len =0 ; +KUNIT_EXPECT_EQ (test,__ext4_check_dir_entry (__func__, __LINE__, dir, +NULL , de, bh, exact_buf, +DIR_TEST_BLK_SIZE , +DIR_TEST_BLK_SIZE -20 ), +1 ); + de->inode =0 ; + de->name_len =1 ; +KUNIT_EXPECT_EQ (test,__ext4_check_dir_entry (__func__, __LINE__, dir, +NULL , de, bh, exact_buf, +DIR_TEST_BLK_SIZE , +DIR_TEST_BLK_SIZE -20 ), +1 ); +/* Legitimate CSUM tail (inode == 0, name_len == 0) is accepted */ + de->name_len =0 ; +KUNIT_EXPECT_EQ (test,__ext4_check_dir_entry (__func__, __LINE__, dir, +NULL , de, bh, exact_buf, +DIR_TEST_BLK_SIZE , +DIR_TEST_BLK_SIZE -20 ), +0 ); + +#ifdef CONFIG_FS_ENCRYPTION + { +int err; + + ctx->sb.s_cop = &dir_test_cryptops; +KUNIT_ASSERT_EQ (test, ext4_dir_operations.open (dir, &ctx->filp), +0 ); + +/* +* 2a. ext4_readdir() skips crafted CSUM entry at block end +* without an out-of-bounds EXT4_DIRENT_HASH() read. +*/ +write_de (exact_buf,DIR_TEST_BLK_SIZE -20 ,15 ,20 , +EXT4_FT_DIR_CSUM ,"crafted_csum" ); +reset_capture (&ctx->cap,0 ,0 ); +inode_lock_shared (dir); + err = ext4_dir_operations.iterate_shared (&ctx->filp, + &ctx->cap.ctx); +inode_unlock_shared (dir); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_ASSERT_EQ (test, ctx->cap.count,1 ); +KUNIT_EXPECT_STREQ (test, ctx->cap.recs[0 ].name,"." ); + +/* +* 2b. 12-byte '..' at the exact end of the allocation must not +* trigger an 8-byte OOB read past exact_buf in ext4_readdir(). +*/ +ext4_set_feature_metadata_csum (&ctx->sb); +set_buffer_verified (bh); +memset (exact_buf,0 ,DIR_TEST_BLK_SIZE ); +write_de (exact_buf,0 ,DIR_TEST_DIR_INO ,DIR_TEST_BLK_SIZE -12 , +EXT4_FT_DIR ,"." ); +write_de (exact_buf,DIR_TEST_BLK_SIZE -12 ,DIR_TEST_ROOT_INO , +12 ,EXT4_FT_DIR ,".." ); + +reset_capture (&ctx->cap,0 ,0 ); +inode_lock_shared (dir); + err = ext4_dir_operations.iterate_shared (&ctx->filp, + &ctx->cap.ctx); +inode_unlock_shared (dir); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_ASSERT_EQ (test, ctx->cap.count,2 ); +KUNIT_EXPECT_STREQ (test, ctx->cap.recs[0 ].name,"." ); +KUNIT_EXPECT_STREQ (test, ctx->cap.recs[1 ].name,".." ); + +KUNIT_EXPECT_EQ (test, + ext4_dir_operations.release (dir, &ctx->filp), +0 ); + ctx->filp.private_data =NULL ; + ctx->sb.s_cop =NULL ; + } +#endif + + dir->i_flags &= ~(S_CASEFOLD |S_ENCRYPTED ); +ext4_set_feature_metadata_csum (&ctx->sb); + bh->b_data = saved_data; +} +static struct kunit_case ext4_dir_test_cases[] = {KUNIT_CASE (test_check_dir_entry_and_all_de),KUNIT_CASE (test_dx_detection_and_hash_pos_cookies),
@@ -978,6 +1134,7 @@ static struct kunit_case ext4_dir_test_cases[] = {KUNIT_CASE (test_htree_store_dirent_and_free),KUNIT_CASE (test_linear_readdir),KUNIT_CASE (test_dx_readdir), + KUNIT_CASE(test_fake_dirent_hash_bounds), {} };
fs/ext4/dir.c +5 -14
@@ -56,18 +56,6 @@ static int is_dx_dir(struct inode *inode)return 0 ; } -static bool is_fake_dir_entry (struct ext4_dir_entry_2 *de) -{ -/* Check if . or .. , or skip if namelen is 0 */ -if ((de->name_len >0 ) && (de->name_len <=2 ) && (de->name[0 ] =='.' ) && - (de->name[1 ] =='.' || de->name[1 ] =='\0' )) -return true; -/* Check if this is a csum entry */ -if (de->file_type ==EXT4_FT_DIR_CSUM ) -return true; -return false; -} -/* * Return 0 if the directory entry is OK, and 1 if there is a problem *
@@ -86,7 +74,7 @@ int __ext4_check_dir_entry(const char *function, unsigned int line,const int rlen =ext4_rec_len_from_disk (de->rec_len, dir->i_sb->s_blocksize);const int next_offset = ((char *) de - buf) + rlen; -bool fake =is_fake_dir_entry (de); +bool fake =ext4_is_fake_dir_entry (de);bool has_csum =ext4_has_feature_metadata_csum (dir->i_sb);if (unlikely (rlen <ext4_dir_rec_len (1 , fake ?NULL : dir)))
@@ -108,6 +96,9 @@ int __ext4_check_dir_entry(const char *function, unsigned int line,else if (unlikely (next_offset == size && de->name_len ==1 && de->name[0 ] =='.' )) error_msg ="'.' directory cannot be the last in data block" ; +else if (unlikely (de->file_type ==EXT4_FT_DIR_CSUM && + (de->inode || de->name_len))) + error_msg ="invalid directory checksum entry" ;else return 0 ;
@@ -303,7 +294,7 @@ static int ext4_readdir(struct file *file, struct dir_context *ctx)u32 hash;u32 minor_hash; -if (IS_CASEFOLDED (inode)) { +if (ext4_dirent_has_hash (inode, de)) { hash =EXT4_DIRENT_HASH (de); minor_hash =EXT4_DIRENT_MINOR_HASH (de); }else {
fs/ext4/ext4.h +18 -0
@@ -2634,6 +2634,24 @@ static inline unsigned int ext4_dir_rec_len(__u8 name_len,return (rec_len & ~EXT4_DIR_ROUND ); } +static inline bool ext4_is_fake_dir_entry (const struct ext4_dir_entry_2 *de) +{ +/* Check if . or .. , or skip if namelen is 0 */ +if ((de->name_len ==1 && de->name[0 ] =='.' ) || + (de->name_len ==2 && de->name[0 ] =='.' && de->name[1 ] =='.' )) +return true; +/* Check if this is a csum entry */ +if (de->file_type ==EXT4_FT_DIR_CSUM ) +return true; +return false; +} + +static inline bool ext4_dirent_has_hash (const struct inode *dir, +const struct ext4_dir_entry_2 *de) +{ +return ext4_hash_in_dirent (dir) && !ext4_is_fake_dir_entry (de); +} +static inline unsigned int ext4_rec_len_from_disk (__le16 dlen,unsigned blocksize) {
fs/ext4/inline-test.c +14 -0
@@ -1672,6 +1672,20 @@ static void test_inline_dir_lifecycle_and_operations(struct kunit *test) &has_inline_data);KUNIT_EXPECT_GE (test, ret,0 );ext4_htree_free_dir_info (info); + +/* +* Casefolded + encrypted inline directory must not read +* uninitialized/OOB EXT4_DIRENT_HASH() bytes on '.' / '..'. +*/ + dir->i_flags |=S_CASEFOLD |S_ENCRYPTED ; + info =kzalloc_obj (*info,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, info); + env->filp.private_data = info; + ret =ext4_inlinedir_to_tree (&env->filp, dir,0 , &hinfo, +0 ,0 , &has_inline_data); +KUNIT_EXPECT_GE (test, ret,2 ); +ext4_htree_free_dir_info (info); + dir->i_flags &= ~(S_CASEFOLD |S_ENCRYPTED ); }/*
fs/ext4/inline.c +8 -2
@@ -1369,8 +1369,14 @@ int ext4_inlinedir_to_tree(struct file *dir_file, }if (ext4_hash_in_dirent (dir)) { - hinfo->hash =EXT4_DIRENT_HASH (de); - hinfo->minor_hash =EXT4_DIRENT_MINOR_HASH (de); +if (de->name_len && de->inode && + !ext4_is_fake_dir_entry (de)) { + hinfo->hash =EXT4_DIRENT_HASH (de); + hinfo->minor_hash =EXT4_DIRENT_MINOR_HASH (de); + }else { + hinfo->hash =0 ; + hinfo->minor_hash =0 ; + } }else { err =ext4fs_dirhash (dir, de->name, de->name_len, hinfo);if (err) {
fs/ext4/namei-test.c +129 -0
147 lines not on this page · raw message
fs/ext4/namei.c +12 -7
@@ -520,7 +520,8 @@ static struct stats dx_show_leaf(struct inode *dir, len = fname_crypto_str.len; }if (IS_CASEFOLDED (dir)) - h.hash =EXT4_DIRENT_HASH (de); + h.hash =ext4_is_fake_dir_entry (de) ? +0 :EXT4_DIRENT_HASH (de);else (void) ext4fs_dirhash(dir, de->name,
@@ -924,7 +925,8 @@ static int htree_dirblock_to_tree(struct file *dir_file,break ; }if (ext4_hash_in_dirent (dir)) { -if (de->name_len && de->inode) { +if (de->name_len && de->inode && + !ext4_is_fake_dir_entry (de)) { hinfo->hash =EXT4_DIRENT_HASH (de); hinfo->minor_hash =EXT4_DIRENT_MINOR_HASH (de); }else {
@@ -1142,9 +1144,12 @@ static int dx_make_map(struct inode *dir, struct buffer_head *bh, ((char *)de) - base))return -EFSCORRUPTED ;if (de->name_len && de->inode) { -if (ext4_hash_in_dirent (dir)) - h.hash =EXT4_DIRENT_HASH (de); -else { +if (ext4_hash_in_dirent (dir)) { +if (!ext4_is_fake_dir_entry (de)) + h.hash =EXT4_DIRENT_HASH (de); +else + h.hash =0 ; + }else {int err =ext4fs_dirhash (dir, de->name, de->name_len, &h);if (err <0 )
@@ -1278,7 +1283,7 @@ static bool ext4_match(struct inode *parent,* considering the calculated hash. */ if (sb_no_casefold_compat_fallback (parent->i_sb) && -IS_ENCRYPTED (parent) && fname->cf_name.name && +ext4_dirent_has_hash (parent, de) && fname->cf_name.name && (fname->hinfo.hash !=EXT4_DIRENT_HASH (de) || fname->hinfo.minor_hash !=EXT4_DIRENT_MINOR_HASH (de)))return false;
@@ -1314,7 +1319,7 @@ int ext4_search_dir(struct buffer_head *bh, char *search_buf, int buf_size,/* this code is executed quadratically often */ /* do minimal checking `by hand' */ if (de->name + de->name_len <= dlimit && - (!ext4_hash_in_dirent (dir) || + (!ext4_dirent_has_hash (dir, de) || (char *)de +ext4_dir_rec_len (de->name_len, dir) <= dlimit) &&ext4_match (dir, fname, de)) {/* found a match - just to be sure, do
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 22/32 ext4: use loff_t for i_size in ext4_inline_data_truncate()
In reply to Theodore Ts'oIn ext4_inline_data_truncate(), the local variable i_size was declared as size_t rather than loff_t. On 32-bit architectures, assigning inode->i_size to size_t silently truncates sizes >= 4 GiB (e.g., an extending truncate of an inline file to (1LL << 32) + 8 wraps i_size to 8), which then corrupts EXT4_I(inode)->i_disksize, erroneously enters the shrink branch (i_size < inline_size), drops delayed extents from the extent status tree, and truncates away inline data.
Change i_size to loff_t and extend test_inline_data_truncate() in ext4_inline_test to verify that an extending truncate to (1LL << 32) + 8 preserves i_disksize, delayed extents, and inline data.
--- fs/ext4/inline-test.c | 63 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/inline.c | 2 +- 2 files changed, 64 insertions(+), 1 deletion(-)
fs/ext4/inline-test.c +63 -0
@@ -62,6 +62,7 @@ struct inline_test_ctx {int dirty_metadata_calls;int da_get_block_prep_err;int journal_mode; +bool es_stats_inited; };static struct inline_test_ctx *t_ctx;
@@ -314,6 +315,24 @@ static int inline_test_init(struct kunit *test)spin_lock_init (&ctx->sbi.s_bdev_wb_lock);spin_lock_init (&ctx->sbi.s_error_lock);spin_lock_init (&ctx->sbi.s_md_lock); +spin_lock_init (&ctx->sbi.s_es_lock); +INIT_LIST_HEAD (&ctx->sbi.s_es_list); +INIT_LIST_HEAD (&ctx->ei.i_orphan); +KUNIT_ASSERT_EQ (test, +percpu_counter_init (&ctx->sbi.s_dirtyclusters_counter, +0 ,GFP_KERNEL ),0 ); +KUNIT_ASSERT_EQ (test, +percpu_counter_init (&ctx->sbi.s_es_stats.es_stats_cache_hits, +0 ,GFP_KERNEL ),0 ); +KUNIT_ASSERT_EQ (test, +percpu_counter_init (&ctx->sbi.s_es_stats.es_stats_cache_misses, +0 ,GFP_KERNEL ),0 ); +KUNIT_ASSERT_EQ (test, +percpu_counter_init (&ctx->sbi.s_es_stats.es_stats_all_cnt, +0 ,GFP_KERNEL ),0 ); +KUNIT_ASSERT_EQ (test, +percpu_counter_init (&ctx->sbi.s_es_stats.es_stats_shk_cnt, +0 ,GFP_KERNEL ),0 );ratelimit_state_init (&ctx->sbi.s_err_ratelimit_state,DEFAULT_RATELIMIT_INTERVAL ,0 ); ratelimit_state_init(&ctx->sbi.s_warning_ratelimit_state,
@@ -380,6 +399,7 @@ static int inline_test_init(struct kunit *test)INIT_LIST_HEAD (&ctx->ei.i_es_list); ctx->ei.i_es_all_nr =0 ; ctx->ei.i_es_shk_nr =0 ; + ctx->es_stats_inited = true;reset_inode_state (ctx,S_IFREG |0644 );
@@ -414,7 +434,15 @@ static void inline_test_exit(struct kunit *test)if (ctx) {if (!list_empty (&ctx->ei.i_orphan))list_del_init (&ctx->ei.i_orphan); +if (ctx->es_stats_inited) +ext4_es_remove_extent (&ctx->ei.vfs_inode,0 , +EXT_MAX_BLOCKS );truncate_inode_pages (&ctx->ei.vfs_inode.i_data,0 ); +percpu_counter_destroy (&ctx->sbi.s_es_stats.es_stats_shk_cnt); +percpu_counter_destroy (&ctx->sbi.s_es_stats.es_stats_all_cnt); +percpu_counter_destroy (&ctx->sbi.s_es_stats.es_stats_cache_misses); +percpu_counter_destroy (&ctx->sbi.s_es_stats.es_stats_cache_hits); +percpu_counter_destroy (&ctx->sbi.s_dirtyclusters_counter); } t_ctx =NULL ; }
@@ -1113,6 +1141,41 @@ static void test_inline_data_truncate(struct kunit *test)ext4_inline_data_truncate (inode, &has_inline);inode_unlock (inode);KUNIT_EXPECT_TRUE (test,list_empty (&ctx->ei.i_orphan)); + +/* +* 8. Extending i_size past 4 GiB ((1LL << 32) + 8) must not truncate +* i_size via a 32-bit size_t local, corrupt i_disksize, wipe delayed +* extents, or truncate inline data. +*/ + { +struct extent_status es; + +reset_inode_state (ctx,S_IFREG |0644 ); + ret =create_inline_file (inode, buf,100 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_clear_inode_state (inode,EXT4_STATE_MAY_INLINE_DATA ); + ctx->ei.i_reserved_data_blocks =1 ; +ext4_es_insert_delayed_extent (inode,0 ,1 , false, false); +inode_lock (inode); +i_size_write (inode, (1LL <<32 ) +8 ); + has_inline =1 ; + ret =ext4_inline_data_truncate (inode, &has_inline); +inode_unlock (inode); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, has_inline,1 ); +KUNIT_EXPECT_EQ (test, ctx->ei.i_disksize, (1LL <<32 ) +8 ); +KUNIT_EXPECT_EQ (test, ctx->ei.i_inline_size,100 ); +KUNIT_EXPECT_MEMEQ (test,raw_inline_i_block (ctx), buf, +EXT4_MIN_INLINE_DATA_SIZE ); +KUNIT_EXPECT_MEMEQ (test,raw_inline_xattr_pos (ctx), + buf +EXT4_MIN_INLINE_DATA_SIZE , +100 -EXT4_MIN_INLINE_DATA_SIZE ); +KUNIT_EXPECT_TRUE (test, +ext4_es_lookup_extent (inode,0 ,NULL , &es, +NULL )); +KUNIT_EXPECT_TRUE (test,ext4_es_is_delayed (&es)); +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); + } }/* =========================================================================
fs/ext4/inline.c +1 -1
@@ -1893,7 +1893,7 @@ int ext4_inline_data_truncate(struct inode *inode, int *has_inline) {handle_t *handle;int inline_size, value_len, needed_blocks, no_expand, err =0 ; -size_t i_size; +loff_t i_size;void *value =NULL ;struct ext4_xattr_ibody_find is = { .s = { .not_found = -ENODATA , },
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 23/32 ext4: initialize inline dir block under buffer lock before raising i_size
In reply to Theodore Ts'oWhen ext4_convert_inline_data_nolock() converts an inline directory to a normal directory block, it unlocked data_bh and raised inode->i_size (with both a redundant bare store and i_size_write()) BEFORE calling ext4_init_dirblock() to populate ".", "..", copied entries, checksum, and buffer uptodate/verified flags. Furthermore, ext4_init_dirblock() set buffer_uptodate and buffer_verified before calling ext4_dirblock_csum_set().
This opened a race window where concurrent lookups or readers could observe an unlocked, uninitialized, or unchecksummed directory block after i_size was already increased, and also left i_size/i_disksize bumped if ext4_handle_dirty_metadata() failed and fell back to ext4_restore_inline_data().
Factor out ext4_init_dirblock_bh() which writes the directory entries, initializes the dirent tail, computes the metadata checksum, and only then marks the buffer uptodate and verified. Call it while holding lock_buffer(data_bh), unlock data_bh before calling ext4_handle_dirty_metadata() (avoiding any lock_buffer() recursion in no-journal sync_dirty_buffer() paths), and only update i_size/i_disksize (rolling them back if ext4_mark_inode_dirty() fails) after the block is fully initialized and dirtied.
Extend test_inline_dir_conversion_and_corruptions() in ext4_inline_test to verify the buffer flags, valid metadata checksum, deferred i_size update, and rollback on dirty-metadata failure.
--- fs/ext4/ext4.h | 3 ++ fs/ext4/inline-test.c | 73 ++++++++++++++++++++++++++++++++++++++----- fs/ext4/inline.c | 19 +++++++---- fs/ext4/namei.c | 18 ++++++++--- 4 files changed, 94 insertions(+), 19 deletions(-)
fs/ext4/ext4.h +3 -0
@@ -4132,6 +4132,9 @@ static inline int ext4_has_inline_data(struct inode *inode)extern const struct inode_operations ext4_dir_inode_operations;extern const struct inode_operations ext4_special_inode_operations;extern struct dentry *ext4_get_parent (struct dentry *child); +extern void ext4_init_dirblock_bh (struct inode *inode,struct buffer_head *bh, +unsigned int parent_ino,void *inline_buf, +int inline_size); extern int ext4_init_dirblock(handle_t *handle, struct inode *inode, struct buffer_head *dir_block, unsigned int parent_ino, void *inline_buf,
fs/ext4/inline-test.c +65 -8
92 lines not on this page · raw message
fs/ext4/inline.c +13 -6
@@ -1191,17 +1191,24 @@ static int ext4_convert_inline_data_nolock(handle_t *handle, error =ext4_handle_dirty_metadata (handle, inode, data_bh); }else { -unlock_buffer (data_bh); - inode->i_size = inode->i_sb->s_blocksize; -i_size_write (inode, inode->i_sb->s_blocksize); -EXT4_I (inode)->i_disksize = inode->i_sb->s_blocksize; +loff_t old_size =i_size_read (inode); +loff_t old_disksize =EXT4_I (inode)->i_disksize; - error =ext4_init_dirblock (handle, inode, data_bh, +ext4_init_dirblock_bh (inode, data_bh,le32_to_cpu (((struct ext4_dir_entry_2 *)buf)->inode), buf +EXT4_INLINE_DOTDOT_SIZE , inline_size -EXT4_INLINE_DOTDOT_SIZE ); -if (!error) +unlock_buffer (data_bh); + error =ext4_handle_dirty_metadata (handle, inode, data_bh); +if (!error) { +i_size_write (inode, inode->i_sb->s_blocksize); +EXT4_I (inode)->i_disksize = inode->i_sb->s_blocksize; error =ext4_mark_inode_dirty (handle, inode); +if (error) { +i_size_write (inode, old_size); +EXT4_I (inode)->i_disksize = old_disksize; + } + } } out_restore:
fs/ext4/namei.c +13 -5
@@ -2779,9 +2779,9 @@ static int ext4_tmpfile(const struct mnt_idmap *idmap, struct inode *dir,return err; } -int ext4_init_dirblock (handle_t *handle,struct inode *inode, -struct buffer_head *bh,unsigned int parent_ino, -void *inline_buf,int inline_size) +void ext4_init_dirblock_bh (struct inode *inode,struct buffer_head *bh, +unsigned int parent_ino,void *inline_buf, +int inline_size) {struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *) bh->b_data;size_t blocksize = bh->b_size;
@@ -2819,10 +2819,18 @@ int ext4_init_dirblock(handle_t *handle, struct inode *inode,if (csum_size)ext4_initialize_dirent_tail (bh, blocksize); -BUFFER_TRACE (dir_block,"call ext4_handle_dirty_metadata" ); +ext4_dirblock_csum_set (inode, bh);set_buffer_uptodate (bh);set_buffer_verified (bh); -return ext4_handle_dirty_dirblock (handle, inode, bh); +} + +int ext4_init_dirblock (handle_t *handle,struct inode *inode, +struct buffer_head *bh,unsigned int parent_ino, +void *inline_buf,int inline_size) +{ +ext4_init_dirblock_bh (inode, bh, parent_ino, inline_buf, inline_size); +BUFFER_TRACE (bh,"call ext4_handle_dirty_metadata" ); +return ext4_handle_dirty_metadata (handle, inode, bh); }EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_init_dirblock);
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 24/32 ext4: propagate cache flush errors from ext4_fc_replay_inode()
In reply to Theodore Ts'oext4_fc_replay_inode() writes the replayed on-disk inode and then flushes the file system device's cache, but it ignores the result of the flush. If the flush fails, fast commit replay reports success even though the replayed inode may not have reached stable storage, and journal recovery completes as if the inode had been replayed.
Return the error from ext4_fc_issue_flush() so that a failed flush aborts the replay.
The other ignored cache flush errors, in ext4_init_inode_table() and in ext4_fc_perform_commit(), have been fixed by
commit baf9a298bdd7 ("ext4: check return value of blkdev_issue_flush() when initializing inode tables") and
commit 49ac01dd7d43 ("ext4: check return value of blkdev_issue_flush() when starting a fast commit").
Extend ext4_fast_commit_test to verify that a flush failure during inode replay is propagated, and that a flush failure before fast commit blocks are written to an external journal falls back to a full commit. Make the lazy inode table zeroing test in ext4_ialloc_test check that the barrier flag is passed down to ext4_itable_zeroout().
--- fs/ext4/fast_commit-test.c | 28 +++++++++++++++++++++++++++- fs/ext4/fast_commit.c | 2 +- fs/ext4/ialloc-test.c | 5 +++-- 3 files changed, 31 insertions(+), 4 deletions(-)
fs/ext4/fast_commit-test.c +27 -1
@@ -117,6 +117,7 @@ struct fc_test_ctx {int fail_fc_get_buf_on_call;int fc_get_buf_calls;bool fail_fc_wait_bufs; +int fail_fc_flush;int submit_inode_data_err;unsigned int fc_submit_bh_calls;
@@ -794,7 +795,7 @@ static int stub_fc_issue_flush(struct block_device *bdev) ctx->fc_flush_calls++; ctx->last_flushed_bdev = bdev; -return 0 ; +return ctx->fail_fc_flush; }static int mock_submit_inode_data_buffers (struct jbd2_inode *jinode)
@@ -1993,6 +1994,21 @@ static void test_fc_commit_paths(struct kunit *test)memcpy (&tl, ctx->fc_buf_data[1 ],EXT4_FC_TAG_BASE_LEN );KUNIT_EXPECT_EQ (test,le16_to_cpu (tl.fc_tag), (u16 )EXT4_FC_TAG_INODE ); +/* External journal flush failure falls back to full commit */ + { +unsigned int failed_before = sbi->s_fc_stats.fc_failed_commits; + + ctx->fail_fc_flush = -EIO ; + ctx->fc_submit_bh_calls =0 ; +ext4_fc_track_inode (&ctx->handle, file1); +KUNIT_EXPECT_EQ (test,ext4_fc_commit (&ctx->journal,10 ),0 ); +KUNIT_EXPECT_EQ (test,atomic_read (&sbi->s_fc_subtid),2 ); +KUNIT_EXPECT_EQ (test, ctx->fc_submit_bh_calls,0U ); +KUNIT_EXPECT_EQ (test, sbi->s_fc_stats.fc_failed_commits, + failed_before +1 ); + ctx->fail_fc_flush =0 ; + } + ctx->journal.j_fs_dev = &ctx->bdev; }
@@ -2448,6 +2464,16 @@ static void test_fc_replay_inode_and_dentries(struct kunit *test)KUNIT_EXPECT_EQ (test,le32_to_cpu (de->inode), (u32 )TEST_FILE2_INO );brelse (bh); + +/* 3) Flush failure during INODE replay propagates -EIO */ + sbi->s_fc_replay_state.fc_replay_num_tags =5 ; + ctx->fail_fc_flush = -EIO ; +KUNIT_EXPECT_EQ (test, +ext4_fc_replay_test (&ctx->journal, + &ctx->fc_bhs[0 ], +PASS_REPLAY ,0 ,10 ), + -EIO ); + ctx->fail_fc_flush =0 ; }ext4_fc_replay_cleanup (sb);
fs/ext4/fast_commit.c +1 -1
@@ -2041,7 +2041,7 @@ static int ext4_fc_replay_inode(struct super_block *sb, out:iput (inode);if (!ret) -ext4_fc_issue_flush (sb->s_bdev); + ret =ext4_fc_issue_flush (sb->s_bdev);return ret; }
fs/ext4/ialloc-test.c +3 -2
@@ -2670,12 +2670,13 @@ static void ialloc_test_init_inode_table(struct kunit *test) !!(le16_to_cpu (ctx->gdps[0 ].bg_flags) & EXT4_BG_INODE_ZEROED)); -/* 7. Zeroout I/O failure (-EIO) and emergency RO (-EROFS) */ +/* 7. Zeroout/flush I/O failure (-EIO) and emergency RO (-EROFS) */ ctx->gdps[3 ].bg_flags =cpu_to_le16 (EXT4_BG_INODE_UNINIT ); ctx->fail_itable_zeroout_err = -EIO ; - err =ext4_init_inode_table (sb,3 ,0 ); + err =ext4_init_inode_table (sb,3 ,1 ); ctx->fail_itable_zeroout_err =0 ;KUNIT_EXPECT_EQ (test, err, -EIO ); +KUNIT_EXPECT_EQ (test, ctx->last_zeroout_barrier,1 );KUNIT_EXPECT_FALSE (test, !!(le16_to_cpu (ctx->gdps[3 ].bg_flags) &EXT4_BG_INODE_ZEROED ));
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 25/32 ext4: validate child dx_node limit and count in ext4_htree_next_block()
In reply to Theodore Ts'oWhile dx_probe() validates both dx_get_limit() and dx_get_count() on root and child dx_node index blocks, ext4_htree_next_block() descended into newly loaded child dx_node blocks without validating either field. On a corrupted multi-level htree directory, an unchecked child dx_node with a mismatched limit, count == 0, or count > limit causes subsequent ext4_htree_next_block() iterations to step out of bounds past the 4 KiB block buffer or dereference arbitrary blocks.
Extract dx_check_entries() to share the limit and count validation between dx_probe() and ext4_htree_next_block(), and release the newly read buffer and return -EFSCORRUPTED before modifying the frame stack if validation fails in ext4_htree_next_block().
Extend test_namei_check_dx_root_and_probe() in ext4_namei_test with three regression cases covering child dx_node limit mismatch, count == 0, and count > limit.
--- fs/ext4/namei-test.c | 60 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/namei.c | 49 ++++++++++++++++++++++-------------- 2 files changed, 90 insertions(+), 19 deletions(-)
fs/ext4/namei-test.c +60 -0
@@ -1252,6 +1252,9 @@ enum dx_probe_case_id {DXP_BAD_ROOT_LIMIT ,DXP_ZERO_COUNT ,DXP_TREE_CYCLE , +DXP_NEXT_BAD_NODE_LIMIT , +DXP_NEXT_ZERO_COUNT , + DXP_NEXT_COUNT_EXCEEDS_LIMIT, }; struct dx_probe_param {
@@ -1337,6 +1340,21 @@ static const struct dx_probe_param dx_probe_params[] = { .id = DXP_TREE_CYCLE, .expect_ok = false, }, + { + .desc = "ext4_htree_next_block rejects child node limit mismatch", + .id = DXP_NEXT_BAD_NODE_LIMIT, + .expect_ok = true, + }, + { + .desc = "ext4_htree_next_block rejects child node count == 0", + .id = DXP_NEXT_ZERO_COUNT, + .expect_ok = true, + }, + { + .desc = "ext4_htree_next_block rejects child node count > limit", + .id = DXP_NEXT_COUNT_EXCEEDS_LIMIT, + .expect_ok = true, + }, }; static void dx_probe_get_desc(const struct dx_probe_param *p, char *desc)
@@ -1401,7 +1419,12 @@ static void test_namei_check_dx_root_and_probe(struct kunit *test) TEST_BLK_SIZE);break ;case DXP_VALID_2LEVEL_AND_NEXT : +case DXP_NEXT_BAD_NODE_LIMIT : +case DXP_NEXT_ZERO_COUNT : +case DXP_NEXT_COUNT_EXCEEDS_LIMIT : + dir->i_size =5 *TEST_BLK_SIZE ; root->info.indirect_levels =1 ; +dx_set_block (root->entries +1 ,4 ); bh1 =map_and_get_dir_bh (ctx, dir,1 );KUNIT_ASSERT_NOT_NULL (test, bh1); node = (struct dx_node *)bh1->b_data;
@@ -1413,6 +1436,30 @@ static void test_namei_check_dx_root_and_probe(struct kunit *test)/* Continuation hash (low bit 1) matching 0x40000000 */ dx_set_hash (node->entries +1 ,0x40000001U );dx_set_block (node->entries +1 ,3 ); +if (p->id !=DXP_VALID_2LEVEL_AND_NEXT ) { +struct buffer_head *bh4; +struct dx_node *node2; + + bh4 =map_and_get_dir_bh (ctx, dir,4 ); +KUNIT_ASSERT_NOT_NULL (test, bh4); + node2 = (struct dx_node *)bh4->b_data; + node2->fake.rec_len =ext4_rec_len_to_disk ( +TEST_BLK_SIZE ,TEST_BLK_SIZE ); +if (p->id ==DXP_NEXT_BAD_NODE_LIMIT ) { +dx_set_limit (node2->entries, +dx_node_limit (dir) -1 ); +dx_set_count (node2->entries,1 ); + }else if (p->id ==DXP_NEXT_ZERO_COUNT ) { +dx_set_limit (node2->entries, +dx_node_limit (dir)); +dx_set_count (node2->entries,0 ); + }else { +dx_set_limit (node2->entries, +dx_node_limit (dir)); +dx_set_count (node2->entries, +dx_node_limit (dir) +1 ); + } + }break ;case DXP_DOT_BAD_NAMELEN : root->dotdot.rec_len =ext4_rec_len_to_disk (12 ,TEST_BLK_SIZE );
@@ -1491,6 +1538,19 @@ static void test_namei_check_dx_root_and_probe(struct kunit *test)KUNIT_EXPECT_EQ (test,ext4_htree_next_block_test (dir,0x40000000U , frame, frames,NULL ),0 ); + }else if (p->id ==DXP_NEXT_BAD_NODE_LIMIT || + p->id ==DXP_NEXT_ZERO_COUNT || + p->id ==DXP_NEXT_COUNT_EXCEEDS_LIMIT ) { +KUNIT_ASSERT_PTR_EQ (test, frame, &frames[1 ]); +/* First step stays in bh1 (entries[1]) */ +KUNIT_ASSERT_EQ (test, +ext4_htree_next_block_test (dir,HASH_NB_ALWAYS , frame, + frames, &start_hash),1 ); +/* Next step descends into corrupt child dx_node at lblk 4 */ +KUNIT_EXPECT_EQ (test, +ext4_htree_next_block_test (dir,HASH_NB_ALWAYS , frame, + frames, &start_hash), + -EFSCORRUPTED ); }dx_release_test (frames); }
fs/ext4/namei.c +30 -19
87 lines not on this page · raw message
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 26/32 ext4: flush s_ea_inode_work before clearing EXT4_FC_REPLAY
In reply to Theodore Ts'oDuring fast commit journal replay at mount time, ext4_xattr_delete_inode() or other xattr helpers can drop the last reference to an EA inode via ext4_put_ea_inode(), deferring the final iput() to the s_ea_inode_work delayed workqueue.
Previously, ext4_fc_replay_cleanup() cleared EXT4_FC_REPLAY from sbi->s_mount_state and freed replay tracking structures before flushing s_ea_inode_work. If the delayed worker ran afterwards (or before mballoc initialization completed in __ext4_fill_super()), ext4_evict_inode() -> ext4_free_inode() would no longer see EXT4_FC_REPLAY and could attempt journal/mballoc operations on a not-yet- initialized filesystem.
Call flush_delayed_work(&sbi->s_ea_inode_work) at the start of ext4_fc_replay_cleanup() so all deferred EA inode iputs drain while EXT4_FC_REPLAY is still set.
Extend test_fc_replay_regions_and_scan() in ext4_fast_commit_test to verify that a deferred EA inode queued via ext4_put_ea_inode() is evicted with EXT4_FC_REPLAY still set before ext4_fc_replay_cleanup() returns.
--- fs/ext4/fast_commit-test.c | 73 +++++++++++++++++++++++++++++++++++++- fs/ext4/fast_commit.c | 6 ++++ 2 files changed, 78 insertions(+), 1 deletion(-)
fs/ext4/fast_commit-test.c +72 -1
@@ -27,6 +27,7 @@#include "extents_status.h" #include "fast_commit.h" #include "namei.h" +#include "xattr.h" #define TEST_BLK_SIZE 1024#define TEST_BLK_BITS 10
@@ -134,8 +135,14 @@ struct fc_test_ctx {bool use_custom_es_lookup;struct extent_status custom_es;int custom_es_ret; + +/* Deferred EA inode eviction tracking during replay cleanup */ +bool ea_evicted; +bool ea_evict_saw_fc_replay; }; +static struct fc_test_ctx *fc_active_ctx; +#ifdef CONFIG_QUOTA static struct dquot __rcu **fc_test_get_dquots (struct inode *inode) {
@@ -152,7 +159,41 @@ static const struct dquot_operations fc_test_qops = { };#endif +static struct inode *fc_test_alloc_inode (struct super_block *sb) +{ +struct ext4_inode_info *ei =kzalloc_obj (*ei,GFP_KERNEL ); + +if (!ei) +return NULL ; +inode_init_once (&ei->vfs_inode); +return &ei->vfs_inode; +} + +static void fc_test_free_inode (struct inode *inode) +{ +kfree (EXT4_I (inode)); +} + +static void fc_test_evict_inode (struct inode *inode) +{ +struct ext4_sb_info *sbi =EXT4_SB (inode->i_sb); + +if (EXT4_I (inode)->i_flags &EXT4_EA_INODE_FL ) { +struct fc_test_ctx *ctx =READ_ONCE (fc_active_ctx); + +if (ctx) { +WRITE_ONCE (ctx->ea_evicted, true); +WRITE_ONCE (ctx->ea_evict_saw_fc_replay, + !!(sbi->s_mount_state &EXT4_FC_REPLAY )); + } + } +clear_inode (inode); +} +static const struct super_operations fc_test_sops = { + .alloc_inode = fc_test_alloc_inode, + .free_inode = fc_test_free_inode, + .evict_inode = fc_test_evict_inode, #ifdef CONFIG_QUOTA .get_dquots = fc_test_get_dquots, #endif
@@ -859,6 +900,8 @@ static void fc_cleanup_all(void *priv)ext4_es_destroy_stats (ctx->sbi); }deactivate_super (ctx->sb); +rcu_barrier (); +WRITE_ONCE (fc_active_ctx,NULL ); }static int fast_commit_test_init (struct kunit *test)
@@ -884,6 +927,8 @@ static int fast_commit_test_init(struct kunit *test) ctx->sb = sb; ctx->sbi = sbi; +WRITE_ONCE (fc_active_ctx, ctx); +ext4_init_ea_inode_work (sbi); test->priv = ctx;/* Superblock and ext4_sb_info setup */
@@ -2211,7 +2256,33 @@ static void test_fc_replay_regions_and_scan(struct kunit *test) PASS_SCAN, 1, 10), JBD2_FC_REPLAY_STOP);KUNIT_EXPECT_EQ (test, state->fc_replay_num_tags,2 ); -ext4_fc_replay_cleanup (sb); + +/* +* 6) ext4_fc_replay_cleanup() must drain deferred EA inode iputs +* while EXT4_FC_REPLAY is still set before clearing replay state. +*/ + { +struct inode *ea_inode =new_inode (sb); + +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ea_inode); + ea_inode->i_ino =500 ; + ea_inode->i_mode =S_IFREG |0600 ; +clear_nlink (ea_inode); +EXT4_I (ea_inode)->i_flags =EXT4_EA_INODE_FL ; +WRITE_ONCE (ctx->ea_evicted, false); +WRITE_ONCE (ctx->ea_evict_saw_fc_replay, false); + sbi->s_mount_state |=EXT4_FC_REPLAY ; + +ext4_put_ea_inode (ea_inode); +ext4_fc_replay_cleanup (sb); + +KUNIT_EXPECT_TRUE (test,READ_ONCE (ctx->ea_evicted)); +KUNIT_EXPECT_TRUE (test, +READ_ONCE (ctx->ea_evict_saw_fc_replay)); +KUNIT_EXPECT_FALSE (test, + !!(sbi->s_mount_state &EXT4_FC_REPLAY )); +KUNIT_EXPECT_TRUE (test,llist_empty (&sbi->s_ea_inode_to_free)); + }memset (state,0 ,sizeof (*state)); }
fs/ext4/fast_commit.c +6 -0
@@ -2426,6 +2426,12 @@ void ext4_fc_replay_cleanup(struct super_block *sb) {struct ext4_sb_info *sbi =EXT4_SB (sb); +/* +* Drain any deferred EA inode iputs queued during fast commit replay +* before clearing EXT4_FC_REPLAY and freeing replay state so that +* ext4_evict_inode() -> ext4_free_inode() still sees EXT4_FC_REPLAY. +*/ +flush_delayed_work (&sbi->s_ea_inode_work); sbi->s_mount_state &= ~EXT4_FC_REPLAY ;kfree (sbi->s_fc_replay_state.fc_regions); sbi->s_fc_replay_state.fc_regions =NULL ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 27/32 ext4: zero dirty EOF folio tail before raising i_size in ext4_setattr()
In reply to Theodore Ts'oWhen extending a file with ext4_setattr() where blocksize < PAGE_SIZE (or on a large folio whose size exceeds blocksize) and oldsize is block-aligned (or falls short of the folio end), ext4_block_zero_eof() only zeroes up to the next block boundary. The remaining post-EOF bytes in the dirty tail folio were not zeroed until pagecache_isize_extended() ran after ext4_journal_stop() — leaving a window after i_size_write() in which concurrent readers or writeback could observe unzeroed post-EOF pagecache data from prior mmap writes.
Add ext4_zero_eof_folio_tail() and call it before ext4_journal_start() and ext4_set_inode_size() in ext4_truncate_up() to zero dirty post-EOF folio bytes before exposing the larger i_size, while keeping pagecache_isize_extended() after ext4_journal_stop() so folio_mkclean() runs after i_size is updated.
Extend inode_test_setattr() in ext4_inode_test to verify that with a 1 KiB block size and a dirty EOF folio, extending from 1024 to PAGE_SIZE zeroes [1024, PAGE_SIZE) before __ext4_mark_inode_dirty() observes the updated i_size.
--- fs/ext4/inode-test.c | 75 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/inode.c | 28 +++++++++++++++++ 2 files changed, 103 insertions(+)
fs/ext4/inode-test.c +75 -0
@@ -3545,6 +3545,36 @@ static void inode_test_buffered_write_and_folio_ops(struct kunit *test)* ------------------------------------------------------------------------- */ +struct setattr_dirty_snap { +bool seen; +loff_t isize; +u8 pre_eof_byte; +u8 post_eof_start_byte; +u8 post_eof_end_byte; +}; + +static struct setattr_dirty_snap setattr_snap; + +static int inode_test_setattr_dirty_stub (handle_t *handle,struct inode *inode, +const char *func,unsigned int line) +{ +struct folio *folio; +u8 *kaddr; + + setattr_snap.seen = true; + setattr_snap.isize =i_size_read (inode); + folio =filemap_get_folio (inode->i_mapping,0 ); +if (!IS_ERR (folio)) { + kaddr =kmap_local_folio (folio,0 ); + setattr_snap.pre_eof_byte = kaddr[1023 ]; + setattr_snap.post_eof_start_byte = kaddr[1024 ]; + setattr_snap.post_eof_end_byte = kaddr[PAGE_SIZE -1 ]; +kunmap_local (kaddr); +folio_put (folio); + } +return 0 ; +} +static void inode_test_setattr (struct kunit *test) {struct inode_test_ctx *ctx =inode_test_setup (test);
@@ -3642,6 +3672,51 @@ static void inode_test_setattr(struct kunit *test)KUNIT_EXPECT_EQ (test, inode->i_size,4096LL );KUNIT_EXPECT_EQ (test, ctx->ei.i_disksize,4096LL );KUNIT_EXPECT_EQ (test, ctx->total_freed_blocks,1UL ); + +/* +* 6. Sub-page blocksize (1024 < PAGE_SIZE) extending truncate from +* block-aligned oldsize = 1024 to PAGE_SIZE must zero dirty post-EOF +* bytes in the tail folio BEFORE i_size is raised and marked dirty. +*/ +inode_test_reset_mock_inode (ctx,S_IFREG |0644 ); + ctx->sb->s_blocksize =1024 ; + ctx->sb->s_blocksize_bits =10 ; + inode->i_blkbits =10 ; + inode->i_size =1024 ; + ctx->ei.i_disksize =1024 ; + + folio =filemap_grab_folio (inode->i_mapping,0 ); +KUNIT_ASSERT_FALSE (test,IS_ERR (folio)); +create_empty_buffers (folio,1024 ,0 ); + kaddr =kmap_local_folio (folio,0 ); +memset (kaddr,0x55 ,1024 ); +memset (kaddr +1024 ,0xaa ,PAGE_SIZE -1024 ); +kunmap_local (kaddr); +folio_mark_uptodate (folio); +folio_mark_dirty (folio); +folio_unlock (folio); +folio_put (folio); + +memset (&setattr_snap,0 ,sizeof (setattr_snap)); +kunit_activate_static_stub (test, __ext4_mark_inode_dirty, + inode_test_setattr_dirty_stub); + attr = (struct iattr ){ .ia_valid =ATTR_SIZE , .ia_size =PAGE_SIZE }; +inode_lock (inode); + err =ext4_setattr (&nop_mnt_idmap, &dentry, &attr); +inode_unlock (inode); +kunit_deactivate_static_stub (test, __ext4_mark_inode_dirty); + +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_ASSERT_TRUE (test, setattr_snap.seen); +KUNIT_EXPECT_EQ (test, setattr_snap.isize, (loff_t )PAGE_SIZE ); +KUNIT_EXPECT_EQ (test, setattr_snap.pre_eof_byte, (u8 )0x55 ); +KUNIT_EXPECT_EQ (test, setattr_snap.post_eof_start_byte, (u8 )0x00 ); +KUNIT_EXPECT_EQ (test, setattr_snap.post_eof_end_byte, (u8 )0x00 ); + +truncate_inode_pages_final (inode->i_mapping); + ctx->sb->s_blocksize =INODE_TEST_BLK_SIZE ; + ctx->sb->s_blocksize_bits =INODE_TEST_BLK_BITS ; + inode->i_blkbits =INODE_TEST_BLK_BITS ; }/* -------------------------------------------------------------------------
fs/ext4/inode.c +28 -0
@@ -7036,6 +7036,28 @@ static inline void ext4_set_inode_size(struct inode *inode, loff_t newsize)up_write (&EXT4_I (inode)->i_data_sem); } +static void ext4_zero_eof_folio_tail (struct inode *inode,loff_t from, +loff_t to) +{ +struct folio *folio; + +if (IS_DAX (inode) || from >= to) +return ; + folio =filemap_lock_folio (inode->i_mapping, from >>PAGE_SHIFT ); +if (IS_ERR (folio)) +return ; +if (folio_test_dirty (folio) && from >folio_pos (folio)) { +size_t offset = from -folio_pos (folio); +size_t end =min_t (loff_t, to -folio_pos (folio), +folio_size (folio)); + +if (offset < end) +folio_zero_segment (folio, offset, end); + } +folio_unlock (folio); +folio_put (folio); +} +static int ext4_truncate_up (struct inode *inode,loff_t oldsize,loff_t newsize) {ext4_lblk_t old_lblk, new_lblk;
@@ -7054,6 +7076,12 @@ static int ext4_truncate_up(struct inode *inode, loff_t oldsize, loff_t newsize)if (ret)return ret; } +/* +* Zero any dirty post-EOF bytes in the tail folio before publishing +* the larger i_size so concurrent readers cannot observe stale +* pagecache data before pagecache_isize_extended(). +*/ +ext4_zero_eof_folio_tail (inode, oldsize, newsize); handle =ext4_journal_start (inode,EXT4_HT_INODE ,3 );if (IS_ERR (handle))
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 28/32 ext4: use atomic iversion accessors in swap_inode_data()
In reply to Theodore Ts'oswap_inode_data() currently uses swap(inode1->i_version, inode2->i_version) to exchange the two inodes' i_version counters. Because inode->i_version is an atomic64_t, swapping the structs directly performs plain non-atomic loads and stores, which can expose torn 64-bit values to concurrent lockless readers (such as inode_peek_iversion_raw()) on 32-bit SMP systems.
Exchange the raw i_version values using inode_peek_iversion_raw() and inode_set_iversion_raw() instead, and update test_swap_inode_data_and_seed() in fs/ext4/ioctl-test.c to verify full 64-bit i_version values across both swaps.
--- fs/ext4/ioctl-test.c | 14 ++++++++++---- fs/ext4/ioctl.c | 5 ++++- 2 files changed, 14 insertions(+), 5 deletions(-)
fs/ext4/ioctl-test.c +10 -4
@@ -1140,8 +1140,8 @@ static void test_swap_inode_data_and_seed(struct kunit *test) ei2->i_disksize =0x22000 ;i_size_write (inode1,0x10500 );i_size_write (inode2,0x20500 ); -inode_set_iversion_raw (inode1,10 ); -inode_set_iversion_raw (inode2,20 ); +inode_set_iversion_raw (inode1,0x123456789abcdef0ULL ); +inode_set_iversion_raw (inode2,0xfedcba9876543210ULL );inode_set_atime_to_ts (inode1, at1);inode_set_atime_to_ts (inode2, at2);inode_set_mtime_to_ts (inode1, mt1);
@@ -1164,8 +1164,10 @@ static void test_swap_inode_data_and_seed(struct kunit *test)KUNIT_EXPECT_EQ (test, ei2->i_disksize, (loff_t )0x11000 );KUNIT_EXPECT_EQ (test,i_size_read (inode1), (loff_t )0x20500 );KUNIT_EXPECT_EQ (test,i_size_read (inode2), (loff_t )0x10500 ); -KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode1),20ULL ); -KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode2),10ULL ); +KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode1), +0xfedcba9876543210ULL ); +KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode2), +0x123456789abcdef0ULL );KUNIT_EXPECT_EQ (test,inode_get_atime_sec (inode1),2000LL );KUNIT_EXPECT_EQ (test,inode_get_mtime_sec (inode1),4000LL );KUNIT_EXPECT_EQ (test, ei1->i_es_all_nr,0U );
@@ -1181,6 +1183,10 @@ static void test_swap_inode_data_and_seed(struct kunit *test)KUNIT_EXPECT_EQ (test, ei2->i_flags, (u32 )EXT4_NOATIME_FL );KUNIT_EXPECT_EQ (test, ei1->i_disksize, (loff_t )0x11000 );KUNIT_EXPECT_EQ (test,i_size_read (inode1), (loff_t )0x10500 ); +KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode1), +0x123456789abcdef0ULL ); +KUNIT_EXPECT_EQ (test,inode_peek_iversion_raw (inode2), +0xfedcba9876543210ULL );/* ext4_reset_inode_seed with and without metadata_csum */ inode1->i_ino =42 ;
fs/ext4/ioctl.c +4 -1
@@ -331,11 +331,14 @@ static void swap_inode_data(struct inode *inode1, struct inode *inode2)struct ext4_inode_info *ei2;unsigned long tmp;struct timespec64 ts1, ts2; +u64 iversion; ei1 =EXT4_I (inode1); ei2 =EXT4_I (inode2); -swap (inode1->i_version, inode2->i_version); + iversion =inode_peek_iversion_raw (inode1); +inode_set_iversion_raw (inode1,inode_peek_iversion_raw (inode2)); +inode_set_iversion_raw (inode2, iversion); ts1 =inode_get_atime (inode1); ts2 =inode_get_atime (inode2);
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 29/32 ext4: reject atomic writes split by fscrypt without warning
In reply to Theodore Ts'oIn ext4_iomap_begin(), map.m_len is clamped by fscrypt_limit_io_blocks() before the IOMAP_ATOMIC length check. For an encrypted inode using IV_INO_LBLK_32, an unprivileged user issuing a multi-block atomic write across a 32-bit DUN wraparound causes fscrypt_limit_io_blocks() to shorten map.m_len below length >> blkbits, triggering WARN_ON_ONCE(1).
Check fscrypt_limit_io_blocks() for IOMAP_ATOMIC before allocating blocks and return -EINVAL cleanly without warning if the write would have to be split. Also move the existing WARN_ON_ONCE(1) check on ext4's own mapping length ahead of fscrypt_limit_io_blocks() and handle any post-mapping truncation cleanly with -EINVAL.
Add an ext4_fscrypt_limit_io_blocks() wrapper with a KUnit static stub redirect and extend inode_test_iomap_and_atomic_writes() in fs/ext4/inode-test.c to cover both checks and non-atomic truncation.
--- fs/ext4/ext4.h | 2 ++ fs/ext4/inode-test.c | 66 ++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/inode.c | 36 +++++++++++++++++++----- 3 files changed, 97 insertions(+), 7 deletions(-)
fs/ext4/ext4.h +2 -0
@@ -3361,6 +3361,8 @@ struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, ext4_fsblk_t block);struct buffer_head *ext4_sb_getblk_unmovable (struct super_block *sb,ext4_fsblk_t block); +u64 ext4_fscrypt_limit_io_blocks (const struct inode *inode,u64 lblk, +u64 nr_blocks);#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )int ext4_inode_csum_verify_test (struct inode *inode,struct ext4_inode *raw,struct ext4_inode_info *ei);
fs/ext4/inode-test.c +66 -0
84 lines not on this page · raw message
fs/ext4/inode.c +29 -7
@@ -1140,6 +1140,15 @@ struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, }EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_sb_getblk_unmovable); +u64 ext4_fscrypt_limit_io_blocks (const struct inode *inode,u64 lblk, +u64 nr_blocks) +{ +KUNIT_STATIC_STUB_REDIRECT (ext4_fscrypt_limit_io_blocks, inode, lblk, + nr_blocks); +return fscrypt_limit_io_blocks (inode, lblk, nr_blocks); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fscrypt_limit_io_blocks); +/* * `handle' can be NULL if create is zero */
@@ -4032,6 +4041,16 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1; orig_mlen = map.m_len; +/* +* Atomic writes must be issued as a single contiguous bio, so reject +* requests that fscrypt would have to split across a DUN wraparound +* before allocating blocks. +*/ +if ((flags &IOMAP_ATOMIC ) && +ext4_fscrypt_limit_io_blocks (inode, map.m_lblk, map.m_len) < + map.m_len) +return -EINVAL ; +if (flags &IOMAP_WRITE ) {/* * We check here if the blocks are already allocated, then we
@@ -4067,13 +4086,6 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,if (ret <0 )return ret; out: -/* -* Sometimes I/O to an encrypted file has to be broken up to guarantee -* DUN contiguity. Handle this by limiting the length of the mapping -* returned. -*/ - map.m_len =fscrypt_limit_io_blocks (inode, map.m_lblk, map.m_len); -/* * Before returning to iomap, let's ensure the allocated mapping * covers the entire requested length for atomic writes.
@@ -4084,6 +4096,16 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,return -EINVAL ; } } + +/* +* Sometimes I/O to an encrypted file has to be broken up to guarantee +* DUN contiguity. Handle this by limiting the length of the mapping +* returned. +*/ + map.m_len =ext4_fscrypt_limit_io_blocks (inode, map.m_lblk, map.m_len); +if ((flags &IOMAP_ATOMIC ) && map.m_len < (length >> blkbits)) +return -EINVAL ; +ext4_set_iomap (inode, iomap, &map, offset, length, flags);return 0 ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 30/32 ext4: protect extent status shrinker stats with s_es_lock
In reply to Theodore Ts'o__es_shrink() updates the 64-bit statistics fields es_stats_scan_time, es_stats_max_scan_time, and es_stats_shrunk at its out label after dropping sbi->s_es_lock. Concurrent shrinker invocations can race on these read-modify-write updates and tear 64-bit values on 32-bit systems.
Similarly, ext4_seq_es_shrinker_info_show() releases sbi->s_es_lock before reading those same statistics fields as well as the max inode's i_ino, i_es_all_nr, and i_es_shk_nr fields.
Hold sbi->s_es_lock across the es_stats updates in __es_shrink(), and snapshot the es_stats and max inode fields while holding sbi->s_es_lock in ext4_seq_es_shrinker_info_show(). Extend test_es_seq_shrinker_info_show_formats_stats() in fs/ext4/extents_status-test.c to cover both EWMA branches and the formatted shrinker statistics output.
--- fs/ext4/extents_status-test.c | 27 +++++++++++++++++++++++++++ fs/ext4/extents_status.c | 21 +++++++++++++++++---- 2 files changed, 44 insertions(+), 4 deletions(-)
fs/ext4/extents_status-test.c +27 -0
@@ -1594,10 +1594,34 @@ static void test_es_seq_shrinker_info_show_formats_stats(struct kunit *test) {struct es_test_ctx *ctx = test->priv;struct inode *inode = &ctx->ei->vfs_inode; +struct shrink_control sc = {};struct seq_file seq = {};char *buf; +/* +* Empty-list scan exercises the early goto-out stats lock path. +* Nothing is examined, so the shrinker reports SHRINK_STOP. +*/ + sc.nr_to_scan =4 ; +KUNIT_EXPECT_EQ (test,es_shrinker_scan (ctx, &sc),SHRINK_STOP ); +KUNIT_EXPECT_EQ (test, sc.nr_scanned,0UL ); + +/* Populate extents and run two scans to exercise both EWMA branches */ es_insert_extent (inode,10 ,2 ,100 ,EXTENT_STATUS_WRITTEN , false); +es_insert_extent (inode,20 ,2 ,200 ,EXTENT_STATUS_WRITTEN , false); +es_insert_extent (inode,30 ,2 ,300 ,EXTENT_STATUS_WRITTEN , false); +es_insert_extent (inode,40 ,2 ,400 ,EXTENT_STATUS_WRITTEN , false); +es_insert_extent (inode,50 ,2 ,500 ,EXTENT_STATUS_WRITTEN , false); + +/* First scan hits nr_to_scan <= 0 goto-out path (shrunk = 2) */ + sc.nr_to_scan =2 ; +KUNIT_EXPECT_EQ (test,es_shrinker_scan (ctx, &sc),2UL ); +KUNIT_EXPECT_EQ (test, ctx->sbi->s_es_stats.es_stats_shrunk,2UL ); + +/* Second scan exercises EWMA update: (1 + 2 * 3) / 4 == 1 */ + sc.nr_to_scan =1 ; +KUNIT_EXPECT_EQ (test,es_shrinker_scan (ctx, &sc),1UL ); +KUNIT_EXPECT_EQ (test, ctx->sbi->s_es_stats.es_stats_shrunk,1UL ); buf =kunit_kzalloc (test,PAGE_SIZE ,GFP_KERNEL );KUNIT_ASSERT_NOT_NULL (test, buf);
@@ -1610,6 +1634,9 @@ static void test_es_seq_shrinker_info_show_formats_stats(struct kunit *test) 0);KUNIT_EXPECT_GT (test, seq.count,0UL );KUNIT_EXPECT_NOT_NULL (test,strstr (buf,"reclaimable objects" )); +KUNIT_EXPECT_NOT_NULL (test,strstr (buf,"1 inodes on list" )); +KUNIT_EXPECT_NOT_NULL (test,strstr (buf,"1 shrunk objects" )); +KUNIT_EXPECT_NOT_NULL (test,strstr (buf,"max scan time" )); }static struct kunit_case extents_status_test_cases[] = {
fs/ext4/extents_status.c +17 -4
@@ -1765,6 +1765,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, *nr_scanned = orig_nr_to_scan - nr_to_scan; scan_time =ktime_to_ns (ktime_sub (ktime_get (), start_time)); +spin_lock (&sbi->s_es_lock);if (likely (es_stats->es_stats_scan_time)) es_stats->es_stats_scan_time = (scan_time + es_stats->es_stats_scan_time*3 ) /4 ;
@@ -1777,6 +1778,7 @@ static int __es_shrink(struct ext4_sb_info *sbi, int nr_to_scan, es_stats->es_stats_shrunk*3) / 4; else es_stats->es_stats_shrunk = nr_shrunk; +spin_unlock (&sbi->s_es_lock);trace_ext4_es_shrink (sbi->s_sb, nr_shrunk, scan_time, nr_skipped, retried);
@@ -1839,6 +1841,9 @@ int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v)struct ext4_es_stats *es_stats = &sbi->s_es_stats;struct ext4_inode_info *ei, *max =NULL ;unsigned int inode_cnt =0 ; +unsigned int max_all_nr =0 , max_shk_nr =0 ; +unsigned long shrunk; +u64 scan_time, max_scan_time, max_ino =0 ;if (v !=SEQ_START_TOKEN )return 0 ;
@@ -1852,6 +1857,14 @@ int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v)else if (!max) max = ei; } +if (max) { + max_ino = max->vfs_inode.i_ino; + max_all_nr = max->i_es_all_nr; + max_shk_nr = max->i_es_shk_nr; + } + scan_time = es_stats->es_stats_scan_time; + shrunk = es_stats->es_stats_shrunk; + max_scan_time = es_stats->es_stats_max_scan_time;spin_unlock (&sbi->s_es_lock); seq_printf(seq, "stats:\n %lld objects\n %lld reclaimable objects\n",
@@ -1864,14 +1877,14 @@ int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v)seq_printf (seq," %d inodes on list\n" , inode_cnt);seq_printf (seq,"average:\n %llu us scan time\n" , -div_u64 (es_stats->es_stats_scan_time,1000 )); -seq_printf (seq," %lu shrunk objects\n" , es_stats->es_stats_shrunk); +div_u64 (scan_time,1000 )); +seq_printf (seq," %lu shrunk objects\n" , shrunk);if (inode_cnt)seq_printf (seq,"maximum:\n %llu inode (%u objects, %u reclaimable)\n" " %llu us max scan time\n" , - max->vfs_inode.i_ino, max->i_es_all_nr, max->i_es_shk_nr, -div_u64 (es_stats->es_stats_max_scan_time,1000 )); + max_ino, max_all_nr, max_shk_nr, +div_u64 (max_scan_time,1000 ));return 0 ; }
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 31/32 ext4: set bh->b_bdev on mock buffers in resize-test
In reply to Theodore Ts'oWhen block:block_dirty_buffer event tracing is enabled, ext4_group_extend() -> ext4_mb_mark_context() -> __ext4_handle_dirty_metadata() -> mark_buffer_dirty() invokes trace_block_dirty_buffer(bh), which dereferences bh->b_bdev->bd_dev.
resize_init_mock_bh() in fs/ext4/resize-test.c previously left bh->b_bdev NULL, causing a NULL pointer dereference in test_group_extend_partial_last_group() when tracing is active.
Pass &ctx->bdev into resize_init_mock_bh() so all mock buffer heads in ext4_resize_test have a valid bh->b_bdev, matching ioctl-test.c.
--- fs/ext4/resize-test.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
fs/ext4/resize-test.c +7 -4
@@ -155,10 +155,13 @@ static struct file_system_type resize_test_fs_type = { .kill_sb = kill_anon_super, }; -static void resize_init_mock_bh (struct buffer_head *bh,struct folio *folio, +static void resize_init_mock_bh (struct buffer_head *bh, +struct block_device *bdev, +struct folio *folio,u8 *data,size_t size,sector_t blocknr) {memset (bh,0 ,sizeof (*bh)); + bh->b_bdev = bdev; bh->b_folio = folio; bh->b_data = (char *)data; bh->b_size = size;
@@ -200,7 +203,7 @@ static struct buffer_head *resize_get_or_create_bh(struct resize_test_ctx *ctx,return NULL ; } blk->blocknr = blocknr; -resize_init_mock_bh (&blk->bh, ctx->bh_folio, blk->data, +resize_init_mock_bh (&blk->bh, &ctx->bdev, ctx->bh_folio, blk->data,RESIZE_TEST_BLK_SIZE , blocknr);list_add_tail (&blk->node, &ctx->blks);get_bh (&blk->bh);
@@ -734,8 +737,8 @@ static int resize_test_init(struct kunit *test) ctx->es = (struct ext4_super_block *)sbh->b_data; sbi->s_es = ctx->es; -resize_init_mock_bh (&ctx->iloc_bh, ctx->bh_folio, ctx->iloc_buf, -RESIZE_TEST_BLK_SIZE ,99 ); +resize_init_mock_bh (&ctx->iloc_bh, &ctx->bdev, ctx->bh_folio, + ctx->iloc_buf,RESIZE_TEST_BLK_SIZE ,99 ); active_resize_test = test;kunit_activate_static_stub (test, ext4_sb_getblk, resize_sb_getblk_stub);
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
Theodore Ts'o
maintainerPATCH 32/32 ext4: avoid zero i_dtime wrap in ialloc-test on RTC-less VMs
In reply to Theodore Ts'oOn RTC-less virtual machines such as QEMU arm64, ktime_get_real_seconds() starts at 0 on boot. In ialloc_test_find_inode_bit() and ialloc_test_recently_deleted(), computing (now - age) for age = 10/20/120 can evaluate to 0 if the test runs at that exact uptime second. Because recently_deleted() treats i_dtime == 0 as "never deleted", the test spuriously fails when now == 10.
Add a small helper ialloc_test_past_dtime() that bumps the age by 1 second (wrapping to 0xffffffff) whenever (now - age) == 0, keeping the timestamp in the same wrap-safe time_before32() window while guaranteeing a non-zero on-disk i_dtime.
--- fs/ext4/ialloc-test.c | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
fs/ext4/ialloc-test.c +20 -5
@@ -1792,6 +1792,21 @@ static void ialloc_test_find_group_other_flex_bg(struct kunit *test)* ========================================================================= */ +/* +* Compute a non-zero on-disk i_dtime @age seconds before @now. +* On RTC-less VMs (e.g., QEMU arm64) ktime_get_real_seconds() starts at 0, +* so (now - age) can land on 0, which recently_deleted() treats as "never +* deleted". Bumping age by 1s in that case keeps it in the same window. +*/ +static __le32 ialloc_test_past_dtime (u32 now,u32 age) +{ +u32 dtime = now - age; + +if (!dtime) + dtime--; +return cpu_to_le32 (dtime); +} +static void ialloc_test_recently_deleted (struct kunit *test) {struct ialloc_test_ctx *ctx = test->priv;
@@ -1816,7 +1831,7 @@ static void ialloc_test_recently_deleted(struct kunit *test) raw = (struct ext4_inode *)(it_slot->cache_buf +2 *IALLOC_TEST_INODE_SIZE ); now =ktime_get_real_seconds (); - raw->i_dtime =cpu_to_le32 (now -10 ); + raw->i_dtime =ialloc_test_past_dtime (now,10 );KUNIT_EXPECT_EQ (test,ext4_recently_deleted_test (sb,1 ,2 ),0 );/* 4. Cached but !buffer_uptodate -> returns 0 */
@@ -1831,16 +1846,16 @@ static void ialloc_test_recently_deleted(struct kunit *test)/* 6. Clean buffer uses 60s window; dirty buffer extends to 360s */ now =ktime_get_real_seconds (); - raw->i_dtime =cpu_to_le32 (now -20 ); + raw->i_dtime =ialloc_test_past_dtime (now,20 );KUNIT_EXPECT_EQ (test,ext4_recently_deleted_test (sb,1 ,2 ),1 ); - raw->i_dtime =cpu_to_le32 (now -120 ); + raw->i_dtime =ialloc_test_past_dtime (now,120 );KUNIT_EXPECT_EQ (test,ext4_recently_deleted_test (sb,1 ,2 ),0 );set_buffer_dirty (&it_slot->bh);KUNIT_EXPECT_EQ (test,ext4_recently_deleted_test (sb,1 ,2 ),1 ); - raw->i_dtime =cpu_to_le32 (now -400 ); + raw->i_dtime =ialloc_test_past_dtime (now,400 );KUNIT_EXPECT_EQ (test,ext4_recently_deleted_test (sb,1 ,2 ),0 );clear_buffer_dirty (&it_slot->bh); }
@@ -1868,7 +1883,7 @@ static void ialloc_test_find_inode_bit(struct kunit *test) true, true);KUNIT_ASSERT_NOT_NULL (test, it_slot); raw1 = (struct ext4_inode *)(it_slot->cache_buf +IALLOC_TEST_INODE_SIZE ); - raw1->i_dtime =cpu_to_le32 ((u32 )ktime_get_real_seconds () -10 ); + raw1->i_dtime =ialloc_test_past_dtime (ktime_get_real_seconds (),10 );/* No-journal mode skips recently deleted bit 1 in favor of bit 6 */ ino =0 ;
Signature · 1 line
2.56.1.708.g77570a6a1d-goog