Skip to contentSkip to conversation

ext4: add lots of KUnit tests!

PATCH New Theodore Ts'o 2 participants 53 messages Nov 19 ext4 file system

lore
Share & tools
lore

Theodore Ts'o

author maintainer
#0 lore raw

cover ext4: add lots of KUnit tests!

These unit tests were written using the writing-kunit-tests.md prompt[1]. It has received human review, as well as multiple passes with LLM's, especially since the -v1 release.

[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

The patches in this series are available at the ext4.git tree on the branch ext4-kunit-tests[3], which is now based on the ext4.git dev branch[4] (commit 008aad6508e3, on top of v7.4-rc2).

[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=dev

Changes since v1[5]:

- Rebased from v7.3-rc4 onto the ext4.git dev branch (on top of v7.4-rc2), updating test stubs, teardown helpers, and expectations for upstream and dev changes (ext4_es_destroy_stats(), const struct mnt_idmap *, buffer_write_io_error(), handle_t * zeroout arguments, blkdev_issue_flush() error propagation, sb_find_get_block() inode bitmap lookups, the 2 MiB max orphan file size, flex_bg sibling directory spreading, and stopping cleanly on incomplete fast commit replay).
- Dropped "ext4: zero s_fc_replay_state in ext4_fc_replay_cleanup()", superseded by commit 2d36dbdbf575 ("ext4: free fast commit replay state on failed mounts") in dev.
- Squashed "ext4: add KUnit tests for ext4_ext_split() leaf and index splitting" into "ext4: add KUnit tests for fs/ext4/extents.c".
- Added "ext4: add KUnit regression tests for inode migration fixes" covering the ext4_ext_migrate() fixes now in dev.
- Addressed build, sparse, bisection, portability, and test-lifecycle issues reported by the kernel test robot and sashiko-bot, along with follow-up verification fixes across UML, x86_64, i386, arm, and arm64 (including 16K/64K pages, lockdep, KASAN, sparse C=2, and per-commit CONFIG_EXT4_KUNIT_TESTS=m builds):
* Deduplicated and reordered EXPORT_SYMBOL_FOR_EXT4_TEST() exports, dropped unused mballoc test wrappers, and moved the SB_ENC_STRICT_MODE_FL fix into the namei test patch for clean modular and CONFIG_UNICODE=y bisection.
* Fixed 32-bit 64-bit-division link errors (div_u64/div_u64_rem), big-endian EXT4_EXT_MAGIC checks, sparse warnings (__le16/__le32, __percpu, __bitwise, flexible-array structs, upper_32_bits()), unaligned bitmap word ops, and large stack frames in tests.
* Fixed mock superblock and inode teardown (attaching s_root via d_make_root() so deactivate_super() drains fserror_worker(), moving ext4_es_remove_extent() from .free_inode to .evict_inode, draining RCU callbacks via rcu_barrier(), and registering KUnit cleanup actions for early-abort safety).
* Fixed lockdep key initialization, i_size_ordered_init() on mock inodes, CONFIG_HIGHMEM folio copies, 16K/64K PAGE_SIZE block and buddy-group spacing, SMP/preemption test races, RTC-less i_dtime checks, and !CONFIG_QUOTA / !CONFIG_PRINTK handling.

[5] https://lore.kernel.org/r/[email protected]

Theodore Ts'o (26):
ext4: add KUinit tests for fs/ext4/extents_status.c
ext4: add KUnit tests for fs/ext4/extents.c
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: 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
ext4: add KUnit regression tests for inode migration fixes

 fs/ext4/.kunitconfig          |    7 +
 fs/ext4/Makefile              |   12 +-
 fs/ext4/balloc-test.c         | 2403 ++++++++++++++++++++++
 fs/ext4/balloc.c              |   11 +-
 fs/ext4/bitmap.c              |    5 +
 fs/ext4/block_validity-test.c | 1598 +++++++++++++++
 fs/ext4/block_validity.c      |   11 +-
 fs/ext4/crypto.c              |    4 +
 fs/ext4/dir-test.c            |  993 ++++++++++
 fs/ext4/dir.c                 |   37 +
 fs/ext4/ext4.h                |  255 ++-
 fs/ext4/ext4_extents.h        |   21 +
 fs/ext4/ext4_jbd2.c           |   21 +
 fs/ext4/extents-test.c        | 2625 +++++++++++++++++++++++-
 fs/ext4/extents.c             |   99 +-
 fs/ext4/extents_status-test.c | 1646 ++++++++++++++++
 fs/ext4/extents_status.c      |   23 +
 fs/ext4/fast_commit-test.c    | 2714 +++++++++++++++++++++++++
 fs/ext4/fast_commit.c         |  180 +-
 fs/ext4/fsmap-test.c          |  796 ++++++++
 fs/ext4/fsmap.c               |    3 +
 fs/ext4/ialloc-test.c         | 2731 +++++++++++++++++++++++++
 fs/ext4/ialloc.c              |  104 +-
 fs/ext4/indirect-test.c       | 1293 ++++++++++++
 fs/ext4/indirect.c            |   18 +-
 fs/ext4/inline-test.c         | 1866 ++++++++++++++++++
 fs/ext4/inline.c              |   34 +-
 fs/ext4/inode-test.c          | 3511 ++++++++++++++++++++++++++++++++-
 fs/ext4/inode.c               |  192 +-
 fs/ext4/ioctl-test.c          | 1198 +++++++++++
 fs/ext4/ioctl.c               |  249 ++-
 fs/ext4/mballoc-test.c        | 1940 +++++++++++++++++-
 fs/ext4/mballoc.c             |  181 +-
 fs/ext4/mballoc.h             |   40 +
 fs/ext4/migrate-test.c        | 1384 +++++++++++++
 fs/ext4/migrate.c             |   11 +
 fs/ext4/mmp-test.c            |  661 +++++++
 fs/ext4/mmp.c                 |  117 +-
 fs/ext4/move_extent-test.c    | 1023 ++++++++++
 fs/ext4/move_extent.c         |   22 +
 fs/ext4/namei-test.c          | 2347 ++++++++++++++++++++++
 fs/ext4/namei.c               |  342 ++--
 fs/ext4/namei.h               |  213 ++
 fs/ext4/orphan-test.c         | 2372 ++++++++++++++++++++++
 fs/ext4/orphan.c              |   12 +
 fs/ext4/page-io.c             |    1 +
 fs/ext4/resize-test.c         | 1336 +++++++++++++
 fs/ext4/resize.c              |  102 +-
 fs/ext4/super-test.c          | 1345 +++++++++++++
 fs/ext4/super.c               |  276 ++-
 fs/ext4/sysfs-test.c          |  679 +++++++
 fs/ext4/sysfs.c               |   55 +
 fs/ext4/xattr-test.c          | 1822 +++++++++++++++++
 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, 40569 insertions(+), 420 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: 008aad6508e30cd1bb6d2c2cf65221ba1f16a065

Signature · 1 line
2.56.1.708.g77570a6a1d-goog
author maintainer
#1 lore raw

PATCH 1/26 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             |    6 -
 fs/ext4/extents_status-test.c | 1646 +++++++++++++++++++++++++++++++++
 fs/ext4/extents_status.c      |   20 +
 fs/ext4/inode.c               |   10 +
 5 files changed, 1678 insertions(+), 7 deletions(-)
 create mode 100644 fs/ext4/extents_status-test.c
fs/ext4/Makefile +2 -1
index 3f9fc0eb8eca..74b485dbb229 100644
@@ -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 -6
index db49be6e4eb0..aa65aca4a1ea 100644
@@ -6526,13 +6526,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_es_destroy_stats);
 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 +1646 -0

1,646 lines not on this page · raw message

fs/ext4/extents_status.c +20 -0
index c250b7d356f5..c86bf438b48c 100644
@@ -2416,3 +2416,23 @@ 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_es_destroy_stats);
+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
index b9a0d085e75d..43a183978692 100644
@@ -418,6 +418,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)) {
@@ -1786,6 +1789,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 */
 
@@ -7994,3 +7999,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.1.708.g77570a6a1d-goog
#2 lore raw

Re: [PATCH -v2 01/26] ext4: add KUinit tests for fs/ext4/extents_status.c

Sashiko has reviewed this patch and found no issues.
Quoted 4 lines

These tests were created with the help of Gemini Pro and verified by a human.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

PATCH 2/26 ext4: add KUnit tests for fs/ext4/extents.c

In reply to Theodore Ts'o

Expand 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), leaf and intermediate index node splitting (ext4_ext_split via test_insert_extent_leaf_split and test_insert_extent_index_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, also exporting ext4_double_{down,up}_write_data_sem for lockdep-clean two-inode locking in test_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 | 2089 ++++++++++++++++++++++++++++++++++++++--
 fs/ext4/extents.c      |   83 +-
 fs/ext4/inode.c        |    5 +
 fs/ext4/mballoc.c      |    7 +
 fs/ext4/move_extent.c  |    5 +
 fs/ext4/super.c        |    1 +
 8 files changed, 2147 insertions(+), 72 deletions(-)
fs/ext4/ext4_extents.h +21 -0
index f4218ff0842d..f819ae995a10 100644
@@ -269,6 +269,8 @@ extern int __ext4_ext_dirty(const char *where, unsigned int line,
 			    struct ext4_ext_path *path);
 extern int ext4_ext_zeroout(handle_t *handle, 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(
@@ -276,6 +278,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
index cf1032a8c89a..7d4f36baf250 100644
@@ -4,6 +4,7 @@
  */
 
 #include "ext4_jbd2.h"
+#include <kunit/static_stub.h>
 
 #include <trace/events/ext4.h>
 
@@ -383,6 +384,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);
@@ -435,3 +439,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 +2021 -68

2,267 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
index 43a183978692..c9400d505281 100644
@@ -7696,6 +7696,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);
@@ -8003,4 +8006,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
index cf728da45ad7..a0f3058da90c 100644
@@ -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
fs/ext4/move_extent.c +5 -0
index 948ef3f44df5..e5450e83da80 100644
@@ -667,3 +667,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
fs/ext4/super.c +1 -0
index 359f9d4ed447..9f0951673fa3 100644
@@ -1170,6 +1170,7 @@ void ext4_update_dynamic_rev(struct super_block *sb)
 	 * can leave it up to e2fsck to clean up any inconsistencies there.
 	 */
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_dynamic_rev);
 
 static inline struct inode *orphan_list_entry(struct list_head *l)
 {
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
#4 lore raw

Re: [PATCH -v2 02/26] ext4: add KUnit tests for fs/ext4/extents.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ext4: extent loss in ext4_ext_split() after dropping __GFP_NOFAIL --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ext4: extent loss in ext4_ext_split() after dropping __GFP_NOFAIL
--

commit ebd19bc1cdea3cf4f65a39e530d43e87d087d855
Author: Theodore Ts'o <[email protected]>

ext4: add KUnit tests for fs/ext4/extents.c

This commit expands the ext4_extents_test KUnit test suite to cover extent tree operations in fs/ext4/extents.c and adds KUnit static stub redirects and symbol exports for testing.

Quoted 4 lines
fs/ext4/extents.c +0 -0
index aa65aca4a1ead..0a442844b954e 100644

[ ... ]

fs/ext4/extents.c static int ext4_ext_split(handle_t *handle, struct inode *inode, · line 1225

Quoted 9 lines
fs/ext4/extents.c +1 -1
@@ -1212,7 +1219,7 @@ static int ext4_ext_split(handle_t *handle, struct inode *inode,
 	while (k--) {
 		oldblock = newblock;
 		newblock = ablocks[--a];
-		bh = sb_getblk(inode->i_sb, newblock);
+		bh = ext4_ext_getblk(inode, newblock, __GFP_MOVABLE | GFP_NOFS);
 		if (unlikely(!bh)) {
 			err = -ENOMEM;
 			goto cleanup;

[Severity: Medium]
Can replacing sb_getblk() (which passes __GFP_NOFAIL) with ext4_ext_getblk(..., __GFP_MOVABLE | GFP_NOFS) lose the m split extents if this allocation fails?

By the time ext4_ext_split() enters the intermediate index loop, the m extents have been moved to the new leaf block in ablocks[] and the old leaf has already had its eh_entries decremented in place and dirtied:

fs/ext4/extents.c:ext4_ext_split() {
	...
	/* correct old leaf */
	if (m) {
		err = ext4_ext_get_access(handle, inode, path + depth);
		if (err)
			goto cleanup;
		le16_add_cpu(&path[depth].p_hdr->eh_entries, -m);
		err = ext4_ext_dirty(handle, inode, path + depth);
		if (err)
			goto cleanup;

	}
	...
}

Jumping to cleanup on -ENOMEM frees all blocks in ablocks[] (including the new leaf block holding those m extents) without restoring path[depth].p_hdr->eh_entries, leaving the old leaf truncated in the running transaction. Passing __GFP_NOFAIL here as sb_getblk() did would avoid failing after the old leaf has been modified.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#5 lore raw

PATCH 3/26 ext4: add KUnit tests for fs/ext4/xattr.c

In reply to Theodore Ts'o

Add 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    | 1810 +++++++++++++++++++++++++++++++++++++++
 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, 1895 insertions(+), 4 deletions(-)
 create mode 100644 fs/ext4/xattr-test.c
fs/ext4/Makefile +1 -1
index 74b485dbb229..13040b97d2ff 100644
@@ -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
index aa0f23052ca2..30d6f7b99f07 100644
@@ -4160,6 +4160,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
index 92e2243b98cf..8b9833ea3802 100644
@@ -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>
 
@@ -1012,6 +1013,10 @@ struct inode *__ext4_new_inode(const 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);
@@ -1693,3 +1698,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
index 2e14ee9b4241..1f7aa2223d1c 100644
@@ -2036,3 +2036,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
index c9400d505281..5fa293c9581e 100644
@@ -796,6 +796,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);
@@ -996,6 +998,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode,
 
 	return ret ? ret : retval;
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks);
 
 /*
  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
@@ -1121,6 +1124,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);
@@ -1183,6 +1189,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)
@@ -5922,6 +5929,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);
 
@@ -5931,6 +5940,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().
@@ -6288,6 +6298,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))) {
@@ -6663,6 +6675,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,
@@ -7455,6 +7468,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);
@@ -7488,6 +7503,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
@@ -8007,5 +8023,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
index 9f0951673fa3..4542a1b8ca0f 100644
@@ -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 */
@@ -262,7 +263,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);
@@ -7701,3 +7706,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 +1810 -0

1,810 lines not on this page · raw message

fs/ext4/xattr.c +29 -1
index 062786fa3646..277731c424a0 100644
@@ -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)
@@ -2166,7 +2183,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:
@@ -2282,6 +2299,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,
@@ -2340,6 +2358,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)
@@ -2537,6 +2556,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)
@@ -2564,6 +2584,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()
@@ -2612,6 +2633,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
@@ -2903,6 +2925,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()
@@ -3011,6 +3034,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
@@ -3064,12 +3088,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()
@@ -3267,10 +3293,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
index 821dc6a50e51..1a72e68cea0c 100644
@@ -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
index a3ecbff72b10..9cd42f6546b5 100644
@@ -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
index 458e1982ef83..d5d033ba7594 100644
@@ -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
index ad35215f6610..26087e98677b 100644
@@ -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.1.708.g77570a6a1d-goog
#6 lore raw

