Linux EXT4 FS development
 help / color / mirror / Atom feed
* [PATCH] ext4: bound xattr journal credits to transaction limit
@ 2026-11-22  7:53 arzuagapozosergio
  2026-11-22  8:09 ` sashiko-bot
  2026-11-22  8:49 ` [PATCH v2] " arzuagapozosergio
  0 siblings, 2 replies; 5+ messages in thread
From: arzuagapozosergio @ 2026-11-22  7:53 UTC (permalink / raw)
  To: tytso; +Cc: jack, linux-ext4, Ryuji Hiroshi, syzbot+25d45c0bd716f2b794a7

From: Ryuji Hiroshi <182191995+root465-lipcripto@users.noreply.github.com>

When setting an xattr without XATTR_CREATE, ext4 reserves credits for
freeing an old ea_inode sized up to XATTR_SIZE_MAX, even when the
attribute does not exist. On a 1 KiB-block filesystem with a minimum
journal, this can request 341 credits while JBD2 permits 334, triggering
a warning before the setxattr operation fails.

Look up the existing attribute under xattr_sem and account for its actual
ea_inode value size. Recheck the estimate under the write lock before
modifying the xattr, since the attribute may change between estimating
credits and starting the transaction. Reject estimates above JBD2's
maximum transaction credits before starting a journal handle.

Add an EXT4 selftest covering large xattr creation and readback,
oversized replacement rejection with value preservation, XATTR_CREATE,
removal, and a small user xattr round trip.

Tested with a QEMU/KVM guest using the syzbot reproducer and the new
selftest. The original xattr operation succeeds, an oversized replacement
returns -ENOSPC without changing the old value, and e2fsck -fn exits 0
after unmount.

Fixes: dec214d00e0d ("ext4: xattr inode deduplication")
Reported-by: syzbot+25d45c0bd716f2b794a7@syzkaller.appspotmail.com
Link: https://syzbot.org/bug?extid=25d45c0bd716f2b794a7
Signed-off-by: Ryuji Hiroshi <182191995+root465-lipcripto@users.noreply.github.com>
---
 fs/ext4/acl.c                                 |   7 +-
 fs/ext4/crypto.c                              |   5 +-
 fs/ext4/ialloc.c                              |   6 +-
 fs/ext4/xattr.c                               | 132 +++++++++++++-----
 fs/ext4/xattr.h                               |   7 +-
 fs/jbd2/transaction.c                         |   6 +
 include/linux/jbd2.h                          |   1 +
 tools/testing/selftests/Makefile              |   1 +
 .../selftests/filesystems/ext4/Makefile       |   6 +
 .../ext4/ext4_xattr_journal_credits.c         |  89 ++++++++++++
 .../ext4/ext4_xattr_journal_credits.sh        |  41 ++++++
 11 files changed, 254 insertions(+), 47 deletions(-)
 create mode 100644 tools/testing/selftests/filesystems/ext4/Makefile
 create mode 100644 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
 create mode 100755 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh

diff --git a/fs/ext4/acl.c b/fs/ext4/acl.c
index 59fac55a2..07b351694 100644
--- a/fs/ext4/acl.c
+++ b/fs/ext4/acl.c
@@ -239,8 +239,11 @@ ext4_set_acl(const struct mnt_idmap *idmap, struct dentry *dentry,
 	if (error)
 		return error;
 retry:
-	error = ext4_xattr_set_credits(inode, acl_size, false /* is_create */,
-				       &credits);
+	error = ext4_xattr_set_credits(inode,
+				       type == ACL_TYPE_ACCESS ?
+				       EXT4_XATTR_INDEX_POSIX_ACL_ACCESS :
+				       EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT,
+				       "", acl_size, false /* is_create */, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c
index 318b2eaea..98afd33b0 100644
--- a/fs/ext4/crypto.c
+++ b/fs/ext4/crypto.c
@@ -203,8 +203,9 @@ static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
 	if (res)
 		return res;
 retry:
-	res = ext4_xattr_set_credits(inode, len, false /* is_create */,
-				     &credits);
+	res = ext4_xattr_set_credits(inode, EXT4_XATTR_INDEX_ENCRYPTION,
+				     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
+				     len, false /* is_create */, &credits);
 	if (res)
 		return res;
 
diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c
index 527f1f703..927b2e8f0 100644
--- a/fs/ext4/ialloc.c
+++ b/fs/ext4/ialloc.c
@@ -889,7 +889,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += (S_ISDIR(mode) ? 2 : 1) *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, acl_size,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 		posix_acl_release(p);
 	}
 #endif
@@ -908,7 +908,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += num_security_xattrs *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, 1024,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 	}
 #endif
 	if (encrypt)
@@ -916,7 +916,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 						    NULL /* inode */,
 						    NULL /* block_bh */,
 						    FSCRYPT_SET_CONTEXT_MAX_SIZE,
-						    true /* is_create */);
+						    true /* is_create */, 0);
 	return nblocks;
 }
 
diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c
index 5c310747b..a904ea1dc 100644
--- a/fs/ext4/xattr.c
+++ b/fs/ext4/xattr.c
@@ -949,7 +949,7 @@ static void ext4_xattr_inode_free_quota(struct inode *parent,
 
 int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 			     struct buffer_head *block_bh, size_t value_len,
-			     bool is_create)
+			     bool is_create, size_t old_ea_value_len)
 {
 	int credits;
 	int blocks;
@@ -998,14 +998,15 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 	/* Blocks themselves. */
 	credits += blocks;
 
-	if (!is_create) {
+	if (!is_create && old_ea_value_len) {
 		/* Dereference ea_inode holding old xattr value.
 		 * Old ea_inode, inode map, block bitmap, group descriptor.
 		 */
 		credits += 4;
 
 		/* Data blocks for old ea_inode. */
-		blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
+		blocks = (old_ea_value_len + sb->s_blocksize - 1) >>
+			 sb->s_blocksize_bits;
 
 		/* Indirection block or one level of extent tree for old
 		 * ea_inode.
@@ -2375,29 +2376,6 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 
 	ext4_write_lock_xattr(inode, &no_expand);
 
-	/* Check journal credits under write lock. */
-	if (ext4_handle_valid(handle)) {
-		struct buffer_head *bh;
-		int credits;
-
-		bh = ext4_xattr_get_block(inode);
-		if (IS_ERR(bh)) {
-			error = PTR_ERR(bh);
-			goto cleanup;
-		}
-
-		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						   value_len,
-						   flags & XATTR_CREATE);
-		brelse(bh);
-
-		if (jbd2_handle_buffer_credits(handle) < credits) {
-			error = -ENOSPC;
-			goto cleanup;
-		}
-		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
-	}
-
 	error = ext4_reserve_inode_write(handle, inode, &is.iloc);
 	if (error)
 		goto cleanup;
@@ -2415,6 +2393,38 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 		error = ext4_xattr_block_find(inode, &i, &bs);
 	if (error)
 		goto cleanup;
+
+	/* Check journal credits under write lock using the old value size. */
+	if (ext4_handle_valid(handle)) {
+		struct ext4_xattr_entry *entry = NULL;
+		size_t old_ea_value_len = 0;
+		int credits;
+
+		if (!is.s.not_found)
+			entry = is.s.here;
+		else if (!bs.s.not_found)
+			entry = bs.s.here;
+		if (entry && entry->e_value_inum &&
+		    !(flags & XATTR_CREATE))
+			old_ea_value_len = le32_to_cpu(entry->e_value_size);
+
+		struct buffer_head *bh = ext4_xattr_get_block(inode);
+
+		if (IS_ERR(bh)) {
+			error = PTR_ERR(bh);
+			goto cleanup;
+		}
+		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
+						   value_len,
+						   flags & XATTR_CREATE,
+						   old_ea_value_len);
+		brelse(bh);
+		if (jbd2_handle_buffer_credits(handle) < credits) {
+			error = -ENOSPC;
+			goto cleanup;
+		}
+		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
+	}
 	if (is.s.not_found && bs.s.not_found) {
 		error = -ENODATA;
 		if (flags & XATTR_REPLACE)
@@ -2500,28 +2510,76 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 	return error;
 }
 
-int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
 			   bool is_create, int *credits)
 {
-	struct buffer_head *bh;
-	int err;
+	struct ext4_xattr_info i = {
+		.name_index = name_index,
+		.name = name,
+	};
+	struct ext4_xattr_ibody_find is = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_block_find bs = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_entry *entry = NULL;
+	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
+	size_t old_ea_value_len = 0;
+	int max_credits, err;
 
 	*credits = 0;
+	if (!name)
+		return -EINVAL;
+	if (strlen(name) > 255)
+		return -ERANGE;
 
-	if (!EXT4_SB(inode->i_sb)->s_journal)
+	if (!journal)
 		return 0;
 
+	/*
+	 * The old ea_inode is only charged when the target attribute currently
+	 * references one.  xattr_sem is dropped before the transaction starts,
+	 * so ext4_xattr_set_handle() repeats this check under the write lock.
+	 */
 	down_read(&EXT4_I(inode)->xattr_sem);
 
-	bh = ext4_xattr_get_block(inode);
-	if (IS_ERR(bh)) {
-		err = PTR_ERR(bh);
+	err = ext4_get_inode_loc(inode, &is.iloc);
+	if (err)
+		goto out_unlock;
+	err = ext4_xattr_ibody_find(inode, &i, &is);
+	if (err)
+		goto out;
+	if (!is.s.not_found) {
+		entry = is.s.here;
 	} else {
+		err = ext4_xattr_block_find(inode, &i, &bs);
+		if (err)
+			goto out;
+		if (!bs.s.not_found)
+			entry = bs.s.here;
+	}
+	if (!is_create && entry && entry->e_value_inum)
+		old_ea_value_len = le32_to_cpu(entry->e_value_size);
+	{
+		struct buffer_head *bh = ext4_xattr_get_block(inode);
+
+		if (IS_ERR(bh)) {
+			err = PTR_ERR(bh);
+			goto out;
+		}
 		*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						    value_len, is_create);
+						    value_len, is_create,
+						    old_ea_value_len);
 		brelse(bh);
-		err = 0;
 	}
+	max_credits = jbd2_journal_get_max_transaction_buffers(journal);
+	err = *credits > max_credits ? -ENOSPC : 0;
+out:
+	brelse(is.iloc.bh);
+	brelse(bs.bh);
+out_unlock:
 
 	up_read(&EXT4_I(inode)->xattr_sem);
 	return err;
@@ -2549,8 +2607,8 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name,
 		return error;
 
 retry:
-	error = ext4_xattr_set_credits(inode, value_len, flags & XATTR_CREATE,
-				       &credits);
+	error = ext4_xattr_set_credits(inode, name_index, name, value_len,
+				       flags & XATTR_CREATE, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/xattr.h b/fs/ext4/xattr.h
index 821dc6a50..e98379eed 100644
--- a/fs/ext4/xattr.h
+++ b/fs/ext4/xattr.h
@@ -175,11 +175,12 @@ extern ssize_t ext4_listxattr(struct dentry *, char *, size_t);
 extern int ext4_xattr_get(struct inode *, int, const char *, void *, size_t);
 extern int ext4_xattr_set(struct inode *, int, const char *, const void *, size_t, int);
 extern int ext4_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);
