summaryrefslogtreecommitdiff
path: root/tools/testing/selftests/filesystems/fuse
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2026-11-21 17:22:21 -0800
committerLinus Torvalds <torvalds@linux-foundation.org>2026-11-21 17:22:21 -0800
commit4843f6873f7c4835e62f2c73ba0fd538e57a2f22 (patch)
treeee620501a1ffbad9a83141e3a70154e1fe641040 /tools/testing/selftests/filesystems/fuse
downloadlinux-master.tar.gz
linux-master.zip
Merge tag 'sysctl-7.04-fixes-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/sysctl/sysctlgraftedHEADmaster
Pull sysctl fix from Joel Granados: "Fix sysctl jiffy / milliseconds conversion: - Writing a previously read value "X" shall keep the same "X" value - Remove truncation that was causing incorrect saturation of valid timeouts" * tag 'sysctl-7.04-fixes-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/sysctl/sysctl: sysctl: Do jiffy / ms conversion in ulong space
Diffstat (limited to 'tools/testing/selftests/filesystems/fuse')
-rw-r--r--tools/testing/selftests/filesystems/fuse/.gitignore8
-rw-r--r--tools/testing/selftests/filesystems/fuse/Makefile36
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_acl_cache_test.c522
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_common.c58
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_common.h33
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_mnt.c149
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_readdir_cache_test.c273
-rw-r--r--tools/testing/selftests/filesystems/fuse/fuse_symlink_cache_test.c162
-rw-r--r--tools/testing/selftests/filesystems/fuse/fusectl_test.c147
-rw-r--r--tools/testing/selftests/filesystems/fuse/test_syncfs.c309
-rw-r--r--tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c475
11 files changed, 2172 insertions, 0 deletions
diff --git a/tools/testing/selftests/filesystems/fuse/.gitignore b/tools/testing/selftests/filesystems/fuse/.gitignore
new file mode 100644
index 000000000..7c787313e
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/.gitignore
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0-only
+fuse_mnt
+fusectl_test
+test_syncfs
+write_extend_eof_test
+fuse_acl_cache_test
+fuse_symlink_cache_test
+fuse_readdir_cache_test
diff --git a/tools/testing/selftests/filesystems/fuse/Makefile b/tools/testing/selftests/filesystems/fuse/Makefile
new file mode 100644
index 000000000..e3ae3acff
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/Makefile
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
+
+TEST_GEN_PROGS := fusectl_test test_syncfs
+TEST_GEN_PROGS += write_extend_eof_test
+TEST_GEN_PROGS += fuse_acl_cache_test
+TEST_GEN_PROGS += fuse_symlink_cache_test
+TEST_GEN_PROGS += fuse_readdir_cache_test
+TEST_GEN_FILES := fuse_mnt
+
+include ../../lib.mk
+
+$(OUTPUT)/write_extend_eof_test: LDLIBS += -lpthread
+
+VAR_CFLAGS := $(shell pkg-config fuse3 --cflags 2>/dev/null)
+ifeq ($(VAR_CFLAGS),)
+VAR_CFLAGS := -D_FILE_OFFSET_BITS=64 -I/usr/include/fuse3
+endif
+
+VAR_LDLIBS := $(shell pkg-config fuse3 --libs 2>/dev/null)
+ifeq ($(VAR_LDLIBS),)
+VAR_LDLIBS := -lfuse3 -pthread
+endif
+
+CFLAGS += $(VAR_CFLAGS)
+LDLIBS += $(VAR_LDLIBS)
+
+$(OUTPUT)/fuse_mnt: CFLAGS += $(VAR_CFLAGS)
+$(OUTPUT)/fuse_mnt: LDLIBS += $(VAR_LDLIBS)
+
+$(OUTPUT)/fuse_acl_cache_test: fuse_common.c fuse_acl_cache_test.c
+$(OUTPUT)/fuse_symlink_cache_test: fuse_common.c fuse_symlink_cache_test.c
+$(OUTPUT)/fuse_readdir_cache_test: fuse_common.c fuse_readdir_cache_test.c
+
+EXTRA_CLEAN := fuse_common.o
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_acl_cache_test.c b/tools/testing/selftests/filesystems/fuse/fuse_acl_cache_test.c
new file mode 100644
index 000000000..9c8840fe8
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_acl_cache_test.c
@@ -0,0 +1,522 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test: FUSE ACL caching bug triggered by AT_STATX_FORCE_SYNC
+ *
+ * A FUSE mount that does not negotiate FUSE_POSIX_ACL initialises every inode
+ * with i_acl = i_default_acl = ACL_DONT_CACHE. When a fresh stat is needed
+ * (e.g. AT_STATX_FORCE_SYNC), fuse_update_get_attr() calls
+ * forget_all_cached_acls() before issuing FUSE_GETATTR. On an unfixed kernel,
+ * __forget_cached_acl() replaces ACL_DONT_CACHE with ACL_NOT_CACHED,
+ * inadvertently enabling the kernel ACL cache for that inode. The next
+ * getxattr populates the cache. Because fuse_set_acl() skips
+ * forget_all_cached_acls() for !fc->posix_acl mounts, any subsequent change to
+ * the ACL leaves the stale kernel entry in place, and the next getxattr returns
+ * wrong data without ever reaching the FUSE daemon.
+ *
+ * Fix (fs/posix_acl.c): __forget_cached_acl() returns early when *p is
+ * ACL_DONT_CACHE, preserving the "never cache" invariant for the inode's
+ * lifetime.
+ *
+ * Test outline:
+ * 1. Mount a minimal FUSE fs (no FUSE_POSIX_ACL negotiated).
+ * 2. lgetxattr -> daemon called, ACL_A returned, NOT cached (ACL_DONT_CACHE).
+ * 3. statx(AT_STATX_FORCE_SYNC) -> forget_all_cached_acls() called.
+ * Buggy: ACL_DONT_CACHE -> ACL_NOT_CACHED (cache enabled).
+ * Fixed: ACL_DONT_CACHE preserved.
+ * 4. lgetxattr -> daemon called, ACL_A returned.
+ * Buggy: result now cached (ACL_NOT_CACHED -> cached).
+ * Fixed: result still not cached.
+ * 5. Daemon switches to ACL_B internally (different size).
+ * 6. lgetxattr -> should return ACL_B (44 bytes).
+ * Buggy: cache hit, returns stale ACL_A (28 bytes). FAIL.
+ * Fixed: no cache, daemon called, returns ACL_B (44 bytes). PASS.
+ */
+
+#define _GNU_SOURCE
+#include <fcntl.h>
+#include <linux/limits.h>
+#include <stdint.h>
+#include <sys/xattr.h>
+
+#include "kselftest_harness.h"
+
+#include "fuse_common.h"
+
+/* ---- ACL binary encoding ------------------------------------------------ */
+/*
+ * POSIX ACL v2 xattr format (little-endian):
+ * header: u32 version (= 0x00000002)
+ * entry: u16 tag | u16 perm | u32 id
+ *
+ * Entries must appear in tag-ascending order; named USER/GROUP entries
+ * require a MASK entry. Both ACLs pass posix_acl_from_xattr() validation.
+ */
+
+/* ACL_A: 3 entries (USER_OBJ:rwx, GROUP_OBJ:r-x, OTHER:r-x) = 28 bytes */
+static const uint8_t acl_a[] = {
+ 0x02, 0x00, 0x00, 0x00, /* v2 header */
+ 0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, /* USER_OBJ rwx */
+ 0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, /* GROUP_OBJ r-x */
+ 0x20, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, /* OTHER r-x */
+};
+
+/*
+ * ACL_B: 5 entries — adds USER uid=1 and MASK = 44 bytes.
+ * A named USER entry requires a MASK; all tags in ascending order.
+ */
+static const uint8_t acl_b[] = {
+ 0x02, 0x00, 0x00, 0x00, /* v2 header */
+ 0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, /* USER_OBJ rwx */
+ 0x02, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, /* USER uid=1 rwx */
+ 0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, /* GROUP_OBJ r-x */
+ 0x10, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, /* MASK rwx */
+ 0x20, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, /* OTHER r-x */
+};
+
+/* ---- Shared state (daemon thread <-> test thread) ----------------------- */
+
+#define FILE_INO 2
+#define FILE_NAME "testfile"
+
+struct daemon_state {
+ pthread_mutex_t lock;
+ uint8_t *acl;
+ size_t acl_size;
+ int getxattr_count;
+ uid_t uid;
+ uid_t gid;
+ bool cache;
+};
+
+/*
+ * Global: callbacks are stateless fns so we use a single global.
+ * Safe because only one test instance runs at a time.
+ */
+static struct daemon_state g_ds = {
+ .lock = PTHREAD_MUTEX_INITIALIZER,
+ .cache = false,
+};
+
+/* ---- FUSE lowlevel callbacks -------------------------------------------- */
+static void fs_init(void *userdata, struct fuse_conn_info *conn)
+{
+ pthread_mutex_lock(&g_ds.lock);
+ if (g_ds.cache)
+ fuse_set_feature_flag(conn, FUSE_CAP_POSIX_ACL);
+ pthread_mutex_unlock(&g_ds.lock);
+}
+
+static void fs_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
+{
+ if (parent != FUSE_ROOT_ID || strcmp(name, FILE_NAME)) {
+ fuse_reply_err(req, ENOENT);
+ return;
+ }
+ struct fuse_entry_param e = {};
+
+ /*
+ * Long attr/entry timeouts so that normal stat() calls do not
+ * expire and trigger forget_all_cached_acls() on their own;
+ * only the explicit AT_STATX_FORCE_SYNC should trigger it.
+ */
+ e.ino = FILE_INO;
+ e.generation = 1;
+ e.attr_timeout = 10.0;
+ e.entry_timeout = 10.0;
+ e.attr.st_ino = FILE_INO;
+ e.attr.st_mode = S_IFREG | 0644;
+ e.attr.st_nlink = 1;
+ pthread_mutex_lock(&g_ds.lock);
+ e.attr.st_uid = g_ds.uid;
+ e.attr.st_gid = g_ds.gid;
+ pthread_mutex_unlock(&g_ds.lock);
+ fuse_reply_entry(req, &e);
+}
+
+static void fs_getattr(fuse_req_t req, fuse_ino_t ino,
+ struct fuse_file_info *fi)
+{
+ struct stat st = {};
+
+ (void)fi;
+ if (ino == FUSE_ROOT_ID) {
+ st.st_ino = FUSE_ROOT_ID;
+ st.st_mode = S_IFDIR | 0755;
+ st.st_nlink = 2;
+ } else if (ino == FILE_INO) {
+ st.st_ino = FILE_INO;
+ st.st_mode = S_IFREG | 0644;
+ st.st_nlink = 1;
+ pthread_mutex_lock(&g_ds.lock);
+ st.st_uid = g_ds.uid;
+ st.st_gid = g_ds.gid;
+ pthread_mutex_unlock(&g_ds.lock);
+ } else {
+ fuse_reply_err(req, ENOENT);
+ return;
+ }
+ fuse_reply_attr(req, &st, 10);
+}
+
+static void fs_getxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
+ size_t size)
+{
+ uint8_t *acl = NULL;
+ size_t acl_size;
+
+ if (ino != FILE_INO ||
+ strcmp(name, "system.posix_acl_access") != 0) {
+ fuse_reply_err(req, ENODATA);
+ return;
+ }
+
+ if (size) {
+ acl = malloc(size);
+ if (!acl) {
+ fuse_reply_err(req, ENOMEM);
+ return;
+ }
+ }
+ pthread_mutex_lock(&g_ds.lock);
+ acl_size = g_ds.acl_size;
+ if (acl && acl_size && (size >= acl_size))
+ memcpy(acl, g_ds.acl, acl_size);
+ g_ds.getxattr_count++;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (acl_size == 0)
+ fuse_reply_err(req, ENODATA);
+ else if (size == 0)
+ fuse_reply_xattr(req, acl_size);
+ else if (size < acl_size)
+ fuse_reply_err(req, ERANGE);
+ else
+ fuse_reply_buf(req, (const char *)acl, acl_size);
+
+ free(acl);
+}
+
+static void fs_setxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
+ const char *value, size_t size, int flags)
+{
+ int ret = 0;
+ uint8_t *acl;
+
+ if (ino != FILE_INO) {
+ ret = ENOENT;
+ goto out;
+ } else if (strcmp(name, "system.posix_acl_access") != 0) {
+ ret = ENOTSUP;
+ goto out;
+ }
+ acl = malloc(size);
+ if (!acl) {
+ ret = ENOMEM;
+ goto out;
+ }
+ memcpy(acl, value, size);
+ pthread_mutex_lock(&g_ds.lock);
+ if (g_ds.acl)
+ free(g_ds.acl);
+ g_ds.acl = acl;
+ g_ds.acl_size = size;
+ pthread_mutex_unlock(&g_ds.lock);
+
+out:
+ fuse_reply_err(req, ret);
+}
+
+static const struct fuse_lowlevel_ops fs_ops = {
+ .init = fs_init,
+ .lookup = fs_lookup,
+ .getattr = fs_getattr,
+ .getxattr = fs_getxattr,
+ .setxattr = fs_setxattr,
+};
+
+/* ---- kselftest harness --------------------------------------------------- */
+
+FIXTURE(acl_cache) {
+ struct fuse_common_ctx ctx;
+ char file_path[PATH_MAX];
+};
+
+FIXTURE_SETUP(acl_cache)
+{
+ char err[MAX_ERR_MSG];
+
+ pthread_mutex_lock(&g_ds.lock);
+ g_ds.acl_size = sizeof(acl_a);
+ g_ds.acl = malloc(g_ds.acl_size);
+ ASSERT_NE(g_ds.acl, NULL);
+ memcpy(g_ds.acl, acl_a, g_ds.acl_size);
+ g_ds.getxattr_count = 0;
+ g_ds.uid = getuid();
+ g_ds.gid = getgid();
+ g_ds.cache = false;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (fs_setup(&fs_ops, &self->ctx, err))
+ SKIP(return, err);
+
+ snprintf(self->file_path, sizeof(self->file_path),
+ "%s/" FILE_NAME, self->ctx.mountpoint);
+}
+
+FIXTURE_TEARDOWN(acl_cache)
+{
+ fs_teardown(&self->ctx);
+ free(g_ds.acl);
+}
+
+static int do_force_statx(const char *path)
+{
+ struct statx stx;
+
+ return statx(AT_FDCWD, path, AT_STATX_FORCE_SYNC, STATX_BASIC_STATS,
+ &stx);
+}
+
+TEST_F(acl_cache, stale_after_force_sync)
+{
+ char buf[512];
+ ssize_t sz;
+ int count;
+ uint8_t *acl;
+
+ /*
+ * Step 1: two getxattr calls before any statx(FORCE_SYNC).
+ * i_acl == ACL_DONT_CACHE. __get_acl's cmpxchg(p, ACL_NOT_CACHED,
+ * sentinel) finds *p != ACL_NOT_CACHED on every call, so the sentinel
+ * is never placed and the result is never cached. Both calls must
+ * reach the daemon, proving ACL_DONT_CACHE suppresses caching.
+ */
+ sz = lgetxattr(self->file_path, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, (ssize_t)sizeof(acl_a));
+
+ sz = lgetxattr(self->file_path, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, (ssize_t)sizeof(acl_a));
+
+ pthread_mutex_lock(&g_ds.lock);
+ count = g_ds.getxattr_count;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ ASSERT_EQ(count, 2);
+ TH_LOG("step 1 OK: both pre-trigger getxattrs reached daemon (count=%d), "
+ "ACL_DONT_CACHE is working", count);
+
+ /*
+ * Step 2: statx(AT_STATX_FORCE_SYNC).
+ * fuse_update_get_attr() calls forget_all_cached_acls() before sending
+ * FUSE_GETATTR.
+ * Buggy kernel: ACL_DONT_CACHE -> ACL_NOT_CACHED (cache enabled)
+ * Fixed kernel: ACL_DONT_CACHE preserved (no effect)
+ */
+ ASSERT_EQ(do_force_statx(self->file_path), 0);
+ TH_LOG("step 2 OK: statx(AT_STATX_FORCE_SYNC) succeeded");
+
+ /*
+ * Step 3: getxattr — cache population attempt after the trigger.
+ * Buggy: *p == ACL_NOT_CACHED -> sentinel placed -> fuse_get_inode_acl
+ * called -> ACL_A parsed and stored in the kernel cache.
+ * Fixed: *p == ACL_DONT_CACHE -> sentinel placement skipped ->
+ * fuse_get_inode_acl called but result not cached.
+ * Either way the correct ACL_A is returned here.
+ */
+ sz = lgetxattr(self->file_path, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, (ssize_t)sizeof(acl_a));
+
+ pthread_mutex_lock(&g_ds.lock);
+ count = g_ds.getxattr_count;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ ASSERT_EQ(count, 3);
+ TH_LOG("step 3 OK: post-trigger getxattr reached daemon (count=%d), "
+ "returned correct ACL_A (%zd bytes)", count, sz);
+
+ /*
+ * Step 4: switch daemon to ACL_B (different size: 44 vs 28 bytes).
+ * Simulates an ACL change that fuse_set_acl() would NOT invalidate for
+ * !fc->posix_acl mounts (it skips forget_all_cached_acls in that case).
+ * On a fixed kernel the ACL was never cached, so this is moot.
+ */
+ acl = malloc(sizeof(acl_b));
+ ASSERT_NE(acl, NULL);
+ memcpy(acl, acl_b, sizeof(acl_b));
+
+ pthread_mutex_lock(&g_ds.lock);
+ free(g_ds.acl);
+ g_ds.acl = acl;
+ g_ds.acl_size = sizeof(acl_b);
+ pthread_mutex_unlock(&g_ds.lock);
+ TH_LOG("step 4: daemon switched to ACL_B (%zu bytes)", sizeof(acl_b));
+
+ /*
+ * Step 5: getxattr — the decisive check.
+ * Buggy kernel: cache hit -> stale ACL_A (28 bytes), count stays 3.
+ * Fixed kernel: no cache -> daemon called -> ACL_B (44 bytes), count 4.
+ */
+ sz = lgetxattr(self->file_path, "system.posix_acl_access",
+ buf, sizeof(buf));
+
+ pthread_mutex_lock(&g_ds.lock);
+ count = g_ds.getxattr_count;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (sz == (ssize_t)sizeof(acl_a))
+ TH_LOG("step 5 BUG: stale ACL_A (%zd bytes) from kernel cache "
+ "(count=%d); ACL_DONT_CACHE corrupted by "
+ "forget_all_cached_acls()", sz, count);
+ else
+ TH_LOG("step 5 OK: daemon reached (count=%d), "
+ "fresh ACL_B (%zd bytes)", count, sz);
+
+ EXPECT_EQ(sz, (ssize_t)sizeof(acl_b));
+ EXPECT_EQ(count, 4);
+}
+
+FIXTURE(acl_cache_onoff)
+{
+ struct fuse_common_ctx ctx;
+ char pathname[PATH_MAX];
+};
+
+FIXTURE_VARIANT(acl_cache_onoff) { bool cache; };
+FIXTURE_VARIANT_ADD(acl_cache_onoff, nocache) { .cache = false, };
+FIXTURE_VARIANT_ADD(acl_cache_onoff, docache) { .cache = true, };
+
+FIXTURE_SETUP(acl_cache_onoff)
+{
+ char err[MAX_ERR_MSG];
+
+ pthread_mutex_lock(&g_ds.lock);
+ g_ds.acl = NULL;
+ g_ds.acl_size = 0;
+ g_ds.getxattr_count = 0;
+ g_ds.cache = variant->cache;
+ g_ds.uid = getuid();
+ g_ds.gid = getgid();
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (fs_setup(&fs_ops, &self->ctx, err))
+ SKIP(return, err);
+
+ snprintf(self->pathname, sizeof(self->pathname),
+ "%s/" FILE_NAME, self->ctx.mountpoint);
+}
+
+FIXTURE_TEARDOWN(acl_cache_onoff)
+{
+ fs_teardown(&self->ctx);
+ free(g_ds.acl);
+}
+
+/*
+ * This is the most basic ACL caching test: verify that, when reading ACLs for
+ * an inode, user-space is called:
+ * - Only once if ACLs cache is enabled, or
+ * - Once per access if cache is disabled.
+ */
+TEST_F(acl_cache_onoff, test_acl_cache_enable_disable)
+{
+ char buf[512];
+ ssize_t sz;
+ bool cache;
+ int counter;
+ int i;
+
+ ASSERT_EQ(lsetxattr(self->pathname, "system.posix_acl_access",
+ acl_a, sizeof(acl_a), 0), 0);
+
+ for (i = 0; i < 100; i++) {
+ sz = lgetxattr(self->pathname, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, sizeof(acl_a));
+ ASSERT_EQ(memcmp(buf, acl_a, sz), 0);
+ }
+
+ pthread_mutex_lock(&g_ds.lock);
+ counter = g_ds.getxattr_count;
+ cache = g_ds.cache;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (cache) {
+ ASSERT_EQ(counter, 1);
+ } else {
+ ASSERT_EQ(counter, 100);
+ }
+
+ TH_LOG("User-space called %d time(s) with ACL caching %s",
+ counter, cache ? "enabled" : "disabled");
+}
+
+/*
+ * Test caching invalidation for several scenarios:
+ * 1. When a new ACL is set
+ * 2. When invalidating an inode (NOTIFY_INVAL_INODE)
+ */
+TEST_F(acl_cache_onoff, test_acl_cache_invalidation)
+{
+ char buf[512];
+ ssize_t sz;
+ int counter;
+ bool cache;
+ int i;
+
+ /* Set an ACL */
+ ASSERT_EQ(lsetxattr(self->pathname, "system.posix_acl_access",
+ acl_a, sizeof(acl_a), 0), 0);
+
+ for (i = 0; i < 100; i++) {
+ sz = lgetxattr(self->pathname, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, sizeof(acl_a));
+ ASSERT_EQ(memcmp(buf, acl_a, sz), 0);
+ }
+
+ /* 1. force cache invalidation by setting a new ACL */
+ ASSERT_EQ(lsetxattr(self->pathname, "system.posix_acl_access",
+ acl_b, sizeof(acl_b), 0), 0);
+
+ sz = lgetxattr(self->pathname, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, sizeof(acl_b));
+ ASSERT_EQ(memcmp(buf, acl_b, sz), 0);
+
+ pthread_mutex_lock(&g_ds.lock);
+ counter = g_ds.getxattr_count;
+ cache = g_ds.cache;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (cache) {
+ ASSERT_EQ(counter, 2);
+ } else {
+ ASSERT_EQ(counter, 101);
+ }
+ TH_LOG("Invalidation by setting new ACL: OK");
+
+ /* 2. send FUSE_NOTIFY_INVAL_INODE */
+ fuse_lowlevel_notify_inval_inode(self->ctx.se, FILE_INO, 0, 0);
+
+ sz = lgetxattr(self->pathname, "system.posix_acl_access",
+ buf, sizeof(buf));
+ ASSERT_EQ(sz, sizeof(acl_b));
+ ASSERT_EQ(memcmp(buf, acl_b, sz), 0);
+
+ pthread_mutex_lock(&g_ds.lock);
+ counter = g_ds.getxattr_count;
+ cache = g_ds.cache;
+ pthread_mutex_unlock(&g_ds.lock);
+
+ if (cache) {
+ ASSERT_EQ(counter, 3);
+ } else {
+ ASSERT_EQ(counter, 102);
+ }
+ TH_LOG("Invalidation through FUSE_NOTIFY_INVAL_INODE: OK");
+}
+
+TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_common.c b/tools/testing/selftests/filesystems/fuse/fuse_common.c
new file mode 100644
index 000000000..d1d3dfd2e
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_common.c
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include "fuse_common.h"
+
+static void *run_daemon(void *arg)
+{
+ fuse_session_loop((struct fuse_session *)arg);
+ return NULL;
+}
+
+int fs_setup(const struct fuse_lowlevel_ops *fs_ops,
+ struct fuse_common_ctx *ctx, char *err)
+{
+ char *fuse_argv[] = { "fuse_test", NULL };
+ struct fuse_args args = FUSE_ARGS_INIT(1, fuse_argv);
+
+ strcpy(ctx->mountpoint, MOUNTPOINT_TEMPLATE);
+ if (!mkdtemp(ctx->mountpoint)) {
+ snprintf(err, MAX_ERR_MSG, "mkdtemp: %s", strerror(errno));
+ return -1;
+ }
+
+ ctx->se = fuse_session_new(&args, fs_ops, sizeof(*fs_ops), NULL);
+ if (!ctx->se) {
+ rmdir(ctx->mountpoint);
+ snprintf(err, MAX_ERR_MSG, "fuse_session_new failed");
+ return -1;
+ }
+
+ if (fuse_session_mount(ctx->se, ctx->mountpoint)) {
+ fuse_session_destroy(ctx->se);
+ rmdir(ctx->mountpoint);
+ snprintf(err, MAX_ERR_MSG, "fuse_session_mount failed "
+ "(missing fusermount3 or insufficient privileges)");
+ return -1;
+ }
+
+ if (pthread_create(&ctx->thread, NULL, run_daemon, ctx->se)) {
+ fuse_session_unmount(ctx->se);
+ fuse_session_destroy(ctx->se);
+ rmdir(ctx->mountpoint);
+ snprintf(err, MAX_ERR_MSG, "pthread_create: %s", strerror(errno));
+ return -1;
+ }
+
+ fuse_opt_free_args(&args);
+
+ return 0;
+}
+
+void fs_teardown(struct fuse_common_ctx *ctx)
+{
+ fuse_session_exit(ctx->se);
+ fuse_session_unmount(ctx->se);
+ pthread_join(ctx->thread, NULL);
+ fuse_session_destroy(ctx->se);
+ rmdir(ctx->mountpoint);
+}
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_common.h b/tools/testing/selftests/filesystems/fuse/fuse_common.h
new file mode 100644
index 000000000..5beb6bf89
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_common.h
@@ -0,0 +1,33 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef __SELFTEST_FUSE_COMMON_H__
+#define __SELFTEST_FUSE_COMMON_H__
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <limits.h>
+
+#define FUSE_USE_VERSION 31
+#include <fuse_lowlevel.h>
+
+#define MAX_ERR_MSG 256
+
+#define MOUNTPOINT_TEMPLATE "/tmp/fuse_test_XXXXXX"
+#define MOUNTPOINT_SZ 64
+
+struct fuse_common_ctx {
+ struct fuse_session *se;
+ char mountpoint[MOUNTPOINT_SZ];
+ pthread_t thread;
+};
+
+int fs_setup(const struct fuse_lowlevel_ops *fs_ops,
+ struct fuse_common_ctx *ctx, char *err);
+void fs_teardown(struct fuse_common_ctx *ctx);
+
+#endif /* __SELFTEST_FUSE_COMMON_H__ */
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_mnt.c b/tools/testing/selftests/filesystems/fuse/fuse_mnt.c
new file mode 100644
index 000000000..5d335fa5c
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_mnt.c
@@ -0,0 +1,149 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * fusectl test file-system
+ * Creates a simple FUSE filesystem with a single read-write file (/test)
+ */
+
+#define FUSE_USE_VERSION 31
+
+#include <fuse.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#define MAX(a, b) ((a) > (b) ? (a) : (b))
+
+static char *content;
+static size_t content_size = 0;
+static const char test_path[] = "/test";
+
+static int test_getattr(const char *path, struct stat *st,
+ struct fuse_file_info *fi)
+{
+ memset(st, 0, sizeof(*st));
+
+ if (!strcmp(path, "/")) {
+ st->st_mode = S_IFDIR | 0755;
+ st->st_nlink = 2;
+ return 0;
+ }
+
+ if (!strcmp(path, test_path)) {
+ st->st_mode = S_IFREG | 0664;
+ st->st_nlink = 1;
+ st->st_size = content_size;
+ return 0;
+ }
+
+ return -ENOENT;
+}
+
+static int test_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
+ off_t offset, struct fuse_file_info *fi,
+ enum fuse_readdir_flags flags)
+{
+ if (strcmp(path, "/"))
+ return -ENOENT;
+
+ filler(buf, ".", NULL, 0, FUSE_FILL_DIR_DEFAULTS);
+ filler(buf, "..", NULL, 0, FUSE_FILL_DIR_DEFAULTS);
+ filler(buf, test_path + 1, NULL, 0, FUSE_FILL_DIR_DEFAULTS);
+
+ return 0;
+}
+
+static int test_open(const char *path, struct fuse_file_info *fi)
+{
+ if (strcmp(path, test_path))
+ return -ENOENT;
+
+ return 0;
+}
+
+static int test_read(const char *path, char *buf, size_t size, off_t offset,
+ struct fuse_file_info *fi)
+{
+ if (strcmp(path, test_path) != 0)
+ return -ENOENT;
+
+ if (!content || content_size == 0)
+ return 0;
+
+ if (offset >= content_size)
+ return 0;
+
+ if (offset + size > content_size)
+ size = content_size - offset;
+
+ memcpy(buf, content + offset, size);
+
+ return size;
+}
+
+static int test_write(const char *path, const char *buf, size_t size,
+ off_t offset, struct fuse_file_info *fi)
+{
+ size_t new_size;
+
+ if (strcmp(path, test_path) != 0)
+ return -ENOENT;
+
+ if(offset > content_size)
+ return -EINVAL;
+
+ new_size = MAX(offset + size, content_size);
+
+ if (new_size > content_size)
+ content = realloc(content, new_size);
+
+ content_size = new_size;
+
+ if (!content)
+ return -ENOMEM;
+
+ memcpy(content + offset, buf, size);
+
+ return size;
+}
+
+static int test_truncate(const char *path, off_t size,
+ struct fuse_file_info *fi)
+{
+ if (strcmp(path, test_path) != 0)
+ return -ENOENT;
+
+ if (size == 0) {
+ free(content);
+ content = NULL;
+ content_size = 0;
+ return 0;
+ }
+
+ content = realloc(content, size);
+
+ if (!content)
+ return -ENOMEM;
+
+ if (size > content_size)
+ memset(content + content_size, 0, size - content_size);
+
+ content_size = size;
+ return 0;
+}
+
+static struct fuse_operations memfd_ops = {
+ .getattr = test_getattr,
+ .readdir = test_readdir,
+ .open = test_open,
+ .read = test_read,
+ .write = test_write,
+ .truncate = test_truncate,
+};
+
+int main(int argc, char *argv[])
+{
+ return fuse_main(argc, argv, &memfd_ops, NULL);
+}
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_readdir_cache_test.c b/tools/testing/selftests/filesystems/fuse/fuse_readdir_cache_test.c
new file mode 100644
index 000000000..59314f996
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_readdir_cache_test.c
@@ -0,0 +1,273 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Simple filesystem to test FUSE readdir cache
+ *
+ * It will simply perform readdir operations on a directory checking how many
+ * times a request is sent to user-space using all the possible caching
+ * combination setting (FOPEN_KEEP_CACHE and FOPEN_CACHE_DIR flags).
+ */
+
+#include <stdio.h>
+#include <dirent.h>
+
+#include "kselftest_harness.h"
+
+#include "fuse_common.h"
+
+#define DIRNAME "mydir"
+#define FILENAME "myfile"
+
+#define DIR_INO 42
+#define FILE_INO 43
+#define DOT_INO 40
+#define DOTDOT_INO 41
+
+#define TIMEOUT 86400.0f
+
+struct test_state {
+ pthread_mutex_t lock;
+ time_t mtime;
+ int readdir_counter;
+ bool cache_readdir;
+ bool keep_cache;
+} test_state = {
+ .lock = PTHREAD_MUTEX_INITIALIZER,
+};
+
+static void fs_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
+{
+ struct fuse_entry_param e = {};
+
+ if (parent != FUSE_ROOT_ID || strcmp(name, DIRNAME) != 0) {
+ fuse_reply_err(req, ENOENT);
+ return;
+ }
+
+ e.ino = DIR_INO;
+ e.attr.st_mode = S_IFDIR | 0755;
+ e.attr.st_nlink = 1;
+ pthread_mutex_lock(&test_state.lock);
+ e.attr.st_mtime = test_state.mtime;
+ pthread_mutex_unlock(&test_state.lock);
+ e.attr_timeout = TIMEOUT;
+ e.entry_timeout = TIMEOUT;
+
+ fuse_reply_entry(req, &e);
+}
+
+static int fill_stat(fuse_ino_t ino, struct stat *st)
+{
+ int ret = 0;
+
+ st->st_ino = ino;
+ pthread_mutex_lock(&test_state.lock);
+ st->st_mtime = test_state.mtime;
+ pthread_mutex_unlock(&test_state.lock);
+
+ switch (ino) {
+ case FUSE_ROOT_ID:
+ st->st_mode = S_IFDIR | 0755;
+ st->st_nlink = 2;
+ break;
+ case DOT_INO:
+ case DOTDOT_INO:
+ case DIR_INO:
+ st->st_mode = S_IFDIR | 0755;
+ st->st_nlink = 1;
+ break;
+ case FILE_INO:
+ st->st_mode = S_IFREG | 0444;
+ st->st_nlink = 1;
+ break;
+ default:
+ ret = -1;
+ break;
+ }
+
+ return ret;
+}
+
+static void fs_getattr(fuse_req_t req, fuse_ino_t ino,
+ struct fuse_file_info *fi)
+{
+ struct stat st = {};
+
+ if (fill_stat(ino, &st) < 0)
+ fuse_reply_err(req, ENOENT);
+ else
+ fuse_reply_attr(req, &st, TIMEOUT);
+}
+
+static void fs_opendir(fuse_req_t req, fuse_ino_t ino,
+ struct fuse_file_info *fi)
+{
+ pthread_mutex_lock(&test_state.lock);
+ fi->keep_cache = test_state.keep_cache;
+ fi->cache_readdir = test_state.cache_readdir;
+ pthread_mutex_unlock(&test_state.lock);
+ fuse_reply_open(req, fi);
+}
+
+static void fs_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
+ off_t offset, struct fuse_file_info *fi)
+{
+ struct stat st = {};
+ char buf[1024];
+ char *pbuf;
+ size_t rem = size;
+ size_t sz;
+ int nextoff = 0;
+
+ if (ino != DIR_INO) {
+ fuse_reply_err(req, ENOTDIR);
+ return;
+ }
+ if (offset) {
+ fuse_reply_buf(req, NULL, 0);
+ return;
+ }
+ pbuf = buf;
+ fill_stat(DOT_INO, &st);
+ sz = fuse_add_direntry(req, pbuf, rem, ".", &st, nextoff++);
+ rem -= sz;
+ pbuf += sz;
+ fill_stat(DOTDOT_INO, &st);
+ sz = fuse_add_direntry(req, pbuf, rem, "..", &st, nextoff++);
+ rem -= sz;
+ pbuf += sz;
+ fill_stat(FILE_INO, &st);
+ sz = fuse_add_direntry(req, pbuf, rem, FILENAME, &st, nextoff++);
+ rem -= sz;
+
+ fuse_reply_buf(req, buf, size - rem);
+
+ pthread_mutex_lock(&test_state.lock);
+ test_state.readdir_counter++;
+ pthread_mutex_unlock(&test_state.lock);
+}
+
+static const struct fuse_lowlevel_ops fs_ops = {
+ .lookup = fs_lookup,
+ .getattr = fs_getattr,
+ .opendir = fs_opendir,
+ .readdir = fs_readdir,
+};
+
+FIXTURE(readdir_cache)
+{
+ struct fuse_common_ctx ctx;
+};
+
+FIXTURE_VARIANT(readdir_cache)
+{
+ bool cache_readdir;
+ bool keep_cache;
+};
+FIXTURE_VARIANT_ADD(readdir_cache, nocache)
+{
+ .cache_readdir = false,
+ .keep_cache = false,
+};
+FIXTURE_VARIANT_ADD(readdir_cache, cache_readdir)
+{
+ .cache_readdir = true,
+ .keep_cache = false,
+};
+FIXTURE_VARIANT_ADD(readdir_cache, keep_cache)
+{
+ .cache_readdir = false,
+ .keep_cache = true,
+};
+FIXTURE_VARIANT_ADD(readdir_cache, cache)
+{
+ .cache_readdir = true,
+ .keep_cache = true,
+};
+
+FIXTURE_SETUP(readdir_cache)
+{
+ char err[MAX_ERR_MSG];
+
+ pthread_mutex_lock(&test_state.lock);
+ test_state.mtime = time(NULL);
+ test_state.readdir_counter = 0;
+ test_state.cache_readdir = variant->cache_readdir;
+ test_state.keep_cache = variant->keep_cache;
+ pthread_mutex_unlock(&test_state.lock);
+
+ if (fs_setup(&fs_ops, &self->ctx, err))
+ SKIP(return, err);
+}
+
+FIXTURE_TEARDOWN(readdir_cache)
+{
+ fs_teardown(&self->ctx);
+}
+
+TEST_F(readdir_cache, test_readdir_cache)
+{
+ struct dirent *dentry;
+ DIR *dir;
+ char pathname[PATH_MAX];
+ int total_counter, rewind_counter;
+ int dentrycount;
+
+ sprintf(pathname, "%s/%s", self->ctx.mountpoint, DIRNAME);
+
+ dir = opendir(pathname);
+ if (dir == NULL)
+ TH_LOG("opendir(): %s", strerror(errno));
+ ASSERT_NE(dir, NULL);
+
+ errno = 0;
+ dentrycount = 0;
+ while ((dentry = readdir(dir)))
+ dentrycount++;
+ ASSERT_EQ(errno, 0);
+ ASSERT_EQ(dentrycount, 3);
+
+ rewinddir(dir);
+ errno = 0;
+ dentrycount = 0;
+ while ((dentry = readdir(dir)))
+ dentrycount++;
+ ASSERT_EQ(errno, 0);
+ ASSERT_EQ(dentrycount, 3);
+
+ ASSERT_EQ(closedir(dir), 0);
+
+ pthread_mutex_lock(&test_state.lock);
+ rewind_counter = test_state.readdir_counter;
+ pthread_mutex_unlock(&test_state.lock);
+
+ dir = opendir(pathname);
+ if (dir == NULL)
+ TH_LOG("opendir(): %s", strerror(errno));
+ ASSERT_NE(dir, NULL);
+
+ errno = 0;
+ dentrycount = 0;
+ while ((dentry = readdir(dir)))
+ dentrycount++;
+ ASSERT_EQ(errno, 0);
+ ASSERT_EQ(dentrycount, 3);
+
+ ASSERT_EQ(closedir(dir), 0);
+
+ pthread_mutex_lock(&test_state.lock);
+ total_counter = test_state.readdir_counter;
+ pthread_mutex_unlock(&test_state.lock);
+
+ if (!variant->cache_readdir) {
+ ASSERT_EQ(rewind_counter, 2);
+ ASSERT_EQ(total_counter, 3);
+ } else if (!variant->keep_cache) {
+ ASSERT_EQ(rewind_counter, 1);
+ ASSERT_EQ(total_counter, 2);
+ } else {
+ ASSERT_EQ(rewind_counter, 1);
+ ASSERT_EQ(total_counter, 1);
+ }
+}
+
+TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/filesystems/fuse/fuse_symlink_cache_test.c b/tools/testing/selftests/filesystems/fuse/fuse_symlink_cache_test.c
new file mode 100644
index 000000000..7b5373499
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fuse_symlink_cache_test.c
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Simple filesystem to test FUSE symlink cache
+ *
+ * This is a simple FUSE filesystem that contains two objects: a file named
+ * 'file' and a symlink to that file named 'link'. If symlink caching is
+ * disabled (i.e. FUSE_CAP_CACHE_SYMLINKS is reset during FUSE_INIT), whenever
+ * the ->readlink() is executed to resolve 'link' a counter will be incremented.
+ *
+ * If symlink caching is enabled (i.e. FUSE_CAP_CACHE_SYMLINKS is set during
+ * FUSE_INIT), resolving a symlink will only call into user-space the first
+ * time.
+ */
+
+#define FUSE_USE_VERSION 31
+
+#include <stdio.h>
+#include <fuse_lowlevel.h>
+
+#include "kselftest_harness.h"
+
+#include "fuse_common.h"
+
+#define FILENAME "file"
+#define FILE_INO 42
+
+#define LINKNAME "link"
+#define LINK_INO 43
+
+#define TIMEOUT 86400.0f
+
+struct test_state {
+ pthread_mutex_t lock;
+ int readlink_counter;
+ bool cache;
+} test_state = {
+ .lock = PTHREAD_MUTEX_INITIALIZER,
+};
+
+static void fs_init(void *userdata, struct fuse_conn_info *conn)
+{
+ pthread_mutex_lock(&test_state.lock);
+ if (test_state.cache)
+ fuse_set_feature_flag(conn, FUSE_CAP_CACHE_SYMLINKS);
+ else
+ fuse_unset_feature_flag(conn, FUSE_CAP_CACHE_SYMLINKS);
+ pthread_mutex_unlock(&test_state.lock);
+}
+
+static void fs_lookup(fuse_req_t req, fuse_ino_t parent, const char *name)
+{
+ struct fuse_entry_param e = {};
+
+ if (parent != FUSE_ROOT_ID ||
+ (strcmp(name, FILENAME) != 0 && strcmp(name, LINKNAME) != 0)) {
+ fuse_reply_err(req, ENOENT);
+ return;
+ }
+
+ if (!strcmp(name, FILENAME)) {
+ e.ino = FILE_INO;
+ e.attr.st_mode = S_IFREG | 0444;
+ e.attr.st_nlink = 2;
+ } else if (!strcmp(name, LINKNAME)) {
+ e.ino = LINK_INO;
+ e.attr.st_mode = S_IFLNK | 0444;
+ e.attr.st_nlink = 1;
+ e.attr.st_size = strlen(FILENAME);
+ }
+ e.attr_timeout = TIMEOUT;
+ e.entry_timeout = TIMEOUT;
+
+ fuse_reply_entry(req, &e);
+}
+
+static void fs_readlink(fuse_req_t req, fuse_ino_t ino)
+{
+ char buf[PATH_MAX];
+ size_t sz = strlen(FILENAME);
+
+ if (ino != LINK_INO) {
+ fuse_reply_err(req, ENOENT);
+ return;
+ }
+
+ memcpy(buf, FILENAME, sz);
+ buf[sz] = '\0';
+ pthread_mutex_lock(&test_state.lock);
+ test_state.readlink_counter++;
+ pthread_mutex_unlock(&test_state.lock);
+
+ fuse_reply_readlink(req, buf);
+}
+
+static const struct fuse_lowlevel_ops fs_ops = {
+ .init = fs_init,
+ .lookup = fs_lookup,
+ .readlink = fs_readlink,
+};
+
+FIXTURE(symlink_cache)
+{
+ struct fuse_common_ctx ctx;
+};
+FIXTURE_VARIANT(symlink_cache)
+{
+ const bool cache;
+};
+FIXTURE_VARIANT_ADD(symlink_cache, symlinks_nocache)
+{
+ /* Variant with symlink cache disabled */
+ .cache = false,
+};
+FIXTURE_VARIANT_ADD(symlink_cache, symlinks_cache)
+{
+ /* Variant with symlink cache enabled */
+ .cache = true,
+};
+
+FIXTURE_SETUP(symlink_cache)
+{
+ char err[MAX_ERR_MSG];
+
+ pthread_mutex_lock(&test_state.lock);
+ test_state.readlink_counter = 0;
+ test_state.cache = variant->cache;
+ pthread_mutex_unlock(&test_state.lock);
+
+ if (fs_setup(&fs_ops, &self->ctx, err))
+ SKIP(return, err);
+}
+
+FIXTURE_TEARDOWN(symlink_cache)
+{
+ fs_teardown(&self->ctx);
+}
+
+TEST_F(symlink_cache, test_symlink_cache)
+{
+ char pathname[PATH_MAX];
+ char buf[PATH_MAX];
+ ssize_t sz;
+ int counter;
+ int i;
+
+ sprintf(pathname, "%s/%s", self->ctx.mountpoint, LINKNAME);
+ for (i = 0; i < 100; i++) {
+ sz = readlink(pathname, buf, PATH_MAX);
+ ASSERT_NE(sz, -1);
+ }
+ pthread_mutex_lock(&test_state.lock);
+ counter = test_state.readlink_counter;
+ pthread_mutex_unlock(&test_state.lock);
+
+ if (variant->cache) {
+ ASSERT_EQ(counter, 1);
+ } else {
+ ASSERT_EQ(counter, 100);
+ }
+}
+
+TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/filesystems/fuse/fusectl_test.c b/tools/testing/selftests/filesystems/fuse/fusectl_test.c
new file mode 100644
index 000000000..b828173c0
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/fusectl_test.c
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+// Copyright (c) 2025 Chen Linxuan <chenlinxuan@uniontech.com>
+
+#define _GNU_SOURCE
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <sched.h>
+#include <linux/limits.h>
+
+#include "kselftest_harness.h"
+
+#define FUSECTL_MOUNTPOINT "/sys/fs/fuse/connections"
+#define FUSE_MOUNTPOINT "/tmp/fuse_mnt_XXXXXX"
+#define FUSE_DEVICE "/dev/fuse"
+#define FUSECTL_TEST_VALUE "1"
+
+static void write_file(struct __test_metadata *const _metadata,
+ const char *path, const char *val)
+{
+ int fd = open(path, O_WRONLY);
+ size_t len = strlen(val);
+
+ ASSERT_GE(fd, 0);
+ ASSERT_EQ(write(fd, val, len), len);
+ ASSERT_EQ(close(fd), 0);
+}
+
+FIXTURE(fusectl){
+ char fuse_mountpoint[sizeof(FUSE_MOUNTPOINT)];
+ int connection;
+};
+
+FIXTURE_SETUP(fusectl)
+{
+ const char *fuse_mnt_prog = "./fuse_mnt";
+ int status, pid;
+ struct stat statbuf;
+ uid_t uid = getuid();
+ gid_t gid = getgid();
+ char buf[32];
+
+ /* Setup userns */
+ ASSERT_EQ(unshare(CLONE_NEWNS|CLONE_NEWUSER), 0);
+ sprintf(buf, "0 %d 1", uid);
+ write_file(_metadata, "/proc/self/uid_map", buf);
+ write_file(_metadata, "/proc/self/setgroups", "deny");
+ sprintf(buf, "0 %d 1", gid);
+ write_file(_metadata, "/proc/self/gid_map", buf);
+ ASSERT_EQ(mount("", "/", NULL, MS_REC|MS_PRIVATE, NULL), 0);
+
+ strcpy(self->fuse_mountpoint, FUSE_MOUNTPOINT);
+
+ if (!mkdtemp(self->fuse_mountpoint))
+ SKIP(return,
+ "Failed to create FUSE mountpoint %s",
+ strerror(errno));
+
+ if (access(FUSECTL_MOUNTPOINT, F_OK))
+ SKIP(return,
+ "FUSE control filesystem not mounted");
+
+ pid = fork();
+ if (pid < 0)
+ SKIP(return,
+ "Failed to fork FUSE daemon process: %s",
+ strerror(errno));
+
+ if (pid == 0) {
+ execlp(fuse_mnt_prog, fuse_mnt_prog, self->fuse_mountpoint, NULL);
+ exit(errno);
+ }
+
+ waitpid(pid, &status, 0);
+ if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
+ SKIP(return,
+ "Failed to start FUSE daemon %s",
+ strerror(WEXITSTATUS(status)));
+ }
+
+ if (stat(self->fuse_mountpoint, &statbuf))
+ SKIP(return,
+ "Failed to stat FUSE mountpoint %s",
+ strerror(errno));
+
+ self->connection = statbuf.st_dev;
+}
+
+FIXTURE_TEARDOWN(fusectl)
+{
+ umount2(self->fuse_mountpoint, MNT_DETACH);
+ rmdir(self->fuse_mountpoint);
+}
+
+TEST_F(fusectl, abort)
+{
+ char path_buf[PATH_MAX];
+ int abort_fd, test_fd, ret;
+
+ snprintf(path_buf, PATH_MAX, "%s/%d", FUSECTL_MOUNTPOINT,
+ self->connection);
+ if (access(path_buf, F_OK) != 0)
+ SKIP(return,
+ "fusectl doesn't seem to be mounted: %s",
+ strerror(errno));
+
+ snprintf(path_buf, PATH_MAX, "%s/%d/abort", FUSECTL_MOUNTPOINT,
+ self->connection);
+ ASSERT_EQ(0, access(path_buf, F_OK));
+
+ abort_fd = open(path_buf, O_WRONLY);
+ ASSERT_GE(abort_fd, 0);
+
+ sprintf(path_buf, "%s/test", self->fuse_mountpoint);
+
+ test_fd = open(path_buf, O_RDWR);
+ ASSERT_GE(test_fd, 0);
+
+ ret = read(test_fd, path_buf, sizeof(path_buf));
+ ASSERT_EQ(ret, 0);
+
+ ret = write(test_fd, "test", sizeof("test"));
+ ASSERT_EQ(ret, sizeof("test"));
+
+ ret = lseek(test_fd, 0, SEEK_SET);
+ ASSERT_GE(ret, 0);
+
+ ret = write(abort_fd, FUSECTL_TEST_VALUE, sizeof(FUSECTL_TEST_VALUE));
+ ASSERT_GT(ret, 0);
+
+ close(abort_fd);
+
+ ret = read(test_fd, path_buf, sizeof(path_buf));
+ ASSERT_EQ(ret, -1);
+ ASSERT_EQ(errno, ENOTCONN);
+}
+
+TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/filesystems/fuse/test_syncfs.c b/tools/testing/selftests/filesystems/fuse/test_syncfs.c
new file mode 100644
index 000000000..d3ca2613b
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/test_syncfs.c
@@ -0,0 +1,309 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test that FUSE_SYNCFS is propagated to a userspace server only when the
+ * server opts in with FUSE_HAS_SYNCFS *and* opened /dev/fuse with
+ * CAP_SYS_ADMIN in the initial user namespace.
+ *
+ * Unlike the libfuse-based selftests, this talks the raw FUSE wire protocol
+ * over /dev/fuse so it can (a) choose whether to advertise FUSE_HAS_SYNCFS in
+ * the INIT reply and (b) observe directly whether a FUSE_SYNCFS opcode arrives.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/eventfd.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/wait.h>
+#include <linux/capability.h>
+#include <linux/fuse.h>
+
+#include "../../kselftest.h"
+
+#define FUSE_ROOT_ID 1
+
+/*
+ * Add or drop CAP_SYS_ADMIN in the effective set via raw capget/capset
+ * (avoids a libcap dependency). Used to construct a server that opens
+ * /dev/fuse without the privilege FUSE_HAS_SYNCFS requires.
+ */
+static int set_sysadmin(int on)
+{
+ struct __user_cap_header_struct hdr = {
+ .version = _LINUX_CAPABILITY_VERSION_3,
+ .pid = 0,
+ };
+ struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3] = {};
+ unsigned int idx = CAP_SYS_ADMIN >> 5;
+ __u32 bit = 1U << (CAP_SYS_ADMIN & 31);
+
+ if (syscall(SYS_capget, &hdr, data))
+ return -1;
+ if (on)
+ data[idx].effective |= bit;
+ else
+ data[idx].effective &= ~bit;
+ return syscall(SYS_capset, &hdr, data);
+}
+
+/*
+ * eventfd the server child writes once when it receives FUSE_SYNCFS; the
+ * parent poll()s it to observe (or rule out) propagation.
+ */
+static int syncfs_evfd;
+
+static void reply(int fd, uint64_t unique, int error, void *data, size_t len)
+{
+ struct fuse_out_header oh = {
+ .len = sizeof(oh) + len,
+ .error = error,
+ .unique = unique,
+ };
+ struct iovec iov[2] = {
+ { &oh, sizeof(oh) },
+ { data, len },
+ };
+
+ if (writev(fd, iov, data ? 2 : 1) < 0)
+ ksft_print_msg("server writev failed: %s\n", strerror(errno));
+}
+
+static void fill_attr(struct fuse_attr *a, uint64_t ino, uint32_t mode,
+ uint32_t nlink)
+{
+ memset(a, 0, sizeof(*a));
+ a->ino = ino;
+ a->mode = mode;
+ a->nlink = nlink;
+ a->blksize = 4096;
+}
+
+/*
+ * Minimal FUSE server. Advertises FUSE_HAS_SYNCFS in its INIT reply iff
+ * @advertise is set. Signals syncfs_evfd when a FUSE_SYNCFS opcode arrives.
+ */
+#define SERVER_MAX_WRITE 65536
+static void run_server(int fd, int advertise)
+{
+ /*
+ * The kernel rejects reads (EINVAL) whose buffer is smaller than
+ * max_write + header, so size generously for the max_write we
+ * advertise in the INIT reply below.
+ */
+ static char buf[SERVER_MAX_WRITE + 4096];
+
+ for (;;) {
+ ssize_t n = read(fd, buf, sizeof(buf));
+ struct fuse_in_header *ih = (void *)buf;
+
+ if (n < 0) {
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+ return; /* device closed on unmount/abort */
+ }
+ if (n < (ssize_t)sizeof(*ih))
+ continue;
+
+ switch (ih->opcode) {
+ case FUSE_INIT: {
+ struct fuse_init_in *in = (void *)(ih + 1);
+ struct fuse_init_out out = {0};
+ uint64_t flags = FUSE_INIT_EXT;
+
+ out.major = FUSE_KERNEL_VERSION;
+ out.minor = FUSE_KERNEL_MINOR_VERSION;
+ out.max_readahead = in->max_readahead;
+ out.max_write = SERVER_MAX_WRITE;
+ out.max_background = 16;
+ out.congestion_threshold = 12;
+ if (advertise)
+ flags |= FUSE_HAS_SYNCFS;
+ out.flags = flags;
+ out.flags2 = flags >> 32;
+ reply(fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_GETATTR: {
+ struct fuse_attr_out out = {0};
+
+ fill_attr(&out.attr, FUSE_ROOT_ID, S_IFDIR | 0755, 2);
+ reply(fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_SYNCFS: {
+ uint64_t one = 1;
+
+ if (write(syncfs_evfd, &one, sizeof(one)) < 0)
+ ksft_print_msg("server eventfd write failed: %s\n",
+ strerror(errno));
+ reply(fd, ih->unique, 0, NULL, 0);
+ break;
+ }
+ default:
+ /*
+ * Anything else (e.g. OPENDIR from opening the mount
+ * root) is not needed to drive this test; -ENOSYS lets
+ * the kernel proceed.
+ */
+ reply(fd, ih->unique, -ENOSYS, NULL, 0);
+ break;
+ }
+ }
+}
+
+/*
+ * Mount a fuse fs backed by a forked server, issue syncfs(), and report
+ * whether the server observed FUSE_SYNCFS. Returns 0 on success, -1 if the
+ * environment could not support the test (caller should skip).
+ *
+ * If @unpriv_open is set, /dev/fuse is opened with CAP_SYS_ADMIN dropped
+ * (regained only for the mount() syscall), so the device opener -- the
+ * server principal FUSE_HAS_SYNCFS is gated on -- lacks the privilege even
+ * though it remains in the initial user namespace.
+ */
+static int do_mount_and_syncfs(const char *mnt, int advertise, int unpriv_open,
+ int *seen)
+{
+ struct pollfd pfd = { .events = POLLIN };
+ char opts[256];
+ int fd, mfd = -1, i;
+ pid_t pid;
+
+ syncfs_evfd = eventfd(0, EFD_CLOEXEC);
+ if (syncfs_evfd < 0)
+ return -1;
+
+ if (unpriv_open && set_sysadmin(0))
+ goto out_evfd;
+ fd = open("/dev/fuse", O_RDWR);
+ if (unpriv_open && set_sysadmin(1)) {
+ if (fd >= 0)
+ close(fd);
+ goto out_evfd;
+ }
+ if (fd < 0)
+ goto out_evfd;
+
+ mkdir(mnt, 0755);
+ snprintf(opts, sizeof(opts),
+ "fd=%d,rootmode=40000,user_id=%d,group_id=%d",
+ fd, getuid(), getgid());
+
+ if (mount("fuse", mnt, "fuse", 0, opts) < 0)
+ goto out_fd;
+
+ pid = fork();
+ if (pid < 0)
+ goto out_umount;
+ if (pid == 0) {
+ run_server(fd, advertise);
+ _exit(0);
+ }
+
+ /*
+ * The parent does not service the fuse fd; the child does. Close our
+ * copy so the kernel sees a single server, and so that if the child
+ * dies the connection aborts instead of hanging us forever.
+ */
+ close(fd);
+
+ /*
+ * mount() returns before the server has answered FUSE_INIT, so the
+ * first open() can race and fail with ENOTCONN; retry until the
+ * handshake settles.
+ */
+ for (i = 0; i < 1000; i++) {
+ mfd = open(mnt, O_RDONLY | O_DIRECTORY);
+ if (mfd >= 0)
+ break;
+ usleep(1000);
+ }
+ if (mfd >= 0) {
+ syncfs(mfd);
+ close(mfd);
+ }
+
+ /*
+ * No waiting is needed: the server writes syncfs_evfd before it replies
+ * to FUSE_SYNCFS, and that reply is what unblocks the synchronous
+ * syncfs() above. So once syncfs() has returned, the eventfd is already
+ * signalled if the opcode was propagated, and will never be otherwise.
+ * poll() with a zero timeout therefore decides both cases immediately.
+ */
+ pfd.fd = syncfs_evfd;
+ *seen = poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN);
+
+ kill(pid, SIGKILL);
+ waitpid(pid, NULL, 0);
+ umount2(mnt, MNT_DETACH);
+ close(syncfs_evfd);
+ return 0;
+
+out_umount:
+ umount2(mnt, MNT_DETACH);
+out_fd:
+ close(fd);
+out_evfd:
+ close(syncfs_evfd);
+ return -1;
+}
+
+int main(void)
+{
+ char mnt[] = "/tmp/fuse_syncfs_XXXXXX";
+ int seen, ret;
+
+ ksft_print_header();
+ ksft_set_plan(3);
+
+ /* Hard watchdog: never let a stuck syncfs hang the test runner. */
+ signal(SIGALRM, SIG_DFL);
+ alarm(60);
+
+ if (geteuid() != 0)
+ ksft_exit_skip("test requires root to mount fuse\n");
+
+ if (!mkdtemp(mnt))
+ ksft_exit_fail_msg("mkdtemp failed\n");
+
+ /* T1: host-root mount, server opts in -> syncfs must reach server. */
+ ret = do_mount_and_syncfs(mnt, 1, 0, &seen);
+ if (ret < 0)
+ ksft_test_result_skip("T1: could not mount fuse\n");
+ else
+ ksft_test_result(seen,
+ "T1 host-root + FUSE_HAS_SYNCFS: server receives FUSE_SYNCFS\n");
+
+ /* T2: host-root mount, server does NOT opt in -> no FUSE_SYNCFS. */
+ ret = do_mount_and_syncfs(mnt, 0, 0, &seen);
+ if (ret < 0)
+ ksft_test_result_skip("T2: could not mount fuse\n");
+ else
+ ksft_test_result(!seen,
+ "T2 host-root, no opt-in: server does NOT receive FUSE_SYNCFS\n");
+
+ /*
+ * T3: server opts in but opened /dev/fuse without CAP_SYS_ADMIN while
+ * still in the initial user namespace -> kernel must withhold
+ * FUSE_SYNCFS. This is the case that distinguishes gating on the
+ * server's privilege from gating on the mount's user namespace.
+ */
+ ret = do_mount_and_syncfs(mnt, 1, 1, &seen);
+ if (ret < 0)
+ ksft_test_result_skip("T3: could not mount fuse unprivileged\n");
+ else
+ ksft_test_result(!seen,
+ "T3 init_userns, opener lacks CAP_SYS_ADMIN: FUSE_SYNCFS withheld\n");
+
+ rmdir(mnt);
+ ksft_finished();
+}
diff --git a/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c
new file mode 100644
index 000000000..d6d5de8da
--- /dev/null
+++ b/tools/testing/selftests/filesystems/fuse/write_extend_eof_test.c
@@ -0,0 +1,475 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Regression test for the fuse write-extend partial-EOF-page zeroing bug.
+ *
+ * A buffered write that extends i_size past a non-page-aligned EOF must zero
+ * the tail of the old last page. If an application has mmap'd that page and
+ * stored into the post-EOF region (undefined until the file grows), the
+ * now-in-bounds tail must read back as zero, not as the stale stored bytes.
+ *
+ * The bug is exposed on a non-writeback_cache server that keeps the page cache
+ * across the write (FOPEN_KEEP_CACHE without FOPEN_DIRECT_IO). This test is a
+ * raw /dev/fuse server in that mode; the backing data is always zero in the
+ * hole, so any non-zero byte a read sees is stale page-cache data.
+ *
+ * Requires root to mount fuse.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/falloc.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/uio.h>
+#include <linux/fuse.h>
+
+#include "../../kselftest_harness.h"
+
+#define FUSE_ROOT_ID 1
+#define FILE_INO 2 /* "file", the file being extended */
+#define SRC_INO 3 /* "src", copy_file_range() source */
+#define MAX_WRITE (128 * 1024)
+#define BACKING_SIZE (4 * 1024 * 1024)
+#define POLLUTE 0xee
+
+/* Called directly: the libc wrapper needs off64_t and a recent enough glibc. */
+static ssize_t sys_copy_file_range(int fd_in, int64_t *off_in, int fd_out,
+ int64_t *off_out, size_t len,
+ unsigned int flags)
+{
+ return syscall(__NR_copy_file_range, fd_in, off_in, fd_out, off_out,
+ len, flags);
+}
+
+/* Per-file server state. */
+struct backing_file {
+ unsigned char data[BACKING_SIZE]; /* authoritative bytes */
+ uint64_t size;
+};
+
+/* Server-side state, shared with the responder thread. */
+struct server {
+ int fd;
+ unsigned int copy_ops; /* FUSE_COPY_FILE_RANGE* seen */
+ struct backing_file file[2]; /* FILE_INO, SRC_INO */
+};
+
+static struct backing_file *lookup_file(struct server *s, uint64_t nodeid)
+{
+ return &s->file[nodeid == SRC_INO];
+}
+
+static void reply(int fd, uint64_t unique, int error, void *data, size_t len)
+{
+ struct fuse_out_header oh = {
+ .len = sizeof(oh) + (data ? len : 0),
+ .error = error,
+ .unique = unique,
+ };
+ struct iovec iov[2] = { { &oh, sizeof(oh) }, { data, len } };
+
+ /* Errors here are teardown races (device closed on unmount); ignore. */
+ if (writev(fd, iov, data ? 2 : 1) < 0)
+ return;
+}
+
+static void fill_attr(struct fuse_attr *a, uint64_t ino, uint32_t mode,
+ uint64_t size)
+{
+ memset(a, 0, sizeof(*a));
+ a->ino = ino;
+ a->mode = mode;
+ a->nlink = 1;
+ a->size = size;
+ a->blksize = sysconf(_SC_PAGESIZE);
+}
+
+static void *server_thread(void *arg)
+{
+ struct server *s = arg;
+ static char buf[MAX_WRITE + 4096];
+
+ for (;;) {
+ ssize_t n = read(s->fd, buf, sizeof(buf));
+ struct fuse_in_header *ih = (void *)buf;
+
+ if (n < 0) {
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+ return NULL; /* device closed on unmount */
+ }
+ if (n < (ssize_t)sizeof(*ih))
+ continue;
+
+ switch (ih->opcode) {
+ case FUSE_INIT: {
+ struct fuse_init_in *in = (void *)(ih + 1);
+ struct fuse_init_out out = {0};
+
+ /* No FUSE_WRITEBACK_CACHE: the exposed configuration. */
+ out.major = FUSE_KERNEL_VERSION;
+ out.minor = FUSE_KERNEL_MINOR_VERSION;
+ out.max_readahead = in->max_readahead;
+ out.max_write = MAX_WRITE;
+ out.max_background = 16;
+ out.congestion_threshold = 12;
+ out.flags = FUSE_MAX_PAGES;
+ out.max_pages = MAX_WRITE / sysconf(_SC_PAGESIZE);
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_GETATTR: {
+ struct fuse_attr_out out = {0};
+ int root = ih->nodeid == FUSE_ROOT_ID;
+
+ out.attr_valid = 3600;
+ fill_attr(&out.attr, ih->nodeid,
+ root ? (S_IFDIR | 0755) : (S_IFREG | 0644),
+ root ? 0 : lookup_file(s, ih->nodeid)->size);
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_LOOKUP: {
+ const char *name = (const char *)(ih + 1);
+ struct fuse_entry_out out = {0};
+ uint64_t nodeid;
+
+ /* Every name exists; "src" is the second file. */
+ nodeid = strcmp(name, "src") ? FILE_INO : SRC_INO;
+ out.nodeid = nodeid;
+ out.attr_valid = 3600;
+ out.entry_valid = 3600;
+ fill_attr(&out.attr, nodeid, S_IFREG | 0644,
+ lookup_file(s, nodeid)->size);
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_OPEN:
+ case FUSE_OPENDIR: {
+ struct fuse_open_out out = {0};
+
+ /* Keep the cache across the write, but not direct I/O. */
+ out.open_flags = FOPEN_KEEP_CACHE;
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_READ: {
+ struct fuse_read_in *in = (void *)(ih + 1);
+ struct backing_file *f = lookup_file(s, ih->nodeid);
+ uint64_t off = in->offset;
+ uint32_t size = in->size;
+
+ if (off >= BACKING_SIZE)
+ size = 0;
+ else if (off + size > BACKING_SIZE)
+ size = BACKING_SIZE - off;
+ reply(s->fd, ih->unique, 0, f->data + off, size);
+ break;
+ }
+ case FUSE_WRITE: {
+ struct fuse_write_in *in = (void *)(ih + 1);
+ struct backing_file *f = lookup_file(s, ih->nodeid);
+ struct fuse_write_out out = {0};
+ uint64_t off = in->offset;
+ uint32_t size = in->size;
+
+ if (off < BACKING_SIZE) {
+ uint32_t c = size;
+
+ if (off + c > BACKING_SIZE)
+ c = BACKING_SIZE - off;
+ memcpy(f->data + off, in + 1, c);
+ if (off + c > f->size)
+ f->size = off + c;
+ }
+ out.size = size;
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_SETATTR: {
+ struct fuse_setattr_in *in = (void *)(ih + 1);
+ struct backing_file *f = lookup_file(s, ih->nodeid);
+ struct fuse_attr_out out = {0};
+
+ if ((in->valid & FATTR_SIZE) && in->size <= BACKING_SIZE) {
+ if (in->size > f->size)
+ memset(f->data + f->size, 0,
+ in->size - f->size);
+ f->size = in->size;
+ }
+ out.attr_valid = 3600;
+ fill_attr(&out.attr, ih->nodeid, S_IFREG | 0644, f->size);
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ break;
+ }
+ case FUSE_FALLOCATE: {
+ struct fuse_fallocate_in *in = (void *)(ih + 1);
+ struct backing_file *f = lookup_file(s, ih->nodeid);
+ uint64_t end = in->offset + in->length;
+
+ /* Only plain (size-extending) fallocate is used here. */
+ if (!(in->mode & FALLOC_FL_KEEP_SIZE) &&
+ end <= BACKING_SIZE && end > f->size) {
+ memset(f->data + f->size, 0, end - f->size);
+ f->size = end;
+ }
+ reply(s->fd, ih->unique, 0, NULL, 0);
+ break;
+ }
+ case FUSE_COPY_FILE_RANGE:
+ case FUSE_COPY_FILE_RANGE_64: {
+ struct fuse_copy_file_range_in *in = (void *)(ih + 1);
+ struct backing_file *src = lookup_file(s, ih->nodeid);
+ struct backing_file *dst;
+ struct fuse_copy_file_range_out out64 = {0};
+ struct fuse_write_out out = {0};
+ uint64_t off_in = in->off_in;
+ uint64_t off_out = in->off_out;
+ uint64_t len = in->len;
+
+ dst = lookup_file(s, in->nodeid_out);
+ s->copy_ops++;
+ if (off_in >= BACKING_SIZE || off_out >= BACKING_SIZE) {
+ len = 0;
+ } else {
+ if (off_in + len > BACKING_SIZE)
+ len = BACKING_SIZE - off_in;
+ if (off_out + len > BACKING_SIZE)
+ len = BACKING_SIZE - off_out;
+ /* The hole left behind stays zero. */
+ memmove(dst->data + off_out, src->data + off_in,
+ len);
+ if (off_out + len > dst->size)
+ dst->size = off_out + len;
+ }
+ if (ih->opcode == FUSE_COPY_FILE_RANGE) {
+ out.size = len;
+ reply(s->fd, ih->unique, 0, &out, sizeof(out));
+ } else {
+ out64.bytes_copied = len;
+ reply(s->fd, ih->unique, 0, &out64,
+ sizeof(out64));
+ }
+ break;
+ }
+ case FUSE_FLUSH:
+ case FUSE_RELEASE:
+ case FUSE_RELEASEDIR:
+ case FUSE_FSYNC:
+ case FUSE_ACCESS:
+ reply(s->fd, ih->unique, 0, NULL, 0);
+ break;
+ case FUSE_FORGET:
+ break;
+ default:
+ reply(s->fd, ih->unique, -EOPNOTSUPP, NULL, 0);
+ break;
+ }
+ }
+}
+
+FIXTURE(fuse)
+{
+ struct server *srv;
+ pthread_t thread;
+ char dir[64];
+ long page; /* runtime page size */
+ off_t eof; /* mid-page EOF, page-relative */
+ int fd; /* open test file */
+ char *map; /* mmap of the EOF page */
+ int mounted;
+};
+
+FIXTURE_SETUP(fuse)
+{
+ char opts[128];
+ pthread_t t;
+
+ if (geteuid() != 0)
+ SKIP(return, "need root to mount fuse");
+
+ self->page = sysconf(_SC_PAGESIZE);
+ self->fd = -1;
+ self->map = MAP_FAILED;
+
+ self->srv = mmap(NULL, sizeof(*self->srv), PROT_READ | PROT_WRITE,
+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+ ASSERT_NE(MAP_FAILED, self->srv);
+
+ self->srv->fd = open("/dev/fuse", O_RDWR);
+ ASSERT_GE(self->srv->fd, 0);
+
+ strcpy(self->dir, "/tmp/fuse_weof_XXXXXX");
+ ASSERT_NE(NULL, mkdtemp(self->dir));
+
+ snprintf(opts, sizeof(opts),
+ "fd=%d,rootmode=40000,user_id=0,group_id=0",
+ self->srv->fd);
+ ASSERT_EQ(0, mount("fuse", self->dir, "fuse", 0, opts));
+ self->mounted = 1;
+
+ ASSERT_EQ(0, pthread_create(&t, NULL, server_thread, self->srv));
+ self->thread = t;
+}
+
+FIXTURE_TEARDOWN(fuse)
+{
+ if (self->map != MAP_FAILED)
+ munmap(self->map, self->page);
+ if (self->fd >= 0)
+ close(self->fd);
+ if (self->mounted)
+ umount2(self->dir, MNT_DETACH);
+ if (self->srv && self->srv != MAP_FAILED) {
+ if (self->srv->fd > 0)
+ close(self->srv->fd);
+ munmap(self->srv, sizeof(*self->srv));
+ }
+ if (self->dir[0])
+ rmdir(self->dir);
+}
+
+/*
+ * Create the test file with a mid-page EOF and mmap-store POLLUTE into its
+ * post-EOF tail (a legal store, undefined until the file grows). Leaves the
+ * file open and the EOF page mapped in the fixture for the caller to extend.
+ */
+static void pollute_eof_tail(struct __test_metadata *_metadata,
+ FIXTURE_DATA(fuse) * self)
+{
+ off_t eof = 2 * self->page + self->page / 4;
+ char path[128];
+ char *buf;
+
+ snprintf(path, sizeof(path), "%s/file", self->dir);
+ self->fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);
+ ASSERT_GE(self->fd, 0);
+ self->eof = eof;
+
+ buf = malloc(eof);
+ ASSERT_NE(NULL, buf);
+ memset(buf, 'A', eof);
+ ASSERT_EQ(eof, pwrite(self->fd, buf, eof, 0));
+ free(buf);
+
+ self->map = mmap(NULL, self->page, PROT_READ | PROT_WRITE, MAP_SHARED,
+ self->fd, eof & ~(self->page - 1));
+ ASSERT_NE(MAP_FAILED, self->map);
+ memset(self->map + (eof & (self->page - 1)), POLLUTE,
+ self->page - (eof & (self->page - 1)));
+}
+
+/* Assert the old post-EOF tail [eof, end of its page) now reads back as zero. */
+static void assert_tail_zeroed(struct __test_metadata *_metadata,
+ FIXTURE_DATA(fuse) * self)
+{
+ off_t base = self->eof & ~(self->page - 1);
+ char *tail = malloc(self->page);
+ int i;
+
+ ASSERT_NE(NULL, tail);
+ ASSERT_EQ(self->page, pread(self->fd, tail, self->page, base));
+ for (i = self->eof & (self->page - 1); i < self->page; i++)
+ ASSERT_EQ(0, tail[i]);
+ free(tail);
+}
+
+/* Basic: pollute the post-EOF tail, extend past it by a later write. */
+TEST_F(fuse, write_extend)
+{
+ pollute_eof_tail(_metadata, self);
+ ASSERT_EQ(4, pwrite(self->fd, "data", 4, 5 * self->page + self->page / 3));
+ assert_tail_zeroed(_metadata, self);
+}
+
+/* Extend via ftruncate() rather than a write. */
+TEST_F(fuse, ftruncate_extend)
+{
+ pollute_eof_tail(_metadata, self);
+ ASSERT_EQ(0, ftruncate(self->fd, 8 * self->page));
+ assert_tail_zeroed(_metadata, self);
+}
+
+/* Extend via fallocate() starting at the old EOF. */
+TEST_F(fuse, fallocate_extend)
+{
+ pollute_eof_tail(_metadata, self);
+ ASSERT_EQ(0, fallocate(self->fd, 0, self->eof, 4 * self->page));
+ assert_tail_zeroed(_metadata, self);
+}
+
+/*
+ * Extend via copy_file_range() landing on a page strictly past the old EOF
+ * page, so neither the copied range nor the flush of either file touches the
+ * old EOF folio. The source has to be a separate file: copying within one
+ * file would flush it from the source offset on, and writeback zeroes the
+ * post-EOF tail on the way out, hiding the bug.
+ */
+TEST_F(fuse, copy_file_range_extend)
+{
+ int64_t off_in = 0;
+ int64_t off_out;
+ char path[128];
+ char *buf;
+ ssize_t ret;
+ int src;
+
+ pollute_eof_tail(_metadata, self);
+ off_out = 5 * self->page;
+
+ snprintf(path, sizeof(path), "%s/src", self->dir);
+ src = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);
+ ASSERT_GE(src, 0);
+
+ buf = malloc(self->page);
+ ASSERT_NE(NULL, buf);
+ memset(buf, 'C', self->page);
+ ASSERT_EQ(self->page, pwrite(src, buf, self->page, 0));
+ free(buf);
+
+ ret = sys_copy_file_range(src, &off_in, self->fd, &off_out,
+ self->page, 0);
+ ASSERT_EQ(self->page, ret);
+ close(src);
+
+ /* A splice fallback would extend via the write path instead. */
+ ASSERT_NE(0u, self->srv->copy_ops);
+
+ assert_tail_zeroed(_metadata, self);
+}
+
+/* A write landing inside the old EOF page must not clobber its own data. */
+TEST_F(fuse, extend_into_eof_page_preserves_data)
+{
+ off_t base, wr;
+ char *buf, *rd;
+ int i;
+
+ pollute_eof_tail(_metadata, self);
+ base = self->eof & ~(self->page - 1);
+ wr = base + 3 * self->page / 4; /* starts in the EOF page */
+
+ buf = malloc(2 * self->page);
+ ASSERT_NE(NULL, buf);
+ memset(buf, 'B', 2 * self->page);
+ ASSERT_EQ(2 * self->page, pwrite(self->fd, buf, 2 * self->page, wr));
+ free(buf);
+
+ rd = malloc(self->page);
+ ASSERT_NE(NULL, rd);
+ ASSERT_EQ(self->page, pread(self->fd, rd, self->page, base));
+ /* [eof, wr) is hole -> zero; [wr, page) is written data -> 'B'. */
+ for (i = self->eof & (self->page - 1); i < wr - base; i++)
+ ASSERT_EQ(0, rd[i]);
+ for (i = wr - base; i < self->page; i++)
+ ASSERT_EQ('B', rd[i]);
+ free(rd);
+}
+
+TEST_HARNESS_MAIN