Re: [PATCH -v2 03/26] ext4: add KUnit tests for fs/ext4/xattr.c

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Add 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,
[ ... ]
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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#7 lore raw

PATCH 4/26 ext4: add KUnit tests for fs/ext4/namei.c

In reply to Theodore Ts'o

Add 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 | 2337 ++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/namei.c      |  338 +++---
 fs/ext4/namei.h      |  213 ++++
 fs/ext4/orphan.c     |    7 +
 7 files changed, 2741 insertions(+), 165 deletions(-)
 create mode 100644 fs/ext4/namei-test.c
 create mode 100644 fs/ext4/namei.h
fs/ext4/Makefile +2 -1
index 13040b97d2ff..8fe7b512ebb4 100644
@@ -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
index 318b2eaea741..002ba8837d33 100644
@@ -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])
 {
@@ -255,3 +258,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
index e921e12acbd7..f9b6aaabcd17 100644
@@ -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 +2337 -0

2,337 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

135 lines not on this page · raw message

fs/ext4/orphan.c +7 -0
index 7394d04e0fd9..e04e90039fef 100644

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.1.708.g77570a6a1d-goog

Part of the diff is not shown here. View the raw message.

#8 lore raw

Re: [PATCH -v2 04/26] ext4: add KUnit tests for fs/ext4/namei.c

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Add 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 [ ... ]
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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#9 lore raw

PATCH 5/26 ext4: expand KUnit tests for fs/ext4/mballoc.c

In reply to Theodore Ts'o

Expand 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 | 1927 +++++++++++++++++++++++++++++++++++++++-
 fs/ext4/mballoc.c      |  168 +++-
 fs/ext4/mballoc.h      |   40 +
 fs/ext4/super.c        |    2 +
 4 files changed, 2120 insertions(+), 17 deletions(-)
fs/ext4/mballoc-test.c +1912 -15
index d31780075c21..6f70bff5c83a 100644
@@ -5,8 +5,10 @@
 
 #include <kunit/test.h>
 #include <kunit/static_stub.h>
+#include <linux/cpumask.h>
 #include <linux/fs_context.h>
 #include <linux/random.h>
+#include <linux/sched.h>
 
 #include "ext4.h"
 #include "mballoc.h"
@@ -79,6 +81,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 +165,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 +349,75 @@ 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);
+	spin_lock_init(&inode->i_lock);
+	init_rwsem(&inode->i_rwsem);
+	init_rwsem(&inode->i_data.invalidate_lock);
+	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 1
 static int mbt_kunit_init(struct kunit *test)
 {
@@ -382,6 +450,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 +473,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 +491,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 +597,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 +668,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 +1013,1814 @@ 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(buf, 10, 0);
+	KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 256);
+
+	/* Multi-word range spanning head bits, 32-bit words, and tail */
+	mb_set_bits(buf, 5, 75);
+	KUNIT_EXPECT_EQ(test, mb_find_next_bit_test(buf, 256, 0), 5);
+	KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 256, 5), 80);
+	/* Clamping when no zero bit exists before max */
+	KUNIT_EXPECT_EQ(test, mb_find_next_zero_bit_test(buf, 50, 5), 50);
+
+	/* Clear a sub-range across 32-bit boundaries */
+	mb_clear_bits_test(buf, 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, buf), 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;
+
+	/* 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 an uninitialized group on a
+	 * separate buddy-cache folio:
+	 * At inexpensive CR_POWER2_ALIGNED, it skips initializing the group
+	 * and returns 0. At expensive CR_GOAL_LEN_SLOW (with STRICT_CHECK),
+	 * it initializes the group and returns 1.
+	 */
+	{
+		ext4_group_t uninit_grp = max_t(ext4_group_t, 2,
+			DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2));
+
+		if (uninit_grp < ext4_get_groups_count(sb)) {
+			grp2 = ext4_get_group_info(sb, uninit_grp);
+			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, uninit_grp,
+							     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, uninit_grp,
+							     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);
+	ext4_get_group_info(sb, TEST_GOAL_GROUP)->bb_free--;
+
+	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 = 4;
+
+	ret = ext4_mb_pa_alloc_test(&ac);
+	KUNIT_ASSERT_EQ(test, ret, 0);
+
+	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_criteria, CR_BEST_AVAIL_LEN);
+	KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_group, 2);
+	KUNIT_EXPECT_EQ(test, ac.ac_f_ex.fe_len, 8);
+	KUNIT_EXPECT_EQ(test, ac.ac_b_ex.fe_len, 4);
+	ext4_discard_preallocations(inode);
+}
+
+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, uninit_grp;
+	int ios = 0;
+
+	if (sb->s_blocksize > PAGE_SIZE)
+		kunit_skip(test, "blocksize exceeds pagesize");
+
+	uninit_grp = max_t(ext4_group_t, 2,
+			   DIV_ROUND_UP(PAGE_SIZE / sb->s_blocksize, 2));
+
+	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));
+	if (uninit_grp < ext4_get_groups_count(sb)) {
+		grp2 = ext4_get_group_info(sb, uninit_grp);
+		KUNIT_ASSERT_NOT_NULL(test, grp2);
+		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);
+}
+
+struct mbt_saved_affinity {
+	cpumask_var_t mask;
+};
+
+static void mbt_restore_cpu_affinity(void *data)
+{
+	struct mbt_saved_affinity *saved = data;
+
+	set_cpus_allowed_ptr(current, saved->mask);
+	free_cpumask_var(saved->mask);
+	kfree(saved);
+}
+
+static void mbt_pin_current_cpu(struct kunit *test)
+{
+	struct mbt_saved_affinity *saved;
+	int err;
+
+	saved = kzalloc_obj(*saved);
+	KUNIT_ASSERT_NOT_NULL(test, saved);
+	if (!alloc_cpumask_var(&saved->mask, GFP_KERNEL)) {
+		kfree(saved);
+		KUNIT_FAIL_AND_ABORT(test, "failed to alloc cpumask");
+	}
+	cpumask_copy(saved->mask, current->cpus_ptr);
+
+	err = set_cpus_allowed_ptr(current,
+				   cpumask_of(raw_smp_processor_id()));
+	if (err) {
+		free_cpumask_var(saved->mask);
+		kfree(saved);
+		KUNIT_ASSERT_EQ(test, err, 0);
+	}
+
+	err = kunit_add_action_or_reset(test, mbt_restore_cpu_affinity, saved);
+	KUNIT_ASSERT_EQ(test, err, 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");
+
+	/* Pin to one CPU so both allocations hit the same locality group PA */
+	mbt_pin_current_cpu(test);
+
+	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!
+	 * Capture one locality group pointer up front so CPU migration across
+	 * iterations cannot split PAs across different per-CPU locality groups.
+	 */
+	lg = raw_cpu_ptr(sbi->s_locality_groups);
+	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 = lg;
+		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);
+
+	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 +2863,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 +166 -2

193 lines not on this page · raw message

fs/ext4/mballoc.h +40 -0
index 571d9bd93810..f332a23d66f8 100644
@@ -275,6 +275,8 @@ extern int ext4_mb_mark_context(handle_t *handle,
 		ext4_group_t group, ext4_grpblk_t blkoff,
 		ext4_grpblk_t len, int flags,
 		ext4_grpblk_t *ret_changed);
+extern int ext4_issue_discard(struct super_block *sb,
+		ext4_group_t block_group, ext4_grpblk_t cluster, int count);
 #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS)
 extern void mb_clear_bits_test(void *bm, int cur, int len);
 extern ext4_fsblk_t
@@ -283,7 +285,45 @@ ext4_mb_new_blocks_simple_test(struct ext4_allocation_request *ar,
 extern int mb_find_next_zero_bit_test(void *addr, int max, int start);
 extern int mb_find_next_bit_test(void *addr, int max, int start);
 extern void mb_clear_bit_test(int bit, void *addr);
+extern void mb_set_bit_test(int bit, void *addr);
 extern int mb_test_bit_test(int bit, void *addr);
+extern int mb_test_and_clear_bits_test(void *bm, int cur, int len);
+extern void *mb_find_buddy_test(struct ext4_buddy *e4b, int order, int *max);
+extern int mb_find_order_for_block_test(struct ext4_buddy *e4b, int block);
+extern int mb_find_extent_test(struct ext4_buddy *e4b, int block, int needed,
+			       struct ext4_free_extent *ex);
+extern int mb_avg_fragment_size_order_test(struct super_block *sb,
+					   ext4_grpblk_t len);
+extern void mb_update_avg_fragment_size_test(struct super_block *sb,
+					     struct ext4_group_info *grp);
+extern void mb_set_largest_free_order_test(struct super_block *sb,
+					   struct ext4_group_info *grp);
+extern bool ext4_mb_good_group_test(struct ext4_allocation_context *ac,
+				    ext4_group_t group, enum criteria cr);
+extern int ext4_mb_good_group_nolock_test(struct ext4_allocation_context *ac,
+					  ext4_group_t group, enum criteria cr);
+extern int ext4_mb_find_by_goal_test(struct ext4_allocation_context *ac,
+				     struct ext4_buddy *e4b);
+extern void ext4_mb_simple_scan_group_test(struct ext4_allocation_context *ac,
+					   struct ext4_buddy *e4b);
+extern void ext4_mb_scan_aligned_test(struct ext4_allocation_context *ac,
+				      struct ext4_buddy *e4b);
+extern void ext4_mb_complex_scan_group_test(struct ext4_allocation_context *ac,
+					    struct ext4_buddy *e4b);
+extern void ext4_mb_try_best_found_test(struct ext4_allocation_context *ac,
+					struct ext4_buddy *e4b);
+extern int ext4_mb_regular_allocator_test(struct ext4_allocation_context *ac);
+extern void ext4_mb_initialize_context_test(struct ext4_allocation_context *ac,
+					    struct ext4_allocation_request *ar);
+extern void ext4_mb_normalize_request_test(struct ext4_allocation_context *ac,
+					   struct ext4_allocation_request *ar);
+extern void ext4_mb_new_preallocation_test(struct ext4_allocation_context *ac);
+extern void ext4_mb_release_context_test(struct ext4_allocation_context *ac);
+extern int ext4_mb_pa_alloc_test(struct ext4_allocation_context *ac);
+extern void ext4_mb_generate_from_pa_test(struct super_block *sb, void *bitmap,
+					  ext4_group_t group);
+extern int ext4_mb_discard_preallocations_test(struct super_block *sb,
+					       int needed);
 extern int
 ext4_mb_mark_diskspace_used_test(struct ext4_allocation_context *ac,
 				 handle_t *handle);
fs/ext4/super.c +2 -0
index 4542a1b8ca0f..517ab0de1841 100644
@@ -372,6 +372,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)
@@ -428,6 +429,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)
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
#10 lore raw