-extern int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
-				  bool is_create, int *credits);
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
+			   bool is_create, int *credits);
 extern int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 				struct buffer_head *block_bh, size_t value_len,
-				bool is_create);
+				bool is_create, size_t old_ea_value_len);
 
 extern int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,
 				   int extra_credits);
diff --git a/fs/jbd2/transaction.c b/fs/jbd2/transaction.c
index 85d84d909..cbc5c8775 100644
--- a/fs/jbd2/transaction.c
+++ b/fs/jbd2/transaction.c
@@ -194,6 +194,12 @@ static int jbd2_max_user_trans_buffers(journal_t *journal)
 				journal->j_transaction_overhead_buffers;
 }
 
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal)
+{
+	return jbd2_max_user_trans_buffers(journal);
+}
+EXPORT_SYMBOL(jbd2_journal_get_max_transaction_buffers);
+
 /*
  * Wait until we can add credits for handle to the running transaction.  Called
  * with j_state_lock held for reading. Returns 0 if handle joined the running
diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h
index e3886963b..ed09abac1 100644
--- a/include/linux/jbd2.h
+++ b/include/linux/jbd2.h
@@ -1523,6 +1523,7 @@ static inline handle_t *journal_current_handle(void)
  */
 
 extern handle_t *jbd2_journal_start(journal_t *, int nblocks);
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal);
 extern handle_t *jbd2__journal_start(journal_t *, int blocks, int rsv_blocks,
 				     int revoke_records, gfp_t gfp_mask,
 				     unsigned int type, unsigned int line_no);
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8..c16b1132e 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -37,6 +37,7 @@ TARGETS += filesystems/binderfs
 TARGETS += filesystems/configfs
 TARGETS += filesystems/epoll
 TARGETS += filesystems/eventfd
+TARGETS += filesystems/ext4
 TARGETS += filesystems/failfs
 TARGETS += filesystems/fat
 TARGETS += filesystems/file_stressor
diff --git a/tools/testing/selftests/filesystems/ext4/Makefile b/tools/testing/selftests/filesystems/ext4/Makefile
new file mode 100644
index 000000000..b271567c0
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := ext4_xattr_journal_credits
+TEST_PROGS := ext4_xattr_journal_credits.sh
+
+include ../../lib.mk
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
new file mode 100644
index 000000000..13f4f6673
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: GPL-2.0
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/xattr.h>
+#include <unistd.h>
+
+#define LARGE_VALUE_SIZE 65296
+
+static int fail(const char *what)
+{
+	fprintf(stderr, "FAIL: %s: %s\n", what, strerror(errno));
+	return 1;
+}
+
+int main(int argc, char **argv)
+{
+	char path[4096];
+	char *value, *readback;
+	int path_len;
+	static const char large_name[] = "security.ima";
+	static const char small_name[] = "user.ext4-credit-test";
+	static const char small_value[] = "small-xattr";
+	char small_readback[sizeof(small_value)];
+
+	if (argc != 2) {
+		fprintf(stderr, "Usage: %s MOUNTPOINT\n", argv[0]);
+		return 2;
+	}
+	path_len = snprintf(path, sizeof(path), "%s/credit-test", argv[1]);
+	if (path_len < 0 || (size_t)path_len >= sizeof(path)) {
+		fprintf(stderr, "Mount path is too long\n");
+		return 2;
+	}
+
+	if (creat(path, 0600) < 0)
+		return fail("create test file");
+
+	value = malloc(LARGE_VALUE_SIZE);
+	readback = malloc(LARGE_VALUE_SIZE);
+	if (!value || !readback)
+		return fail("allocate xattr buffers");
+	memset(value, 0x5a, LARGE_VALUE_SIZE);
+	value[0] = 1;
+
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, 0) < 0)
+		return fail("create large ea_inode xattr");
+	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
+	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE))
+		return fail("verify newly created xattr");
+	puts("PASS: large xattr creation and readback");
+
+	value[0] = 2;
+	errno = 0;
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_REPLACE) !=
+	    -1 || errno != ENOSPC)
+		return fail("oversized replacement should return ENOSPC");
+	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
+	    LARGE_VALUE_SIZE || readback[0] != 1)
+		return fail("failed replacement changed the old value");
+	puts("PASS: oversized replacement rejected without changing old value");
+
+	errno = 0;
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_CREATE) !=
+	    -1 || errno != EEXIST)
+		return fail("XATTR_CREATE on existing name should return EEXIST");
+	puts("PASS: XATTR_CREATE semantics");
+
+	if (removexattr(path, large_name) < 0)
+		return fail("remove large xattr");
+	puts("PASS: large xattr removal");
+
+	if (setxattr(path, small_name, small_value, sizeof(small_value), 0) < 0)
+		return fail("create small user xattr");
+	if (getxattr(path, small_name, small_readback, sizeof(small_readback)) !=
+	    sizeof(small_value) ||
+	    memcmp(small_value, small_readback, sizeof(small_value)))
+		return fail("verify small user xattr");
+	if (removexattr(path, small_name) < 0)
+		return fail("remove small user xattr");
+	puts("PASS: small user xattr create, readback, and removal");
+
+	free(readback);
+	free(value);
+	return 0;
+}
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
new file mode 100755
index 000000000..837329fbd
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
@@ -0,0 +1,41 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+KSFT_SKIP=4
+
+skip()
+{
+	printf 'SKIP: %s\n' "$1"
+	exit "$KSFT_SKIP"
+}
+
+[ "$(id -u)" -eq 0 ] || skip "requires root to mount a disposable EXT4 image"
+
+for command in mkfs.ext4 mount umount truncate e2fsck; do
+	command -v "$command" >/dev/null 2>&1 || skip "missing $command"
+done
+
+test_dir=$(mktemp -d) || exit 1
+mounted=0
+
+cleanup()
+{
+	if [ "$mounted" -eq 1 ]; then
+		umount "$test_dir/mnt" || true
+	fi
+	rm -rf "$test_dir"
+}
+trap cleanup EXIT INT TERM
+
+truncate -s 32M "$test_dir/fs.img" || exit 1
+mkfs.ext4 -q -F -b 1024 -O ea_inode -J size=1 "$test_dir/fs.img" || exit 1
+mkdir "$test_dir/mnt" || exit 1
+mount -t ext4 -o loop "$test_dir/fs.img" "$test_dir/mnt" || exit 1
+mounted=1
+
+test_bin="$(dirname "$0")/ext4_xattr_journal_credits"
+"$test_bin" "$test_dir/mnt" || exit $?
+
+umount "$test_dir/mnt" || exit 1
+mounted=0
+e2fsck -fn "$test_dir/fs.img"

base-commit: c44104f3642da720164042623e4832836aefdd8e
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* Re: [PATCH] ext4: bound xattr journal credits to transaction limit
  2026-11-22  7:53 [PATCH] ext4: bound xattr journal credits to transaction limit arzuagapozosergio
@ 2026-11-22  8:09 ` sashiko-bot
  2026-11-22  8:49 ` [PATCH v2] " arzuagapozosergio
  1 sibling, 0 replies; 5+ messages in thread
From: sashiko-bot @ 2026-11-22  8:09 UTC (permalink / raw)
  To: arzuagapozosergio; +Cc: linux-ext4, tytso

Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [Medium] ext4: ext4_xattr_set_credits() bound check omits default
  revoke block credits
- [Medium] ext4: __ext4_xattr_set_credits() overcharges for deferred
  ea_inode eviction
- [Medium] selftests: ext4: helper binary listed in TEST_GEN_PROGS
  breaks make run_tests
- [Low] selftests: ext4: missing kselftest helpers, fd close, and mount
  skip handling
- [Low] ext4: redundant xattr block reads and lookups during credit
  calculation
--

commit c2bfcf812ed8b979038bd6d5afa72dc0e3e9494f
Author: Ryuji Hiroshi <182191995+root465-lipcripto@users.noreply.github.com>

ext4: bound xattr journal credits to transaction limit

This commit looks up existing xattr entries to charge journal credits for
the actual old ea_inode value size instead of XATTR_SIZE_MAX, rejects
estimates exceeding JBD2's maximum transaction credits, and adds an ext4
selftest.

Link: https://syzbot.org/bug?extid=25d45c0bd716f2b794a7

> diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c
> index 5c310747b9650..a904ea1dc05bc 100644
> --- a/fs/ext4/xattr.c
> +++ b/fs/ext4/xattr.c
> @@ -949,7 +949,7 @@ static void ext4_xattr_inode_free_quota(struct inode *parent,
>  
>  int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
>  			     struct buffer_head *block_bh, size_t value_len,
> -			     bool is_create)
> +			     bool is_create, size_t old_ea_value_len)
>  {
>  	int credits;
>  	int blocks;
> @@ -998,14 +998,15 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
>  	/* Blocks themselves. */
>  	credits += blocks;
>  
> -	if (!is_create) {
> +	if (!is_create && old_ea_value_len) {
>  		/* Dereference ea_inode holding old xattr value.
>  		 * Old ea_inode, inode map, block bitmap, group descriptor.
>  		 */
>  		credits += 4;
>  
>  		/* Data blocks for old ea_inode. */
> -		blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
> +		blocks = (old_ea_value_len + sb->s_blocksize - 1) >>
> +			 sb->s_blocksize_bits;
>  
>  		/* Indirection block or one level of extent tree for old
>  		 * ea_inode.

[Severity: Medium]
Does the setxattr transaction actually free the old ea_inode's data blocks
here?

ext4_xattr_set_entry() only calls ext4_xattr_inode_dec_ref() (which
dirties old_ea_inode and adds it to the orphan list when ref_count reaches
0, using 2 credits) and then releases the reference via
ext4_put_ea_inode().  Because ext4_put_ea_inode() defers the final iput()
and ext4_evict_inode() truncation to sbi->s_ea_inode_work in a separate
transaction, charging 2 * blocks credits for old_ea_value_len here causes
in-place replacements of large ea_inode xattrs on small-journal
filesystems to fail with -ENOSPC.

[ ... ]

> @@ -2415,6 +2393,38 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
>  		error = ext4_xattr_block_find(inode, &i, &bs);
>  	if (error)
>  		goto cleanup;
> +
> +	/* Check journal credits under write lock using the old value size. */
> +	if (ext4_handle_valid(handle)) {
> +		struct ext4_xattr_entry *entry = NULL;
> +		size_t old_ea_value_len = 0;
> +		int credits;
> +
> +		if (!is.s.not_found)
> +			entry = is.s.here;
> +		else if (!bs.s.not_found)
> +			entry = bs.s.here;
> +		if (entry && entry->e_value_inum &&
> +		    !(flags & XATTR_CREATE))
> +			old_ea_value_len = le32_to_cpu(entry->e_value_size);
> +
> +		struct buffer_head *bh = ext4_xattr_get_block(inode);
> +
> +		if (IS_ERR(bh)) {
> +			error = PTR_ERR(bh);
> +			goto cleanup;
> +		}
> +		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
> +						   value_len,
> +						   flags & XATTR_CREATE,
> +						   old_ea_value_len);
> +		brelse(bh);
> +		if (jbd2_handle_buffer_credits(handle) < credits) {
> +			error = -ENOSPC;
> +			goto cleanup;
> +		}
> +		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
> +	}

[Severity: Low]
When is.s.not_found is true, ext4_xattr_block_find() has already read and
validated EXT4_I(inode)->i_file_acl into bs.bh, so calling
ext4_xattr_get_block() again here (and below in ext4_xattr_set_credits())
repeats the buffer read and block validation while bs.bh is already held.
In addition, bh is declared after statements here, and
ext4_xattr_set_credits() unconditionally reads and searches the inode and
xattr block even when !ext4_has_feature_ea_inode(inode->i_sb) or is_create
is true.

[ ... ]

> @@ -2500,28 +2510,76 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
>  	return error;
>  }
>  
> -int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
> +int ext4_xattr_set_credits(struct inode *inode, int name_index,
> +			   const char *name, size_t value_len,
>  			   bool is_create, int *credits)
>  {

[ ... ]

> +	{
> +		struct buffer_head *bh = ext4_xattr_get_block(inode);
> +
> +		if (IS_ERR(bh)) {
> +			err = PTR_ERR(bh);
> +			goto out;
> +		}
>  		*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
> -						    value_len, is_create);
> +						    value_len, is_create,
> +						    old_ea_value_len);
>  		brelse(bh);
> -		err = 0;
>  	}
> +	max_credits = jbd2_journal_get_max_transaction_buffers(journal);
> +	err = *credits > max_credits ? -ENOSPC : 0;

