ext4: add lots of KUnit tests!
Theodore Ts'o
maintainercover ext4: add lots of KUnit tests!
These unit tests were written using the writing-kunit-tests.md prompt[1], and then lightly reviewed by a human with only a few fix-ups needed.
[1] https://drive.google.com/file/d/1MVZIhlG79kTRX_A65phWiZkTPJEtypsL/view
While the LLM was busily generating these unit tests, it also found around two dozen potential bug fixes[2]. Those will be sent in a separate series.
[2] https://drive.google.com/file/d/1pnTKAVf9pAoCK27619uP4_3_hpE04SkR/view
Hopefully extending ext4's Kunit coverage will make it easier to sanity check the flood of AI generated patch submissions. IOW, since these tests were created Gemeni Pro, I'm hoping that we can use fire to fight fire. :-)
So as I process the AI slop backlog, my plan is to do trial merges to determine whether the patches break the unit tests or not. Which to be fair, might be an indication of breakage of the unit tests, and not necessarily a bug in the patches under review.
The patches in this series are available at the ext4.git tree on the branch ext4-kunit-tests[3]. The patch series was originally based on v7.3-rc4, so you want to try merging with with v7.4-rc2 or later, use the branch ext4-kinit-tests-merge[4].
[3] https://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git/log/?h=ext4-kunit-tests
[4] https://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git/log/?h=ext4-kunit-tests-merge
Theodore Ts'o (27):
ext4: add KUinit tests for fs/ext4/extents_status.c
ext4: add KUnit tests for fs/ext4/extents.c
ext4: add KUnit tests for ext4_ext_split() leaf and index splitting
ext4: add KUnit tests for fs/ext4/xattr.c
ext4: add KUnit tests for fs/ext4/namei.c
ext4: expand KUnit tests for fs/ext4/mballoc.c
ext4: add KUnit tests for fs/ext4/inline.c
ext4: zero s_fc_replay_state in ext4_fc_replay_cleanup()
ext4: add KUnit tests for fs/ext4/fast_commit.c
ext4: expand KUnit tests for fs/ext4/inode.c
ext4: add KUnit tests for fs/ext4/ialloc.c
ext4: add KUnit tests for fs/ext4/balloc.c
ext4: add KUnit tests for fs/ext4/orphan.c
ext4: add KUnit tests for fs/ext4/block_validity.c
ext4: check multi-block overlap on left traversal in add_system_zone()
ext4: enable full feature coverage in fs/ext4/.kunitconfig
ext4: add KUnit tests for fs/ext4/super.c
ext4: add KUnit tests for fs/ext4/sysfs.c
ext4: add KUnit tests for fs/ext4/ioctl.c
ext4: add KUnit tests for fs/ext4/resize.c
ext4: add KUnit tests for fs/ext4/migrate.c
ext4: add KUnit tests for fs/ext4/indirect.c
ext4: expand KUnit tests in fs/ext4/extents-test.c for file range
operations
ext4: add KUnit tests for fs/ext4/fsmap.c
ext4: add KUnit tests for fs/ext4/move_extent.c
ext4: add KUnit tests for fs/ext4/mmp.c
ext4: add KUnit tests for fs/ext4/dir.c
fs/ext4/.kunitconfig | 7 + fs/ext4/Makefile | 12 +- fs/ext4/balloc-test.c | 2362 ++++++++++++++++++++++ fs/ext4/balloc.c | 11 +- fs/ext4/bitmap.c | 5 + fs/ext4/block_validity-test.c | 1595 +++++++++++++++ fs/ext4/block_validity.c | 11 +- fs/ext4/crypto.c | 4 + fs/ext4/dir-test.c | 992 ++++++++++ fs/ext4/dir.c | 37 + fs/ext4/ext4.h | 251 ++- fs/ext4/ext4_extents.h | 21 + fs/ext4/ext4_jbd2.c | 17 + fs/ext4/extents-test.c | 2601 ++++++++++++++++++++++++- fs/ext4/extents.c | 94 +- fs/ext4/extents_status-test.c | 1640 ++++++++++++++++ fs/ext4/extents_status.c | 22 + fs/ext4/fast_commit-test.c | 2668 +++++++++++++++++++++++++ fs/ext4/fast_commit.c | 181 +- fs/ext4/fsmap-test.c | 787 ++++++++ fs/ext4/fsmap.c | 3 + fs/ext4/ialloc-test.c | 2714 ++++++++++++++++++++++++++ fs/ext4/ialloc.c | 96 +- fs/ext4/indirect-test.c | 1270 ++++++++++++ fs/ext4/indirect.c | 18 +- fs/ext4/inline-test.c | 1839 ++++++++++++++++++ fs/ext4/inline.c | 34 +- fs/ext4/inode-test.c | 3460 ++++++++++++++++++++++++++++++++- fs/ext4/inode.c | 191 +- fs/ext4/ioctl-test.c | 1169 +++++++++++ fs/ext4/ioctl.c | 249 ++- fs/ext4/mballoc-test.c | 1868 +++++++++++++++++- fs/ext4/mballoc.c | 214 +- fs/ext4/mballoc.h | 49 + fs/ext4/migrate-test.c | 1064 ++++++++++ fs/ext4/migrate.c | 11 + fs/ext4/mmp-test.c | 661 +++++++ fs/ext4/mmp.c | 117 +- fs/ext4/move_extent-test.c | 997 ++++++++++ fs/ext4/move_extent.c | 22 + fs/ext4/namei-test.c | 2314 ++++++++++++++++++++++ fs/ext4/namei.c | 342 ++-- fs/ext4/namei.h | 213 ++ fs/ext4/orphan-test.c | 2364 ++++++++++++++++++++++ fs/ext4/orphan.c | 12 + fs/ext4/page-io.c | 1 + fs/ext4/resize-test.c | 1341 +++++++++++++ fs/ext4/resize.c | 102 +- fs/ext4/super-test.c | 1341 +++++++++++++ fs/ext4/super.c | 276 ++- fs/ext4/sysfs-test.c | 653 +++++++ fs/ext4/sysfs.c | 55 + fs/ext4/xattr-test.c | 1813 +++++++++++++++++ fs/ext4/xattr.c | 30 +- fs/ext4/xattr.h | 2 + fs/ext4/xattr_hurd.c | 4 + fs/ext4/xattr_security.c | 4 + fs/ext4/xattr_trusted.c | 4 + fs/ext4/xattr_user.c | 4 + 59 files changed, 39827 insertions(+), 412 deletions(-) create mode 100644 fs/ext4/balloc-test.c create mode 100644 fs/ext4/block_validity-test.c create mode 100644 fs/ext4/dir-test.c create mode 100644 fs/ext4/extents_status-test.c create mode 100644 fs/ext4/fast_commit-test.c create mode 100644 fs/ext4/fsmap-test.c create mode 100644 fs/ext4/ialloc-test.c create mode 100644 fs/ext4/indirect-test.c create mode 100644 fs/ext4/inline-test.c create mode 100644 fs/ext4/ioctl-test.c create mode 100644 fs/ext4/migrate-test.c create mode 100644 fs/ext4/mmp-test.c create mode 100644 fs/ext4/move_extent-test.c create mode 100644 fs/ext4/namei-test.c create mode 100644 fs/ext4/namei.h create mode 100644 fs/ext4/orphan-test.c create mode 100644 fs/ext4/resize-test.c create mode 100644 fs/ext4/super-test.c create mode 100644 fs/ext4/sysfs-test.c create mode 100644 fs/ext4/xattr-test.c
base-commit: 93f51579e7df248780214094418f205253383cc5
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Theodore Ts'o
maintainerPATCH 1/27 ext4: add KUinit tests for fs/ext4/extents_status.c
These tests were created with the help of Gemini Pro and verified by a human.
--- fs/ext4/Makefile | 3 +- fs/ext4/extents.c | 5 - fs/ext4/extents_status-test.c | 1640 +++++++++++++++++++++++++++++++++ fs/ext4/extents_status.c | 19 + fs/ext4/inode.c | 10 + 5 files changed, 1671 insertions(+), 6 deletions(-) create mode 100644 fs/ext4/extents_status-test.c
fs/ext4/Makefile +2 -1
@@ -15,7 +15,8 @@ ext4-y := balloc.o bitmap.o block_validity.o dir.o ext4_jbd2.o extents.o \ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ - extents-test.o hash-test.o + extents-test.o hash-test.o \ + extents_status-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/extents.c +0 -5
@@ -6407,12 +6407,7 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_split_convert_extents_test);EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_ext_dirty);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ext_zeroout); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_register_shrinker); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_unregister_shrinker);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_map_create_blocks); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_init_tree); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_lookup_extent); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_insert_extent);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ext_insert_extent);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_find_extent);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_issue_zeroout);
fs/ext4/extents_status-test.c new file +1640 -0
1,640 lines not on this page · raw message
fs/ext4/extents_status.c +19 -0
@@ -2390,3 +2390,22 @@ static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, out:return (ret <0 ) ? ret : pendings; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_init_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_insert_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_cache_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_remove_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_find_extent_range); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_lookup_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_scan_range); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_scan_clu); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_register_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_unregister_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_seq_es_shrinker_info_show); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_init_pending_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_remove_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_is_pending); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_insert_delayed_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_clear_inode_es); +#endif
fs/ext4/inode.c +10 -0
@@ -350,6 +350,9 @@ void ext4_da_update_reserve_space(struct inode *inode,struct ext4_sb_info *sbi =EXT4_SB (inode->i_sb);struct ext4_inode_info *ei =EXT4_I (inode); +KUNIT_STATIC_STUB_REDIRECT (ext4_da_update_reserve_space, + inode, used, quota_claim); +spin_lock (&ei->i_block_reservation_lock);trace_ext4_da_update_reserve_space (inode, used, quota_claim);if (unlikely (used > ei->i_reserved_data_blocks)) {
@@ -1646,6 +1649,8 @@ void ext4_da_release_space(struct inode *inode, int to_free)struct ext4_sb_info *sbi =EXT4_SB (inode->i_sb);struct ext4_inode_info *ei =EXT4_I (inode); +KUNIT_STATIC_STUB_REDIRECT (ext4_da_release_space, inode, to_free); +if (!to_free)return ;/* Nothing to release, exit */
@@ -6973,3 +6978,8 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)sb_end_pagefault (inode->i_sb);return ret; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_update_reserve_space); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_release_space); +#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 01/27] ext4: add KUinit tests for fs/ext4/extents_status.c
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [Medium] ext4: data race in __es_shrink() [1] --
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [Medium] ext4: data race in __es_shrink() [1]
--
commit 45574cf43b458dd12781bdd04f9e4dfbf9ef71c4
Author: Theodore Ts'o <[email protected]>
ext4: add KUinit tests for fs/ext4/extents_status.c
This commit adds KUnit tests for the ext4 extent status tree and bigalloc pending reservations, and exports the required symbols for the test module.
Quoted 11 lines
fs/ext4/extents_status.c +3
-0@@ -2390,3 +2390,22 @@ static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, out:return (ret <0 ) ? ret : pendings; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_init_tree);
fs/ext4/extents_status.c static int __revise_pending(struct inode *inode, ext4_lblk_t lblk, · line 2405
Quoted 10 lines
fs/ext4/extents_status.c +10
-0+EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_insert_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_cache_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_remove_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_find_extent_range); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_lookup_extent); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_scan_range); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_scan_clu); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_register_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_es_unregister_shrinker); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_seq_es_shrinker_info_show);
[Severity: Medium]
This problem wasn't introduced by this patch, but can concurrent shrinker runs race on the 64-bit statistics fields in sbi->s_es_stats [1]?
fs/ext4/extents_status.c:__es_shrink() {
...
spin_unlock(&sbi->s_es_lock);
...
out:
scan_time = ktime_to_ns(ktime_sub(ktime_get(), start_time));
if (likely(es_stats->es_stats_scan_time))
es_stats->es_stats_scan_time = (scan_time +
es_stats->es_stats_scan_time*3) / 4;
else
es_stats->es_stats_scan_time = scan_time;
if (scan_time > es_stats->es_stats_max_scan_time)
es_stats->es_stats_max_scan_time = scan_time;
if (likely(es_stats->es_stats_shrunk))
es_stats->es_stats_shrunk = (nr_shrunk +
es_stats->es_stats_shrunk*3) / 4;
else
es_stats->es_stats_shrunk = nr_shrunk;
}__es_shrink() drops sbi->s_es_lock before reaching the out label, so concurrent memory reclaim threads can update es_stats_scan_time, es_stats_max_scan_time, and es_stats_shrunk simultaneously without synchronization. On 32-bit architectures, these plain 64-bit read-modify-write accesses can tear and corrupt the shrinker metrics.
[1] https://sashiko.dev/#/bug/linux-ffbda43a-8d25-4cbd-be48-64c4f05ffa5f
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Theodore Ts'o
maintainerPATCH 2/27 ext4: add KUnit tests for fs/ext4/extents.c
In reply to Theodore Ts'oExpand the ext4_extents_test KUnit test suite in fs/ext4/extents-test.c to cover the core extent tree operations in fs/ext4/extents.c:
- 48-bit physical block encoding/decoding (ext4_ext_pblock, ext4_ext_store_pblock, ext4_idx_pblock, ext4_idx_store_pblock) and unwritten extent length encoding (ext4_ext_mark_unwritten, ext4_ext_is_unwritten, ext4_ext_get_actual_len, ext4_ext_mark_initialized).
- Extent tree initialization (ext4_ext_tree_init) and header/entry validation (ext4_ext_check_inode, __ext4_ext_check) across 13 parameterized corruption cases (magic, depth, max, entries, empty non-root index, zero-length extent, logical block wrap-around, out-of-bounds physical blocks, overlapping/unsorted extents and indexes, and parent/leaf logical block mismatch).
- Metadata checksum calculation and verification on external extent blocks when EXT4_FEATURE_RO_COMPAT_METADATA_CSUM is enabled.
- Root and multi-level (depth >= 1) extent tree lookup and navigation (ext4_find_extent, ext4_ext_search_left, ext4_ext_search_right, ext4_ext_next_allocated_block, ext4_ext_next_leaf_block) and extent status precaching (ext4_ext_precache) using in-memory simulated metadata buffer_heads via an ext4_ext_getblk() KUnit static stub.
- Extent merge rules (ext4_can_extents_be_merged) and insertion (ext4_ext_insert_extent), including forward/backward/three-way merging, nomerge flag handling, tree depth growth (ext4_ext_grow_indepth), node splitting (ext4_ext_split), and tree collapse back into the root inode (ext4_ext_try_to_merge_up).
- Extent space removal and truncation (ext4_ext_remove_space, ext4_ext_truncate) across tail truncates, partial trims, middle hole punches, multi-level index removal (ext4_ext_rm_idx), and bigalloc partial-cluster nofree and pending cluster rereservation (ext4_rereserve_cluster).
- Block mapping and allocation (ext4_ext_map_blocks), including hole lookup, delayed-extent hole adjustment, QUERY_LAST_IN_LEAF, block allocation, overlap clamping, ENOSPC handling, unwritten-to-written conversion with neighbor merging, and bigalloc implied cluster allocation (ext4_map_cluster_from_extent).
- Extent shifting (ext4_ext_shift_extents) for FALLOC_FL_COLLAPSE_RANGE and FALLOC_FL_INSERT_RANGE, extent swapping (ext4_swap_extents), cluster mapping queries (ext4_clu_mapped), JBD2 transaction credit calculations (ext4_ext_calc_credits_for_single_extent, ext4_ext_index_trans_blocks), and fast-commit replay helpers (ext4_ext_replay_update_ex, ext4_ext_replay_shrink_inode, ext4_ext_replay_set_iblocks).
- Fix ext4_ext_path memory leaks in the existing test_split_convert() helpers and isolate the mock extent status shrinker from background reclaim.
--- fs/ext4/ext4_extents.h | 21 + fs/ext4/ext4_jbd2.c | 8 + fs/ext4/extents-test.c | 1886 ++++++++++++++++++++++++++++++++++++++-- fs/ext4/extents.c | 83 +- fs/ext4/inode.c | 5 + fs/ext4/mballoc.c | 7 + 6 files changed, 1938 insertions(+), 72 deletions(-)
fs/ext4/ext4_extents.h +21 -0
@@ -268,6 +268,8 @@ extern int __ext4_ext_dirty(const char *where, unsigned int line, handle_t *handle, struct inode *inode, struct ext4_ext_path *path);extern int ext4_ext_zeroout (struct inode *inode,struct ext4_extent *ex); +extern struct buffer_head *ext4_ext_getblk (struct inode *inode, +ext4_fsblk_t pblk,gfp_t gfp_flags);#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )extern int ext4_ext_space_root_idx_test (struct inode *inode,int check); extern struct ext4_ext_path *ext4_split_convert_extents_test(
@@ -275,6 +277,25 @@ extern struct ext4_ext_path *ext4_split_convert_extents_test(struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags, unsigned int *allocated); +extern int ext4_ext_check_test (struct inode *inode, +struct ext4_extent_header *eh,int depth, +ext4_fsblk_t pblk,ext4_lblk_t lblk); +extern void ext4_extent_block_csum_set_test (struct inode *inode, +struct ext4_extent_header *eh); +extern int ext4_can_extents_be_merged_test (struct inode *inode, +struct ext4_extent *ex1, +struct ext4_extent *ex2); +extern int ext4_ext_search_left_test (struct inode *inode, +struct ext4_ext_path *path, +ext4_lblk_t *logical,ext4_fsblk_t *phys); +extern int ext4_ext_search_right_test (struct inode *inode, +struct ext4_ext_path *path, +ext4_lblk_t *logical,ext4_fsblk_t *phys, +struct ext4_extent *ret_ex,int flags); +extern ext4_lblk_t ext4_ext_next_leaf_block_test (struct ext4_ext_path *path); +extern int ext4_ext_shift_extents_test (struct inode *inode,handle_t *handle, +ext4_lblk_t start,ext4_lblk_t shift, +enum SHIFT_DIRECTION direction);#endif #endif /* _EXT4_EXTENTS */
fs/ext4/ext4_jbd2.c +8 -0
@@ -4,6 +4,7 @@*/ #include "ext4_jbd2.h" +#include <kunit/static_stub.h> #include <trace/events/ext4.h>
@@ -379,6 +380,9 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, {int err =0 ; +KUNIT_STATIC_STUB_REDIRECT (__ext4_handle_dirty_metadata, where, line, + handle, inode, bh); +might_sleep ();set_buffer_meta (bh);
@@ -431,3 +435,7 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, }return err; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_handle_dirty_metadata); +#endif
fs/ext4/extents-test.c +1818 -68
2,062 lines not on this page · raw message
fs/ext4/extents.c +79 -4
124 lines not on this page · raw message
fs/ext4/inode.c +5 -0
@@ -6699,6 +6699,9 @@ int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,struct ext4_sb_info *sbi =EXT4_SB (inode->i_sb);int err; +KUNIT_STATIC_STUB_REDIRECT (__ext4_mark_inode_dirty, handle, inode, + func, line); +might_sleep ();trace_ext4_mark_inode_dirty (inode, _RET_IP_); err =ext4_reserve_inode_write (handle, inode, &iloc);
@@ -6982,4 +6985,6 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_update_reserve_space);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_release_space); +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_mark_inode_dirty); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_map_blocks);#endif
fs/ext4/mballoc.c +7 -0
@@ -6239,6 +6239,8 @@ ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,int retries =0 ;u64 seq; +KUNIT_STATIC_STUB_REDIRECT (ext4_mb_new_blocks, handle, ar, errp); +might_sleep (); sb = ar->inode->i_sb; sbi =EXT4_SB (sb);
@@ -6697,6 +6699,9 @@ void ext4_free_blocks(handle_t *handle, struct inode *inode,unsigned int overflow;struct ext4_sb_info *sbi; +KUNIT_STATIC_STUB_REDIRECT (ext4_free_blocks, handle, inode, bh, block, + count, flags); + sbi =EXT4_SB (sb);if (bh) {
@@ -7281,4 +7286,6 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_block_bitmap_nowait);EXPORT_SYMBOL_FOR_EXT4_TEST (mb_set_bits);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fc_init_inode);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_mark_context); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_new_blocks); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_blocks);#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 02/27] ext4: add KUnit tests for fs/ext4/extents.c
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] ext4: use-after-free of sb->s_bdev after deactivate_super() in extents_kunit_exit() - [Low] ext4…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] ext4: use-after-free of sb->s_bdev after deactivate_super() in extents_kunit_exit()
- [Low] ext4: stale i_es_tree entries and warnings in extents-test.c KUnit tests
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Medium] ext4: data block leak in ext4_ext_map_blocks() on -ENOMEM extent insert [1]
--
commit 228dbe39d61604db8aef3d32655ec0608aa3210f
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/extents.c
This commit expands the ext4_extents_test KUnit suite in fs/ext4/extents-test.c to cover extent tree initialization, validation, navigation, insertion, merging, removal, block mapping, shifting, swapping, and fast-commit replay helpers, while adding KUnit static stubs for metadata and block allocation helpers.
Quoted 4 lines
fs/ext4/extents-test.c +0
-0
[ ... ]
Quoted 1 line
fs/ext4/extents-test.c +0
-0@@ -142,33 +182,201 @@ static struct file_system_type ext_fs_type = {
[ ... ]
Quoted 19 lines
static void
extents_kunit_exit(struct kunit *test){fs/ext4/extents-test.c +11
-1struct ext4_sb_info *sbi; +struct super_block *sb;if (!k_ctx.k_ei)return ; - sbi = k_ctx.k_ei->vfs_inode.i_sb->s_fs_info; + sb = k_ctx.k_ei->vfs_inode.i_sb; + sbi = sb->s_fs_info; + +if (k_ctx.k_ei2) { +ext_cleanup_inode (&k_ctx.k_ei2->vfs_inode); +kfree (k_ctx.k_ei2); + } +ext_cleanup_inode (&k_ctx.k_ei->vfs_inode); + +percpu_counter_destroy (&sbi->s_freeclusters_counter);
fs/ext4/extents-test.c static struct file_system_type ext_fs_type = { · line 263
Quoted 10 lines
fs/ext4/extents-test.c +7
-1+percpu_counter_destroy (&sbi->s_dirtyclusters_counter);ext4_es_unregister_shrinker (sbi); -deactivate_super (sbi->s_sb); +deactivate_super (sb); + +kfree (k_ctx.meta_blocks); +kfree (sbi->s_es); +kfree (sb->s_bdev->bd_mapping); +kfree (sb->s_bdev);kfree (sbi);
[Severity: Low]
Can dereferencing sb->s_bdev after deactivate_super(sb) cause a use-after-free?
deactivate_super(sb) drops the final active and passive references on sb via kill_anon_super() and put_super(), queuing sb for RCU and workqueue destruction (destroy_super_work() -> kfree(sb)). Freeing sb->s_bdev->bd_mapping and sb->s_bdev before calling deactivate_super(sb), as the error path in extents_kunit_init() does, avoids reading from sb after its reference count reaches zero.
[ ... ]
Quoted 30 lines
fs/ext4/extents-test.c +30
-0+static void test_convert_to_initialized_abut_neighbors (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct ext4_extent_header *eh =ext_inode_hdr (inode); +struct ext4_extent *ex; +struct ext4_map_blocks map = {}; +int ret; + +EXT4_SB (inode->i_sb)->s_extent_max_zeroout_kb =0 ; +ext_reset_tree (inode); + +/* +* Setup: [10, 12) @ 100 (written), [12, 16) @ 102 (unwritten), +* [16, 18) @ 106 (written). +*/ +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,10 ,2 ,100 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,12 ,4 ,102 , true,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,16 ,2 ,106 , false,0 ),0 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),3 ); + +/* +* Convert head of unwritten extent [12, 14): transfers 2 blocks to +* left neighbor [10, 12) -> [10, 14) written, [14, 16) unwritten. +*/ + map.m_lblk =12 ; + map.m_len =2 ; + map.m_flags =0 ; +down_write (&EXT4_I (inode)->i_data_sem); + ret =ext4_ext_map_blocks (NULL , inode, &map,EXT4_GET_BLOCKS_CREATE ); +up_write (&EXT4_I (inode)->i_data_sem);
[ ... ]
fs/ext4/extents-test.c static void test_split_convert(struct kunit *test) · line 2216
Quoted 13 lines
fs/ext4/extents-test.c +13
-0+static void test_ext_fast_commit_replay (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct ext4_extent_header *eh =ext_inode_hdr (inode); +struct ext4_extent *ex; +int err; + +ext_reset_tree (inode); +/* Start with unwritten extent [10, 20) @ 100 */ +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,10 ,10 ,100 , true,0 ),0 ); + +/* Replay update converting middle [12, 16) to written @ 102 */ + err =ext4_ext_replay_update_ex (inode,12 ,4 ,0 ,102 );
[Severity: Low]
Do test_ext_fast_commit_replay() and test_convert_to_initialized_abut_neighbors() leave stale unwritten entries in i_es_tree that trigger ext4_es_cache_extent() conflict warnings?
In test_ext_fast_commit_replay(), EXT4_FC_REPLAY is not set in EXT4_SB(inode->i_sb)->s_mount_state. The first ext4_ext_replay_update_ex() call invokes ext4_find_extent(..., 0) -> ext4_cache_extents(), which caches [10, 20) as unwritten in i_es_tree before converting [12, 16) to written in the extent tree. Later calls to ext4_ext_replay_update_ex(), ext4_ext_replay_shrink_inode(), and ext4_ext_replay_set_iblocks() then try to cache the converted written extents over the stale unwritten entry in i_es_tree, logging ext4_warning_inode() conflict messages and causing ext4_ext_replay_set_iblocks() -> ext4_map_blocks() to hit the stale cache instead of reading the extent tree.
Similarly, test_convert_to_initialized_abut_neighbors() calls ext4_ext_map_blocks() directly without EXT4_EX_NOCACHE, bypassing ext4_map_blocks() where i_es_tree is normally updated via ext4_es_insert_extent(), so the second ext4_ext_map_blocks() call also hits an ext4_es_cache_extent() conflict warning on [10, 14).
Quoted 4 lines
fs/ext4/extents.c +0
-0
[ ... ]
fs/ext4/extents.c static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode, · line 1344
Quoted 8 lines
fs/ext4/extents.c +1
-1@@ -1332,7 +1339,7 @@ static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,if (newblock ==0 )return err; - bh =sb_getblk_gfp (inode->i_sb, newblock, __GFP_MOVABLE |GFP_NOFS ); + bh =ext4_ext_getblk (inode, newblock, __GFP_MOVABLE |GFP_NOFS );if (unlikely (!bh))return -ENOMEM ;
[Severity: Medium]
This problem wasn't introduced by this patch, but does ext4_ext_map_blocks() leak newly allocated data blocks [1] when ext4_ext_insert_extent() fails with -ENOMEM?
Memory allocations in ext4_ext_insert_extent(), such as in ext4_ext_create_new_leaf(), happen before the new extent is inserted into the tree. However, the error path in ext4_ext_map_blocks() only calls ext4_free_blocks() when err is -EDQUOT or -ENOSPC, leaving the unreferenced blocks allocated in the block bitmap and charged to inode->i_blocks and quota on -ENOMEM:
fs/ext4/extents.c:ext4_ext_map_blocks() {
...
path = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
if (IS_ERR(path)) {
err = PTR_ERR(path);
if (allocated_clusters && (err == -EDQUOT || err == -ENOSPC)) {
...
ext4_free_blocks(handle, inode, NULL, newblock,
EXT4_C2B(sbi, allocated_clusters),
fb_flags);
}
goto out;
}
...
}[1] https://sashiko.dev/#/bug/linux-d55bdb55-6626-49d1-965d-23a09e7996e3
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Theodore Ts'o
maintainerPATCH 3/27 ext4: add KUnit tests for ext4_ext_split() leaf and index splitting
In reply to Theodore Ts'oCommit 7831b3664109 ("ext4: add KUnit tests for fs/ext4/extents.c") updated both block-allocation paths in ext4_ext_split() to call ext4_ext_getblk() and noted node splitting in the commit message, but none of the test cases in fs/ext4/extents-test.c actually reached ext4_ext_split(). In test_insert_extent_grow_and_merge_up(), inserting a 5th extent into a full depth-0 root triggers ext4_ext_grow_indepth(), moving the 4 extents into an external leaf block with eh_max == 340 and returning from ext4_ext_create_new_leaf() without splitting.
Add two KUnit test cases to exercise ext4_ext_split() across leaf and intermediate index levels:
- test_insert_extent_leaf_split(): fills a depth-1 external leaf block to capacity (340 extents), inserts in the middle to trigger a leaf split that moves tail extents into a new leaf block, and then fills the second leaf and appends past its end to exercise the m == 0 leaf-addition path.
- test_insert_extent_index_split(): exercises depth 1 -> 2 tree growth followed by leaf splitting via the repeat loop in ext4_ext_create_new_leaf(), and then clamps the depth-1 index block's eh_max to exercise simultaneous leaf and intermediate index block splitting (k == 1) in ext4_ext_split().
--- fs/ext4/extents-test.c | 206 +++++++++++++++++++++++++++++++++++++++-- fs/ext4/move_extent.c | 5 + 2 files changed, 203 insertions(+), 8 deletions(-)
fs/ext4/extents-test.c +198 -8
@@ -1584,6 +1584,198 @@ static void test_insert_extent_grow_and_merge_up(struct kunit *test)KUNIT_EXPECT_EQ (test,ext4_ext_get_actual_len (&ex[0 ]),12 ); } +/* +* Verify ext4_ext_split() at depth 1 both when splitting a full leaf in the +* middle (moving tail extents to a newly allocated leaf block) and when +* appending past the end of a full leaf (m == 0). +*/ +static void test_insert_extent_leaf_split (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct ext4_extent_header *eh =ext_inode_hdr (inode); +struct ext4_ext_path *path; +int i; + +ext_reset_tree (inode); + +/* +* Insert 340 non-contiguous extents [i * 4, i * 4 + 2) @ 2000 + i * 4 +* to grow from depth 0 to depth 1 and completely fill the external +* 4096-byte leaf block (eh_max = 340). +*/ +for (i =0 ; i <340 ; i++) { +KUNIT_ASSERT_EQ_MSG (test, +ext_insert_one (inode, i *4 ,2 , +2000 + i *4 , false,0 ), +0 ,"i=%d" , i); + } +KUNIT_EXPECT_EQ (test,ext_depth (inode),1 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),1 ); + +/* +* Insert [402, 403) @ 9000 in the middle of the full leaf between +* [400, 402) and [404, 406): triggers ext4_ext_split() with m = 239, +* moving [404..1358) into a newly allocated second leaf block. +*/ + k_ctx.alloc_calls =0 ; +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,402 ,1 ,9000 , false,0 ),0 ); +KUNIT_EXPECT_EQ (test, k_ctx.alloc_calls,1U ); +KUNIT_EXPECT_EQ (test,ext_depth (inode),1 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),2 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT_FIRST_INDEX (eh)[0 ].ei_block),0U ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT_FIRST_INDEX (eh)[1 ].ei_block), +404U ); +KUNIT_EXPECT_EQ (test,ext4_ext_check_inode (inode),0 ); + + path =ext4_find_extent (inode,402 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test,le16_to_cpu (path[1 ].p_hdr->eh_entries),102 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[1 ].p_ext->ee_block),402U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[1 ].p_ext),9000ULL ); +ext4_free_ext_path (path); + + path =ext4_find_extent (inode,404 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test,le16_to_cpu (path[1 ].p_hdr->eh_entries),239 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[1 ].p_ext->ee_block),404U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[1 ].p_ext),2404ULL ); +ext4_free_ext_path (path); + +/* +* Fill the second leaf to capacity (239 + 101 = 340 entries), then +* append [1764, 1766) @ 3764 past its end to exercise ext4_ext_split() +* with m == 0 (adding a new leaf without moving existing entries). +*/ +for (i =340 ; i <441 ; i++) { +KUNIT_ASSERT_EQ_MSG (test, +ext_insert_one (inode, i *4 ,2 , +2000 + i *4 , false,0 ), +0 ,"i=%d" , i); + } + k_ctx.alloc_calls =0 ; +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,1764 ,2 ,3764 , false,0 ), +0 ); +KUNIT_EXPECT_EQ (test, k_ctx.alloc_calls,1U ); +KUNIT_EXPECT_EQ (test,ext_depth (inode),1 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),3 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT_FIRST_INDEX (eh)[2 ].ei_block), +1764U ); + + path =ext4_find_extent (inode,1764 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test,le16_to_cpu (path[1 ].p_hdr->eh_entries),1 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[1 ].p_ext->ee_block),1764U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[1 ].p_ext),3764ULL ); +ext4_free_ext_path (path); +} + +/* +* Verify multi-level tree growth from depth 1 -> 2 followed by leaf split +* (ext4_ext_create_new_leaf repeat loop), and intermediate index block +* splitting in ext4_ext_split() when both leaf and depth-1 index are full. +*/ +static void test_insert_extent_index_split (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct ext4_extent_header *eh =ext_inode_hdr (inode); +struct ext4_extent_idx *idx; +struct ext4_ext_path *path; +struct buffer_head *bh; +int i; + +ext_reset_tree (inode); + +/* +* Build a full depth-1 root index (eh_entries = eh_max = 4) pointing +* to 4 full leaf blocks (eh_entries = eh_max = 2). +*/ + eh->eh_depth =cpu_to_le16 (1 ); + eh->eh_entries =cpu_to_le16 (4 ); + eh->eh_max =cpu_to_le16 (ext4_ext_space_root_idx_test (inode,0 )); + idx =EXT_FIRST_INDEX (eh); + +for (i =0 ; i <4 ; i++) { +struct ext4_extent_header *leaf_eh; +struct ext4_extent *ex; +ext4_lblk_t lblk =10 + i *10 ; + + idx[i].ei_block =cpu_to_le32 (lblk); +ext4_idx_store_pblock (&idx[i],EXT_META_BASE_PBLK + i); + + bh =ext4_ext_getblk_stub (inode,EXT_META_BASE_PBLK + i, +GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, bh); + leaf_eh =ext_block_hdr (bh); + leaf_eh->eh_magic =EXT4_EXT_MAGIC ; + leaf_eh->eh_depth =0 ; + leaf_eh->eh_entries =cpu_to_le16 (2 ); + leaf_eh->eh_max =cpu_to_le16 (2 ); + ex =EXT_FIRST_EXTENT (leaf_eh); + ex[0 ].ee_block =cpu_to_le32 (lblk); + ex[0 ].ee_len =cpu_to_le16 (2 ); +ext4_ext_store_pblock (&ex[0 ],2000 + i *10 ); + ex[1 ].ee_block =cpu_to_le32 (lblk +4 ); + ex[1 ].ee_len =cpu_to_le16 (2 ); +ext4_ext_store_pblock (&ex[1 ],2004 + i *10 ); +brelse (bh); + } + +/* +* Inserting [48, 50) @ 2038 finds both leaf 3 and the root index full: +* ext4_ext_grow_indepth() grows depth 1 -> 2, and the repeat loop in +* ext4_ext_create_new_leaf() calls ext4_ext_split() at depth 1. +*/ + k_ctx.alloc_calls =0 ; +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,48 ,2 ,2038 , false,0 ),0 ); +KUNIT_EXPECT_EQ (test, k_ctx.alloc_calls,2U ); +KUNIT_EXPECT_EQ (test,ext_depth (inode),2 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),1 ); + +/* +* Clamp the depth-1 index block's eh_max to its current 5 entries so +* inserting [12, 13) @ 9000 into full leaf 0 splits both leaf 0 and +* the intermediate depth-1 index block (depth = 2, at = 0, k = 1). +*/ + bh =ext4_ext_getblk_stub (inode,ext4_idx_pblock (EXT_FIRST_INDEX (eh)), +GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, bh); +KUNIT_ASSERT_EQ (test,le16_to_cpu (ext_block_hdr (bh)->eh_entries),5 ); +ext_block_hdr (bh)->eh_max =cpu_to_le16 (5 ); +brelse (bh); + + k_ctx.alloc_calls =0 ; +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,12 ,1 ,9000 , false,0 ),0 ); +KUNIT_EXPECT_EQ (test, k_ctx.alloc_calls,2U ); +KUNIT_EXPECT_EQ (test,ext_depth (inode),2 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (eh->eh_entries),2 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT_FIRST_INDEX (eh)[0 ].ei_block), +10U ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (EXT_FIRST_INDEX (eh)[1 ].ei_block), +14U ); +KUNIT_EXPECT_EQ (test,ext4_ext_check_inode (inode),0 ); + + path =ext4_find_extent (inode,12 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test, path->p_depth,2 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[2 ].p_ext->ee_block),12U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[2 ].p_ext),9000ULL ); +ext4_free_ext_path (path); + + path =ext4_find_extent (inode,14 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test, path->p_depth,2 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[2 ].p_ext->ee_block),14U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[2 ].p_ext),2004ULL ); +ext4_free_ext_path (path); + + path =ext4_find_extent (inode,48 ,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR_OR_NULL (path)); +KUNIT_EXPECT_EQ (test, path->p_depth,2 ); +KUNIT_EXPECT_EQ (test,le32_to_cpu (path[2 ].p_ext->ee_block),48U ); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (path[2 ].p_ext),2038ULL ); +ext4_free_ext_path (path); +} +/* * Verify ext4_ext_remove_space() for middle-of-extent hole punching, full * extent removal with left-scooting, and ext4_ext_truncate() tail removal.
@@ -2073,17 +2265,13 @@ static void test_swap_extents(struct kunit *test)KUNIT_ASSERT_EQ (test,ext_insert_one (inode1,10 ,10 ,100 , false,0 ),0 );KUNIT_ASSERT_EQ (test,ext_insert_one (inode2,10 ,10 ,200 , false,0 ),0 ); -inode_lock (inode1); -inode_lock (inode2); -down_write (&EXT4_I (inode1)->i_data_sem); -down_write (&EXT4_I (inode2)->i_data_sem); +lock_two_nondirectories (inode1, inode2); +ext4_double_down_write_data_sem (inode1, inode2); replaced =ext4_swap_extents (NULL , inode1, inode2,12 ,12 ,5 ,1 , &err); -up_write (&EXT4_I (inode2)->i_data_sem); -up_write (&EXT4_I (inode1)->i_data_sem); -inode_unlock (inode2); -inode_unlock (inode1); +ext4_double_up_write_data_sem (inode1, inode2); +unlock_two_nondirectories (inode1, inode2);KUNIT_EXPECT_EQ (test, err,0 );KUNIT_EXPECT_EQ (test, replaced,5 );
@@ -2787,6 +2975,8 @@ static struct kunit_case extents_test_cases[] = {KUNIT_CASE (test_can_extents_be_merged),KUNIT_CASE (test_insert_extent_merge_and_nomerge),KUNIT_CASE (test_insert_extent_grow_and_merge_up), +KUNIT_CASE (test_insert_extent_leaf_split), +KUNIT_CASE (test_insert_extent_index_split),KUNIT_CASE (test_remove_space_tail_and_hole_punch),KUNIT_CASE (test_remove_space_multilevel_collapse), KUNIT_CASE(test_remove_space_bigalloc_partial_cluster),
fs/ext4/move_extent.c +5 -0
@@ -656,3 +656,8 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk,unlock_two_nondirectories (orig_inode, donor_inode);return ret; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_down_write_data_sem); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_up_write_data_sem); +#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 03/27] ext4: add KUnit tests for ext4_ext_split() leaf and index splitting
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: unexplained test_swap_extents() changes and stale Fixes SHA --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: unexplained test_swap_extents() changes and stale Fixes SHA
--
commit 55141b7904f9009059aca2d2a02dc5c501ed9bde
Author: Theodore Ts'o <[email protected]>
Quoted 32 lines
ext4: add KUnit tests for
ext4_ext_split()leaf and index splittingCommit
7831b3664109("ext4: add KUnit tests forfs/ext4/extents.c") updated both block-allocation paths inext4_ext_split()to callext4_ext_getblk()and noted node splitting in the commit message, but none of the test cases infs/ext4/extents-test.cactually reachedext4_ext_split(). Intest_insert_extent_grow_and_merge_up(), inserting a 5th extent into a full depth-0 root triggersext4_ext_grow_indepth(), moving the 4 extents into an external leaf block witheh_max== 340 and returning fromext4_ext_create_new_leaf()without splitting.Add two KUnit test cases to exercise
ext4_ext_split()across leaf and intermediate index levels:-
test_insert_extent_leaf_split(): fills a depth-1 external leaf block to capacity (340 extents), inserts in the middle to trigger a leaf split that moves tail extents into a new leaf block, and then fills the second leaf and appends past its end to exercise the m == 0 leaf-addition path.
-test_insert_extent_index_split(): exercises depth 1 -> 2 tree growth followed by leaf splitting via the repeat loop inext4_ext_create_new_leaf(), and then clamps the depth-1 index block'seh_maxto exercise simultaneous leaf and intermediate index block splitting (k == 1) inext4_ext_split().Fixes 7831b3664109 ("ext4: add KUnit tests for fs/ext4/extents.c")Signed-off-by Theodore Ts'o <[email protected]>fs/ext4/extents-test.c +0
-0
[ ... ]
Quoted 22 lines
fs/ext4/extents-test.c +4
-8@@ -2073,17 +2265,13 @@ static void test_swap_extents(struct kunit *test)KUNIT_ASSERT_EQ (test,ext_insert_one (inode1,10 ,10 ,100 , false,0 ),0 );KUNIT_ASSERT_EQ (test,ext_insert_one (inode2,10 ,10 ,200 , false,0 ),0 ); -inode_lock (inode1); -inode_lock (inode2); -down_write (&EXT4_I (inode1)->i_data_sem); -down_write (&EXT4_I (inode2)->i_data_sem); +lock_two_nondirectories (inode1, inode2); +ext4_double_down_write_data_sem (inode1, inode2); replaced =ext4_swap_extents (NULL , inode1, inode2,12 ,12 ,5 ,1 , &err); -up_write (&EXT4_I (inode2)->i_data_sem); -up_write (&EXT4_I (inode1)->i_data_sem); -inode_unlock (inode2); -inode_unlock (inode1); +ext4_double_up_write_data_sem (inode1, inode2); +unlock_two_nondirectories (inode1, inode2);KUNIT_EXPECT_EQ (test, err,0 );KUNIT_EXPECT_EQ (test, replaced,5 );
[ ... ]
fs/ext4/move_extent.c int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk, · line 663
Quoted 13 lines
fs/ext4/move_extent.c +5
-0@@ -656,3 +656,8 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk,unlock_two_nondirectories (orig_inode, donor_inode);return ret; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_down_write_data_sem); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_up_write_data_sem); +#endif
[Severity: Low]
This isn't a bug, but the commit message does not mention updating test_swap_extents() to use lock_two_nondirectories() and ext4_double_down_write_data_sem() (and exporting those helpers from fs/ext4/move_extent.c) to avoid lockdep warnings on i_rwsem and i_data_sem.
Also, the commit message and Fixes: trailer cite a stale pre-rebase sha for commit "ext4: add KUnit tests for fs/ext4/extents.c" rather than the parent commit in this branch.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Theodore Ts'o
maintainerPATCH 4/27 ext4: add KUnit tests for fs/ext4/xattr.c
In reply to Theodore Ts'oAdd the ext4_xattr_test KUnit test suite in fs/ext4/xattr-test.c to exercise the core extended attribute operations in fs/ext4/xattr.c without requiring a mounted block device:
- Entry/value sizing macros (EXT4_XATTR_LEN, EXT4_XATTR_SIZE, EXT4_XATTR_MIN_LARGE_EA_SIZE), EXT4_INODE_HAS_XATTR_SPACE boundary checks, and xattr_sem locking helpers (ext4_write_lock_xattr, ext4_write_trylock_xattr, ext4_write_unlock_xattr) preserving EXT4_STATE_NO_EXPAND.
- In-inode xattr validation (xattr_check_inode / __xattr_check_inode) across 11 parameterized valid and corrupted on-disk layouts (bad magic, truncated headers, out-of-bounds names, unterminated entry lists, non-zero offset on EA inode entries, and overlapping or out-of-bounds value ranges).
- In-inode (ibody) get/set operations (ext4_xattr_get, ext4_xattr_ibody_get, ext4_xattr_set_handle, ext4_xattr_set), XATTR_CREATE and XATTR_REPLACE flag enforcement, EXT4_STATE_NEW raw inode initialization, superblock EXT4_FEATURE_COMPAT_EXT_ATTR update, and the identical-value fastpath (ext4_xattr_value_same).
- In-inode value replacement (same padded size vs. shifted offsets), zero-length values, entry removal, and EXT4_I(inode)->i_inline_off adjustment when system.data is present.
- External xattr block allocation, entry sorting by (e_name_index, e_name_len, e_name), migration from ibody to external block, EXT4_XATTR_BLOCK_RESERVE enforcement when ea_inode is enabled, and external block header and metadata CRC32C checksum verification.
- External xattr block mb_cache deduplication across inodes, copy-on-write cloning when modifying a shared block, and EXT4_XATTR_REFCOUNT_MAX reuse bit transitions.
- Attribute listing (ext4_listxattr) across ibody and external block entries, and user/hurd/trusted xattr handler prefix and mount-option filtering.
- Large xattr inode (EXT4_FEATURE_INCOMPAT_EA_INODE) multi-block write/read, 64-bit refcount and hash encoding, mb_cache deduplication, reference decrement to zero, and ext4_evict_ea_inode() cache cleanup.
- EA inode hash verification (including legacy signed-char name hash fallback), ext4_xattr_inode_iget() corruption checks, and Lustre-style EA inode compatibility.
- Inode quota usage calculation (ext4_get_inode_usage), journal credit estimation (__ext4_xattr_set_credits, ext4_xattr_set_credits), extra isize expansion (ext4_expand_extra_isize_ea) for in-place shifts and external block eviction, inode xattr deletion (ext4_xattr_delete_inode), and error-injection rollback paths.
Export the tested xattr entry points with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_xattr_getblk, ext4_sb_bread, ext4_map_blocks, ext4_getblk, ext4_get_inode_loc, ext4_mark_iloc_dirty, __ext4_iget, and __ext4_new_inode.
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 2 + fs/ext4/ialloc.c | 9 + fs/ext4/inline.c | 4 + fs/ext4/inode.c | 17 +- fs/ext4/super.c | 11 +- fs/ext4/xattr-test.c | 1801 +++++++++++++++++++++++++++++++++++++++ fs/ext4/xattr.c | 30 +- fs/ext4/xattr.h | 2 + fs/ext4/xattr_hurd.c | 4 + fs/ext4/xattr_trusted.c | 4 + fs/ext4/xattr_user.c | 4 + 12 files changed, 1886 insertions(+), 4 deletions(-) create mode 100644 fs/ext4/xattr-test.c
fs/ext4/Makefile +1 -1
@@ -16,7 +16,7 @@ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ - extents_status-test.o + extents_status-test.o xattr-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +2 -0
@@ -4072,6 +4072,8 @@ extern int ext4_block_write_begin(handle_t *handle, struct folio *folio,#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )#define EXPORT_SYMBOL_FOR_EXT4_TEST (sym) \ EXPORT_SYMBOL_FOR_MODULES(sym, "ext4-test") +#else +#define EXPORT_SYMBOL_FOR_EXT4_TEST (sym)#endif #endif /* __KERNEL__ */
fs/ext4/ialloc.c +9 -0
@@ -23,6 +23,7 @@#include <linux/bitops.h> #include <linux/blkdev.h> #include <linux/cred.h> +#include <kunit/static_stub.h> #include <asm/byteorder.h>
@@ -953,6 +954,10 @@ struct inode *__ext4_new_inode(struct mnt_idmap *idmap,struct ext4_group_info *grp =NULL ;bool encrypt = false; +KUNIT_STATIC_STUB_REDIRECT (__ext4_new_inode, idmap, handle, dir, mode, + qstr, goal, owner, i_flags, handle_type, + line_no, nblocks); +/* Cannot create files in a deleted directory */ if (!dir || !dir->i_nlink)return ERR_PTR (-EPERM );
@@ -1630,3 +1635,7 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group, out:return ret; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_new_inode); +#endif
fs/ext4/inline.c +4 -0
@@ -2016,3 +2016,7 @@ int ext4_convert_inline_data(struct inode *inode)brelse (iloc.bh);return error; } + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_find_inline_data_nolock); +#endif
fs/ext4/inode.c +16 -1
@@ -713,6 +713,8 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode,memcpy (&orig_map, map,sizeof (*map));#endif +KUNIT_STATIC_STUB_REDIRECT (ext4_map_blocks, handle, inode, map, flags); + map->m_flags =0 ;ext_debug (inode,"flag 0x%x, max_blocks %u, logical block %lu\n" , flags, map->m_len, (unsigned long ) map->m_lblk);
@@ -863,6 +865,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, map->m_len - 1);return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_map_blocks);/* * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
@@ -985,6 +988,9 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,bool nowait = map_flags &EXT4_GET_BLOCKS_CACHED_NOWAIT ;int err; +KUNIT_STATIC_STUB_REDIRECT (ext4_getblk, handle, inode, block, + map_flags); +ASSERT ((EXT4_SB (inode->i_sb)->s_mount_state &EXT4_FC_REPLAY ) || handle !=NULL || create ==0 );ASSERT (create ==0 || !nowait);
@@ -1047,6 +1053,7 @@ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,brelse (bh);return ERR_PTR (err); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_getblk);struct buffer_head *ext4_bread (handle_t *handle,struct inode *inode,ext4_lblk_t block,int map_flags)
@@ -5051,6 +5058,8 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)ext4_fsblk_t err_blk =0 ;int ret; +KUNIT_STATIC_STUB_REDIRECT (ext4_get_inode_loc, inode, iloc); + ret =__ext4_get_inode_loc (inode->i_sb, inode->i_ino, inode, iloc, &err_blk);
@@ -5060,6 +5069,7 @@ int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_inode_loc);/* * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc().
@@ -5336,6 +5346,8 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,gid_t i_gid;projid_t i_projid; +KUNIT_STATIC_STUB_REDIRECT (__ext4_iget, sb, ino, flags, function, line); +if ((!(flags &EXT4_IGET_SPECIAL ) &&is_special_ino (sb, ino)) || (ino <EXT4_ROOT_INO ) || (ino >le32_to_cpu (es->s_inodes_count))) {
@@ -5704,6 +5716,7 @@ struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,iget_failed (inode);return ERR_PTR (ret); } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_iget); static void __ext4_update_other_inode_time(struct super_block *sb, unsigned long orig_ino,
@@ -6464,6 +6477,8 @@ int ext4_mark_iloc_dirty(handle_t *handle,struct super_block *sb = inode->i_sb;int err =0 ; +KUNIT_STATIC_STUB_REDIRECT (ext4_mark_iloc_dirty, handle, inode, iloc); + err =ext4_emergency_state (sb);if (unlikely (err)) {put_bh (iloc->bh);
@@ -6497,6 +6512,7 @@ int ext4_mark_iloc_dirty(handle_t *handle, }return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mark_iloc_dirty);/* * On success, We end up with an outstanding reference count against
@@ -6986,5 +7002,4 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_update_reserve_space);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_release_space);EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_mark_inode_dirty); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_map_blocks);#endif
fs/ext4/super.c +10 -1
@@ -49,6 +49,7 @@#include <linux/fs_context.h> #include <linux/fs_parser.h> #include <linux/fserror.h> +#include <kunit/static_stub.h> #include "ext4.h" #include "ext4_extents.h" /* Needed for trace points definition */
@@ -251,7 +252,11 @@ static struct buffer_head *__ext4_sb_bread_gfp(struct super_block *sb,struct buffer_head *ext4_sb_bread (struct super_block *sb,sector_t block,blk_opf_t op_flags) { -gfp_t gfp =mapping_gfp_constraint (sb->s_bdev->bd_mapping, +gfp_t gfp; + +KUNIT_STATIC_STUB_REDIRECT (ext4_sb_bread, sb, block, op_flags); + + gfp =mapping_gfp_constraint (sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE;return __ext4_sb_bread_gfp (sb, block, op_flags, gfp);
@@ -7639,3 +7644,7 @@ MODULE_DESCRIPTION("Fourth Extended Filesystem");MODULE_LICENSE ("GPL" ); module_init(ext4_init_fs) module_exit(ext4_exit_fs) + +#if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) +EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_bread); +#endif
fs/ext4/xattr-test.c new file +1801 -0
1,801 lines not on this page · raw message
fs/ext4/xattr.c +29 -1
@@ -57,6 +57,7 @@#include <linux/mbcache.h> #include <linux/quotaops.h> #include <linux/iversion.h> +#include <kunit/static_stub.h> #include "ext4_jbd2.h" #include "ext4.h" #include "xattr.h"
@@ -107,6 +108,7 @@ const struct xattr_handler * const ext4_xattr_handlers[] = { &ext4_xattr_hurd_handler, NULL }; +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_handlers);#define EA_BLOCK_CACHE (inode) (((struct ext4_sb_info *) \ inode->i_sb->s_fs_info)->s_ea_block_cache)
@@ -169,6 +171,14 @@ static void ext4_xattr_block_csum_set(struct inode *inode, bh->b_blocknr, BHDR(bh)); } +struct buffer_head *ext4_xattr_getblk (struct super_block *sb, +ext4_fsblk_t block) +{ +KUNIT_STATIC_STUB_REDIRECT (ext4_xattr_getblk, sb, block); +return sb_getblk (sb, block); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_getblk); +static inline const char *ext4_xattr_prefix (int name_index,struct dentry *dentry) {
@@ -315,6 +325,7 @@ __xattr_check_inode(struct inode *inode, struct ext4_xattr_ibody_header *header,return check_xattrs (inode,NULL ,IFIRST (header), end,IFIRST (header), function, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST (__xattr_check_inode); static int xattr_find_entry(struct inode *inode, struct ext4_xattr_entry **pentry,
@@ -493,6 +504,7 @@ void ext4_evict_ea_inode(struct inode *inode)mb_cache_entry_put (EA_INODE_CACHE (inode), oe); } } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_evict_ea_inode); static int ext4_xattr_inode_verify_hashes(struct inode *ea_inode,
@@ -693,6 +705,7 @@ ext4_xattr_ibody_get(struct inode *inode, int name_index, const char *name,brelse (iloc.bh);return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_ibody_get);/* * ext4_xattr_get()
@@ -725,6 +738,7 @@ ext4_xattr_get(struct inode *inode, int name_index, const char *name,up_read (&EXT4_I (inode)->xattr_sem);return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_get); static int ext4_xattr_list_entries(struct dentry *dentry, struct ext4_xattr_entry *entry,
@@ -841,6 +855,7 @@ ext4_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)up_read (&EXT4_I (d_inode (dentry))->xattr_sem);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_listxattr);/* * If the EXT4_FEATURE_COMPAT_EXT_ATTR feature of this file system is
@@ -912,6 +927,7 @@ int ext4_get_inode_usage(struct inode *inode, qsize_t *usage)brelse (bh);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_inode_usage);static inline size_t round_up_cluster (struct inode *inode,size_t length) {
@@ -1029,6 +1045,7 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode, }return credits; } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_xattr_set_credits);static int ext4_xattr_inode_update_ref (handle_t *handle,struct inode *ea_inode,int ref_change)
@@ -2136,7 +2153,7 @@ ext4_xattr_block_set(handle_t *handle, struct inode *inode,ea_idebug (inode,"creating block %llu" , (unsigned long long )block); - new_bh =sb_getblk (sb, block); + new_bh =ext4_xattr_getblk (sb, block);if (unlikely (!new_bh)) { error = -ENOMEM ; getblk_failed:
@@ -2252,6 +2269,7 @@ int ext4_xattr_ibody_find(struct inode *inode, struct ext4_xattr_info *i, }return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_ibody_find); int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode, struct ext4_xattr_info *i,
@@ -2302,6 +2320,7 @@ int ext4_xattr_ibody_set(handle_t *handle, struct inode *inode,ext4_put_ea_inode (ea_inode);return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_ibody_set);static int ext4_xattr_value_same (struct ext4_xattr_search *s,struct ext4_xattr_info *i)
@@ -2499,6 +2518,7 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,ext4_write_unlock_xattr (inode, &no_expand);return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_set_handle);int ext4_xattr_set_credits (struct inode *inode,size_t value_len,bool is_create,int *credits)
@@ -2526,6 +2546,7 @@ int ext4_xattr_set_credits(struct inode *inode, size_t value_len,up_read (&EXT4_I (inode)->xattr_sem);return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_set_credits);/* * ext4_xattr_set()
@@ -2574,6 +2595,7 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name,return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_set);/* * Shift the EA entries in the inode to create space for the increased
@@ -2865,6 +2887,7 @@ int ext4_expand_extra_isize_ea(struct inode *inode, int new_extra_isize, }return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_expand_extra_isize_ea);/* * ext4_xattr_delete_inode()
@@ -2973,6 +2996,7 @@ int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,brelse (bh);return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_delete_inode);/* * Worker function for deferred EA inode iput. Processes all inodes queued
@@ -3026,12 +3050,14 @@ void ext4_put_ea_inode(struct inode *inode)*/ schedule_delayed_work (&EXT4_SB (inode->i_sb)->s_ea_inode_work,1 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_put_ea_inode);void ext4_init_ea_inode_work (struct ext4_sb_info *sbi) {init_llist_head (&sbi->s_ea_inode_to_free);INIT_DELAYED_WORK (&sbi->s_ea_inode_work, ext4_ea_inode_work); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_init_ea_inode_work);/* * ext4_xattr_block_cache_insert()
@@ -3229,10 +3255,12 @@ ext4_xattr_create_cache(void) {return mb_cache_create (HASH_BUCKET_BITS ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_create_cache);void ext4_xattr_destroy_cache (struct mb_cache *cache) {if (cache)mb_cache_destroy (cache); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_destroy_cache);
fs/ext4/xattr.h +2 -0
@@ -229,3 +229,5 @@ static inline void ext4_xattr_inode_set_class(struct inode *ea_inode) { }#endif extern int ext4_get_inode_usage (struct inode *inode,qsize_t *usage); +extern struct buffer_head *ext4_xattr_getblk (struct super_block *sb, +ext4_fsblk_t block);
fs/ext4/xattr_hurd.c +4 -0
@@ -50,3 +50,7 @@ const struct xattr_handler ext4_xattr_hurd_handler = { .get = ext4_xattr_hurd_get, .set = ext4_xattr_hurd_set, }; + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_hurd_handler); +#endif
fs/ext4/xattr_trusted.c +4 -0
@@ -45,3 +45,7 @@ const struct xattr_handler ext4_xattr_trusted_handler = { .get = ext4_xattr_trusted_get, .set = ext4_xattr_trusted_set, }; + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_trusted_handler); +#endif
fs/ext4/xattr_user.c +4 -0
@@ -48,3 +48,7 @@ const struct xattr_handler ext4_xattr_user_handler = { .get = ext4_xattr_user_get, .set = ext4_xattr_user_set, }; + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_xattr_user_handler); +#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 04/27] ext4: add KUnit tests for fs/ext4/xattr.c
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] ext4: uninitialized e_name in test_xattr_check_inode() bypasses value checks - [Low] ext4: stack…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] ext4: uninitialized e_name in test_xattr_check_inode() bypasses value checks
- [Low] ext4: stack frame size warning in test_xattr_credits_usage_expand_and_delete()
- [Low] ext4: missing i_size_ordered_init() in init_mock_inode_slot() --
commit b81033fe08ff323ec6a5c24275644912bdfe1108
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/xattr.c
This commit adds a KUnit test suite in fs/ext4/xattr-test.c to exercise extended attribute operations in fs/ext4/xattr.c using static stubs and exports.
Quoted 5 lines
fs/ext4/xattr-test.c new file +0
-0
[ ... ]
Quoted 10 lines
fs/ext4/xattr-test.c new file +10
-0+static void init_mock_inode_slot (struct xattr_test_ctx *ctx, +struct mock_inode_slot *slot, +unsigned long ino) +{ +struct inode *inode = &slot->ei.vfs_inode; +struct ext4_inode *raw_inode; + +memset (slot,0 ,sizeof (*slot)); + slot->allocated = true; +
fs/ext4/xattr-test.c line 114
Quoted 10 lines
fs/ext4/xattr-test.c new file +10
-0+ inode->i_sb = &ctx->sb; + inode->i_ino = ino; + inode->i_mode =S_IFREG |0644 ; + inode->i_blkbits =TEST_BLK_BITS ; + inode->i_mapping = &inode->i_data; +set_nlink (inode,1 ); +atomic_set (&inode->i_count,1 ); + +spin_lock_init (&inode->i_lock); +init_rwsem (&inode->i_rwsem);
[Severity: Low]
Should init_mock_inode_slot() also call i_size_ordered_init(inode)?
On 32-bit SMP builds with CONFIG_DEBUG_LOCK_ALLOC=y, struct inode embeds i_size_seqcount, so calling i_size_write() or i_size_read() on the mock EA inodes triggers a lockdep warning for an uninitialized key and disables lockdep.
[ ... ]
Quoted 17 lines
fs/ext4/xattr-test.c new file +17
-0+static void test_xattr_check_inode (struct kunit *test) +{ +const struct xattr_check_param *p = test->param_value; +struct xattr_test_ctx *ctx = test->priv; +struct inode *inode = &ctx->primary.ei.vfs_inode; +struct ext4_inode *raw_inode = (struct ext4_inode *)ctx->primary.raw_buf; +struct ext4_xattr_ibody_header *hdr =IHDR (inode, raw_inode); +struct ext4_xattr_entry *e1, *e2; +void *end =ITAIL (inode, raw_inode); +size_t total_size = (char *)end - (char *)IFIRST (hdr); +int ret; + +memset (hdr,0 , (char *)end - (char *)hdr); + hdr->h_magic =cpu_to_le32 (EXT4_XATTR_MAGIC ); + e1 =IFIRST (hdr); + +switch (p->id) {
[ ... ]
Quoted 12 lines
fs/ext4/xattr-test.c new file +12
-0+case CHECK_NONZERO_OFFS_WITH_INUM : + e1->e_name_len =1 ; + e1->e_value_inum =cpu_to_le32 (20 ); + e1->e_value_offs =cpu_to_le16 (total_size -4 ); +break ; +case CHECK_VALUE_SIZE_GT_TOTAL : + e1->e_name_len =1 ; + e1->e_value_size =cpu_to_le32 (total_size +4 ); + e1->e_value_offs =cpu_to_le16 (total_size -4 ); +break ; +case CHECK_VALUE_OFFS_OVERLAPS_ENTRY : + e1->e_name_len =1 ;
fs/ext4/xattr-test.c line 779
Quoted 10 lines
fs/ext4/xattr-test.c new file +10
-0+ e1->e_value_size =cpu_to_le32 (4 ); +/* Offset points inside e1 + 4-byte terminator */ + e1->e_value_offs =cpu_to_le16 (EXT4_XATTR_LEN (1 )); +break ; +case CHECK_VALUE_END_EXCEEDS_TOTAL : + e1->e_name_len =1 ; + e1->e_value_size =cpu_to_le32 (8 ); + e1->e_value_offs =cpu_to_le16 (total_size -4 ); +break ; + }
[Severity: Medium]
Do these four cases reach the value checks in check_xattrs()?
Because hdr is zeroed with memset() and e1->e_name[0] is left as NUL while e1->e_name_len is 1, check_xattrs() rejects all four cases in the entry-name loop before reaching the value-validation loop:
fs/ext4/xattr.c:check_xattrs() {
...
while (!IS_LAST_ENTRY(e)) {
...
if (strnlen(e->e_name, e->e_name_len) != e->e_name_len) {
err_str = "bad e_name length";
goto errout;
}
e = next;
}
/* Check the values */
while (!IS_LAST_ENTRY(entry)) {
...
}In addition, check_xattrs() only inspects e_value_offs when entry->e_value_inum == 0, so CHECK_NONZERO_OFFS_WITH_INUM does not test a check that check_xattrs() performs; even with e1->e_name[0] set, it would fail on the missing EXT4_FEATURE_INCOMPAT_EA_INODE feature or zero e_value_size instead.
[ ... ]
fs/ext4/xattr-test.c line 1538
Quoted 8 lines
fs/ext4/xattr-test.c new file +8
-0+static void test_xattr_credits_usage_expand_and_delete (struct kunit *test) +{ +struct xattr_test_ctx *ctx = test->priv; +struct inode *inode = &ctx->primary.ei.vfs_inode; +struct ext4_inode *raw = (struct ext4_inode *)ctx->primary.raw_buf; +journal_t fake_journal = { + .j_revoke_records_per_block =64 , + };
[Severity: Low]
Can placing fake_journal on the stack exceed CONFIG_FRAME_WARN?
journal_t (struct journal_s) is ~1.3 KB on 64-bit builds and over 2.2 KB when lock debugging is enabled, which triggers -Wframe-larger-than= warnings on 32-bit builds or 64-bit debug configurations. Moving fake_journal into struct xattr_test_ctx or allocating it with kunit_kzalloc() would avoid the large stack frame.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Theodore Ts'o
maintainerPATCH 5/27 ext4: add KUnit tests for fs/ext4/namei.c
In reply to Theodore Ts'oAdd the ext4_namei_test KUnit test suite in fs/ext4/namei-test.c and shared internal HTree definitions in fs/ext4/namei.h to exercise directory lookup, HTree indexing, and namespace operations in fs/ext4/namei.c without requiring a mounted block device:
- Directory leaf tail initialization (ext4_initialize_dirent_tail), metadata CRC32C checksum calculation and verification (ext4_dirblock_csum_verify, ext4_handle_dirty_dirblock), and corrupted tail/checksum detection.
- HTree root and interior node limit calculations (dx_root_limit, dx_node_limit), entry accessors (dx_get_block, dx_set_block, dx_get_hash, dx_set_hash, dx_get_count, dx_get_limit, dx_set_count, dx_set_limit), and index block checksum verification (ext4_dx_csum_set, ext4_dx_csum_verify).
- Directory block reading (__ext4_read_dirblock) across 10 parameterized cases covering valid leaf and index blocks, unmapped holes (EITHER vs. block 0 vs. DIRENT_HTREE), reads past i_size, ext4_bread -EIO propagation, leaf block found when expecting INDEX, and corrupted leaf/index checksums (-EFSBADCRC).
- New directory initialization (ext4_init_new_dir, ext4_init_dirblock with and without inline directory conversion data) and directory block appending (ext4_append), including s_max_dir_size_kb limit enforcement (-ENOSPC) and pre-allocated logical block detection (-EFSCORRUPTED).
- Directory entry destination search (ext4_find_dest_de), insertion (ext4_insert_dentry), linear search (ext4_search_dir), and deletion (ext4_delete_entry, ext4_generic_delete_entry) for both first-entry inode zeroing and predecessor rec_len merging.
- Directory emptiness checks (ext4_empty_dir) across fresh, populated, deleted, multi-block with unmapped holes, and corrupted '.'/'..' directories.
- HTree leaf splitting and index helpers (dx_make_map, dx_sort_map exercising both combsort and bubble-sort phases, dx_move_dirents, dx_pack_dirents, and dx_insert_block).
- HTree root validation (ext4_check_dx_root), multi-level index probing (dx_probe), and continuation block traversal (ext4_htree_next_block) across 14 parameterized valid and corrupted on-disk layouts (invalid '.'/'..' entries, bad hash_version, SipHash without hash-in-dirent, non-zero unused_flags, excessive indirect_levels, limit mismatch, zero entry count, and tree cycle detection).
- End-to-end HTree conversion (make_indexed_dir), leaf splitting (do_split / ext4_dx_add_entry), indexed lookup (ext4_dx_find_entry), and readdir red-black tree population (ext4_htree_fill_tree).
- HTree index level growth (splitting a full dx_root into a 2-level tree and splitting a full interior dx_node), max HTree level -ENOSPC enforcement, and corrupted dx_root fallback in __ext4_find_entry and __ext4_add_entry.
- Inline directory lifecycle through namei.c entry points (ext4_init_new_dir, ext4_empty_dir, ext4_add_entry, ext4_find_entry, ext4_delete_entry, and ext4_htree_fill_tree).
- Directory link count helpers (ext4_inc_count, ext4_dec_count including EXT4_LINK_MAX wrap to 1), VFS lookup (ext4_lookup) and parent resolution (ext4_get_parent) error paths (-ENAMETOOLONG, self-linked directory entry, invalid inode number, and -ESTALE to -EFSCORRUPTED translation).
- Hard link creation (__ext4_link, ext4_link including 0-nlink tmpfile orphan removal, EXT4_INODE_PROJINHERIT -EXDEV, and EXT4_LINK_MAX -EMLINK), unlinking (__ext4_unlink, ext4_unlink including orphan addition and EXT4_FC_REPLAY inode mismatch handling), and directory removal (ext4_rmdir).
- Same-directory rename, overwrite rename, cross-directory subdirectory rename, RENAME_EXCHANGE (ext4_cross_rename), project quota inheritance -EXDEV checks, 0-nlink target -EFSCORRUPTED check, slow symlink block initialization (ext4_init_symlink_block), and case-folded (EXT4_INODE_CASEFOLD) directory lookup and strict UTF-8 validation.
Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_orphan_add and ext4_orphan_del.
--- fs/ext4/Makefile | 3 +- fs/ext4/crypto.c | 4 + fs/ext4/dir.c | 4 + fs/ext4/namei-test.c | 2304 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/namei.c | 338 ++++--- fs/ext4/namei.h | 213 ++++ fs/ext4/orphan.c | 7 + 7 files changed, 2708 insertions(+), 165 deletions(-) create mode 100644 fs/ext4/namei-test.c create mode 100644 fs/ext4/namei.h
fs/ext4/Makefile +2 -1
@@ -16,7 +16,8 @@ ext4-$(CONFIG_EXT4_FS_POSIX_ACL) += acl.o ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ - extents_status-test.o xattr-test.o + extents_status-test.o xattr-test.o \ + namei-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/crypto.c +4 -0
@@ -37,6 +37,7 @@ int ext4_fname_setup_filename(struct inode *dir, const struct qstr *iname,return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fname_setup_filename);int ext4_fname_prepare_lookup (struct inode *dir,struct dentry *dentry,struct ext4_filename *fname)
@@ -55,6 +56,7 @@ int ext4_fname_prepare_lookup(struct inode *dir, struct dentry *dentry,ext4_fname_free_filename (fname);return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fname_prepare_lookup);void ext4_fname_free_filename (struct ext4_filename *fname) {
@@ -69,6 +71,7 @@ void ext4_fname_free_filename(struct ext4_filename *fname)ext4_fname_free_ci_filename (fname); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fname_free_filename);static bool uuid_is_zero (__u8 u[16 ]) {
@@ -246,3 +249,4 @@ const struct fscrypt_operations ext4_cryptops = { .empty_dir = ext4_empty_dir, .has_stable_inodes = ext4_has_stable_inodes, }; +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_cryptops);
fs/ext4/dir.c +4 -0
@@ -126,6 +126,7 @@ int __ext4_check_dir_entry(const char *function, unsigned int line,return 1 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_check_dir_entry);static int ext4_readdir (struct file *file,struct dir_context *ctx) {
@@ -475,6 +476,7 @@ void ext4_htree_free_dir_info(struct dir_private_info *p)free_rb_tree_fname (&p->root);kfree (p); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_htree_free_dir_info);/* * Given a directory entry, enter it into the fname rb tree.
@@ -535,6 +537,7 @@ int ext4_htree_store_dirent(struct file *dir_file, __u32 hash,rb_insert_color (&new_fn->rb_hash, &info->root);return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_htree_store_dirent);
@@ -683,6 +686,7 @@ int ext4_check_all_de(struct inode *dir, struct buffer_head *bh, void *buf,return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_check_all_de);static int ext4_dir_open (struct inode *inode,struct file *file) {
fs/ext4/namei-test.c new file +2304 -0
2,304 lines not on this page · raw message
fs/ext4/namei.c +174 -164
466 lines not on this page · raw message
fs/ext4/namei.h new file +213 -0
168 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Part of the diff is not shown here. View the raw message.
[email protected]
AI reviewRe: [PATCH 05/27] ext4: add KUnit tests for fs/ext4/namei.c
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] ext4: out-of-bounds read due to missing…
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] ext4: out-of-bounds read due to missing dx_entry validation in ext4_htree_next_block() [1]
--
commit 2ae6fd1b46635dda6b69ee78cd382ff9c0d0450a
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/namei.c
This commit adds a KUnit test suite for directory lookup, HTree indexing, and namespace operations in fs/ext4/namei.c, and exports the internal HTree definitions and helper wrappers needed by the tests.
Quoted 4 lines
fs/ext4/namei.c +0
-0
[ ... ]
Quoted 7 lines
fs/ext4/namei.c +3
-0@@ -4249,3 +4103,159 @@ const struct inode_operations ext4_special_inode_operations = { .get_inode_acl = ext4_get_acl, .set_acl = ext4_set_acl, }; +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_special_inode_operations); + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )
[ ... ]
fs/ext4/namei.c const struct inode_operations ext4_special_inode_operations = { · line 4157
Quoted 7 lines
fs/ext4/namei.c +7
-0+int ext4_htree_next_block_test (struct inode *dir,__u32 hash, +struct dx_frame *frame, +struct dx_frame *frames,__u32 *start_hash) +{ +return ext4_htree_next_block (dir, hash, frame, frames, start_hash); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_htree_next_block_test);
[Severity: High]
This problem wasn't introduced by this patch, but can ext4_htree_next_block() read out of bounds past bh->b_data [1] when loading a sibling interior dx_node block?
fs/ext4/namei.c:ext4_htree_next_block() {
...
while (1) {
if (++(p->at) < p->entries + dx_get_count(p->entries))
break;
if (p == frames)
return 0;
num_frames++;
p--;
}
...
while (num_frames--) {
bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX);
if (IS_ERR(bh))
return PTR_ERR(bh);
p++;
brelse(p->bh);
p->bh = bh;
p->at = p->entries = ((struct dx_node *) bh->b_data)->entries;
}
return 1;
}Unlike dx_probe(), which checks dx_get_limit() against dx_node_limit() and verifies that dx_get_count() is non-zero and within dx_get_limit(), ext4_htree_next_block() assigns p->entries directly from bh->b_data without validating the new node's count or limit. If a corrupted interior node has an out-of-bounds count (for example, when metadata_csum is disabled or buffer_verified(bh) is already set), later calls to ext4_htree_next_block() advance p->at up to p->entries + dx_get_count(p->entries) and dereference it via dx_get_hash() and dx_get_block(), reading past the end of bh->b_data.
[1] https://sashiko.dev/#/bug/linux-c6639d9a-25ec-49eb-a6a4-468135552f9a
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Theodore Ts'o
maintainerPATCH 6/27 ext4: expand KUnit tests for fs/ext4/mballoc.c
In reply to Theodore Ts'oExpand the ext4_mballoc_test KUnit test suite in fs/ext4/mballoc-test.c from 7 subtests (21 test cases) to 32 subtests (96 parameterized test cases across 1K, 4K, and 64K block sizes) to comprehensively exercise the multi-block allocator in fs/ext4/mballoc.c:
- Low-level bitmap helpers (mb_set_bit, mb_clear_bit, mb_test_bit, mb_find_next_zero_bit, mb_find_next_bit, mb_clear_bits, mb_set_bits, and mb_test_and_clear_bits across clean, partially clear, and fully clear ranges).
- Buddy bitmap lookup and extent discovery (mb_find_buddy, mb_find_order_for_block, mb_find_extent for free, used, and merged power-of-two ranges, and mb_regenerate_buddy).
- Corrupted block bitmap detection in ext4_mb_generate_buddy (setting EXT4_GROUP_INFO_BBITMAP_CORRUPT when bitmap free count mismatches grp->bb_free) and double-free / EXT4_STATE_FC_REPLAY handling in mb_free_blocks.
- Group fragment size order calculation (mb_avg_fragment_size_order), per-order XArray insertion/migration/removal (mb_update_avg_fragment_size and mb_set_largest_free_order), and largest free order tracking.
- Group eligibility filtering (ext4_mb_good_group_nolock and ext4_mb_good_group) across CR_POWER2_ALIGNED, CR_GOAL_LEN_FAST, CR_BEST_AVAIL_LEN, CR_GOAL_LEN_SLOW, and CR_ANY_FREE, including BBITMAP_CORRUPT, 0 free blocks, uninitialized bitmaps, and flex_bg metadata allocation rules.
- Goal-based allocation (ext4_mb_find_by_goal) covering power-of-two buddies, non-power-of-two extents, EXT4_MB_HINT_MERGE tail merging, stripe-aligned requests, and occupied goals.
- Buddy and bitmap group scanning (ext4_mb_simple_scan_group, ext4_mb_scan_aligned, ext4_mb_complex_scan_group, ext4_mb_measure_extent, and ext4_mb_try_best_found) including s_mb_max_to_scan limits and EXT4_MB_HINT_FIRST.
- Regular allocator orchestration (ext4_mb_regular_allocator) for EXT4_MB_HINT_GOAL_ONLY, stream allocation (EXT4_MB_STREAM_ALLOC) with s_mb_last_groups updates, and MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming.
- Block bitmap prefetching (ext4_mb_prefetch and ext4_mb_prefetch_fini) and allocation context initialization and request normalization (ext4_mb_initialize_context and ext4_mb_normalize_request across metadata/no-normalize, small/large/huge files, stripe alignment, and existing preallocation overlap avoidance).
- Inode and locality group preallocation lifecycles (ext4_mb_pa_alloc, ext4_mb_pa_put_free, ext4_mb_new_preallocation, ext4_mb_use_preallocated, ext4_mb_generate_from_pa, ext4_mb_discard_group_preallocations, ext4_discard_preallocations, ext4_mb_discard_preallocations, and locality group list trimming past PREALLOC_TB_SIZE).
- Top-level allocation and deallocation entry points (ext4_mb_new_blocks including PA satisfaction and ENOSPC retry after discarding group PAs, ext4_mb_mark_context, ext4_mb_mark_bb, ext4_free_blocks with EXT4_FREE_BLOCKS_NO_QUOT_UPDATE / VALIDATED / METADATA and cross-group extents, mb_free_metadata merging and splitting with ext4_process_freed_data, ext4_group_add_blocks, ext4_trim_fs with a static stub for ext4_issue_discard, and ext4_mballoc_query_range).
Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_issue_discard.
--- fs/ext4/mballoc-test.c | 1855 +++++++++++++++++++++++++++++++++++++++- fs/ext4/mballoc.c | 201 ++++- fs/ext4/mballoc.h | 49 ++ 3 files changed, 2089 insertions(+), 16 deletions(-)
fs/ext4/mballoc-test.c +1840 -15
@@ -79,6 +79,7 @@ static int mbt_mb_init(struct super_block *sb) sb->s_bdev =kzalloc_obj (*sb->s_bdev);if (sb->s_bdev ==NULL )return -ENOMEM ; +bdev_set_flag (sb->s_bdev,BD_READ_ONLY ); sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue);if (sb->s_bdev->bd_queue ==NULL ) {
@@ -162,10 +163,15 @@ static struct super_block *mbt_ext4_alloc_super_block(void) goto out_deactivate;bgl_lock_init (sbi->s_blockgroup_lock); +spin_lock_init (&sbi->s_error_lock); +ratelimit_state_init (&sbi->s_err_ratelimit_state,5 *HZ ,10 ); +ratelimit_state_init (&sbi->s_warning_ratelimit_state,5 *HZ ,10 ); +ratelimit_state_init (&sbi->s_msg_ratelimit_state,5 *HZ ,10 ); sbi->s_es = &fsb->es; sbi->s_sb = sb; sb->s_fs_info = sbi; +set_opt (sb,ERRORS_CONT );up_write (&sb->s_umount);return sb;
@@ -341,15 +347,72 @@ ext4_mb_mark_context_stub(handle_t *handle, struct super_block *sb, bool state, {struct mbt_grp_ctx *grp_ctx =MBT_GRP_CTX (sb, group);struct buffer_head *bitmap_bh = &grp_ctx->bitmap_bh; +struct ext4_group_desc *gdp = &grp_ctx->desc; +ext4_grpblk_t i, already =0 , changed = len; +__u32 free; -if (state) +for (i =0 ; i < len; i++) { +if (mb_test_bit_test (blkoff + i, bitmap_bh->b_data) == state) + already++; + } +if (flags &0x0001 /* EXT4_MB_BITMAP_MARKED_CHECK */ ) + changed = len - already; + + free =ext4_free_group_clusters (sb, gdp); +if (state) {mb_set_bits (bitmap_bh->b_data, blkoff, len); -else +if (free >= changed) +ext4_free_group_clusters_set (sb, gdp, free - changed); + }else {mb_clear_bits_test (bitmap_bh->b_data, blkoff, len); +ext4_free_group_clusters_set (sb, gdp, free + changed); + } + +if (ret_changed) + *ret_changed = changed;return 0 ; } +static int +ext4_issue_discard_stub (struct super_block *sb,ext4_group_t block_group, +ext4_grpblk_t cluster,int count) +{ +return 0 ; +} + +static struct inode *mbt_alloc_test_inode (struct kunit *test, +struct super_block *sb, +umode_t mode) +{ +struct ext4_inode_info *ei; +struct inode *inode; + + ei =kunit_kzalloc (test,sizeof (*ei),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ei); + +INIT_LIST_HEAD (&ei->i_orphan); +init_rwsem (&ei->xattr_sem); +init_rwsem (&ei->i_data_sem); + ei->i_prealloc_node =RB_ROOT ; +atomic_set (&ei->i_prealloc_active,0 ); +rwlock_init (&ei->i_prealloc_lock); +spin_lock_init (&ei->i_block_reservation_lock); +spin_lock_init (&ei->i_raw_lock); + + inode = &ei->vfs_inode; +inode_init_once (inode); +ext4_fc_init_inode (inode); + inode->i_sb = sb; + inode->i_ino =12 ; + inode->i_mode = mode; + inode->i_flags |=S_NOQUOTA ; +atomic_set (&inode->i_writecount,1 ); +ext4_set_inode_flag (inode,EXT4_INODE_EXTENTS ); + +return inode; +} +#define TEST_GOAL_GROUP 1static int mbt_kunit_init (struct kunit *test) {
@@ -382,6 +445,9 @@ static int mbt_kunit_init(struct kunit *test)kunit_activate_static_stub (test, ext4_mb_mark_context, ext4_mb_mark_context_stub); +kunit_activate_static_stub (test, + ext4_issue_discard, + ext4_issue_discard_stub);/* stub function will be called in mbt_mb_init->ext4_mb_init */ if (mbt_mb_init (sb) !=0 ) {
@@ -402,7 +468,10 @@ static void mbt_kunit_exit(struct kunit *test)if (!sb)return ; +if (sb->s_blocksize <=PAGE_SIZE ) +ext4_mb_discard_preallocations_test (sb,0 );mbt_mb_release (sb); +rcu_barrier ();mbt_ctx_release (sb);mbt_ext4_free_super_block (sb); }
@@ -417,11 +486,7 @@ static void test_new_blocks_simple(struct kunit *test)ext4_fsblk_t found;struct ext4_sb_info *sbi =EXT4_SB (sb); - inode =kunit_kzalloc (test,sizeof (*inode),GFP_KERNEL ); -if (!inode) -return ; - - inode->i_sb = sb; + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); ar.inode = inode;/* get block at goal */
@@ -527,10 +592,7 @@ test_free_blocks_simple_range(struct kunit *test, ext4_group_t goal_group,struct inode *inode;ext4_fsblk_t block; - inode =kunit_kzalloc (test,sizeof (*inode),GFP_KERNEL ); -if (!inode) -return ; - inode->i_sb = sb; + inode =mbt_alloc_test_inode (test, sb,S_IFREG );if (len ==0 )return ;
@@ -601,10 +663,7 @@ static void test_mark_diskspace_used(struct kunit *test)mbt_generate_test_ranges (sb, ranges,TEST_RANGE_COUNT ); - inode =kunit_kzalloc (test,sizeof (*inode),GFP_KERNEL ); -if (!inode) -return ; - inode->i_sb = sb; + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); ac.ac_status =AC_STATUS_FOUND ; ac.ac_sb = sb;
@@ -949,6 +1008,1747 @@ static void test_mb_mark_used_cost(struct kunit *test)ext4_mb_unload_buddy_test (&e4b); } +static void test_mb_bit_ops (struct kunit *test) +{ +u8 *buf; +void *unaligned; +int bit, i; + + buf =kunit_kzalloc (test,128 ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, buf); + +/* +* Use an unaligned pointer (offset by 3 bytes) to exercise +* mb_correct_addr_and_bit() on 64-bit/32-bit architectures. +*/ + unaligned = buf +3 ; + +mb_set_bit_test (0 , unaligned); +mb_set_bit_test (7 , unaligned); +mb_set_bit_test (64 , unaligned); +KUNIT_EXPECT_NE (test,mb_test_bit_test (0 , unaligned),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (1 , unaligned),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (7 , unaligned),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (64 , unaligned),0 ); + +mb_clear_bit_test (7 , unaligned); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (7 , unaligned),0 ); + + bit =mb_find_next_bit_test (unaligned,128 ,1 ); +KUNIT_EXPECT_EQ (test, bit,64 ); + +/* Clamping when no set bit exists before max */ + bit =mb_find_next_bit_test (unaligned,60 ,1 ); +KUNIT_EXPECT_EQ (test, bit,60 ); + +/* Zero-length mb_set_bits / mb_clear_bits should be a no-op */ +memset (buf,0 ,128 ); +mb_set_bits (unaligned,10 ,0 ); +KUNIT_EXPECT_EQ (test,mb_find_next_bit_test (unaligned,256 ,0 ),256 ); + +/* Multi-word unaligned range spanning head bits, 32-bit words, and tail */ +mb_set_bits (unaligned,5 ,75 ); +KUNIT_EXPECT_EQ (test,mb_find_next_bit_test (unaligned,256 ,0 ),5 ); +KUNIT_EXPECT_EQ (test,mb_find_next_zero_bit_test (unaligned,256 ,5 ),80 ); +/* Clamping when no zero bit exists before max */ +KUNIT_EXPECT_EQ (test,mb_find_next_zero_bit_test (unaligned,50 ,5 ),50 ); + +/* Clear a sub-range across 32-bit boundaries */ +mb_clear_bits_test (unaligned,13 ,50 ); +for (i =0 ; i <100 ; i++) { +int expected = (i >=5 && i <13 ) || (i >=63 && i <80 ); + +KUNIT_EXPECT_EQ (test, !!mb_test_bit_test (i, unaligned), expected); + } +} + +static void test_mb_test_and_clear_bits (struct kunit *test) +{ +u8 *buf; +void *bm; +int ret, i; + + buf =kunit_kzalloc (test,128 ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, buf); + bm = buf +3 ; + +/* Case 1: All bits in range [5, 85) are set -> returns -1 and clears all */ +memset (buf,0xff ,128 ); + ret =mb_test_and_clear_bits_test (bm,5 ,80 ); +KUNIT_EXPECT_EQ (test, ret,-1 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (4 , bm),0 ); +for (i =5 ; i <85 ; i++) +KUNIT_EXPECT_EQ (test,mb_test_bit_test (i, bm),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (85 , bm),0 ); + +/* Case 2: Zero bit in the unaligned head (bit 7) */ +memset (buf,0xff ,128 ); +mb_clear_bit_test (7 , bm); + ret =mb_test_and_clear_bits_test (bm,5 ,80 ); +KUNIT_EXPECT_EQ (test, ret,7 ); +for (i =5 ; i <85 ; i++) +KUNIT_EXPECT_EQ (test,mb_test_bit_test (i, bm),0 ); + +/* Case 3: Zero bit inside the 32-bit word fast-path region (bit 45) */ +memset (buf,0xff ,128 ); +mb_clear_bit_test (45 , bm); + ret =mb_test_and_clear_bits_test (bm,5 ,80 ); +KUNIT_EXPECT_EQ (test, ret,45 ); +for (i =5 ; i <85 ; i++) +KUNIT_EXPECT_EQ (test,mb_test_bit_test (i, bm),0 ); +} + +static void test_mb_find_buddy_and_order (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_free_extent ex; +void *bb; +int max =0 , ret; +int ord0, ord1, ord2, ord3; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* Order 0 returns bitmap and bit count */ + bb =mb_find_buddy_test (&e4b,0 , &max); +KUNIT_EXPECT_PTR_EQ (test, bb, e4b.bd_bitmap); +KUNIT_EXPECT_EQ (test, max, (int )(sb->s_blocksize <<3 )); + +/* Valid higher order returns buddy offset */ + bb =mb_find_buddy_test (&e4b,1 , &max); +KUNIT_EXPECT_PTR_EQ (test, bb, e4b.bd_buddy + sbi->s_mb_offsets[1 ]); +KUNIT_EXPECT_EQ (test, max, sbi->s_mb_maxs[1 ]); + +/* Out-of-bounds order (> bd_blkbits + 1) returns NULL and max = 0 */ + bb =mb_find_buddy_test (&e4b,MB_NUM_ORDERS (sb), &max); +KUNIT_EXPECT_NULL (test, bb); +KUNIT_EXPECT_EQ (test, max,0 ); + +/* +* Mark cluster 0 used in group 1: this splits the group so that: +* - cluster 1 is free at order 0 +* - clusters [2, 4) are free at order 1 +* - clusters [4, 8) are free at order 2 +* - clusters [8, 16) are free at order 3 +*/ + ex.fe_group =TEST_GOAL_GROUP ; + ex.fe_start =0 ; + ex.fe_len =1 ; +ext4_lock_group (sb,TEST_GOAL_GROUP ); +mb_mark_used_test (&e4b, &ex); + ord0 =mb_find_order_for_block_test (&e4b,1 ); + ord1 =mb_find_order_for_block_test (&e4b,2 ); + ord2 =mb_find_order_for_block_test (&e4b,4 ); + ord3 =mb_find_order_for_block_test (&e4b,8 ); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_EQ (test, ord0,0 ); +KUNIT_EXPECT_EQ (test, ord1,1 ); +KUNIT_EXPECT_EQ (test, ord2,2 ); +KUNIT_EXPECT_EQ (test, ord3,3 ); + +ext4_mb_unload_buddy_test (&e4b); +} + +static void test_mb_find_extent (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_buddy e4b; +struct ext4_free_extent ex, found_used, found_small, found_coalesced, found_unaligned; +int ret, len_used, len_small, len_coalesced, len_unaligned; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* +* Leave only [10, 26) (16 clusters) free: +* [10, 12) order 1 (2) + [12, 16) order 2 (4) + +* [16, 24) order 3 (8) + [24, 26) order 1 (2). +*/ +ext4_lock_group (sb,TEST_GOAL_GROUP ); + ex.fe_group =TEST_GOAL_GROUP ; + ex.fe_start =0 ; + ex.fe_len =10 ; +mb_mark_used_test (&e4b, &ex); + + ex.fe_start =26 ; + ex.fe_len =EXT4_CLUSTERS_PER_GROUP (sb) -26 ; +mb_mark_used_test (&e4b, &ex); + + len_used =mb_find_extent_test (&e4b,5 ,8 , &found_used); + len_small =mb_find_extent_test (&e4b,10 ,1 , &found_small); + len_coalesced =mb_find_extent_test (&e4b,10 ,20 , &found_coalesced); + len_unaligned =mb_find_extent_test (&e4b,11 ,20 , &found_unaligned); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +/* Used block returns 0 */ +KUNIT_EXPECT_EQ (test, len_used,0 ); +KUNIT_EXPECT_EQ (test, found_used.fe_len,0 ); + +/* Needed = 1 at block 10 returns the order-1 buddy [10, 12) */ +KUNIT_EXPECT_EQ (test, len_small,2 ); +KUNIT_EXPECT_EQ (test, found_small.fe_start,10 ); +KUNIT_EXPECT_EQ (test, found_small.fe_len,2 ); + +/* Needed = 20 at block 10 coalesces across orders 1, 2, 3, 1 -> 16 clusters */ +KUNIT_EXPECT_EQ (test, len_coalesced,16 ); +KUNIT_EXPECT_EQ (test, found_coalesced.fe_start,10 ); +KUNIT_EXPECT_EQ (test, found_coalesced.fe_len,16 ); + +/* Unaligned start at block 11 coalesces [11, 26) -> 15 clusters */ +KUNIT_EXPECT_EQ (test, len_unaligned,15 ); +KUNIT_EXPECT_EQ (test, found_unaligned.fe_start,11 ); +KUNIT_EXPECT_EQ (test, found_unaligned.fe_len,15 ); + +ext4_mb_unload_buddy_test (&e4b); +} + +static void test_mb_generate_buddy_corrupt (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_group_info *grp; +void *bitmap, *buddy; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +bool is_corrupt; +ext4_grpblk_t corrected_free; +int i; + + bitmap =kunit_kzalloc (test, sb->s_blocksize,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, bitmap); + buddy =kunit_kzalloc (test, sb->s_blocksize,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, buddy); + + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); +KUNIT_ASSERT_NOT_NULL (test, grp); + +/* Mark 10 clusters used in bitmap, so actual free is max - 10 */ +mb_set_bits (bitmap, max, sb->s_blocksize *8 - max); +mb_set_bits (bitmap,0 ,10 ); + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +for (i =0 ; i <MB_NUM_ORDERS (sb); i++) + grp->bb_counters[i] =0 ; +/* Intentionally set wrong bb_free = max (mismatch with max - 10) */ + grp->bb_free = max; +memset (buddy,0xff , sb->s_blocksize); +ext4_mb_generate_buddy_test (sb, buddy, bitmap,TEST_GOAL_GROUP , grp); + is_corrupt =EXT4_MB_GRP_BBITMAP_CORRUPT (grp); + corrected_free = grp->bb_free; +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_TRUE (test, is_corrupt); +KUNIT_EXPECT_EQ (test, corrected_free, max -10 ); +} + +static void test_mb_free_blocks_double_free_and_fc_replay (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_free_extent ex; +bool corrupt_normal, corrupt_fc; +ext4_grpblk_t free_after_fc; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + +/* Part 1: Normal mode double-free marks group bitmap corrupt */ + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +/* Clusters [10, 14) are already free; freeing them again is a double free */ +mb_free_blocks_test (NULL , &e4b,10 ,4 ); + corrupt_normal =EXT4_MB_GRP_BBITMAP_CORRUPT (e4b.bd_info); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_unload_buddy_test (&e4b); + +KUNIT_EXPECT_TRUE (test, corrupt_normal); + +/* +* Part 2: In EXT4_FC_REPLAY mode, freeing an already-freed range +* triggers mb_regenerate_buddy() instead of marking the group corrupt. +*/ + ret =ext4_mb_load_buddy_test (sb,2 , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +ext4_lock_group (sb,2 ); + ex.fe_group =2 ; + ex.fe_start =10 ; + ex.fe_len =10 ; +mb_mark_used_test (&e4b, &ex); +/* Free sub-range [12, 16) first so [12, 16) is already free */ +mb_free_blocks_test (NULL , &e4b,12 ,4 ); + +/* Re-freeing [12, 16) in EXT4_FC_REPLAY mode regenerates buddy cleanly */ + sbi->s_mount_state |=EXT4_FC_REPLAY ; +mb_free_blocks_test (NULL , &e4b,12 ,4 ); + sbi->s_mount_state &= ~EXT4_FC_REPLAY ; + + corrupt_fc =EXT4_MB_GRP_BBITMAP_CORRUPT (e4b.bd_info); + free_after_fc = e4b.bd_info->bb_free; +ext4_unlock_group (sb,2 ); +ext4_mb_unload_buddy_test (&e4b); + +KUNIT_EXPECT_FALSE (test, corrupt_fc); +KUNIT_EXPECT_EQ (test, free_after_fc,EXT4_CLUSTERS_PER_GROUP (sb) -6 ); +} + +static void test_mb_xarray_orders_and_frag_size (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_group_info *grp; +int ord_1, ord_4, ord_7, ord_8; +int old_lfo, new_lfo, new_afso; +void *xa_lfo_entry, *xa_afso_entry, *xa_old_entry; +int i; + +set_opt2 (sb,MB_OPTIMIZE_SCAN ); + +/* mb_avg_fragment_size_order computes clamp(fls(len) - 2, 0, MB_NUM_ORDERS - 1) */ + ord_1 =mb_avg_fragment_size_order_test (sb,1 ); + ord_4 =mb_avg_fragment_size_order_test (sb,4 ); + ord_7 =mb_avg_fragment_size_order_test (sb,7 ); + ord_8 =mb_avg_fragment_size_order_test (sb,8 ); +KUNIT_EXPECT_EQ (test, ord_1,0 ); +KUNIT_EXPECT_EQ (test, ord_4,1 ); +KUNIT_EXPECT_EQ (test, ord_7,1 ); +KUNIT_EXPECT_EQ (test, ord_8,2 ); + + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); +KUNIT_ASSERT_NOT_NULL (test, grp); + +ext4_lock_group (sb,TEST_GOAL_GROUP ); + old_lfo = grp->bb_largest_free_order; +for (i =0 ; i <MB_NUM_ORDERS (sb); i++) + grp->bb_counters[i] =0 ; + grp->bb_counters[3 ] =2 ; + grp->bb_free =16 ; + grp->bb_fragments =2 ; + +mb_set_largest_free_order_test (sb, grp); +mb_update_avg_fragment_size_test (sb, grp); + + new_lfo = grp->bb_largest_free_order; + new_afso = grp->bb_avg_fragment_size_order; + xa_lfo_entry =xa_load (&sbi->s_mb_largest_free_orders[3 ],TEST_GOAL_GROUP ); + xa_afso_entry =xa_load (&sbi->s_mb_avg_fragment_size[2 ],TEST_GOAL_GROUP ); + +/* Now mark group completely full and verify XArray entries are erased */ + grp->bb_counters[3 ] =0 ; + grp->bb_free =0 ; + grp->bb_fragments =0 ; +mb_set_largest_free_order_test (sb, grp); +mb_update_avg_fragment_size_test (sb, grp); + xa_old_entry =xa_load (&sbi->s_mb_largest_free_orders[3 ],TEST_GOAL_GROUP ); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_EQ (test, old_lfo,-1 ); +KUNIT_EXPECT_EQ (test, new_lfo,3 ); +KUNIT_EXPECT_EQ (test, new_afso,2 ); +KUNIT_EXPECT_PTR_EQ (test, xa_lfo_entry, grp); +KUNIT_EXPECT_PTR_EQ (test, xa_afso_entry, grp); +KUNIT_EXPECT_NULL (test, xa_old_entry); +} + +static void test_mb_good_group (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct ext4_group_info *grp1, *grp2; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + +/* Initialize group 1 buddy cache so bb_fragments and orders are populated */ + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + + grp1 =ext4_get_group_info (sb,TEST_GOAL_GROUP ); +KUNIT_ASSERT_NOT_NULL (test, grp1); + + ac.ac_sb = sb; + ac.ac_2order =3 ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_flags =EXT4_MB_HINT_DATA ; + +/* Group 1 has all clusters free in 1 fragment -> eligible at all CRs */ +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_POWER2_ALIGNED )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_GOAL_LEN_FAST )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_BEST_AVAIL_LEN )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_GOAL_LEN_SLOW )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_ANY_FREE )); + +/* +* Simulate high fragmentation: free = 16, fragments = 8 (avg = 2 < 8), +* largest_free_order = 1 (< ac_2order = 3). +* CR_POWER2_ALIGNED, CR_GOAL_LEN_FAST, CR_BEST_AVAIL_LEN must reject, +* while CR_GOAL_LEN_SLOW (free 16 >= 8) and CR_ANY_FREE accept. +*/ +ext4_lock_group (sb,TEST_GOAL_GROUP ); + grp1->bb_free =16 ; + grp1->bb_fragments =8 ; + grp1->bb_largest_free_order =1 ; +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_FALSE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_POWER2_ALIGNED )); +KUNIT_EXPECT_FALSE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_GOAL_LEN_FAST )); +KUNIT_EXPECT_FALSE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_BEST_AVAIL_LEN )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_GOAL_LEN_SLOW )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_ANY_FREE )); + +/* When free = 4 < fe_len = 8, CR_GOAL_LEN_SLOW rejects, CR_ANY_FREE accepts */ +ext4_lock_group (sb,TEST_GOAL_GROUP ); + grp1->bb_free =4 ; +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_FALSE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_GOAL_LEN_SLOW )); +KUNIT_EXPECT_TRUE (test,ext4_mb_good_group_test (&ac,TEST_GOAL_GROUP , +CR_ANY_FREE )); + +/* Flex_bg first group avoidance at CR_POWER2_ALIGNED for data */ + ret =ext4_mb_load_buddy_test (sb,0 , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + sbi->s_log_groups_per_flex =2 ;/* flex_size = 4 >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME */ +KUNIT_EXPECT_FALSE (test,ext4_mb_good_group_test (&ac,0 ,CR_POWER2_ALIGNED )); + sbi->s_log_groups_per_flex =0 ; + +/* +* Test ext4_mb_good_group_nolock on uninitialized group 2: +* At inexpensive CR_POWER2_ALIGNED, it skips initializing group 2 and returns 0. +* At expensive CR_GOAL_LEN_SLOW (with STRICT_CHECK), it initializes group 2 +* and returns 1. +*/ + grp2 =ext4_get_group_info (sb,2 ); +KUNIT_ASSERT_NOT_NULL (test, grp2); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2)); + + ac.ac_criteria =CR_POWER2_ALIGNED ; + ret =ext4_mb_good_group_nolock_test (&ac,2 ,CR_POWER2_ALIGNED ); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2)); + + ac.ac_flags |=EXT4_MB_STRICT_CHECK ; + ac.ac_criteria =CR_GOAL_LEN_SLOW ; + ret =ext4_mb_good_group_nolock_test (&ac,2 ,CR_GOAL_LEN_SLOW ); +KUNIT_EXPECT_EQ (test, ret,1 ); +KUNIT_EXPECT_FALSE (test,EXT4_MB_GRP_NEED_INIT (grp2)); +} + +static void test_mb_find_by_goal (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct inode *inode; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* Mark [24, 32) used in group 1 so [20, 24) has only 4 free clusters */ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,24 ,8 ); +ext4_get_group_info (sb,TEST_GOAL_GROUP )->bb_free -=8 ; + +/* 1. Exact goal hit at [10, 14) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_TRY_GOAL ; + ac.ac_g_ex.fe_group =TEST_GOAL_GROUP ; + ac.ac_g_ex.fe_start =10 ; + ac.ac_g_ex.fe_len =4 ; + ac.ac_o_ex = ac.ac_g_ex; + + ret =ext4_mb_find_by_goal_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_group,TEST_GOAL_GROUP ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,10 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,4 ); + +/* 2. Partial goal at [20, 28) without HINT_MERGE fails to match */ +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_TRY_GOAL ; + ac.ac_g_ex.fe_group =TEST_GOAL_GROUP ; + ac.ac_g_ex.fe_start =20 ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_o_ex = ac.ac_g_ex; + + ret =ext4_mb_find_by_goal_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_CONTINUE ); + +/* 3. Partial goal at [20, 28) WITH EXT4_MB_HINT_MERGE allocates [20, 24) */ +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_TRY_GOAL |EXT4_MB_HINT_MERGE ; + ac.ac_g_ex.fe_group =TEST_GOAL_GROUP ; + ac.ac_g_ex.fe_start =20 ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_o_ex = ac.ac_g_ex; + + ret =ext4_mb_find_by_goal_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,20 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,4 ); + +/* +* 4. Stripe-aligned check: s_stripe = 8 clusters; unaligned start 36 +* rejected, aligned 40 accepted. +*/ + sbi->s_stripe =EXT4_C2B (sbi,8 ); +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_TRY_GOAL ; + ac.ac_g_ex.fe_group =TEST_GOAL_GROUP ; + ac.ac_g_ex.fe_start =36 ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_o_ex = ac.ac_g_ex; + + ret =ext4_mb_find_by_goal_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_CONTINUE ); + + ac.ac_g_ex.fe_start =40 ; + ac.ac_o_ex = ac.ac_g_ex; + ret =ext4_mb_find_by_goal_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,40 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,8 ); + sbi->s_stripe =0 ; +} + +static void test_mb_simple_and_aligned_scan (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct inode *inode; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* +* Mark cluster 0 used in group 1 so: +* - order 3 buddy [8, 16) is the first order-3 buddy +* - first 16-cluster stripe [0, 16) is not completely free, so +* stripe-aligned scan must skip to cluster 16. +*/ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,0 ,1 ); + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* 1. ext4_mb_simple_scan_group with ac_2order = 3 (8 clusters) */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_criteria =CR_POWER2_ALIGNED ; + ac.ac_2order =3 ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_o_ex.fe_len =8 ; + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_simple_scan_group_test (&ac, &e4b); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_release_context_test (&ac); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_group,TEST_GOAL_GROUP ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,8 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,8 ); + +/* 2. ext4_mb_scan_aligned with stripe = 16 clusters */ + sbi->s_stripe =EXT4_C2B (sbi,16 ); +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_criteria =CR_GOAL_LEN_FAST ; + ac.ac_g_ex.fe_len =16 ; + ac.ac_o_ex.fe_len =16 ; + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_scan_aligned_test (&ac, &e4b); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_release_context_test (&ac); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_group,TEST_GOAL_GROUP ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,16 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,16 ); + + sbi->s_stripe =0 ; +ext4_mb_unload_buddy_test (&e4b); +} + +static void test_mb_complex_scan_and_measure (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct inode *inode; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* +* Create 3 power-of-2 aligned free extents in TEST_GOAL_GROUP: +* - [0, 4) len 4 (order 2 buddy) +* - [16, 32) len 16 (order 4 buddy) +* - [40, 48) len 8 (order 3 buddy) +* Mark everything else used (total free = 28 clusters). +*/ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,4 ,12 ); +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,32 ,8 ); +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,48 , max -48 ); +ext4_get_group_info (sb,TEST_GOAL_GROUP )->bb_free =28 ; + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* +* Case 1: Goal len = 5 at CR_GOAL_LEN_SLOW. +* Scans [0, 4) (len 4 < 5), [16, 32) (order 4 buddy -> len 16 > 5), +* and [40, 48) (order 3 buddy -> len 8 > 5, smaller than 16 so preferred!), +* then allocates 5 clusters from [40, 48) at finish_group. +*/ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_criteria =CR_GOAL_LEN_SLOW ; + ac.ac_g_ex.fe_len =5 ; + ac.ac_o_ex.fe_len =5 ; + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_complex_scan_group_test (&ac, &e4b); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_release_context_test (&ac); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,40 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,5 ); + +/* +* Case 2: Goal len = 32 (larger than any free extent) with s_mb_max_to_scan = 1. +* Scanning [0, 4) and [16, 32) increments ac_found to 2 > s_mb_max_to_scan, +* triggering AC_STATUS_BREAK with best smaller extent [16, 32) (len 16) +* recorded in ac_b_ex. Calling ext4_mb_try_best_found() then claims [16, 32). +*/ + sbi->s_mb_max_to_scan =1 ; +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_criteria =CR_ANY_FREE ; + ac.ac_g_ex.fe_len =32 ; + ac.ac_o_ex.fe_len =32 ; + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_complex_scan_group_test (&ac, &e4b); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_BREAK ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,16 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,16 ); + +ext4_mb_try_best_found_test (&ac, &e4b); +ext4_mb_release_context_test (&ac); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,16 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,16 ); + +/* +* Case 3: EXT4_MB_HINT_FIRST immediately takes the first free extent [0, 4). +*/ + sbi->s_mb_max_to_scan =200 ; +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_criteria =CR_ANY_FREE ; + ac.ac_flags =EXT4_MB_HINT_FIRST ; + ac.ac_g_ex.fe_len =4 ; + ac.ac_o_ex.fe_len =4 ; + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_complex_scan_group_test (&ac, &e4b); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); +ext4_mb_release_context_test (&ac); + +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_start,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,4 ); + +ext4_mb_unload_buddy_test (&e4b); +} + +static void test_mb_regular_allocator (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_allocation_context ac = {}; +struct inode *inode; +int ret, hash; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* +* 1. EXT4_MB_HINT_GOAL_ONLY when goal block (group 0, cluster 0) is already +* marked used: must stop immediately without scanning other blocks. +*/ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_GOAL_ONLY ; + ac.ac_g_ex.fe_group =0 ; + ac.ac_g_ex.fe_start =0 ; + ac.ac_g_ex.fe_len =1 ; + ac.ac_o_ex = ac.ac_g_ex; + + ret =ext4_mb_regular_allocator_test (&ac); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_CONTINUE ); + +/* +* 2. Stream allocation (EXT4_MB_STREAM_ALLOC) with group 0 full: +* allocates in group 1 and updates s_mb_last_groups[hash] to 1. +*/ +mbt_ctx_mark_used (sb,0 ,0 ,EXT4_CLUSTERS_PER_GROUP (sb)); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,0 )->desc,0 ); +ext4_get_group_info (sb,0 )->bb_free =0 ; + +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_STREAM_ALLOC |EXT4_MB_HINT_DATA ; + ac.ac_g_ex.fe_len =8 ; + ac.ac_orig_goal_len =8 ; + ac.ac_o_ex.fe_len =8 ; + + ret =ext4_mb_regular_allocator_test (&ac); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_group,1 ); + + hash = (unsigned int )inode->i_ino % sbi->s_mb_nr_global_goals; +KUNIT_EXPECT_EQ (test,READ_ONCE (sbi->s_mb_last_groups[hash]),1 ); + +/* +* 3. MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming: +* Make group 2 the only group with free blocks, fragmented into two +* 8-cluster chunks [0, 8) and [16, 24) so largest_free_order = 3 +* and avg_fragment_size = 8. +* Note: group 2 may have already been prefetched during step 2, so +* mark its blocks used via mb_mark_used_test on the loaded buddy. +*/ +set_opt2 (sb,MB_OPTIMIZE_SCAN ); +mbt_ctx_mark_used (sb,1 ,0 ,EXT4_CLUSTERS_PER_GROUP (sb)); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,1 )->desc,0 ); +ext4_get_group_info (sb,1 )->bb_free =0 ; +ext4_get_group_info (sb,1 )->bb_fragments =0 ; +mb_set_largest_free_order_test (sb,ext4_get_group_info (sb,1 )); +mb_update_avg_fragment_size_test (sb,ext4_get_group_info (sb,1 )); + +mbt_ctx_mark_used (sb,3 ,0 ,EXT4_CLUSTERS_PER_GROUP (sb)); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,3 )->desc,0 ); +ext4_get_group_info (sb,3 )->bb_free =0 ; +ext4_get_group_info (sb,3 )->bb_fragments =0 ; +mb_set_largest_free_order_test (sb,ext4_get_group_info (sb,3 )); +mb_update_avg_fragment_size_test (sb,ext4_get_group_info (sb,3 )); + + { +struct ext4_buddy e4b; +struct ext4_free_extent ex; + + ret =ext4_mb_load_buddy_test (sb,2 , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_lock_group (sb,2 ); + ex.fe_group =2 ; + ex.fe_start =8 ; + ex.fe_len =8 ; +mb_mark_used_test (&e4b, &ex); + ex.fe_start =24 ; + ex.fe_len =EXT4_CLUSTERS_PER_GROUP (sb) -24 ; +mb_mark_used_test (&e4b, &ex); +ext4_unlock_group (sb,2 ); +ext4_mb_unload_buddy_test (&e4b); + } + +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_DATA ; + ac.ac_g_ex.fe_group =0 ; + ac.ac_g_ex.fe_len =16 ; + ac.ac_orig_goal_len =16 ; + ac.ac_o_ex.fe_len =8 ; + + ret =ext4_mb_regular_allocator_test (&ac); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_status,AC_STATUS_FOUND ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_group,2 ); +KUNIT_EXPECT_EQ (test, ac.ac_b_ex.fe_len,8 ); +} + +static void test_mb_prefetch (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_group_info *grp0, *grp1, *grp2; +ext4_group_t next_grp; +int ios =0 ; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + grp0 =ext4_get_group_info (sb,0 ); + grp1 =ext4_get_group_info (sb,1 ); + grp2 =ext4_get_group_info (sb,2 ); +KUNIT_ASSERT_NOT_NULL (test, grp0); +KUNIT_ASSERT_NOT_NULL (test, grp1); +KUNIT_ASSERT_NOT_NULL (test, grp2); + +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp0)); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp1)); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2)); + + next_grp =ext4_mb_prefetch (sb,0 ,2 , &ios); +KUNIT_EXPECT_EQ (test, next_grp,2 ); +/* First prefetch of uninitialized buffers increments ios count */ +KUNIT_EXPECT_EQ (test, ios,2 ); + +/* Repeated prefetch on the same groups does not re-read bitmaps */ + ios =0 ; +ext4_mb_prefetch (sb,0 ,2 , &ios); +KUNIT_EXPECT_EQ (test, ios,0 ); + +/* ext4_mb_prefetch_fini initializes the prefetched groups [0, 2) */ +ext4_mb_prefetch_fini (sb, next_grp,2 ); +KUNIT_EXPECT_FALSE (test,EXT4_MB_GRP_NEED_INIT (grp0)); +KUNIT_EXPECT_FALSE (test,EXT4_MB_GRP_NEED_INIT (grp1)); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2)); +} + +static void test_mb_initialize_context (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_allocation_context ac = {}; +struct ext4_allocation_request ar = {}; +struct inode *inode; + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* 1. Small open file (<= s_mb_stream_request) uses locality group alloc */ +i_size_write (inode, sb->s_blocksize); + ar.inode = inode; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + ar.flags =EXT4_MB_HINT_DATA ; + +ext4_mb_initialize_context_test (&ac, &ar); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_NE (test, ac.ac_flags &EXT4_MB_HINT_GROUP_ALLOC ,0 ); +KUNIT_EXPECT_NOT_NULL (test, ac.ac_lg); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_group,TEST_GOAL_GROUP ); + +/* 2. Large open file (> s_mb_stream_request) uses stream alloc */ +memset (&ac,0 ,sizeof (ac)); +i_size_write (inode, (loff_t)(sbi->s_mb_stream_request +64 ) << sb->s_blocksize_bits); +ext4_mb_initialize_context_test (&ac, &ar); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_NE (test, ac.ac_flags &EXT4_MB_STREAM_ALLOC ,0 ); +KUNIT_EXPECT_NULL (test, ac.ac_lg); + +/* +* 3. Closed file (i_writecount == 0) with size == isize and +* size > s_mb_stream_request sets EXT4_MB_HINT_NOPREALLOC. +*/ +memset (&ac,0 ,sizeof (ac)); +atomic_set (&inode->i_writecount,0 ); + ar.logical =EXT4_LBLK_CMASK (sbi, sbi->s_mb_stream_request +EXT4_C2B (sbi,2 )); + ar.len =1 ; +i_size_write (inode, (loff_t)(ar.logical +EXT4_C2B (sbi,1 )) << sb->s_blocksize_bits); +/* Also test out-of-range ar.goal fallback to group 0 */ + ar.goal =ext4_blocks_count (sbi->s_es) +100 ; +ext4_mb_initialize_context_test (&ac, &ar); +ext4_mb_release_context_test (&ac); +KUNIT_EXPECT_NE (test, ac.ac_flags &EXT4_MB_HINT_NOPREALLOC ,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_o_ex.fe_group,0 ); +KUNIT_EXPECT_EQ (test, ac.ac_o_ex.fe_start,0 ); +} + +static void test_mb_normalize_request (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_allocation_context ac = {}; +struct ext4_allocation_request ar = {}; +struct inode *inode; +struct ext4_inode_info *ei; +struct ext4_prealloc_space left_pa = {}, right_pa = {}; +int bsbits = sb->s_blocksize_bits; + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + ei =EXT4_I (inode); + +/* 1. Metadata request (no EXT4_MB_HINT_DATA) is not normalized */ + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_o_ex.fe_logical =0 ; + ac.ac_o_ex.fe_len =1 ; + ac.ac_g_ex = ac.ac_o_ex; +ext4_mb_normalize_request_test (&ac, &ar); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_len,1 ); + +/* 2. Locality group request normalizes fe_len to s_mb_group_prealloc */ +memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA |EXT4_MB_HINT_GROUP_ALLOC ; + ac.ac_lg =raw_cpu_ptr (sbi->s_locality_groups); + ac.ac_o_ex.fe_len =1 ; + ac.ac_g_ex = ac.ac_o_ex; +ext4_mb_normalize_request_test (&ac, &ar); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_len, sbi->s_mb_group_prealloc); + +/* 3. Small file (<= 16KB) normalizes up to max(SZ_16K, cluster_size) */ +if ((SZ_16K >> bsbits) >= sbi->s_cluster_ratio) { +memset (&ac,0 ,sizeof (ac)); +i_size_write (inode,4096 ); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA ; + ac.ac_o_ex.fe_logical =0 ; + ac.ac_o_ex.fe_len =1 ; + ac.ac_g_ex = ac.ac_o_ex; +ext4_mb_normalize_request_test (&ac, &ar); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_len, +EXT4_NUM_B2C (sbi,SZ_16K >> bsbits)); + } + +/* 4. 200KB file normalizes up to next power of two (256KB) */ +if ((SZ_256K >> bsbits) >= sbi->s_cluster_ratio) { +memset (&ac,0 ,sizeof (ac)); +i_size_write (inode,200 *1024 ); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA ; + ac.ac_o_ex.fe_logical =0 ; + ac.ac_o_ex.fe_len =1 ; + ac.ac_g_ex = ac.ac_o_ex; +ext4_mb_normalize_request_test (&ac, &ar); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_len, +EXT4_NUM_B2C (sbi,SZ_256K >> bsbits)); + } + +/* +* 5. Trimming against left/right allocated neighbors (ar.pleft / ar.pright) +* and against existing inode preallocations (ext4_mb_pa_adjust_overlap). +*/ +if (((loff_t )EXT4_C2B (sbi,16 ) << bsbits) <=SZ_1M ) { +memset (&ac,0 ,sizeof (ac)); +memset (&ar,0 ,sizeof (ar)); +i_size_write (inode, (loff_t )EXT4_C2B (sbi,16 ) << bsbits); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA ; + ac.ac_o_ex.fe_logical =EXT4_C2B (sbi,4 ); + ac.ac_o_ex.fe_len =1 ; + ac.ac_g_ex = ac.ac_o_ex; + +/* Left neighbor ends at cluster 2 (logical block EXT4_C2B(sbi, 2) - 1) */ + ar.lleft =EXT4_C2B (sbi,2 ) -1 ; + ar.pleft =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ) + ar.lleft; +/* Right neighbor starts at cluster 10 */ + ar.lright =EXT4_C2B (sbi,10 ); + ar.pright =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ) + ar.lright; + +/* +* Also insert a left PA covering clusters [2, 3) and a right PA covering +* clusters [8, 10) into ei->i_prealloc_node so ext4_mb_pa_adjust_overlap +* trims the range further to clusters [3, 8) (5 clusters). +*/ +spin_lock_init (&left_pa.pa_lock); + left_pa.pa_lstart =EXT4_C2B (sbi,2 ); + left_pa.pa_len =1 ; + left_pa.pa_free =1 ; + left_pa.pa_deleted =0 ; + +spin_lock_init (&right_pa.pa_lock); + right_pa.pa_lstart =EXT4_C2B (sbi,8 ); + right_pa.pa_len =2 ; + right_pa.pa_free =2 ; + right_pa.pa_deleted =0 ; + +rb_link_node (&left_pa.pa_node.inode_node,NULL , + &ei->i_prealloc_node.rb_node); +rb_insert_color (&left_pa.pa_node.inode_node, &ei->i_prealloc_node); +rb_link_node (&right_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node, + &left_pa.pa_node.inode_node.rb_right); +rb_insert_color (&right_pa.pa_node.inode_node, &ei->i_prealloc_node); + +ext4_mb_normalize_request_test (&ac, &ar); + ei->i_prealloc_node =RB_ROOT ; + +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_logical,EXT4_C2B (sbi,3 )); +KUNIT_EXPECT_EQ (test, ac.ac_g_ex.fe_len,5 ); + } +} + +static void test_mb_inode_pa_lifecycle (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode; +struct ext4_inode_info *ei; +struct ext4_allocation_request ar = {}; +struct ext4_group_info *grp; +ext4_group_t pa_grp; +ext4_grpblk_t pa_off, free_before; +ext4_fsblk_t blk1, blk2; +void *pa_bitmap; +int err =0 ; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + ei =EXT4_I (inode); +/* Large file size (> s_mb_stream_request) so inode PA is used */ +i_size_write (inode, (loff_t)(sbi->s_mb_stream_request +64 ) << sb->s_blocksize_bits); + + ar.inode = inode; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + ar.flags =EXT4_MB_HINT_DATA ; + + blk1 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_NE (test, blk1,0ULL ); +KUNIT_EXPECT_EQ (test, ar.len,1 ); +KUNIT_EXPECT_EQ (test,atomic_read (&ei->i_prealloc_active),1 ); +KUNIT_EXPECT_FALSE (test,RB_EMPTY_ROOT (&ei->i_prealloc_node)); + +ext4_get_group_no_and_offset (sb, blk1, &pa_grp, &pa_off); + grp =ext4_get_group_info (sb, pa_grp); + free_before =ext4_free_group_clusters (sb, &MBT_GRP_CTX (sb, pa_grp)->desc) +1 ; + +/* Verify ext4_mb_generate_from_pa marks the PA's clusters in a bitmap */ + pa_bitmap =kunit_kzalloc (test, sb->s_blocksize,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, pa_bitmap); +ext4_lock_group (sb, pa_grp); +ext4_mb_generate_from_pa_test (sb, pa_bitmap, pa_grp); +ext4_unlock_group (sb, pa_grp); +KUNIT_EXPECT_NE (test,mb_test_bit_test (pa_off, pa_bitmap),0 ); + +/* Second sequential allocation is served directly from the inode PA */ + ar.logical =EXT4_C2B (sbi,1 ); + ar.len =1 ; + ar.goal = blk1 +EXT4_C2B (sbi,1 ); + blk2 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, blk2, blk1 +EXT4_C2B (sbi,1 )); + +/* Discard inode preallocations and verify cleanup */ +ext4_discard_preallocations (inode); +KUNIT_EXPECT_EQ (test,atomic_read (&ei->i_prealloc_active),0 ); +KUNIT_EXPECT_TRUE (test,RB_EMPTY_ROOT (&ei->i_prealloc_node)); +/* Only the 2 allocated clusters should remain used in the group */ +KUNIT_EXPECT_EQ (test, grp->bb_free, free_before -2 ); +} + +static void test_mb_group_pa_lifecycle (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode1, *inode2; +struct ext4_allocation_request ar = {}; +struct ext4_group_info *grp; +ext4_fsblk_t blk1, blk2; +int err =0 , discarded; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode1 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2->i_ino =13 ; + +/* Small files (<= s_mb_stream_request) use locality group PA (MB_GROUP_PA) */ +i_size_write (inode1, sb->s_blocksize); +i_size_write (inode2, sb->s_blocksize); + + ar.inode = inode1; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + ar.flags =EXT4_MB_HINT_DATA ; + + blk1 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, blk1,ext4_group_first_block_no (sb,TEST_GOAL_GROUP )); + +/* Second small file allocation reuses the locality group PA */ + ar.inode = inode2; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + blk2 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, blk2, blk1 +EXT4_C2B (sbi,1 )); + +/* Discard all group preallocations and verify free count is restored */ + discarded =ext4_mb_discard_preallocations_test (sb,0 ); +rcu_barrier (); +KUNIT_EXPECT_EQ (test, discarded, (int )sbi->s_mb_group_prealloc -2 ); + + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); +KUNIT_EXPECT_EQ (test, grp->bb_free,EXT4_CLUSTERS_PER_GROUP (sb) -2 ); +} + +static void test_mb_lg_list_trim (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_locality_group *lg; +struct inode *inode; +struct ext4_buddy e4b; +struct ext4_prealloc_space *pa; +int i, ret, count =0 ; +int order =fls (15 ) -1 ;/* pa_free = 15 -> order 3 */ + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + sbi->s_mb_group_prealloc =16 ; + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* +* Create 9 locality-group PAs in bucket order 3 (each of length 16 with +* 1 cluster used -> pa_free = 15). When the 9th PA is added via +* ext4_mb_release_context -> ext4_mb_add_n_trim, lg_prealloc_count > 8 +* triggers ext4_mb_discard_lg_preallocations() to trim the list to 5! +*/ +for (i =0 ; i <9 ; i++) { +struct ext4_allocation_context ac = {}; +struct ext4_free_extent ex = { + .fe_group =TEST_GOAL_GROUP , + .fe_start = i *32 , + .fe_len =16 , + }; + + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA |EXT4_MB_HINT_GROUP_ALLOC ; + ac.ac_lg =raw_cpu_ptr (sbi->s_locality_groups); +mutex_lock (&ac.ac_lg->lg_mutex); + + ret =ext4_mb_pa_alloc_test (&ac); +if (ret) { +mutex_unlock (&ac.ac_lg->lg_mutex); +ext4_mb_unload_buddy_test (&e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + } + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +mb_mark_used_test (&e4b, &ex); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + + ac.ac_status =AC_STATUS_FOUND ; + ac.ac_o_ex.fe_len =1 ; + ac.ac_b_ex = ex; + ac.ac_f_ex = ex; +ext4_mb_new_preallocation_test (&ac); +/* Release context updates pa_free to 15 and runs ext4_mb_add_n_trim */ +ext4_mb_release_context_test (&ac); + } + +ext4_mb_unload_buddy_test (&e4b); + + lg =raw_cpu_ptr (sbi->s_locality_groups); +spin_lock (&lg->lg_prealloc_lock); +list_for_each_entry (pa, &lg->lg_prealloc_list[order], pa_node.lg_list) + count++; +spin_unlock (&lg->lg_prealloc_lock); + +KUNIT_EXPECT_EQ (test, count,5 ); +} + +static void test_mb_new_blocks_and_enospc_retry (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode1, *inode2; +struct ext4_allocation_request ar = {}; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +ext4_fsblk_t blk; +int err =0 ; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode1 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2->i_ino =14 ; +i_size_write (inode1, sb->s_blocksize); + +/* +* Leave only 16 free clusters in group 1 and mark groups 0, 2, 3 full. +* Set s_mb_group_prealloc = 16 so allocating 1 cluster for inode1 +* preallocates the remaining 15 clusters into a group PA (leaving +* 0 free clusters in buddy for all groups). +*/ +mbt_ctx_mark_used (sb,0 ,0 , max); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,0 )->desc,0 ); +ext4_get_group_info (sb,0 )->bb_free =0 ; + +mbt_ctx_mark_used (sb,1 ,16 , max -16 ); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,1 )->desc,16 ); +ext4_get_group_info (sb,1 )->bb_free =16 ; + +mbt_ctx_mark_used (sb,2 ,0 , max); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,2 )->desc,0 ); +ext4_get_group_info (sb,2 )->bb_free =0 ; + +mbt_ctx_mark_used (sb,3 ,0 , max); +ext4_free_group_clusters_set (sb, &MBT_GRP_CTX (sb,3 )->desc,0 ); +ext4_get_group_info (sb,3 )->bb_free =0 ; + +percpu_counter_set (&sbi->s_freeclusters_counter,16 ); + sbi->s_mb_group_prealloc =16 ; + + ar.inode = inode1; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,1 ); + ar.flags =EXT4_MB_HINT_DATA ; + + blk =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test,ext4_get_group_info (sb,1 )->bb_free,0 ); + +/* +* Now request 4 metadata clusters (no EXT4_MB_HINT_DATA so it cannot +* use the PA directly). First allocator pass finds 0 free clusters, +* then ext4_mb_discard_preallocations_should_retry() discards the PA +* (recovering 15 clusters) and retries, succeeding! +*/ +memset (&ar,0 ,sizeof (ar)); + ar.inode = inode2; + ar.len =4 ; + ar.goal =ext4_group_first_block_no (sb,1 ); + ar.flags =0 ; + + blk =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_NE (test, blk,0ULL ); +KUNIT_EXPECT_EQ (test, ar.len,4 ); + +/* +* The 4-cluster power-of-2 allocation claimed [4, 8), leaving two +* fragments [1, 4) (3 clusters) and [8, 16) (8 clusters). +* Requesting 11 clusters allocates the largest fragment (8 clusters), +* then requesting 3 clusters allocates [1, 4), and the next request +* returns -ENOSPC. +*/ + ar.len =11 ; + blk =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, ar.len,8 ); + + ar.len =3 ; + blk =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, ar.len,3 ); + + ar.len =1 ; + blk =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_EXPECT_EQ (test, err, -ENOSPC ); +KUNIT_EXPECT_EQ (test, blk,0ULL ); +} + +static int +ext4_handle_dirty_metadata_Updated_stub (const char *where,unsigned int line, +handle_t *handle,struct inode *inode, +struct buffer_head *bh) +{ +return 0 ; +} + +static void test_mb_mark_context_and_mark_bb (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_group_desc *gdp1, *gdp2; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +ext4_grpblk_t changed =0 ; +ext4_fsblk_t boundary_blk; +__u32 free_before; +int ret; + +/* Test the real ext4_mb_mark_context implementation */ +kunit_deactivate_static_stub (test, ext4_mb_mark_context); +kunit_activate_static_stub (test, __ext4_handle_dirty_metadata, + ext4_handle_dirty_metadata_Updated_stub); + + gdp1 =ext4_get_group_desc (sb,1 ,NULL ); + gdp2 =ext4_get_group_desc (sb,2 ,NULL ); +KUNIT_ASSERT_NOT_NULL (test, gdp1); +KUNIT_ASSERT_NOT_NULL (test, gdp2); + free_before =ext4_free_group_clusters (sb, gdp1); + +/* 1. Mark [10, 20) used with EXT4_MB_BITMAP_MARKED_CHECK (0x1) */ + ret =ext4_mb_mark_context (NULL , sb, true,1 ,10 ,10 ,0x0001 , &changed); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, changed,10 ); +KUNIT_EXPECT_EQ (test,ext4_free_group_clusters (sb, gdp1), free_before -10 ); + +/* 2. Mark overlapping [15, 25) used -> only 5 new clusters changed */ + ret =ext4_mb_mark_context (NULL , sb, true,1 ,15 ,10 ,0x0001 , &changed); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, changed,5 ); +KUNIT_EXPECT_EQ (test,ext4_free_group_clusters (sb, gdp1), free_before -15 ); + +/* 3. Clear [10, 25) -> 15 clusters freed */ + ret =ext4_mb_mark_context (NULL , sb, false,1 ,10 ,15 ,0x0001 , &changed); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, changed,15 ); +KUNIT_EXPECT_EQ (test,ext4_free_group_clusters (sb, gdp1), free_before); + +/* +* 4. Test ext4_mb_mark_bb across the boundary between group 1 and group 2: +* 2 clusters at the end of group 1 + 3 clusters at the start of group 2. +*/ +kunit_activate_static_stub (test, ext4_mb_mark_context, + ext4_mb_mark_context_stub); + boundary_blk =ext4_group_first_block_no (sb,2 ) -EXT4_C2B (sbi,2 ); +ext4_mb_mark_bb (sb, boundary_blk,EXT4_C2B (sbi,5 ), true); + +KUNIT_EXPECT_NE (test,mb_test_bit_test (max -2 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (max -1 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (0 ,mbt_ctx_bitmap (sb,2 )),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (2 ,mbt_ctx_bitmap (sb,2 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (3 ,mbt_ctx_bitmap (sb,2 )),0 ); + +ext4_mb_mark_bb (sb, boundary_blk,EXT4_C2B (sbi,5 ), false); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (max -2 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (0 ,mbt_ctx_bitmap (sb,2 )),0 ); +} + +static void test_ext4_free_blocks_flags_and_cross_group (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode; +struct ext4_buddy e4b; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +ext4_fsblk_t grp1_first =ext4_group_first_block_no (sb,1 ); +ext4_fsblk_t grp2_first =ext4_group_first_block_no (sb,2 ); +s64 free_before; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* Mark clusters [10, 20) and [max - 2, max) in group 1, and [0, 3) in group 2 used */ +mbt_ctx_mark_used (sb,1 ,10 ,10 ); +mbt_ctx_mark_used (sb,1 , max -2 ,2 ); +mbt_ctx_mark_used (sb,2 ,0 ,3 ); +ext4_get_group_info (sb,1 )->bb_free -=12 ; +ext4_get_group_info (sb,2 )->bb_free -=3 ; + + ret =ext4_mb_load_buddy_test (sb,1 , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + ret =ext4_mb_load_buddy_test (sb,2 , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + +/* +* 1. EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER: +* Freeing from cluster 10 + 2 blocks through cluster 12 + 3 blocks +* skips partial clusters 10 and 12 and frees only full cluster 11! +*/ +ext4_free_blocks (NULL , inode,NULL , + grp1_first +EXT4_C2B (sbi,10 ) +2 , +EXT4_C2B (sbi,2 ) -2 +3 , +EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER | +EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER | +EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); + +KUNIT_EXPECT_NE (test,mb_test_bit_test (10 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (11 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_NE (test,mb_test_bit_test (12 ,mbt_ctx_bitmap (sb,1 )),0 ); + +/* +* 2. EXT4_FREE_BLOCKS_RERESERVE_CLUSTER: frees cluster 12 in bitmap & buddy +* without incrementing s_freeclusters_counter. +*/ + free_before =percpu_counter_sum (&sbi->s_freeclusters_counter); +ext4_free_blocks (NULL , inode,NULL , + grp1_first +EXT4_C2B (sbi,12 ), +EXT4_C2B (sbi,1 ), +EXT4_FREE_BLOCKS_RERESERVE_CLUSTER | +EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (12 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_EQ (test,percpu_counter_sum (&sbi->s_freeclusters_counter), + free_before); + +/* +* 3. Cross-group boundary free: 2 clusters at end of group 1 + 3 clusters +* at start of group 2. +*/ +ext4_free_blocks (NULL , inode,NULL , + grp2_first -EXT4_C2B (sbi,2 ), +EXT4_C2B (sbi,5 ), +EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (max -2 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (max -1 ,mbt_ctx_bitmap (sb,1 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (0 ,mbt_ctx_bitmap (sb,2 )),0 ); +KUNIT_EXPECT_EQ (test,mb_test_bit_test (2 ,mbt_ctx_bitmap (sb,2 )),0 ); +} + +static void test_mb_free_metadata_and_process_freed_data (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode; +struct ext4_buddy e4b; +struct ext4_group_info *grp; +struct ext4_free_data *entry; +transaction_t trans = { .t_tid =42 }; +handle_t handle = { .h_transaction = &trans }; +ext4_fsblk_t grp1_first =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); +ext4_grpblk_t merged_start =0 , merged_count =0 ; +int node_count =0 , ret; +struct rb_node *n; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + +/* Mark clusters [20, 28) used in group 1 and load buddy */ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,20 ,8 ); + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); + grp->bb_free -=8 ; + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + +/* +* Free [20, 22), then [25, 28), then the middle [22, 25) as metadata +* with a valid journal handle (tid = 42). +* This exercises rbtree insertion and both prev and next extent merging! +*/ +ext4_free_blocks (&handle, inode,NULL , + grp1_first +EXT4_C2B (sbi,20 ),EXT4_C2B (sbi,2 ), +EXT4_FREE_BLOCKS_METADATA |EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); +ext4_free_blocks (&handle, inode,NULL , + grp1_first +EXT4_C2B (sbi,25 ),EXT4_C2B (sbi,3 ), +EXT4_FREE_BLOCKS_METADATA |EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); +ext4_free_blocks (&handle, inode,NULL , + grp1_first +EXT4_C2B (sbi,22 ),EXT4_C2B (sbi,3 ), +EXT4_FREE_BLOCKS_METADATA |EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); + +KUNIT_EXPECT_EQ (test,atomic_read (&sbi->s_mb_free_pending),8 ); +/* Blocks are not yet freed in buddy until transaction commit */ +KUNIT_EXPECT_EQ (test, grp->bb_free,EXT4_CLUSTERS_PER_GROUP (sb) -8 ); + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +for (n =rb_first (&grp->bb_free_root); n; n =rb_next (n)) { + entry = rb_entry(n, struct ext4_free_data, efd_node); + merged_start = entry->efd_start_cluster; + merged_count = entry->efd_count; + node_count++; + } +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + +/* All 3 freed extents for tid 42 must have merged into a single node [20, 28) */ +KUNIT_EXPECT_EQ (test, node_count,1 ); +KUNIT_EXPECT_EQ (test, merged_start,20 ); +KUNIT_EXPECT_EQ (test, merged_count,8 ); + +/* Commit tid 42 -> ext4_process_freed_data releases [20, 28) into buddy */ +ext4_process_freed_data (sb,42 ); +KUNIT_EXPECT_EQ (test,atomic_read (&sbi->s_mb_free_pending),0 ); +KUNIT_EXPECT_TRUE (test,RB_EMPTY_ROOT (&grp->bb_free_root)); +KUNIT_EXPECT_EQ (test, grp->bb_free,EXT4_CLUSTERS_PER_GROUP (sb)); +} + +static void test_ext4_group_add_blocks (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_group_info *grp; +ext4_fsblk_t grp1_first =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); +s64 free_before; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + +/* Mark [50, 60) used in group 1 and initialize buddy */ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,50 ,10 ); + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); + grp->bb_free -=10 ; + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b); + + free_before =percpu_counter_sum (&sbi->s_freeclusters_counter); + ret =ext4_group_add_blocks (NULL , sb, + grp1_first +EXT4_C2B (sbi,50 ), +EXT4_C2B (sbi,10 )); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, grp->bb_free,EXT4_CLUSTERS_PER_GROUP (sb)); +KUNIT_EXPECT_EQ (test,percpu_counter_sum (&sbi->s_freeclusters_counter), + free_before +10 ); + +/* Cross-group boundary addition must fail with -EINVAL */ + ret =ext4_group_add_blocks (NULL , sb, + grp1_first +EXT4_C2B (sbi,EXT4_CLUSTERS_PER_GROUP (sb) -2 ), +EXT4_C2B (sbi,5 )); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + +/* System zone block (block 0) must fail with -EINVAL */ + ret =ext4_group_add_blocks (NULL , sb,0 ,EXT4_C2B (sbi,1 )); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); +} + +static int mbt_discard_calls; +static int mbt_discard_clusters; + +static int +ext4_issue_discard_count_stub (struct super_block *sb,ext4_group_t block_group, +ext4_grpblk_t cluster,int count) +{ + mbt_discard_calls++; + mbt_discard_clusters += count; +return 0 ; +} + +static void test_ext4_trim_fs (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct fstrim_range range = {}; +struct ext4_group_info *grp1; +struct inode *inode; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); +kunit_activate_static_stub (test, ext4_issue_discard, + ext4_issue_discard_count_stub); + +/* +* Mark groups 0, 2, 3 completely used. +* In group 1, leave only [10, 14) (4 clusters) and [30, 50) (20 clusters) free. +*/ +mbt_ctx_mark_used (sb,0 ,0 , max); +ext4_get_group_info (sb,0 )->bb_free =0 ; +mbt_ctx_mark_used (sb,2 ,0 , max); +ext4_get_group_info (sb,2 )->bb_free =0 ; +mbt_ctx_mark_used (sb,3 ,0 , max); +ext4_get_group_info (sb,3 )->bb_free =0 ; + +mbt_ctx_mark_used (sb,1 ,0 ,10 ); +mbt_ctx_mark_used (sb,1 ,14 ,16 ); +mbt_ctx_mark_used (sb,1 ,50 , max -50 ); + grp1 =ext4_get_group_info (sb,1 ); + grp1->bb_free =24 ; + +/* Invalid range checks */ + range.start =0 ; + range.len = sb->s_blocksize -1 ; + range.minlen =0 ; +KUNIT_EXPECT_EQ (test,ext4_trim_fs (sb, &range), -EINVAL ); + +/* Trim with minlen = 10 clusters: skips [10, 14) and trims only [30, 50) (20 clusters) */ + mbt_discard_calls =0 ; + mbt_discard_clusters =0 ; + range.start =0 ; + range.len = (u64 )ext4_blocks_count (sbi->s_es) << sb->s_blocksize_bits; + range.minlen = (u64 )EXT4_C2B (sbi,10 ) << sb->s_blocksize_bits; + + ret =ext4_trim_fs (sb, &range); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, mbt_discard_calls,1 ); +KUNIT_EXPECT_EQ (test, mbt_discard_clusters,20 ); +KUNIT_EXPECT_EQ (test, range.len, + (u64 )EXT4_C2B (sbi,20 ) << sb->s_blocksize_bits); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_WAS_TRIMMED (grp1)); + +/* Second trim with same minlen is skipped because WAS_TRIMMED is set */ + range.len = (u64 )ext4_blocks_count (sbi->s_es) << sb->s_blocksize_bits; + ret =ext4_trim_fs (sb, &range); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, mbt_discard_calls,1 ); +KUNIT_EXPECT_EQ (test, range.len,0ULL ); + +/* Freeing a block clears WAS_TRIMMED, allowing subsequent trim */ +ext4_free_blocks (NULL , inode,NULL , +ext4_group_first_block_no (sb,1 ) +EXT4_C2B (sbi,50 ), +EXT4_C2B (sbi,1 ),EXT4_FREE_BLOCKS_NO_QUOT_UPDATE ); +KUNIT_EXPECT_FALSE (test,EXT4_MB_GRP_WAS_TRIMMED (grp1)); +} + +struct mbt_query_ctx { +int meta_calls; +ext4_grpblk_t meta_start; +ext4_grpblk_t meta_len; +int free_calls; +ext4_grpblk_t free_starts[4 ]; +ext4_grpblk_t free_lens[4 ]; +int stop_after; +}; + +static int mbt_query_meta_cb (struct super_block *sb,ext4_group_t agno, +ext4_grpblk_t start,ext4_grpblk_t len,void *priv) +{ +struct mbt_query_ctx *q = priv; + + q->meta_calls++; + q->meta_start = start; + q->meta_len = len; +return 0 ; +} + +static int mbt_query_free_cb (struct super_block *sb,ext4_group_t agno, +ext4_grpblk_t start,ext4_grpblk_t len,void *priv) +{ +struct mbt_query_ctx *q = priv; + +if (q->free_calls <4 ) { + q->free_starts[q->free_calls] = start; + q->free_lens[q->free_calls] = len; + } + q->free_calls++; +if (q->stop_after && q->free_calls >= q->stop_after) +return -ECANCELED ; +return 0 ; +} + +static void test_ext4_mballoc_query_range (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct mbt_query_ctx q = {}; +ext4_grpblk_t max =EXT4_CLUSTERS_PER_GROUP (sb); +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + +/* +* In group 1: +* [0, 10) used (before bb_first_free = 10 -> reported to meta_formatter) +* [10, 15) free (len 5) +* [15, 25) used +* [25, 32) free (len 7) +* [32, max) used +*/ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,0 ,10 ); +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,15 ,10 ); +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,32 , max -32 ); +ext4_get_group_info (sb,TEST_GOAL_GROUP )->bb_free =12 ; + + ret =ext4_mballoc_query_range (sb,TEST_GOAL_GROUP ,0 ,100 , + mbt_query_meta_cb, mbt_query_free_cb, &q); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, q.meta_calls,1 ); +KUNIT_EXPECT_EQ (test, q.meta_start,0 ); +KUNIT_EXPECT_EQ (test, q.meta_len,10 ); +KUNIT_EXPECT_EQ (test, q.free_calls,2 ); +KUNIT_EXPECT_EQ (test, q.free_starts[0 ],10 ); +KUNIT_EXPECT_EQ (test, q.free_lens[0 ],5 ); +KUNIT_EXPECT_EQ (test, q.free_starts[1 ],25 ); +KUNIT_EXPECT_EQ (test, q.free_lens[1 ],7 ); + +/* Early abort from formatter callback propagates error code */ +memset (&q,0 ,sizeof (q)); + q.stop_after =1 ; + ret =ext4_mballoc_query_range (sb,TEST_GOAL_GROUP ,0 ,100 , +NULL , mbt_query_free_cb, &q); +KUNIT_EXPECT_EQ (test, ret, -ECANCELED ); +KUNIT_EXPECT_EQ (test, q.free_calls,1 ); +} +static const struct mbt_ext4_block_layout mbt_test_layouts[] = { { .blocksize_bits =10 ,
@@ -991,6 +2791,31 @@ static struct kunit_case mbt_test_cases[] = {KUNIT_CASE_PARAM (test_mb_mark_used, mbt_layouts_gen_params),KUNIT_CASE_PARAM (test_mb_free_blocks, mbt_layouts_gen_params),KUNIT_CASE_PARAM (test_mark_diskspace_used, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_bit_ops, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_test_and_clear_bits, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_find_buddy_and_order, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_find_extent, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_generate_buddy_corrupt, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_free_blocks_double_free_and_fc_replay, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_xarray_orders_and_frag_size, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_good_group, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_find_by_goal, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_simple_and_aligned_scan, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_complex_scan_and_measure, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_regular_allocator, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_prefetch, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_initialize_context, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_normalize_request, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_inode_pa_lifecycle, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_group_pa_lifecycle, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_lg_list_trim, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_new_blocks_and_enospc_retry, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_mark_context_and_mark_bb, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_ext4_free_blocks_flags_and_cross_group, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_mb_free_metadata_and_process_freed_data, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_ext4_group_add_blocks, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_ext4_trim_fs, mbt_layouts_gen_params), +KUNIT_CASE_PARAM (test_ext4_mballoc_query_range, mbt_layouts_gen_params),KUNIT_CASE_PARAM_ATTR (test_mb_mark_used_cost, mbt_layouts_gen_params, { .speed = KUNIT_SPEED_SLOW }), {}
fs/ext4/mballoc.c +200 -1
227 lines not on this page · raw message
fs/ext4/mballoc.h +49 -0
62 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 06/27] ext4: expand KUnit tests for fs/ext4/mballoc.c
Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [Medium] ext4: test_mb_good_group() and test_mb_prefetch() fail on 16K/64K PAGE_SIZE - [Low] ext4: unpinned…
Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [Medium] ext4: test_mb_good_group() and test_mb_prefetch() fail on 16K/64K PAGE_SIZE
- [Low] ext4: unpinned per-CPU locality group lookups across sleeps in mballoc-test.c
- [Low] ext4: unaligned __u32 accesses in mb_set_bits() and mb_test_and_clear_bits()
- [Low] ext4: test_mb_regular_allocator() step 3 skips CR_BEST_AVAIL_LEN trimming
- [Low] ext4: missing bb_free update in test_mb_simple_and_aligned_scan()
- [Low] ext4: unused *_test() wrapper functions in fs/ext4/mballoc.c --
commit 72a0b9666c2cc1afd5fa22724c492669c1b39ccf
Author: Theodore Ts'o <[email protected]>
ext4: expand KUnit tests for fs/ext4/mballoc.c
This commit expands the ext4_mballoc_test KUnit suite in fs/ext4/mballoc-test.c with 25 new parameterized tests and exports the corresponding helper wrappers from fs/ext4/mballoc.c.
Quoted 4 lines
fs/ext4/mballoc-test.c +0
-0
[ ... ]
Quoted 18 lines
fs/ext4/mballoc-test.c +14
-0@@ -949,6 +1008,1747 @@ static void test_mb_mark_used_cost(struct kunit *test)ext4_mb_unload_buddy_test (&e4b); } +static void test_mb_bit_ops (struct kunit *test) +{ +u8 *buf; +void *unaligned; +int bit, i; + + buf =kunit_kzalloc (test,128 ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, buf); + +/* +* Use an unaligned pointer (offset by 3 bytes) to exercise +* mb_correct_addr_and_bit() on 64-bit/32-bit architectures. +*/ + unaligned = buf +3 ;
[ ... ]
Quoted 19 lines
fs/ext4/mballoc-test.c +19
-0+/* Multi-word unaligned range spanning head bits, 32-bit words, and tail */ +mb_set_bits (unaligned,5 ,75 ); +KUNIT_EXPECT_EQ (test,mb_find_next_bit_test (unaligned,256 ,0 ),5 ); +KUNIT_EXPECT_EQ (test,mb_find_next_zero_bit_test (unaligned,256 ,5 ),80 ); +/* Clamping when no zero bit exists before max */ +KUNIT_EXPECT_EQ (test,mb_find_next_zero_bit_test (unaligned,50 ,5 ),50 ); + +/* Clear a sub-range across 32-bit boundaries */ +mb_clear_bits_test (unaligned,13 ,50 ); +for (i =0 ; i <100 ; i++) { +int expected = (i >=5 && i <13 ) || (i >=63 && i <80 ); + +KUNIT_EXPECT_EQ (test, !!mb_test_bit_test (i, unaligned), expected); + } +} + +static void test_mb_test_and_clear_bits (struct kunit *test) +{ +u8 *buf;
fs/ext4/mballoc-test.c static void test_mb_mark_used_cost(struct kunit *test) · line 1077
Quoted 10 lines
fs/ext4/mballoc-test.c +10
-0+void *bm; +int ret, i; + + buf =kunit_kzalloc (test,128 ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, buf); + bm = buf +3 ; + +/* Case 1: All bits in range [5, 85) are set -> returns -1 and clears all */ +memset (buf,0xff ,128 ); + ret =mb_test_and_clear_bits_test (bm,5 ,80 );
[Severity: Low]
Does passing buf + 3 to mb_set_bits() and mb_test_and_clear_bits_test() cause misaligned 32-bit accesses?
Unlike the single-bit helpers that align the base address via mb_correct_addr_and_bit(), mb_set_bits() and mb_test_and_clear_bits() take a 32-bit word fast path when (cur & 31) == 0 && (len - cur) >= 32 and dereference __u32 *addr = bm + (cur >> 3) directly. When cur reaches 32, addr is buf + 7, which triggers UBSAN alignment warnings under CONFIG_UBSAN_ALIGNMENT or alignment faults on strict-alignment architectures.
[ ... ]
Quoted 16 lines
fs/ext4/mballoc-test.c +16
-0+static void test_mb_good_group (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct ext4_group_info *grp1, *grp2; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + +/* Initialize group 1 buddy cache so bb_fragments and orders are populated */ + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); +ext4_mb_unload_buddy_test (&e4b);
[ ... ]
fs/ext4/mballoc-test.c static void test_mb_mark_used_cost(struct kunit *test) · line 1455
Quoted 13 lines
fs/ext4/mballoc-test.c +13
-0+/* +* Test ext4_mb_good_group_nolock on uninitialized group 2: +* At inexpensive CR_POWER2_ALIGNED, it skips initializing group 2 and returns 0. +* At expensive CR_GOAL_LEN_SLOW (with STRICT_CHECK), it initializes group 2 +* and returns 1. +*/ + grp2 =ext4_get_group_info (sb,2 ); +KUNIT_ASSERT_NOT_NULL (test, grp2); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2)); + + ac.ac_criteria = CR_POWER2_ALIGNED;\n> + ret = ext4_mb_good_group_nolock_test(&ac, 2, CR_POWER2_ALIGNED); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_TRUE (test,EXT4_MB_GRP_NEED_INIT (grp2));
[Severity: Medium]
Will test_mb_good_group() and test_mb_prefetch() fail on 16K or 64K PAGE_SIZE kernels?
ext4_mb_init_cache() initializes groups_per_folio = DIV_ROUND_UP(folio_size(folio) / blocksize, 2) consecutive groups at once whenever a buddy-cache folio is populated. When blocksize is 1K on a 16K page kernel, or 1K/4K on a 64K page kernel, groups_per_folio is at least 8, so loading group 1's buddy (or calling ext4_mb_prefetch_fini() on groups [0, 2) in test_mb_prefetch()) also initializes group 2 on folio 0 and clears EXT4_GROUP_INFO_NEED_INIT_BIT on grp2, causing the EXT4_MB_GRP_NEED_INIT(grp2) expectations in both tests to fail.
[ ... ]
Quoted 14 lines
fs/ext4/mballoc-test.c +14
-0+static void test_mb_simple_and_aligned_scan (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_buddy e4b; +struct ext4_allocation_context ac = {}; +struct inode *inode; +int ret; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); +
fs/ext4/mballoc-test.c static void test_mb_mark_used_cost(struct kunit *test) · line 1586
Quoted 10 lines
fs/ext4/mballoc-test.c +10
-0+/* +* Mark cluster 0 used in group 1 so: +* - order 3 buddy [8, 16) is the first order-3 buddy +* - first 16-cluster stripe [0, 16) is not completely free, so +* stripe-aligned scan must skip to cluster 16. +*/ +mbt_ctx_mark_used (sb,TEST_GOAL_GROUP ,0 ,1 ); + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 );
[Severity: Low]
Does marking cluster 0 used here without decrementing ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free trigger a false bitmap corruption error?
When ext4_mb_load_buddy_test() calls ext4_mb_generate_buddy(), the bitmap free count is 1 less than grp->bb_free, which logs an inconsistency error via ext4_grp_locked_error() and sets EXT4_GROUP_INFO_BBITMAP_CORRUPT on TEST_GOAL_GROUP.
[ ... ]
Quoted 2 lines
fs/ext4/mballoc-test.c +2
-0+static void test_mb_regular_allocator (struct kunit *test) +{
[ ... ]
Quoted 8 lines
fs/ext4/mballoc-test.c +8
-0+/* +* 3. MB_OPTIMIZE_SCAN with CR_BEST_AVAIL_LEN goal length trimming: +* Make group 2 the only group with free blocks, fragmented into two +* 8-cluster chunks [0, 8) and [16, 24) so largest_free_order = 3 +* and avg_fragment_size = 8. +* Note: group 2 may have already been prefetched during step 2, so +* mark its blocks used via mb_mark_used_test on the loaded buddy. +*/
[ ... ]
fs/ext4/mballoc-test.c static void test_mb_mark_used_cost(struct kunit *test) · line 1846
Quoted 11 lines
fs/ext4/mballoc-test.c +11
-0+memset (&ac,0 ,sizeof (ac)); + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_status =AC_STATUS_CONTINUE ; + ac.ac_flags =EXT4_MB_HINT_DATA ; + ac.ac_g_ex.fe_group =0 ; + ac.ac_g_ex.fe_len =16 ; + ac.ac_orig_goal_len =16 ; + ac.ac_o_ex.fe_len =8 ; + + ret =ext4_mb_regular_allocator_test (&ac);
[Severity: Low]
Does setting ac_o_ex.fe_len = 8 prevent ext4_mb_scan_groups_best_avail() from trimming ac_g_ex.fe_len down to 8 at CR_BEST_AVAIL_LEN?
In ext4_mb_scan_groups_best_avail(), order = fls(16) - 1 = 4 and min_order starts at 4 - 3 = 1, but because (1 << min_order) < ac->ac_o_ex.fe_len, it clamps min_order to fls(8) = 4:
fs/ext4/mballoc.c:ext4_mb_scan_groups_best_avail() {
...
order = fls(ac->ac_g_ex.fe_len) - 1;
...
min_order = order - sbi->s_mb_best_avail_max_trim_order;
if (min_order < 0)
min_order = 0;
if (1 << min_order < ac->ac_o_ex.fe_len)
min_order = fls(ac->ac_o_ex.fe_len);
for (i = order; i >= min_order; i--) {
...
}As a result, the loop only checks i = 4 (fe_len = 16) and never trims to i = 3 (fe_len = 8), so the allocation only succeeds after falling back to CR_GOAL_LEN_SLOW and ext4_mb_try_best_found(). Setting ac_o_ex.fe_len <= 4 would allow min_order <= 3 so CR_BEST_AVAIL_LEN trims fe_len to 8.
[ ... ]
Quoted 109 lines
fs/ext4/mballoc-test.c +109
-0+static void test_mb_group_pa_lifecycle (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct inode *inode1, *inode2; +struct ext4_allocation_request ar = {}; +struct ext4_group_info *grp; +ext4_fsblk_t blk1, blk2; +int err =0 , discarded; + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode1 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2 =mbt_alloc_test_inode (test, sb,S_IFREG ); + inode2->i_ino =13 ; + +/* Small files (<= s_mb_stream_request) use locality group PA (MB_GROUP_PA) */ +i_size_write (inode1, sb->s_blocksize); +i_size_write (inode2, sb->s_blocksize); + + ar.inode = inode1; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + ar.flags =EXT4_MB_HINT_DATA ; + + blk1 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, blk1,ext4_group_first_block_no (sb,TEST_GOAL_GROUP )); + +/* Second small file allocation reuses the locality group PA */ + ar.inode = inode2; + ar.logical =0 ; + ar.len =1 ; + ar.goal =ext4_group_first_block_no (sb,TEST_GOAL_GROUP ); + blk2 =ext4_mb_new_blocks (NULL , &ar, &err); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, blk2, blk1 +EXT4_C2B (sbi,1 )); + +/* Discard all group preallocations and verify free count is restored */ + discarded =ext4_mb_discard_preallocations_test (sb,0 ); +rcu_barrier (); +KUNIT_EXPECT_EQ (test, discarded, (int )sbi->s_mb_group_prealloc -2 ); + + grp =ext4_get_group_info (sb,TEST_GOAL_GROUP ); +KUNIT_EXPECT_EQ (test, grp->bb_free,EXT4_CLUSTERS_PER_GROUP (sb) -2 ); +} + +static void test_mb_lg_list_trim (struct kunit *test) +{ +struct super_block *sb = (struct super_block *)test->priv; +struct ext4_sb_info *sbi =EXT4_SB (sb); +struct ext4_locality_group *lg; +struct inode *inode; +struct ext4_buddy e4b; +struct ext4_prealloc_space *pa; +int i, ret, count =0 ; +int order =fls (15 ) -1 ;/* pa_free = 15 -> order 3 */ + +if (sb->s_blocksize >PAGE_SIZE ) +kunit_skip (test,"blocksize exceeds pagesize" ); + + inode =mbt_alloc_test_inode (test, sb,S_IFREG ); + sbi->s_mb_group_prealloc =16 ; + + ret =ext4_mb_load_buddy_test (sb,TEST_GOAL_GROUP , &e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* +* Create 9 locality-group PAs in bucket order 3 (each of length 16 with +* 1 cluster used -> pa_free = 15). When the 9th PA is added via +* ext4_mb_release_context -> ext4_mb_add_n_trim, lg_prealloc_count > 8 +* triggers ext4_mb_discard_lg_preallocations() to trim the list to 5! +*/ +for (i =0 ; i <9 ; i++) { +struct ext4_allocation_context ac = {}; +struct ext4_free_extent ex = { + .fe_group =TEST_GOAL_GROUP , + .fe_start = i *32 , + .fe_len =16 , + }; + + ac.ac_sb = sb; + ac.ac_inode = inode; + ac.ac_flags =EXT4_MB_HINT_DATA |EXT4_MB_HINT_GROUP_ALLOC ; + ac.ac_lg =raw_cpu_ptr (sbi->s_locality_groups); +mutex_lock (&ac.ac_lg->lg_mutex); + + ret =ext4_mb_pa_alloc_test (&ac); +if (ret) { +mutex_unlock (&ac.ac_lg->lg_mutex); +ext4_mb_unload_buddy_test (&e4b); +KUNIT_ASSERT_EQ (test, ret,0 ); + } + +ext4_lock_group (sb,TEST_GOAL_GROUP ); +mb_mark_used_test (&e4b, &ex); +ext4_unlock_group (sb,TEST_GOAL_GROUP ); + + ac.ac_status =AC_STATUS_FOUND ; + ac.ac_o_ex.fe_len =1 ; + ac.ac_b_ex = ex; + ac.ac_f_ex = ex; +ext4_mb_new_preallocation_test (&ac); +/* Release context updates pa_free to 15 and runs ext4_mb_add_n_trim */ +ext4_mb_release_context_test (&ac); + } +
fs/ext4/mballoc-test.c static void test_mb_mark_used_cost(struct kunit *test) · line 2242
Quoted 10 lines
fs/ext4/mballoc-test.c +10
-0+ext4_mb_unload_buddy_test (&e4b); + + lg =raw_cpu_ptr (sbi->s_locality_groups); +spin_lock (&lg->lg_prealloc_lock); +list_for_each_entry (pa, &lg->lg_prealloc_list[order], pa_node.lg_list) + count++; +spin_unlock (&lg->lg_prealloc_lock); + +KUNIT_EXPECT_EQ (test, count,5 ); +}
[Severity: Low]
Can CPU migration across sleeping calls cause test_mb_group_pa_lifecycle() and test_mb_lg_list_trim() to use different per-CPU sbi->s_locality_groups instances?
Both tests run in a preemptible KUnit kthread and call sleeping functions (ext4_mb_new_blocks(), mutex_lock(), and ext4_mb_pa_alloc_test()). If the kthread migrates CPUs between the two ext4_mb_new_blocks() calls in test_mb_group_pa_lifecycle(), the second call looks up the new CPU's empty lg_prealloc_list instead of reusing the first PA. Similarly, test_mb_lg_list_trim() re-evaluates raw_cpu_ptr(sbi->s_locality_groups) on each loop iteration and again when counting lg_prealloc_list[order], so a migration splits the 9 PAs across per-CPU lists and fails the count == 5 check.
Quoted 4 lines
fs/ext4/mballoc.c +0
-0
[ ... ]
Quoted 5 lines
fs/ext4/mballoc.c +5
-0+void mb_regenerate_buddy_test (struct ext4_buddy *e4b) +{ +mb_regenerate_buddy (e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (mb_regenerate_buddy_test);
[ ... ]
Quoted 7 lines
fs/ext4/mballoc.c +7
-0+void ext4_mb_measure_extent_test (struct ext4_allocation_context *ac, +struct ext4_free_extent *ex, +struct ext4_buddy *e4b) +{ +ext4_mb_measure_extent (ac, ex, e4b); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_measure_extent_test);
[ ... ]
Quoted 5 lines
fs/ext4/mballoc.c +5
-0+bool ext4_mb_use_preallocated_test (struct ext4_allocation_context *ac) +{ +return ext4_mb_use_preallocated (ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_use_preallocated_test);
[ ... ]
Quoted 9 lines
fs/ext4/mballoc.c +9
-0+void ext4_mb_pa_put_free_test (struct ext4_allocation_context *ac) +{ +ext4_mb_pa_put_free (ac); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_pa_put_free_test); + +void ext4_mb_generate_from_pa_test (struct super_block *sb,void *bitmap, +ext4_group_t group) +{
fs/ext4/mballoc.c void ext4_free_blocks_simple_test(struct inode *inode, ext4_fsblk_t block, · line 7457
Quoted 10 lines
fs/ext4/mballoc.c +10
-0+ext4_mb_generate_from_pa (sb, bitmap, group); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_generate_from_pa_test); + +int ext4_mb_discard_group_preallocations_test (struct super_block *sb, +ext4_group_t group,int *busy) +{ +return ext4_mb_discard_group_preallocations (sb, group, busy); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_discard_group_preallocations_test);
[Severity: Low]
This isn't a bug, but mb_regenerate_buddy_test(), ext4_mb_measure_extent_test(), ext4_mb_use_preallocated_test(), ext4_mb_pa_put_free_test(), and ext4_mb_discard_group_preallocations_test() have no callers in fs/ext4/mballoc-test.c.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Theodore Ts'o
maintainerPATCH 7/27 ext4: add KUnit tests for fs/ext4/inline.c
In reply to Theodore Ts'oAdd the ext4_inline_test KUnit test suite in fs/ext4/inline-test.c to comprehensively exercise inline data operations for regular files, symlinks, and directories in fs/ext4/inline.c without requiring a mounted block device:
- Inline capacity and discovery (ext4_get_max_inline_size and ext4_find_inline_data_nolock) across fresh inodes, inodes with zero extra_isize or 128-byte inode size, inodes with coexisting user xattrs in ibody, 0-byte and non-empty system.data xattrs, and corrupted xattr entries (e_name_len overflow and non-zero e_value_inum).
- Inline file creation, expansion, overwrite, and destruction (ext4_try_to_write_inline_data, ext4_write_inline_data_end, and ext4_destroy_inline_data) spanning i_block (< 60 bytes) and the ibody system.data xattr (>= 60 bytes), short writes with failed-write truncation, non-uptodate folios, emergency shutdown (EXT4_FLAGS_SHUTDOWN), concurrent inline flag clearing, and corrupted inline xattr state detection.
- Inline page reading, symlinks, and iomap mapping (ext4_readpage_inline on index 0 and index > 0, i_inline_size > PAGE_SIZE corruption detection, ext4_read_inline_link for short and long symlinks, and ext4_inline_data_iomap).
- Inline file truncation (ext4_inline_data_truncate) across size extensions, shrinking within system.data xattr, shrinking into i_block with tail zeroing, truncating to zero, and clearing the extent status tree when EXT4_STATE_MAY_INLINE_DATA is unset.
- Inline-to-extent conversion for regular files (ext4_convert_inline_data, ext4_convert_inline_data_to_extent, and ext4_da_convert_inline_data_to_extent via ext4_generic_write_inline_data), including DIOREAD_NOLOCK, DELALLOC, and journaled data modes, plus error rollback via ext4_restore_inline_data when block allocation, buffer lookup, or metadata dirtying fails.
- Inline directory operations (ext4_update_final_de, ext4_try_create_inline_dir, ext4_get_first_inline_block, ext4_try_add_inline_entry across i_block and system.data xattr, duplicate -EEXIST handling, ext4_find_inline_entry, ext4_read_inline_dir with cookie/iversion revalidation, ext4_inlinedir_to_tree, ext4_delete_inline_entry, empty_inline_dir, conversion of full inline directories to extent-mapped directory blocks with rollback on allocation failure, and corrupted dirent detection).
Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_inline_getblk, ext4_da_get_block_prep, and ext4_inode_journal_mode.
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 2 + fs/ext4/ext4_jbd2.c | 3 + fs/ext4/inline-test.c | 1825 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/inline.c | 30 +- fs/ext4/inode.c | 4 + 6 files changed, 1864 insertions(+), 2 deletions(-) create mode 100644 fs/ext4/inline-test.c
fs/ext4/Makefile +1 -1
@@ -17,7 +17,7 @@ ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ - namei-test.o + namei-test.o inline-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +2 -0
@@ -3765,6 +3765,8 @@ extern const struct file_operations ext4_file_operations;extern loff_t ext4_llseek (struct file *file,loff_t offset,int origin);/* inline.c */ +extern struct buffer_head *ext4_inline_getblk (struct super_block *sb, +ext4_fsblk_t block);extern int ext4_get_max_inline_size (struct inode *inode);extern int ext4_find_inline_data_nolock (struct inode *inode);extern int ext4_destroy_inline_data (handle_t *handle,struct inode *inode);
fs/ext4/ext4_jbd2.c +3 -0
@@ -10,6 +10,8 @@int ext4_inode_journal_mode (struct inode *inode) { +KUNIT_STATIC_STUB_REDIRECT (ext4_inode_journal_mode, inode); +if (EXT4_JOURNAL (inode) ==NULL )return EXT4_INODE_WRITEBACK_DATA_MODE ;/* writeback */ /* We do not support data journalling with delayed allocation */
@@ -437,5 +439,6 @@ int __ext4_handle_dirty_metadata(const char *where, unsigned int line, }#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_journal_mode);EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_handle_dirty_metadata);#endif
fs/ext4/inline-test.c new file +1825 -0
1,825 lines not on this page · raw message
fs/ext4/inline.c +29 -1
@@ -9,6 +9,7 @@#include <linux/namei.h> #include <linux/iversion.h> #include <linux/sched/mm.h> +#include <kunit/static_stub.h> #include "ext4_jbd2.h" #include "ext4.h"
@@ -1096,6 +1097,13 @@ static void ext4_restore_inline_data(handle_t *handle, struct inode *inode,ext4_set_inode_state (inode,EXT4_STATE_MAY_INLINE_DATA ); } +struct buffer_head *ext4_inline_getblk (struct super_block *sb, +ext4_fsblk_t block) +{ +KUNIT_STATIC_STUB_REDIRECT (ext4_inline_getblk, sb, block); +return sb_getblk (sb, block); +} +static int ext4_convert_inline_data_nolock (handle_t *handle,struct inode *inode,struct ext4_iloc *iloc)
@@ -1144,7 +1152,7 @@ static int ext4_convert_inline_data_nolock(handle_t *handle, goto out_restore; } - data_bh =sb_getblk (inode->i_sb, map.m_pblk); + data_bh =ext4_inline_getblk (inode->i_sb, map.m_pblk);if (!data_bh) { error = -ENOMEM ; goto out_restore;
@@ -2018,5 +2026,25 @@ int ext4_convert_inline_data(struct inode *inode) }#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inline_getblk); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_max_inline_size);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_find_inline_data_nolock); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_readpage_inline); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_generic_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_try_to_write_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_write_inline_data_end); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_update_final_de); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_try_add_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inlinedir_to_tree); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_read_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_read_inline_link); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_first_inline_block); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_try_create_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_find_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_delete_inline_entry); +EXPORT_SYMBOL_FOR_EXT4_TEST (empty_inline_dir); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_destroy_inline_data); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inline_data_iomap); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inline_data_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_convert_inline_data);#endif
fs/ext4/inode.c +4 -0
@@ -2030,6 +2030,9 @@ int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,sector_t invalid_block = ~((sector_t )0xffff );int ret =0 ; +KUNIT_STATIC_STUB_REDIRECT (ext4_da_get_block_prep, inode, iblock, bh, + create); +BUG_ON (create ==0 );BUG_ON (bh->b_size != inode->i_sb->s_blocksize);
@@ -6999,6 +7002,7 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) }#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_get_block_prep);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_update_reserve_space);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_release_space);EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_mark_inode_dirty);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 07/27] ext4: add KUnit tests for fs/ext4/inline.c
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Low] ext4: unexercised dioread_nolock branch in inline conversion KUnit test - [Low] ext4: unexercised…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Low] ext4: unexercised dioread_nolock branch in inline conversion KUnit test
- [Low] ext4: unexercised iversion revalidation in test_filldir_actor()
- [Low] ext4: inaccurate comment on ext4_inlinedir_to_tree() in inline-test.c
- [Low] ext4: missing i_size_ordered_init() on mock inode in inline_test_init()
It also noticed 2 related pre-existing issues this patch does not introduce:
- [Critical] ext4: TOCTOU race condition in ext4_convert_inline_data_nolock() [1]
- [Critical] ext4: 32-bit i_size truncation in ext4_inline_data_truncate() [2]
--
commit 2474f0318caf555f2d6839372e8f1734082921e5
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/inline.c
This commit adds a KUnit test suite in fs/ext4/inline-test.c to exercise ext4 inline data operations for regular files, symlinks, and directories, along with static stub hooks and symbol exports for the tested functions.
Quoted 5 lines
fs/ext4/inline-test.c new file +0
-0
[ ... ]
Quoted 2 lines
fs/ext4/inline-test.c new file +2
-0+static int inline_test_init (struct kunit *test) +{
[ ... ]
fs/ext4/inline-test.c line 342
Quoted 9 lines
fs/ext4/inline-test.c new file +9
-0+/* Initialize mock ext4_inode_info and embedded vfs_inode */ + inode = &ctx->ei.vfs_inode; + inode->i_sb = &ctx->sb; + inode->i_ino =TEST_INO ; + inode->i_blkbits =TEST_BLOCK_BITS ; +set_nlink (inode,1 ); +atomic_set (&inode->i_count,1 ); +spin_lock_init (&inode->i_lock); +init_rwsem (&inode->i_rwsem);
[Severity: Low]
Does the mock inode initialization in inline_test_init() miss a call to i_size_ordered_init(inode) (or inode_init_once())?
On 32-bit SMP kernels with CONFIG_DEBUG_LOCK_ALLOC enabled, struct inode embeds seqcount_t i_size_seqcount. Because ctx is allocated from the heap via kunit_kzalloc(), calling i_size_write() or i_size_read() in create_inline_file() and the tested inline helpers accesses an uninitialized lockdep_map key on inode->i_size_seqcount, triggering a lockdep warning and disabling lockdep.
[ ... ]
Quoted 2 lines
fs/ext4/inline-test.c new file +2
-0+static void test_write_triggers_inline_to_extent_conversion (struct kunit *test) +{
[ ... ]
Quoted 8 lines
fs/ext4/inline-test.c new file +8
-0+/* +* 2. Conversion with DIOREAD_NOLOCK + DELALLOC enabled and journal_data +* mode (exercises ext4_should_dioread_nolock and ext4_should_journal_data +* branches in ext4_convert_inline_data_to_extent). +*/ +reset_inode_state (ctx,S_IFREG |0644 ); + ret =create_inline_file (inode, buf,sizeof (buf)); +KUNIT_ASSERT_EQ (test, ret,0 );
fs/ext4/inline-test.c line 1243
Quoted 10 lines
fs/ext4/inline-test.c new file +10
-0+ +set_opt (&ctx->sb,DIOREAD_NOLOCK ); +set_opt (&ctx->sb,DELALLOC ); + ctx->journal_mode =EXT4_INODE_JOURNAL_DATA_MODE ; + +inode_lock (inode); + folio =NULL ; + ret =ext4_try_to_write_inline_data (&inode->i_data, inode,0 ,200 , + &folio); +inode_unlock (inode);
[Severity: Low]
Does setting ctx->journal_mode to EXT4_INODE_JOURNAL_DATA_MODE here prevent the ext4_should_dioread_nolock() branch in ext4_convert_inline_data_to_extent() from being exercised?
ext4_should_dioread_nolock() returns 0 wheneverext4_should_journal_data(inode) is true:
fs/ext4/ext4_jbd2.h:ext4_should_dioread_nolock() {
...
if (ext4_should_journal_data(inode))
return 0;
...
}Testing the DIOREAD_NOLOCK + DELALLOC unwritten-extent conversion path requires a separate call with a non-journaled data mode such as EXT4_INODE_WRITEBACK_DATA_MODE.
[ ... ]
Quoted 9 lines
fs/ext4/inline-test.c new file +9
-0+static bool test_filldir_actor (struct dir_context *dctx,const char *name, +int namelen,loff_t offset,u64 ino, +unsigned int d_type) +{ +struct test_dir_ctx *tctx = + container_of(dctx, struct test_dir_ctx, ctx); + +if (tctx->max_emit >0 && tctx->count >= tctx->max_emit) +return false;
[ ... ]
fs/ext4/inline-test.c line 1602
Quoted 9 lines
fs/ext4/inline-test.c new file +9
-0+/* Mutating inode iversion during iteration triggers offset revalidation */ +memset (&env->dctx,0 ,sizeof (env->dctx)); + env->dctx.ctx.actor = test_filldir_actor; + env->dctx.ctx.pos =0 ; + env->dctx.mutate_inode_on_second = dir; + ret =ext4_read_inline_dir (&env->filp, &env->dctx.ctx, + &has_inline_data); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, env->dctx.count,6 );
[Severity: Low]
Does this subtest ever exercise partial iteration or the iversion revalidation loop in ext4_read_inline_dir()?
tctx->max_emit is never set to a non-zero value anywhere in the file, and ext4_read_inline_dir() is only called once starting from ctx.pos = 0. When test_filldir_actor() increments dir's iversion on the second entry, ext4_read_inline_dir() has already passed the !inode_eq_iversion(inode, info->cookie) check at the top of the function and continues emitting all 6 entries in the same call without ever re-entering at a non-zero ctx.pos.
[ ... ]
Quoted 2 lines
fs/ext4/inline-test.c new file +2
-0+static void test_inline_dir_conversion_and_corruptions (struct kunit *test) +{
[ ... ]
Quoted 20 lines
fs/ext4/inline-test.c new file +20
-0+/* +* 4. Corrupted inline directory checks: +* 4a. Parent ino ("..") == 0 -> empty_inline_dir returns false. +* 4b. Zero rec_len dirent -> empty_inline_dir returns false, +* ext4_inlinedir_to_tree returns -EFSCORRUPTED, and +* ext4_convert_inline_data_nolock aborts via ext4_check_all_de. +*/ +reset_inode_state (ctx,S_IFDIR |0755 ); + handle =ext4_journal_start (dir,EXT4_HT_DIR ,1 ); +KUNIT_ASSERT_FALSE (test,IS_ERR (handle)); + ret =ext4_try_create_inline_dir (handle, &env->parent, dir); +ext4_journal_stop (handle); +KUNIT_ASSERT_EQ (test, ret,0 ); + +/* Corrupt parent ino to 0 */ + *(__le32 *)raw_inline_i_block (ctx) =cpu_to_le32 (0 ); +KUNIT_EXPECT_FALSE (test,empty_inline_dir (dir, &has_inline_data)); + *(__le32 *)raw_inline_i_block (ctx) =cpu_to_le32 (TEST_PARENT_INO ); + +/* Corrupt first dirent rec_len to 0 */
fs/ext4/inline-test.c line 1799
Quoted 10 lines
fs/ext4/inline-test.c new file +10
-0+ de = (struct ext4_dir_entry_2 *)((char *)raw_inline_i_block (ctx) + +EXT4_INLINE_DOTDOT_SIZE ); + de->rec_len =cpu_to_le16 (0 ); +KUNIT_EXPECT_FALSE (test,empty_inline_dir (dir, &has_inline_data)); + +/* ext4_convert_inline_data on corrupted inline dir fails in ext4_check_all_de */ + ret =ext4_convert_inline_data (dir); +KUNIT_EXPECT_EQ (test, ret, -EFSCORRUPTED ); +KUNIT_EXPECT_TRUE (test,ext4_has_inline_data (dir)); +}
[Severity: Low]
This isn't a bug, but comment 4b states that a zero rec_len dirent causes ext4_inlinedir_to_tree() to return -EFSCORRUPTED, whereas the test does not call ext4_inlinedir_to_tree() here and ext4_inlinedir_to_tree() breaks out of its loop and returns the count of already-processed entries (2 for "." and "..") when ext4_check_dir_entry() fails.
Quoted 4 lines
fs/ext4/inline.c +0
-0
[ ... ]
fs/ext4/inline.c static int ext4_convert_inline_data_nolock(handle_t *handle, · line 1158
Quoted 9 lines
fs/ext4/inline.c +1
-1@@ -1144,7 +1152,7 @@ static int ext4_convert_inline_data_nolock(handle_t *handle, goto out_restore; } - data_bh =sb_getblk (inode->i_sb, map.m_pblk); + data_bh =ext4_inline_getblk (inode->i_sb, map.m_pblk);if (!data_bh) { error = -ENOMEM ; goto out_restore;
[Severity: Critical]
This problem wasn't introduced by this patch, but can unlocking data_bh before ext4_init_dirblock() in ext4_convert_inline_data_nolock() expose an uninitialized directory block to concurrent readers [1]?
CPU0 CPU1ext4_convert_inline_data_nolock()
ext4_destroy_inline_data_nolock()
ext4_map_blocks()
data_bh = ext4_inline_getblk()
lock_buffer(data_bh)
memset(data_bh->b_data, 0, ...)
unlock_buffer(data_bh)
i_size_write(inode, s_blocksize)
ext4_get_parent()
ext4_find_entry()
...
ext4_dirblock_csum_verify()
<-- fails on zeroed block ext4_init_dirblock(data_bh)
set_buffer_uptodate(data_bh)
set_buffer_verified(data_bh)
ext4_handle_dirty_dirblock()
In the S_ISDIR branch of ext4_convert_inline_data_nolock(), data_bh is zeroed, unlocked, and published via i_size_write() before ext4_init_dirblock() populates the directory entries and computes the block checksum:
fs/ext4/inline.c:ext4_convert_inline_data_nolock() {
...
} else {
unlock_buffer(data_bh);
inode->i_size = inode->i_sb->s_blocksize;
i_size_write(inode, inode->i_sb->s_blocksize);
EXT4_I(inode)->i_disksize = inode->i_sb->s_blocksize;
error = ext4_init_dirblock(handle, inode, data_bh,
le32_to_cpu(((struct ext4_dir_entry_2 *)buf)->inode),
buf + EXT4_INLINE_DOTDOT_SIZE,
inline_size - EXT4_INLINE_DOTDOT_SIZE);
...
}In addition, ext4_init_dirblock() sets buffer_uptodate and buffer_verified before ext4_handle_dirty_dirblock() calculates the checksum. A concurrent reader (such as NFS export lookup via ext4_get_parent()) can read the partially initialized or unchecksummed block and fail ext4_dirblock_csum_verify(), triggering an ext4 filesystem error (and a read-only remount or panic).
Quoted 4 lines
fs/ext4/inline.c +0
-0@@ -2018,5 +2026,25 @@ int ext4_convert_inline_data(struct inode *inode) }#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )
[ ... ]
fs/ext4/inline.c int ext4_convert_inline_data(struct inode *inode) · line 2050
Quoted 3 lines
fs/ext4/inline.c +2
-0+EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inline_data_truncate); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_convert_inline_data);#endif
[Severity: Critical]
This problem wasn't introduced by this patch, but can ext4_inline_data_truncate() truncate the 64-bit inode->i_size into a 32-bit size_t on 32-bit architectures [2]?
fs/ext4/inline.c:ext4_inline_data_truncate() {
...
size_t i_size;
...
down_write(&EXT4_I(inode)->i_data_sem);
i_size = inode->i_size;
inline_size = ext4_get_inline_size(inode);
EXT4_I(inode)->i_disksize = i_size;
if (i_size < inline_size) {
if (!ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, i_size);
ext4_es_remove_extent(inode, lblk,
EXT_MAX_BLOCKS - lblk);
}
...
}When an inline file is converted to delayed-allocation extents via a buffered write at an offset of 4 GiB or greater, EXT4_STATE_MAY_INLINE_DATA is cleared while EXT4_INODE_INLINE_DATA remains set until writeback. If a subsequent truncate or ext4_truncate_failed_write() calls ext4_inline_data_truncate() before writeback on a 32-bit system, assigning inode->i_size to the 32-bit i_size local variable discards the upper 32 bits, corrupting EXT4_I(inode)->i_disksize. When the lower 32 bits are smaller than inline_size, it also enters the i_size < inline_size branch, removing live delayed extents from the extent status tree and zeroing the inline data buffer.
[1] https://sashiko.dev/#/bug/linux-48900fa2-4764-4787-990d-c127e7cf2417
[2] https://sashiko.dev/#/bug/linux-d1c56a9e-62e9-4eeb-addd-143c371dbdca
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Theodore Ts'o
maintainerPATCH 8/27 ext4: zero s_fc_replay_state in ext4_fc_replay_cleanup()
In reply to Theodore Ts'oext4_fc_replay_cleanup() frees sbi->s_fc_replay_state.fc_regions and sbi->s_fc_replay_state.fc_modified_inodes, but leaves the dangling pointers and non-zero size/usage counters in sbi->s_fc_replay_state.
This makes ext4_fc_replay_cleanup() non-idempotent: calling it more than once triggers a slab double-free of fc_regions and fc_modified_inodes. In particular, the ext4_fast_commit_test KUnit suite calls ext4_fc_replay_cleanup() explicitly at the end of replay test cases and again from its fc_cleanup_all() teardown action, causing SLUB double-free errors in test_fc_replay_inode_and_dentries() and test_fc_replay_ranges_and_end_to_end(). Leaving stale pointers and a non-zero fc_regions_valid count in s_fc_replay_state after replay completes also risks a use-after-free if ext4_fc_replay_check_excluded() is ever invoked after cleanup, or a double-free if mount error paths are updated to call ext4_fc_replay_cleanup().
Zero sbi->s_fc_replay_state in ext4_fc_replay_cleanup() after freeing both buffers so the replay state is fully reset and repeated calls are safe no-ops.
--- fs/ext4/fast_commit.c | 1 + 1 file changed, 1 insertion(+)
fs/ext4/fast_commit.c +1 -0
@@ -2398,6 +2398,7 @@ void ext4_fc_replay_cleanup(struct super_block *sb) sbi->s_mount_state &= ~EXT4_FC_REPLAY ;kfree (sbi->s_fc_replay_state.fc_regions);kfree (sbi->s_fc_replay_state.fc_modified_inodes); +memset (&sbi->s_fc_replay_state,0 ,sizeof (sbi->s_fc_replay_state)); } static bool ext4_fc_value_len_isvalid(struct ext4_sb_info *sbi,
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 08/27] ext4: zero s_fc_replay_state in ext4_fc_replay_cleanup()
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] ext4: missing s_ea_inode_work flush…
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] ext4: missing s_ea_inode_work flush before ext4_fc_replay_cleanup() [1]
--
commit a4ccfbc7c2db4e8403230f07464457a51d148eaa
Author: Theodore Ts'o <[email protected]>
ext4: zero s_fc_replay_state in ext4_fc_replay_cleanup()
This commit zeroes sbi->s_fc_replay_state in ext4_fc_replay_cleanup() after freeing fc_regions and fc_modified_inodes so that repeated calls to ext4_fc_replay_cleanup() are idempotent.
fs/ext4/fast_commit.c void ext4_fc_replay_cleanup(struct super_block *sb) · line 2402
Quoted 10 lines
fs/ext4/fast_commit.c +1
-0@@ -2398,6 +2398,7 @@ void ext4_fc_replay_cleanup(struct super_block *sb) sbi->s_mount_state &= ~EXT4_FC_REPLAY ;kfree (sbi->s_fc_replay_state.fc_regions);kfree (sbi->s_fc_replay_state.fc_modified_inodes); +memset (&sbi->s_fc_replay_state,0 ,sizeof (sbi->s_fc_replay_state)); }
[Severity: High]
This problem wasn't introduced by this patch, but can ext4_fc_replay_cleanup() clear EXT4_FC_REPLAY before sbi->s_ea_inode_work is flushed [1]?
When fast-commit replay unlinks an inode that owns an extended attribute inode, ext4_xattr_inode_dec_ref_all() -> ext4_put_ea_inode() queues the EA inode onto sbi->s_ea_inode_to_free and schedules sbi->s_ea_inode_work. Unlike the failed_mount3a error path, the normal mount path in __ext4_fill_super() calls ext4_fc_replay_cleanup() without flushing sbi->s_ea_inode_work first, clearing EXT4_FC_REPLAY before ext4_mb_init() initializes sbi->s_group_info:
fs/ext4/super.c:__ext4_fill_super() {
...
ext4_fc_replay_cleanup(sb);
ext4_ext_init(sb);
/* Register extent status tree shrinker */
err = ext4_es_register_shrinker(sbi);
if (err)
goto failed_mount3;
err = ext4_Inode_table_init(sb);
...
err = ext4_mb_init(sb);
...
failed_mount3a:
/* Drain deferred EA inode iputs from journal replay */
flush_delayed_work(&sbi->s_ea_inode_work);
ext4_fc_replay_cleanup(sb);
...
}If ext4_ea_inode_work() runs before ext4_mb_init() populates sbi->s_group_info (or when mount failure jumps to failed_mount_wq after ext4_mb_release()), ext4_evict_inode() -> ext4_free_inode() runs with EXT4_FC_REPLAY cleared and ext4_get_group_info() returning NULL, which triggers ext4_std_error(sb, -EFSCORRUPTED).
Should ext4_fc_replay_cleanup() (or __ext4_fill_super() right before it) call flush_delayed_work(&sbi->s_ea_inode_work) before clearing EXT4_FC_REPLAY?
[1] https://sashiko.dev/#/bug/linux-f893d2ed-6353-413a-8dd1-c6bc439b880a
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Theodore Ts'o
maintainerPATCH 9/27 ext4: add KUnit tests for fs/ext4/fast_commit.c
In reply to Theodore Ts'oAdd the ext4_fast_commit_test KUnit test suite in fs/ext4/fast_commit-test.c to comprehensively exercise fast commit tracking, snapshotting, TLV serialization, commit execution, and journal replay in fs/ext4/fast_commit.c without requiring a mounted block device:
- Fast commit initialization and eligibility helpers (ext4_fc_init, ext4_fc_init_inode, ext4_fc_disabled, ext4_fc_eligible, ext4_fc_set_snap_err, and ext4_fc_snap_stats_update_max).
- Ineligibility tracking (ext4_fc_mark_ineligible) with active handles, NULL handles with or without a running transaction, monotonic s_fc_ineligible_tid updates, and per-reason statistics counters.
- Inode and logical range tracking (ext4_fc_track_inode and ext4_fc_track_range), covering directory skips, data-journalling and inline-data ineligibility, special inodes (< EXT4_FIRST_INO), same-TID bounding-interval range merging, cross-TID resets, EXT4_STATE_FC_COMMITTING to EXT4_STATE_FC_REQUEUE transitions, and FC_Q_MAIN vs. FC_Q_STAGING queue routing.
- Dentry update tracking (ext4_fc_track_create, ext4_fc_track_link, and ext4_fc_track_unlink) and inode deletion cleanup (ext4_fc_del), including root dentry parent handling, EXT4_FC_TAG_CREAT removal, and concurrent wait-bit wakeups across EXT4_STATE_FC_FLUSHING_DATA and EXT4_STATE_FC_COMMITTING.
- Fast commit buffer space reservation and TLV serialization (ext4_fc_reserve_space, ext4_fc_add_tlv, and ext4_fc_write_tail), including oversize rejection, block boundary EXT4_FC_TAG_PAD insertion and buffer submission, and EXT4_FC_TAG_TAIL padding and CRC32C calculation.
- Inode and extent-status range snapshotting (ext4_fc_snapshot_inode, ext4_fc_count_snapshot_inodes, ext4_fc_alloc_snapshot_inodes, ext4_fc_snapshot_inodes, ext4_fc_write_inode, and ext4_fc_write_inode_data), including ext4_get_inode_loc_noio fallback, ES miss/delayed/unsupported status errors, inode and range capacity caps (-E2BIG), extent splitting past EXT_INIT_MAX_LEN (32768), and create-only dentry inode snapshotting.
- Fast and full commit cleanup (ext4_fc_cleanup), EWMA commit time stats (ext4_fc_update_stats), and procfs stats output (ext4_fc_info_show).
- Top-level commit execution and fallbacks (ext4_fc_commit) across already-committed TIDs, disabled fast commits, jbd2_fc_begin_commit failures, ineligible filesystems, data flush -EIO errors, snapshot -EAGAIN fallbacks, jbd2_fc_wait_bufs -EIO errors, and consecutive fast commits with external journal device cache flushes.
- Recovery region exclusion and scan validation (ext4_fc_record_regions, ext4_fc_replay_check_excluded, ext4_fc_record_modified_inode, ext4_fc_value_len_isvalid, tag2str, and PASS_SCAN validation of missing HEAD, unexpected offset, unsupported features, wrong TID, bad tail CRC, and partial multi-commit logs).
- Recovery replay of EXT4_FC_TAG_INODE (extent and inline-data inodes), EXT4_FC_TAG_CREAT (regular files and subdirectories), EXT4_FC_TAG_LINK (-EEXIST idempotency), and EXT4_FC_TAG_UNLINK (missing entries and rename-overwrite inode mismatches).
- Recovery replay of EXT4_FC_TAG_ADD_RANGE and EXT4_FC_TAG_DEL_RANGE, error handling, and an end-to-end ext4_fc_commit() -> PASS_SCAN -> PASS_REPLAY round-trip.
Export the tested fast commit entry points with EXPORT_SYMBOL_FOR_EXT4_TEST and add KUNIT_STATIC_STUB_REDIRECT hooks for ext4_fc_get_buf, ext4_fc_submit_bh, ext4_fc_issue_flush, ext4_get_inode_loc_noio, ext4_get_fc_inode_loc, ext4_mark_inode_used, ext4_mb_mark_bb, and ext4_es_lookup_extent.
--- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 35 + fs/ext4/extents_status.c | 3 + fs/ext4/fast_commit-test.c | 2656 ++++++++++++++++++++++++++++++++++++ fs/ext4/fast_commit.c | 180 ++- fs/ext4/ialloc.c | 3 + fs/ext4/inode.c | 6 + fs/ext4/mballoc.c | 3 +- 8 files changed, 2882 insertions(+), 7 deletions(-) create mode 100644 fs/ext4/fast_commit-test.c
fs/ext4/Makefile +2 -1
@@ -17,7 +17,8 @@ ext4-$(CONFIG_EXT4_FS_SECURITY) += xattr_security.o ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ - namei-test.o inline-test.o + namei-test.o inline-test.o \ + fast_commit-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +35 -0
@@ -3070,6 +3070,9 @@ extern int ext4_init_inode_table(struct super_block *sb,void ext4_end_bitmap_read (struct bio *bio);/* fast_commit.c */ +int ext4_fc_get_buf (journal_t *journal,struct buffer_head **bh); +void ext4_fc_submit_bh (struct super_block *sb,bool is_tail); +void ext4_fc_issue_flush (struct block_device *bdev);int ext4_fc_info_show (struct seq_file *seq,void *v);void ext4_fc_init (struct super_block *sb,journal_t *journal);void ext4_fc_init_inode (struct inode *inode);
@@ -3096,6 +3099,38 @@ void ext4_fc_destroy_dentry_cache(void);int ext4_fc_record_regions (struct super_block *sb,int ino,ext4_lblk_t lblk,ext4_fsblk_t pblk,int len,int replay); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +void ext4_fc_set_snap_err_test (int *snap_err,int err); +bool ext4_fc_disabled_test (struct super_block *sb); +bool ext4_fc_eligible_test (struct super_block *sb); +void ext4_fc_snap_stats_update_max_test (atomic64_t *stat,u64 value); +void ext4_fc_wake_inode_state_test (struct inode *inode,int bit); +u8 *ext4_fc_reserve_space_test (struct super_block *sb,int len,u32 *crc); +int ext4_fc_write_tail_test (struct super_block *sb,u32 crc); +bool ext4_fc_add_tlv_test (struct super_block *sb,u16 tag,u16 len,u8 *val, +u32 *crc); +int ext4_fc_write_inode_test (struct inode *inode,u32 *crc); +int ext4_fc_write_inode_data_test (struct inode *inode,u32 *crc); +void ext4_fc_free_inode_snap_test (struct inode *inode); +int ext4_fc_snapshot_inode_test (struct inode *inode, +unsigned int nr_ranges_total, +unsigned int *nr_rangesp,int *snap_err); +unsigned int ext4_fc_count_snapshot_inodes_test (struct super_block *sb); +int ext4_fc_alloc_snapshot_inodes_test (struct super_block *sb, +struct inode ***inodesp, +unsigned int *nr_inodesp); +int ext4_fc_snapshot_inodes_test (journal_t *journal,struct inode **inodes, +unsigned int inodes_size, +unsigned int *nr_inodesp, +unsigned int *nr_rangesp,int *snap_err); +void ext4_fc_update_stats_test (struct super_block *sb,int status, +u64 commit_time,int nblks,tid_t commit_tid); +void ext4_fc_cleanup_test (journal_t *journal,int full,tid_t tid); +int ext4_fc_record_modified_inode_test (struct super_block *sb,int ino); +bool ext4_fc_value_len_isvalid_test (struct ext4_sb_info *sbi,int tag,int len); +int ext4_fc_replay_test (journal_t *journal,struct buffer_head *bh, +enum passtype pass,int off,tid_t expected_tid); +#endif /* mballoc.c */ extern const struct seq_operations ext4_mb_seq_groups_ops;
fs/ext4/extents_status.c +3 -0
@@ -1099,6 +1099,9 @@ int ext4_es_lookup_extent(struct inode *inode, ext4_lblk_t lblk,struct rb_node *node;int found =0 ; +KUNIT_STATIC_STUB_REDIRECT (ext4_es_lookup_extent, inode, lblk, + next_lblk, es, pseq); +if (EXT4_SB (inode->i_sb)->s_mount_state &EXT4_FC_REPLAY )return 0 ;
fs/ext4/fast_commit-test.c new file +2656 -0
2,656 lines not on this page · raw message
fs/ext4/fast_commit.c +175 -5
223 lines not on this page · raw message
fs/ext4/ialloc.c +3 -0
@@ -768,6 +768,8 @@ int ext4_mark_inode_used(struct super_block *sb, int ino)int bit;int err; +KUNIT_STATIC_STUB_REDIRECT (ext4_mark_inode_used, sb, ino); +if (ino <EXT4_FIRST_INO (sb) || ino > max_ino)return -EFSCORRUPTED ;
@@ -1638,4 +1640,5 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS )EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_new_inode); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mark_inode_used);#endif
fs/ext4/inode.c +6 -0
@@ -5088,6 +5088,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc)int inodes_per_block, inode_offset;unsigned long ino = inode->i_ino; +KUNIT_STATIC_STUB_REDIRECT (ext4_get_inode_loc_noio, inode, iloc); + iloc->bh =NULL ;if (ino <EXT4_ROOT_INO || ino >le32_to_cpu (EXT4_SB (sb)->s_es->s_inodes_count))
@@ -5129,6 +5131,8 @@ int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc)int ext4_get_fc_inode_loc (struct super_block *sb,unsigned long ino,struct ext4_iloc *iloc) { +KUNIT_STATIC_STUB_REDIRECT (ext4_get_fc_inode_loc, sb, ino, iloc); +return __ext4_get_inode_loc (sb, ino,NULL , iloc,NULL ); }
@@ -7002,6 +7006,8 @@ vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) }#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_inode_loc_noio); +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_fc_inode_loc);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_get_block_prep);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_update_reserve_space);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_da_release_space);
fs/ext4/mballoc.c +2 -1
@@ -4269,6 +4269,8 @@ void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,int err =0 ;unsigned int clen, thisgrp_len; +KUNIT_STATIC_STUB_REDIRECT (ext4_mb_mark_bb, sb, block, len, state); +while (len >0 ) {ext4_get_group_no_and_offset (sb, block, &group, &blkoff);
@@ -7474,7 +7476,6 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_group_number);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_release);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_read_block_bitmap_nowait);EXPORT_SYMBOL_FOR_EXT4_TEST (mb_set_bits); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fc_init_inode);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_mark_context);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mb_new_blocks);EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_blocks);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 09/27] ext4: add KUnit tests for fs/ext4/fast_commit.c
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] ext4: uninitialized j_trans_commit_map in fast_commit_test_init() - [Medium] ext4: excessive stack…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] ext4: uninitialized j_trans_commit_map in fast_commit_test_init()
- [Medium] ext4: excessive stack frame size in fast_commit-test.c test cases
- [Low] ext4: resource leak and UAF on abort in fast_commit_test_init() and cleanup
--
commit 0a44fff123afc676ec0d455ddc174806f24be58f
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/fast_commit.c
This commit adds the ext4_fast_commit_test KUnit test suite in fs/ext4/fast_commit-test.c and exports fast commit helpers and static stub hooks in fs/ext4/fast_commit.c and related files.
Quoted 5 lines
fs/ext4/fast_commit-test.c new file +0
-0
[ ... ]
Quoted 44 lines
fs/ext4/fast_commit-test.c new file +44
-0+/* --- Suite Setup & Teardown --- */ + +static void fc_cleanup_all (void *priv) +{ +struct fc_test_ctx *ctx = priv; +int i; + + ctx->sbi->s_mount_state &= ~EXT4_FC_REPLAY ; +ext4_fc_cleanup_test (&ctx->journal,1 ,999999 ); +ext4_fc_replay_cleanup (ctx->sb); + +for (i =0 ; i <TEST_MAX_INODES ; i++) { +if (!ctx->inodes[i].allocated) +continue ; +down_write (&ctx->inodes[i].ei.i_data_sem); +ext4_es_remove_extent (&ctx->inodes[i].ei.vfs_inode,0 , +EXT_MAX_BLOCKS ); +up_write (&ctx->inodes[i].ei.i_data_sem); +ext4_fc_free_inode_snap_test (&ctx->inodes[i].ei.vfs_inode); + } + +ext4_es_unregister_shrinker (ctx->sbi); +deactivate_super (ctx->sb); +} + +static int fast_commit_test_init (struct kunit *test) +{ +struct fc_test_ctx *ctx; +struct ext4_sb_info *sbi; +struct super_block *sb; +struct fs_context *fc; +int i, err; + + ctx =kunit_kzalloc (test,sizeof (*ctx),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx); + + sbi =kunit_kzalloc (test,sizeof (*sbi),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, sbi); + + fc =fs_context_for_mount (&fc_fs_type,0 ); +KUNIT_ASSERT_FALSE (test,IS_ERR (fc)); + sb =sget_fc (fc,NULL , fc_set_anon); +put_fs_context (fc); +KUNIT_ASSERT_FALSE (test,IS_ERR (sb));
[ ... ]
fs/ext4/fast_commit-test.c line 943
Quoted 13 lines
fs/ext4/fast_commit-test.c new file +13
-0+up_write (&sb->s_umount); + + err =ext4_es_register_shrinker (sbi); +KUNIT_ASSERT_EQ (test, err,0 ); + ctx->shrinker_count = sbi->s_es_shrinker->count_objects; + ctx->shrinker_scan = sbi->s_es_shrinker->scan_objects; +WRITE_ONCE (sbi->s_es_shrinker->count_objects, fc_dummy_shrinker_count); +WRITE_ONCE (sbi->s_es_shrinker->scan_objects, fc_dummy_shrinker_scan); + +/* Mock journal, running transaction, and handle setup */ +rwlock_init (&ctx->journal.j_state_lock); +spin_lock_init (&ctx->journal.j_list_lock); +mutex_init (&ctx->journal.j_barrier);
[Severity: Medium]
Does fast_commit_test_init() leave ctx->journal.j_trans_commit_map uninitialized?
ctx is heap-allocated with kunit_kzalloc(). When test_fc_commit_paths() calls ext4_fc_commit() -> ext4_fc_perform_commit() -> jbd2_journal_lock_updates(), jbd2_might_wait_for_commit() passes &ctx->journal.j_trans_commit_map to rwsem_acquire() and rwsem_release(). With CONFIG_LOCKDEP enabled, its NULL key in non-static memory triggers "INFO: trying to register non-static key" and turns off lockdep via debug_locks_off().
[ ... ]
Quoted 11 lines
fs/ext4/fast_commit-test.c new file +11
-0+kunit_activate_static_stub (test, ext4_fc_submit_bh, + stub_fc_submit_bh); +kunit_activate_static_stub (test, ext4_fc_issue_flush, + stub_fc_issue_flush); + +init_mock_inode_slot (ctx, &ctx->inodes[0 ],TEST_ROOT_INO , +S_IFDIR |0755 ); +init_mock_inode_slot (ctx, &ctx->inodes[1 ],TEST_DIR_INO , +S_IFDIR |0755 ); +init_mock_inode_slot (ctx, &ctx->inodes[2 ],TEST_FILE1_INO , +S_IFREG |0644 );
fs/ext4/fast_commit-test.c line 1066
Quoted 10 lines
fs/ext4/fast_commit-test.c new file +10
-0+init_mock_inode_slot (ctx, &ctx->inodes[3 ],TEST_FILE2_INO , +S_IFREG |0644 ); +init_mock_inode_slot (ctx, &ctx->inodes[4 ],TEST_SUBDIR_INO , +S_IFDIR |0755 ); + + err =kunit_add_action_or_reset (test, fc_cleanup_all, ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + +return 0 ; +}
[Severity: Low]
Can an assertion failure in fast_commit_test_init() leak sb and leave sbi->s_es_shrinker and sbi->s_es_stats percpu_counters registered after KUnit frees sbi?
fc_cleanup_all() is only registered after ext4_es_register_shrinker() and all the kunit_activate_static_stub() calls, which themselves assert on allocation failure. Aborting in that window skips deactivate_super(sb) and ext4_es_unregister_shrinker(sbi), causing a use-after-free once the kunit_kzalloc()-allocated sbi is freed.
Also, in fc_cleanup_all(), calling ext4_fc_cleanup_test() only once drains FC_Q_MAIN before splicing FC_Q_STAGING into FC_Q_MAIN, so any ext4_fc_dentry_update entries on s_fc_dentry_q[FC_Q_STAGING] when a test aborts are leaked.
fs/ext4/fast_commit-test.c line 1079
Quoted 13 lines
fs/ext4/fast_commit-test.c new file +13
-0+ +/* ========================================================================= +* 1. Initialization, Eligibility, and Snapshot Stat Helpers +* ========================================================================= +*/ + +static void test_fc_init_and_eligibility (struct kunit *test) +{ +struct fc_test_ctx *ctx = test->priv; +struct super_block *sb = ctx->sb; +struct inode *inode =get_mock_inode (ctx,TEST_FILE1_INO ); +struct ext4_inode_info *ei =EXT4_I (inode); +journal_t tmp_journal = {};
[Severity: Medium]
Does allocating tmp_journal on the stack here (and five struct dentry objects on the stack in test_fc_replay_inode_and_dentries()) exceed CONFIG_FRAME_WARN?
journal_t is over 1.3 KB (and over 2.2 KB with CONFIG_LOCKDEP enabled), and the five dentries in test_fc_replay_inode_and_dentries() take ~1.6 KB with CONFIG_LOCKDEP, triggering -Wframe-larger-than warnings or build failures under CONFIG_WERROR. Could tmp_journal and the mock dentries be allocated with kunit_kzalloc() or moved into struct fc_test_ctx?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Theodore Ts'o
maintainerPATCH 10/27 ext4: expand KUnit tests for fs/ext4/inode.c
In reply to Theodore Ts'oExpand the ext4_inode_test KUnit test suite in fs/ext4/inode-test.c from 1 parameterized test (16 timestamp decoding subtests) to 26 test cases (41 subtests total) to comprehensively exercise fs/ext4/inode.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device:
- Extra timestamp encoding and 64-bit round-trips across all 16 boundary vectors, 256-byte inodes with 34-bit seconds + nanoseconds, and 128-byte old inodes storing signed 32-bit seconds with zeroed nanoseconds.
- Raw inode CRC32C checksum computation and verification (ext4_inode_csum_set and ext4_inode_csum_verify) across legacy non-csum filesystems, 128-byte inodes (16-bit lo CRC), 256-byte inodes with i_extra_isize = 0 vs >= 4 (32-bit CRC), and bit-flip corruptions.
- Inode block count encoding and decoding (ext4_inode_blocks_set and ext4_inode_blocks) across 32-bit 512B sectors, 48-bit huge_file sectors, and EXT4_HUGE_FILE_FL filesystem block units.
- VFS-to-raw inode serialization and writeback paths (ext4_fill_raw_inode, ext4_reserve_inode_write, ext4_mark_iloc_dirty, __ext4_mark_inode_dirty, ext4_dirty_inode, ext4_inode_attach_jinode, ext4_write_inode, and ext4_sync_inode_metadata), including inline data preservation, project IDs, lazytime neighbor timestamp flushes, emergency read-only -EROFS handling, and buffer I/O error propagation.
- Dynamic extra-isize expansion (__ext4_expand_extra_isize, ext4_try_to_expand_extra_isize, and ext4_expand_extra_isize), including corrupted/invalid size guards, EXT4_STATE_NO_EXPAND, xattr_sem contention, and shifting in-body extended attributes forward.
- On-disk inode location lookup (__ext4_get_inode_loc, ext4_get_inode_loc, ext4_get_inode_loc_noio, and ext4_get_fc_inode_loc), including zero-I/O uninitialized/unused inode table optimization, neighbor bitmap occupancy checks, readahead window calculation, and read -EIO handling.
- Inode loading and validation (__ext4_iget) across EXT4_IGET_NORMAL, EXT4_IGET_SPECIAL, EXT4_IGET_HANDLE, EXT4_IGET_EA_INODE, EXT4_IGET_NOWAIT, and EXT4_IGET_BAD, special device rdev encodings, fast symlinks, and corruption rejections (bad CRC, unlinked ino, bad mode, reserved ino < first_ino, bad extra_isize, conflicting flags, oversize indirect i_size, bad i_file_acl, and bad extent header).
- Inode eviction (ext4_evict_inode) across live inodes, unlinked regular files (truncating data extents, setting i_dtime, and freeing the inode), and unlinked fast symlinks.
- Fast symlink classification, ext4_can_truncate, inode flag propagation (ext4_set_inode_flags), address_space_operations selection (ext4_set_aops), folio order caps (ext4_set_inode_mapping_order), project ID lookup (ext4_get_projid), DIO alignment checks (ext4_dio_alignment), and STATX_BTIME / STATX_DIOALIGN / STATX_WRITE_ATOMIC / STATX_ATTR_* reporting in ext4_getattr and ext4_file_getattr.
- Delayed allocation space accounting (ext4_da_reserve_space, ext4_da_update_reserve_space, ext4_da_release_space, and ext4_nonda_switch) and bigalloc shared-cluster pending reservations (ext4_clu_alloc_state, ext4_insert_delayed_blocks, and ext4_da_map_blocks).
- Logical-to-physical block mapping (ext4_map_blocks, ext4_get_block, ext4_get_block_unwritten, ext4_da_get_block_prep, ext4_getblk, ext4_bread, ext4_bread_batch, and ext4_walk_page_buffers) across ES hits, extent allocation, unwritten extents, zeroout, and batch reads.
- iomap mapping callbacks (ext4_iomap_begin, ext4_iomap_ops, and ext4_iomap_report_ops, including bigalloc multi-block IOMAP_ATOMIC writes), buffered write_begin/write_end (ext4_da_aops and ext4_aops), bmap, invalidate_folio, release_folio, and ext4_page_mkwrite.
- Transaction credit helpers (ext4_meta_trans_blocks, ext4_chunk_trans_extent, and ext4_chunk_trans_blocks), ext4_break_layouts, ext4_update_disksize_before_punch, partial-block and EOF zeroing (ext4_zero_partial_blocks, ext4_block_zero_eof, and ext4_truncate_page_cache_block_range), ext4_punch_hole, ext4_truncate, and ext4_setattr.
Add thin KUNIT_STATIC_STUB_REDIRECT wrappers for buffer-cache lookup and inode freeing (ext4_sb_getblk, ext4_sb_find_get_block, ext4_sb_getblk_unmovable, ext4_read_bh_nowait, ext4_read_bh_lock, ext4_sb_breadahead_unmovable, and ext4_free_inode) and export the tested entry points and static-helper wrappers with EXPORT_SYMBOL_FOR_EXT4_TEST.
--- fs/ext4/ext4.h | 29 + fs/ext4/ext4_jbd2.c | 2 + fs/ext4/ialloc.c | 3 + fs/ext4/inode-test.c | 3449 +++++++++++++++++++++++++++++++++++++++++- fs/ext4/inode.c | 149 +- fs/ext4/page-io.c | 1 + fs/ext4/super.c | 19 +- 7 files changed, 3640 insertions(+), 12 deletions(-)
fs/ext4/ext4.h +29 -0
@@ -3258,6 +3258,35 @@ extern void ext4_da_update_reserve_space(struct inode *inode, int used, int quota_claim);extern int ext4_issue_zeroout (struct inode *inode,ext4_lblk_t lblk,ext4_fsblk_t pblk,ext4_lblk_t len); +struct buffer_head *ext4_sb_getblk (struct super_block *sb,ext4_fsblk_t block); +struct buffer_head *ext4_sb_find_get_block (struct super_block *sb, +ext4_fsblk_t block); +struct buffer_head *ext4_sb_getblk_unmovable (struct super_block *sb, +ext4_fsblk_t block); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +int ext4_inode_csum_verify_test (struct inode *inode,struct ext4_inode *raw, +struct ext4_inode_info *ei); +int ext4_inode_blocks_set_test (struct ext4_inode *raw_inode, +struct ext4_inode_info *ei); +blkcnt_t ext4_inode_blocks_test (struct ext4_inode *raw_inode, +struct ext4_inode_info *ei); +int ext4_fill_raw_inode_test (struct inode *inode, +struct ext4_inode *raw_inode); +int ext4_expand_extra_isize_test (struct inode *inode, +unsigned int new_extra_isize, +struct ext4_iloc *iloc, +handle_t *handle,int *no_expand); +int ext4_try_to_expand_extra_isize_test (struct inode *inode, +unsigned int new_extra_isize, +struct ext4_iloc *iloc, +handle_t *handle); +int ext4_da_reserve_space_test (struct inode *inode,int nr_resv); +int ext4_clu_alloc_state_test (struct inode *inode,ext4_lblk_t lblk); +int ext4_insert_delayed_blocks_test (struct inode *inode,ext4_lblk_t lblk, +ext4_lblk_t len); +int ext4_da_map_blocks_test (struct inode *inode,struct ext4_map_blocks *map); +int ext4_nonda_switch_test (struct super_block *sb); +#endif static inline bool is_special_ino (struct super_block *sb,unsigned long ino) {
fs/ext4/ext4_jbd2.c +2 -0
@@ -125,6 +125,7 @@ handle_t *__ext4_journal_start_sb(struct inode *inode,return jbd2__journal_start (journal, blocks, rsv_blocks, revoke_creds,GFP_NOFS , type, line); } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_journal_start_sb);int __ext4_journal_stop (const char *where,unsigned int line,handle_t *handle) {
@@ -152,6 +153,7 @@ int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)__ext4_std_error (sb, where, line, err);return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_journal_stop);handle_t *__ext4_journal_start_reserved (handle_t *handle,unsigned int line,int type)
fs/ext4/ialloc.c +3 -0
@@ -250,6 +250,8 @@ void ext4_free_inode(handle_t *handle, struct inode *inode)int fatal =0 , err, count, cleared;struct ext4_group_info *grp; +KUNIT_STATIC_STUB_REDIRECT (ext4_free_inode, handle, inode); +if (!sb) {printk (KERN_ERR "EXT4-fs: %s:%d: inode on " "nonexistent device\n" , __func__, __LINE__);
@@ -363,6 +365,7 @@ void ext4_free_inode(handle_t *handle, struct inode *inode)brelse (bitmap_bh);ext4_std_error (sb, fatal); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_inode);struct orlov_stats {__u64 free_clusters;
fs/ext4/inode-test.c +3445 -4
2,936 lines not on this page · raw message
fs/ext4/inode.c +143 -6
149 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Part of the diff is not shown here. View the raw message.
[email protected]
AI reviewRe: [PATCH 10/27] ext4: expand KUnit tests for fs/ext4/inode.c
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] ext4: use-after-free of mock superblock and inodes in inode_test_cleanup() - [Medium] ext4…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] ext4: use-after-free of mock superblock and inodes in inode_test_cleanup()
- [Medium] ext4: highmem NULL deref on bh->b_data in inode_test_read_bh_lock_stub()
It also noticed 2 related pre-existing issues this patch does not introduce:
- [Medium] ext4: user-triggerable WARN_ON_ONCE in ext4_iomap_begin() [1]
- [Critical] ext4: stale data leak to concurrent readers in ext4_setattr() [2]
--
commit f093b56ce7ca8d901aefc501ae9f381a7877b64a
Author: Theodore Ts'o <[email protected]>
ext4: expand KUnit tests for fs/ext4/inode.c
This commit expands the ext4_inode_test KUnit test suite to exercise fs/ext4/inode.c using an in-memory VFS superblock and mock block pool, and adds KUnit static stub redirects and symbol exports for the tested entry points.
Quoted 5 lines
fs/ext4/inode-test.c +0
-0@@ -267,8 +284,3432 @@ static void inode_test_xtimestamp_decoding(struct kunit *test)
[ ... ]
Quoted 50 lines
fs/ext4/inode-test.c +50
-0+static void inode_test_read_bh_nowait_stub (struct buffer_head *bh, +blk_opf_t op_flags, +bio_end_io_t end_io, +bool simu_fail) +{ +struct kunit *test =kunit_get_current_test (); +struct inode_test_ctx *ctx = test ? test->priv :NULL ; +struct inode_test_blk *slot; + +if (!ctx) { +unlock_buffer (bh); +return ; + } + ctx->read_nowait_calls++; +if (ctx->fail_read_eio || simu_fail) { +clear_buffer_uptodate (bh); +unlock_buffer (bh); +return ; + } + slot =inode_test_find_blk_by_bh (ctx, bh); +if (!slot) + slot =inode_test_find_blk (ctx, bh->b_blocknr); +if (slot) { +memcpy (bh->b_data, slot->disk_buf, bh->b_size); +set_buffer_uptodate (bh); + }else { +clear_buffer_uptodate (bh); + } +unlock_buffer (bh); +} + +static int inode_test_read_bh_lock_stub (struct buffer_head *bh, +blk_opf_t op_flags,bool wait) +{ +struct kunit *test =kunit_get_current_test (); +struct inode_test_ctx *ctx = test ? test->priv :NULL ; +struct inode_test_blk *slot; + +if (!ctx) +return -EIO ; + ctx->read_lock_calls++; +lock_buffer (bh); +if (ctx->fail_read_eio) { +clear_buffer_uptodate (bh); +unlock_buffer (bh); +return wait ? -EIO :0 ; + } + slot =inode_test_find_blk_by_bh (ctx, bh); +if (!slot) + slot =inode_test_find_blk (ctx, bh->b_blocknr);
fs/ext4/inode-test.c static void inode_test_xtimestamp_decoding(struct kunit *test) · line 669
Quoted 10 lines
fs/ext4/inode-test.c +10
-0+if (!slot) { +clear_buffer_uptodate (bh); +unlock_buffer (bh); +return wait ? -EIO :0 ; + } +memcpy (bh->b_data, slot->disk_buf, bh->b_size); +set_buffer_uptodate (bh); +unlock_buffer (bh); +return 0 ; +}
[Severity: Medium]
Can copying directly to bh->b_data in inode_test_read_bh_lock_stub() and inode_test_read_bh_nowait_stub() cause a NULL or low-address pointer dereference on 32-bit CONFIG_HIGHMEM=y kernels?
inode_test_setup() configures inode->i_data with GFP_HIGHUSER_MOVABLE. When inode_test_zero_partial_and_eof() or inode_test_setattr() calls ext4_zero_partial_blocks() -> ext4_block_zero_range() -> ext4_load_tail_bh(), the pagecache folio allocated for inode->i_mapping can come from highmem. create_empty_buffers() -> folio_set_bh() sets bh->b_data on a highmem folio to (char *)(0 + offset) rather than a kernel virtual address, so memcpy(bh->b_data, ...) faults when ext4_load_tail_bh() calls ext4_read_bh_lock(). Using memcpy_to_folio(bh->b_folio, bh_offset(bh), ...) when bh->b_folio is present (or dropping __GFP_HIGHMEM from inode->i_data) would avoid this.
[ ... ]
Quoted 71 lines
fs/ext4/inode-test.c +71
-0+static void inode_test_cleanup (void *data) +{ +struct inode_test_ctx *ctx = data; +struct inode *inode = &ctx->ei.vfs_inode; +struct mapping_metadata_bhs *mmb; +unsigned int i; + + ctx->sbi.s_journal =NULL ; + +for (i =0 ; i < ctx->nr_tracked_inodes; i++) { +struct inode *ti = ctx->tracked_inodes[i]; + +if (ti) { +spin_lock (&ti->i_lock); +inode_state_clear (ti,I_DIRTY_TIME ); +spin_unlock (&ti->i_lock); +iput (ti); + ctx->tracked_inodes[i] =NULL ; + } + } + ctx->nr_tracked_inodes =0 ; + +truncate_inode_pages_final (&inode->i_data); +inode_io_list_del (inode); +ext4_fc_del (inode); + mmb =ext4_i_metadata_bhs (inode); +if (mmb) +mmb_invalidate (mmb); +inode_test_cleanup_ext4_trees (inode); +if (ctx->ei.jinode) { +jbd2_free_inode (ctx->ei.jinode); + ctx->ei.jinode =NULL ; + } + +deactivate_super (ctx->sb); +rcu_barrier (); + +ext4_es_unregister_shrinker (&ctx->sbi); +percpu_counter_destroy (&ctx->sbi.s_dirtyclusters_counter); +percpu_counter_destroy (&ctx->sbi.s_freeclusters_counter); + +kfree (mmb); +kfree (ctx); +} + +static struct inode_test_ctx *inode_test_setup (struct kunit *test) +{ +struct inode_test_ctx *ctx; +struct fs_context *fc; +struct super_block *sb; +struct ext4_sb_info *sbi; +struct inode *inode; +int err, i; + + ctx =kzalloc_obj (*ctx); +KUNIT_ASSERT_NOT_NULL (test, ctx); + test->priv = ctx; + + fc =fs_context_for_mount (&inode_test_fs_type,0 ); +if (IS_ERR (fc)) { + err =PTR_ERR (fc); +kfree (ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + } + sb =sget_fc (fc,NULL , set_anon_super_fc); +put_fs_context (fc); +if (IS_ERR (sb)) { + err =PTR_ERR (sb); +kfree (ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + }
fs/ext4/inode-test.c static void inode_test_xtimestamp_decoding(struct kunit *test) · line 954
Quoted 10 lines
fs/ext4/inode-test.c +10
-0+ ctx->sb = sb; + sbi = &ctx->sbi; + + sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &inode_test_sops; +#ifdef CONFIG_QUOTA + sb->dq_op = &inode_test_qops; +#endif + sb->s_flags |=SB_ACTIVE ;
[Severity: Medium]
Can setting SB_ACTIVE while leaving sb->s_root NULL cause a use-after-free of ctx->sb, ctx->sbi, and inodes after inode_test_cleanup() runs?
sget_fc() -> alloc_super() calls fserror_mount(sb), which sets sb->s_pending_errors to 1. When tests exercise corruption paths that call __ext4_error() or __ext4_error_inode(), fserror_report() sees SB_ACTIVE and s_pending_errors > 0, takes a reference on the inode via igrab(), and queues fserror_worker() on system_dfl_wq. Because ctx->sb->s_root is NULL, deactivate_super() -> generic_shutdown_super() skips fserror_unmount(sb):
CPU0 (KUnit test) CPU1 (kworker)inode_test_iget_corruptions()
ext4_iget()
__ext4_error_inode()
fserror_report()
igrab(inode)
schedule_work(&event->work)
inode_test_cleanup()
deactivate_super(ctx->sb)
generic_shutdown_super()
/* s_root is NULL: skips
fserror_unmount() */
kfree(ctx)
fserror_worker()
/* accesses freed event->sb */
iput(event->inode)
ext4_evict_inode()
/* accesses freed ctx->sbi */
<-- use-after-freeIn addition, when __ext4_error_inode() is called on the embedded &ctx->ei.vfs_inode (for example in inode_test_expand_extra_isize()), fserror_worker() races with inode_test_reset_mock_inode() and calls iput() on the embedded inode after ctx is freed. Calling fserror_unmount(sb) in inode_test_setup() (or before freeing ctx in inode_test_cleanup()) would prevent fserror_report() from queuing async work.
Quoted 4 lines
fs/ext4/inode.c +0
-0
[ ... ]
fs/ext4/inode.c int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, · line 3891
Quoted 5 lines
fs/ext4/inode.c +1
-0@@ -3858,12 +3888,14 @@ int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_iomap_begin);
[Severity: Medium]
This problem wasn't introduced by this patch, but can an atomic write to an encrypted file trigger WARN_ON_ONCE(1) in ext4_iomap_begin() [1]?
Before checking the IOMAP_ATOMIC length constraint, ext4_iomap_begin() calls fscrypt_limit_io_blocks() to truncate map.m_len when an I/O crosses a 32-bit DUN boundary:
fs/ext4/inode.c:ext4_iomap_begin() {
...
map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
/*
* Before returning to iomap, let's ensure the allocated mapping
* covers the entire requested length for atomic writes.
*/
if (flags & IOMAP_ATOMIC) {
if (map.m_len < (length >> blkbits)) {
WARN_ON_ONCE(1);
return -EINVAL;
}
}
...
}When an unprivileged user issues an atomic write across a DUN boundary on an encrypted file, fscrypt_limit_io_blocks() shortens map.m_len below length >> blkbits and triggers WARN_ON_ONCE(1).
[ ... ]
fs/ext4/inode.c int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry, · line 6325
Quoted 5 lines
fs/ext4/inode.c +1
-0@@ -6274,6 +6322,7 @@ int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry, error = rc;return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_setattr);
[Severity: Critical]
This problem wasn't introduced by this patch, but when extending a file via ext4_setattr(), can updating i_size before calling pagecache_isize_extended() expose stale post-EOF pagecache data to concurrent readers [2]?
When extending a file whose old size is block-aligned (or where blocksize < PAGE_SIZE) and whose tail folio already has uptodate post-EOF data in the pagecache (such as from an earlier mmap write past EOF), ext4_setattr() writes the new i_size under i_data_sem before stopping the journal handle and zeroing the extended pagecache range:
CPU0 CPU1ext4_setattr()
i_size_write(inode, attr->ia_size)
generic_file_read_iter()
filemap_read()
/* sees new i_size and copies
unzeroed tail folio <-- stale data */
ext4_journal_stop(handle)
pagecache_isize_extended()
Because buffered reads do not take i_rwsem, CPU1 can read the unzeroed post-EOF portion of the folio before pagecache_isize_extended() zeroes it.
[1] https://sashiko.dev/#/bug/linux-38b43030-f0ce-4abf-8653-7266f768a948
[2] https://sashiko.dev/#/bug/linux-808e5d6d-ae12-4689-877c-3d6dc1f711d5
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Theodore Ts'o
maintainerPATCH 11/27 ext4: add KUnit tests for fs/ext4/ialloc.c
In reply to Theodore Ts'oAdd the ext4_ialloc_test KUnit test suite in fs/ext4/ialloc-test.c (28 test cases, 33 subtests total) to comprehensively exercise inode bitmap management, group selection heuristics, inode allocation, freeing, orphan lookup, and lazy inode table initialization in fs/ext4/ialloc.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device:
- Bitmap padding and asynchronous read completion helpers (ext4_mark_bitmap_end and ext4_end_bitmap_read) across unaligned and byte-aligned start/end bit boundaries, partial single-byte updates, no-op guards, BLK_STS_OK completion, and BLK_STS_IOERR / BIO_QUIET failure handling.
- Inode bitmap validation and loading (ext4_validate_inode_bitmap and ext4_read_inode_bitmap), covering CRC32C verification, out-of-group metadata block overlap detection, EXT4_FC_REPLAY and buffer_verified short-circuits, cache hits vs. synchronous disk reads, lazy EXT4_BG_INODE_UNINIT bitmap initialization, and fault injection across ext4_get_group_desc, ext4_sb_getblk, and ext4_read_bh.
- Inode freeing (ext4_free_inode) across regular files and directories, bitmap bit clearing, group descriptor, flex_bg, and percpu counter updates, CRC32C recomputation, guard rejections (NULL i_sb, i_count > 1, i_nlink > 0, reserved ino < EXT4_FIRST_INO, and out-of-range ino), double-free corruption marking, pre-corrupt bitmap skips (vs. EXT4_FC_REPLAY), and journal get_write_access error handling.
- Orlov directory group allocator (find_group_orlov) across root and EXT4_INODE_TOPDIR spreading (hashed qstr and NULL qstr), subdirectory co-location, i_last_alloc_group hints, max_dirs / min_inodes / min_clusters thresholds, flex_bg constituent group packing, and two-pass linear fallback when percpu counters are inflated or all groups are exhausted.
- Non-directory group allocator (find_group_other) with and without flex_bg, covering parent group preference, last-allocated group spreading, quadratic hash probing, cyclic linear search, and modulo wraparound.
- Recently-deleted inode buffer-cache checks (recently_deleted) across EXT4_BG_INODE_UNINIT, bg_itable_unused bounds, uncached or non-uptodate inode table blocks, zero i_dtime, and clean (60s) vs. dirty (360s) buffer_dirty() recency windows, plus find_inode_bit scanning across non-journaled skipping, journaled (s_journal) bypass, and recently_deleted_ino fallback.
- On-disk inode reservation during fast-commit replay (ext4_mark_inode_used) across uninitialized EXT4_BG_INODE_UNINIT and EXT4_BG_BLOCK_UNINIT groups, overhead cluster calculation, bg_itable_unused updates, idempotency on already-set bits, and invalid ino, inode/block bitmap read and wait, dirty-metadata, and sync_dirty_buffer error paths.
- Extended attribute transaction credit estimation (ext4_xattr_credits_for_new_inode) across POSIX default ACL inheritance, security xattrs, and encryption contexts.
- Full new-inode allocation (__ext4_new_inode) across regular files, directories, symlinks, and special files, flag inheritance and masking (EXT4_FL_INHERITED and ext4_mask_flags), EXT4_EA_INODE_FL inline-data suppression, UID/GID ownership overrides, SGID inheritance, EXT4_INODE_PROJINHERIT project ID propagation, explicit goal and s_inode_goal targeting, uninitialized group setup, corrupt/reserved bit skipping, EXT4_FC_REPLAY goal allocation, ext4_new_inode_start_handle, and error paths (-EPERM, emergency -EIO/-EROFS, -ENOMEM, -ENOSPC, duplicate inode hash -EIO, write-access and dirty-metadata failures, and ext4_init_security / ext4_mark_inode_dirty rollback).
- Orphan inode lookup and validation (ext4_orphan_get), group free-inode and used-directory summation (ext4_count_free_inodes and ext4_count_dirs, including 64-bit high-16-bit fields), and lazy inode table zeroing (ext4_init_inode_table) across already-zeroed, uninit, partially used, full, bogus bg_itable_unused, and zeroout error cases.
Route buffer-cache lookups in ialloc.c through ext4_sb_getblk() and ext4_sb_find_get_block(), extract ext4_itable_zeroout() with KUNIT_STATIC_STUB_REDIRECT, add KUNIT_STATIC_STUB_REDIRECT hooks in ext4_read_bh(), __ext4_journal_get_write_access(), and ext4_init_security(), and export the tested entry points and static-helper wrappers with EXPORT_SYMBOL_FOR_EXT4_TEST.
--- fs/ext4/Makefile | 2 +- fs/ext4/bitmap.c | 5 + fs/ext4/ext4.h | 21 + fs/ext4/ext4_jbd2.c | 4 + fs/ext4/ialloc-test.c | 2714 ++++++++++++++++++++++++++++++++++++++ fs/ext4/ialloc.c | 85 +- fs/ext4/super.c | 17 + fs/ext4/xattr_security.c | 4 + 8 files changed, 2844 insertions(+), 8 deletions(-) create mode 100644 fs/ext4/ialloc-test.c
fs/ext4/Makefile +1 -1
@@ -18,7 +18,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ - fast_commit-test.o + fast_commit-test.o ialloc-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/bitmap.c +5 -0
@@ -15,6 +15,7 @@ unsigned int ext4_count_free(char *bitmap, unsigned int numchars) {return numchars *BITS_PER_BYTE -memweight (bitmap, numchars); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_count_free); int ext4_inode_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp,
@@ -39,6 +40,7 @@ int ext4_inode_bitmap_csum_verify(struct super_block *sb,return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_bitmap_csum_verify); void ext4_inode_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp,
@@ -57,6 +59,7 @@ void ext4_inode_bitmap_csum_set(struct super_block *sb,if (sbi->s_desc_size >=EXT4_BG_INODE_BITMAP_CSUM_HI_END ) gdp->bg_inode_bitmap_csum_hi =cpu_to_le16 (csum >>16 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_bitmap_csum_set); int ext4_block_bitmap_csum_verify(struct super_block *sb, struct ext4_group_desc *gdp,
@@ -80,6 +83,7 @@ int ext4_block_bitmap_csum_verify(struct super_block *sb,return provided == calculated; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_block_bitmap_csum_verify); void ext4_block_bitmap_csum_set(struct super_block *sb, struct ext4_group_desc *gdp,
@@ -97,3 +101,4 @@ void ext4_block_bitmap_csum_set(struct super_block *sb,if (sbi->s_desc_size >=EXT4_BG_BLOCK_BITMAP_CSUM_HI_END ) gdp->bg_block_bitmap_csum_hi =cpu_to_le16 (csum >>16 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_block_bitmap_csum_set);
fs/ext4/ext4.h +21 -0
@@ -3065,9 +3065,30 @@ extern struct inode * ext4_orphan_get(struct super_block *, unsigned long);extern unsigned long ext4_count_free_inodes (struct super_block *);extern unsigned long ext4_count_dirs (struct super_block *);extern void ext4_mark_bitmap_end (int start_bit,int end_bit,char *bitmap); +int ext4_itable_zeroout (struct super_block *sb,ext4_fsblk_t blk,int num, +int barrier);extern int ext4_init_inode_table (struct super_block *sb,ext4_group_t group,int barrier);void ext4_end_bitmap_read (struct bio *bio); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +int ext4_validate_inode_bitmap_test (struct super_block *sb, +struct ext4_group_desc *desc, +ext4_group_t block_group, +struct buffer_head *bh); +struct buffer_head *ext4_read_inode_bitmap_test (struct super_block *sb, +ext4_group_t block_group); +int ext4_find_group_orlov_test (struct super_block *sb,struct inode *parent, +ext4_group_t *group,umode_t mode, +const struct qstr *qstr); +int ext4_find_group_other_test (struct super_block *sb,struct inode *parent, +ext4_group_t *group,umode_t mode); +int ext4_recently_deleted_test (struct super_block *sb,ext4_group_t group, +int ino); +int ext4_find_inode_bit_test (struct super_block *sb,ext4_group_t group, +struct buffer_head *bitmap,unsigned long *ino); +int ext4_xattr_credits_for_new_inode_test (struct inode *dir,mode_t mode, +bool encrypt); +#endif /* fast_commit.c */ int ext4_fc_get_buf (journal_t *journal,struct buffer_head **bh);
fs/ext4/ext4_jbd2.c +4 -0
@@ -248,6 +248,9 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, {int err; +KUNIT_STATIC_STUB_REDIRECT (__ext4_journal_get_write_access, where, line, + handle, sb, bh, trigger_type); +might_sleep ();if (ext4_handle_valid (handle)) {
@@ -267,6 +270,7 @@ int __ext4_journal_get_write_access(const char *where, unsigned int line, &EXT4_SB(sb)->s_journal_triggers[trigger_type].tr_triggers);return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (__ext4_journal_get_write_access);/* * The ext4 forget function must perform a revoke if we are freeing data
fs/ext4/ialloc-test.c new file +2714 -0
2,714 lines not on this page · raw message
fs/ext4/ialloc.c +78 -7
153 lines not on this page · raw message
fs/ext4/super.c +17 -0
@@ -201,6 +201,9 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_read_bh_nowait);int ext4_read_bh (struct buffer_head *bh,blk_opf_t op_flags,bio_end_io_t end_io,bool simu_fail) { +KUNIT_STATIC_STUB_REDIRECT (ext4_read_bh, bh, op_flags, + end_io, simu_fail); +BUG_ON (!buffer_locked (bh));if (ext4_buffer_uptodate (bh)) {
@@ -215,6 +218,7 @@ int ext4_read_bh(struct buffer_head *bh, blk_opf_t op_flags,return 0 ;return -EIO ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_read_bh);int ext4_read_bh_lock (struct buffer_head *bh,blk_opf_t op_flags,bool wait) {
@@ -348,6 +352,7 @@ ext4_fsblk_t ext4_block_bitmap(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t )le32_to_cpu (bg->bg_block_bitmap_hi) <<32 :0 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_block_bitmap);ext4_fsblk_t ext4_inode_bitmap (struct super_block *sb,struct ext4_group_desc *bg)
@@ -356,6 +361,7 @@ ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t )le32_to_cpu (bg->bg_inode_bitmap_hi) <<32 :0 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_bitmap);ext4_fsblk_t ext4_inode_table (struct super_block *sb,struct ext4_group_desc *bg)
@@ -364,6 +370,7 @@ ext4_fsblk_t ext4_inode_table(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (ext4_fsblk_t )le32_to_cpu (bg->bg_inode_table_hi) <<32 :0 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_table);__u32 ext4_free_group_clusters (struct super_block *sb,struct ext4_group_desc *bg)
@@ -380,6 +387,7 @@ __u32 ext4_free_inodes_count(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (__u32 )le16_to_cpu (READ_ONCE (bg->bg_free_inodes_count_hi)) <<16 :0 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_inodes_count);__u32 ext4_used_dirs_count (struct super_block *sb,struct ext4_group_desc *bg)
@@ -388,6 +396,7 @@ __u32 ext4_used_dirs_count(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (__u32 )le16_to_cpu (bg->bg_used_dirs_count_hi) <<16 :0 ); }
Lines of this file are not shown. View the raw message.
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Part of the diff is not shown here. View the raw message.
[email protected]
AI reviewRe: [PATCH 11/27] ext4: add KUnit tests for fs/ext4/ialloc.c
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ext4: UAF on super_block in ialloc_test_cleanup() from undrained fserror work It also noticed 1…
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ext4: UAF on super_block in ialloc_test_cleanup() from undrained fserror work
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Critical] ext4: missing error handling for blkdev_issue_flush() in ext4_fc_commit() [1]
--
commit 52f553b981802c3fefc912614c6427cda362ae6f
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/ialloc.c
This commit adds a KUnit test suite for fs/ext4/ialloc.c along with static stub hooks and helper exports to test inode allocation, freeing, bitmap validation, and lazy inode table initialization.
Quoted 5 lines
fs/ext4/ialloc-test.c new file +0
-0
[ ... ]
Quoted 26 lines
fs/ext4/ialloc-test.c new file +26
-0+static void ialloc_test_cleanup (void *data) +{ +struct ialloc_test_ctx *ctx = data; +handle_t *handle; +unsigned int i; + + ctx->evict_skip_free = true; + ctx->sbi.s_journal =NULL ; + +while ((handle =ext4_journal_current_handle ()) !=NULL ) +ext4_journal_stop (handle); + +for (i =0 ; i < ctx->nr_tracked_inodes; i++) { +struct inode *ti = ctx->tracked_inodes[i]; + +if (ti) { +if (inode_state_read_once (ti) &I_NEW ) +unlock_new_inode (ti); +spin_lock (&ti->i_lock); +inode_state_clear (ti,I_DIRTY_TIME ); +spin_unlock (&ti->i_lock); +set_nlink (ti,1 ); +iput (ti); + ctx->tracked_inodes[i] =NULL ; + } + }
fs/ext4/ialloc-test.c line 713
Quoted 10 lines
fs/ext4/ialloc-test.c new file +10
-0+ ctx->nr_tracked_inodes =0 ; + + ctx->sb->s_root =NULL ; +if (ctx->root_inode) { +set_nlink (ctx->root_inode,2 ); +iput (ctx->root_inode); + ctx->root_inode =NULL ; + } + +deactivate_super (ctx->sb);
[Severity: Medium]
Can clearing ctx->sb->s_root before deactivate_super(ctx->sb) cause a use-after-free on ctx->sb in fserror_worker()?
ialloc_test_init() sets SB_ACTIVE on ctx->sb, so tests that trigger ext4_error() or ext4_std_error() queue fserror_worker() items referencing ctx->sb via fserror_report_metadata(). In generic_shutdown_super(), fserror_unmount(sb) is only called inside the if (sb->s_root) block, so nulling s_root beforehand skips draining those pending work items before ctx->sb is freed:
CPU0 kworkerialloc_test_validate_ibitmap_csum()
ext4_error()
fserror_report_metadata()
queue_work(..., &event->work)
ialloc_test_cleanup()
ctx->sb->s_root = NULL
deactivate_super(ctx->sb)
generic_shutdown_super()
/* skips fserror_unmount() */
put_super()
...
kfree(sb)
fserror_worker()
sb = event->sb
if (sb->s_flags & SB_ACTIVE)
<-- use-after-freeOmitting SB_ACTIVE in ialloc_test_init() would avoid queueing fserror events in the first place.
Quoted 4 lines
fs/ext4/ialloc.c +0
-0
[ ... ]
Quoted 11 lines
fs/ext4/ialloc.c +7
-0@@ -1521,6 +1527,23 @@ unsigned long ext4_count_dirs(struct super_block * sb) }return count; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_count_dirs); + +int ext4_itable_zeroout (struct super_block *sb,ext4_fsblk_t blk,int num, +int barrier) +{ +int ret; +
fs/ext4/ialloc.c unsigned long ext4_count_dirs(struct super_block * sb) · line 1546
Quoted 10 lines
fs/ext4/ialloc.c +10
-0+KUNIT_STATIC_STUB_REDIRECT (ext4_itable_zeroout, sb, blk, num, barrier); + + ret =sb_issue_zeroout (sb, blk, num,GFP_NOFS ); +if (ret <0 ) +return ret; +if (barrier) +blkdev_issue_flush (sb->s_bdev); +return ret; +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_itable_zeroout);
[Severity: Critical]
This problem wasn't introduced by this patch, but should ext4_itable_zeroout() check and return the error from blkdev_issue_flush() [1]?
When barrier is set and blkdev_issue_flush() fails, ext4_itable_zeroout() still returns 0, so ext4_init_inode_table() proceeds to set EXT4_BG_INODE_ZEROED in the group descriptor even though the zeroed inode table blocks may not have been flushed to stable storage before a crash. (The same unchecked blkdev_issue_flush() pattern also exists in ext4_fc_perform_commit() and ext4_fc_replay_inode() in fs/ext4/fast_commit.c.)
[1] https://sashiko.dev/#/bug/linux-d85ff7fd-2937-4bb0-8016-be8fb0499fbd
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Theodore Ts'o
maintainerPATCH 12/27 ext4: add KUnit tests for fs/ext4/balloc.c
In reply to Theodore Ts'oAdd the ext4_balloc_test KUnit test suite in fs/ext4/balloc-test.c (29 test cases, 43 subtests total) to comprehensively exercise block bitmap management, group descriptor and overhead calculations, cluster pool reservation, allocation retry policy, metadata block allocation, and goal block selection in fs/ext4/balloc.c using an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device:
- Block-to-group and cluster-offset mapping (ext4_get_group_number and ext4_get_group_no_and_offset) across 1K and 4K block sizes, standard shift-based vs. non-standard do_div group geometries, bigalloc multi-block clusters, s_first_data_block offsets, >32-bit physical block numbers, and optional NULL output pointers.
- Backup superblock placement (ext4_bg_has_super) across dense filesystems, sparse_super powers of 3, 5, and 7, and sparse_super2 explicit s_backup_bgs configurations.
- Group descriptor table and base metadata block counts (ext4_bg_num_gdb and ext4_num_base_meta_blocks) across traditional GDT layouts with s_reserved_gdt_blocks and hybrid meta_bg filesystems spanning pre-s_first_meta_bg and meta_bg descriptor groups.
- Group overhead and post-init free cluster accounting (ext4_free_clusters_after_init, ext4_num_overhead_clusters, and num_clusters_in_group) across standard groups, partial final groups, external flex_bg metadata, spanning inode tables, and bigalloc shared-cluster layouts.
- Group descriptor and group info lookup (ext4_get_group_desc and ext4_get_group_info) across multi-block descriptor tables, bounds checks, missing descriptor buffers, and NULL RCU slice guards.
- Block bitmap validation, reading, prefetching, and lazy initialization (ext4_read_block_bitmap_nowait, ext4_wait_block_bitmap, and ext4_read_block_bitmap), covering CRC32C verification, in-group and out-of-group metadata bit validation with and without flex_bg, bitmap tail padding checks, EXT4_FC_REPLAY and buffer_verified short-circuits, cold disk reads vs. cached buffer promotions, REQ_RAHEAD locked-buffer prefetching, EXT4_BG_BLOCK_UNINIT lazy bitmap initialization (CRC32C, legacy CRC16 GDT_CSUM, and unchecksummed fallback), group 0 and oversized base-metadata corruption guards, and simulated getblk / I/O errors.
- Free cluster reservation and pool accounting (ext4_claim_free_clusters and ext4_has_free_clusters) across above-watermark fast paths, unprivileged limits, bigalloc r_blocks scaling, root-reserved pool access via s_resuid, non-root s_resgid supplementary group membership, EXT4_MB_USE_ROOT_BLOCKS, and CAP_SYS_RESOURCE, plus EXT4_MB_USE_RESERVED internal pool access.
- Allocation retry policy (ext4_should_retry_alloc) across non-journaled mounts, pending mballoc free retries up to the 3-attempt limit with s_sra_exceeded_retry_limit accounting, free-space rechecks, and s_discard_work flushing under s_retry_alloc_pending.
- Metadata block allocation (ext4_new_meta_blocks), free cluster summation (ext4_count_free_clusters across corrupt bitmaps, 64-bit high free-cluster counts, and unloaded descriptor blocks), and inode goal block selection (ext4_inode_to_goal_block across flex_bg directory vs. regular file placement, delalloc, and nodelalloc PID colouring).
Route the block bitmap buffer lookup in ext4_read_block_bitmap_nowait() through ext4_sb_getblk() so KUnit tests can intercept buffer-cache lookups via its existing static stub hook, and export the remaining non-static balloc.c entry points with EXPORT_SYMBOL_FOR_EXT4_TEST.
--- fs/ext4/Makefile | 3 +- fs/ext4/balloc-test.c | 2359 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/balloc.c | 11 +- 3 files changed, 2371 insertions(+), 2 deletions(-) create mode 100644 fs/ext4/balloc-test.c
fs/ext4/Makefile +2 -1
@@ -18,7 +18,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents-test.o hash-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ - fast_commit-test.o ialloc-test.o + fast_commit-test.o ialloc-test.o \ + balloc-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/balloc-test.c new file +2359 -0
2,359 lines not on this page · raw message
fs/ext4/balloc.c +10 -1
@@ -243,6 +243,7 @@ unsigned ext4_free_clusters_after_init(struct super_block *sb,return num_clusters_in_group (sb, block_group) -ext4_num_overhead_clusters (sb, block_group, gdp); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_clusters_after_init);/* * The free blocks are managed by bitmaps. A file system contains several
@@ -489,7 +490,7 @@ ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group, EXT4_GROUP_INFO_BBITMAP_CORRUPT);return ERR_PTR (-EFSCORRUPTED ); } - bh =sb_getblk (sb, bitmap_blk); + bh =ext4_sb_getblk (sb, bitmap_blk);if (unlikely (!bh)) { ext4_warning(sb, "Cannot get buffer for block bitmap - " "block_group = %u, block_bitmap = %llu",
@@ -611,6 +612,7 @@ ext4_read_block_bitmap(struct super_block *sb, ext4_group_t block_group) }return bh; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_read_block_bitmap);/** * ext4_has_free_clusters()
@@ -678,6 +680,7 @@ int ext4_claim_free_clusters(struct ext4_sb_info *sbi, }else return -ENOSPC ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_claim_free_clusters);/** * ext4_should_retry_alloc() - check if a block allocation should be retried
@@ -724,6 +727,7 @@ int ext4_should_retry_alloc(struct super_block *sb, int *retries) (void )jbd2_journal_force_commit_nested (sbi->s_journal);return 1 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_should_retry_alloc);/* * ext4_new_meta_blocks() -- allocate block for meta data (indexing) blocks
@@ -764,6 +768,7 @@ ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode, }return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_new_meta_blocks);/** * ext4_count_free_clusters() -- count filesystem free clusters
@@ -877,6 +882,7 @@ int ext4_bg_has_super(struct super_block *sb, ext4_group_t group)return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_bg_has_super);static unsigned long ext4_bg_num_gdb_meta (struct super_block *sb,ext4_group_t group)
@@ -923,6 +929,7 @@ unsigned long ext4_bg_num_gdb(struct super_block *sb, ext4_group_t group)return ext4_bg_num_gdb_meta (sb,group); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_bg_num_gdb);/* * This function returns the number of file system metadata blocks at
@@ -949,6 +956,7 @@ unsigned int ext4_num_base_meta_blocks(struct super_block *sb, }return num; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_num_base_meta_blocks);static unsigned int ext4_num_base_meta_clusters (struct super_block *sb,ext4_group_t block_group)
@@ -1004,4 +1012,5 @@ ext4_fsblk_t ext4_inode_to_goal_block(struct inode *inode) ((last_block - bg_start) /16 );return bg_start + colour; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_to_goal_block);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 12/27] ext4: add KUnit tests for fs/ext4/balloc.c
Sashiko has reviewed this patch and found no issues.
Quoted 20 lines
Add the
ext4_balloc_testKUnit test suite infs/ext4/balloc-test.c(29 test cases, 43 subtests total) to comprehensively exercise block bitmap management, group descriptor and overhead calculations, cluster pool reservation, allocation retry policy, metadata block allocation, and goal block selection infs/ext4/balloc.cusing an in-memory VFS superblock, mock block device, and deterministic block pool without requiring a mounted block device:- Block-to-group and cluster-offset mapping (
ext4_get_group_numberandext4_get_group_no_and_offset) across 1K and 4K block sizes, standard shift-based vs. non-standarddo_divgroup geometries, bigalloc multi-block clusters,s_first_data_blockoffsets, >32-bit physical block numbers, and optional NULL output pointers.
- Backup superblock placement (ext4_bg_has_super) across dense filesystems,sparse_superpowers of 3, 5, and 7, andsparse_super2
[ ... ]
throughext4_sb_getblk()so KUnit tests can intercept buffer-cache lookups via its existing static stub hook, and export the remaining non-staticballoc.centry points withEXPORT_SYMBOL_FOR_EXT4_TEST.
Quoted 1 line
Signed-off-by Theodore Ts'o <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Theodore Ts'o
maintainerPATCH 13/27 ext4: add KUnit tests for fs/ext4/orphan.c
In reply to Theodore Ts'oAdd the ext4_orphan_test KUnit test suite in fs/ext4/orphan-test.c (22 test cases, 25 subtests total when CONFIG_QUOTA is enabled; 21 test cases, 24 subtests otherwise) to comprehensively exercise orphan inode tracking, orphan file management, and mount-time orphan recovery in fs/ext4/orphan.c using an in-memory VFS superblock, mock block device, and deterministic buffer pool without requiring a mounted block device:
- Orphan block geometry and empty-state checks (ext4_inodes_per_orphan_block across 1K, 2K, 4K, and 64K block sizes, and ext4_orphan_file_empty across disabled feature, zero-block files, and multi-block occupancy transitions).
- Superblock linked-list orphan insertion (ext4_orphan_add), covering no-journal and bad-inode early exits, I_NEW unlocked insertion and deletion, idempotency when already tracked via i_orphan or EXT4_STATE_ORPHAN_FILE, LIFO chaining across regular, directory, and symlink inodes with superblock CRC32C updates, NEXT_ORPHAN boundary checks at s_inodes_count vs. s_inodes_count + 1, and journal/iloc error rollbacks without leaking buffer references or leaving stray s_orphan entries.
- Superblock linked-list orphan removal (ext4_orphan_del), covering untracked inodes, no-journal early exit vs. EXT4_ORPHAN_FS recovery mode, head/middle/tail unlinking, NULL-handle in-core-only cleanup, and error propagation across superblock and predecessor/target inode journal operations.
- Orphan-file insertion and deletion (ext4_orphan_file_add and ext4_orphan_file_del), covering EXT4_JTR_ORPHAN_FILE trigger wiring, slot claiming and freeing, circular block-ring wrap-around and final slot allocation, -ENOSPC fallback to the superblock linked list when all orphan blocks are full, non-ENOSPC journal write-access and dirty-metadata error propagation without fallback, NULL-handle state cleanup, and out-of-range block index warning guards.
- Orphan-file JBD2 frozen-buffer checksum trigger and lifecycle management (ext4_orphan_file_block_trigger on live and frozen buffers, ext4_init_orphan_info, ext4_orphan_file_block_csum_verify with and without metadata_csum, the 512-block EXT4_MAX_ORPHAN_FILE_BLOCKS size boundary, partial-load error cleanup on iget/bread/hole/bad-magic/ bad-checksum failures, and ext4_release_orphan_info).
- End-to-end mount-time orphan recovery (ext4_orphan_cleanup and ext4_process_orphan), covering empty-fs, read-only bdev, incompatible ROCOMPAT features, and EXT4_ERROR_FS skip guards, unlinked file and fast-symlink eviction, linked-inode truncation, combined linked-list and orphan-file recovery with corrupt-slot skipping and SB_RDONLY restoration, truncate failure handling via ext4_orphan_del(NULL, ...) and mid-loop EXT4_ERROR_FS abort, and quota activation/teardown paths under CONFIG_QUOTA and CONFIG_QFMT_V2.
Add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_truncate() in fs/ext4/inode.c for truncate failure injection during orphan recovery, and export the remaining non-static fs/ext4/orphan.c entry points with EXPORT_SYMBOL_FOR_EXT4_TEST.
--- fs/ext4/Makefile | 2 +- fs/ext4/inode.c | 2 + fs/ext4/orphan-test.c | 2364 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/orphan.c | 5 + 4 files changed, 2372 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/orphan-test.c
fs/ext4/Makefile +1 -1
@@ -19,7 +19,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ - balloc-test.o + balloc-test.o orphan-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/inode.c +2 -0
@@ -4686,6 +4686,8 @@ int ext4_truncate(struct inode *inode)int err =0 , err2;handle_t *handle; +KUNIT_STATIC_STUB_REDIRECT (ext4_truncate, inode); +/* * There is a possibility that we're either freeing the inode * or it's a completely new inode. In those cases we might not
fs/ext4/orphan-test.c new file +2364 -0
2,364 lines not on this page · raw message
fs/ext4/orphan.c +5 -0
@@ -511,6 +511,7 @@ void ext4_orphan_cleanup(struct super_block *sb, struct ext4_super_block *es)#endif sb->s_flags = s_flags;/* Restore SB_RDONLY status */ } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_orphan_cleanup);void ext4_release_orphan_info (struct super_block *sb) {
@@ -523,6 +524,7 @@ void ext4_release_orphan_info(struct super_block *sb)brelse (oi->of_binfo[i].ob_bh);kvfree (oi->of_binfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_release_orphan_info); static struct ext4_orphan_block_tail *ext4_orphan_block_tail( struct super_block *sb,
@@ -570,6 +572,7 @@ void ext4_orphan_file_block_trigger(struct jbd2_buffer_trigger_type *triggers, ot =ext4_orphan_block_tail (sb, bh); ot->ob_checksum =cpu_to_le32 (csum); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_orphan_file_block_trigger);int ext4_init_orphan_info (struct super_block *sb) {
@@ -652,6 +655,7 @@ int ext4_init_orphan_info(struct super_block *sb)iput (inode);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_init_orphan_info);int ext4_orphan_file_empty (struct super_block *sb) {
@@ -667,3 +671,4 @@ int ext4_orphan_file_empty(struct super_block *sb)return 0 ;return 1 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_orphan_file_empty);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 13/27] ext4: add KUnit tests for fs/ext4/orphan.c
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ext4: unexported ext4_superblock_csum_set() breaks modular KUnit build --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ext4: unexported ext4_superblock_csum_set() breaks modular KUnit build
--
commit 7b2d7b8d20233b110a9621f769fa6154acdc1c4b
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/orphan.c
This commit adds a KUnit test suite for orphan inode tracking, orphan file management, and mount-time orphan recovery in fs/ext4/orphan-test.c, along with a static stub redirect in ext4_truncate() and test symbol exports.
Quoted 5 lines
fs/ext4/orphan-test.c new file +0
-0
[ ... ]
Quoted 2 lines
fs/ext4/orphan-test.c new file +2
-0+static int orphan_test_init (struct kunit *test) +{
[ ... ]
fs/ext4/orphan-test.c line 920
Quoted 8 lines
fs/ext4/orphan-test.c new file +8
-0+/* Keep sb_bh unmapped so ext4_commit_super() skips bh_submit I/O */ + ctx->sb_bh.b_data = (char *)&ctx->es; + ctx->sb_bh.b_size =sizeof (ctx->es); + ctx->sb_bh.b_bdev = &ctx->bdev; +atomic_set (&ctx->sb_bh.b_count,1 ); +set_buffer_uptodate (&ctx->sb_bh); + sbi->s_sbh = &ctx->sb_bh; +ext4_superblock_csum_set (sb);
[Severity: Medium]
Does calling ext4_superblock_csum_set() here break the build when CONFIG_EXT4_KUNIT_TESTS=m? orphan-test.o is linked into ext4-test.ko while ext4_superblock_csum_set() in fs/ext4/super.c is not exported with EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum_set) until a later commit in the series, commit "ext4: add KUnit tests for fs/ext4/super.c", causing modpost to fail with an undefined symbol error and breaking bisection.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Theodore Ts'o
maintainerPATCH 14/27 ext4: add KUnit tests for fs/ext4/block_validity.c
In reply to Theodore Ts'oAdd the ext4_block_validity_test KUnit test suite in fs/ext4/block_validity-test.c (16 test cases, 40 subtests total) to comprehensively exercise system-zone rbtree construction, RCU release, block range validation, reserved journal inode protection, and indirect block reference checking in fs/ext4/block_validity.c using an in-memory VFS superblock and mock block device without requiring a mounted disk:
- Bounds and 64-bit overflow checks (ext4_sb_block_valid and ext4_inode_block_valid) across 1KiB (s_first_data_block = 1) and 4KiB (s_first_data_block = 0) geometries, exact end-of-filesystem single and multi-block spans, 64-bit u64 addition wrap-around, >32-bit block counts under EXT4_FEATURE_INCOMPAT_64BIT, and high-32-bit masking when 64bit is cleared.
- System-zone lifecycle management (ext4_setup_system_zone and ext4_release_system_zone), covering pre-setup NULL behavior, RCU publication and teardown, and idempotent double-release handling.
- Multi-group sparse_super and flex_bg layouts (including groups with zero base metadata blocks and relocated bitmaps/inode tables) as well as DEBUG mount-option tree printing (debug_print_tree).
- System-zone rbtree merging (add_system_zone and can_merge) across left-neighbor merges, right-neighbor merges, 3-way bridge merges, and 64-bit (>2^32) group descriptor metadata zones, plus parameterized interval-overlap geometries (adjacent, single-block, boundary straddling, interior, exact, and enclosing spans).
- Corrupt overlapping group metadata detection (-EFSCORRUPTED) across block bitmap, inode bitmap, inode table, and cross-group collisions, verifying partial rbtree cleanup without publishing s_system_blks.
- Reserved journal inode protection (ext4_protect_reserved_inode), verifying non-block-aligned i_size rounding, multi-extent and sparse hole mapping, journal-inode ownership vs. regular/NULL inode rejection, can_merge() isolation between adjacent ino=0 and journal zones, disabled-feature/zero-inum/empty-inode skips, and -EINVAL, ext4_iget, ext4_map_blocks, and metadata-overlap (-EFSCORRUPTED + EXT4_ERROR_FS) failure paths.
- Block reference array validation (ext4_check_blockref, ext4_ind_check_inode, and ext4_check_indirect_blockref) across empty and sparse arrays, metadata and out-of-bounds corruption reporting, active journal inode (s_journal->j_inode) bypass, and integration with ext4_map_blocks() block validity checks.
Export the five runtime entry points in fs/ext4/block_validity.c with EXPORT_SYMBOL_FOR_EXT4_TEST for the ext4-test KUnit module.
--- fs/ext4/Makefile | 3 +- fs/ext4/block_validity-test.c | 1517 +++++++++++++++++++++++++++++++++ fs/ext4/block_validity.c | 6 + 3 files changed, 1525 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/block_validity-test.c
fs/ext4/Makefile +2 -1
@@ -19,7 +19,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ extents_status-test.o xattr-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ - balloc-test.o orphan-test.o + balloc-test.o orphan-test.o \ + block_validity-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/block_validity-test.c new file +1517 -0
1,517 lines not on this page · raw message
fs/ext4/block_validity.c +6 -0
@@ -17,6 +17,7 @@#include <linux/swap.h> #include <linux/pagemap.h> #include <linux/blkdev.h> +#include <linux/export.h> #include <linux/slab.h> #include "ext4.h"
@@ -269,6 +270,7 @@ int ext4_setup_system_zone(struct super_block *sb)kfree (system_blks);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_setup_system_zone);/* * Called when the filesystem is unmounted or when remounting it with
@@ -291,6 +293,7 @@ void ext4_release_system_zone(struct super_block *sb)if (system_blks)call_rcu (&system_blks->rcu, ext4_destroy_system_zone); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_release_system_zone);int ext4_sb_block_valid (struct super_block *sb,struct inode *inode,ext4_fsblk_t start_blk,unsigned int count)
@@ -334,6 +337,7 @@ int ext4_sb_block_valid(struct super_block *sb, struct inode *inode,rcu_read_unlock ();return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_sb_block_valid);/* * Returns 1 if the passed-in block region (start_blk,
@@ -345,6 +349,7 @@ int ext4_inode_block_valid(struct inode *inode, ext4_fsblk_t start_blk, {return ext4_sb_block_valid (inode->i_sb, inode, start_blk, count); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_inode_block_valid);int ext4_check_blockref (const char *function,unsigned int line,struct inode *inode,__le32 *p,unsigned int max)
@@ -367,4 +372,5 @@ int ext4_check_blockref(const char *function, unsigned int line, }return 0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_check_blockref);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 14/27] ext4: add KUnit tests for fs/ext4/block_validity.c
Sashiko has reviewed this patch and found no issues.
Quoted 17 lines
Add the
ext4_block_validity_testKUnit test suite infs/ext4/block_validity-test.c(16 test cases, 40 subtests total) to comprehensively exercise system-zone rbtree construction, RCU release, block range validation, reserved journal inode protection, and indirect block reference checking infs/ext4/block_validity.cusing an in-memory VFS superblock and mock block device without requiring a mounted disk:- Bounds and 64-bit overflow checks (
ext4_sb_block_validandext4_inode_block_valid) across 1KiB (s_first_data_block= 1) and 4KiB (s_first_data_block= 0) geometries, exact end-of-filesystem single and multi-block spans, 64-bit u64 addition wrap-around, >32-bit block counts underEXT4_FEATURE_INCOMPAT_64BIT, and high-32-bit masking when 64bit is cleared.
- System-zone lifecycle management (ext4_setup_system_zoneandext4_release_system_zone), covering pre-setup NULL behavior, RCU
[ ... ]
Quoted 4 lines
Export the five runtime entry points in
fs/ext4/block_validity.cwithEXPORT_SYMBOL_FOR_EXT4_TESTfor the ext4-test KUnit module.Signed-off-by Theodore Ts'o <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
Theodore Ts'o
maintainerPATCH 15/27 ext4: check multi-block overlap on left traversal in add_system_zone()
In reply to Theodore Ts'oWhen walking system_blks->root to insert [start_blk, start_blk + count), add_system_zone() takes the left branch whenever start_blk < entry->start_blk instead of checking that the entire range ends at or before entry->start_blk (unlike ext4_sb_block_valid(), which checks start_blk + count - 1 < entry->start_blk).
As a result, a corrupt multi-block metadata range (such as a group's inode table or a reserved journal inode extent mapped in ext4_protect_reserved_inode() before sbi->s_system_blks is published) that starts strictly before an existing system zone and extends into or across it traverses rb_left instead of returning -EFSCORRUPTED. This inserts overlapping intervals into system_blks->root and breaks the disjoint-interval invariant relied upon by ext4_sb_block_valid() (for example, a lookup on blocks past entry->start_blk + entry->count branches right and misses the overlapping zone stored in rb_left). A corrupt 64-bit start_blk whose start_blk + count wraps around u64 can similarly corrupt the rbtree ordering.
Reject zero-length or u64-wrapping ranges up front and require start_blk + count <= entry->start_blk before taking rb_left in add_system_zone(). Add KUnit regression tests in fs/ext4/block_validity-test.c covering group metadata and journal extents that partially overlap from the left, completely enclose an existing system zone, or wrap 64-bit block numbers.
--- fs/ext4/block_validity-test.c | 68 +++++++++++++++++++++++++++++++++++ fs/ext4/block_validity.c | 5 ++- 2 files changed, 72 insertions(+), 1 deletion(-)
fs/ext4/block_validity-test.c +68 -0
@@ -1111,6 +1111,27 @@ static const struct bv_corrupt_meta_case bv_corrupt_meta_cases[] = { .ibitmap = 2050, .itable = 2051, }, + { + .desc = "itable_starts_before_and_overlaps_bbitmap", + .grp = 0, + .bbitmap = 20, + .ibitmap = 40, + .itable = 15, + }, + { + .desc = "itable_starts_before_and_encloses_ibitmap", + .grp = 2, + .bbitmap = 50, + .ibitmap = 55, + .itable = 52, + }, + { + .desc = "itable_u64_wrap_around_overflow", + .grp = 2, + .bbitmap = 2049, + .ibitmap = 2050, + .itable = U64_MAX - 2ULL, + }, }; KUNIT_ARRAY_PARAM_DESC(bv_corrupt_meta, bv_corrupt_meta_cases, desc);
@@ -1314,6 +1335,52 @@ static void test_journal_inode_overlap_sets_fs_error(struct kunit *test)KUNIT_EXPECT_NULL (test,rcu_access_pointer (ctx->sbi.s_system_blks)); } +static void test_journal_extent_left_overlap_rejected (struct kunit *test) +{ +struct bv_test_ctx *ctx = test->priv; +struct inode *j_inode; + +/* +* Place group 2's block bitmap at block 20 (ino = 0) and map a +* multi-block journal extent at [18..21] that starts strictly before +* block 20 and extends across it. During ext4_setup_system_zone(), +* s_system_blks is still NULL when ext4_map_blocks() runs, so +* add_system_zone() must catch this left-traversal overlap. +*/ +bv_set_group_meta (ctx->sb, &ctx->gdps[2 ],20ULL ,2050ULL ,2051ULL ); +ext4_set_feature_journal (ctx->sb); + ctx->es.s_journal_inum =cpu_to_le32 (EXT4_JOURNAL_INO ); + + j_inode =bv_create_inode (test, ctx,EXT4_JOURNAL_INO , +S_IFREG |0600 , true); +i_size_write (j_inode,4 *BV_TEST_BLK_SIZE ); +bv_append_extent (test, j_inode,0 ,18ULL ,4 ); + +KUNIT_EXPECT_EQ (test,ext4_setup_system_zone (ctx->sb), -EFSCORRUPTED ); +KUNIT_EXPECT_TRUE (test, + (bool )(ctx->sbi.s_mount_state &EXT4_ERROR_FS )); +KUNIT_EXPECT_EQ (test,le32_to_cpu (ctx->es.s_last_error_ino), + (u32 )EXT4_JOURNAL_INO ); +KUNIT_EXPECT_EQ (test, ctx->es.s_last_error_errcode, +EXT4_ERR_EFSCORRUPTED ); +KUNIT_EXPECT_NULL (test,rcu_access_pointer (ctx->sbi.s_system_blks)); + +/* +* Also verify a journal extent [1020..1040] that completely encloses +* group 1's entire metadata zone [1025..1038]. +*/ +bv_clear_fs_error (ctx); +ext4_es_remove_extent (j_inode,0 ,EXT_MAX_BLOCKS ); +ext_inode_hdr (j_inode)->eh_entries =0 ; +i_size_write (j_inode,21 *BV_TEST_BLK_SIZE ); +bv_append_extent (test, j_inode,0 ,1020ULL ,21 ); + +KUNIT_EXPECT_EQ (test,ext4_setup_system_zone (ctx->sb), -EFSCORRUPTED ); +KUNIT_EXPECT_TRUE (test, + (bool )(ctx->sbi.s_mount_state &EXT4_ERROR_FS )); +KUNIT_EXPECT_NULL (test,rcu_access_pointer (ctx->sbi.s_system_blks)); +} +/* --- Test 10: ext4_check_blockref and Indirect Macros --- */ static void test_check_blockref_valid_and_sparse (struct kunit *test)
@@ -1498,6 +1565,7 @@ static struct kunit_case ext4_block_validity_test_cases[] = {KUNIT_CASE (test_journal_inode_iget_error),KUNIT_CASE (test_journal_inode_map_blocks_error),KUNIT_CASE (test_journal_inode_overlap_sets_fs_error), +KUNIT_CASE (test_journal_extent_left_overlap_rejected),KUNIT_CASE (test_check_blockref_valid_and_sparse),KUNIT_CASE (test_check_blockref_corrupt_entries_and_journal_bypass), KUNIT_CASE(test_ind_check_inode_and_indirect_blockref),
fs/ext4/block_validity.c +4 -1
@@ -75,10 +75,13 @@ static int add_system_zone(struct ext4_system_blocks *system_blks,struct rb_node **n = &system_blks->root.rb_node, *node;struct rb_node *parent =NULL , *new_node; +if (!count || (start_blk + count < start_blk)) +return -EFSCORRUPTED ; +while (*n) { parent = *n; entry = rb_entry(parent, struct ext4_system_zone, node); -if (start_blk < entry->start_blk) +if (start_blk + count <= entry->start_blk) n = &(*n)->rb_left;else if (start_blk >= (entry->start_blk + entry->count)) n = &(*n)->rb_right;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 15/27] ext4: check multi-block overlap on left traversal in add_system_zone()
Sashiko has reviewed this patch and found no issues.
Quoted 25 lines
When walking
system_blks->rootto insert [start_blk,start_blk+ count),add_system_zone()takes the left branch wheneverstart_blk<entry->start_blkinstead of checking that the entire range ends at or beforeentry->start_blk(unlikeext4_sb_block_valid(), which checksstart_blk+ count - 1 <entry->start_blk).As a result, a corrupt multi-block metadata range (such as a group's inode table or a reserved journal inode extent mapped in
ext4_protect_reserved_inode()beforesbi->s_system_blksis published) that starts strictly before an existing system zone and extends into or across it traversesrb_leftinstead of returning-EFSCORRUPTED. This inserts overlapping intervals intosystem_blks->rootand breaks the disjoint-interval invariant relied upon byext4_sb_block_valid()(for example, a lookup on blocks pastentry->start_blk+entry->countbranches right and misses the overlapping zone stored inrb_left). A corrupt 64-bitstart_blkwhosestart_blk+ count wraps around u64 can similarly corrupt the rbtree ordering.Reject zero-length or u64-wrapping ranges up front and require
start_blk+ count <=entry->start_blkbefore takingrb_leftinadd_system_zone(). Add KUnit regression tests infs/ext4/block_validity-test.ccovering group metadata and journal extents that partially overlap from the left, completely enclose an existing system zone, or wrap 64-bit block numbers.
Quoted 2 lines
Fixes bf9a379d0980 ("ext4: don't allow overlapping system zones")Signed-off-by Theodore Ts'o <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
Theodore Ts'o
maintainerPATCH 16/27 ext4: enable full feature coverage in fs/ext4/.kunitconfig
In reply to Theodore Ts'oEnable CONFIG_EXT4_FS_POSIX_ACL, CONFIG_EXT4_FS_SECURITY, CONFIG_FS_VERITY, CONFIG_FS_ENCRYPTION, CONFIG_QUOTA, CONFIG_QFMT_V2, and CONFIG_UNICODE in fs/ext4/.kunitconfig so conditional ext4 source files and feature-gated code paths (POSIX ACLs, security xattrs, fs-verity, fscrypt, quota accounting, and UTF-8 casefolding) are compiled and exercised during KUnit runs.
Fix mock superblock and test setup bugs in existing KUnit suites exposed by enabling these Kconfig options:
- Provide .get_dquots callbacks in mock super_operations under CONFIG_QUOTA in block_validity-test.c, extents-test.c, fast_commit-test.c, inline-test.c, inode-test.c, mballoc-test.c, namei-test.c, and xattr-test.c so dquot_drop() does not dereference a NULL callback during ext4_clear_inode().
- Populate sb->s_cop = &ext4_cryptops under CONFIG_FS_ENCRYPTION in balloc-test.c, extents-test.c, fast_commit-test.c, inline-test.c, inode-test.c, mballoc-test.c, and xattr-test.c so fscrypt_put_encryption_info() can resolve inode_info_offs safely on eviction.
- Fix test_namei_casefold_lookup_and_strict() under CONFIG_UNICODE in namei-test.c to use SB_ENC_STRICT_MODE_FL (instead of undeclared SB_STRICT_ENCODING) and propagate EXT4_INODE_CASEFOLD to S_CASEFOLD on the VFS directory inode via ext4_set_inode_flags().
--- fs/ext4/.kunitconfig | 7 +++++++ fs/ext4/balloc-test.c | 3 +++ fs/ext4/block_validity-test.c | 10 ++++++++++ fs/ext4/extents-test.c | 16 ++++++++++++++-- fs/ext4/fast_commit-test.c | 16 ++++++++++++++-- fs/ext4/inline-test.c | 16 +++++++++++++++- fs/ext4/inode-test.c | 27 +++++++++++++++++++-------- fs/ext4/mballoc-test.c | 13 +++++++++++++ fs/ext4/namei-test.c | 18 ++++++++++++++---- fs/ext4/xattr-test.c | 16 ++++++++++++++-- 10 files changed, 123 insertions(+), 19 deletions(-)
fs/ext4/.kunitconfig +7 -0
@@ -1,3 +1,10 @@ CONFIG_KUNIT=y CONFIG_EXT4_FS=y +CONFIG_EXT4_FS_POSIX_ACL=y +CONFIG_EXT4_FS_SECURITY=y CONFIG_EXT4_KUNIT_TESTS=y +CONFIG_FS_VERITY=y +CONFIG_FS_ENCRYPTION=y +CONFIG_QUOTA=y +CONFIG_QFMT_V2=y +CONFIG_UNICODE=y
fs/ext4/balloc-test.c +3 -0
@@ -516,6 +516,9 @@ static int balloc_test_init(struct kunit *test) sb->s_op = &balloc_test_sops;#ifdef CONFIG_QUOTA sb->dq_op = &balloc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops;#endif sb->s_flags |=SB_ACTIVE ; sb->s_blocksize =BALLOC_TEST_BLK_SIZE ;
fs/ext4/block_validity-test.c +10 -0
@@ -228,12 +228,22 @@ static void bv_test_free_inode_mem(struct inode *inode)kfree (EXT4_I (inode)); } +#ifdef CONFIG_QUOTA +static struct dquot __rcu **bv_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +#endif +static const struct super_operations bv_test_sops = { .alloc_inode = bv_test_alloc_inode, .evict_inode = bv_test_evict_inode, .destroy_inode = bv_test_destroy_inode, .free_inode = bv_test_free_inode_mem, .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = bv_test_get_dquots, +#endif };static int bv_test_init_fs_context (struct fs_context *fc)
fs/ext4/extents-test.c +14 -2
@@ -153,9 +153,12 @@ static unsigned long ext_dummy_shrinker_scan(struct shrinker *shrink,return SHRINK_STOP ; } -static const struct super_operations ext_dummy_sops = {}; -#ifdef CONFIG_QUOTA +static struct dquot __rcu **ext_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +static qsize_t *ext_get_reserved_space (struct inode *inode) {return &EXT4_I (inode)->i_reserved_quota;
@@ -166,6 +169,12 @@ static const struct dquot_operations ext_dummy_qops = { };#endif +static const struct super_operations ext_dummy_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = ext_get_dquots, +#endif +}; +static int ext_init_fs_context (struct fs_context *fc) {return 0 ;
@@ -461,6 +470,9 @@ static int extents_kunit_init(struct kunit *test) sb->s_op = &ext_dummy_sops;#ifdef CONFIG_QUOTA sb->dq_op = &ext_dummy_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops;#endif sb->s_blocksize =4096 ; sb->s_blocksize_bits =12 ;
fs/ext4/fast_commit-test.c +14 -2
@@ -134,9 +134,12 @@ struct fc_test_ctx {int custom_es_ret; }; -static const struct super_operations fc_test_sops = {}; -#ifdef CONFIG_QUOTA +static struct dquot __rcu **fc_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +static qsize_t *fc_test_get_reserved_space (struct inode *inode) {return &EXT4_I (inode)->i_reserved_quota;
@@ -147,6 +150,12 @@ static const struct dquot_operations fc_test_qops = { };#endif +static const struct super_operations fc_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = fc_test_get_dquots, +#endif +}; +static unsigned long fc_dummy_shrinker_count (struct shrinker *shrink,struct shrink_control *sc) {
@@ -867,6 +876,9 @@ static int fast_commit_test_init(struct kunit *test) sb->s_op = &fc_test_sops;#ifdef CONFIG_QUOTA sb->dq_op = &fc_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops;#endif strscpy (sb->s_id,"ext4-fc-test" ,sizeof (sb->s_id));
fs/ext4/inline-test.c +15 -1
@@ -66,7 +66,18 @@ struct inline_test_ctx {static struct inline_test_ctx *t_ctx; -static const struct super_operations inline_test_sops = {}; +#ifdef CONFIG_QUOTA +static struct dquot __rcu **inline_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +#endif + +static const struct super_operations inline_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = inline_test_get_dquots, +#endif +};static bool test_release_folio (struct folio *folio,gfp_t wait) {
@@ -265,6 +276,9 @@ static int inline_test_init(struct kunit *test) ctx->sb.s_bdi = &noop_backing_dev_info; ctx->sb.s_fs_info = &ctx->sbi; ctx->sb.s_op = &inline_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + ctx->sb.s_cop = &ext4_cryptops; +#endif snprintf (ctx->sb.s_id,sizeof (ctx->sb.s_id),"ext4-inline-test" );init_rwsem (&ctx->sb.s_umount);
fs/ext4/inode-test.c +19 -8
@@ -462,15 +462,12 @@ static void inode_test_free_inode(struct inode *inode)kfree (EXT4_I (inode)); } -static const struct super_operations inode_test_sops = { - .alloc_inode = inode_test_alloc_inode, - .evict_inode = ext4_evict_inode, - .destroy_inode = inode_test_destroy_inode, - .free_inode = inode_test_free_inode, - .drop_inode = inode_just_drop, -}; -#ifdef CONFIG_QUOTA +static struct dquot __rcu **inode_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +static qsize_t *inode_test_get_reserved_space (struct inode *inode) {return &EXT4_I (inode)->i_reserved_quota;
@@ -481,6 +478,17 @@ static const struct dquot_operations inode_test_qops = { };#endif +static const struct super_operations inode_test_sops = { + .alloc_inode = inode_test_alloc_inode, + .evict_inode = ext4_evict_inode, + .destroy_inode = inode_test_destroy_inode, + .free_inode = inode_test_free_inode, + .drop_inode = inode_just_drop, +#ifdef CONFIG_QUOTA + .get_dquots = inode_test_get_dquots, +#endif +}; +static int inode_test_init_fs_context (struct fs_context *fc) {return 0 ;
@@ -950,6 +958,9 @@ static struct inode_test_ctx *inode_test_setup(struct kunit *test) sb->s_op = &inode_test_sops;#ifdef CONFIG_QUOTA sb->dq_op = &inode_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops;#endif sb->s_flags |=SB_ACTIVE ; sb->s_blocksize =INODE_TEST_BLK_SIZE ;
fs/ext4/mballoc-test.c +13 -0
@@ -54,9 +54,19 @@ static void mbt_free_inode(struct inode *inode)kfree (EXT4_I (inode)); } +#ifdef CONFIG_QUOTA +static struct dquot __rcu **mbt_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +#endif +static const struct super_operations mbt_sops = { .alloc_inode = mbt_alloc_inode, .free_inode = mbt_free_inode, +#ifdef CONFIG_QUOTA + .get_dquots = mbt_get_dquots, +#endif };static int mbt_init_fs_context (struct fs_context *fc)
@@ -93,6 +103,9 @@ static int mbt_mb_init(struct super_block *sb)*/ INIT_LIST_HEAD (&sb->s_inodes); sb->s_op = &mbt_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif ret =ext4_mb_init (sb);if (ret !=0 )
fs/ext4/namei-test.c +14 -4
@@ -84,9 +84,12 @@ struct namei_test_ctx {unsigned int mark_inode_dirty_calls; }; -static const struct super_operations namei_test_sops = {}; -#ifdef CONFIG_QUOTA +static struct dquot __rcu **namei_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +static qsize_t *namei_test_get_reserved_space (struct inode *inode) {return &EXT4_I (inode)->i_reserved_quota;
@@ -97,6 +100,12 @@ static const struct dquot_operations namei_test_qops = { };#endif +static const struct super_operations namei_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = namei_test_get_dquots, +#endif +}; +static void init_mock_inode_slot (struct namei_test_ctx *ctx,struct mock_inode_slot *slot,unsigned long ino,umode_t mode)
@@ -2245,6 +2254,7 @@ static void test_namei_casefold_lookup_and_strict(struct kunit *test) ctx->es.s_feature_incompat |=cpu_to_le32 (EXT4_FEATURE_INCOMPAT_CASEFOLD );ext4_set_inode_flag (dir,EXT4_INODE_CASEFOLD ); +ext4_set_inode_flags (dir, true);KUNIT_ASSERT_EQ (test,ext4_init_new_dir (NULL , root_dir, dir),0 );init_mock_dentry (&parent_dentry,NULL ,"cfdir" , dir, &ctx->sb);
@@ -2261,8 +2271,8 @@ static void test_namei_casefold_lookup_and_strict(struct kunit *test)KUNIT_EXPECT_EQ (test,le32_to_cpu (de->inode),TEST_FILE1_INO );brelse (bh); -/* Enable SB_STRICT_ENCODING -> invalid UTF-8 sequence is rejected */ - ctx->sb.s_encoding_flags |=SB_STRICT_ENCODING ; +/* Enable SB_ENC_STRICT_MODE_FL -> invalid UTF-8 sequence is rejected */ + ctx->sb.s_encoding_flags |=SB_ENC_STRICT_MODE_FL ; add_dentry.__d_name = bad_utf8; KUNIT_EXPECT_EQ(test, ext4_add_entry_test(NULL, &add_dentry, file1),
fs/ext4/xattr-test.c +14 -2
@@ -79,9 +79,12 @@ struct xattr_test_ctx {unsigned int dirty_metadata_calls; }; -static const struct super_operations xattr_test_sops = {}; -#ifdef CONFIG_QUOTA +static struct dquot __rcu **xattr_test_get_dquots (struct inode *inode) +{ +return EXT4_I (inode)->i_dquot; +} +static qsize_t *xattr_test_get_reserved_space (struct inode *inode) {return &EXT4_I (inode)->i_reserved_quota;
@@ -92,6 +95,12 @@ static const struct dquot_operations xattr_test_qops = { };#endif +static const struct super_operations xattr_test_sops = { +#ifdef CONFIG_QUOTA + .get_dquots = xattr_test_get_dquots, +#endif +}; +static void init_mock_inode_slot (struct xattr_test_ctx *ctx,struct mock_inode_slot *slot,unsigned long ino)
@@ -476,6 +485,9 @@ static int xattr_test_init(struct kunit *test) sb->s_op = &xattr_test_sops;#ifdef CONFIG_QUOTA sb->dq_op = &xattr_test_qops; +#endif +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops;#endif sb->s_blocksize =TEST_BLK_SIZE ; sb->s_blocksize_bits =TEST_BLK_BITS ;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 16/27] ext4: enable full feature coverage in fs/ext4/.kunitconfig
Sashiko has reviewed this patch and found no issues.
Quoted 25 lines
Enable
CONFIG_EXT4_FS_POSIX_ACL,CONFIG_EXT4_FS_SECURITY,CONFIG_FS_VERITY,CONFIG_FS_ENCRYPTION,CONFIG_QUOTA,CONFIG_QFMT_V2, andCONFIG_UNICODEinfs/ext4/.kunitconfigso conditional ext4 source files and feature-gated code paths (POSIX ACLs, security xattrs, fs-verity, fscrypt, quota accounting, and UTF-8 casefolding) are compiled and exercised during KUnit runs.Fix mock superblock and test setup bugs in existing KUnit suites exposed by enabling these
Kconfigoptions:- Provide .get_dquots callbacks in mock
super_operationsunderCONFIG_QUOTAinblock_validity-test.c,extents-test.c,fast_commit-test.c,inline-test.c,inode-test.c,mballoc-test.c,namei-test.c, andxattr-test.csodquot_drop()does not dereference a NULL callback duringext4_clear_inode().
- Populatesb->s_cop=&ext4_cryptopsunderCONFIG_FS_ENCRYPTIONinballoc-test.c,extents-test.c,fast_commit-test.c,inline-test.c,inode-test.c,mballoc-test.c, andxattr-test.csofscrypt_put_encryption_info()can resolveinode_info_offssafely on eviction.
- Fixtest_namei_casefold_lookup_and_strict()underCONFIG_UNICODEinnamei-test.cto useSB_ENC_STRICT_MODE_FL(instead of undeclaredSB_STRICT_ENCODING) and propagateEXT4_INODE_CASEFOLDtoS_CASEFOLDon the VFS directory inode viaext4_set_inode_flags().
Quoted 1 line
Signed-off-by Theodore Ts'o <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Theodore Ts'o
maintainerPATCH 17/27 ext4: add KUnit tests for fs/ext4/super.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_super_test) covering superblock validation, geometry checks, metadata checksums, mount options, overhead/statfs accounting, and persistent error recording in fs/ext4/super.c:
- Feature flag compatibility in ext4_feature_set_ok() and ext4_check_feature_compatibility() across RW/RO mounts, bigalloc constraints, Hurd creator-OS restrictions, DAX, and encryption levels.
- Inode, block-group, cluster-size, and directory hash initialization in ext4_inode_info_init(), ext4_block_group_meta_init(), ext4_handle_clustersize(), and ext4_hash_info_init().
- Filesystem geometry validation in ext4_check_geometry(), descriptor location arithmetic in descriptor_loc() (linear and meta_bg), superblock and group descriptor CRC16/CRC32C verification, descriptor overlap checks in ext4_check_descriptors(), and flex_bg counter aggregation in ext4_fill_flex_info() / ext4_alloc_flex_bg_array().
- Maximum file size helpers ext4_max_size() / ext4_max_bitmap_size(), stripe selection in ext4_get_stripe_size(), reserved cluster defaults in ext4_set_resv_clusters(), overhead calculation in count_overhead() and ext4_calculate_overhead(), and space reporting in ext4_statfs().
- Mount option defaults, parsing, consistency checks, remount guards, on-disk s_mount_opts parsing, and _ext4_show_options() formatting.
- Error translation, first/last error persistence in save_error_info(), and superblock state flushing in ext4_update_super().
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 45 ++ fs/ext4/super-test.c | 1341 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/super.c | 222 +++++++ 4 files changed, 1609 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/super-test.c
fs/ext4/Makefile +1 -1
@@ -20,7 +20,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ - block_validity-test.o + block_validity-test.o super-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +45 -0
51 lines not on this page · raw message
fs/ext4/super-test.c new file +1341 -0
1,341 lines not on this page · raw message
fs/ext4/super.c +222 -0
274 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 17/27] ext4: add KUnit tests for fs/ext4/super.c
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] ext4: duplicate test symbol exports in super.c and mballoc.c break modpost --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] ext4: duplicate test symbol exports in super.c and mballoc.c break modpost
--
commit bd8448103700f2d8698fe8da1a5ea9c5b818c8f5
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/super.c
This commit adds a KUnit test suite (ext4_super_test) for superblock validation, geometry checks, metadata checksums, mount options, overhead and statfs accounting, and error recording in fs/ext4/super.c, along with test helper wrappers and symbol exports.
Quoted 4 lines
fs/ext4/super.c +0
-0
[ ... ]
Quoted 9 lines
fs/ext4/super.c +1
-0@@ -379,6 +381,7 @@ __u32 ext4_free_group_clusters(struct super_block *sb, (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ? (__u32 )le16_to_cpu (bg->bg_free_blocks_count_hi) <<16 :0 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_group_clusters);__u32 ext4_free_inodes_count (struct super_block *sb,struct ext4_group_desc *bg)
fs/ext4/super.c void ext4_free_group_clusters_set(struct super_block *sb, · line 450
Quoted 7 lines
fs/ext4/super.c +1
-0@@ -441,6 +444,7 @@ void ext4_free_group_clusters_set(struct super_block *sb,if (EXT4_DESC_SIZE (sb) >=EXT4_MIN_DESC_SIZE_64BIT ) bg->bg_free_blocks_count_hi =cpu_to_le16 (count >>16 ); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_free_group_clusters_set);void ext4_free_inodes_set (struct super_block *sb,struct ext4_group_desc *bg,__u32 count)
[Severity: High]
Does exporting ext4_free_group_clusters and ext4_free_group_clusters_set here duplicate the existing exports in fs/ext4/mballoc.c?
fs/ext4/mballoc.c:
...
EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters);
EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_free_group_clusters_set);
...Because super.o and mballoc.o are linked into the same module or vmlinux, builds with CONFIG_MODULES=y and CONFIG_EXT4_KUNIT_TESTS enabled fail in modpost with "symbol ... exported twice".
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
Theodore Ts'o
maintainerPATCH 18/27 ext4: add KUnit tests for fs/ext4/sysfs.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_sysfs_test) covering ext4 sysfs attribute show/store handlers, feature capability attributes, and sysfs/procfs registration in fs/ext4/sysfs.c:
- Generic pointer attributes across sbi, superblock, and explicit targets (attr_pointer_ui, attr_pointer_ul, attr_pointer_pi negative value rejection, attr_pointer_u8, attr_pointer_u64 LE64 decoding, attr_pointer_string 32-byte bounding, and attr_pointer_atomic).
- Range-checked read-write attributes: inode_readahead_blks power-of-2 and upper-bound enforcement, reserved_clusters bounds against total clusters, mb_best_avail_max_trim_order <= 64, mb_group_prealloc <= s_clusters_per_group, and err_report_sec <= 1 year.
- Computed read-only attributes: delayed_allocation_blocks cluster-to- block scaling, session_write_kbytes and lifetime_write_kbytes sector accounting, sra_exceeded_retry_limit percpu summation, 40-bit error timestamps (first_error_time / last_error_time), and journal_task.
- Feature capability attributes under /sys/fs/ext4/features, error injection via trigger_fs_error, and lifecycle coverage of ext4_register_sysfs(), ext4_notify_error_sysfs(), and ext4_unregister_sysfs().
--- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 8 + fs/ext4/sysfs-test.c | 653 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/sysfs.c | 55 ++++ 4 files changed, 718 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/sysfs-test.c
fs/ext4/Makefile +2 -1
@@ -20,7 +20,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ namei-test.o inline-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ - block_validity-test.o super-test.o + block_validity-test.o super-test.o \ + sysfs-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +8 -0
@@ -4008,6 +4008,14 @@ extern int ext4_register_sysfs(struct super_block *sb);extern void ext4_unregister_sysfs (struct super_block *sb);extern int __init ext4_init_sysfs (void );extern void ext4_exit_sysfs (void ); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern ssize_t ext4_sysfs_attr_show_test (struct ext4_sb_info *sbi, +const char *name,char *buf); +extern ssize_t ext4_sysfs_attr_store_test (struct ext4_sb_info *sbi, +const char *name,const char *buf, +size_t len); +extern ssize_t ext4_sysfs_feat_show_test (const char *name,char *buf); +#endif /* block_validity */ extern void ext4_release_system_zone (struct super_block *sb);
fs/ext4/sysfs-test.c new file +653 -0
653 lines not on this page · raw message
fs/ext4/sysfs.c +55 -0
76 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 18/27] ext4: add KUnit tests for fs/ext4/sysfs.c
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] ext4: UAF of ctx->sb in fserror_worker() due to NULL sb->s_root in sysfs-test.c - [Low] ext4…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] ext4: UAF of ctx->sb in fserror_worker() due to NULL sb->s_root in sysfs-test.c
- [Low] ext4: preemptible part_stat_add() call in test_computed_ro_and_error_time_attrs()
- [Low] ext4: s_last_error_func check fails under !CONFIG_PRINTK in sysfs-test.c
- [Low] ext4: sysfs_test_cleanup() frees ctx->sb before canceling work and timer
--
commit f2e9ba8068c01ef9b7c5be16e187d6640c8a57c0
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/sysfs.c
This commit adds a KUnit test suite covering ext4 sysfs attribute show and store handlers, feature capability attributes, and sysfs/procfs registration.
Quoted 6 lines
fs/ext4/sysfs-test.c new file +0
-0@@ -0,0 +1,653 @@
[ ... ]
fs/ext4/sysfs-test.c line 139
Quoted 9 lines
fs/ext4/sysfs-test.c new file +9
-0+static void sysfs_test_cleanup (struct sysfs_test_ctx *ctx) +{ + ctx->sbi.s_journal =NULL ; + +deactivate_super (ctx->sb); +rcu_barrier (); + +cancel_work_sync (&ctx->sbi.s_sb_upd_work); +timer_delete_sync (&ctx->sbi.s_err_report);
[Severity: Low]
Should cancel_work_sync() and timer_delete_sync() run before deactivate_super(ctx->sb)?
Writing a non-zero value to err_report_sec in test_validated_rw_attrs() replaces sbi->s_err_report's callback with print_daily_error_info() and arms the timer, and print_daily_error_info() dereferences sbi->s_sb (ctx->sb). Stopping the work item and timer before deactivating and RCU-freeing ctx->sb ensures neither callback can access ctx->sb after it is freed.
[ ... ]
fs/ext4/sysfs-test.c line 208
Quoted 10 lines
fs/ext4/sysfs-test.c new file +10
-0+ sbi->s_sb = sb; + sb->s_fs_info = sbi; + sb->s_op = &sysfs_test_sops; +#ifdef CONFIG_FS_ENCRYPTION + sb->s_cop = &ext4_cryptops; +#endif + sb->s_flags |=SB_ACTIVE ; + sb->s_blocksize =SYSFS_TEST_BLK_SIZE ; + sb->s_blocksize_bits =SYSFS_TEST_BLK_BITS ; +strscpy (sb->s_id,"ext4_sysfs_kunit" ,sizeof (sb->s_id));
[Severity: Medium]
Can leaving sb->s_root NULL while setting SB_ACTIVE cause a use-after-free of ctx->sb in fserror_worker()?
In test_feature_attrs_and_trigger_error(), writing to trigger_fs_error calls trigger_test_error() -> ext4_error() -> __ext4_error() -> fserror_report_metadata(). Because alloc_super() initialized sb->s_pending_errors to 1 and SB_ACTIVE is set, fserror_report_metadata() queues an asynchronous fserror_worker work item holding a raw pointer to ctx->sb. However, generic_shutdown_super() only clears SB_ACTIVE and calls fserror_unmount(sb) to drain pending events when sb->s_root is non-NULL:
CPU0 kworkertest_feature_attrs_and_trigger_error()
...
fserror_report_metadata(sb, ...)
schedule_work(&event->work)
sysfs_test_cleanup()
deactivate_super(ctx->sb)
kill_anon_super()
generic_shutdown_super()
/* sb->s_root is NULL:
* skips fserror_unmount(sb)
*/
put_super(sb)
rcu_barrier()
/* destroy_super_work() frees sb */
fserror_worker()
sb = event->sb;
if (!(sb->s_flags & SB_ACTIVE))
<-- use-after-freeInitializing sb->s_root with d_make_root() (or calling fserror_unmount(ctx->sb) before deactivating the superblock) would ensure pending fserror events are drained before ctx->sb is freed.
[ ... ]
Quoted 13 lines
fs/ext4/sysfs-test.c new file +13
-0+static void test_computed_ro_and_error_time_attrs (struct kunit *test) +{ +struct sysfs_test_ctx *ctx = test->priv; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ext4_super_block *es = &ctx->es; +char expected_pid[32 ]; +char *buf; + + buf =kunit_kzalloc (test,PAGE_SIZE ,GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, buf); + +/* 7 dirty clusters * 4 blocks/cluster == 28 delayed allocation blks */ +percpu_counter_set (&sbi->s_dirtyclusters_counter,7 );
fs/ext4/sysfs-test.c line 502
Quoted 10 lines
fs/ext4/sysfs-test.c new file +10
-0+KUNIT_EXPECT_GT (test, +ext4_sysfs_attr_show_test (sbi, +"delayed_allocation_blocks" , buf), + (ssize_t )0 ); +KUNIT_EXPECT_STREQ (test, buf,"28\n" ); + +/* (50 - 10) sectors >> 1 == 20 KB session, + 100 == 120 KB lifetime */ + sbi->s_sectors_written_start =10 ; + sbi->s_kbytes_written =100 ; +part_stat_add (&ctx->bdev, sectors[STAT_WRITE ],50 );
[Severity: Low]
Does calling part_stat_add() here without part_stat_lock() / part_stat_unlock() trigger a CONFIG_DEBUG_PREEMPT warning?
part_stat_add() uses __this_cpu_add(), which requires preemption to be disabled and logs a "BUG: using __this_cpu_add() in preemptible" warning when called in a preemptible KUnit thread with CONFIG_DEBUG_PREEMPT enabled.
[ ... ]
fs/ext4/sysfs-test.c line 616
Quoted 9 lines
fs/ext4/sysfs-test.c new file +9
-0+/* Non-empty message records error state via ext4_error() */ +KUNIT_EXPECT_EQ (test, +ext4_sysfs_attr_store_test (sbi,"trigger_fs_error" , +"kunit injected\n" ,15 ), + (ssize_t )15 ); +KUNIT_EXPECT_NE (test, sbi->s_mount_state &EXT4_ERROR_FS ,0 ); +KUNIT_EXPECT_STREQ (test, sbi->s_last_error_func,"trigger_test_error" ); + sbi->s_journal =NULL ; +}
[Severity: Low]
Will the sbi->s_last_error_func assertion fail when CONFIG_PRINTK is disabled?
In fs/ext4/ext4.h, the !CONFIG_PRINTK definition of ext4_error() passes "" instead of __func__ to __ext4_error(), so sbi->s_last_error_func is set to "" rather than "trigger_test_error".
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
Theodore Ts'o
maintainerPATCH 19/27 ext4: add KUnit tests for fs/ext4/ioctl.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_ioctl_test) covering superblock online tuning, backup superblock propagation, inode data swapping, fileattr validation, forced shutdown, and ioctl dispatch in fs/ext4/ioctl.c:
- Superblock modification callbacks (ext4_sb_setlabel, ext4_sb_setuuid, and ext4_sb_setparams across error behavior, mount counts, 64-bit reserved blocks, 32-bit split reserved uid/gid, hash/RAID/encoding fields, mount_opts, DIR_INDEX / CSUM_SEED feature edits, and FORCE_FSCK).
- Parameter validation and normalization in ext4_validate_tune_sb_params (-E2BIG mount_opts, -EOPNOTSUPP flags/feature clears, reserved_blocks and hash algorithm bounds, DIR_INDEX hash seed initialization, and CASEFOLD encoding defaults).
- Primary and sparse_super backup superblock updates via ext4_update_backup_sb, ext4_update_superblocks_fn (including EXT4_FLAGS_RESIZING contention and unjournaled >2 backup updates), and ext4_update_overhead skip/force semantics.
- Inode swap rollback invariants in swap_inode_data (swapped vs preserved flags, extent status cache clearing, double-swap round-trip) and metadata_csum seed recalculation in ext4_reset_inode_seed.
- Immutable enforcement, DAX mutual-exclusion rules (including inline directories and verity-in-progress), and end-to-end ext4_fileattr_get / ext4_fileattr_set flag masking and VFS flag synchronization.
- Forced shutdown state transitions (ext4_force_shutdown) and ext4_ioctl / ext4_compat_ioctl dispatch checks.
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 33 ++ fs/ext4/ioctl-test.c | 1169 ++++++++++++++++++++++++++++++++++++++++++ fs/ext4/ioctl.c | 249 ++++++--- 4 files changed, 1382 insertions(+), 71 deletions(-) create mode 100644 fs/ext4/ioctl-test.c
fs/ext4/Makefile +1 -1
@@ -21,7 +21,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ - sysfs-test.o + sysfs-test.o ioctl-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +33 -0
@@ -3337,6 +3337,39 @@ int ext4_fileattr_get(struct dentry *dentry, struct file_kattr *fa);extern void ext4_reset_inode_seed (struct inode *inode);int ext4_update_overhead (struct super_block *sb,bool force);int ext4_force_shutdown (struct super_block *sb,u32 flags); +int ext4_ioctl_sync_bh (struct buffer_head *bh); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +struct ext4_tune_sb_params ; +void ext4_sb_setlabel_test (struct ext4_sb_info *sbi, +struct ext4_super_block *es,const void *arg); +void ext4_sb_setuuid_test (struct ext4_sb_info *sbi, +struct ext4_super_block *es,const void *arg); +void ext4_sb_setparams_test (struct ext4_sb_info *sbi, +struct ext4_super_block *es,const void *arg); +int ext4_validate_tune_sb_params_test (struct super_block *sb, +struct ext4_tune_sb_params *params); +int ext4_update_primary_sb_test (struct super_block *sb,handle_t *handle, +void (*func)(struct ext4_sb_info *, +struct ext4_super_block *, +const void *), +const void *arg); +int ext4_update_backup_sb_test (struct super_block *sb,handle_t *handle, +ext4_group_t grp, +void (*func)(struct ext4_sb_info *, +struct ext4_super_block *, +const void *), +const void *arg); +int ext4_update_superblocks_fn_test (struct super_block *sb, +void (*func)(struct ext4_sb_info *, +struct ext4_super_block *, +const void *), +const void *arg); +void ext4_swap_inode_data_test (struct inode *inode1,struct inode *inode2); +int ext4_ioctl_check_immutable_test (struct inode *inode,__u32 new_projid, +unsigned int flags); +bool ext4_dax_compatible_test (struct inode *inode,unsigned int oldflags, +unsigned int flags); +#endif /* migrate.c */ extern int ext4_ext_migrate (struct inode *);
fs/ext4/ioctl-test.c new file +1169 -0
1,169 lines not on this page · raw message
fs/ext4/ioctl.c +179 -70
376 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 19/27] ext4: add KUnit tests for fs/ext4/ioctl.c
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] ext4: uninitialized s_es_stats counters dereferenced in ioctl_test_init() - [Low] ext4…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] ext4: uninitialized s_es_stats counters dereferenced in ioctl_test_init()
- [Low] ext4: uninitialized work and timer cleanup in ioctl_test_init() error paths
- [Low] ext4: NULL bh->b_bdev in ioctl_init_mock_bh() dereferenced by tracepoint
- [Low] ext4: leaked inodes and dentries on KUNIT_ASSERT_NOT_NULL() abort in ioctl-test
It also noticed 2 related pre-existing issues this patch does not introduce:
- [High] ext4: missing s_encoding initialization in ext4_ioctl_set_tune_sb() [1]
- [High] ext4: torn read of i_version in swap_inode_data() [2] --
commit e7c759c842d0abec3f3d75ab9a035c69eb297d76
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/ioctl.c
This commit adds a KUnit test suite for superblock online tuning, backup superblock updates, inode data swapping, fileattr handling, forced shutdown, and ioctl dispatch in fs/ext4/ioctl.c, exporting helper wrappers for testing.
Quoted 5 lines
fs/ext4/ioctl-test.c new file +0
-0
[ ... ]
fs/ext4/ioctl-test.c line 233
Quoted 11 lines
fs/ext4/ioctl-test.c new file +11
-0+static void ioctl_init_mock_bh (struct buffer_head *bh,struct folio *folio, +u8 *data,size_t size,sector_t blocknr) +{ +memset (bh,0 ,sizeof (*bh)); + bh->b_folio = folio; + bh->b_data = (char *)data; + bh->b_size = size; + bh->b_blocknr = blocknr; +atomic_set (&bh->b_count,2 ); +set_buffer_uptodate (bh); +}
[Severity: Low]
Can leaving bh->b_bdev NULL here cause a NULL pointer dereference when the block_dirty_buffer tracepoint is enabled?
test_update_superblocks_and_overhead() marks these mock buffer_heads dirty via ext4_update_primary_sb() and ext4_update_backup_sb() -> mark_buffer_dirty(), which calls trace_block_dirty_buffer(bh) and dereferences bh->b_bdev->bd_dev.
[ ... ]
Quoted 11 lines
fs/ext4/ioctl-test.c new file +11
-0+static void ioctl_test_cleanup (struct ioctl_test_ctx *ctx) +{ + active_ioctl_test =NULL ; + +if (ctx->sb) { +deactivate_super (ctx->sb); +rcu_barrier (); + } + +cancel_work_sync (&ctx->sbi.s_sb_upd_work); +timer_delete_sync (&ctx->sbi.s_err_report);
[ ... ]
Quoted 2 lines
fs/ext4/ioctl-test.c new file +2
-0+static int ioctl_test_init (struct kunit *test) +{
[ ... ]
Quoted 4 lines
fs/ext4/ioctl-test.c new file +4
-0+ ctx =kzalloc_obj (*ctx); +KUNIT_ASSERT_NOT_NULL (test, ctx); + test->priv = ctx; + active_ioctl_test = test;
[ ... ]
Quoted 15 lines
fs/ext4/ioctl-test.c new file +15
-0+ err =percpu_counter_init (&sbi->s_freeclusters_counter,0 ,GFP_KERNEL ); +if (err) { +up_write (&sb->s_umount); +ioctl_test_cleanup (ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + } + err =percpu_counter_init (&sbi->s_dirtyclusters_counter,0 ,GFP_KERNEL ); +if (err) { +percpu_counter_destroy (&sbi->s_freeclusters_counter); +up_write (&sb->s_umount); +ioctl_test_cleanup (ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + } + err =percpu_counter_init (&sbi->s_freeinodes_counter,0 ,GFP_KERNEL ); +if (err) {
fs/ext4/ioctl-test.c line 351
Quoted 10 lines
fs/ext4/ioctl-test.c new file +10
-0+percpu_counter_destroy (&sbi->s_dirtyclusters_counter); +percpu_counter_destroy (&sbi->s_freeclusters_counter); +up_write (&sb->s_umount); +ioctl_test_cleanup (ctx); +KUNIT_ASSERT_EQ (test, err,0 ); + } + ctx->counters_inited = true; + +INIT_WORK (&sbi->s_sb_upd_work, ioctl_test_sb_upd_work); +timer_setup (&sbi->s_err_report, ioctl_test_err_timer,0 );
[Severity: Low]
If any of the percpu_counter_init() calls fail, does ioctl_test_cleanup() run cancel_work_sync() and timer_delete_sync() on uninitialized s_sb_upd_work and s_err_report?
Because INIT_WORK() and timer_setup() happen after these error branches, cancel_work_sync() hits WARN_ON(!work->func) in __flush_work() and timer_delete_sync() passes an uninitialized lockdep_map to lock_map_acquire(). Also, the earlier allocation failure paths before sget_fc() abort without resetting active_ioctl_test to NULL.
fs/ext4/ioctl-test.c line 356
Quoted 5 lines
fs/ext4/ioctl-test.c new file +5
-0+spin_lock_init (&sbi->s_error_lock); +spin_lock_init (&sbi->s_md_lock); +spin_lock_init (&sbi->s_bdev_wb_lock); +spin_lock_init (&sbi->s_es_lock); +INIT_LIST_HEAD (&sbi->s_es_list);
[Severity: Medium]
Does ioctl_test_init() leave the sbi->s_es_stats per-CPU counters uninitialized?
test_swap_inode_data_and_seed() and test_force_shutdown_and_ioctl_dispatch() insert and remove extents via ext4_es_insert_extent() and ext4_es_remove_extent(), which call percpu_counter_inc() and percpu_counter_dec() on sbi->s_es_stats.es_stats_shk_cnt and sbi->s_es_stats.es_stats_all_cnt. Because neither percpu_counter_init() nor ext4_es_register_shrinker() is called for sbi, running these tests on CONFIG_SMP dereferences a NULL per-CPU pointer and uses an uninitialized spinlock in percpu_counter_add_batch().
[ ... ]
Quoted 2 lines
fs/ext4/ioctl-test.c new file +2
-0+static void test_swap_inode_data_and_seed (struct kunit *test) +{
[ ... ]
fs/ext4/ioctl-test.c line 805
Quoted 4 lines
fs/ext4/ioctl-test.c new file +4
-0+ inode1 =new_inode (sb); + inode2 =new_inode (sb); +KUNIT_ASSERT_NOT_NULL (test, inode1); +KUNIT_ASSERT_NOT_NULL (test, inode2);
[Severity: Low]
If the second new_inode(sb) call returns NULL, does KUNIT_ASSERT_NOT_NULL() abort the test while leaking inode1?
When ioctl_test_cleanup() subsequently calls deactivate_super(ctx->sb), the unreleased inode remains on sb->s_inodes and triggers the busy-inodes CHECK_DATA_CORRUPTION() in generic_shutdown_super(). The same pattern appears in test_immutable_dax_and_fileattr() when allocating reg_inode, dir_inode, reg_dentry, and dir_dentry before d_instantiate(), and in test_force_shutdown_and_ioctl_dispatch() if d_alloc_anon() fails after new_inode().
Quoted 4 lines
fs/ext4/ioctl.c +0
-0
[ ... ]
Quoted 25 lines
fs/ext4/ioctl.c +8
-8@@ -1465,34 +1468,35 @@ static int ext4_ioctl_set_tune_sb(struct file *filp,* Filter out the features that are already set from * the set_mask. */ - params.set_feature_compat_mask &= + params->set_feature_compat_mask &= ~le32_to_cpu (es->s_feature_compat); - params.set_feature_incompat_mask &= + params->set_feature_incompat_mask &= ~le32_to_cpu (es->s_feature_incompat); - params.set_feature_ro_compat_mask &= + params->set_feature_ro_compat_mask &= ~le32_to_cpu (es->s_feature_ro_compat); -if ((params.set_feature_incompat_mask & -EXT4_FEATURE_INCOMPAT_CASEFOLD )) { +if (params->set_feature_incompat_mask & +EXT4_FEATURE_INCOMPAT_CASEFOLD ) { enabling_casefold =1 ; -if (!(params.set_flags &EXT4_TUNE_FL_ENCODING )) { - params.encoding =EXT4_ENC_UTF8_12_1 ; - params.set_flags |=EXT4_TUNE_FL_ENCODING ; +if (!(params->set_flags &EXT4_TUNE_FL_ENCODING )) { + params->encoding =EXT4_ENC_UTF8_12_1 ; + params->set_flags |=EXT4_TUNE_FL_ENCODING ; }
fs/ext4/ioctl.c static int ext4_ioctl_set_tune_sb(struct file *filp, · line 1490
Quoted 10 lines
fs/ext4/ioctl.c +5
-3-if (!(params.set_flags &EXT4_TUNE_FL_ENCODING_FLAGS )) { - params.encoding_flags =0 ; - params.set_flags |=EXT4_TUNE_FL_ENCODING_FLAGS ; +if (!(params->set_flags & +EXT4_TUNE_FL_ENCODING_FLAGS )) { + params->encoding_flags =0 ; + params->set_flags |= +EXT4_TUNE_FL_ENCODING_FLAGS ; } }
[Severity: High]
This problem wasn't introduced by this patch, but when EXT4_FEATURE_INCOMPAT_CASEFOLD is enabled online via EXT4_IOC_SET_TUNE_SB_PARAM [1], does anything initialize sb->s_encoding in memory?
ext4_sb_setparams() sets EXT4_FEATURE_INCOMPAT_CASEFOLD in the superblock without loading the unicode map into sb->s_encoding. Subsequent EXT4_IOC_SETFLAGS calls can then set EXT4_CASEFOLD_FL on a directory, and a lookup in that directory calls ext4_fname_setup_ci_filename() -> utf8_casefold(dir->i_sb->s_encoding, ...), dereferencing a NULL sb->s_encoding pointer.
[ ... ]
fs/ext4/ioctl.c int ext4_update_overhead(struct super_block *sb, bool force) · line 2122
Quoted 5 lines
fs/ext4/ioctl.c +5
-0+void ext4_swap_inode_data_test (struct inode *inode1,struct inode *inode2) +{ +swap_inode_data (inode1, inode2); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_swap_inode_data_test);
[Severity: High]
This problem wasn't introduced by this patch, but can swap_inode_data() cause torn reads of i_version on 32-bit architectures [2]?
fs/ext4/ioctl.c:swap_inode_data() {
...
swap(inode1->i_version, inode2->i_version);
...
}Because i_version is an atomic64_t, exchanging it with swap() performs plain struct assignment instead of using atomic64 accessors, allowing concurrent lockless readers such as inode_peek_iversion_raw() to observe torn values on 32-bit SMP systems.
[1] https://sashiko.dev/#/bug/linux-4eae7256-2707-4887-b442-c774f5662e2b
[2] https://sashiko.dev/#/bug/linux-14d568d4-dbf5-4a52-9af4-757563dc37e3
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
Theodore Ts'o
maintainerPATCH 20/27 ext4: add KUnit tests for fs/ext4/resize.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_resize_test) covering online filesystem resizing, group validation, flex_bg table packing, backup descriptor reservation, and meta_bg conversion in fs/ext4/resize.c:
- Precondition checks in ext4_resize_begin() and EXT4_FLAGS_RESIZING mutual exclusion with ext4_resize_end().
- Backup group iteration in ext4_list_backups() (sparse_super powers of 3/5/7, dense non-sparse sequence, and sparse_super2 s_backup_bgs) and reserved GDT validation in verify_reserved_gdb().
- Group geometry and overlap validation in verify_group_input() across partial prior groups, reserved-block ratios, out-of-bounds bitmaps and inode tables, bitmap collisions, and superblock/GDT overhead overlaps.
- Flex group batch sizing in alloc_flex_gd(), descriptor flag and partial-group initialization in ext4_setup_next_flex_gd(), and packed metadata table placement and -ENOSPC handling in ext4_alloc_group_tables().
- Online partial-last-group extension in ext4_group_extend() updating superblock counts, block bitmaps, buddy caches, and backup superblocks.
- Group addition in ext4_group_add() including backup reserved GDT updates via reserve_backup_gdb(), resize_inode validation and meta_bg conversion in ext4_convert_meta_bg(), and end-to-end ext4_resize_fs() growth across reserved GDT consumption into meta_bg.
Route raw sb_getblk() calls in resize.c through ext4_sb_getblk() and wrap sb_issue_zeroout() in ext4_resize_issue_zeroout() with KUNIT_STATIC_STUB_REDIRECT so resize metadata I/O can be exercised deterministically in memory.
--- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 32 + fs/ext4/resize-test.c | 1341 +++++++++++++++++++++++++++++++++++++++++ fs/ext4/resize.c | 102 +++- 4 files changed, 1453 insertions(+), 25 deletions(-) create mode 100644 fs/ext4/resize-test.c
fs/ext4/Makefile +2 -1
@@ -21,7 +21,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ fast_commit-test.o ialloc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ - sysfs-test.o ioctl-test.o + sysfs-test.o ioctl-test.o \ + resize-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +32 -0
@@ -688,6 +688,17 @@ enum { GROUP_TABLE_COUNT, }; +/* +* ext4_new_flex_group_data is used by 64bit-resize interface to add a flex +* group each time. +*/ +struct ext4_new_flex_group_data { +struct ext4_new_group_data *groups; +__u16 *bg_flags; +ext4_group_t resize_bg; +ext4_group_t count; +}; +/* * Flags used by ext4_map_blocks() */
@@ -3399,6 +3410,8 @@ extern bool ext4_empty_dir(struct inode *inode);/* resize.c */ extern void ext4_kvfree_array_rcu (void *to_free); +extern int ext4_resize_issue_zeroout (struct super_block *sb,sector_t blk, +sector_t nr_blks,gfp_t gfp_mask);extern int ext4_group_add (struct super_block *sb,struct ext4_new_group_data *input); extern int ext4_group_extend(struct super_block *sb,
@@ -3408,6 +3421,25 @@ extern int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count);extern unsigned int ext4_list_backups (struct super_block *sb,unsigned int *three,unsigned int *five,unsigned int *seven); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_verify_group_input_test (struct super_block *sb, +struct ext4_new_group_data *input); +extern struct ext4_new_flex_group_data * +ext4_alloc_flex_gd_test (unsigned int flexbg_size,ext4_group_t o_group, +ext4_group_t n_group); +extern void ext4_free_flex_gd_test (struct ext4_new_flex_group_data *flex_gd); +extern int ext4_alloc_group_tables_test (struct super_block *sb, +struct ext4_new_flex_group_data *flex_gd, +unsigned int flexbg_size); +extern int ext4_verify_reserved_gdb_test (struct super_block *sb, +ext4_group_t end, +struct buffer_head *primary); +extern int ext4_setup_next_flex_gd_test (struct super_block *sb, +struct ext4_new_flex_group_data *flex_gd, +ext4_fsblk_t n_blocks_count); +extern int ext4_convert_meta_bg_test (struct super_block *sb, +struct inode *inode); +#endif /* super.c */ extern struct buffer_head *ext4_sb_bread(struct super_block *sb,
fs/ext4/resize-test.c new file +1341 -0
1,341 lines not on this page · raw message
fs/ext4/resize.c +78 -24
195 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 20/27] ext4: add KUnit tests for fs/ext4/resize.c
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] ext4: RCU callback context and barrier order in resize_test_cleanup() - [Low] ext4: uninitialized…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] ext4: RCU callback context and barrier order in resize_test_cleanup()
- [Low] ext4: uninitialized work/timer cancel in resize_test_init() unwind
- [Low] ext4: leak of group_desc on assertion abort in resize_configure_fs()
- [Low] ext4: partial percpu_counter_init() leak in resize_configure_fs()
--
commit 2234a2c272479e93ed67d158ad4b60b46b408f78
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/resize.c
This commit adds a KUnit test suite for online filesystem resizing in fs/ext4/resize.c and routes resize metadata buffer lookups and zeroout calls through KUnit stubbed helpers.
Quoted 5 lines
fs/ext4/resize-test.c new file +0
-0
[ ... ]
Quoted 11 lines
fs/ext4/resize-test.c new file +11
-0+static void resize_test_free_inode (struct inode *inode) +{ +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +kfree (EXT4_I (inode)); +} + +static void resize_test_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final (&inode->i_data); +clear_inode (inode); +}
[ ... ]
Quoted 37 lines
fs/ext4/resize-test.c new file +37
-0+static void resize_test_cleanup (struct resize_test_ctx *ctx) +{ +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct flex_groups **flex_groups; +struct resize_mock_blk *blk, *tmp; +unsigned int i; + +if (sb) { +cancel_work_sync (&sbi->s_sb_upd_work); +timer_delete_sync (&sbi->s_err_report); + } + +if (ctx->resize_inode) { +iput (ctx->resize_inode); + ctx->resize_inode =NULL ; + } + +if (ctx->mb_inited && sb) { +ext4_mb_release (sb); + ctx->mb_inited = false; + } + +if (ctx->counters_inited) { +percpu_counter_destroy (&sbi->s_freeclusters_counter); +percpu_counter_destroy (&sbi->s_dirtyclusters_counter); +percpu_counter_destroy (&sbi->s_freeinodes_counter); + ctx->counters_inited = false; + } + + flex_groups =rcu_access_pointer (sbi->s_flex_groups); +if (flex_groups) { +for (i =0 ; i < sbi->s_flex_groups_allocated; i++) +kvfree (flex_groups[i]); +kvfree (flex_groups); +rcu_assign_pointer (sbi->s_flex_groups,NULL ); + sbi->s_flex_groups_allocated =0 ;
fs/ext4/resize-test.c line 390
Quoted 10 lines
fs/ext4/resize-test.c new file +10
-0+ } + +rcu_barrier (); +kvfree (rcu_access_pointer (sbi->s_group_desc)); +rcu_assign_pointer (sbi->s_group_desc,NULL ); + +if (sb) { +deactivate_super (sb); + ctx->sb =NULL ; + }
[Severity: Medium]
Can resize_test_free_inode() and resize_test_cleanup() cause a use-after-free on ctx->sbi and take i_es_lock in RCU softirq context?
The VFS invokes super_operations.free_inode from i_callback() in RCU softirq context, but resize_test_free_inode() calls ext4_es_remove_extent(), which takes write_lock(&EXT4_I(inode)->i_es_lock) without disabling softirqs, reads EXT4_SB(inode->i_sb)->s_mount_state, and can touch sbi->s_dirtyclusters_counter. In addition, resize_test_cleanup() destroys the percpu counters before rcu_barrier() and calls deactivate_super(sb) after rcu_barrier(); if a test aborts while an inode such as rinode in test_convert_meta_bg_validation_and_conversion() is still live, deactivate_super() -> evict_inodes() queues i_callback() after rcu_barrier() has already returned, so resize_test_free_inode() can run after KUnit frees ctx.
Moving ext4_es_remove_extent() into resize_test_evict_inode() (matching ext4_clear_inode()) and calling deactivate_super(sb) before rcu_barrier() and percpu_counter_destroy() would avoid both issues.
[ ... ]
Quoted 4 lines
fs/ext4/resize-test.c new file +4
-0+static void resize_configure_fs (struct kunit *test,ext4_group_t ngroups, +u16 reserved_gdb,u8 log_flex, +u32 last_grp_blks) +{
[ ... ]
fs/ext4/resize-test.c line 492
Quoted 12 lines
fs/ext4/resize-test.c new file +12
-0+ group_desc =kvmalloc_array (gdb_count,sizeof (*group_desc),GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, group_desc); +for (g =0 ; g < gdb_count; g++) { +struct buffer_head *bh; + + bh =resize_get_or_create_bh (ctx, +RESIZE_TEST_FIRST_DATA_BLK +1 + g); +KUNIT_ASSERT_NOT_NULL (test, bh); +brelse (bh); + group_desc[g] = bh; + } +rcu_assign_pointer (sbi->s_group_desc, group_desc);
[Severity: Low]
Does this leak group_desc if KUNIT_ASSERT_NOT_NULL(test, bh) aborts the test? Because sbi->s_group_desc is only assigned after the loop, resize_test_cleanup() will not see group_desc to free it.
[ ... ]
fs/ext4/resize-test.c line 620
Quoted 9 lines
fs/ext4/resize-test.c new file +9
-0+ ret =percpu_counter_init (&sbi->s_freeclusters_counter, + total_free_blks,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_dirtyclusters_counter,0 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_freeinodes_counter, + total_inodes -10 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ctx->counters_inited = true;
[Severity: Low]
What happens if the second or third percpu_counter_init() fails and KUNIT_ASSERT_EQ() aborts before ctx->counters_inited is set?
resize_test_cleanup() skips percpu_counter_destroy() when ctx->counters_inited is false, leaking the already-initialized counter(s) and, under CONFIG_HOTPLUG_CPU, leaving their list_head entries inside ctx->sbi linked on the global percpu_counters list after ctx is freed. Since percpu_counter_destroy() is a no-op on zero-initialized counters, resize_test_cleanup() can call percpu_counter_destroy() unconditionally.
[ ... ]
Quoted 2 lines
fs/ext4/resize-test.c new file +2
-0+static int resize_test_init (struct kunit *test) +{
[ ... ]
Quoted 5 lines
fs/ext4/resize-test.c new file +5
-0+ ctx->sb = sb; +up_write (&sb->s_umount); + + ret =kunit_add_action_or_reset (test, resize_test_cleanup_action, ctx); +KUNIT_ASSERT_EQ (test, ret,0 );
[ ... ]
fs/ext4/resize-test.c line 706
Quoted 2 lines
fs/ext4/resize-test.c new file +2
-0+INIT_WORK (&sbi->s_sb_upd_work, resize_test_sb_upd_work); +timer_setup (&sbi->s_err_report, resize_test_err_timer,0 );
[Severity: Low]
If kunit_add_action_or_reset() fails to allocate the action, it immediately invokes resize_test_cleanup() while ctx->sb is already set, before sbi->s_sb_upd_work and sbi->s_err_report are initialized below. Would cancel_work_sync() and timer_delete_sync() in resize_test_cleanup() then trigger warnings on the uninitialized work and timer structures?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
Theodore Ts'o
maintainerPATCH 21/27 ext4: add KUnit tests for fs/ext4/migrate.c
In reply to Theodore Ts'oAdd the ext4_migrate_test KUnit suite in fs/ext4/migrate-test.c to test online inode format migration between indirect block maps and extent trees in fs/ext4/migrate.c:
- ext4_ext_migrate() precondition guards, fast symlink no-op handling, and temporary inode allocation error propagation
- direct and single-indirect physically contiguous block coalescing, sparse logical hole preservation, and indirect metadata freeing
- double-indirect and triple-indirect tree traversal and multi-level extent tree construction with proper i_csum_seed propagation
- error rollback freeing allocated temporary extent tree blocks while preserving the original indirect inode layout
- ext4_ext_swap_inode_data() concurrent block allocation detection via EXT4_STATE_EXT_MIGRATE (-EAGAIN)
- ext4_ind_migrate() conversion of empty and single-extent inodes back to direct block maps and rejection of unsupported layouts
Export ext4_ext_migrate(), ext4_ind_migrate(), and a KUnit wrapper for ext4_ext_swap_inode_data() via EXPORT_SYMBOL_FOR_EXT4_TEST.
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 4 + fs/ext4/migrate-test.c | 1064 ++++++++++++++++++++++++++++++++++++++++ fs/ext4/migrate.c | 11 + 4 files changed, 1080 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/migrate-test.c
fs/ext4/Makefile +1 -1
@@ -22,7 +22,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ - resize-test.o + resize-test.o migrate-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +4 -0
@@ -3385,6 +3385,10 @@ bool ext4_dax_compatible_test(struct inode *inode, unsigned int oldflags,/* migrate.c */ extern int ext4_ext_migrate (struct inode *);extern int ext4_ind_migrate (struct inode *inode); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_ext_swap_inode_data_test (handle_t *handle,struct inode *inode, +struct inode *tmp_inode); +#endif /* namei.c */ extern int ext4_init_new_dir(handle_t *handle, struct inode *dir,
fs/ext4/migrate-test.c new file +1064 -0
1,064 lines not on this page · raw message
fs/ext4/migrate.c +11 -0
@@ -597,6 +597,7 @@ int ext4_ext_migrate(struct inode *inode)iput (tmp_inode);return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ext_migrate);/* * Migrate a simple extent-based inode to use the i_blocks[] array
@@ -683,3 +684,13 @@ int ext4_ind_migrate(struct inode *inode)ext4_writepages_up_write (inode->i_sb, alloc_ctx);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ind_migrate); + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +int ext4_ext_swap_inode_data_test (handle_t *handle,struct inode *inode, +struct inode *tmp_inode) +{ +return ext4_ext_swap_inode_data (handle, inode, tmp_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ext_swap_inode_data_test); +#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 21/27] ext4: add KUnit tests for fs/ext4/migrate.c
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] ext4: UAF and invalid RCU context in migrate_test_free_inode() and cleanup - [Low] ext4…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] ext4: UAF and invalid RCU context in migrate_test_free_inode() and cleanup
- [Low] ext4: uninitialized work/timer teardown and counter leak in migrate_test_init()
- [Low] ext4: skipped extent block checksum check in migrate-test due to BH_Verified
- [Low] ext4: leaked ext4_ext_path and busy inodes on mid-test KUNIT_ASSERT failure
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Critical] ext4: error clobbering and data loss in ext4_ext_migrate()
[1]
--
commit 5ed76678c1803e6d79647899ecaa6195b5ca46ef
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/migrate.c
This commit adds the ext4_migrate_test KUnit suite in fs/ext4/migrate-test.c to test online inode format migration between indirect block maps and extent trees, and exports the tested helpers via EXPORT_SYMBOL_FOR_EXT4_TEST.
Quoted 5 lines
fs/ext4/migrate-test.c new file +0
-0
[ ... ]
Quoted 11 lines
fs/ext4/migrate-test.c new file +11
-0+static void migrate_test_free_inode (struct inode *inode) +{ +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +kfree (EXT4_I (inode)); +} + +static void migrate_test_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final (&inode->i_data); +clear_inode (inode); +}
[ ... ]
Quoted 22 lines
fs/ext4/migrate-test.c new file +22
-0+static void migrate_test_cleanup (struct migrate_test_ctx *ctx) +{ +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct migrate_mock_blk *blk, *tmp; + +if (sb) { +cancel_work_sync (&sbi->s_sb_upd_work); +timer_delete_sync (&sbi->s_err_report); + } + +if (ctx->es_shrinker_inited) { +ext4_es_unregister_shrinker (sbi); + ctx->es_shrinker_inited = false; + } + +if (ctx->counters_inited) { +percpu_counter_destroy (&sbi->s_freeclusters_counter); +percpu_counter_destroy (&sbi->s_dirtyclusters_counter); +percpu_counter_destroy (&sbi->s_freeinodes_counter); + ctx->counters_inited = false; + }
fs/ext4/migrate-test.c line 415
Quoted 10 lines
fs/ext4/migrate-test.c new file +10
-0+ +if (ctx->rwsem_inited) { +percpu_free_rwsem (&sbi->s_writepages_rwsem); + ctx->rwsem_inited = false; + } + +if (sb) { +deactivate_super (sb); + ctx->sb =NULL ; + }
[Severity: High]
Does calling ext4_es_remove_extent() from migrate_test_free_inode() run in RCU softirq context and race with migrate_test_cleanup()?
During ext4_ext_migrate(), finish_range() -> ext4_find_extent() caches extents in EXT4_I(tmp_inode)->i_es_tree and links the inode onto ctx->sbi.s_es_list. Because destroy_inode() invokes .free_inode via call_rcu(), migrate_test_free_inode() runs in RCU softirq context, where ext4_es_remove_extent() takes non-softirq-safe locks (i_es_lock and s_es_lock) and can allocate with GFP_KERNEL.
In addition, migrate_test_cleanup() destroys the extent status shrinker's percpu counters before deactivate_super(sb) and returns without rcu_barrier() before KUnit frees ctx:
CPU0 CPU1 (<softirq>)migrate_test_cleanup()
ext4_es_unregister_shrinker(sbi)
percpu_counter_destroy(...)
deactivate_super(sb)
/* KUnit frees ctx */
i_callback()
migrate_test_free_inode()
ext4_es_remove_extent()
/* dereferences freed ctx->sbi
* and NULL counter->counters
*/ <-- use-after-freeCalling ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS) in migrate_test_evict_inode() before clear_inode(), moving deactivate_super(sb) ahead of the sbi teardown in migrate_test_cleanup(), and calling rcu_barrier() before returning would avoid this.
[ ... ]
Quoted 2 lines
fs/ext4/migrate-test.c new file +2
-0+static int migrate_test_init (struct kunit *test) +{
[ ... ]
Quoted 5 lines
fs/ext4/migrate-test.c new file +5
-0+ ctx->sb = sb; +up_write (&sb->s_umount); + + ret =kunit_add_action_or_reset (test, migrate_test_cleanup_action, ctx); +KUNIT_ASSERT_EQ (test, ret,0 );
[ ... ]
Quoted 2 lines
fs/ext4/migrate-test.c new file +2
-0+INIT_WORK (&sbi->s_sb_upd_work, migrate_test_sb_upd_work); +timer_setup (&sbi->s_err_report, migrate_test_err_timer,0 );
[ ... ]
fs/ext4/migrate-test.c line 552
Quoted 8 lines
fs/ext4/migrate-test.c new file +8
-0+ ret =percpu_counter_init (&sbi->s_freeclusters_counter,4096 , +GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_dirtyclusters_counter,0 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_freeinodes_counter,200 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ctx->counters_inited = true;
[Severity: Low]
If kunit_add_action_or_reset() fails, can migrate_test_cleanup() call cancel_work_sync() and timer_delete_sync() on s_sb_upd_work and s_err_report before they are initialized?
Also, if the second or third percpu_counter_init() fails, KUNIT_ASSERT_EQ() aborts before ctx->counters_inited is set, so migrate_test_cleanup() skips percpu_counter_destroy() and leaks the already-initialized percpu counters.
[ ... ]
Quoted 2 lines
fs/ext4/migrate-test.c new file +2
-0+static void test_ext_migrate_dind_tind_and_multilevel_tree (struct kunit *test) +{
[ ... ]
fs/ext4/migrate-test.c line 829
Quoted 13 lines
fs/ext4/migrate-test.c new file +13
-0+for (i =0 ; i <ARRAY_SIZE (expected); i++) { + path =ext4_find_extent (inode, expected[i].lblk,NULL ,0 ); +KUNIT_ASSERT_FALSE_MSG (test,IS_ERR (path), +"find_extent failed at idx %u" , i); +KUNIT_ASSERT_NOT_NULL (test, path[path->p_depth].p_ext); +KUNIT_EXPECT_EQ_MSG (test, +le32_to_cpu (path[path->p_depth].p_ext->ee_block), + expected[i].lblk,"lblk idx %u" , i); +KUNIT_EXPECT_EQ_MSG (test, +ext4_ext_pblock (path[path->p_depth].p_ext), + expected[i].pblk,"pblk idx %u" , i); +ext4_free_ext_path (path); + }
[Severity: Low]
Does ext4_find_extent(inode, ..., 0) here skip verifying the extent block checksum on the migrated inode?
While building the tree on tmp_inode, ext4_ext_grow_indepth() and migrate_ext_dirty_stub() call set_buffer_verified() on the mock buffer_head. When ext4_find_extent() is later called on inode with flags == 0, __read_extent_tree_block() sees buffer_verified(bh) and returns without running __ext4_ext_check(), so i_csum_seed propagation is never checked. Passing EXT4_EX_FORCE_CACHE (or clearing buffer_verified() on the block) would force checksum verification.
[Severity: Low]
In the same loop, if KUNIT_ASSERT_NOT_NULL(test, path[path->p_depth].p_ext) fails, does the early abort leak path and leave inode referenced during deactivate_super(sb)? Other KUNIT_ASSERT_* calls in these tests while holding a test inode similarly skip iput(inode) on failure.
fs/ext4/migrate.c int ext4_ext_migrate(struct inode *inode) · line 600
Quoted 9 lines
fs/ext4/migrate.c +1
-0@@ -597,6 +597,7 @@ int ext4_ext_migrate(struct inode *inode)iput (tmp_inode);return retval; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ext_migrate);
[Severity: Critical]
This problem wasn't introduced by this patch [1], but in ext4_ext_migrate(), does assigning the result of ext4_journal_ensure_credits() to retval after err_out clobber the migration error and risk freeing the original file's data blocks?
fs/ext4/migrate.c:ext4_ext_migrate() {
...
err_out:
if (retval)
free_ext_block(handle, tmp_inode);
else {
...
}
/* We mark the tmp_inode dirty via ext4_ext_tree_init. */
retval = ext4_journal_ensure_credits(handle, 1, 0);
if (retval < 0)
goto out_stop;
...
tmp_inode->i_blocks = 0;
EXT4_I(tmp_inode)->i_csum_seed = tmp_csum_seed;
/* Reset the extent details */
ext4_ext_tree_init(handle, tmp_inode);
out_stop:
ext4_journal_stop(handle);
out_tmp_inode:
unlock_new_inode(tmp_inode);
out_unlock:
ext4_writepages_up_write(inode->i_sb, alloc_ctx);
iput(tmp_inode);
return retval;
}When extent building fails (such as in test_ext_migrate_error_rollback_frees_tmp_extent_blocks()), ext4_journal_ensure_credits() overwrites the negative retval with 0 so ext4_ext_migrate() returns success. Worse, if ext4_journal_ensure_credits() fails, jumping to out_stop leaves tmp_inode with i_nlink == 0, non-zero i_blocks, and in-inode root extents still pointing at the original file's physical data blocks, which iput(tmp_inode) -> ext4_evict_inode() will then free.
[1] https://sashiko.dev/#/bug/linux-29ab25ff-78b3-4378-b750-b1aca01c3a2d
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
Theodore Ts'o
maintainerPATCH 22/27 ext4: add KUnit tests for fs/ext4/indirect.c
In reply to Theodore Ts'oAdd the ext4_indirect_test KUnit suite in fs/ext4/indirect-test.c to test legacy direct, single-, double-, and triple-indirect block mapping, truncation, and hole punching in fs/ext4/indirect.c:
- ext4_block_to_path() offset decomposition, boundary distance, and out-of-range block rejection, plus ext4_ind_trans_blocks() credits
- ext4_ind_map_blocks() read-only lookup across contiguous runs, EXT4_MAP_BOUNDARY detection, and multi-level hole span calculation
- ext4_ind_map_blocks() allocation and branch splicing across direct, IND, DIND, and TIND depths
- error handling (out-of-range logical/physical blocks, bigalloc rejection, indirect read I/O failure, corrupt indirect blockref) and partial branch allocation unwind freeing intermediate metadata blocks
- ext4_ind_truncate() partial shared-branch truncation, indirect root detachment, and full truncation to zero
- ext4_ind_remove_space() hole punching within direct blocks, across mixed levels, and converging on shared IND and DIND blocks
- corrupt block pointer rejection in ext4_clear_blocks() and ext4_free_branches()
Route indirect block buffer lookups through ext4_sb_getblk(), add a KUnit static stub redirect to ext4_sb_bread_nofail(), and export the indirect mapping and truncation entry points for KUnit testing.
--- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 4 + fs/ext4/indirect-test.c | 1270 +++++++++++++++++++++++++++++++++++++++ fs/ext4/indirect.c | 18 +- fs/ext4/super.c | 7 +- 5 files changed, 1298 insertions(+), 4 deletions(-) create mode 100644 fs/ext4/indirect-test.c
fs/ext4/Makefile +2 -1
@@ -22,7 +22,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ balloc-test.o orphan-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ - resize-test.o migrate-test.o + resize-test.o migrate-test.o \ + indirect-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +4 -0
@@ -3338,6 +3338,10 @@ extern int ext4_ind_trans_blocks(struct inode *inode, int nrblocks);extern void ext4_ind_truncate (handle_t *,struct inode *inode);extern int ext4_ind_remove_space (handle_t *handle,struct inode *inode,ext4_lblk_t start,ext4_lblk_t end); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_block_to_path_test (struct inode *inode,ext4_lblk_t i_block, +ext4_lblk_t offsets[4 ],int *boundary); +#endif /* ioctl.c */ extern long ext4_ioctl (struct file *,unsigned int ,unsigned long );
fs/ext4/indirect-test.c new file +1270 -0
1,270 lines not on this page · raw message
fs/ext4/indirect.c +16 -2
@@ -163,7 +163,7 @@ static Indirect *ext4_get_branch(struct inode *inode, int depth, ret = -EFSCORRUPTED ; goto failure; } - bh =sb_getblk (sb, key); + bh =ext4_sb_getblk (sb, key);if (unlikely (!bh)) { ret = -ENOMEM ; goto failure;
@@ -354,7 +354,8 @@ static int ext4_alloc_branch(handle_t *handle,if (i ==0 )continue ; - bh = branch[i].bh =sb_getblk (ar->inode->i_sb, new_blocks[i-1 ]); + bh = branch[i].bh =ext4_sb_getblk (ar->inode->i_sb, + new_blocks[i -1 ]);if (unlikely (!bh)) { err = -ENOMEM ; goto failed;
@@ -671,6 +672,7 @@ int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,trace_ext4_ind_map_blocks_exit (inode, flags, map, err);return err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ind_map_blocks);/* * Calculate number of indirect blocks touched by mapping @nrblocks logically
@@ -685,6 +687,7 @@ int ext4_ind_trans_blocks(struct inode *inode, int nrblocks)*/ return DIV_ROUND_UP (nrblocks,EXT4_ADDR_PER_BLOCK (inode->i_sb)) +4 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ind_trans_blocks);static int ext4_ind_trunc_restart_fn (handle_t *handle,struct inode *inode,struct buffer_head *bh,int *dropped)
@@ -1213,6 +1216,7 @@ void ext4_ind_truncate(handle_t *handle, struct inode *inode) ; } } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ind_truncate);/** * ext4_ind_remove_space - remove space from the range
@@ -1472,3 +1476,13 @@ int ext4_ind_remove_space(handle_t *handle, struct inode *inode, } goto cleanup; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_ind_remove_space); + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +int ext4_block_to_path_test (struct inode *inode,ext4_lblk_t i_block, +ext4_lblk_t offsets[4 ],int *boundary) +{ +return ext4_block_to_path (inode, i_block, offsets, boundary); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_block_to_path_test); +#endif
fs/ext4/super.c +6 -1
@@ -285,11 +285,16 @@ struct buffer_head *ext4_sb_bread_unmovable(struct super_block *sb,struct buffer_head *ext4_sb_bread_nofail (struct super_block *sb,sector_t block) { -gfp_t gfp =mapping_gfp_constraint (sb->s_bdev->bd_mapping, +gfp_t gfp; + +KUNIT_STATIC_STUB_REDIRECT (ext4_sb_bread_nofail, sb, block); + + gfp =mapping_gfp_constraint (sb->s_bdev->bd_mapping, ~__GFP_FS) | __GFP_MOVABLE | __GFP_NOFAIL;return __ext4_sb_bread_gfp (sb, block,0 , gfp); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_sb_bread_nofail);void ext4_sb_breadahead_unmovable (struct super_block *sb,sector_t block) {
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 22/27] ext4: add KUnit tests for fs/ext4/indirect.c
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] ext4: indirect-test: UAF in ind_test_free_inode() after RCU grace period - [Low] ext4: uncleaned…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] ext4: indirect-test: UAF in ind_test_free_inode() after RCU grace period
- [Low] ext4: uncleaned percpu_counter and uninited work/timer in ind_test_init()
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Critical] ext4: incomplete error check in ext4_ind_map_blocks() [1] --
commit ebeb5ffec6cf1b1539b939ab7329a1923d9ae24c
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/indirect.c
This commit adds the ext4_indirect_test KUnit test suite for indirect block mapping, truncation, and hole punching, and routes indirect block buffer lookups through ext4_sb_getblk().
Quoted 5 lines
fs/ext4/indirect-test.c new file +0
-0
[ ... ]
fs/ext4/indirect-test.c line 132
Quoted 11 lines
fs/ext4/indirect-test.c new file +11
-0+static void ind_test_free_inode (struct inode *inode) +{ +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +kfree (EXT4_I (inode)); +} + +static void ind_test_evict_inode (struct inode *inode) +{ +truncate_inode_pages_final (&inode->i_data); +clear_inode (inode); +}
[Severity: Medium]
Can ind_test_free_inode() trigger a use-after-free on ctx->sbi after the test finishes?
At the end of each test, iput() runs ind_test_evict_inode() synchronously and queues i_callback() -> ind_test_free_inode() via call_rcu(). KUnit then runs ind_test_cleanup() without an rcu_barrier() and frees ctx, so when the RCU callback later runs ext4_es_remove_extent(), it dereferences EXT4_SB(inode->i_sb) inside the freed ctx.
Moving ext4_es_remove_extent() into ind_test_evict_inode() and calling rcu_barrier() in ind_test_cleanup() before deactivating sb would avoid this.
[ ... ]
Quoted 22 lines
fs/ext4/indirect-test.c new file +22
-0+static void ind_test_cleanup (struct ind_test_ctx *ctx) +{ +struct super_block *sb = ctx->sb; +struct ext4_sb_info *sbi = &ctx->sbi; +struct ind_mock_blk *blk, *tmp; + +if (sb) { +cancel_work_sync (&sbi->s_sb_upd_work); +timer_delete_sync (&sbi->s_err_report); + } + +if (ctx->es_shrinker_inited) { +ext4_es_unregister_shrinker (sbi); + ctx->es_shrinker_inited = false; + } + +if (ctx->counters_inited) { +percpu_counter_destroy (&sbi->s_freeclusters_counter); +percpu_counter_destroy (&sbi->s_dirtyclusters_counter); +percpu_counter_destroy (&sbi->s_freeinodes_counter); + ctx->counters_inited = false; + }
[ ... ]
Quoted 5 lines
fs/ext4/indirect-test.c new file +5
-0+ ctx->sb = sb; +up_write (&sb->s_umount); + + ret =kunit_add_action_or_reset (test, ind_test_cleanup_action, ctx); +KUNIT_ASSERT_EQ (test, ret,0 );
[ ... ]
Quoted 2 lines
fs/ext4/indirect-test.c new file +2
-0+INIT_WORK (&sbi->s_sb_upd_work, ind_test_sb_upd_work); +timer_setup (&sbi->s_err_report, ind_test_err_timer,0 );
[ ... ]
fs/ext4/indirect-test.c line 552
Quoted 8 lines
fs/ext4/indirect-test.c new file +8
-0+ ret =percpu_counter_init (&sbi->s_freeclusters_counter,4096 , +GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_dirtyclusters_counter,0 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ret =percpu_counter_init (&sbi->s_freeinodes_counter,200 ,GFP_KERNEL ); +KUNIT_ASSERT_EQ (test, ret,0 ); + ctx->counters_inited = true;
[Severity: Low]
If the second or third percpu_counter_init() fails, does KUNIT_ASSERT_EQ() abort while ctx->counters_inited is still false? ind_test_cleanup() then skips percpu_counter_destroy(), leaking the earlier counter and leaving it linked in the global percpu_counters list when ctx is freed.
Also, ctx->sb is set before kunit_add_action_or_reset(), whereas s_sb_upd_work and s_err_report are initialized later, so if kunit_add_action_or_reset() fails, ind_test_cleanup() calls cancel_work_sync() and timer_delete_sync() on uninitialized structures.
[ ... ]
fs/ext4/indirect.c static Indirect *ext4_get_branch(struct inode *inode, int depth, · line 169
Quoted 13 lines
fs/ext4/indirect.c +1
-1@@ -163,7 +163,7 @@ static Indirect *ext4_get_branch(struct inode *inode, int depth, ret = -EFSCORRUPTED ; goto failure; } - bh =sb_getblk (sb, key); + bh =ext4_sb_getblk (sb, key);if (unlikely (!bh)) { ret = -ENOMEM ; goto failure;
[Severity: Critical]
This problem wasn't introduced by this patch, but when ext4_get_branch() fails with -EFSCORRUPTED or -ENOMEM [1], doesn't ext4_ind_map_blocks() miss the error when EXT4_GET_BLOCKS_CREATE is set?
fs/ext4/indirect.c:ext4_ind_map_blocks() {
...
/* Failed read of indirect block */
if (err == -EIO)
goto cleanup;
...
}Because ext4_ind_map_blocks() only checks for err == -EIO, it treats the partial chain returned on -ENOMEM or -EFSCORRUPTED as a hole, allocates new blocks, and splices them over the existing indirect block pointer, orphaning the original subtree and corrupting the file.
[1] https://sashiko.dev/#/bug/linux-2bfbc9ba-6121-45d3-a664-11e7452ad5d6
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
Theodore Ts'o
maintainerPATCH 23/27 ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations
In reply to Theodore Ts'oExpand ext4_extents_test to cover high-level file-range operations and reporting entry points in fs/ext4/extents.c:
- ext4_fallocate() mode validation (unsupported flags, encrypted collapse/insert rejection, FALLOC_FL_WRITE_ZEROES device limit check, non-extent inode rejection), preallocation with and without FALLOC_FL_KEEP_SIZE, and hole punching via FALLOC_FL_PUNCH_HOLE
- ext4_zero_range() via FALLOC_FL_ZERO_RANGE (written-to-unwritten split and EOF extension) and FALLOC_FL_WRITE_ZEROES (block zeroouts, unwritten-to-written conversion, and orphan tracking across EOF)
- ext4_collapse_range() alignment/EOF validation, block freeing, left-shift of trailing extents, and adjacent extent coalescing
- ext4_insert_range() alignment/EOF/maxbytes validation, mid-extent splitting, right-shift of trailing extents, and i_size growth
- ext4_convert_unwritten_extents(), ext4_convert_unwritten_extents_atomic(), and ext4_convert_unwritten_io_end_vec() IO completion conversions
- ext4_fiemap() and ext4_get_es_cache() range checks, FIEMAP_FLAG_CACHE precaching, external xattr reporting, and status extent reporting
--- fs/ext4/extents-test.c | 519 ++++++++++++++++++++++++++++++++++++++++- fs/ext4/extents.c | 6 + 2 files changed, 522 insertions(+), 3 deletions(-)
fs/ext4/extents-test.c +516 -3
@@ -15,8 +15,11 @@#include <kunit/static_stub.h> #include <linux/blkdev.h> #include <linux/buffer_head.h> +#include <linux/falloc.h> +#include <linux/fiemap.h> #include <linux/fs_context.h> #include <linux/gfp_types.h> +#include <linux/iversion.h> #include <linux/stddef.h> #include "ext4.h"
@@ -71,6 +74,13 @@ struct kunit_ctx {int last_free_flags;unsigned long total_freed_blocks; +unsigned int zeroout_calls; +ext4_lblk_t last_zeroout_lblk; +ext4_lblk_t last_zeroout_len; +unsigned int orphan_add_calls; +unsigned int orphan_del_calls; +struct dentry k_dentry; +bool fail_getblk; } k_ctx;
@@ -200,20 +210,29 @@ static void ext_init_mock_inode(struct ext4_inode_info *ei, inode->i_sb = sb; inode->i_ino = ino; inode->i_mode =S_IFREG |0644 ; +set_nlink (inode,1 ); inode->i_blkbits = sb->s_blocksize_bits; - inode->i_flags |=S_NOQUOTA ; + inode->i_flags |=S_NOQUOTA |S_NOSEC ; inode->i_mapping = &inode->i_data; +inode_set_iversion (inode,1 );spin_lock_init (&inode->i_lock);init_rwsem (&inode->i_rwsem); -init_rwsem (&inode->i_data.invalidate_lock); +address_space_init_once (&inode->i_data); + inode->i_data.host = inode;inode_state_set_raw (inode,I_DIRTY_SYNC |I_DIRTY_DATASYNC );ext4_es_init_tree (&ei->i_es_tree);ext4_init_pending_tree (&ei->i_pending_tree);rwlock_init (&ei->i_es_lock);INIT_LIST_HEAD (&ei->i_es_list); +INIT_LIST_HEAD (&ei->i_orphan); +INIT_LIST_HEAD (&ei->i_fc_list); +INIT_LIST_HEAD (&ei->i_fc_dilist); +spin_lock_init (&ei->i_fc_lock);init_rwsem (&ei->i_data_sem); +init_rwsem (&ei->xattr_sem); +spin_lock_init (&ei->i_raw_lock);spin_lock_init (&ei->i_block_reservation_lock);rwlock_init (&ei->i_prealloc_lock); ei->i_prealloc_node =RB_ROOT ;
@@ -267,6 +286,7 @@ static void extents_kunit_exit(struct kunit *test)kfree (k_ctx.meta_blocks);kfree (sbi->s_es); +kfree (sb->s_bdev->bd_queue);kfree (sb->s_bdev->bd_mapping);kfree (sb->s_bdev);kfree (sbi);
@@ -490,16 +510,22 @@ static int extents_kunit_init(struct kunit *test) err = -ENOMEM ; goto out_bdev; } + sb->s_bdev->bd_queue = kzalloc_obj(struct request_queue); +if (!sb->s_bdev->bd_queue) { + err = -ENOMEM ; + goto out_bdev_mapping; + } sbi->s_es = kzalloc_obj(struct ext4_super_block);if (!sbi->s_es) { err = -ENOMEM ; - goto out_bdev_mapping; + goto out_bdev_queue; } sbi->s_es->s_first_data_block =cpu_to_le32 (1 ); sbi->s_es->s_rev_level =cpu_to_le32 (EXT4_DYNAMIC_REV );ext4_blocks_count_set (sbi->s_es,EXT_TOTAL_BLOCKS );set_opt (sb,ERRORS_CONT ); + sbi->s_bitmap_maxbytes =1ULL <<40 ; sbi->s_blocks_per_group =32768 ; sbi->s_clusters_per_group =32768 ; sbi->s_cluster_ratio =1 ;
@@ -507,12 +533,20 @@ static int extents_kunit_init(struct kunit *test) sbi->s_desc_per_block =64 ; sbi->s_groups_count =32 ; sbi->s_extent_max_zeroout_kb =32 ; +mutex_init (&sbi->s_orphan_lock); +INIT_LIST_HEAD (&sbi->s_orphan);spin_lock_init (&sbi->s_bdev_wb_lock);spin_lock_init (&sbi->s_error_lock);spin_lock_init (&sbi->s_md_lock); +ratelimit_state_init (&sbi->s_err_ratelimit_state, +DEFAULT_RATELIMIT_INTERVAL , +DEFAULT_RATELIMIT_BURST );ratelimit_state_init (&sbi->s_warning_ratelimit_state,DEFAULT_RATELIMIT_INTERVAL ,DEFAULT_RATELIMIT_BURST ); +ratelimit_state_init (&sbi->s_msg_ratelimit_state, +DEFAULT_RATELIMIT_INTERVAL , +DEFAULT_RATELIMIT_BURST ); err =percpu_counter_init (&sbi->s_freeclusters_counter,100000 ,GFP_KERNEL );
@@ -621,6 +655,8 @@ static int extents_kunit_init(struct kunit *test)percpu_counter_destroy (&sbi->s_freeclusters_counter); out_es:kfree (sbi->s_es); +out_bdev_queue: +kfree (sb->s_bdev->bd_queue); out_bdev_mapping:kfree (sb->s_bdev->bd_mapping); out_bdev:
@@ -2441,6 +2477,477 @@ static void test_ext_fast_commit_replay(struct kunit *test) 10ULL << (inode->i_sb->s_blocksize_bits - 9)); } +static int ext_range_ext_zeroout_stub (struct inode *inode, +struct ext4_extent *ex) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk =le32_to_cpu (ex->ee_block); + k_ctx.last_zeroout_len =ext4_ext_get_actual_len (ex); +return 0 ; +} + +static int ext_range_issue_zeroout_stub (struct inode *inode,ext4_lblk_t lblk, +ext4_fsblk_t pblk,ext4_lblk_t len) +{ + k_ctx.zeroout_calls++; + k_ctx.last_zeroout_lblk = lblk; + k_ctx.last_zeroout_len = len; +return 0 ; +} + +static int ext_orphan_add_stub (handle_t *handle,struct inode *inode) +{ + k_ctx.orphan_add_calls++; +return 0 ; +} + +static int ext_orphan_del_stub (handle_t *handle,struct inode *inode) +{ + k_ctx.orphan_del_calls++; +return 0 ; +} + +static void ext_setup_range_test (struct kunit *test,struct inode *inode, +struct file *file) +{ +kunit_activate_static_stub (test, ext4_ext_zeroout, + ext_range_ext_zeroout_stub); +kunit_activate_static_stub (test, ext4_issue_zeroout, + ext_range_issue_zeroout_stub); +kunit_activate_static_stub (test, ext4_orphan_add, ext_orphan_add_stub); +kunit_activate_static_stub (test, ext4_orphan_del, ext_orphan_del_stub); + +ext_reset_tree (inode); + inode->i_size =0 ; +EXT4_I (inode)->i_disksize =0 ; + inode->i_blocks =0 ; + + k_ctx.next_alloc_pblk =EXT_ALLOC_BASE_PBLK ; + k_ctx.alloc_calls =0 ; + k_ctx.free_calls =0 ; + k_ctx.total_freed_blocks =0 ; + k_ctx.zeroout_calls =0 ; + k_ctx.orphan_add_calls =0 ; + k_ctx.orphan_del_calls =0 ; + +if (file) { +struct file tmp = { + .f_path = { .dentry = &k_ctx.k_dentry }, + .f_inode = inode, + .f_mapping = inode->i_mapping, + .f_mode =FMODE_READ |FMODE_WRITE | +FMODE_NOCMTIME , + }; + +memset (&k_ctx.k_dentry,0 ,sizeof (k_ctx.k_dentry)); + k_ctx.k_dentry.d_inode = inode; +memcpy (file, &tmp,sizeof (tmp)); + } +} + +static void ext_expect_extent_at (struct kunit *test,struct inode *inode, +ext4_lblk_t lblk,unsigned short exp_len, +ext4_fsblk_t exp_pblk,bool exp_unwritten) +{ +struct ext4_ext_path *path; +struct ext4_extent *ex; + +down_read (&EXT4_I (inode)->i_data_sem); + path =ext4_find_extent (inode, lblk,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR (path)); + ex = path[path->p_depth].p_ext; +KUNIT_ASSERT_NOT_NULL (test, ex); + +KUNIT_EXPECT_EQ (test,le32_to_cpu (ex->ee_block), lblk); +KUNIT_EXPECT_EQ (test,ext4_ext_get_actual_len (ex), exp_len); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (ex), exp_pblk); +KUNIT_EXPECT_EQ (test, !!ext4_ext_is_unwritten (ex), exp_unwritten); + +ext4_free_ext_path (path); +up_read (&EXT4_I (inode)->i_data_sem); +} + +/* +* Verify ext4_fallocate() mode validation (unsupported flags, encrypted +* collapse/insert rejection, WRITE_ZEROES without bdev support, non-extent +* preallocation rejection), preallocation with and without FALLOC_FL_KEEP_SIZE, +* and hole punching via FALLOC_FL_PUNCH_HOLE. +*/ +static void test_fallocate_modes_and_prealloc (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct file file; +long ret; + +ext_setup_range_test (test, inode, &file); + +/* Unsupported mode flag -> -EOPNOTSUPP */ + ret =ext4_fallocate (&file,0x40000000 ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); + +/* FALLOC_FL_WRITE_ZEROES without unmap sectors -> -EOPNOTSUPP */ + ret =ext4_fallocate (&file,FALLOC_FL_WRITE_ZEROES ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); + +/* Encrypted inode rejects COLLAPSE_RANGE and INSERT_RANGE */ + inode->i_flags |=S_ENCRYPTED ; + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); + inode->i_flags &= ~S_ENCRYPTED ; + +/* Non-extent (indirect) inode rejects fallocate preallocation */ +ext4_clear_inode_flag (inode,EXT4_INODE_EXTENTS ); + ret =ext4_fallocate (&file,0 ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); +ext4_set_inode_flag (inode,EXT4_INODE_EXTENTS ); + +/* Preallocate [0, 4 blocks) with FALLOC_FL_KEEP_SIZE: i_size stays 0 */ + ret =ext4_fallocate (&file,FALLOC_FL_KEEP_SIZE ,0 ,4 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, inode->i_size,0LL ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,0LL ); +ext_expect_extent_at (test, inode,0 ,4 ,EXT_ALLOC_BASE_PBLK , true); + +/* Extend allocation across [2, 6 blocks) without KEEP_SIZE */ + ret =ext4_fallocate (&file,0 ,2 *4096 ,4 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, inode->i_size,6LL *4096 ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,6LL *4096 ); +ext_expect_extent_at (test, inode,0 ,6 ,EXT_ALLOC_BASE_PBLK , true); + +/* Punch middle [2, 4) with FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE */ + ret =ext4_fallocate (&file,FALLOC_FL_PUNCH_HOLE |FALLOC_FL_KEEP_SIZE , +2 *4096 ,2 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, inode->i_size,6LL *4096 ); +KUNIT_EXPECT_EQ (test, k_ctx.total_freed_blocks,2UL ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (ext_inode_hdr (inode)->eh_entries),2 ); +ext_expect_extent_at (test, inode,0 ,2 ,EXT_ALLOC_BASE_PBLK , true); +ext_expect_extent_at (test, inode,4 ,2 ,EXT_ALLOC_BASE_PBLK +4 , true); +} + +/* +* Verify ext4_zero_range() via both FALLOC_FL_ZERO_RANGE (splitting written +* extents to unwritten and allocating unwritten blocks past EOF) and +* FALLOC_FL_WRITE_ZEROES (issuing block zeroouts, converting to written, and +* tracking orphan state when extending i_disksize). +*/ +static void test_zero_range_and_write_zeroes (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct super_block *sb = inode->i_sb; +struct file file; +long ret; + +/* Part A: FALLOC_FL_ZERO_RANGE across written tail + past EOF */ +ext_setup_range_test (test, inode, &file); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,6 ,200 , false,0 ),0 ); + inode->i_size =6LL *4096 ; +EXT4_I (inode)->i_disksize =6LL *4096 ; + + ret =ext4_fallocate (&file,FALLOC_FL_ZERO_RANGE ,2 *4096 ,6 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, inode->i_size,8LL *4096 ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,8LL *4096 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (ext_inode_hdr (inode)->eh_entries),3 ); +ext_expect_extent_at (test, inode,0 ,2 ,200 , false); +ext_expect_extent_at (test, inode,2 ,4 ,202 , true); +ext_expect_extent_at (test, inode,6 ,2 ,EXT_ALLOC_BASE_PBLK , true); + +/* Part B: FALLOC_FL_WRITE_ZEROES over unwritten + hole past EOF */ +ext_setup_range_test (test, inode, &file); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors =1024 ; + +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,2 ,300 , true,0 ),0 ); + inode->i_size =2LL *4096 ; +EXT4_I (inode)->i_disksize =2LL *4096 ; + + ret =ext4_fallocate (&file,FALLOC_FL_WRITE_ZEROES ,0 ,4 *4096 ); + sb->s_bdev->bd_queue->limits.max_wzeroes_unmap_sectors =0 ; + +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_GE (test, k_ctx.zeroout_calls,2U ); +KUNIT_EXPECT_GE (test, k_ctx.orphan_add_calls,1U ); +KUNIT_EXPECT_EQ (test, k_ctx.orphan_del_calls,1U ); +KUNIT_EXPECT_EQ (test, inode->i_size,4LL *4096 ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,4LL *4096 ); +ext_expect_extent_at (test, inode,0 ,2 ,300 , false); +ext_expect_extent_at (test, inode,2 ,2 ,EXT_ALLOC_BASE_PBLK , false); +} + +/* +* Verify ext4_collapse_range() validation checks, block removal, left-shift of +* subsequent extents, adjacent extent coalescing after collapse, and i_size +* reduction. +*/ +static void test_collapse_range (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct file file; +long ret; + +ext_setup_range_test (test, inode, &file); + inode->i_size =10LL *4096 ; +EXT4_I (inode)->i_disksize =10LL *4096 ; + +/* Block-unaligned offset or length -> -EINVAL */ + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE ,512 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE ,4096 ,512 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + +/* Non-extent inode -> -EOPNOTSUPP */ +ext4_clear_inode_flag (inode,EXT4_INODE_EXTENTS ); + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); +ext4_set_inode_flag (inode,EXT4_INODE_EXTENTS ); + +/* Collapsing up to or beyond i_size -> -EINVAL */ + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE , +8 *4096 ,2 *4096 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + +/* +* Build [0, 2)@200 writ, [2, 4)@500 writ, [4, 7)@202 writ, and +* [8, 10)@600 unwrit. Collapsing [2, 4) frees [2, 4)@500, shifts +* [4, 7)@202 left to [2, 5)@202 where it merges with [0, 2)@200 into +* [0, 5)@200, and shifts [8, 10)@600 left to [6, 8)@600. +*/ +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,2 ,200 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,2 ,2 ,500 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,4 ,3 ,202 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,8 ,2 ,600 , true,0 ),0 ); + + ret =ext4_fallocate (&file,FALLOC_FL_COLLAPSE_RANGE , +2 *4096 ,2 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, k_ctx.total_freed_blocks,2UL ); +KUNIT_EXPECT_EQ (test, inode->i_size,8LL *4096 ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,8LL *4096 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (ext_inode_hdr (inode)->eh_entries),2 ); +ext_expect_extent_at (test, inode,0 ,5 ,200 , false); +ext_expect_extent_at (test, inode,6 ,2 ,600 , true); +} + +/* +* Verify ext4_insert_range() alignment, EOF, and s_maxbytes checks, as well as +* mid-extent splitting, right-shift of trailing extents, and i_size growth. +*/ +static void test_insert_range (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct file file; +long ret; + +ext_setup_range_test (test, inode, &file); + inode->i_size =10LL *4096 ; +EXT4_I (inode)->i_disksize =10LL *4096 ; + +/* Block-unaligned offset or length -> -EINVAL */ + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,1024 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,4096 ,1024 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + +/* Non-extent inode -> -EOPNOTSUPP */ +ext4_clear_inode_flag (inode,EXT4_INODE_EXTENTS ); + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,0 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EOPNOTSUPP ); +ext4_set_inode_flag (inode,EXT4_INODE_EXTENTS ); + +/* Offset at or beyond i_size -> -EINVAL */ + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,10 *4096 ,4096 ); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + +/* Length exceeding s_maxbytes - i_size -> -EFBIG */ + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE ,4096 , +round_down (inode->i_sb->s_maxbytes,4096 )); +KUNIT_EXPECT_EQ (test, ret, -EFBIG ); + +/* +* Insert 3-block hole at lblk 2 inside [0, 6)@200 writ with trailing +* [8, 10)@400 unwrit: produces [0, 2)@200 writ, [5, 9)@202 writ, and +* [11, 13)@400 unwrit, with i_size = 13 blocks. +*/ +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,6 ,200 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,8 ,2 ,400 , true,0 ),0 ); + + ret =ext4_fallocate (&file,FALLOC_FL_INSERT_RANGE , +2 *4096 ,3 *4096 ); +KUNIT_ASSERT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, inode->i_size,13LL *4096 ); +KUNIT_EXPECT_EQ (test,EXT4_I (inode)->i_disksize,13LL *4096 ); +KUNIT_EXPECT_EQ (test,le16_to_cpu (ext_inode_hdr (inode)->eh_entries),3 ); +ext_expect_extent_at (test, inode,0 ,2 ,200 , false); +ext_expect_extent_at (test, inode,5 ,4 ,202 , false); +ext_expect_extent_at (test, inode,11 ,2 ,400 , true); +} + +/* +* Verify unwritten-to-written IO completion conversion helpers: +* ext4_convert_unwritten_extents(), ext4_convert_unwritten_extents_atomic() +* across a split unwritten mapping, and ext4_convert_unwritten_io_end_vec(). +*/ +static void test_convert_unwritten_extents_and_io_end (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +ext4_io_end_t io_end = {}; +struct ext4_io_end_vec vec1 = {}, vec2 = {}; +ext4_lblk_t converted =0 ; +int err; + +/* 1. ext4_convert_unwritten_extents() on middle of unwritten extent */ +ext_setup_range_test (test, inode,NULL ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,6 ,200 , true,0 ),0 ); + + err =ext4_convert_unwritten_extents (NULL , inode,2 *4096 ,2 *4096 , + &converted); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, converted,2U ); +ext_expect_extent_at (test, inode,0 ,2 ,200 , true); +ext_expect_extent_at (test, inode,2 ,2 ,202 , false); +ext_expect_extent_at (test, inode,4 ,2 ,204 , true); + +/* 2. ext4_convert_unwritten_extents_atomic() across split unwritten */ +ext_setup_range_test (test, inode,NULL ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,2 ,200 , true,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,2 ,3 ,300 , true,0 ),0 ); + + err =ext4_convert_unwritten_extents_atomic (NULL , inode,0 ,5 *4096 ); +KUNIT_ASSERT_EQ (test, err,0 ); +ext_expect_extent_at (test, inode,0 ,2 ,200 , false); +ext_expect_extent_at (test, inode,2 ,3 ,300 , false); + +/* 3. ext4_convert_unwritten_io_end_vec() across multiple vecs */ +ext_setup_range_test (test, inode,NULL ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,8 ,200 , true,0 ),0 ); + + io_end.inode = inode; +INIT_LIST_HEAD (&io_end.list_vec); + vec1.offset =1 *4096 ; + vec1.size =2 *4096 ; + vec2.offset =5 *4096 ; + vec2.size =2 *4096 ; +list_add_tail (&vec1.list, &io_end.list_vec); +list_add_tail (&vec2.list, &io_end.list_vec); + + err =ext4_convert_unwritten_io_end_vec (NULL , &io_end); +KUNIT_ASSERT_EQ (test, err,0 ); +ext_expect_extent_at (test, inode,0 ,1 ,200 , true); +ext_expect_extent_at (test, inode,1 ,2 ,201 , false); +ext_expect_extent_at (test, inode,3 ,2 ,203 , true); +ext_expect_extent_at (test, inode,5 ,2 ,205 , false); +ext_expect_extent_at (test, inode,7 ,1 ,207 , true); +} + +/* +* Verify ext4_fiemap() (range checks, FIEMAP_FLAG_CACHE precaching, data and +* external xattr reporting) and ext4_get_es_cache() (flag checks, precaching, +* and reporting mapped + delayed status extents). +*/ +static void test_ext_fiemap_and_get_es_cache (struct kunit *test) +{ +struct inode *inode = &k_ctx.k_ei->vfs_inode; +struct fiemap_extent_info fieinfo = {}; +struct extent_status es = {}; +int err; + +ext_setup_range_test (test, inode,NULL ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,3 ,200 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,6 ,2 ,300 , true,0 ),0 ); + inode->i_size =10LL *4096 ; +EXT4_I (inode)->i_disksize =10LL *4096 ; + +/* Zero-length FIEMAP -> -EINVAL */ + err =ext4_fiemap (inode, &fieinfo,0 ,0 ); +KUNIT_EXPECT_EQ (test, err, -EINVAL ); + +/* Start past maxbytes on non-extent inode -> -EFBIG */ +ext4_clear_inode_flag (inode,EXT4_INODE_EXTENTS ); + err =ext4_fiemap (inode, &fieinfo, +EXT4_SB (inode->i_sb)->s_bitmap_maxbytes +4096 ,4096 ); +KUNIT_EXPECT_EQ (test, err, -EFBIG ); +ext4_set_inode_flag (inode,EXT4_INODE_EXTENTS ); + +/* Count-only data FIEMAP with FIEMAP_FLAG_CACHE populates ES cache */ +memset (&fieinfo,0 ,sizeof (fieinfo)); + fieinfo.fi_flags =FIEMAP_FLAG_CACHE ; + err =ext4_fiemap (inode, &fieinfo,0 ,10 *4096 ); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_flags &FIEMAP_FLAG_CACHE ,0U ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,2U ); +KUNIT_EXPECT_EQ (test,ext4_es_lookup_extent (inode,0 ,NULL , &es,NULL ), +1 ); + +/* FIEMAP_FLAG_XATTR with no xattrs vs external i_file_acl block */ +memset (&fieinfo,0 ,sizeof (fieinfo)); + fieinfo.fi_flags =FIEMAP_FLAG_XATTR ; + err =ext4_fiemap (inode, &fieinfo,0 ,4096 ); +KUNIT_EXPECT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,0U ); + +EXT4_I (inode)->i_file_acl =750 ; +memset (&fieinfo,0 ,sizeof (fieinfo)); + fieinfo.fi_flags =FIEMAP_FLAG_XATTR ; + err =ext4_fiemap (inode, &fieinfo,0 ,4096 ); +EXT4_I (inode)->i_file_acl =0 ; +KUNIT_EXPECT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,1U ); + +/* ext4_get_es_cache: unsupported flag -> -EBADR, len == 0 -> -EINVAL */ +memset (&fieinfo,0 ,sizeof (fieinfo)); + fieinfo.fi_flags =FIEMAP_FLAG_XATTR ; + err =ext4_get_es_cache (inode, &fieinfo,0 ,4096 ); +KUNIT_EXPECT_EQ (test, err, -EBADR ); + +memset (&fieinfo,0 ,sizeof (fieinfo)); + err =ext4_get_es_cache (inode, &fieinfo,0 ,0 ); +KUNIT_EXPECT_EQ (test, err, -EINVAL ); + +/* +* Populate ES tree with written, hole, delayed, and unwritten entries +* and verify ext4_get_es_cache reports all 4 entries. +*/ +down_write (&EXT4_I (inode)->i_data_sem); +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +ext4_es_insert_extent (inode,0 ,3 ,200 ,EXTENT_STATUS_WRITTEN ,0 ); +ext4_es_insert_extent (inode,3 ,1 , ~0 ,EXTENT_STATUS_HOLE ,0 ); +ext4_es_insert_delayed_extent (inode,4 ,2 , false, false); +ext4_es_insert_extent (inode,6 ,2 ,300 ,EXTENT_STATUS_UNWRITTEN ,0 ); +up_write (&EXT4_I (inode)->i_data_sem); + +memset (&fieinfo,0 ,sizeof (fieinfo)); + err =ext4_get_es_cache (inode, &fieinfo,0 ,10 *4096 ); +KUNIT_ASSERT_EQ (test, err,0 ); +KUNIT_EXPECT_EQ (test, fieinfo.fi_extents_mapped,4U ); + +/* +* Build a depth-1 tree (5 discontiguous extents), clear ES cache, and +* verify FIEMAP_FLAG_CACHE precaches external leaf extents + holes. +*/ +ext_setup_range_test (test, inode,NULL ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,0 ,1 ,200 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,2 ,1 ,202 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,4 ,1 ,204 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,6 ,1 ,206 , false,0 ),0 ); +KUNIT_ASSERT_EQ (test,ext_insert_one (inode,8 ,1 ,208 , false,0 ),0 ); + inode->i_size =10LL *4096 ; +EXT4_I (inode)->i_disksize =10LL *4096 ; + +down_write (&EXT4_I (inode)->i_data_sem); +ext4_es_remove_extent (inode,0 ,EXT_MAX_BLOCKS ); +up_write (&EXT4_I (inode)->i_data_sem); + +memset (&fieinfo,0 ,sizeof (fieinfo)); + fieinfo.fi_flags =FIEMAP_FLAG_CACHE ; + err =ext4_get_es_cache (inode, &fieinfo,0 ,10 *4096 ); +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 ); +} +static const struct kunit_ext_test_param test_split_convert_params[] = {/* unwrit to writ splits */ { .desc ="split unwrit extent to 2 extents and convert 1st half writ" ,
@@ -3001,6 +3508,12 @@ static struct kunit_case extents_test_cases[] = {KUNIT_CASE (test_clu_mapped),KUNIT_CASE (test_ext_credits_calculation),KUNIT_CASE (test_ext_fast_commit_replay), +KUNIT_CASE (test_fallocate_modes_and_prealloc), +KUNIT_CASE (test_zero_range_and_write_zeroes), +KUNIT_CASE (test_collapse_range), +KUNIT_CASE (test_insert_range), +KUNIT_CASE (test_convert_unwritten_extents_and_io_end), + KUNIT_CASE(test_ext_fiemap_and_get_es_cache), {} };
fs/ext4/extents.c +6 -0
@@ -5034,6 +5034,7 @@ long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)inode_unlock (inode);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fallocate);/* * This function converts a range of blocks to written extents. The caller of
@@ -5121,6 +5122,7 @@ int ext4_convert_unwritten_extents_atomic(handle_t *handle, struct inode *inode,return ret >0 ? ret2 : ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_convert_unwritten_extents_atomic);/* * This function convert a range of blocks to written extents
@@ -5202,6 +5204,7 @@ int ext4_convert_unwritten_extents(handle_t *handle, struct inode *inode,return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_convert_unwritten_extents);int ext4_convert_unwritten_io_end_vec (handle_t *handle,ext4_io_end_t *io_end) {
@@ -5233,6 +5236,7 @@ int ext4_convert_unwritten_io_end_vec(handle_t *handle, ext4_io_end_t *io_end)return ret <0 ? ret : err; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_convert_unwritten_io_end_vec);static int ext4_iomap_xattr_fiemap (struct inode *inode,struct iomap *iomap) {
@@ -5345,6 +5349,7 @@ int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,inode_unlock_shared (inode);return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fiemap);int ext4_get_es_cache (struct inode *inode,struct fiemap_extent_info *fieinfo,__u64 start,__u64 len)
@@ -5392,6 +5397,7 @@ int ext4_get_es_cache(struct inode *inode, struct fiemap_extent_info *fieinfo,*/ return ext4_fill_es_cache_info (inode, start_blk, len_blks, fieinfo); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_es_cache);/* * ext4_ext_shift_path_extents:
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 23/27] ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] ext4: uninitialized invalidate_lock in ext_init_mock_inode() - [Low] ext4: use-after-free of…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] ext4: uninitialized invalidate_lock in ext_init_mock_inode()
- [Low] ext4: use-after-free of sb->s_bdev after deactivate_super() in extents_kunit_exit()
- [Low] ext4: i_data_sem and path leak on assertion abort in ext_expect_extent_at()
--
commit 0bbdba01f4f2a820793844a83a44fb01144fcc50
Author: Theodore Ts'o <[email protected]>
ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations
This commit expands the ext4 extents KUnit test suite to cover ext4_fallocate(), ext4_zero_range(), ext4_collapse_range(), ext4_insert_range(), unwritten extent conversion helpers, ext4_fiemap(), and ext4_get_es_cache().
Quoted 4 lines
fs/ext4/extents-test.c +0
-0
[ ... ]
Quoted 7 lines
fs/ext4/extents-test.c +1
-1@@ -200,20 +210,29 @@ static void ext_init_mock_inode(struct ext4_inode_info *ei, inode->i_sb = sb; inode->i_ino = ino; inode->i_mode =S_IFREG |0644 ; +set_nlink (inode,1 ); inode->i_blkbits = sb->s_blocksize_bits; - inode->i_flags |=S_NOQUOTA ;
fs/ext4/extents-test.c static void ext_init_mock_inode(struct ext4_inode_info *ei, · line 223
Quoted 10 lines
fs/ext4/extents-test.c +4
-1+ inode->i_flags |=S_NOQUOTA |S_NOSEC ; inode->i_mapping = &inode->i_data; +inode_set_iversion (inode,1 );spin_lock_init (&inode->i_lock);init_rwsem (&inode->i_rwsem); -init_rwsem (&inode->i_data.invalidate_lock); +address_space_init_once (&inode->i_data); + inode->i_data.host = inode;inode_state_set_raw (inode,I_DIRTY_SYNC |I_DIRTY_DATASYNC );
[Severity: Medium]
Does replacing init_rwsem(&inode->i_data.invalidate_lock) with address_space_init_once(&inode->i_data) leave invalidate_lock uninitialized?
address_space_init_once() zeroes inode->i_data and initializes only i_pages, i_mmap_rwsem, i_private_lock, and i_mmap; in the VFS, invalidate_lock is initialized separately in inode_init_always_gfp(). When the new fallocate tests call ext4_fallocate() with punch hole, zero range, collapse range, or insert range, filemap_invalidate_lock() acquires this zeroed rw_semaphore, which triggers lockdep or CONFIG_DEBUG_RWSEMS warnings and deadlocks on CONFIG_PREEMPT_RT kernels. Keeping init_rwsem(&inode->i_data.invalidate_lock) after address_space_init_once() avoids this.
[ ... ]
fs/ext4/extents-test.c static void extents_kunit_exit(struct kunit *test) · line 292
Quoted 8 lines
fs/ext4/extents-test.c +1
-0@@ -267,6 +286,7 @@ static void extents_kunit_exit(struct kunit *test)kfree (k_ctx.meta_blocks);kfree (sbi->s_es); +kfree (sb->s_bdev->bd_queue);kfree (sb->s_bdev->bd_mapping);kfree (sb->s_bdev);kfree (sbi);
[Severity: Low]
Can dereferencing sb->s_bdev here use sb after it has been freed?
deactivate_super(sb) is called just above this hunk, which drops the final reference on sb and schedules its destruction via RCU and destroy_super_work(), unlike the error path in extents_kunit_init() which frees sb->s_bdev->bd_queue, sb->s_bdev->bd_mapping, and sb->s_bdev before deactivating the superblock.
[ ... ]
Quoted 11 lines
fs/ext4/extents-test.c +11
-0+static void ext_expect_extent_at (struct kunit *test,struct inode *inode, +ext4_lblk_t lblk,unsigned short exp_len, +ext4_fsblk_t exp_pblk,bool exp_unwritten) +{ +struct ext4_ext_path *path; +struct ext4_extent *ex; + +down_read (&EXT4_I (inode)->i_data_sem); + path =ext4_find_extent (inode, lblk,NULL ,EXT4_EX_NOCACHE ); +KUNIT_ASSERT_FALSE (test,IS_ERR (path)); + ex = path[path->p_depth].p_ext;
fs/ext4/extents-test.c static void test_ext_fast_commit_replay(struct kunit *test) · line 2568
Quoted 10 lines
fs/ext4/extents-test.c +10
-0+KUNIT_ASSERT_NOT_NULL (test, ex); + +KUNIT_EXPECT_EQ (test,le32_to_cpu (ex->ee_block), lblk); +KUNIT_EXPECT_EQ (test,ext4_ext_get_actual_len (ex), exp_len); +KUNIT_EXPECT_EQ (test,ext4_ext_pblock (ex), exp_pblk); +KUNIT_EXPECT_EQ (test, !!ext4_ext_is_unwritten (ex), exp_unwritten); + +ext4_free_ext_path (path); +up_read (&EXT4_I (inode)->i_data_sem); +}
[Severity: Low]
If KUNIT_ASSERT_FALSE() or KUNIT_ASSERT_NOT_NULL() fails in ext_expect_extent_at(), does the test abort with EXT4_I(inode)->i_data_sem still held for read and path leaked?
Because KUNIT_ASSERT_* immediately terminates the test kthread, extents_kunit_exit() -> ext_cleanup_inode() will then deadlock on down_write(&ei->i_data_sem).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
Theodore Ts'o
maintainerPATCH 24/27 ext4: add KUnit tests for fs/ext4/fsmap.c
In reply to Theodore Ts'oAdd KUnit test suite ext4_fsmap_test in fs/ext4/fsmap-test.c covering FS_IOC_GETFSMAP reverse-mapping queries in fs/ext4/fsmap.c:
- ext4_fsmap_from_internal() and ext4_fsmap_to_internal() block/byte conversions across 1K, 4K, and 64K block sizes
- ext4_getfsmap() validation of flags, device IDs, inverted keys, out-of-range physical offsets, and missing group descriptors
- fixed per-group metadata synthesis (superblock, GDT, reserved GDT, block bitmap, inode bitmap, inode table), free extents, and EXT4_FMR_OWN_UNKNOWN gaps in the middle and at EOFS
- flex_bg adjacent fixed-metadata merging and cross-group free-extent coalescing via gfi_lastfree
- 1K s_first_data_block offset handling, bigalloc cluster scaling, and META_BG reserved-GDT suppression
- count-only queries, bounded continuation-key pagination, formatter abort propagation, and external journal device reporting
--- fs/ext4/Makefile | 2 +- fs/ext4/fsmap-test.c | 787 +++++++++++++++++++++++++++++++++++++++++++ fs/ext4/fsmap.c | 3 + fs/ext4/mballoc.c | 3 + 4 files changed, 794 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/fsmap-test.c
fs/ext4/Makefile +1 -1
@@ -23,7 +23,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ - indirect-test.o + indirect-test.o fsmap-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/fsmap-test.c new file +787 -0
787 lines not on this page · raw message
fs/ext4/fsmap.c +3 -0
@@ -26,6 +26,7 @@ void ext4_fsmap_from_internal(struct super_block *sb, struct fsmap *dest, dest->fmr_reserved[1 ] =0 ; dest->fmr_reserved[2 ] =0 ; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fsmap_from_internal);/* Convert an fsmap to an ext4_fsmap. */ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest,
@@ -37,6 +38,7 @@ void ext4_fsmap_to_internal(struct super_block *sb, struct ext4_fsmap *dest, dest->fmr_owner = src->fmr_owner; dest->fmr_length = src->fmr_length >> sb->s_blocksize_bits; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_fsmap_to_internal);/* getfsmap query state */ struct ext4_getfsmap_info {
@@ -790,3 +792,4 @@ int ext4_getfsmap(struct super_block *sb, struct ext4_fsmap_head *head, head->fmh_oflags =FMH_OF_DEV_T ;return error; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_getfsmap);
fs/ext4/mballoc.c +3 -0
@@ -7151,6 +7151,9 @@ ext4_mballoc_query_range(struct ext4_buddy e4b;int error; +KUNIT_STATIC_STUB_REDIRECT (ext4_mballoc_query_range, sb, group, first, + end, meta_formatter, formatter, priv); + error =ext4_mb_load_buddy (sb, group, &e4b);if (error)return error;
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 24/27] ext4: add KUnit tests for fs/ext4/fsmap.c
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] ext4: per-CPU disk_stats leak on assert abort in fsmap_create_ctx() - [Low] ext4: unused fail_err…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] ext4: per-CPU disk_stats leak on assert abort in fsmap_create_ctx()
- [Low] ext4: unused fail_err field in fsmap_rec_sink and fsmap_collect_cb()
--
commit 26245fe40968f50951fa0187b785c405d62e3f12
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/fsmap.c
This commit adds a KUnit test suite covering FS_IOC_GETFSMAP reverse-mapping queries in fs/ext4/fsmap.c.
Quoted 6 lines
fs/ext4/fsmap-test.c new file +0
-0@@ -0,0 +1,787 @@
[ ... ]
Quoted 6 lines
fs/ext4/fsmap-test.c new file +6
-0+struct fsmap_rec_sink { +struct ext4_fsmap recs[FSMAP_TEST_MAX_RECS ]; +unsigned int count; +unsigned int abort_after; +int fail_err; +};
[ ... ]
fs/ext4/fsmap-test.c line 161
Quoted 6 lines
fs/ext4/fsmap-test.c new file +6
-0+static int fsmap_collect_cb (struct ext4_fsmap *fmr,void *priv) +{ +struct fsmap_rec_sink *sink = priv; + +if (sink->fail_err) +return sink->fail_err;
[Severity: Low]
Nothing in this file sets sink->fail_err, leaving the field and this check in fsmap_collect_cb() unused.
[ ... ]
Quoted 43 lines
fs/ext4/fsmap-test.c new file +43
-0+static struct fsmap_test_ctx *fsmap_create_ctx (struct kunit *test, +unsigned int blocksize_bits, +unsigned int cluster_bits, +ext4_group_t groups_count, +ext4_grpblk_t blocks_per_group) +{ +struct fsmap_test_ctx *ctx; +struct fs_context *fc; +struct super_block *sb; +struct ext4_sb_info *sbi; +unsigned int blocksize =1U << blocksize_bits; +ext4_fsblk_t bofs = (blocksize ==1024 ) ?1 :0 ; +int err; + + ctx =kunit_kzalloc (test,sizeof (*ctx),GFP_KERNEL ); +KUNIT_ASSERT_NOT_NULL (test, ctx); + +inode_init_once (&ctx->data_bdev.vfs_inode); +address_space_init_once (&ctx->data_bdev.vfs_inode.i_data); + ctx->data_bdev.vfs_inode.i_data.host = &ctx->data_bdev.vfs_inode; + ctx->data_bdev.bdev.bd_dev =FSMAP_TEST_DATADEV ; + ctx->data_bdev.bdev.bd_mapping = &ctx->data_bdev.vfs_inode.i_data; + ctx->data_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); +KUNIT_ASSERT_NOT_NULL (test, ctx->data_bdev.bdev.bd_stats); + +inode_init_once (&ctx->log_bdev.vfs_inode); +address_space_init_once (&ctx->log_bdev.vfs_inode.i_data); + ctx->log_bdev.vfs_inode.i_data.host = &ctx->log_bdev.vfs_inode; + ctx->log_bdev.bdev.bd_dev =FSMAP_TEST_LOGDEV ; + ctx->log_bdev.bdev.bd_mapping = &ctx->log_bdev.vfs_inode.i_data; + ctx->log_bdev.bdev.bd_stats = alloc_percpu(struct disk_stats); +KUNIT_ASSERT_NOT_NULL (test, ctx->log_bdev.bdev.bd_stats); + ctx->log_bdev_file.f_mapping = &ctx->log_bdev.vfs_inode.i_data; + + sbi = &ctx->sbi; +INIT_WORK (&sbi->s_sb_upd_work, fsmap_noop_work); +timer_setup (&sbi->s_err_report, fsmap_noop_timer,0 ); +spin_lock_init (&sbi->s_error_lock); +spin_lock_init (&sbi->s_bdev_wb_lock); +ratelimit_state_init (&sbi->s_err_ratelimit_state, +DEFAULT_RATELIMIT_INTERVAL , +DEFAULT_RATELIMIT_BURST ); +
fs/ext4/fsmap-test.c line 249
Quoted 10 lines
fs/ext4/fsmap-test.c new file +10
-0+ fc =fs_context_for_mount (&fsmap_test_fs_type,0 ); +KUNIT_ASSERT_FALSE (test,IS_ERR (fc)); + sb =sget_fc (fc,NULL , fsmap_test_set_super); +put_fs_context (fc); +KUNIT_ASSERT_FALSE (test,IS_ERR (sb)); +up_write (&sb->s_umount); + + ctx->sb = sb; + err =kunit_add_action_or_reset (test, fsmap_cleanup_ctx, ctx); +KUNIT_ASSERT_EQ (test, err,0 );
[Severity: Low]
Does this leak the per-CPU bd_stats allocations if one of the assertions before kunit_add_action_or_reset() aborts the test? Registering fsmap_cleanup_ctx() before calling alloc_percpu() would ensure they are freed on early assertion failure.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
Theodore Ts'o
maintainerPATCH 25/27 ext4: add KUnit tests for fs/ext4/move_extent.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_move_extent_test) covering online extent swapping and validation helpers in fs/ext4/move_extent.c:
- Ordered i_data_sem lock acquisition/release in ext4_double_down_write_data_sem() and ext4_double_up_write_data_sem()
- File, feature, and mode checks in mext_check_validity() (same inode, cross-sb, non-regular, bigalloc, DAX, data journaling, encrypted, non-extent, SUID/SGID, immutable/append, swapfile, quota, zero size)
- Sub-page alignment, EXT_MAX_BLOCKS bounds, and EOF clamping in mext_check_adjust_range()
- End-to-end ext4_move_extents() across origin/donor holes, unwritten extent moves, written MEXT_COPY_DATA with extent splitting and page cache preservation, unwritten-origin zeroing, and -EBUSY release
--- fs/ext4/Makefile | 3 +- fs/ext4/ext4.h | 8 + fs/ext4/move_extent-test.c | 997 +++++++++++++++++++++++++++++++++++++ fs/ext4/move_extent.c | 21 +- 4 files changed, 1026 insertions(+), 3 deletions(-) create mode 100644 fs/ext4/move_extent-test.c
fs/ext4/Makefile +2 -1
@@ -23,7 +23,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ block_validity-test.o super-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ - indirect-test.o fsmap-test.o + indirect-test.o fsmap-test.o \ + move_extent-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +8 -0
@@ -4180,6 +4180,14 @@ extern void ext4_double_up_write_data_sem(struct inode *orig_inode,extern int ext4_move_extents (struct file *o_filp,struct file *d_filp,__u64 start_orig,__u64 start_donor,__u64 len,__u64 *moved_len); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_mext_check_validity_test (struct inode *orig_inode, +struct inode *donor_inode); +extern int ext4_mext_check_adjust_range_test (struct inode *orig_inode, +struct inode *donor_inode, +__u64 orig_start, +__u64 donor_start,__u64 *len); +#endif /* page-io.c */ extern int __init ext4_init_pageio (void );
fs/ext4/move_extent-test.c new file +997 -0
997 lines not on this page · raw message
fs/ext4/move_extent.c +19 -2
@@ -40,6 +40,7 @@ ext4_double_down_write_data_sem(struct inode *first, struct inode *second)down_write_nested (&EXT4_I (first)->i_data_sem,I_DATA_SEM_OTHER ); } } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_down_write_data_sem);/** * ext4_double_up_write_data_sem - Release two inodes' write lock of i_data_sem
@@ -55,6 +56,7 @@ ext4_double_up_write_data_sem(struct inode *orig_inode,up_write (&EXT4_I (orig_inode)->i_data_sem);up_write (&EXT4_I (donor_inode)->i_data_sem); } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_up_write_data_sem);/* Grab and lock folio on both @inode1 and @inode2 by inode order. */ static int mext_folio_double_lock(struct inode *inode1, struct inode *inode2,
@@ -656,8 +658,23 @@ int ext4_move_extents(struct file *o_filp, struct file *d_filp, __u64 orig_blk,unlock_two_nondirectories (orig_inode, donor_inode);return ret; } +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_move_extents);#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_down_write_data_sem); -EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_double_up_write_data_sem); +int ext4_mext_check_validity_test (struct inode *orig_inode, +struct inode *donor_inode) +{ +return mext_check_validity (orig_inode, donor_inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mext_check_validity_test); + +int ext4_mext_check_adjust_range_test (struct inode *orig_inode, +struct inode *donor_inode, +__u64 orig_start,__u64 donor_start, +__u64 *len) +{ +return mext_check_adjust_range (orig_inode, donor_inode, orig_start, + donor_start, len); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_mext_check_adjust_range_test);#endif
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 25/27] ext4: add KUnit tests for fs/ext4/move_extent.c
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] ext4: 64KB page failure in test_mext_check_adjust_range() - [Medium] ext4: sub-folio dirty buffer…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] ext4: 64KB page failure in test_mext_check_adjust_range()
- [Medium] ext4: sub-folio dirty buffer -EBUSY in move_extent-test.c on
Quoted 1 line
4KB pages
--
commit abdff1b8eb818ad1bc77ee7f502a090b450df395
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/move_extent.c
This commit adds a KUnit test suite covering lock ordering, validity and range checks, and extent swapping in fs/ext4/move_extent.c.
Quoted 5 lines
fs/ext4/move_extent-test.c new file +0
-0
[ ... ]
Quoted 13 lines
fs/ext4/move_extent-test.c new file +13
-0+static void test_mext_check_adjust_range (struct kunit *test) +{ +struct mext_test_ctx *ctx =mext_setup_ctx (test); +struct inode *orig = ctx->orig_inode; +struct inode *donor = ctx->donor_inode; +__u64 len; +int ret; + +/* Sub-page block alignment check when blocksize (1024) < PAGE_SIZE */ + orig->i_blkbits =10 ; + donor->i_blkbits =10 ; +i_size_write (orig,32 *1024 ); +i_size_write (donor,32 *1024 );
fs/ext4/move_extent-test.c line 764
Quoted 10 lines
fs/ext4/move_extent-test.c new file +10
-0+ + len =4 ; + ret =ext4_mext_check_adjust_range_test (orig, donor,1 ,2 , &len); +KUNIT_EXPECT_EQ (test, ret, -EINVAL ); + + len =4 ; + ret =ext4_mext_check_adjust_range_test (orig, donor,1 , +1 + (PAGE_SIZE >>10 ), &len); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, len,4ULL );
[Severity: Medium]
Does this sub-page alignment check fail on kernels with 64KB pages?
With i_blkbits set to 10 and i_size set to 32KB, donor_eof is 32 blocks, while donor_start = 1 + (PAGE_SIZE >> 10) evaluates to 65 when PAGE_SIZE is 65536. mext_check_adjust_range() sees donor_eof <= donor_start, clamps *len to 0, and returns -EINVAL instead of 0. Sizing orig and donor relative to PAGE_SIZE (for example, max_t(loff_t, 32 * 1024, 4 * PAGE_SIZE)) would avoid this.
[ ... ]
Quoted 24 lines
fs/ext4/move_extent-test.c new file +24
-0+static void test_move_extents_written_copy_data_and_split (struct kunit *test) +{ +struct mext_test_ctx *ctx =mext_setup_ctx (test); +struct inode *orig = ctx->orig_inode; +struct inode *donor = ctx->donor_inode; +ext4_lblk_t lblk; +__u64 moved_len =0 ; +int ret; + +/* +* orig: [0, 6) written -> pblk 400..405, uptodate folios pre-filled +* donor: [1, 2) written -> pblk 501, [2, 3) hole, +* [3, 5) unwritten -> pblk 503..504 +* +* Moving [1, 5) exercises MEXT_COPY_DATA, left/right extent splits on +* orig, donor hole skipping at lblk 2, written preservation on orig, +* mark_unwritten=1 on donor, and page cache data preservation. +*/ +i_size_write (orig,6 *MEXT_TEST_BLK_SIZE ); +EXT4_I (orig)->i_disksize =6 *MEXT_TEST_BLK_SIZE ; +i_size_write (donor,6 *MEXT_TEST_BLK_SIZE ); +EXT4_I (donor)->i_disksize =6 *MEXT_TEST_BLK_SIZE ; + +mext_insert_extent (test, orig,0 ,6 ,400 , false);
fs/ext4/move_extent-test.c line 885
Quoted 10 lines
fs/ext4/move_extent-test.c new file +10
-0+mext_insert_extent (test, donor,1 ,1 ,501 , false); +mext_insert_extent (test, donor,3 ,2 ,503 , true); + +for (lblk =0 ; lblk <6 ; lblk++) +mext_populate_folio_block (test, orig, lblk,0xA0 + lblk); + + ret =ext4_move_extents (&ctx->orig_file, &ctx->donor_file,1 ,1 ,4 , + &moved_len); +KUNIT_EXPECT_EQ (test, ret,0 ); +KUNIT_EXPECT_EQ (test, moved_len,3ULL );
[Severity: Medium]
Does ext4_move_extents() fail with -EBUSY here when PAGE_SIZE > 4096?
With a 4KB block size on 16KB or 64KB page kernels, logical blocks 1 and 3 share folio 0 in orig->i_mapping. Moving lblk 1 via MEXT_COPY_DATA calls mext_folio_mkwrite() -> block_commit_write(), which attaches buffer_heads to orig's folio 0 and marks lblk 1's buffer dirty. After skipping the donor hole at lblk 2, mext_move_extent() tries to move lblk 3..4 in the same folio and calls filemap_release_folio(folio[0], 0) -> ext4_release_folio() -> try_to_free_buffers(), which refuses to drop the dirty buffer from lblk 1 and aborts the move with -EBUSY and moved_len = 1.
Similarly, in test_move_extents_unwritten_orig_and_ebusy(), moving lblk 0..1 leaves dirty buffers on orig's folio 0 when PAGE_SIZE >= 16384, so the subsequent move of lblk 2 fails filemap_release_folio() on orig before reaching the PG_checked donor_folio under test.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
Theodore Ts'o
maintainerPATCH 26/27 ext4: add KUnit tests for fs/ext4/mmp.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_mmp_test) covering multi-mount protection checksums, block I/O validation, and mount state transitions in fs/ext4/mmp.c:
- CRC32C generation and verification in ext4_mmp_csum_set() and ext4_mmp_csum_verify() with and without METADATA_CSUM
- Block read/write error handling, magic validation (-EFSCORRUPTED), CRC mismatch handling (-EFSBADCRC), and buffer cleanup in read_mmp_block() and write_mmp_block()
- ext4_multi_mount_protect() validation of out-of-range MMP blocks, EXT4_MMP_SEQ_FSCK rejection (-EBUSY), EXT4_MMP_SEQ_CLEAN claim and ext4_stop_mmpd() teardown, active/racing node sequence conflicts, check_interval clamping, interrupted waits (-ETIMEDOUT), and kthread startup failure
--- fs/ext4/Makefile | 2 +- fs/ext4/ext4.h | 20 +- fs/ext4/mmp-test.c | 661 +++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/mmp.c | 117 ++++++-- 4 files changed, 770 insertions(+), 30 deletions(-) create mode 100644 fs/ext4/mmp-test.c
fs/ext4/Makefile +1 -1
@@ -24,7 +24,7 @@ ext4-test-objs += inode-test.o mballoc-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ indirect-test.o fsmap-test.o \ - move_extent-test.o + move_extent-test.o mmp-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/ext4.h +18 -2
@@ -4207,9 +4207,25 @@ extern struct ext4_io_end_vec *ext4_last_io_end_vec(ext4_io_end_t *io_end);/* mmp.c */ extern int ext4_multi_mount_protect (struct super_block *,ext4_fsblk_t ); - -/* mmp.c */ extern void ext4_stop_mmpd (struct ext4_sb_info *sbi); +extern int ext4_mmp_submit_write (struct buffer_head *bh); +extern int ext4_mmp_load_bh (struct super_block *sb,struct buffer_head **bh, +ext4_fsblk_t mmp_block); +extern long ext4_mmp_wait_timeout (long timeout); +extern struct task_struct *ext4_mmp_run_thread (struct super_block *sb, +const char *bdevname, +int bdevname_len); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_mmp_csum_verify_test (struct super_block *sb, +struct mmp_struct *mmp); +extern void ext4_mmp_csum_set_test (struct super_block *sb, +struct mmp_struct *mmp); +extern int ext4_read_mmp_block_test (struct super_block *sb, +struct buffer_head **bh, +ext4_fsblk_t mmp_block); +extern int ext4_write_mmp_block_test (struct super_block *sb, +struct buffer_head *bh); +#endif /* verity.c */ extern const struct fsverity_operations ext4_verityops;
fs/ext4/mmp-test.c new file +661 -0
661 lines not on this page · raw message
fs/ext4/mmp.c +90 -27
184 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 26/27] ext4: add KUnit tests for fs/ext4/mmp.c
Sashiko has reviewed this patch and found no issues.
Quoted 15 lines
Add a KUnit test suite (
ext4_mmp_test) covering multi-mount protection checksums, block I/O validation, and mount state transitions infs/ext4/mmp.c:- CRC32C generation and verification in
ext4_mmp_csum_set()andext4_mmp_csum_verify()with and withoutMETADATA_CSUM
- Block read/write error handling, magic validation (-EFSCORRUPTED), CRC mismatch handling (-EFSBADCRC), and buffer cleanup inread_mmp_block()andwrite_mmp_block()
-ext4_multi_mount_protect()validation of out-of-range MMP blocks,EXT4_MMP_SEQ_FSCKrejection (-EBUSY),EXT4_MMP_SEQ_CLEANclaim andext4_stop_mmpd()teardown, active/racing node sequence conflicts,check_intervalclamping, interrupted waits (-ETIMEDOUT), and kthread startup failure
Quoted 1 line
Signed-off-by Theodore Ts'o <[email protected]>
Sashiko has reviewed this patch and found no issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26
Theodore Ts'o
maintainerPATCH 27/27 ext4: add KUnit tests for fs/ext4/dir.c
In reply to Theodore Ts'oAdd a KUnit test suite (ext4_dir_test) in fs/ext4/dir-test.c covering directory entry validation, hash-cookie helpers, directory llseek, and both linear and HTree directory iteration in fs/ext4/dir.c:
- __ext4_check_dir_entry() and ext4_check_all_de() validation across valid blocks (including fake '.', '..', and metadata_csum tail entries, as well as encrypted+casefolded extended-hash entries) and corrupt rec_len, alignment, name_len, block-end slack, overrun, out-of-bounds inode numbers, and full-block '.' entries.
- is_dx_dir(), get_dtype(), and 32-bit vs 64-bit HTree telldir hash position conversions (hash2pos, pos2maj_hash, pos2min_hash, and ext4_get_htree_eof).
- ext4_dir_operations open(), llseek() (64-bit and 32-bit HTree EOF bounds vs non-DX s_bitmap_maxbytes/SEEK_END bounds and cookie invalidation), and release().
- ext4_htree_store_dirent() rbtree ordering across major/minor hashes, 64-bit hash collision chaining, and ext4_htree_free_dir_info().
- Linear ext4_readdir() across multi-block directories with sparse holes, deleted entries, stop/resume, unaligned f_pos revalidation on i_version change, bad checksum and corrupt entry skipping, and ERR_BAD_DX_DIR fallback clearing EXT4_INODE_INDEX.
- HTree ext4_dx_readdir() across multi-leaf next_hash continuations, mid-collision extra_fname stop/resume, EOF handling, seek reset, and mid-iteration i_version refill.
Export ext4_dir_operations, expose thin KUnit wrappers for static helpers in fs/ext4/dir.c, and add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_htree_fill_tree().
--- fs/ext4/Makefile | 3 +- fs/ext4/dir-test.c | 992 +++++++++++++++++++++++++++++++++++++++++++++ fs/ext4/dir.c | 33 ++ fs/ext4/ext4.h | 8 + fs/ext4/namei.c | 4 + 5 files changed, 1039 insertions(+), 1 deletion(-) create mode 100644 fs/ext4/dir-test.c
fs/ext4/Makefile +2 -1
@@ -24,7 +24,8 @@ ext4-test-objs += inode-test.o mballoc-test.o \ sysfs-test.o ioctl-test.o \ resize-test.o migrate-test.o \ indirect-test.o fsmap-test.o \ - move_extent-test.o mmp-test.o + move_extent-test.o mmp-test.o \ + dir-test.o obj-$(CONFIG_EXT4_KUNIT_TESTS) += ext4-test.o ext4-$(CONFIG_FS_VERITY) += verity.o ext4-$(CONFIG_FS_ENCRYPTION) += crypto.o
fs/ext4/dir-test.c new file +992 -0
992 lines not on this page · raw message
fs/ext4/dir.c +33 -0
@@ -712,3 +712,36 @@ const struct file_operations ext4_dir_operations = { .release = ext4_release_dir, .setlease = generic_setlease, }; +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_dir_operations); + +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +int ext4_is_dx_dir_test (struct inode *inode) +{ +return is_dx_dir (inode); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_is_dx_dir_test); + +loff_t ext4_dir_hash2pos_test (struct file *filp,__u32 major,__u32 minor) +{ +return hash2pos (filp, major, minor); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_dir_hash2pos_test); + +__u32 ext4_dir_pos2maj_hash_test (struct file *filp,loff_t pos) +{ +return pos2maj_hash (filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_dir_pos2maj_hash_test); + +__u32 ext4_dir_pos2min_hash_test (struct file *filp,loff_t pos) +{ +return pos2min_hash (filp, pos); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_dir_pos2min_hash_test); + +loff_t ext4_get_htree_eof_test (struct file *filp) +{ +return ext4_get_htree_eof (filp); +} +EXPORT_SYMBOL_FOR_EXT4_TEST (ext4_get_htree_eof_test); +#endif
fs/ext4/ext4.h +8 -0
@@ -3045,6 +3045,14 @@ static inline unsigned char get_dtype(struct super_block *sb, int filetype) }extern int ext4_check_all_de (struct inode *dir,struct buffer_head *bh,void *buf,int buf_size); +#if IS_ENABLED (CONFIG_EXT4_KUNIT_TESTS ) +extern int ext4_is_dx_dir_test (struct inode *inode); +extern loff_t ext4_dir_hash2pos_test (struct file *filp,__u32 major, +__u32 minor); +extern __u32 ext4_dir_pos2maj_hash_test (struct file *filp,loff_t pos); +extern __u32 ext4_dir_pos2min_hash_test (struct file *filp,loff_t pos); +extern loff_t ext4_get_htree_eof_test (struct file *filp); +#endif /* fsync.c */ extern int ext4_sync_file (struct file *,loff_t ,loff_t ,int );
fs/ext4/namei.c +4 -0
@@ -36,6 +36,7 @@#include <linux/bio.h> #include <linux/iversion.h> #include <linux/unicode.h> +#include <kunit/static_stub.h> #include "ext4.h" #include "ext4_jbd2.h"
@@ -1002,6 +1003,9 @@ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,__u32 hashval;struct fscrypt_str tmp_str; +KUNIT_STATIC_STUB_REDIRECT (ext4_htree_fill_tree, dir_file, start_hash, + start_minor_hash, next_hash); +dxtrace (printk (KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n" , start_hash, start_minor_hash)); dir =file_inode (dir_file);
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
[email protected]
AI reviewRe: [PATCH 27/27] ext4: add KUnit tests for fs/ext4/dir.c
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: uninitialized i_size_seqcount in dir_test_init() on 32-bit SMP It also noticed 1 related…
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: uninitialized i_size_seqcount in dir_test_init() on 32-bit SMP
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Critical] ext4: out-of-bounds read in ext4_readdir() on fake dirents
[1]
--
commit 789413bd80e96edcb89e48a8973879c9137951c1
Author: Theodore Ts'o <[email protected]>
ext4: add KUnit tests for fs/ext4/dir.c
This commit adds a KUnit test suite for fs/ext4/dir.c covering directory entry validation, hash-cookie helpers, directory llseek, and linear and HTree directory iteration, and exports helper symbols for testing.
Quoted 5 lines
fs/ext4/dir-test.c new file +0
-0
[ ... ]
Quoted 9 lines
fs/ext4/dir-test.c new file +9
-0+static int dir_test_init (struct kunit *test) +{ +struct dir_test_ctx *ctx; +struct inode *dir; +int i; + + ctx =kunit_kzalloc (test,sizeof (*ctx),GFP_KERNEL ); +KUNIT_ASSERT_NOT_ERR_OR_NULL (test, ctx); + test->priv = ctx;
[ ... ]
Quoted 6 lines
fs/ext4/dir-test.c new file +6
-0+ dir = &ctx->dir_ei.vfs_inode; + dir->i_sb = &ctx->sb; + dir->i_ino =DIR_TEST_DIR_INO ; + dir->i_mode =S_IFDIR |0755 ; + dir->i_blkbits =DIR_TEST_BLK_BITS ; + dir->i_mapping = &dir->i_data;
fs/ext4/dir-test.c line 431
Quoted 10 lines
fs/ext4/dir-test.c new file +10
-0+ dir->i_data.host = dir; + set_nlink(dir, 2);\n> + atomic_set(&dir->i_count, 1); +spin_lock_init (&dir->i_lock); +init_rwsem (&dir->i_rwsem); +INIT_LIST_HEAD (&dir->i_io_list); +INIT_LIST_HEAD (&dir->i_wb_list); +INIT_LIST_HEAD (&dir->i_lru); +INIT_HLIST_NODE (&dir->i_hash); +inode_state_set_raw (dir,I_DIRTY ); +inode_set_iversion_raw (dir,10 );
[Severity: Low]
Does dir_test_init() leave dir->i_size_seqcount uninitialized on 32-bit SMP builds?
Because ctx is allocated on the heap via kunit_kzalloc() without calling i_size_ordered_init(dir) (or inode_init_once(dir)), i_size_write(dir, ...) and i_size_read(dir) in the test cases pass an uninitialized lockdep_map to write_seqcount_begin() and read_seqcount_begin() when CONFIG_DEBUG_LOCK_ALLOC is enabled, triggering a non-static key warning and disabling lockdep.
Quoted 2 lines
fs/ext4/dir-test.c new file +2
-0+ +init_rwsem (&ctx->dir_ei.xattr_sem);
[ ... ]
Quoted 2 lines
fs/ext4/dir-test.c new file +2
-0+static void test_check_dir_entry_and_all_de (struct kunit *test) +{
[ ... ]
fs/ext4/dir-test.c line 513
Quoted 11 lines
fs/ext4/dir-test.c new file +11
-0+/* +* 4. Casefolded + encrypted directory requires space for +* ext4_dir_entry_hash (+8 bytes) on regular entries, while fake +* entries ('.', '..', csum tail) remain 12 bytes. +*/ + dir->i_flags |=S_CASEFOLD |S_ENCRYPTED ; +write_de (buf,24 ,15 ,16 ,EXT4_FT_REG_FILE ,"ab" ); + de = (struct ext4_dir_entry_2 *)(buf +24 ); +KUNIT_EXPECT_EQ (test,__ext4_check_dir_entry (__func__, __LINE__, dir, +NULL , de, bh, buf, +DIR_TEST_BLK_SIZE ,24 ),1 );
[Severity: Critical]
This problem wasn't introduced by this patch, but can ext4_readdir() perform an 8-byte out-of-bounds read past the end of the directory block buffer on fake entries [1]?
In encrypted and casefolded directories, __ext4_check_dir_entry() passes NULL instead of dir to ext4_dir_rec_len() when is_fake_dir_entry(de) is true, so it does not require space for the 8-byte ext4_dir_entry_hash:
fs/ext4/dir.c:__ext4_check_dir_entry() {
...
bool fake = is_fake_dir_entry(de);
...
if (unlikely(rlen < ext4_dir_rec_len(1, fake ? NULL : dir)))
error_msg = "rec_len is smaller than minimal";
else if (unlikely(rlen % 4 != 0))
error_msg = "rec_len % 4 != 0";
else if (unlikely(rlen < ext4_dir_rec_len(de->name_len,
fake ? NULL : dir)))
error_msg = "rec_len is too small for name_len";
...
}However, ext4_readdir() only checks that de->inode is non-zero before reading EXT4_DIRENT_HASH(de) and EXT4_DIRENT_MINOR_HASH(de):
fs/ext4/dir.c:ext4_readdir() {
...
if (le32_to_cpu(de->inode)) {
if (!IS_ENCRYPTED(inode)) {
...
} else {
...
if (IS_CASEFOLDED(inode)) {
hash = EXT4_DIRENT_HASH(de);
minor_hash = EXT4_DIRENT_MINOR_HASH(de);
}
...
}If a corrupted directory places a fake entry (such as "." or "..", or an entry with file_type set to EXT4_FT_DIR_CSUM and a non-zero de->inode) at the end of the block with rlen sized without the 8-byte hash, reading the hash accesses 8 bytes past bh->b_data + sb->s_blocksize, which can fault on an unmapped page or leak adjacent memory to userspace via nokey_name.dirhash.
[1] https://sashiko.dev/#/bug/linux-7bcf348c-5fde-4625-bb87-69ecef239378
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=27