Re: [PATCH -v2 05/26] ext4: expand KUnit tests for fs/ext4/mballoc.c

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Expand 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
[ ... ]

Quoted 4 lines

Export the tested functions with EXPORT_SYMBOL_FOR_EXT4_TEST and add a KUNIT_STATIC_STUB_REDIRECT hook to ext4_issue_discard.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#11 lore raw

PATCH 6/26 ext4: add KUnit tests for fs/ext4/inline.c

In reply to Theodore Ts'o

Add 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   |    5 +
 fs/ext4/inline-test.c | 1852 +++++++++++++++++++++++++++++++++++++++++
 fs/ext4/inline.c      |   30 +-
 fs/ext4/inode.c       |    4 +
 6 files changed, 1893 insertions(+), 2 deletions(-)
 create mode 100644 fs/ext4/inline-test.c
fs/ext4/Makefile +1 -1
index 8fe7b512ebb4..5a90bf5b28e3 100644
@@ -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
index 30d6f7b99f07..ae5edd8e8d4d 100644
@@ -3831,6 +3831,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 +5 -0
index 7d4f36baf250..b6d84057009c 100644
@@ -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 */
@@ -127,6 +129,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)
 {
@@ -154,6 +157,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)
@@ -441,5 +445,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 +1852 -0