[Severity: Medium]
Can *credits still trigger the WARN_ON(1) in start_this_handle() when
*credits is equal to max_credits?

Every caller of ext4_xattr_set_credits() passes *credits to
ext4_journal_start(), which passes
ext4_trans_default_revoke_credits(inode->i_sb) as revoke_records to
jbd2__journal_start():

fs/jbd2/transaction.c:jbd2__journal_start() {
    ...
	nblocks += DIV_ROUND_UP(revoke_records,
				journal->j_revoke_records_per_block);
	handle = new_handle(nblocks);
    ...
}

start_this_handle() then checks handle->h_total_credits (which includes at
least 1 revoke descriptor block) against
jbd2_max_user_trans_buffers(journal).  On the 1 KiB-block, 1 MiB-journal
filesystem from the test (max_credits = 334), replacing a 61-block
(62464-byte) ea_inode xattr with a 64-block (65296-byte) value yields
*credits = 334, passing this check and requesting 335 credits in
start_this_handle().

> diff --git a/tools/testing/selftests/filesystems/ext4/Makefile b/tools/testing/selftests/filesystems/ext4/Makefile
> new file mode 100644
> index 0000000000000..b271567c0a46d
> --- /dev/null
> +++ b/tools/testing/selftests/filesystems/ext4/Makefile
> @@ -0,0 +1,6 @@
> +# SPDX-License-Identifier: GPL-2.0
> +
> +TEST_GEN_PROGS := ext4_xattr_journal_credits
> +TEST_PROGS := ext4_xattr_journal_credits.sh
> +
> +include ../../lib.mk

[Severity: Medium]
Won't listing ext4_xattr_journal_credits in TEST_GEN_PROGS cause make
run_tests to fail?

lib.mk executes every binary in TEST_GEN_PROGS directly as a standalone
test with no arguments, which hits the argc != 2 check in
ext4_xattr_journal_credits.c and exits with status 2.  Helper binaries
invoked by TEST_PROGS scripts belong in TEST_GEN_PROGS_EXTENDED.

> diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
> new file mode 100644
> index 0000000000000..13f4f6673408b
> --- /dev/null
> +++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
> @@ -0,0 +1,89 @@
> +// SPDX-License-Identifier: GPL-2.0
> +#define _GNU_SOURCE
> +#include <errno.h>
> +#include <fcntl.h>
> +#include <stdio.h>
> +#include <stdlib.h>
> +#include <string.h>
> +#include <sys/xattr.h>
> +#include <unistd.h>
> +
> +#define LARGE_VALUE_SIZE 65296
> +
> +static int fail(const char *what)
> +{
> +	fprintf(stderr, "FAIL: %s: %s\n", what, strerror(errno));
> +	return 1;
> +}
> +
> +int main(int argc, char **argv)
> +{
> +	char path[4096];
> +	char *value, *readback;
> +	int path_len;
> +	static const char large_name[] = "security.ima";
> +	static const char small_name[] = "user.ext4-credit-test";
> +	static const char small_value[] = "small-xattr";
> +	char small_readback[sizeof(small_value)];
> +
> +	if (argc != 2) {
> +		fprintf(stderr, "Usage: %s MOUNTPOINT\n", argv[0]);
> +		return 2;
> +	}
> +	path_len = snprintf(path, sizeof(path), "%s/credit-test", argv[1]);
> +	if (path_len < 0 || (size_t)path_len >= sizeof(path)) {
> +		fprintf(stderr, "Mount path is too long\n");
> +		return 2;
> +	}
> +
> +	if (creat(path, 0600) < 0)
> +		return fail("create test file");
> +
> +	value = malloc(LARGE_VALUE_SIZE);
> +	readback = malloc(LARGE_VALUE_SIZE);
> +	if (!value || !readback)
> +		return fail("allocate xattr buffers");

[Severity: Low]
Could this test use the kselftest.h or kselftest_harness.h reporting
helpers instead of custom fprintf()/puts() and raw return codes?

Also, using "security.ima" for large_name fails when
CONFIG_EXT4_FS_SECURITY is disabled or when IMA/EVM validates the
attribute format (whereas a user.* attribute avoids both), creat() leaks
its returned file descriptor, and the error paths after malloc() do not
free value or readback.

> diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
> new file mode 100755
> index 0000000000000..837329fbd859b
> --- /dev/null
> +++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
> @@ -0,0 +1,41 @@

[ ... ]

> +truncate -s 32M "$test_dir/fs.img" || exit 1
> +mkfs.ext4 -q -F -b 1024 -O ea_inode -J size=1 "$test_dir/fs.img" || exit 1
> +mkdir "$test_dir/mnt" || exit 1
> +mount -t ext4 -o loop "$test_dir/fs.img" "$test_dir/mnt" || exit 1

[Severity: Low]
Should a mount failure here call skip instead of exiting with 1 so kernels
built without CONFIG_EXT4_FS or CONFIG_BLK_DEV_LOOP skip the test rather
than failing?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261122075355.81772-1-arzuagapozosergio@gmail.com?part=1

^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH v2] ext4: bound xattr journal credits to transaction limit
  2026-11-22  7:53 [PATCH] ext4: bound xattr journal credits to transaction limit arzuagapozosergio
  2026-11-22  8:09 ` sashiko-bot
@ 2026-11-22  8:49 ` arzuagapozosergio
  2026-11-22  9:09   ` sashiko-bot
  2026-11-22  9:37   ` [PATCH v3] " arzuagapozosergio
  1 sibling, 2 replies; 5+ messages in thread
From: arzuagapozosergio @ 2026-11-22  8:49 UTC (permalink / raw)
  To: tytso; +Cc: jack, linux-ext4, syzbot+25d45c0bd716f2b794a7, Ryuji Hiroshi

From: Ryuji Hiroshi <arzuagapozosergio@gmail.com>

When setting an xattr without XATTR_CREATE, ext4 reserves credits for
releasing an old ea_inode even when the attribute does not exist. On a
1 KiB-block filesystem with a minimum journal, this can request more
credits than JBD2 permits, triggering a warning before the operation
fails.

Look up the existing attribute and account for the work done when its
ea_inode reference is dropped. The final iput() and block truncation are
deferred to a separate transaction. Check the credit limit after reserving
space for the default JBD2 revoke records, and repeat the estimate under
the xattr write lock before modifying the attribute.

Add an EXT4 selftest for large xattr creation and replacement, readback,
XATTR_CREATE, oversized replacement rejection with value preservation,
removal, and a small user xattr round trip.

Changes in v2:
- Include the default revoke descriptor blocks in the JBD2 credit limit.
- Do not charge the current transaction for deferred ea_inode truncation.
- Correct selftest registration and use kselftest result reporting.
- Use user.* attributes and skip when required mount support is
  unavailable.
- Reuse the validated xattr block buffer during the locked credit check.

Tests:
- make defconfig
- make -j2 fs/ext4/xattr.o fs/jbd2/transaction.o
- make -C tools/testing/selftests/filesystems/ext4 clean all
- sh -n tools/testing/selftests/filesystems/ext4/
  ext4_xattr_journal_credits.sh
- scripts/checkpatch.pl --strict --no-tree: 0 errors; two environment or
  tree warnings for the Fixes commit lookup and new selftest MAINTAINERS
  coverage.
- Built and booted the patched x86_64 kernel in a QEMU/KVM guest.
- The EXT4 selftest passed all 8 cases as guest root on a 1 KiB-block
  ea_inode filesystem with a 1 MiB journal. e2fsck -fn passed after
  the guest unmounted it.
- The host kselftest runner correctly reported KSFT_SKIP because it cannot
  mount the disposable filesystem without root privileges.

Fixes: dec214d00e0d ("ext4: xattr inode deduplication")
Reported-by: syzbot+25d45c0bd716f2b794a7@syzkaller.appspotmail.com
Link: https://syzbot.org/bug?extid=25d45c0bd716f2b794a7
Signed-off-by: Ryuji Hiroshi <arzuagapozosergio@gmail.com>
---
 fs/ext4/acl.c                                 |   7 +-
 fs/ext4/crypto.c                              |   5 +-
 fs/ext4/ialloc.c                              |   6 +-
 fs/ext4/xattr.c                               | 165 ++++++++++++------
 fs/ext4/xattr.h                               |   7 +-
 fs/jbd2/transaction.c                         |   9 +
 include/linux/jbd2.h                          |   2 +
 tools/testing/selftests/Makefile              |   1 +
 .../selftests/filesystems/ext4/Makefile       |   6 +
 .../ext4/ext4_xattr_journal_credits.c         | 146 ++++++++++++++++
 .../ext4/ext4_xattr_journal_credits.sh        |  56 ++++++
 11 files changed, 345 insertions(+), 65 deletions(-)
 create mode 100644 tools/testing/selftests/filesystems/ext4/Makefile
 create mode 100644 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
 create mode 100755 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh

diff --git a/fs/ext4/acl.c b/fs/ext4/acl.c
index 59fac55a2..07b351694 100644
--- a/fs/ext4/acl.c
+++ b/fs/ext4/acl.c
@@ -239,8 +239,11 @@ ext4_set_acl(const struct mnt_idmap *idmap, struct dentry *dentry,
 	if (error)
 		return error;
 retry:
-	error = ext4_xattr_set_credits(inode, acl_size, false /* is_create */,
-				       &credits);
+	error = ext4_xattr_set_credits(inode,
+				       type == ACL_TYPE_ACCESS ?
+				       EXT4_XATTR_INDEX_POSIX_ACL_ACCESS :
+				       EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT,
+				       "", acl_size, false /* is_create */, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c
index 318b2eaea..98afd33b0 100644
--- a/fs/ext4/crypto.c
+++ b/fs/ext4/crypto.c
@@ -203,8 +203,9 @@ static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
 	if (res)
 		return res;
 retry:
-	res = ext4_xattr_set_credits(inode, len, false /* is_create */,
-				     &credits);
+	res = ext4_xattr_set_credits(inode, EXT4_XATTR_INDEX_ENCRYPTION,
+				     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
+				     len, false /* is_create */, &credits);
 	if (res)
 		return res;
 
diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c
index 527f1f703..927b2e8f0 100644
--- a/fs/ext4/ialloc.c
+++ b/fs/ext4/ialloc.c
@@ -889,7 +889,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += (S_ISDIR(mode) ? 2 : 1) *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, acl_size,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 		posix_acl_release(p);
 	}
 #endif
@@ -908,7 +908,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += num_security_xattrs *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, 1024,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 	}
 #endif
 	if (encrypt)
