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, the fixes for the valid bugs are in this patch set. A summary of all the bugs, how they are fixed, and their criticality level --- e.g., "Critical (data loss)", "High (metadata corruption)", "Low (32-bit compat)", etc. --- 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
Some of these bug fixes may be duplicative of the backlog of AI slop patch backlog (sorry, submitters; I'll be processing them now that the merge window is closed).
Of course, these patches are *also* potentially AI slop, so while I've given them a very light review, we'll have to see what Sashiko has to say, and they need a more in-depth review before they get landed.
Theodore Ts'o (23):
ext4: only update s_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: cap migrated extents at EXT_INIT_MAX_LEN
ext4: don't treat a handle restart as an error in finish_range()
ext4: don't clobber the migration result in ext4_ext_migrate()
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
fs/ext4/ext4.h | 8 + fs/ext4/extents-test.c | 30 +++ fs/ext4/extents.c | 13 +- fs/ext4/extents_status-test.c | 17 +- fs/ext4/extents_status.c | 23 +++ fs/ext4/fsmap-test.c | 56 ++++++ fs/ext4/fsmap.c | 2 +- fs/ext4/indirect-test.c | 90 ++++++++- fs/ext4/indirect.c | 19 +- fs/ext4/ioctl-test.c | 356 ++++++++++++++++++++++++++++++++-- fs/ext4/ioctl.c | 145 +++++++++----- fs/ext4/migrate-test.c | 210 +++++++++++++++++++- fs/ext4/migrate.c | 20 +- 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/resize-test.c | 118 +++++++++++ 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 +- 23 files changed, 1504 insertions(+), 128 deletions(-)
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 1/23 ext4: only update s_mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set
Every field written by ext4_sb_setparams() is guarded by its EXT4_TUNE_FL_* bit in params->set_flags, except for s_mount_opts, which is unconditionally overwritten with params->mount_opts. Likewise, ext4_validate_tune_sb_params() rejects an unterminated mount_opts string even when the caller is not asking to change it.
As a result, any EXT4_IOC_SET_TUNE_SB_PARAM call that tunes an unrelated field (e.g. errors behavior or the reserved block count) with a zeroed mount_opts silently wipes the default mount options stored in the primary and all backup superblocks, and a caller that leaves mount_opts uninitialized can get a spurious -E2BIG or have stack garbage written into the superblock.
Only validate and copy mount_opts when EXT4_TUNE_FL_MOUNT_OPTS is set.
--- fs/ext4/ioctl-test.c | 40 ++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 6 ++++-- 2 files changed, 44 insertions(+), 2 deletions(-)
fs/ext4/ioctl-test.c +40 -0
@@ -597,6 +597,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 );
@@ -690,6 +691,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,
@@ -1150,6 +1189,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 +4 -2
@@ -1374,7 +1374,8 @@ static void ext4_sb_setparams(struct ext4_sb_info *sbi, es->s_encoding =cpu_to_le16 (params->encoding);if (params->set_flags &EXT4_TUNE_FL_ENCODING_FLAGS ) es->s_encoding_flags =cpu_to_le16 (params->encoding_flags); -strscpy_pad (es->s_mount_opts, params->mount_opts); +if (params->set_flags &EXT4_TUNE_FL_MOUNT_OPTS ) +strscpy_pad (es->s_mount_opts, params->mount_opts);if (params->set_flags &EXT4_TUNE_FL_EDIT_FEATURES ) { es->s_feature_compat |=cpu_to_le32 (params->set_feature_compat_mask);
@@ -1406,7 +1407,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 2/23 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
@@ -817,6 +817,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
@@ -1191,6 +1237,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 3/23 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
@@ -522,8 +522,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 ;
@@ -539,8 +537,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 ;
@@ -563,9 +559,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,
@@ -583,8 +576,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) {
@@ -675,20 +669,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 4/23 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
@@ -736,6 +736,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,
@@ -1243,6 +1302,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);
@@ -1488,10 +1500,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 5/23 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
@@ -795,6 +795,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,
@@ -1303,6 +1397,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 6/23 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>
@@ -889,6 +891,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,
@@ -1398,6 +1459,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;
@@ -1432,6 +1435,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 7/23 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
@@ -1423,6 +1423,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
@@ -2064,6 +2064,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 8/23 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
@@ -1305,6 +1305,18 @@ static void test_error_recording_and_update_super(struct kunit *test)KUNIT_EXPECT_EQ (test,le64_to_cpu (es->s_kbytes_written),100ULL );KUNIT_EXPECT_EQ (test, es->s_checksum,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
@@ -6302,6 +6302,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);/*
@@ -6360,9 +6361,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 9/23 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
@@ -3756,6 +3756,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. */
@@ -3792,8 +3793,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 10/23 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
@@ -1077,6 +1077,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
@@ -4266,12 +4266,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 11/23 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
@@ -1317,6 +1317,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),
@@ -1326,6 +1405,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 12/23 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
@@ -950,6 +950,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 13/23 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
@@ -1408,6 +1408,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),
@@ -1418,6 +1441,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
@@ -2190,7 +2190,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 14/23 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
@@ -1305,6 +1305,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
@@ -2043,6 +2043,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 15/23 ext4: cap migrated extents at EXT_INIT_MAX_LEN
In reply to Theodore Ts'oWhen converting an indirect-mapped inode to extents, ext4_ext_migrate() coalesces physically and logically contiguous blocks in update_extent_range() without any upper bound, and finish_range() then stores the raw run length into the 16-bit ee_len field.
An initialized extent can be at most EXT_INIT_MAX_LEN (32768) blocks long; larger ee_len values encode unwritten extents. So if an indirect file contains a contiguous run of more than 32768 blocks (128 MiB with 4 KiB blocks), the migrated extent is silently turned into an unwritten extent of length (len - 32768): the file data reads back as zeroes, the tail of the run becomes a hole, and 32768 blocks are leaked once the file is truncated or unlinked. A run of exactly 65536 blocks wraps ee_len to zero, producing a corrupt extent.
Stop extending the current range once it reaches EXT_INIT_MAX_LEN, so that long runs are split into several initialized extents.
--- fs/ext4/migrate-test.c | 91 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/migrate.c | 6 ++- 2 files changed, 95 insertions(+), 2 deletions(-)
fs/ext4/migrate-test.c +91 -0
@@ -1041,6 +1041,96 @@ static void test_ind_migrate_rejections(struct kunit *test)iput (inode); } +/* +* Test 8: ext4_ext_migrate() splits a physically and logically contiguous +* run longer than EXT_INIT_MAX_LEN into multiple initialized extents rather +* than encoding the raw length into ee_len, which would turn the extent +* into an unwritten one (or wrap ee_len) and lose the file data. +*/ +static void test_ext_migrate_caps_long_run_at_init_max_len (struct kunit *test) +{ +struct migrate_test_ctx *ctx = test->priv; +const unsigned int per_blk =MIGRATE_TEST_BLK_SIZE /sizeof (__le32); +const unsigned int nr_ind =128 ; +const ext4_fsblk_t data_pblk =2000 ; +const ext4_fsblk_t ind_pblk =600 , dind_pblk =700 ; +const ext4_lblk_t len =EXT4_NDIR_BLOCKS + per_blk + nr_ind * per_blk; +const int max_len =EXT_INIT_MAX_LEN ; +struct ext4_extent_header *eh; +struct ext4_extent *ex; +struct buffer_head *bh; +struct inode *inode; +ext4_fsblk_t pblk = data_pblk; +unsigned int i, j; + +/* 12 + 256 + 128 * 256 = 33036 blocks > EXT_INIT_MAX_LEN */ +KUNIT_ASSERT_GT (test, len, (ext4_lblk_t )max_len); +ext4_blocks_count_set (ctx->es, data_pblk + len +1024 ); + + inode =migrate_make_test_inode (test,22 ,S_IFREG |0644 ); +i_size_write (inode, (loff_t )len *MIGRATE_TEST_BLK_SIZE ); + +for (i =0 ; i <EXT4_NDIR_BLOCKS ; i++) +EXT4_I (inode)->i_data[i] =cpu_to_le32 (pblk++); + +EXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =cpu_to_le32 (ind_pblk); + bh =migrate_get_or_create_bh (ctx, ind_pblk); +KUNIT_ASSERT_NOT_NULL (test, bh); +for (j =0 ; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] =cpu_to_le32 (pblk++); +brelse (bh); + +EXT4_I (inode)->i_data[EXT4_DIND_BLOCK ] =cpu_to_le32 (dind_pblk); + bh =migrate_get_or_create_bh (ctx, dind_pblk); +KUNIT_ASSERT_NOT_NULL (test, bh); +for (i =0 ; i < nr_ind; i++) + ((__le32 *)bh->b_data)[i] =cpu_to_le32 (dind_pblk +1 + i); +brelse (bh); + +for (i =0 ; i < nr_ind; i++) { + bh =migrate_get_or_create_bh (ctx, dind_pblk +1 + i); +KUNIT_ASSERT_NOT_NULL (test, bh); +for (j =0 ; j < per_blk; j++) + ((__le32 *)bh->b_data)[j] =cpu_to_le32 (pblk++); +brelse (bh); + } + inode->i_blocks = (blkcnt_t)(len +2 + nr_ind) * + (MIGRATE_TEST_BLK_SIZE >>9 ); + +KUNIT_EXPECT_EQ (test,ext4_ext_migrate (inode),0 ); +KUNIT_EXPECT_TRUE (test, +ext4_test_inode_flag (inode,EXT4_INODE_EXTENTS )); + eh =ext_inode_hdr (inode); +if (!ext4_test_inode_flag (inode,EXT4_INODE_EXTENTS ) || + !eh->eh_entries) + goto out; + +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_depth),0U ); + ex =EXT_FIRST_EXTENT (eh); + +/* Extent 0: lblk [0..32767] -> data_pblk, initialized */ +KUNIT_EXPECT_EQ (test,le32_to_cpu (ex[0 ].ee_block),0U ); +KUNIT_EXPECT_FALSE (test,ext4_ext_is_unwritten (&ex[0 ])); +KUNIT_EXPECT_EQ (test,ext4_ext_get_actual_len (&ex[0 ]), max_len); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (&ex[0 ]), data_pblk); + +/* Extent 1: remainder of the run, initialized */ +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),2U ); +if (le16_to_cpu (eh->eh_entries) <2 ) + goto out; +KUNIT_EXPECT_EQ (test,le32_to_cpu (ex[1 ].ee_block), (u32 )max_len); +KUNIT_EXPECT_FALSE (test,ext4_ext_is_unwritten (&ex[1 ])); +KUNIT_EXPECT_EQ (test,ext4_ext_get_actual_len (&ex[1 ]), + (int )len - max_len); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (&ex[1 ]), data_pblk + max_len); + +/* Indirect metadata blocks were released */ +KUNIT_EXPECT_TRUE (test,migrate_was_freed (ctx, ind_pblk)); +KUNIT_EXPECT_TRUE (test,migrate_was_freed (ctx, dind_pblk +1 )); +out: +iput (inode); +} +static struct kunit_case ext4_migrate_test_cases[] = {KUNIT_CASE (test_ext_migrate_precondition_checks_and_fast_symlink),KUNIT_CASE (test_ext_migrate_direct_and_ind_coalescing_and_holes),
@@ -1049,6 +1139,7 @@ static struct kunit_case ext4_migrate_test_cases[] = {KUNIT_CASE (test_ext_swap_inode_data_detects_concurrent_allocation),KUNIT_CASE (test_ind_migrate_empty_and_single_direct_extent),KUNIT_CASE (test_ind_migrate_rejections), + KUNIT_CASE(test_ext_migrate_caps_long_run_at_init_max_len), {} };
fs/ext4/migrate.c +4 -2
@@ -67,11 +67,13 @@ static int update_extent_range(handle_t *handle, struct inode *inode, {int retval;/* -* See if we can add on to the existing range (if it exists) +* See if we can add on to the existing range (if it exists). +* An initialized extent cannot be longer than EXT_INIT_MAX_LEN. */ if (lb->first_pblock && (lb->last_pblock+1 == pblock) && - (lb->last_block+1 == lb->curr_block)) { + (lb->last_block+1 == lb->curr_block) && + (lb->last_block - lb->first_block +1 <EXT_INIT_MAX_LEN )) { lb->last_pblock = pblock; lb->last_block = lb->curr_block; lb->curr_block++;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 16/23 ext4: don't treat a handle restart as an error in finish_range()
In reply to Theodore Ts'oext4_datasem_ensure_credits() returns 1 when it had to restart the transaction to get the requested credits. finish_range() only bails out on a negative value, but it then leaves the 1 in retval, and since ext4_ext_insert_extent() was converted to return the path, a successful insertion no longer overwrites retval. finish_range() therefore returns 1, which all its callers treat as a failure.
As a result, whenever the handle has to be restarted while building the extent tree of the temporary inode (which is likely for fragmented files that need many extent insertions), the migration is aborted and the extent blocks built so far are thrown away. Because the error code is later clobbered in ext4_ext_migrate(), userspace is even told that the migration succeeded while the inode stays indirect-mapped.
A restart is not an error: reset retval to 0 after a successful ext4_datasem_ensure_credits(). The path does not need to be looked up again since tmp_inode is private to the migration and cannot change while i_data_sem is briefly dropped.
Add a KUnit static stub hook to ext4_datasem_ensure_credits() so that a transaction restart can be emulated without a journal.
--- fs/ext4/extents.c | 4 +++ fs/ext4/migrate-test.c | 66 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/migrate.c | 5 ++++ 3 files changed, 75 insertions(+)
fs/ext4/extents.c +4 -0
@@ -142,12 +142,16 @@ int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,int ret;int dropped =0 ; +KUNIT_STATIC_STUB_REDIRECT (ext4_datasem_ensure_credits, handle, inode, + check_cred, restart_cred, revoke_cred); + ret =ext4_journal_ensure_credits_fn (handle, check_cred, restart_cred, revoke_cred,ext4_ext_trunc_restart_fn (inode, &dropped));if (dropped)down_write (&EXT4_I (inode)->i_data_sem);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_datasem_ensure_credits);/* * could return:
fs/ext4/migrate-test.c +66 -0
90 lines not on this page · raw message
fs/ext4/migrate.c +5 -0
@@ -52,6 +52,11 @@ static int finish_range(handle_t *handle, struct inode *inode, retval =ext4_datasem_ensure_credits (handle, inode, needed, needed,0 );if (retval <0 ) goto err_out; +/* +* A positive return only means the handle was restarted. The +* path is still valid because nobody else can modify tmp_inode. +*/ + retval =0 ; path =ext4_ext_insert_extent (handle, inode, path, &newext,0 );if (IS_ERR (path)) retval =PTR_ERR (path);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 17/23 ext4: don't clobber the migration result in ext4_ext_migrate()
In reply to Theodore Ts'oAfter building the extent tree and (on success) swapping it into the inode, ext4_ext_migrate() makes sure the handle has a credit left for resetting tmp_inode, storing the result of ext4_journal_ensure_credits() in retval. This throws away the outcome of the migration itself:
- If anything failed before (an I/O error reading an indirect block, ENOSPC while growing the temporary extent tree, or EAGAIN from ext4_ext_swap_inode_data() because a block was allocated concurrently), the error is replaced by 0 and EXT4_IOC_MIGRATE or "chattr +e" reports success although the inode is still indirect-mapped.
- If the handle had to be restarted to obtain the credit, ext4_journal_ensure_credits() returns 1, which is then returned to userspace from EXT4_IOC_MIGRATE and treated as a failure by ext4_ioctl_setflags().
Use a separate variable for the credit check and only let its error override retval if the migration itself succeeded.
--- fs/ext4/migrate-test.c | 53 +++++++++++++++++++++++++++++++++++++++--- fs/ext4/migrate.c | 9 ++++--- 2 files changed, 56 insertions(+), 6 deletions(-)
fs/ext4/migrate-test.c +50 -3
@@ -68,6 +68,7 @@ struct migrate_test_ctx {ext4_fsblk_t freed_blks[MIGRATE_MAX_FREED_REC ];unsigned int freed_cnt;unsigned int datasem_restarts; +struct inode *race_inode;bool rwsem_inited;bool es_shrinker_inited;bool counters_inited;
@@ -382,6 +383,20 @@ static int migrate_datasem_restart_stub(handle_t *handle, struct inode *inode,return 1 ; } +/* +* Emulate a block allocation racing with the migration of +* ctx->race_inode, which clears EXT4_STATE_EXT_MIGRATE on it. +*/ +static int migrate_datasem_race_stub (handle_t *handle,struct inode *inode, +int check_cred,int restart_cred, +int revoke_cred) +{ +struct migrate_test_ctx *ctx = active_migrate_test->priv; + +ext4_clear_inode_state (ctx->race_inode,EXT4_STATE_EXT_MIGRATE ); +return 0 ; +} +static struct inode *migrate_make_test_inode (struct kunit *test,unsigned long ino,umode_t mode) {
@@ -859,8 +874,8 @@ static void test_ext_migrate_dind_tind_and_multilevel_tree(struct kunit *test)/* * Test 4: When reading an indirect block fails midway after tmp_inode has * already grown a depth-1 extent tree, free_ext_block() / free_ext_idx() -* frees the allocated temporary extent metadata block and leaves the original -* inode untouched. +* frees the allocated temporary extent metadata block, leaves the original +* inode untouched, and ext4_ext_migrate() returns the error. */ static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks (struct kunit *test) {
@@ -886,7 +901,8 @@ static void test_ext_migrate_error_rollback_frees_tmp_extent_blocks(struct kunitEXT4_I (inode)->i_data[EXT4_IND_BLOCK ] =cpu_to_le32 (MIGRATE_TEST_TOTAL_BLKS +50 ); - (void )ext4_ext_migrate (inode); +/* The read error is reported to the caller, not swallowed */ +KUNIT_EXPECT_EQ (test,ext4_ext_migrate (inode), -EIO );/* Temporary extent leaf block allocated during build must be freed */ KUNIT_EXPECT_TRUE (test,migrate_was_freed (ctx, expected_leaf_blk));
@@ -1196,6 +1212,36 @@ static void test_ext_migrate_survives_handle_restart(struct kunit *test)iput (inode); } +/* +* Test 10: If a concurrent block allocation invalidates the migration, +* ext4_ext_migrate() reports -EAGAIN instead of claiming success, and the +* inode keeps its indirect block map. +*/ +static void test_ext_migrate_reports_concurrent_allocation (struct kunit *test) +{ +struct migrate_test_ctx *ctx = test->priv; +struct inode *inode; + +kunit_activate_static_stub (test, ext4_datasem_ensure_credits, + migrate_datasem_race_stub); + + inode =migrate_make_test_inode (test,24 ,S_IFREG |0644 ); +i_size_write (inode,4 *MIGRATE_TEST_BLK_SIZE ); + inode->i_blocks =2 * (MIGRATE_TEST_BLK_SIZE >>9 ); +EXT4_I (inode)->i_data[0 ] =cpu_to_le32 (100 ); +EXT4_I (inode)->i_data[3 ] =cpu_to_le32 (200 ); + ctx->race_inode = inode; + +KUNIT_EXPECT_EQ (test,ext4_ext_migrate (inode), -EAGAIN ); +KUNIT_EXPECT_FALSE (test, +ext4_test_inode_flag (inode,EXT4_INODE_EXTENTS )); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT4_I (inode)->i_data[0 ]),100U ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT4_I (inode)->i_data[3 ]),200U ); + + ctx->race_inode =NULL ; +iput (inode); +} +static struct kunit_case ext4_migrate_test_cases[] = {KUNIT_CASE (test_ext_migrate_precondition_checks_and_fast_symlink),KUNIT_CASE (test_ext_migrate_direct_and_ind_coalescing_and_holes),
@@ -1206,6 +1252,7 @@ static struct kunit_case ext4_migrate_test_cases[] = {KUNIT_CASE (test_ind_migrate_rejections),KUNIT_CASE (test_ext_migrate_caps_long_run_at_init_max_len),KUNIT_CASE (test_ext_migrate_survives_handle_restart), + KUNIT_CASE(test_ext_migrate_reports_concurrent_allocation), {} };
fs/ext4/migrate.c +6 -3
@@ -417,7 +417,7 @@ static int free_ext_block(handle_t *handle, struct inode *inode)int ext4_ext_migrate (struct inode *inode) {handle_t *handle; -int retval =0 , i; +int retval =0 , err, i;__le32 *i_data;struct ext4_inode_info *ei;struct inode *tmp_inode =NULL ;
@@ -574,9 +574,12 @@ int ext4_ext_migrate(struct inode *inode) }/* We mark the tmp_inode dirty via ext4_ext_tree_init. */ - retval =ext4_journal_ensure_credits (handle,1 ,0 ); -if (retval <0 ) + err =ext4_journal_ensure_credits (handle,1 ,0 ); +if (err <0 ) { +if (!retval) + retval = err; goto out_stop; + }/* * Mark the tmp_inode as of size zero */
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 18/23 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
@@ -802,6 +802,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
@@ -545,11 +545,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 19/23 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
@@ -2866,6 +2866,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 */
@@ -4233,6 +4240,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 20/23 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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 21/23 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
@@ -765,6 +765,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),
@@ -773,6 +828,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.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 22/23 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.
The bigalloc check that rejects allocation for indirect-mapped inodes also jumps to "out" instead of "cleanup", leaking the references to the indirect block buffer_heads that ext4_get_branch() already took.
Bail out on any error from ext4_get_branch() before using the partial chain on both the lookup and the allocation paths, release the chain on the bigalloc error path, 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.
--- fs/ext4/indirect-test.c | 90 ++++++++++++++++++++++++++++++++++++++++- fs/ext4/indirect.c | 19 ++++++--- 2 files changed, 102 insertions(+), 7 deletions(-)
fs/ext4/indirect-test.c +88 -2
@@ -78,6 +78,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;
@@ -230,6 +231,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); }
@@ -953,14 +957,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 ;
@@ -1247,6 +1252,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),
@@ -1255,6 +1340,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 +14 -5
@@ -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);
@@ -593,10 +606,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. */
@@ -604,7 +613,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,EXT4_ERROR_INODE (inode,"Can't allocate blocks for " "non-extent mapped inodes with bigalloc" ); err = -EFSCORRUPTED ; - goto out; + goto cleanup; }/* Set up for the direct block allocation */
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 23/23 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
@@ -2946,6 +2946,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
@@ -2242,8 +2242,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
@@ -507,6 +507,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 );
@@ -579,9 +580,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.0.542.g3ef89b7020-goog