1,852 lines not on this page · raw message

fs/ext4/inline.c +29 -1
index 1f7aa2223d1c..acdc65ce4796 100644
@@ -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"
@@ -1112,6 +1113,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)
@@ -1160,7 +1168,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;
@@ -2038,5 +2046,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
index 5fa293c9581e..9fe324cda5e6 100644
@@ -2171,6 +2171,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);
 
@@ -8020,6 +8023,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.1.708.g77570a6a1d-goog
#12 lore raw

Re: [PATCH -v2 06/26] ext4: add KUnit tests for fs/ext4/inline.c

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Add 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
[ ... ]
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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#13 lore raw

PATCH 7/26 ext4: add KUnit tests for fs/ext4/fast_commit.c

In reply to Theodore Ts'o

Add 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 | 2702 ++++++++++++++++++++++++++++++++++++
 fs/ext4/fast_commit.c      |  180 ++-
 fs/ext4/ialloc.c           |    3 +
 fs/ext4/inode.c            |    6 +
 fs/ext4/mballoc.c          |    3 +-
 8 files changed, 2928 insertions(+), 7 deletions(-)
 create mode 100644 fs/ext4/fast_commit-test.c
fs/ext4/Makefile +2 -1
index 5a90bf5b28e3..7bd91839c3ce 100644
@@ -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
index ae5edd8e8d4d..ae773eb08895 100644
@@ -3094,6 +3094,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);
+int 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);
@@ -3120,6 +3123,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
index c86bf438b48c..b7fb8502f9d4 100644
@@ -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 +2702 -0

2,702 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
index 8b9833ea3802..c836923d018a 100644
@@ -827,6 +827,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;
 
@@ -1701,4 +1703,5 @@ int ext4_init_inode_table(struct super_block *sb, ext4_group_t group,
 
 #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS)
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

fs/ext4/inode.c +6 -0
index 9fe324cda5e6..49560ca27036 100644

Lines of this file are not shown. View the raw message.

fs/ext4/mballoc.c +2 -1
index 2ecf5aa77e68..b346f8bbee89 100644

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.1.708.g77570a6a1d-goog

Part of the diff is not shown here. View the raw message.

#14 lore raw

Re: [PATCH -v2 07/26] ext4: add KUnit tests for fs/ext4/fast_commit.c

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Add 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
[ ... ]
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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author maintainer
#15 lore raw

PATCH 8/26 ext4: expand KUnit tests for fs/ext4/inode.c

In reply to Theodore Ts'o

Expand 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/ialloc.c     |    3 +
 fs/ext4/inode-test.c | 3500 +++++++++++++++++++++++++++++++++++++++++-
 fs/ext4/inode.c      |  150 +-
 fs/ext4/page-io.c    |    1 +
 fs/ext4/super.c      |   18 +-
 6 files changed, 3689 insertions(+), 12 deletions(-)
fs/ext4/ext4.h +29 -0
index ae773eb08895..bbe930023d11 100644
@@ -3291,6 +3291,35 @@ extern void ext4_da_update_reserve_space(struct inode *inode,
 extern int ext4_issue_zeroout(handle_t *handle, 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/ialloc.c +3 -0
index c836923d018a..e4c75c56fc17 100644
@@ -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 +3496 -4

2,950 lines not on this page · raw message

fs/ext4/inode.c +144 -6

150 lines not on this page · raw message

fs/ext4/page-io.c +1 -0
index 791e61228f41..059827b961ec 100644

Lines of this file are not shown. View the raw message.

fs/ext4/super.c +16 -2
index 517ab0de1841..47da1e456d6d 100644

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.1.708.g77570a6a1d-goog

Part of the diff is not shown here. View the raw message.

#16 lore raw

Re: [PATCH -v2 08/26] ext4: expand KUnit tests for fs/ext4/inode.c

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Expand 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_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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#17 lore raw

PATCH 9/26 ext4: add KUnit tests for fs/ext4/ialloc.c

In reply to Theodore Ts'o

Add 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    | 2731 ++++++++++++++++++++++++++++++++++++++
 fs/ext4/ialloc.c         |   93 +-
 fs/ext4/super.c          |   17 +
 fs/ext4/xattr_security.c |    4 +
 8 files changed, 2865 insertions(+), 12 deletions(-)
 create mode 100644 fs/ext4/ialloc-test.c
fs/ext4/Makefile +1 -1
index 7bd91839c3ce..72198aff5b45 100644
@@ -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
index 87760fabdd2e..f9c22427891f 100644
@@ -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
index bbe930023d11..b7be93b06746 100644
@@ -3089,9 +3089,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
index b6d84057009c..3e6c9ce108ad 100644
@@ -252,6 +252,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)) {
@@ -271,6 +274,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 +2731 -0

2,731 lines not on this page · raw message

fs/ext4/ialloc.c +82 -11

160 lines not on this page · raw message

fs/ext4/super.c +17 -0
index 47da1e456d6d..0768ba540637 100644
@@ -212,6 +212,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)) {
@@ -226,6 +229,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)
 {
@@ -359,6 +363,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)

Lines of this file are not shown. View the raw message.

fs/ext4/xattr_security.c +4 -0
index af5b8a93fed1..c3919643d64f 100644

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.1.708.g77570a6a1d-goog

Part of the diff is not shown here. View the raw message.

#18 lore raw

Re: [PATCH -v2 09/26] ext4: add KUnit tests for fs/ext4/ialloc.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: leak of ctx and locked sb in ialloc_test_init() on allocation failure --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: leak of ctx and locked sb in ialloc_test_init() on allocation failure
--

commit 1c66a229567b11dc0a2eee47f9e0bdd4aba440b8
Author: Theodore Ts'o <[email protected]>

ext4: add KUnit tests for fs/ext4/ialloc.c

This commit adds the ext4_ialloc_test KUnit test suite in fs/ext4/ialloc-test.c along with static stub hooks and symbol exports to exercise inode allocation, freeing, bitmap management, and group selection heuristics in fs/ext4/ialloc.c.

Quoted 5 lines
fs/ext4/ialloc-test.c new file +0 -0
new file mode 100644
index 0000000000000..c68b60c959614

[ ... ]

Quoted 2 lines
fs/ext4/ialloc-test.c new file +2 -0
+static int ialloc_test_init(struct kunit *test)
+{

[ ... ]

Quoted 18 lines
fs/ext4/ialloc-test.c new file +18 -0
+	ctx = kzalloc_obj(*ctx);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	test->priv = ctx;
+
+	fc = fs_context_for_mount(&ialloc_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);
+	}
+	ctx->sb = sb;