@@ -916,7 +916,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 						    NULL /* inode */,
 						    NULL /* block_bh */,
 						    FSCRYPT_SET_CONTEXT_MAX_SIZE,
-						    true /* is_create */);
+						    true /* is_create */, 0);
 	return nblocks;
 }
 
diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c
index 5c310747b..0249dc137 100644
--- a/fs/ext4/xattr.c
+++ b/fs/ext4/xattr.c
@@ -949,7 +949,7 @@ static void ext4_xattr_inode_free_quota(struct inode *parent,
 
 int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 			     struct buffer_head *block_bh, size_t value_len,
-			     bool is_create)
+			     bool is_create, bool old_ea_inode)
 {
 	int credits;
 	int blocks;
@@ -998,23 +998,14 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 	/* Blocks themselves. */
 	credits += blocks;
 
-	if (!is_create) {
-		/* Dereference ea_inode holding old xattr value.
-		 * Old ea_inode, inode map, block bitmap, group descriptor.
-		 */
-		credits += 4;
-
-		/* Data blocks for old ea_inode. */
-		blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
-
-		/* Indirection block or one level of extent tree for old
-		 * ea_inode.
-		 */
-		blocks += 1;
-
-		/* Block bitmap and group descriptor updates for each block. */
-		credits += blocks * 2;
-	}
+	/*
+	 * Replacing an ea_inode xattr only drops its reference here.  The
+	 * final iput() and block truncation happen asynchronously in a separate
+	 * transaction, so charge only for updating the ea_inode and, when its
+	 * reference count reaches zero, adding it to the orphan list.
+	 */
+	if (!is_create && old_ea_inode)
+		credits += 2;
 
 	/* We may need to clone the existing xattr block in which case we need
 	 * to increment ref counts for existing ea_inodes referenced by it.
@@ -2375,29 +2366,6 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 
 	ext4_write_lock_xattr(inode, &no_expand);
 
-	/* Check journal credits under write lock. */
-	if (ext4_handle_valid(handle)) {
-		struct buffer_head *bh;
-		int credits;
-
-		bh = ext4_xattr_get_block(inode);
-		if (IS_ERR(bh)) {
-			error = PTR_ERR(bh);
-			goto cleanup;
-		}
-
-		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						   value_len,
-						   flags & XATTR_CREATE);
-		brelse(bh);
-
-		if (jbd2_handle_buffer_credits(handle) < credits) {
-			error = -ENOSPC;
-			goto cleanup;
-		}
-		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
-	}
-
 	error = ext4_reserve_inode_write(handle, inode, &is.iloc);
 	if (error)
 		goto cleanup;
@@ -2415,6 +2383,30 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 		error = ext4_xattr_block_find(inode, &i, &bs);
 	if (error)
 		goto cleanup;
+
+	/* Check journal credits under write lock using the old ea_inode state. */
+	if (ext4_handle_valid(handle)) {
+		struct ext4_xattr_entry *entry = NULL;
+		bool old_ea_inode = false;
+		int credits;
+
+		if (!is.s.not_found)
+			entry = is.s.here;
+		else if (!bs.s.not_found)
+			entry = bs.s.here;
+		if (entry && entry->e_value_inum &&
+		    !(flags & XATTR_CREATE))
+			old_ea_inode = true;
+		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bs.bh,
+						   value_len,
+						   flags & XATTR_CREATE,
+						   old_ea_inode);
+		if (jbd2_handle_buffer_credits(handle) < credits) {
+			error = -ENOSPC;
+			goto cleanup;
+		}
+		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
+	}
 	if (is.s.not_found && bs.s.not_found) {
 		error = -ENODATA;
 		if (flags & XATTR_REPLACE)
@@ -2500,28 +2492,91 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 	return error;
 }
 
-int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
 			   bool is_create, int *credits)
 {
-	struct buffer_head *bh;
-	int err;
+	struct ext4_xattr_info i = {
+		.name_index = name_index,
+		.name = name,
+	};
+	struct ext4_xattr_ibody_find is = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_block_find bs = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_entry *entry = NULL;
+	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
+	bool old_ea_inode = false;
+	int max_credits, revoke_credits, err;
 
 	*credits = 0;
+	if (!name)
+		return -EINVAL;
+	if (strlen(name) > 255)
+		return -ERANGE;
 
-	if (!EXT4_SB(inode->i_sb)->s_journal)
+	if (!journal)
 		return 0;
 
+	/*
+	 * The old ea_inode reference is charged only when the target attribute
+	 * currently points to one.  xattr_sem is dropped before the transaction
+	 * starts, so ext4_xattr_set_handle() repeats this check under the write
+	 * lock.
+	 */
 	down_read(&EXT4_I(inode)->xattr_sem);
 
-	bh = ext4_xattr_get_block(inode);
-	if (IS_ERR(bh)) {
-		err = PTR_ERR(bh);
-	} else {
-		*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						    value_len, is_create);
-		brelse(bh);
-		err = 0;
+	if (ext4_has_feature_ea_inode(inode->i_sb)) {
+		struct buffer_head *bh;
+
+		if (is_create) {
+			/* The target lookup is unnecessary, but block refs matter. */
+			bh = ext4_xattr_get_block(inode);
+			if (IS_ERR(bh)) {
+				err = PTR_ERR(bh);
+				goto out_unlock;
+			}
+			bs.bh = bh;
+		} else {
+			err = ext4_get_inode_loc(inode, &is.iloc);
+			if (err)
+				goto out_unlock;
+			err = ext4_xattr_ibody_find(inode, &i, &is);
+			if (err)
+				goto out;
+			if (!is.s.not_found) {
+				entry = is.s.here;
+			} else {
+				err = ext4_xattr_block_find(inode, &i, &bs);
+				if (err)
+					goto out;
+				if (!bs.s.not_found)
+					entry = bs.s.here;
+			}
+			if (!bs.bh) {
+				bh = ext4_xattr_get_block(inode);
+				if (IS_ERR(bh)) {
+					err = PTR_ERR(bh);
+					goto out;
+				}
+				bs.bh = bh;
+			}
+		}
 	}
+	if (!is_create && entry && entry->e_value_inum)
+		old_ea_inode = true;
+	*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bs.bh,
+					    value_len, is_create,
+					    old_ea_inode);
+	revoke_credits = ext4_trans_default_revoke_credits(inode->i_sb);
+	max_credits = jbd2_journal_get_max_transaction_buffers(journal, revoke_credits);
+	err = *credits > max_credits ? -ENOSPC : 0;
+out:
+	brelse(is.iloc.bh);
+	brelse(bs.bh);
+out_unlock:
 
 	up_read(&EXT4_I(inode)->xattr_sem);
 	return err;
@@ -2549,8 +2604,8 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name,
 		return error;
 
 retry:
-	error = ext4_xattr_set_credits(inode, value_len, flags & XATTR_CREATE,
-				       &credits);
+	error = ext4_xattr_set_credits(inode, name_index, name, value_len,
+				       flags & XATTR_CREATE, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/xattr.h b/fs/ext4/xattr.h
index 821dc6a50..47fd2a7c5 100644
--- a/fs/ext4/xattr.h
+++ b/fs/ext4/xattr.h
@@ -175,11 +175,12 @@ extern ssize_t ext4_listxattr(struct dentry *, char *, size_t);
 extern int ext4_xattr_get(struct inode *, int, const char *, void *, size_t);
 extern int ext4_xattr_set(struct inode *, int, const char *, const void *, size_t, int);
 extern int ext4_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);
-extern int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
-				  bool is_create, int *credits);
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
+			   bool is_create, int *credits);
 extern int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 				struct buffer_head *block_bh, size_t value_len,
-				bool is_create);
+				bool is_create, bool old_ea_inode);
 
 extern int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,
 				   int extra_credits);
diff --git a/fs/jbd2/transaction.c b/fs/jbd2/transaction.c
index 85d84d909..5fe49f118 100644
--- a/fs/jbd2/transaction.c
+++ b/fs/jbd2/transaction.c
@@ -194,6 +194,15 @@ static int jbd2_max_user_trans_buffers(journal_t *journal)
 				journal->j_transaction_overhead_buffers;
 }
 
+/* Maximum buffer credits available after reserving @revoke_records. */
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal,
+					     int revoke_records)
+{
+	return jbd2_max_user_trans_buffers(journal) -
+		DIV_ROUND_UP(revoke_records, journal->j_revoke_records_per_block);
+}
+EXPORT_SYMBOL(jbd2_journal_get_max_transaction_buffers);
+
 /*
  * Wait until we can add credits for handle to the running transaction.  Called
  * with j_state_lock held for reading. Returns 0 if handle joined the running
diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h
index e3886963b..a72f14440 100644
--- a/include/linux/jbd2.h
+++ b/include/linux/jbd2.h
@@ -1523,6 +1523,8 @@ static inline handle_t *journal_current_handle(void)
  */
 
 extern handle_t *jbd2_journal_start(journal_t *, int nblocks);
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal,
+					     int revoke_records);
 extern handle_t *jbd2__journal_start(journal_t *, int blocks, int rsv_blocks,
 				     int revoke_records, gfp_t gfp_mask,
 				     unsigned int type, unsigned int line_no);
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8..c16b1132e 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -37,6 +37,7 @@ TARGETS += filesystems/binderfs
 TARGETS += filesystems/configfs
 TARGETS += filesystems/epoll
 TARGETS += filesystems/eventfd
+TARGETS += filesystems/ext4
 TARGETS += filesystems/failfs
 TARGETS += filesystems/fat
 TARGETS += filesystems/file_stressor