[ ... ]

fs/ext4/ialloc-test.c line 870

Quoted 10 lines
fs/ext4/ialloc-test.c new file +10 -0
+	/* Wire RCU-indexed group_info and flex_groups tables */
+	for (g = 0; g < IALLOC_TEST_NGROUPS; g++) {
+		struct ialloc_test_blk *iblk, *bblk;
+		u32 free_inos = (g == 0) ? IALLOC_TEST_BG0_FREE_INODES :
+					   IALLOC_TEST_INODES_PER_GRP;
+
+		ctx->grp_infos[g] = kunit_kzalloc(test,
+						  sizeof(*ctx->grp_infos[g]),
+						  GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]);

[Severity: Low]
Does KUNIT_ASSERT_NOT_NULL() leak ctx and leave sb active with s_umount write-locked if kunit_kzalloc() fails?

ialloc_test_cleanup() is not registered until kunit_add_action_or_reset() at the end of ialloc_test_init(), so aborting here skips the deactivate_locked_super(sb) and kfree(ctx) cleanup that the subsequent error paths in this function perform.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author maintainer
#19 lore raw

PATCH 10/26 ext4: add KUnit tests for fs/ext4/balloc.c

In reply to Theodore Ts'o

Add 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 | 2400 +++++++++++++++++++++++++++++++++++++++++
 fs/ext4/balloc.c      |   11 +-
 3 files changed, 2412 insertions(+), 2 deletions(-)
 create mode 100644 fs/ext4/balloc-test.c
fs/ext4/Makefile +2 -1
index 72198aff5b45..7d0ae7fd4448 100644
@@ -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 +2400 -0

2,400 lines not on this page · raw message

fs/ext4/balloc.c +10 -1
index 778fe8788f06..d2f0f27bbc9a 100644
@@ -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.1.708.g77570a6a1d-goog
#20 lore raw

Re: [PATCH -v2 10/26] ext4: add KUnit tests for fs/ext4/balloc.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: kunit: leak of ctx in balloc_test_init() if kunit_kzalloc() fails --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: kunit: leak of ctx in balloc_test_init() if kunit_kzalloc() fails
--

commit 12a7df5573859469528c2402fafb82063d22f755
Author: Theodore Ts'o <[email protected]>

ext4: add KUnit tests for fs/ext4/balloc.c

This commit adds a KUnit test suite in fs/ext4/balloc-test.c to exercise block bitmap management, group descriptor and overhead calculations, cluster pool reservation, and metadata block allocation helpers in fs/ext4/balloc.c.

Quoted 6 lines
fs/ext4/balloc-test.c new file +0 -0
new file mode 100644
index 0000000000000..b15d50907324f
@@ -0,0 +1,2400 @@

[ ... ]

Quoted 15 lines
fs/ext4/balloc-test.c new file +15 -0
+static int balloc_test_init(struct kunit *test)
+{
+	struct balloc_test_ctx *ctx;
+	struct fs_context *fc;
+	struct super_block *sb;
+	struct ext4_sb_info *sbi;
+	struct inode *root_inode;
+	ext4_group_t g;
+	s64 total_free_clusters = 0;
+	s64 total_free_inodes = 0;
+	int err;
+
+	ctx = kzalloc_obj(*ctx);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	test->priv = ctx;

fs/ext4/balloc-test.c

Quoted 10 lines
fs/ext4/balloc-test.c new file +10 -0
+
+	for (g = 0; g < BALLOC_TEST_MAX_GROUPS; g++) {
+		ctx->grp_infos[g] = kunit_kzalloc(test,
+						  sizeof(*ctx->grp_infos[g]),
+						  GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]);
+	}
+
+	INIT_WORK(&ctx->sbi.s_discard_work, balloc_test_discard_work_fn);
+	rwlock_init(&ctx->journal.j_state_lock);\n+\n+\terr = kunit_add_action_or_reset(test, balloc_test_cleanup_action, ctx);

[Severity: Low]
Does this leak ctx if kunit_kzalloc() fails? KUNIT_ASSERT_NOT_NULL() aborts the test before kunit_add_action_or_reset() registers balloc_test_cleanup_action to free ctx.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#21 lore raw

PATCH 11/26 ext4: add KUnit tests for fs/ext4/orphan.c

In reply to Theodore Ts'o

Add 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 | 2372 +++++++++++++++++++++++++++++++++++++++++
 fs/ext4/orphan.c      |    5 +
 fs/ext4/super.c       |    1 +
 5 files changed, 2381 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/orphan-test.c
fs/ext4/Makefile +1 -1
index 7d0ae7fd4448..9bad2bff0de9 100644
@@ -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
index 28fc6ec46cf4..9368a68db289 100644
@@ -5553,6 +5553,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 +2372 -0

2,372 lines not on this page · raw message

fs/ext4/orphan.c +5 -0
index e04e90039fef..847eca2d866a 100644
@@ -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)
 {
@@ -658,6 +661,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)
 {
@@ -673,3 +677,4 @@ int ext4_orphan_file_empty(struct super_block *sb)
 			return 0;
 	return 1;
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_orphan_file_empty);
fs/ext4/super.c +1 -0
index 0768ba540637..d03d5dd8d6eb 100644
@@ -355,6 +355,7 @@ void ext4_superblock_csum_set(struct super_block *sb)
 
 	es->s_checksum = ext4_superblock_csum(es);
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_superblock_csum_set);
 
 ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
 			       struct ext4_group_desc *bg)
Signature · 1 line
2.56.1.708.g77570a6a1d-goog
#22 lore raw

Re: [PATCH -v2 11/26] ext4: add KUnit tests for fs/ext4/orphan.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: locked superblock and memory leak in orphan_test_init() on OOM --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: locked superblock and memory leak in orphan_test_init() on OOM
--

commit 793a4f2e9db580fb201beeb33032333df8328513
Author: Theodore Ts'o <[email protected]>

ext4: add KUnit tests for fs/ext4/orphan.c

This commit adds the ext4_orphan_test KUnit test suite to exercise ext4 orphan inode tracking, orphan file management, and mount-time orphan recovery.

Quoted 5 lines
fs/ext4/orphan-test.c new file +0 -0
new file mode 100644
index 0000000000000..bd60976a840d2

[ ... ]

Quoted 2 lines
fs/ext4/orphan-test.c new file +2 -0
+static int orphan_test_init(struct kunit *test)
+{

[ ... ]

Quoted 8 lines
fs/ext4/orphan-test.c new file +8 -0
+	sb = sget_fc(fc, NULL, set_anon_super_fc);
+	put_fs_context(fc);
+	if (IS_ERR(sb)) {
+		err = PTR_ERR(sb);
+		free_percpu(ctx->bdev.bd_stats);
+		kfree(ctx);
+		KUNIT_ASSERT_EQ(test, err, 0);
+	}

[ ... ]

fs/ext4/orphan-test.c line 980

Quoted 7 lines
fs/ext4/orphan-test.c new file +7 -0
+	for (g = 0; g < ORPHAN_TEST_NGROUPS; g++) {
+		struct orphan_test_ibitmap *ibm = &ctx->ibitmaps[g];
+
+		ctx->grp_infos[g] = kunit_kzalloc(test,
+						  sizeof(*ctx->grp_infos[g]),
+						  GFP_KERNEL);
+		KUNIT_ASSERT_NOT_NULL(test, ctx->grp_infos[g]);

[Severity: Low]
Does KUNIT_ASSERT_NOT_NULL() leak sb, ctx->bdev.bd_stats, and ctx if kunit_kzalloc() fails here?

sget_fc() returns with sb->s_umount write-locked, and orphan_test_cleanup_action is not registered until the end of orphan_test_init(). Aborting here exits the KUnit kthread with sb->s_umount held and leaves sb on super_blocks, unlike the root_inode failure paths below that call deactivate_locked_super(sb), free_percpu(), and kfree(ctx) before aborting.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author maintainer
#23 lore raw

PATCH 12/26 ext4: add KUnit tests for fs/ext4/block_validity.c

In reply to Theodore Ts'o

Add 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 | 1520 +++++++++++++++++++++++++++++++++
 fs/ext4/block_validity.c      |    6 +
 3 files changed, 1528 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/block_validity-test.c
fs/ext4/Makefile +2 -1
index 9bad2bff0de9..5c6afff5f12a 100644
@@ -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 +1520 -0

1,520 lines not on this page · raw message

fs/ext4/block_validity.c +6 -0
index 3a31e3d718c9..53b042f36a69 100644
@@ -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.1.708.g77570a6a1d-goog
#24 lore raw

Re: [PATCH -v2 12/26] 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_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
[ ... ]

Quoted 4 lines

Export the five runtime entry points in fs/ext4/block_validity.c with EXPORT_SYMBOL_FOR_EXT4_TEST for the ext4-test KUnit module.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
author maintainer
#25 lore raw

PATCH 13/26 ext4: check multi-block overlap on left traversal in add_system_zone()

In reply to Theodore Ts'o

When 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.

Fixes bf9a379d0980 ("ext4: don't allow overlapping system zones")
---
 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
index f7667099ac6c..8d3af4093a3c 100644
@@ -1114,6 +1114,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);
@@ -1317,6 +1338,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)
@@ -1501,6 +1568,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
index 53b042f36a69..34468932e461 100644
@@ -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.1.708.g77570a6a1d-goog
#26 lore raw

Re: [PATCH -v2 13/26] 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->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.

Quoted 2 lines
Fixes bf9a379d0980 ("ext4: don't allow overlapping system zones")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author maintainer
#27 lore raw

PATCH 14/26 ext4: enable full feature coverage in fs/ext4/.kunitconfig

In reply to Theodore Ts'o

Enable 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 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          | 14 ++++++++++++--
 fs/ext4/xattr-test.c          | 16 ++++++++++++++--
 10 files changed, 121 insertions(+), 17 deletions(-)
fs/ext4/.kunitconfig +7 -0
index bf51da7cd9fc..17103c583fdb 100644
@@ -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
index b15d50907324..ab076c0edf99 100644
@@ -535,6 +535,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
index 8d3af4093a3c..97817befd6e7 100644
@@ -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
index cb1ef31490d0..bc5488293103 100644
@@ -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;
@@ -467,6 +476,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
index be416cb3653e..07cb9c043cd2 100644
@@ -135,9 +135,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;
@@ -148,6 +151,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)
 {
@@ -886,6 +895,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
index efc068c1f823..0198ce8311c7 100644
@@ -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
index 4881736e8742..8a3d753b7079 100644
@@ -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;
@@ -960,6 +968,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_blocksize = INODE_TEST_BLK_SIZE;
 	sb->s_blocksize_bits = INODE_TEST_BLK_BITS;
fs/ext4/mballoc-test.c +13 -0
index 6f70bff5c83a..bd5dabf74b6f 100644
@@ -56,9 +56,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)
@@ -95,6 +105,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 +12 -2
index 6dde9e5cc332..cce3f8d5b36d 100644
@@ -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)
@@ -2278,6 +2287,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);
fs/ext4/xattr-test.c +14 -2
index 30ee5c337284..981bf1455851 100644
@@ -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)
@@ -477,6 +486,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.1.708.g77570a6a1d-goog
#28 lore raw

Re: [PATCH -v2 14/26] ext4: enable full feature coverage in fs/ext4/.kunitconfig

Sashiko has reviewed this patch and found no issues.
Quoted 24 lines

Enable 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 propagate EXT4_INODE_CASEFOLD to S_CASEFOLD on the VFS directory inode via ext4_set_inode_flags().

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#29 lore raw

PATCH 15/26 ext4: add KUnit tests for fs/ext4/super.c

In reply to Theodore Ts'o

Add 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 | 1345 ++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/super.c      |  219 +++++++
 4 files changed, 1610 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/super-test.c
fs/ext4/Makefile +1 -1
index 5c6afff5f12a..ca1a1201cbfe 100644
@@ -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 +1345 -0

1,345 lines not on this page · raw message

fs/ext4/super.c +219 -0

253 lines not on this page · raw message

Signature · 1 line
2.56.1.708.g77570a6a1d-goog
#30 lore raw

Re: [PATCH -v2 15/26] ext4: add KUnit tests for fs/ext4/super.c

Sashiko has reviewed this patch and found no issues.
Quoted 24 lines

Add 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().

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
author maintainer
#31 lore raw

PATCH 16/26 ext4: add KUnit tests for fs/ext4/sysfs.c

In reply to Theodore Ts'o

Add 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 | 679 +++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/sysfs.c      |  55 ++++
 4 files changed, 744 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/sysfs-test.c
fs/ext4/Makefile +2 -1
index ca1a1201cbfe..ff489dff825d 100644
@@ -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
index 81d3f48c44c1..a704783e4356 100644
@@ -4074,6 +4074,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 +679 -0

679 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.1.708.g77570a6a1d-goog
#32 lore raw

Re: [PATCH -v2 16/26] ext4: add KUnit tests for fs/ext4/sysfs.c

Sashiko has reviewed this patch and found no issues.
Quoted 21 lines

Add 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().

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
author maintainer
#33 lore raw

PATCH 17/26 ext4: add KUnit tests for fs/ext4/ioctl.c

In reply to Theodore Ts'o

Add 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 | 1198 ++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/ioctl.c      |  249 ++++++---
 4 files changed, 1411 insertions(+), 71 deletions(-)
 create mode 100644 fs/ext4/ioctl-test.c
fs/ext4/Makefile +1 -1
index ff489dff825d..c18530508863 100644
@@ -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
index a704783e4356..afde7567c661 100644
@@ -3370,6 +3370,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 +1198 -0

1,198 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.1.708.g77570a6a1d-goog
#34 lore raw

Re: [PATCH -v2 17/26] ext4: add KUnit tests for fs/ext4/ioctl.c

Sashiko has reviewed this patch and found no issues.
Quoted 26 lines

Add 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.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
author maintainer
#35 lore raw

PATCH 18/26 ext4: add KUnit tests for fs/ext4/resize.c

In reply to Theodore Ts'o

Add 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 | 1336 +++++++++++++++++++++++++++++++++++++++++
 fs/ext4/resize.c      |  102 +++-
 4 files changed, 1448 insertions(+), 25 deletions(-)
 create mode 100644 fs/ext4/resize-test.c
fs/ext4/Makefile +2 -1
index c18530508863..6163d47f3627 100644
@@ -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
index afde7567c661..1f9c044f7e24 100644
@@ -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()
  */
@@ -3432,6 +3443,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,
@@ -3441,6 +3454,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 +1336 -0

1,336 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.1.708.g77570a6a1d-goog
#36 lore raw

Re: [PATCH -v2 18/26] ext4: add KUnit tests for fs/ext4/resize.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: NULL b_bdev in resize_init_mock_bh() crashes trace_block_dirty_buffer() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: NULL b_bdev in resize_init_mock_bh() crashes trace_block_dirty_buffer()
--

commit de282382ebae06ada6fcade5556ed1357d9a76d9
Author: Theodore Ts'o <[email protected]>

ext4: add KUnit tests for fs/ext4/resize.c

This commit adds a KUnit test suite for fs/ext4/resize.c and routes resize metadata I/O through stubbable helpers so online resize paths can be tested in memory.

Quoted 6 lines
fs/ext4/resize-test.c new file +0 -0
new file mode 100644
index 0000000000000..81c9fd96816c6
@@ -0,0 +1,1336 @@

[ ... ]

fs/ext4/resize-test.c line 168

Quoted 11 lines
fs/ext4/resize-test.c new file +11 -0
+static void resize_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]
Should resize_init_mock_bh() also set bh->b_bdev (for example, to &ctx->bdev)? Because these tests run without a journal and do not stub __ext4_handle_dirty_metadata(), ext4_handle_dirty_metadata() calls mark_buffer_dirty() -> trace_block_dirty_buffer(), which dereferences bh->b_bdev->bd_dev when the block:block_dirty_buffer tracepoint is enabled.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=18
author maintainer
#37 lore raw

PATCH 19/26 ext4: add KUnit tests for fs/ext4/migrate.c

In reply to Theodore Ts'o

Add 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         |    8 +-
 fs/ext4/migrate-test.c | 1061 ++++++++++++++++++++++++++++++++++++++++
 fs/ext4/migrate.c      |   11 +
 4 files changed, 1079 insertions(+), 3 deletions(-)
 create mode 100644 fs/ext4/migrate-test.c