diff --git a/tools/testing/selftests/filesystems/ext4/Makefile b/tools/testing/selftests/filesystems/ext4/Makefile
new file mode 100644
index 000000000..90569a1cc
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS_EXTENDED := ext4_xattr_journal_credits
+TEST_PROGS := ext4_xattr_journal_credits.sh
+
+include ../../lib.mk
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
new file mode 100644
index 000000000..92a6a8f79
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: GPL-2.0
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/xattr.h>
+#include <unistd.h>
+
+#include "../../kselftest.h"
+
+#define LARGE_VALUE_SIZE 65296
+#define OVERSIZED_VALUE_SIZE 65537
+
+int main(int argc, char **argv)
+{
+	char path[4096];
+	char *value = NULL;
+	char *readback = NULL;
+	int fd = -1;
+	int path_len;
+	int saved_errno = 0;
+	const char *failed_test = NULL;
+	static const char large_name[] = "user.ext4-credit-test";
+	static const char small_name[] = "user.ext4-credit-small";
+	static const char small_value[] = "small-xattr";
+	char small_readback[sizeof(small_value)];
+
+	ksft_print_header();
+	ksft_set_plan(8);
+	if (argc != 2)
+		ksft_exit_fail_msg("Usage: %s MOUNTPOINT\n", argv[0]);
+
+	path_len = snprintf(path, sizeof(path), "%s/credit-test", argv[1]);
+	if (path_len < 0 || (size_t)path_len >= sizeof(path))
+		ksft_exit_fail_msg("Mount path is too long\n");
+
+	fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0600);
+	if (fd < 0) {
+		failed_test = "create test file";
+		saved_errno = errno;
+		goto out;
+	}
+	if (close(fd) < 0) {
+		fd = -1;
+		failed_test = "close test file";
+		saved_errno = errno;
+		goto out;
+	}
+	fd = -1;
+
+	value = malloc(OVERSIZED_VALUE_SIZE);
+	readback = malloc(LARGE_VALUE_SIZE);
+	if (!value || !readback) {
+		failed_test = "allocate xattr buffers";
+		saved_errno = errno;
+		goto out;
+	}
+	memset(value, 0x5a, LARGE_VALUE_SIZE);
+	value[0] = 1;
+
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, 0) < 0) {
+		failed_test = "create large ea_inode xattr";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("large xattr creation\n");
+
+	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
+	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE)) {
+		failed_test = "verify newly created xattr";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("large xattr readback\n");
+
+	memset(value, 0xa5, LARGE_VALUE_SIZE);
+	value[0] = 2;
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_REPLACE) < 0) {
+		failed_test = "replace large ea_inode xattr";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("large xattr replacement\n");
+
+	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
+	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE)) {
+		failed_test = "verify replaced xattr";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("replacement readback\n");
+
+	errno = 0;
+	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_CREATE) !=
+	    -1 || errno != EEXIST) {
+		failed_test = "XATTR_CREATE on an existing name should return EEXIST";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("XATTR_CREATE semantics\n");
+
+	errno = 0;
+	if (setxattr(path, large_name, value, OVERSIZED_VALUE_SIZE,
+		     XATTR_REPLACE) != -1 || errno != E2BIG) {
+		failed_test = "oversized replacement should return E2BIG";
+		saved_errno = errno;
+		goto out;
+	}
+	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
+	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE)) {
+		failed_test = "oversized replacement changed the old value";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("oversized replacement rejected without changing value\n");
+
+	if (removexattr(path, large_name) < 0) {
+		failed_test = "remove large xattr";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("large xattr removal\n");
+
+	if (setxattr(path, small_name, small_value, sizeof(small_value), 0) < 0 ||
+	    getxattr(path, small_name, small_readback, sizeof(small_readback)) !=
+		    sizeof(small_value) ||
+	    memcmp(small_value, small_readback, sizeof(small_value)) ||
+	    removexattr(path, small_name) < 0) {
+		failed_test = "small user xattr round trip";
+		saved_errno = errno;
+		goto out;
+	}
+	ksft_test_result_pass("small user xattr round trip\n");
+
+out:
+	if (fd >= 0)
+		close(fd);
+	free(readback);
+	free(value);
+	if (failed_test)
+		ksft_exit_fail_msg("%s: %s\n", failed_test,
+				   strerror(saved_errno));
+	ksft_finished();
+}
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
new file mode 100755
index 000000000..365bef975
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
@@ -0,0 +1,56 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+KSFT_SKIP=4
+
+skip()
+{
+	printf 'SKIP: %s\n' "$1"
+	exit "$KSFT_SKIP"
+}
+
+[ "$(id -u)" -eq 0 ] || skip "requires root to mount a disposable EXT4 image"
+
+for command in mkfs.ext4 mount umount truncate e2fsck losetup grep; do
+	command -v "$command" >/dev/null 2>&1 || skip "missing $command"
+done
+
+grep -qw ext4 /proc/filesystems || skip "EXT4 is not available in this kernel"
+losetup -f >/dev/null 2>&1 || skip "no loop device is available"
+
+test_dir=$(mktemp -d) || exit 1
+mounted=0
+
+cleanup()
+{
+	if [ "$mounted" -eq 1 ]; then
+		umount "$test_dir/mnt" || true
+	fi
+	rm -rf "$test_dir"
+}
+trap cleanup EXIT INT TERM
+
+truncate -s 32M "$test_dir/fs.img" || exit 1
+if ! mkfs.ext4 -q -F -b 1024 -O ea_inode -J size=1 "$test_dir/fs.img" \
+		2>"$test_dir/mkfs.err"; then
+	cat "$test_dir/mkfs.err" >&2
+	skip "mkfs.ext4 does not support the ea_inode test image"
+fi
+mkdir "$test_dir/mnt" || exit 1
+if ! mount -t ext4 -o loop "$test_dir/fs.img" "$test_dir/mnt" \
+		2>"$test_dir/mount.err"; then
+	cat "$test_dir/mount.err" >&2
+	if grep -Eqi 'permission denied|operation not permitted|not permitted' \
+			"$test_dir/mount.err"; then
+		skip "mounting a loop image is not permitted"
+	fi
+	exit 1
+fi
+mounted=1
+
+test_bin="$(dirname "$0")/ext4_xattr_journal_credits"
+"$test_bin" "$test_dir/mnt" || exit $?
+
+umount "$test_dir/mnt" || exit 1
+mounted=0
+e2fsck -fn "$test_dir/fs.img"

base-commit: c44104f3642da720164042623e4832836aefdd8e
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* Re: [PATCH v2] ext4: bound xattr journal credits to transaction limit
  2026-11-22  8:49 ` [PATCH v2] " arzuagapozosergio
@ 2026-11-22  9:09   ` sashiko-bot
  2026-11-22  9:37   ` [PATCH v3] " arzuagapozosergio
  1 sibling, 0 replies; 5+ messages in thread
From: sashiko-bot @ 2026-11-22  9:09 UTC (permalink / raw)
  To: arzuagapozosergio; +Cc: linux-ext4, tytso

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] ext4: missing xattr block lookup in ext4_xattr_set_handle()
  credit check
- [Low] ext4: patch changelog and test checklist included in commit
  message
- [Low] selftests: ext4: tautological value check in main() after E2BIG
  setxattr()
- [Low] selftests: ext4: missing .gitignore and non-standard reporting
  in main()
--

commit d21a4fa912d1237c90e910dcdee358a0869f3cfa
Author: Ryuji Hiroshi <arzuagapozosergio@gmail.com>

ext4: bound xattr journal credits to transaction limit

This commit refines ext4 xattr journal credit estimation by charging for
old ea_inode reference drops only when an existing ea_inode attribute is
replaced, bounds the requested credits against the maximum JBD2
transaction buffer limit, and adds an ext4 kselftest.

Link: https://syzbot.org/bug?extid=25d45c0bd716f2b794a7

>     Changes in v2:
>     - Include the default revoke descriptor blocks in the JBD2 credit limit.
>     - Do not charge the current transaction for deferred ea_inode truncation.
>     - Correct selftest registration and use kselftest result reporting.
>     - Use user.* attributes and skip when required mount support is
>       unavailable.
>     - Reuse the validated xattr block buffer during the locked credit check.
>     
>     Tests:
>     - make defconfig
>     - make -j2 fs/ext4/xattr.o fs/jbd2/transaction.o
>     - make -C tools/testing/selftests/filesystems/ext4 clean all
>     - sh -n tools/testing/selftests/filesystems/ext4/
>       ext4_xattr_journal_credits.sh
>     - scripts/checkpatch.pl --strict --no-tree: 0 errors; two environment or
>       tree warnings for the Fixes commit lookup and new selftest MAINTAINERS
>       coverage.
>     - Built and booted the patched x86_64 kernel in a QEMU/KVM guest.
>     - The EXT4 selftest passed all 8 cases as guest root on a 1 KiB-block
>       ea_inode filesystem with a 1 MiB journal. e2fsck -fn passed after
>       the guest unmounted it.
>     - The host kselftest runner correctly reported KSFT_SKIP because it cannot
>       mount the disposable filesystem without root privileges.

[Severity: Low]
This isn't a bug, but the patch revision changelog ("Changes in v2:") and
the build/checkpatch checklist ("Tests:") belong below the "---" tearline
so they are not recorded in the permanent git commit log.

> diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c
> index 5c310747b9650..0249dc1375386 100644
> --- a/fs/ext4/xattr.c
> +++ b/fs/ext4/xattr.c
[ ... ]
> @@ -2415,6 +2383,30 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
>  		error = ext4_xattr_block_find(inode, &i, &bs);
>  	if (error)
>  		goto cleanup;
> +
> +	/* Check journal credits under write lock using the old ea_inode state. */
> +	if (ext4_handle_valid(handle)) {
> +		struct ext4_xattr_entry *entry = NULL;
> +		bool old_ea_inode = false;
> +		int credits;
> +
> +		if (!is.s.not_found)
> +			entry = is.s.here;
> +		else if (!bs.s.not_found)
> +			entry = bs.s.here;
> +		if (entry && entry->e_value_inum &&
> +		    !(flags & XATTR_CREATE))
> +			old_ea_inode = true;
> +		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bs.bh,
> +						   value_len,
> +						   flags & XATTR_CREATE,
> +						   old_ea_inode);
> +		if (jbd2_handle_buffer_credits(handle) < credits) {
> +			error = -ENOSPC;
> +			goto cleanup;
> +		}
> +		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
> +	}

[Severity: Medium]
Does this underestimate the required credits in ext4_xattr_set_handle()
when the target attribute is found in the inode body?

When !is.s.not_found, ext4_xattr_block_find() is not called, so bs.bh is
NULL even if EXT4_I(inode)->i_file_acl is present (unlike
ext4_xattr_set_credits(), which falls back to ext4_xattr_get_block() when
!bs.bh).  Passing bs.bh == NULL to __ext4_xattr_set_credits() omits the
per-ea_inode credits for cloning a shared external xattr block.

If an external xattr block containing ea_inode references was attached
after ext4_xattr_set_credits() dropped xattr_sem, and the new value no
longer fits in the inode body, ext4_xattr_ibody_set() returns -ENOSPC and
falls back to ext4_xattr_block_find() and ext4_xattr_block_set().  Cloning
that shared external xattr block in ext4_xattr_inode_inc_ref_all() can
then run out of handle buffer credits and trigger the WARN_ON_ONCE() in
jbd2_journal_dirty_metadata().

> diff --git a/tools/testing/selftests/filesystems/ext4/Makefile b/tools/testing/selftests/filesystems/ext4/Makefile
> new file mode 100644
> index 0000000000000..90569a1ccef38
> --- /dev/null
> +++ b/tools/testing/selftests/filesystems/ext4/Makefile
> @@ -0,0 +1,6 @@
> +# SPDX-License-Identifier: GPL-2.0
> +
> +TEST_GEN_PROGS_EXTENDED := ext4_xattr_journal_credits
> +TEST_PROGS := ext4_xattr_journal_credits.sh
> +
> +include ../../lib.mk
> diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
> new file mode 100644
> index 0000000000000..92a6a8f7937bc
> --- /dev/null
> +++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
[ ... ]
> +	fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0600);
> +	if (fd < 0) {
> +		failed_test = "create test file";
> +		saved_errno = errno;
> +		goto out;
> +	}

[Severity: Low]
This isn't a bug, but tools/testing/selftests/filesystems/ext4/ is missing
a .gitignore entry for the generated ext4_xattr_journal_credits binary.
Also, in main(), both setup failures (open(), close(), malloc()) and test
failures jump to out: and abort via ksft_exit_fail_msg() rather than using
kselftest_harness.h (FIXTURE / TEST_F) or distinguishing setup errors with
ksft_test_result_error() from test failures with ksft_test_result_fail().

[ ... ]

> +	memset(value, 0xa5, LARGE_VALUE_SIZE);
> +	value[0] = 2;
> +	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_REPLACE) < 0) {
> +		failed_test = "replace large ea_inode xattr";
> +		saved_errno = errno;
> +		goto out;
> +	}
> +	ksft_test_result_pass("large xattr replacement\n");
> +
> +	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
> +	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE)) {
> +		failed_test = "verify replaced xattr";
> +		saved_errno = errno;
> +		goto out;
> +	}
> +	ksft_test_result_pass("replacement readback\n");
> +
> +	errno = 0;
> +	if (setxattr(path, large_name, value, LARGE_VALUE_SIZE, XATTR_CREATE) !=
> +	    -1 || errno != EEXIST) {
> +		failed_test = "XATTR_CREATE on an existing name should return EEXIST";
> +		saved_errno = errno;
> +		goto out;
> +	}
> +	ksft_test_result_pass("XATTR_CREATE semantics\n");
> +
> +	errno = 0;
> +	if (setxattr(path, large_name, value, OVERSIZED_VALUE_SIZE,
> +		     XATTR_REPLACE) != -1 || errno != E2BIG) {
> +		failed_test = "oversized replacement should return E2BIG";
> +		saved_errno = errno;
> +		goto out;
> +	}
> +	if (getxattr(path, large_name, readback, LARGE_VALUE_SIZE) !=
> +	    LARGE_VALUE_SIZE || memcmp(value, readback, LARGE_VALUE_SIZE)) {
> +		failed_test = "oversized replacement changed the old value";
> +		saved_errno = errno;
> +		goto out;
> +	}
> +	ksft_test_result_pass("oversized replacement rejected without changing value\n");

[Severity: Low]
Does the oversized replacement check in main() actually test whether the
stored value was preserved?

value is not modified after the preceding XATTR_REPLACE write (and the
trailing bytes between LARGE_VALUE_SIZE and OVERSIZED_VALUE_SIZE are left
uninitialized from malloc()), so value[0..LARGE_VALUE_SIZE - 1] already
matches the attribute on disk and memcmp(value, readback,
LARGE_VALUE_SIZE) would pass even if setxattr() had overwritten the
attribute.

In addition, OVERSIZED_VALUE_SIZE is 65537 (XATTR_SIZE_MAX + 1), which VFS
setxattr_copy() rejects with -E2BIG before reaching ext4_xattr_set() or
ext4_xattr_set_credits().  Also, in the readback checks, if getxattr()
succeeds but memcmp() fails, errno is not set by memcmp(), so saved_errno
captures a stale errno from an earlier syscall.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261122084939.129223-1-arzuagapozosergio@gmail.com?part=1

^ permalink raw reply	[flat|nested] 5+ messages in thread

* [PATCH v3] ext4: bound xattr journal credits to transaction limit
  2026-11-22  8:49 ` [PATCH v2] " arzuagapozosergio
  2026-11-22  9:09   ` sashiko-bot
@ 2026-11-22  9:37   ` arzuagapozosergio
  1 sibling, 0 replies; 5+ messages in thread
From: arzuagapozosergio @ 2026-11-22  9:37 UTC (permalink / raw)
  To: tytso; +Cc: jack, linux-ext4, syzbot+25d45c0bd716f2b794a7, Ryuji Hiroshi

From: Ryuji Hiroshi <arzuagapozosergio@gmail.com>

When setting an xattr without XATTR_CREATE, ext4 reserves credits for
releasing an old ea_inode even when the attribute does not exist. On a
1 KiB-block filesystem with a minimum journal, this can request more
credits than JBD2 permits, triggering a warning before the operation
fails.

Look up the existing attribute and account for the work done when its
ea_inode reference is dropped. The final iput() and block truncation are
deferred to a separate transaction. Check the credit limit after reserving
space for the default JBD2 revoke records, and repeat the estimate under
the xattr write lock before modifying the attribute. When the target is
found in the inode body, also read the external xattr block so shared
block EA inode references are included in the locked estimate.

Add EXT4 selftests for the original no-XATTR_CREATE credit-estimation
path, large xattr creation and replacement, preservation after a rejected
XATTR_CREATE operation, shared external xattr block cloning, removal, and
a small user xattr round trip.

Fixes: dec214d00e0d ("ext4: xattr inode deduplication")
Reported-by: syzbot+25d45c0bd716f2b794a7@syzkaller.appspotmail.com
Link: https://syzbot.org/bug?extid=25d45c0bd716f2b794a7
Assisted-by: Codex:GPT-6
Signed-off-by: Ryuji Hiroshi <arzuagapozosergio@gmail.com>
---
 MAINTAINERS                                   |   1 +
 fs/ext4/acl.c                                 |   7 +-
 fs/ext4/crypto.c                              |   5 +-
 fs/ext4/ialloc.c                              |   6 +-
 fs/ext4/xattr.c                               | 174 +++++++++----
 fs/ext4/xattr.h                               |   7 +-
 fs/jbd2/transaction.c                         |   9 +
 include/linux/jbd2.h                          |   2 +
 tools/testing/selftests/Makefile              |   1 +
 .../selftests/filesystems/ext4/.gitignore     |   2 +
 .../selftests/filesystems/ext4/Makefile       |   6 +
 .../ext4/ext4_xattr_journal_credits.c         | 244 ++++++++++++++++++
 .../ext4/ext4_xattr_journal_credits.sh        |  56 ++++
 13 files changed, 455 insertions(+), 65 deletions(-)
 create mode 100644 tools/testing/selftests/filesystems/ext4/.gitignore
 create mode 100644 tools/testing/selftests/filesystems/ext4/Makefile
 create mode 100644 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
 create mode 100755 tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh

Changes in v3:
- Re-read the external xattr block for the locked estimate when the target
  attribute is in the inode body.
- Replace the pre-VFS E2BIG check with the original no-XATTR_CREATE case,
  preservation after XATTR_CREATE rejection, and shared-block clone coverage.
- Report setup errors separately, ignore the generated test binary, and add
  the EXT4 selftest path to MAINTAINERS.

Tests:
- make -j4 bzImage
- make -C tools/testing/selftests/filesystems/ext4 clean all
- sh -n tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
- Booted the patched kernel in QEMU/KVM; all 10 selftest cases passed on a
  1 KiB-block ea_inode filesystem with a 1 MiB journal; QEMU shut down cleanly.
- Confirmed the shared-block fixture used the same external xattr block with
  refcount 2 before cloning.
- e2fsck -fn passed after the guest unmounted the image.
- The host kselftest runner returned KSFT_SKIP because the unprivileged host
  cannot mount the disposable filesystem; the binary passed in the VM as root.

diff --git a/MAINTAINERS b/MAINTAINERS
index 2ac5128b7..1debcbeb0 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -10131,6 +10131,7 @@ F:	Documentation/filesystems/ext4/
 F:	fs/ext4/
 F:	include/trace/events/ext4.h
 F:	include/uapi/linux/ext4.h
+F:	tools/testing/selftests/filesystems/ext4/
 
 Extended Verification Module (EVM)
 M:	Mimi Zohar <zohar@linux.ibm.com>
diff --git a/fs/ext4/acl.c b/fs/ext4/acl.c
index 59fac55a2..07b351694 100644
--- a/fs/ext4/acl.c
+++ b/fs/ext4/acl.c
@@ -239,8 +239,11 @@ ext4_set_acl(const struct mnt_idmap *idmap, struct dentry *dentry,
 	if (error)
 		return error;
 retry:
-	error = ext4_xattr_set_credits(inode, acl_size, false /* is_create */,
-				       &credits);
+	error = ext4_xattr_set_credits(inode,
+				       type == ACL_TYPE_ACCESS ?
+				       EXT4_XATTR_INDEX_POSIX_ACL_ACCESS :
+				       EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT,
+				       "", acl_size, false /* is_create */, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c
index 318b2eaea..98afd33b0 100644
--- a/fs/ext4/crypto.c
+++ b/fs/ext4/crypto.c
@@ -203,8 +203,9 @@ static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
 	if (res)
 		return res;
 retry:
-	res = ext4_xattr_set_credits(inode, len, false /* is_create */,
-				     &credits);
+	res = ext4_xattr_set_credits(inode, EXT4_XATTR_INDEX_ENCRYPTION,
+				     EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
+				     len, false /* is_create */, &credits);
 	if (res)
 		return res;
 
diff --git a/fs/ext4/ialloc.c b/fs/ext4/ialloc.c
index 527f1f703..927b2e8f0 100644
--- a/fs/ext4/ialloc.c
+++ b/fs/ext4/ialloc.c
@@ -889,7 +889,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += (S_ISDIR(mode) ? 2 : 1) *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, acl_size,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 		posix_acl_release(p);
 	}
 #endif
@@ -908,7 +908,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 		nblocks += num_security_xattrs *
 			__ext4_xattr_set_credits(sb, NULL /* inode */,
 						 NULL /* block_bh */, 1024,
-						 true /* is_create */);
+							 true /* is_create */, 0);
 	}
 #endif
 	if (encrypt)