fs/ext4/Makefile +1 -1
index 6163d47f3627..fafd9600cacb 100644
@@ -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 +6 -2
index 1f9c044f7e24..b648df826a5d 100644
@@ -3418,6 +3418,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,
@@ -3734,8 +3738,8 @@ static inline ext4_fsblk_t ext4_free_blocks_count(struct ext4_super_block *es)
 static inline void ext4_blocks_count_set(struct ext4_super_block *es,
 					 ext4_fsblk_t blk)
 {
-	es->s_blocks_count_lo = cpu_to_le32((u32)blk);
-	es->s_blocks_count_hi = cpu_to_le32(blk >> 32);
+	es->s_blocks_count_lo = cpu_to_le32(lower_32_bits(blk));
+	es->s_blocks_count_hi = cpu_to_le32(upper_32_bits(blk));
 }
 
 static inline void ext4_free_blocks_count_set(struct ext4_super_block *es,
fs/ext4/migrate-test.c new file +1061 -0

1,061 lines not on this page · raw message

fs/ext4/migrate.c +11 -0
index cdef31eaa490..807bd30341e6 100644
@@ -615,6 +615,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
@@ -703,3 +704,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.1.708.g77570a6a1d-goog
#38 lore raw

Re: [PATCH -v2 19/26] ext4: add KUnit tests for fs/ext4/migrate.c

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Add 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

Quoted 4 lines

Export ext4_ext_migrate(), ext4_ind_migrate(), and a KUnit wrapper for ext4_ext_swap_inode_data() via EXPORT_SYMBOL_FOR_EXT4_TEST.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=19
author maintainer
#39 lore raw

PATCH 20/26 ext4: add KUnit tests for fs/ext4/indirect.c

In reply to Theodore Ts'o

Add 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 | 1293 +++++++++++++++++++++++++++++++++++++++
 fs/ext4/indirect.c      |   18 +-
 fs/ext4/super.c         |    7 +-
 5 files changed, 1321 insertions(+), 4 deletions(-)
 create mode 100644 fs/ext4/indirect-test.c
fs/ext4/Makefile +2 -1
index fafd9600cacb..503acc946409 100644
@@ -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
index b648df826a5d..03689d55e751 100644
@@ -3371,6 +3371,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 +1293 -0

1,293 lines not on this page · raw message

fs/ext4/indirect.c +16 -2
index 15c978f37a5c..fd6d60f0323d 100644
@@ -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;
@@ -688,6 +689,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
@@ -702,6 +704,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)
@@ -1230,6 +1233,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
@@ -1489,3 +1493,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
index cccbb2e3ad5f..880f664d6c04 100644
@@ -296,11 +296,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.1.708.g77570a6a1d-goog
#40 lore raw

Re: [PATCH -v2 20/26] ext4: add KUnit tests for fs/ext4/indirect.c

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] ext4: leak of test inode and handle on KUNIT_ASSERT abort in indirect-test.c --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] ext4: leak of test inode and handle on KUNIT_ASSERT abort in indirect-test.c
--

commit ac1d07e8010829fce0fd4a0596e2f92e79885c99
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 covering legacy indirect block mapping, truncation, and hole punching in fs/ext4/indirect.c.

Quoted 5 lines
fs/ext4/indirect-test.c new file +0 -0
new file mode 100644
index 0000000000000..8d4a430ecb272

[ ... ]

Quoted 25 lines
fs/ext4/indirect-test.c new file +25 -0
+static __le32 *ind_blk_ptrs(struct kunit *test, ext4_fsblk_t blk)
+{
+	struct ind_test_ctx *ctx = test->priv;
+	struct buffer_head *bh;
+
+	bh = ind_get_or_create_bh(ctx, blk);
+	KUNIT_ASSERT_NOT_NULL(test, bh);
+	brelse(bh);
+	return (__le32 *)bh->b_data;
+}
+
+static struct inode *ind_make_test_inode(struct kunit *test, unsigned long ino)
+{
+	struct ind_test_ctx *ctx = test->priv;
+	struct inode *inode;
+
+	inode = new_inode(ctx->sb);
+	KUNIT_ASSERT_NOT_NULL(test, inode);
+	inode->i_ino = ino;
+	inode->i_mode = S_IFREG | 0644;
+	inode->i_blkbits = IND_TEST_BLK_BITS;
+	inode->i_flags |= S_NOQUOTA;
+	EXT4_I(inode)->i_block_group = 0;
+	return inode;
+}

[ ... ]

Quoted 11 lines
fs/ext4/indirect-test.c new file +11 -0
+static void test_ind_remove_space_levels_and_convergence(struct kunit *test)
+{
+	struct ind_test_ctx *ctx = test->priv;
+	struct inode *inode = ind_make_test_inode(test, 17);
+	__le32 *ind, *dind, *c0, *c1, *c2;
+	handle_t *handle;
+	unsigned int i;
+	int ret;
+
+	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 8);
+	KUNIT_ASSERT_FALSE(test, IS_ERR(handle));

[ ... ]

fs/ext4/indirect-test.c line 1162

Quoted 2 lines
fs/ext4/indirect-test.c new file +2 -0
+	EXT4_I(inode)->i_data[EXT4_IND_BLOCK] = cpu_to_le32(510);
+	ind = ind_blk_ptrs(test, 510);

[Severity: Low]
Can a KUNIT_ASSERT_* failure after ind_make_test_inode() or ext4_journal_start() leak the test inode and journal handle?

If ind_get_or_create_bh() fails inside ind_blk_ptrs() (or in test_ind_map_blocks_errors_and_alloc_branch_unwind()), or if ext4_journal_start() fails after ind_make_test_inode(), the test aborts before reaching ext4_journal_stop() and iput(). That leaves the no-journal handle in current->journal_info with memalloc_nofs_save() active on the KUnit runner thread, and leaves an active inode on ctx->sb->s_inodes when ind_test_cleanup() calls deactivate_super(sb). Registering KUnit cleanup actions for the inode (as in migrate_make_test_inode()) and handle, or releasing them before aborting, would avoid this.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=20
author maintainer
#41 lore raw

PATCH 21/26 ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations

In reply to Theodore Ts'o

Expand 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 | 528 ++++++++++++++++++++++++++++++++++++++++-
 fs/ext4/extents.c      |   6 +
 2 files changed, 532 insertions(+), 2 deletions(-)
fs/ext4/extents-test.c +526 -2
index bc5488293103..6458345ea958 100644
@@ -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 @@ static 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,21 +210,31 @@ 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);
 	i_size_ordered_init(inode);
 	init_rwsem(&inode->i_rwsem);
+	address_space_init_once(&inode->i_data);
 	init_rwsem(&inode->i_data.invalidate_lock);
+	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;
@@ -271,6 +291,7 @@ static void extents_kunit_exit(struct kunit *test)
 
 	kfree(k_ctx.meta_blocks);
 	kfree(sbi->s_es);
+	kfree(bdev->bd_queue);
 	kfree(bdev->bd_mapping);
 	kfree(bdev);
 	kfree(sbi);