@@ -916,7 +916,7 @@ static int ext4_xattr_credits_for_new_inode(struct inode *dir, mode_t mode,
 						    NULL /* inode */,
 						    NULL /* block_bh */,
 						    FSCRYPT_SET_CONTEXT_MAX_SIZE,
-						    true /* is_create */);
+						    true /* is_create */, 0);
 	return nblocks;
 }
 
diff --git a/fs/ext4/xattr.c b/fs/ext4/xattr.c
index 5c310747b..21061850d 100644
--- a/fs/ext4/xattr.c
+++ b/fs/ext4/xattr.c
@@ -949,7 +949,7 @@ static void ext4_xattr_inode_free_quota(struct inode *parent,
 
 int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 			     struct buffer_head *block_bh, size_t value_len,
-			     bool is_create)
+			     bool is_create, bool old_ea_inode)
 {
 	int credits;
 	int blocks;
@@ -998,23 +998,14 @@ int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 	/* Blocks themselves. */
 	credits += blocks;
 
-	if (!is_create) {
-		/* Dereference ea_inode holding old xattr value.
-		 * Old ea_inode, inode map, block bitmap, group descriptor.
-		 */
-		credits += 4;
-
-		/* Data blocks for old ea_inode. */
-		blocks = XATTR_SIZE_MAX >> sb->s_blocksize_bits;
-
-		/* Indirection block or one level of extent tree for old
-		 * ea_inode.
-		 */
-		blocks += 1;
-
-		/* Block bitmap and group descriptor updates for each block. */
-		credits += blocks * 2;
-	}
+	/*
+	 * Replacing an ea_inode xattr only drops its reference here.  The
+	 * final iput() and block truncation happen asynchronously in a separate
+	 * transaction, so charge only for updating the ea_inode and, when its
+	 * reference count reaches zero, adding it to the orphan list.
+	 */
+	if (!is_create && old_ea_inode)
+		credits += 2;
 
 	/* We may need to clone the existing xattr block in which case we need
 	 * to increment ref counts for existing ea_inodes referenced by it.
@@ -2375,29 +2366,6 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 
 	ext4_write_lock_xattr(inode, &no_expand);
 
-	/* Check journal credits under write lock. */
-	if (ext4_handle_valid(handle)) {
-		struct buffer_head *bh;
-		int credits;
-
-		bh = ext4_xattr_get_block(inode);
-		if (IS_ERR(bh)) {
-			error = PTR_ERR(bh);
-			goto cleanup;
-		}
-
-		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						   value_len,
-						   flags & XATTR_CREATE);
-		brelse(bh);
-
-		if (jbd2_handle_buffer_credits(handle) < credits) {
-			error = -ENOSPC;
-			goto cleanup;
-		}
-		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
-	}
-
 	error = ext4_reserve_inode_write(handle, inode, &is.iloc);
 	if (error)
 		goto cleanup;
@@ -2415,6 +2383,39 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 		error = ext4_xattr_block_find(inode, &i, &bs);
 	if (error)
 		goto cleanup;
+
+	/* Check journal credits under write lock using the old ea_inode state. */
+	if (ext4_handle_valid(handle)) {
+		struct ext4_xattr_entry *entry = NULL;
+		bool old_ea_inode = false;
+		int credits;
+
+		if (!is.s.not_found)
+			entry = is.s.here;
+		else if (!bs.s.not_found)
+			entry = bs.s.here;
+		if (entry && entry->e_value_inum &&
+		    !(flags & XATTR_CREATE))
+			old_ea_inode = true;
+		if (!bs.bh) {
+			struct buffer_head *bh = ext4_xattr_get_block(inode);
+
+			if (IS_ERR(bh)) {
+				error = PTR_ERR(bh);
+				goto cleanup;
+			}
+			bs.bh = bh;
+		}
+		credits = __ext4_xattr_set_credits(inode->i_sb, inode, bs.bh,
+						   value_len,
+						   flags & XATTR_CREATE,
+						   old_ea_inode);
+		if (jbd2_handle_buffer_credits(handle) < credits) {
+			error = -ENOSPC;
+			goto cleanup;
+		}
+		WARN_ON_ONCE(!(current->flags & PF_MEMALLOC_NOFS));
+	}
 	if (is.s.not_found && bs.s.not_found) {
 		error = -ENODATA;
 		if (flags & XATTR_REPLACE)
@@ -2500,28 +2501,91 @@ ext4_xattr_set_handle(handle_t *handle, struct inode *inode, int name_index,
 	return error;
 }
 
-int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
 			   bool is_create, int *credits)
 {
-	struct buffer_head *bh;
-	int err;
+	struct ext4_xattr_info i = {
+		.name_index = name_index,
+		.name = name,
+	};
+	struct ext4_xattr_ibody_find is = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_block_find bs = {
+		.s = { .not_found = -ENODATA, },
+	};
+	struct ext4_xattr_entry *entry = NULL;
+	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
+	bool old_ea_inode = false;
+	int max_credits, revoke_credits, err;
 
 	*credits = 0;
+	if (!name)
+		return -EINVAL;
+	if (strlen(name) > 255)
+		return -ERANGE;
 
-	if (!EXT4_SB(inode->i_sb)->s_journal)
+	if (!journal)
 		return 0;
 
+	/*
+	 * The old ea_inode reference is charged only when the target attribute
+	 * currently points to one.  xattr_sem is dropped before the transaction
+	 * starts, so ext4_xattr_set_handle() repeats this check under the write
+	 * lock.
+	 */
 	down_read(&EXT4_I(inode)->xattr_sem);
 
-	bh = ext4_xattr_get_block(inode);
-	if (IS_ERR(bh)) {
-		err = PTR_ERR(bh);
-	} else {
-		*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bh,
-						    value_len, is_create);
-		brelse(bh);
-		err = 0;
+	if (ext4_has_feature_ea_inode(inode->i_sb)) {
+		struct buffer_head *bh;
+
+		if (is_create) {
+			/* The target lookup is unnecessary, but block refs matter. */
+			bh = ext4_xattr_get_block(inode);
+			if (IS_ERR(bh)) {
+				err = PTR_ERR(bh);
+				goto out_unlock;
+			}
+			bs.bh = bh;
+		} else {
+			err = ext4_get_inode_loc(inode, &is.iloc);
+			if (err)
+				goto out_unlock;
+			err = ext4_xattr_ibody_find(inode, &i, &is);
+			if (err)
+				goto out;
+			if (!is.s.not_found) {
+				entry = is.s.here;
+			} else {
+				err = ext4_xattr_block_find(inode, &i, &bs);
+				if (err)
+					goto out;
+				if (!bs.s.not_found)
+					entry = bs.s.here;
+			}
+			if (!bs.bh) {
+				bh = ext4_xattr_get_block(inode);
+				if (IS_ERR(bh)) {
+					err = PTR_ERR(bh);
+					goto out;
+				}
+				bs.bh = bh;
+			}
+		}
 	}
+	if (!is_create && entry && entry->e_value_inum)
+		old_ea_inode = true;
+	*credits = __ext4_xattr_set_credits(inode->i_sb, inode, bs.bh,
+					    value_len, is_create,
+					    old_ea_inode);
+	revoke_credits = ext4_trans_default_revoke_credits(inode->i_sb);
+	max_credits = jbd2_journal_get_max_transaction_buffers(journal, revoke_credits);
+	err = *credits > max_credits ? -ENOSPC : 0;
+out:
+	brelse(is.iloc.bh);
+	brelse(bs.bh);
+out_unlock:
 
 	up_read(&EXT4_I(inode)->xattr_sem);
 	return err;
@@ -2549,8 +2613,8 @@ ext4_xattr_set(struct inode *inode, int name_index, const char *name,
 		return error;
 
 retry:
-	error = ext4_xattr_set_credits(inode, value_len, flags & XATTR_CREATE,
-				       &credits);
+	error = ext4_xattr_set_credits(inode, name_index, name, value_len,
+				       flags & XATTR_CREATE, &credits);
 	if (error)
 		return error;
 
diff --git a/fs/ext4/xattr.h b/fs/ext4/xattr.h
index 821dc6a50..47fd2a7c5 100644
--- a/fs/ext4/xattr.h
+++ b/fs/ext4/xattr.h
@@ -175,11 +175,12 @@ extern ssize_t ext4_listxattr(struct dentry *, char *, size_t);
 extern int ext4_xattr_get(struct inode *, int, const char *, void *, size_t);
 extern int ext4_xattr_set(struct inode *, int, const char *, const void *, size_t, int);
 extern int ext4_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);
-extern int ext4_xattr_set_credits(struct inode *inode, size_t value_len,
-				  bool is_create, int *credits);
+int ext4_xattr_set_credits(struct inode *inode, int name_index,
+			   const char *name, size_t value_len,
+			   bool is_create, int *credits);
 extern int __ext4_xattr_set_credits(struct super_block *sb, struct inode *inode,
 				struct buffer_head *block_bh, size_t value_len,
-				bool is_create);
+				bool is_create, bool old_ea_inode);
 
 extern int ext4_xattr_delete_inode(handle_t *handle, struct inode *inode,
 				   int extra_credits);
diff --git a/fs/jbd2/transaction.c b/fs/jbd2/transaction.c
index 85d84d909..5fe49f118 100644
--- a/fs/jbd2/transaction.c
+++ b/fs/jbd2/transaction.c
@@ -194,6 +194,15 @@ static int jbd2_max_user_trans_buffers(journal_t *journal)
 				journal->j_transaction_overhead_buffers;
 }
 
+/* Maximum buffer credits available after reserving @revoke_records. */
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal,
+					     int revoke_records)
+{
+	return jbd2_max_user_trans_buffers(journal) -
+		DIV_ROUND_UP(revoke_records, journal->j_revoke_records_per_block);
+}
+EXPORT_SYMBOL(jbd2_journal_get_max_transaction_buffers);
+
 /*
  * Wait until we can add credits for handle to the running transaction.  Called
  * with j_state_lock held for reading. Returns 0 if handle joined the running
diff --git a/include/linux/jbd2.h b/include/linux/jbd2.h
index e3886963b..a72f14440 100644
--- a/include/linux/jbd2.h
+++ b/include/linux/jbd2.h
@@ -1523,6 +1523,8 @@ static inline handle_t *journal_current_handle(void)
  */
 
 extern handle_t *jbd2_journal_start(journal_t *, int nblocks);
+int jbd2_journal_get_max_transaction_buffers(journal_t *journal,
+					     int revoke_records);
 extern handle_t *jbd2__journal_start(journal_t *, int blocks, int rsv_blocks,
 				     int revoke_records, gfp_t gfp_mask,
 				     unsigned int type, unsigned int line_no);
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8..c16b1132e 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -37,6 +37,7 @@ TARGETS += filesystems/binderfs
 TARGETS += filesystems/configfs
 TARGETS += filesystems/epoll
 TARGETS += filesystems/eventfd
+TARGETS += filesystems/ext4
 TARGETS += filesystems/failfs
 TARGETS += filesystems/fat
 TARGETS += filesystems/file_stressor