@@ -496,16 +517,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;
@@ -513,12 +540,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);
@@ -628,6 +663,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:
@@ -2458,6 +2495,487 @@ 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(handle_t *handle, 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(handle_t *handle, 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;
+	bool found = false;
+	int err = 0;
+
+	down_read(&EXT4_I(inode)->i_data_sem);
+	path = ext4_find_extent(inode, lblk, NULL, EXT4_EX_NOCACHE);
+	if (IS_ERR(path)) {
+		err = PTR_ERR(path);
+	} else {
+		if (path[path->p_depth].p_ext) {
+			ex = *path[path->p_depth].p_ext;
+			found = true;
+		}
+		ext4_free_ext_path(path);
+	}
+	up_read(&EXT4_I(inode)->i_data_sem);
+
+	KUNIT_ASSERT_EQ(test, err, 0);
+	KUNIT_ASSERT_TRUE(test, found);
+
+	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);
+}
+
+/*
+ * 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",
@@ -3018,6 +3536,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
index 0a442844b954..cbe187914fe2 100644
@@ -5106,6 +5106,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
@@ -5201,6 +5202,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
@@ -5293,6 +5295,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)
 {
@@ -5324,6 +5327,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)
 {
@@ -5436,6 +5440,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)
@@ -5483,6 +5488,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.1.708.g77570a6a1d-goog
#42 lore raw

Re: [PATCH -v2 21/26] ext4: expand KUnit tests in fs/ext4/extents-test.c for file range operations

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Expand 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

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=21
author maintainer
#43 lore raw

PATCH 22/26 ext4: add KUnit tests for fs/ext4/fsmap.c

In reply to Theodore Ts'o

Add 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 | 796 +++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/fsmap.c      |   3 +
 fs/ext4/mballoc.c    |   3 +
 4 files changed, 803 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/fsmap-test.c
fs/ext4/Makefile +1 -1
index 503acc946409..e1964407be24 100644
@@ -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 +796 -0

796 lines not on this page · raw message

fs/ext4/fsmap.c +3 -0
index 8b1138d2dc8e..f41c2298d196 100644
@@ -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
index b346f8bbee89..81a4f45906d3 100644
@@ -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.1.708.g77570a6a1d-goog
#44 lore raw

Re: [PATCH -v2 22/26] ext4: add KUnit tests for fs/ext4/fsmap.c

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Add 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

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
author maintainer
#45 lore raw

PATCH 23/26 ext4: add KUnit tests for fs/ext4/move_extent.c

In reply to Theodore Ts'o

Add 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 | 1023 ++++++++++++++++++++++++++++++++++++
 fs/ext4/move_extent.c      |   21 +-
 4 files changed, 1052 insertions(+), 3 deletions(-)
 create mode 100644 fs/ext4/move_extent-test.c
fs/ext4/Makefile +2 -1
index e1964407be24..5cf735df7656 100644
@@ -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
index 03689d55e751..29277a79c65b 100644
@@ -4250,6 +4250,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 */
 /*
fs/ext4/move_extent-test.c new file +1023 -0

1,023 lines not on this page · raw message

fs/ext4/move_extent.c +19 -2
index e5450e83da80..15f4126c5c51 100644
@@ -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,
@@ -667,8 +669,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.1.708.g77570a6a1d-goog
#46 lore raw

Re: [PATCH -v2 23/26] ext4: add KUnit tests for fs/ext4/move_extent.c

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

Add 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

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
author maintainer
#47 lore raw

PATCH 24/26 ext4: add KUnit tests for fs/ext4/mmp.c

In reply to Theodore Ts'o

Add 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
index 5cf735df7656..cb0d7b6edf6d 100644
@@ -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
index 29277a79c65b..9cf1dd6351a7 100644
@@ -4285,9 +4285,25 @@ extern void ext4_iomap_end_bio(struct bio *bio);
 
 /* 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.1.708.g77570a6a1d-goog
#48 lore raw

Re: [PATCH -v2 24/26] 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 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

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=24
author maintainer
#49 lore raw

PATCH 25/26 ext4: add KUnit tests for fs/ext4/dir.c

In reply to Theodore Ts'o

Add 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 | 993 +++++++++++++++++++++++++++++++++++++++++++++
 fs/ext4/dir.c      |  33 ++
 fs/ext4/ext4.h     |   8 +
 fs/ext4/namei.c    |   4 +
 5 files changed, 1040 insertions(+), 1 deletion(-)
 create mode 100644 fs/ext4/dir-test.c
fs/ext4/Makefile +2 -1
index cb0d7b6edf6d..a427f6f361e5 100644
@@ -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 +993 -0

993 lines not on this page · raw message

fs/ext4/dir.c +33 -0
index f9b6aaabcd17..43f4f2d451aa 100644
@@ -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
index 9cf1dd6351a7..646c017dda1c 100644
@@ -3069,6 +3069,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
index ed590010b046..b2753daad49f 100644
@@ -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.1.708.g77570a6a1d-goog
#50 lore raw

Re: [PATCH -v2 25/26] ext4: add KUnit tests for fs/ext4/dir.c

Sashiko has reviewed this patch and found no issues.
Quoted 25 lines

Add 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.

Quoted 5 lines

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().

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
author maintainer
#51 lore raw

PATCH 26/26 ext4: add KUnit regression tests for inode migration fixes

In reply to Theodore Ts'o

Add KUnit regression tests in fs/ext4/migrate-test.c covering the ext4_ext_migrate() bug fixes in the tree:

- test_ext_migrate_caps_long_run_at_init_max_len(): verify that a contiguous run longer than EXT_INIT_MAX_LEN is split into multiple initialized extents, covering commit b0a3f2c102e8 ("ext4: cap migration extent length at EXT_INIT_MAX_LEN").
- test_ext_migrate_survives_handle_restart(): verify that a handle restart during extent insertion does not abort migration, covering commit 3b6aee59883c ("ext4: clear journal restart indication after inserting extent").
- test_ext_migrate_reports_concurrent_allocation() and an -EIO check in test_ext_migrate_error_rollback_frees_tmp_extent_blocks(): verify that migration errors are returned to the caller instead of being overwritten, covering commit 82e2a5743b6a ("ext4: don't clobber the migration error in ext4_ext_migrate()").
- test_ext_migrate_credit_or_dirty_failure_keeps_live_blocks(): verify that post-swap ext4_journal_ensure_credits() or ext4_mark_inode_dirty() failures leave tmp_inode empty on eviction and do not free the migrated inode's extent blocks, covering commit 047061e6a6da ("ext4:
don't free the tmp_inode tree after a partial migration swap"), commit ed8c07b7692c ("ext4: drop tmp inode ownership before migration cleanup"), and commit 7c1f0eea4a9b ("ext4: fix failed migrate freeing extent tree blocks").

Add KUNIT_STATIC_STUB_REDIRECT() hooks and EXPORT_SYMBOL_FOR_EXT4_TEST() exports for ext4_datasem_ensure_credits() in fs/ext4/extents.c and __ext4_journal_ensure_credits() in fs/ext4/ext4_jbd2.c so the KUnit tests can emulate transaction restarts, concurrent block allocations, and post-swap credit failures without a journal.

---
 fs/ext4/ext4_jbd2.c    |   4 +
 fs/ext4/extents.c      |   4 +
 fs/ext4/migrate-test.c | 329 ++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 334 insertions(+), 3 deletions(-)
fs/ext4/ext4_jbd2.c +4 -0
index 3e6c9ce108ad..23e53c9cc0ce 100644
@@ -186,6 +186,9 @@ handle_t *__ext4_journal_start_reserved(handle_t *handle, unsigned int line,
 int __ext4_journal_ensure_credits(handle_t *handle, int check_cred,
 				  int extend_cred, int revoke_cred)
 {
+	KUNIT_STATIC_STUB_REDIRECT(__ext4_journal_ensure_credits, handle,
+				   check_cred, extend_cred, revoke_cred);
+
 	if (!ext4_handle_valid(handle))
 		return 0;
 	if (is_handle_aborted(handle))
@@ -197,6 +200,7 @@ int __ext4_journal_ensure_credits(handle_t *handle, int check_cred,
 	revoke_cred = max(0, revoke_cred - handle->h_revoke_credits);
 	return ext4_journal_extend(handle, extend_cred, revoke_cred);
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_journal_ensure_credits);
 
 static void ext4_journal_abort_handle(const char *caller, unsigned int line,
 				      const char *err_fn,
fs/ext4/extents.c +4 -0
index cbe187914fe2..10d36012ade4 100644
@@ -142,12 +142,16 @@ int ext4_datasem_ensure_credits(handle_t *handle, struct inode *inode,
 	int ret;
 	int dropped = 0;
 
+	KUNIT_STATIC_STUB_REDIRECT(ext4_datasem_ensure_credits, handle, inode,
+				   check_cred, restart_cred, revoke_cred);
+
 	ret = ext4_journal_ensure_credits_fn(handle, check_cred, restart_cred,
 		revoke_cred, ext4_ext_trunc_restart_fn(inode, &dropped));
 	if (dropped)
 		down_write(&EXT4_I(inode)->i_data_sem);
 	return ret;
 }
+EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_datasem_ensure_credits);
 
 /*
  * could return:
fs/ext4/migrate-test.c +326 -3

377 lines not on this page · raw message

Signature · 1 line
2.56.1.708.g77570a6a1d-goog
#52 lore raw

Re: [PATCH -v2 26/26] ext4: add KUnit regression tests for inode migration fixes

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

Add KUnit regression tests in fs/ext4/migrate-test.c covering the ext4_ext_migrate() bug fixes in the tree:

- test_ext_migrate_caps_long_run_at_init_max_len(): verify that a contiguous run longer than EXT_INIT_MAX_LEN is split into multiple initialized extents, covering commit b0a3f2c102e8 ("ext4: cap migration extent length at EXT_INIT_MAX_LEN").
- test_ext_migrate_survives_handle_restart(): verify that a handle restart during extent insertion does not abort migration, covering commit 3b6aee59883c ("ext4: clear journal restart indication after inserting extent").
- test_ext_migrate_reports_concurrent_allocation() and an -EIO check in test_ext_migrate_error_rollback_frees_tmp_extent_blocks(): verify that migration errors are returned to the caller instead of being overwritten, covering commit 82e2a5743b6a ("ext4: don't clobber the
[ ... ]
__ext4_journal_ensure_credits() in fs/ext4/ext4_jbd2.c so the KUnit tests can emulate transaction restarts, concurrent block allocations, and post-swap credit failures without a journal.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=26