diff --git a/tools/testing/selftests/filesystems/ext4/.gitignore b/tools/testing/selftests/filesystems/ext4/.gitignore
new file mode 100644
index 000000000..d3678b52d
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0
+/ext4_xattr_journal_credits
diff --git a/tools/testing/selftests/filesystems/ext4/Makefile b/tools/testing/selftests/filesystems/ext4/Makefile
new file mode 100644
index 000000000..90569a1cc
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/Makefile
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS_EXTENDED := ext4_xattr_journal_credits
+TEST_PROGS := ext4_xattr_journal_credits.sh
+
+include ../../lib.mk
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
new file mode 100644
index 000000000..313e81767
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.c
@@ -0,0 +1,244 @@
+// SPDX-License-Identifier: GPL-2.0
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/xattr.h>
+#include <unistd.h>
+
+#include "../../kselftest.h"
+
+#define LARGE_VALUE_SIZE 65296
+#define FILLER_VALUE_SIZE 32
+#define TEST_COUNT 10
+
+static const char large_name[] = "user.ext4-credit-large";
+static const char small_name[] = "user.ext4-credit-small";
+static const char target_name[] = "user.ext4-credit-target";
+static const char filler_name[] = "user.ext4-credit-filler";
+
+static void result(bool passed, const char *name)
+{
+	ksft_test_result(passed, "%s\n", name);
+}
+
+static bool xattr_matches(const char *path, const char *name,
+			  char *buffer, const void *expected, size_t size)
+{
+	ssize_t len;
+
+	errno = 0;
+	len = getxattr(path, name, buffer, size);
+	if (len < 0) {
+		ksft_print_msg("getxattr(%s): %s\n", name, strerror(errno));
+		return false;
+	}
+	return len == size && !memcmp(buffer, expected, size);
+}
+
+static int create_file(const char *path)
+{
+	int fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0600);
+	int error;
+
+	if (fd < 0)
+		return -1;
+	if (!close(fd))
+		return 0;
+	error = errno;
+	errno = error;
+	return -1;
+}
+
+static bool set_xattr(const char *path, const char *name,
+		      const void *value, size_t size, int flags)
+{
+	errno = 0;
+	if (!setxattr(path, name, value, size, flags))
+		return true;
+	ksft_print_msg("setxattr(%s): %s\n", name, strerror(errno));
+	return false;
+}
+
+static void report_setup_error(const char *what, unsigned int skip_count)
+{
+	int saved_errno = errno;
+	unsigned int i;
+
+	ksft_test_result_error("setup %s: %s\n", what,
+			       strerror(saved_errno));
+	for (i = 0; i < skip_count; i++)
+		ksft_test_result_skip("setup failed\n");
+}
+
+static bool prepare_shared_file(const char *path, const char *large_value,
+				const char *filler, char target_value)
+{
+	return create_file(path) == 0 &&
+	       set_xattr(path, target_name, &target_value, sizeof(target_value),
+			 XATTR_CREATE) &&
+	       set_xattr(path, filler_name, filler, FILLER_VALUE_SIZE,
+			 XATTR_CREATE) &&
+	       set_xattr(path, large_name, large_value, LARGE_VALUE_SIZE,
+			 XATTR_CREATE);
+}
+
+static bool prepare_shared_block(const char *path_a, const char *path_b,
+				 char *large_value, char *readback)
+{
+	char target_value = 0x11;
+	char filler[FILLER_VALUE_SIZE];
+	char target_readback;
+
+	memset(filler, 0x6c, sizeof(filler));
+	memset(large_value, 0x7e, LARGE_VALUE_SIZE);
+	large_value[0] = 0x42;
+
+	if (!prepare_shared_file(path_a, large_value, filler, target_value) ||
+	    !prepare_shared_file(path_b, large_value, filler, target_value))
+		return false;
+
+	return xattr_matches(path_a, large_name, readback, large_value,
+			     LARGE_VALUE_SIZE) &&
+	       xattr_matches(path_b, large_name, readback, large_value,
+			     LARGE_VALUE_SIZE) &&
+	       xattr_matches(path_a, target_name, &target_readback,
+			     &target_value, sizeof(target_value)) &&
+	       xattr_matches(path_b, target_name, &target_readback,
+			     &target_value, sizeof(target_value));
+}
+
+int main(int argc, char **argv)
+{
+	char path[4096], shared_a[4096], shared_b[4096];
+	char *value = NULL, *expected = NULL, *readback = NULL;
+	char target_new[64];
+	static const char small_value[] = "small-xattr";
+	char small_value_readback[sizeof(small_value)];
+	char target_old = 0x11;
+	int fd, path_len, shared_len;
+	bool created = false, replaced = false, shared_ready = false;
+	bool shared_replaced = false;
+	int ret;
+
+	ksft_print_header();
+	ksft_set_plan(TEST_COUNT);
+	if (argc != 2)
+		ksft_exit_fail_msg("Usage: %s MOUNTPOINT\n", argv[0]);
+
+	path_len = snprintf(path, sizeof(path), "%s/credit-test", argv[1]);
+	shared_len = snprintf(shared_a, sizeof(shared_a), "%s/shared-a", argv[1]);
+	if (path_len < 0 || (size_t)path_len >= sizeof(path) ||
+	    shared_len < 0 || (size_t)shared_len >= sizeof(shared_a))
+		ksft_exit_fail_msg("Mount path is too long\n");
+	shared_len = snprintf(shared_b, sizeof(shared_b), "%s/shared-b", argv[1]);
+	if (shared_len < 0 || (size_t)shared_len >= sizeof(shared_b))
+		ksft_exit_fail_msg("Mount path is too long\n");
+
+	fd = open(path, O_CREAT | O_EXCL | O_RDWR, 0600);
+	if (fd < 0) {
+		report_setup_error("create test file", TEST_COUNT - 1);
+		ksft_finished();
+	}
+	if (close(fd) < 0) {
+		report_setup_error("close test file", TEST_COUNT - 1);
+		ksft_finished();
+	}
+
+	value = malloc(LARGE_VALUE_SIZE);
+	expected = malloc(LARGE_VALUE_SIZE);
+	readback = malloc(LARGE_VALUE_SIZE);
+	if (!value || !expected || !readback) {
+		report_setup_error("allocate xattr buffers", TEST_COUNT - 1);
+		ksft_finished();
+	}
+
+	memset(value, 0x5a, LARGE_VALUE_SIZE);
+	value[0] = 1;
+	/* Exercise the original no-XATTR_CREATE credit-estimation path. */
+	created = set_xattr(path, large_name, value, LARGE_VALUE_SIZE, 0);
+	result(created, "large xattr creation");
+	if (created) {
+		result(xattr_matches(path, large_name, readback, value,
+				     LARGE_VALUE_SIZE), "large xattr readback");
+
+		memset(value, 0xa5, LARGE_VALUE_SIZE);
+		value[0] = 2;
+		replaced = set_xattr(path, large_name, value,
+				     LARGE_VALUE_SIZE, XATTR_REPLACE);
+		result(replaced, "large xattr replacement");
+	} else {
+		ksft_test_result_skip("readback needs the created xattr\n");
+		ksft_test_result_skip("replacement needs the created xattr\n");
+	}
+
+	if (replaced) {
+		result(xattr_matches(path, large_name, readback, value,
+				     LARGE_VALUE_SIZE), "replacement readback");
+
+		memcpy(expected, value, LARGE_VALUE_SIZE);
+		memset(value, 0x3c, LARGE_VALUE_SIZE);
+		value[0] = 3;
+		errno = 0;
+		ret = setxattr(path, large_name, value, LARGE_VALUE_SIZE,
+			       XATTR_CREATE);
+		result(ret < 0 && errno == EEXIST &&
+		       xattr_matches(path, large_name, readback, expected,
+				     LARGE_VALUE_SIZE),
+		       "XATTR_CREATE rejection preserves the old value");
+	} else {
+		ksft_test_result_skip("replacement readback needs a successful replacement\n");
+		ksft_test_result_skip("XATTR_CREATE check needs a successful replacement\n");
+	}
+
+	if (prepare_shared_block(shared_a, shared_b, value, readback)) {
+		shared_ready = true;
+		ksft_test_result_pass("shared external xattr block fixture\n");
+	} else {
+		report_setup_error("prepare shared xattr block", 2);
+	}
+
+	if (shared_ready) {
+		memset(target_new, 0x22, sizeof(target_new));
+		shared_replaced = set_xattr(shared_a, target_name, target_new,
+					    sizeof(target_new), XATTR_REPLACE);
+		result(shared_replaced,
+		       "replace inode-body xattr with shared external block present");
+
+		result(xattr_matches(shared_a, target_name, readback,
+				     shared_replaced ? target_new : &target_old,
+				     shared_replaced ? sizeof(target_new) :
+				     sizeof(target_old)) &&
+		       xattr_matches(shared_b, target_name, readback,
+				     &target_old, sizeof(target_old)) &&
+		       xattr_matches(shared_b, large_name, readback, value,
+				     LARGE_VALUE_SIZE),
+		       "xattr block clone preserves both files' values");
+	} else {
+		ksft_test_result_skip("shared-block replacement needs its fixture\n");
+		ksft_test_result_skip("shared-block readback needs its fixture\n");
+	}
+
+	if (created) {
+		ret = removexattr(path, large_name);
+		result(ret == 0, "large xattr removal");
+	} else {
+		ksft_test_result_skip("removal needs the created xattr\n");
+	}
+
+	ret = setxattr(path, small_name, small_value, sizeof(small_value), 0);
+	result(ret == 0 &&
+	       getxattr(path, small_name, small_value_readback,
+			sizeof(small_value_readback)) == sizeof(small_value) &&
+	       !memcmp(small_value, small_value_readback, sizeof(small_value)) &&
+	       removexattr(path, small_name) == 0,
+	       "small user xattr round trip");
+
+	free(readback);
+	free(expected);
+	free(value);
+	ksft_finished();
+}
diff --git a/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
new file mode 100755
index 000000000..365bef975
--- /dev/null
+++ b/tools/testing/selftests/filesystems/ext4/ext4_xattr_journal_credits.sh
@@ -0,0 +1,56 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+KSFT_SKIP=4
+
+skip()
+{
+	printf 'SKIP: %s\n' "$1"
+	exit "$KSFT_SKIP"
+}
+
+[ "$(id -u)" -eq 0 ] || skip "requires root to mount a disposable EXT4 image"
+
+for command in mkfs.ext4 mount umount truncate e2fsck losetup grep; do
+	command -v "$command" >/dev/null 2>&1 || skip "missing $command"
+done
+
+grep -qw ext4 /proc/filesystems || skip "EXT4 is not available in this kernel"
+losetup -f >/dev/null 2>&1 || skip "no loop device is available"
+
+test_dir=$(mktemp -d) || exit 1
+mounted=0
+
+cleanup()
+{
+	if [ "$mounted" -eq 1 ]; then
+		umount "$test_dir/mnt" || true
+	fi
+	rm -rf "$test_dir"
+}
+trap cleanup EXIT INT TERM
+
+truncate -s 32M "$test_dir/fs.img" || exit 1
+if ! mkfs.ext4 -q -F -b 1024 -O ea_inode -J size=1 "$test_dir/fs.img" \
+		2>"$test_dir/mkfs.err"; then
+	cat "$test_dir/mkfs.err" >&2
+	skip "mkfs.ext4 does not support the ea_inode test image"
+fi
+mkdir "$test_dir/mnt" || exit 1
+if ! mount -t ext4 -o loop "$test_dir/fs.img" "$test_dir/mnt" \
+		2>"$test_dir/mount.err"; then
+	cat "$test_dir/mount.err" >&2
+	if grep -Eqi 'permission denied|operation not permitted|not permitted' \
+			"$test_dir/mount.err"; then
+		skip "mounting a loop image is not permitted"
+	fi
+	exit 1
+fi
+mounted=1
+
+test_bin="$(dirname "$0")/ext4_xattr_journal_credits"
+"$test_bin" "$test_dir/mnt" || exit $?
+
+umount "$test_dir/mnt" || exit 1
+mounted=0
+e2fsck -fn "$test_dir/fs.img"

base-commit: c44104f3642da720164042623e4832836aefdd8e
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2026-11-22  9:37 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-22  7:53 [PATCH] ext4: bound xattr journal credits to transaction limit arzuagapozosergio
2026-11-22  8:09 ` sashiko-bot
2026-11-22  8:49 ` [PATCH v2] " arzuagapozosergio
2026-11-22  9:09   ` sashiko-bot
2026-11-22  9:37   ` [PATCH v3] " arzuagapozosergio

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox