Skip to contentSkip to conversation

fuse: containerize ext4 for safer operation

PATCH Superseded Darrick J. Wong 13 participants 333 messages Oct 29, 2025 – Feb 6 Page 1 of 4

Subsystems (8)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

PATCH v6 1/1 fuse: containerize ext4 for safer operation

Look ma, no more RFC tag!

This is the sixth public draft of a prototype to connect the Linux fuse driver to fs-iomap for regular file IO operations to and from files whose contents persist to locally attached storage devices. With this release, I show that it's possible to build a fuse server for a real filesystem (ext4) that runs entirely in userspace yet maintains most of its performance. Furthermore, I also show that the userspace program runs with minimal privilege, which means that we no longer need to have filesystem metadata parsing be a privileged (== risky) operation.

Why would you want to do that? Most filesystem drivers are seriously vulnerable to metadata parsing attacks, as syzbot has shown repeatedly over almost a decade of its existence. Faulty code can lead to total kernel compromise, and I think there's a very strong incentive to move all that parsing out to userspace where we can containerize the fuse server process.

willy's folios conversion project (and to a certain degree RH's new mount API) have also demonstrated that treewide changes to the core mm/pagecache/fs code are very very difficult to pull off and take years because you have to understand every filesystem's bespoke use of that core code. Eeeugh.

The fuse command plumbing is very simple -- the ->iomap_begin, ->iomap_end, and iomap ->ioend calls within iomap are turned into upcalls to the fuse server via a trio of new fuse commands. Pagecache writeback is now a directio write. The fuse server is now able to upsert mappings into the kernel for cached access (== zero upcalls for rereads and pure overwrites!) and the iomap cache revalidation code works.

At this stage I still get about 95% of the kernel ext4 driver's streaming directio performance on streaming IO, and 110% of its streaming buffered IO performance. Random buffered IO is about 85% as fast as the kernel. Random direct IO is about 80% as fast as the kernel; see the cover letter for the fuse2fs iomap changes for more details. Unwritten extent conversions on random direct writes are especially painful for fuse+iomap (~90% more overhead) due to upcall overhead. And that's with (now dynamic) debugging turned on!

These items have been addressed since the fifth RFC:

1. After seven months of work, I can get seven of my 15 or so testing profiles to pass fstests, most days. There are a few flakey tests like generic/347 that (I think) sometimes fail because there's no journalling in jbd2. That's better than kernel ext4, which never gets all the way to passing here.

2. Swap files, filesystem freeze and thaw, and shutdowns now work.

3. fuse4fs can now use PSI information as a clue that it's time for it to flush its caches and evict them.

There are some warts remaining:

a. I would like to start a discussion about how the design review of
this code should be structured, and how might I go about creating new userspace filesystem servers -- lightweight new ones based off the existing userspace tools? Or by merging lklfuse?

b. ext4 doesn't support out of place writes so I don't know if that
actually works correctly.

c. fuse2fs doesn't support the ext4 journal. Urk.

d. There's a VERY large quantity of fuse2fs improvements that need to be
applied before we get to the fuse-iomap parts. I'm not sending these (or the fstests changes) to keep the size of the patchbomb at "unreasonably large". :P As a result, the fstests and e2fsprogs postings are very targeted.

I'll work on these in November, but now I'm much more serious about getting this merged for 6.19 now that the LTS is past and the coast is clear.

--Darrick

#1 lore raw

PATCH v6 1/8 fuse: general bug fixes

Hi all,

Here's a collection of fixes that I *think* are bugs in fuse, along with some scattered improvements.

If you're going to start using this code, I strongly recommend pulling from my git trees, which are linked below.

This has been running on the djcloud for months with no problems. Enjoy! Comments and questions are, as always, welcome.

--D

kernel git tree:
https://git.kernel.org/cgit/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-fixes
---
Commits in this patchset:
* fuse: flush pending fuse events before aborting the connection
* fuse: signal that a fuse inode should exhibit local fs behaviors
* fuse: implement file attributes mask for statx
* fuse: update file mode when updating acls
* fuse: propagate default and file acls on creation

---
 fs/fuse/fuse_i.h |   62 ++++++++++++++++++++++++++++++-
 fs/fuse/acl.c    |  108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/dev.c    |   35 ++++++++++++++++++
 fs/fuse/dir.c    |   96 +++++++++++++++++++++++++++++++++++++-----------
 fs/fuse/inode.c  |   15 +++++++-
 5 files changed, 289 insertions(+), 27 deletions(-)
#2 lore raw

PATCH 1/5 fuse: flush pending fuse events before aborting the connection

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +35 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
 	}
 }
 
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+	spin_lock(&fc->lock);
+	if (!fc->connected) {
+		spin_unlock(&fc->lock);
+		return;
+	}
+
+	/* Push all the background requests to the queue. */
+	spin_lock(&fc->bg_lock);
+	fc->blocked = 0;
+	fc->max_background = UINT_MAX;
+	flush_bg_queue(fc);
+	spin_unlock(&fc->bg_lock);
+	spin_unlock(&fc->lock);
+
+	/*
+	 * Wait for all pending fuse requests to complete or abort.  The fuse
+	 * server could take a significant amount of time to complete a
+	 * request, so run this in a loop with a short timeout so that we don't
+	 * trip the soft lockup detector.
+	 */
+	smp_mb();
+	while (wait_event_timeout(fc->blocked_waitq,
+			!fc->connected || atomic_read(&fc->num_waiting) == 0,
+			HZ) == 0) {
+		/* empty */
+	}
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +10 -1
index d1babf56f25470..d048d634ef46f5 100644
@@ -2094,8 +2094,17 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
 	struct fuse_conn *fc = fm->fc;
 
-	if (fc->destroy)
+	if (fc->destroy) {
+		/*
+		 * Flush all pending requests (most of which will be
+		 * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
+		 * server must close the filesystem before replying to the
+		 * destroy message, because unmount is about to release its
+		 * O_EXCL hold on the block device.
+		 */
+		fuse_flush_requests_and_wait(fc);
 		fuse_send_destroy(fm);
+	}
 
 	fuse_abort_conn(fc);
 	fuse_wait_aborted(fc);
#3 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 88 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +1 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2440

Quoted 10 lines
fs/fuse/dev.c +7 -0
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);

Do we need to grab the fc lock? fc->connected is protected under the bg_lock, afaict from fuse_abort_conn().

Quoted 15 lines
fs/fuse/dev.c +15 -0
+       if (!fc->connected) {
+               spin_unlock(&fc->lock);
+               return;
+       }
+
+       /* Push all the background requests to the queue. */
+       spin_lock(&fc->bg_lock);
+       fc->blocked = 0;
+       fc->max_background = UINT_MAX;
+       flush_bg_queue(fc);
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+
+       /*
+        * Wait for all pending fuse requests to complete or abort.  The fuse

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 10 lines
fs/fuse/dev.c +10 -0
+        * server could take a significant amount of time to complete a
+        * request, so run this in a loop with a short timeout so that we don't
+        * trip the soft lockup detector.
+        */
+       smp_mb();
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort? We are already guaranteeing that the background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

Thanks,
Joanne

Quoted 29 lines
fs/fuse/dev.c +2 -0
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +10 -1
index d1babf56f25470..d048d634ef46f5 100644
@@ -2094,8 +2094,17 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;
 
-       if (fc->destroy)
+       if (fc->destroy) {
+               /*
+                * Flush all pending requests (most of which will be
+                * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
+                * server must close the filesystem before replying to the
+                * destroy message, because unmount is about to release its
+                * O_EXCL hold on the block device.
+                */
+               fuse_flush_requests_and_wait(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#4 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 92 lines · Joanne Koong
Quoted 91 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +1 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
Quoted 10 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2440

Quoted 7 lines
fs/fuse/dev.c +7 -0
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);

Do we need to grab the fc lock? fc->connected is protected under the bg_lock, afaict from fuse_abort_conn().

Oh, heh. Yeah, it does indeed take both fc->lock and fc->bg_lock. Will fix that, thanks. :)

FWIW I don't think it's a big deal if we see a stale connected==1 value because the events will all get cancelled and the wait loop won't run anyway, but I agree with being consistent about lock ordering. :)

Quoted 20 lines
Quoted 20 lines
fs/fuse/dev.c +20 -0
+       if (!fc->connected) {
+               spin_unlock(&fc->lock);
+               return;
+       }
+
+       /* Push all the background requests to the queue. */
+       spin_lock(&fc->bg_lock);
+       fc->blocked = 0;
+       fc->max_background = UINT_MAX;
+       flush_bg_queue(fc);
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+
+       /*
+        * Wait for all pending fuse requests to complete or abort.  The fuse
+        * server could take a significant amount of time to complete a
+        * request, so run this in a loop with a short timeout so that we don't
+        * trip the soft lockup detector.
+        */
+       smp_mb();
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

--D

Quoted 32 lines

Thanks,
Joanne

Quoted 29 lines
fs/fuse/dev.c +2 -0
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +10 -1
index d1babf56f25470..d048d634ef46f5 100644
@@ -2094,8 +2094,17 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;
 
-       if (fc->destroy)
+       if (fc->destroy) {
+               /*
+                * Flush all pending requests (most of which will be
+                * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
+                * server must close the filesystem before replying to the
+                * destroy message, because unmount is about to release its
+                * O_EXCL hold on the block device.
+                */
+               fuse_flush_requests_and_wait(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#5 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 158 lines · Darrick J. Wong
Quoted 92 lines · Joanne Koong
Quoted 91 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +1 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
Quoted 10 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2440

Quoted 7 lines
fs/fuse/dev.c +7 -0
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);

Do we need to grab the fc lock? fc->connected is protected under the bg_lock, afaict from fuse_abort_conn().

Oh, heh. Yeah, it does indeed take both fc->lock and fc->bg_lock. Will fix that, thanks. :)

FWIW I don't think it's a big deal if we see a stale connected==1 value because the events will all get cancelled and the wait loop won't run anyway, but I agree with being consistent about lock ordering. :)

Quoted 20 lines
Quoted 20 lines
fs/fuse/dev.c +20 -0
+       if (!fc->connected) {
+               spin_unlock(&fc->lock);
+               return;
+       }
+
+       /* Push all the background requests to the queue. */
+       spin_lock(&fc->bg_lock);
+       fc->blocked = 0;
+       fc->max_background = UINT_MAX;
+       flush_bg_queue(fc);
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+
+       /*
+        * Wait for all pending fuse requests to complete or abort.  The fuse
+        * server could take a significant amount of time to complete a
+        * request, so run this in a loop with a short timeout so that we don't
+        * trip the soft lockup detector.
+        */
+       smp_mb();
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic. imo the only responsibility of the kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

Quoted 10 lines
Quoted 6 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

With the "while (wait_event_timeout(fc->blocked_waitq, !fc->connected || atomic_read(&fc->num_waiting) == 0...)" logic, I think this also now means if a server is tripped up somewhere (eg if a remote network connection is lost or it runs into a deadlock when servicing a request) where it's unable to fulfill any one of its previous requests, unmounting would hang.

Thanks,
Joanne

Quoted 35 lines

--D

Quoted 32 lines

Thanks,
Joanne

Quoted 29 lines
fs/fuse/dev.c +2 -0
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +10 -1
index d1babf56f25470..d048d634ef46f5 100644
@@ -2094,8 +2094,17 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;
 
-       if (fc->destroy)
+       if (fc->destroy) {
+               /*
+                * Flush all pending requests (most of which will be
+                * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
+                * server must close the filesystem before replying to the
+                * destroy message, because unmount is about to release its
+                * O_EXCL hold on the block device.
+                */
+               fuse_flush_requests_and_wait(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#6 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 167 lines · Joanne Koong
Quoted 158 lines · Darrick J. Wong
Quoted 92 lines · Joanne Koong
Quoted 91 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +1 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
Quoted 10 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2440

Quoted 7 lines
fs/fuse/dev.c +7 -0
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);

Do we need to grab the fc lock? fc->connected is protected under the bg_lock, afaict from fuse_abort_conn().

Oh, heh. Yeah, it does indeed take both fc->lock and fc->bg_lock. Will fix that, thanks. :)

FWIW I don't think it's a big deal if we see a stale connected==1 value because the events will all get cancelled and the wait loop won't run anyway, but I agree with being consistent about lock ordering. :)

Quoted 20 lines
Quoted 20 lines
fs/fuse/dev.c +20 -0
+       if (!fc->connected) {
+               spin_unlock(&fc->lock);
+               return;
+       }
+
+       /* Push all the background requests to the queue. */
+       spin_lock(&fc->bg_lock);
+       fc->blocked = 0;
+       fc->max_background = UINT_MAX;
+       flush_bg_queue(fc);
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+
+       /*
+        * Wait for all pending fuse requests to complete or abort.  The fuse
+        * server could take a significant amount of time to complete a
+        * request, so run this in a loop with a short timeout so that we don't
+        * trip the soft lockup detector.
+        */
+       smp_mb();
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 6 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic. imo the only responsibility of the kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

Hmm, good idea, I guess we can add that in libfuse, maybe with some kind of timeout.

There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()

I.e. how can it release the superblock (which triggers FUSE_DESTROY)

Thanks,
Bernd

#7 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 193 lines · Bernd Schubert
Quoted 167 lines · Joanne Koong
Quoted 158 lines · Darrick J. Wong
Quoted 92 lines · Joanne Koong
Quoted 91 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

generic/488 fails with fuse2fs in the following fashion:

generic/488 _check_generic_filesystem: filesystem on /dev/sdf is inconsistent
(see /var/tmp/fstests/generic/488.full for details)

This test opens a large number of files, unlinks them (which really just renames them to fuse hidden files), closes the program, unmounts the filesystem, and runs fsck to check that there aren't any inconsistencies in the filesystem.

Unfortunately, the 488.full file shows that there are a lot of hidden files left over in the filesystem, with incorrect link counts. Tracing fuse_request_* shows that there are a large number of FUSE_RELEASE commands that are queued up on behalf of the unlinked files at the time that fuse_conn_destroy calls fuse_abort_conn. Had the connection not aborted, the fuse server would have responded to the RELEASE commands by removing the hidden files; instead they stick around.

For upper-level fuse servers that don't use fuseblk mode this isn't a problem because libfuse responds to the connection going down by pruning its inode cache and calling the fuse server's ->release for any open files before calling the server's ->destroy function.

For fuseblk servers this is a problem, however, because the kernel sends FUSE_DESTROY to the fuse server, and the fuse server has to close the block device before returning. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

Create a function to push all the background requests to the queue and then wait for the number of pending events to hit zero, and call this before sending FUSE_DESTROY. That way, all the pending events are processed by the fuse server and we don't end up with a corrupt filesystem.

Note that we use a wait_event_timeout() loop to cause the process to schedule at least once per second to avoid a "task blocked" warning:

INFO: task umount:1279 blocked for more than 20 seconds.
      Not tainted 6.17.0-rc7-xfsx #rc7

"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this messag.
task:umount state:D stack:11984 pid:1279 tgid:1279 ppid:10690

Earlier in the threads about this patch there was a (self-inflicted) dispute as to whether it was necessary to call touch_softlockup_watchdog in the loop body. Because the process goes to sleep, it's not necessary to touch the softlockup watchdog because we're not preventing another process from being scheduled on a CPU.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c  |   11 ++++++++++-
 3 files changed, 50 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index c2f2a48156d6c5..aaa8574fd72775 100644
@@ -1274,6 +1274,11 @@ void fuse_request_end(struct fuse_req *req);
 void fuse_abort_conn(struct fuse_conn *fc);
 void fuse_wait_aborted(struct fuse_conn *fc);
 
+/**
+ * Flush all pending requests and wait for them.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +1 -0
index 132f38619d7072..ecc0a5304c59d1 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>
 
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,40 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
Quoted 10 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2440

Quoted 7 lines
fs/fuse/dev.c +7 -0
+/*
+ * Flush all pending requests and wait for them.  Only call this function when
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests_and_wait(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);

Do we need to grab the fc lock? fc->connected is protected under the bg_lock, afaict from fuse_abort_conn().

Oh, heh. Yeah, it does indeed take both fc->lock and fc->bg_lock. Will fix that, thanks. :)

FWIW I don't think it's a big deal if we see a stale connected==1 value because the events will all get cancelled and the wait loop won't run anyway, but I agree with being consistent about lock ordering. :)

Quoted 20 lines
Quoted 20 lines
fs/fuse/dev.c +20 -0
+       if (!fc->connected) {
+               spin_unlock(&fc->lock);
+               return;
+       }
+
+       /* Push all the background requests to the queue. */
+       spin_lock(&fc->bg_lock);
+       fc->blocked = 0;
+       fc->max_background = UINT_MAX;
+       flush_bg_queue(fc);
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+
+       /*
+        * Wait for all pending fuse requests to complete or abort.  The fuse
+        * server could take a significant amount of time to complete a
+        * request, so run this in a loop with a short timeout so that we don't
+        * trip the soft lockup detector.
+        */
+       smp_mb();
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 6 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic. imo the only responsibility of the kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

Hmm, good idea, I guess we can add that in libfuse, maybe with some kind of timeout.

There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()
Quoted 1 line

I.e. how can it release the superblock (which triggers FUSE_DESTROY)

The short answer is that fuse_file_put doesn't wait for the backgrounded release request to complete and returns; and that FUSE_DESTROY is sent synchronously and with args->force = true so it jumps the queue.

(See my longer reply to Joanne for more details)

--D

Quoted 4 lines

Thanks,
Bernd

#8 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

In reply to Joanne Koong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Is the above assumption correct?

I don't see any fuse servers that actually *do* this, though. I perceive that there are a lot of fuse servers out there that aren't packaged in Debian, though, so is this actually a common thing for proprietary fuse servers which I wouldn't know about?

Downthread, Bernd suggested doing this in libfuse instead of making the fuse servers do it. He asks:

"There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

"->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()"

The answer to this is: fuse_file_release is always asynchronous now, so the FUSE_RELEASE is queued to the background and the kernel moves on with its life.

It's likely much more effective to put the reordering barrier in the library (ignoring all the vendored libfuse out there) assuming that the above assumption holds. I think it wouldn't be hard to have _do_open (fuse_lowlevel.c) increment a counter in fuse_session, decrement it in _do_release, and then _do_destroy would wait for it to hit zero.

For a single-threaded fuse server I think this might not even be an issue because the events are (AFAICT) processed in order. However, you'd have to be careful about how you did that for a multithreaded fuse server. You wouldn't want to spin in _do_destroy because that takes out a thread that could be doing work. Is there a way to park a request?

Note that both of these approaches come with the risk that the kernel could decide to time out and abort the FUSE_DESTROY while the server is still waiting for the counter to hit zero.

For a fuseblk filesystem this abort is very dangerous because the kernel releases its O_EXCL hold on the block device in kill_block_super before the fuse server has a chance to finish up and close the block device. The fuseblk server itself could not have opened the block device O_EXCL so that means there's a period where another process (or even another fuseblk mount) could open the bdev O_EXCL and both try to write to the block device.

(I actually have been wondering who uses the fuse request timeouts? In my testing even 30min wasn't sufficient to avoid aborts for some of the truncate/inactivation fstests.)

Aside: The reason why I abandoned making fuse2fs a fuseblk server is because I realized this exact trap -- the fuse server MUST have exclusive write access to the device at all times, or else it can race with other programs (e.g. tune2fs) and corrupt the filesystem. In fuseblk mode the kernel owns the exclusive access and but doesn't install that file in the server's fd table. At best the fuse server can pretend that it has exclusive write access, but the kernel can make that go away without telling the fuse server, which opens a world of hurt.

Quoted 4 lines

imo the only responsibility of the
kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

They do receive it because fuse_session_destroy calls ->destroy if no event has been received from the kernel after the fusedev shuts down.

Quoted 22 lines
Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 3 lines

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

It's not sufficient, because there might be other cached dirty metadata that needs to be flushed out to disk. A fuse server could respond to a FUSE_FLUSH by pushing out that inode's dirty metadata to disk but go no farther. Plumbing in FUSE_SYNCFS for iomap helps a lot in that regard because that's a signal that we need to push dirty ext4 bitmaps and group descriptors and whatnot out to storage; without it we end up doing all that at destroy time.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

Quoted 7 lines
Quoted 3 lines

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

I think it's worse than that -- fuse_send_destroy sets fuse_args::force and sends the request synchronously, which (afaict) means it jumps ahead of the backgrounded requests.

Quoted 6 lines

With the "while (wait_event_timeout(fc->blocked_waitq, !fc->connected || atomic_read(&fc->num_waiting) == 0...)" logic, I think this also now means if a server is tripped up somewhere (eg if a remote network connection is lost or it runs into a deadlock when servicing a request) where it's unable to fulfill any one of its previous requests, unmounting would hang.

Well yeah, I was only going to use this function for "local" filesystems like fuseblk and iomap servers. Definitely not for network fses!

(Though really, all local storage is network storage...)

--D

Quoted 39 lines

Thanks,
Joanne

Quoted 35 lines

--D

Quoted 32 lines

Thanks,
Joanne

Quoted 29 lines
fs/fuse/dev.c +2 -0
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +10 -1
index d1babf56f25470..d048d634ef46f5 100644
@@ -2094,8 +2094,17 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;
 
-       if (fc->destroy)
+       if (fc->destroy) {
+               /*
+                * Flush all pending requests (most of which will be
+                * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
+                * server must close the filesystem before replying to the
+                * destroy message, because unmount is about to release its
+                * O_EXCL hold on the block device.
+                */
+               fuse_flush_requests_and_wait(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#9 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Quoted 34 lines

Is the above assumption correct?

I don't see any fuse servers that actually *do* this, though. I perceive that there are a lot of fuse servers out there that aren't packaged in Debian, though, so is this actually a common thing for proprietary fuse servers which I wouldn't know about?

Downthread, Bernd suggested doing this in libfuse instead of making the fuse servers do it. He asks:

"There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

"->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()"

The answer to this is: fuse_file_release is always asynchronous now, so the FUSE_RELEASE is queued to the background and the kernel moves on with its life.

It's likely much more effective to put the reordering barrier in the library (ignoring all the vendored libfuse out there) assuming that the above assumption holds. I think it wouldn't be hard to have _do_open (fuse_lowlevel.c) increment a counter in fuse_session, decrement it in _do_release, and then _do_destroy would wait for it to hit zero.

Quoted 5 lines

For a single-threaded fuse server I think this might not even be an issue because the events are (AFAICT) processed in order. However, you'd have to be careful about how you did that for a multithreaded fuse server. You wouldn't want to spin in _do_destroy because that takes out a thread that could be doing work. Is there a way to park a request?

If the background requests are flushed before the destroy request, then this doesn't take out a thread because al the background requests will already have been or are being serviced.

Quoted 13 lines

Note that both of these approaches come with the risk that the kernel could decide to time out and abort the FUSE_DESTROY while the server is still waiting for the counter to hit zero.

For a fuseblk filesystem this abort is very dangerous because the kernel releases its O_EXCL hold on the block device in kill_block_super before the fuse server has a chance to finish up and close the block device. The fuseblk server itself could not have opened the block device O_EXCL so that means there's a period where another process (or even another fuseblk mount) could open the bdev O_EXCL and both try to write to the block device.

Quoted 3 lines

(I actually have been wondering who uses the fuse request timeouts? In my testing even 30min wasn't sufficient to avoid aborts for some of the truncate/inactivation fstests.)

Meta uses fuse request timeouts. We saw a few cases of deadlocks in some buggy fuse server implementations, so we now enforce default timeouts. The timeout is set to a pretty large number though. Our main use of it is to free/cleanup system resources if the server is deadlocked.

If it takes 30 minutes to do all the cleanup, then I think it's worse to have unmounting take that long, than to just do a quicker unmount and have lingering unlinked files on the server. As a user, if I were unmounting something and it took that long, I would probably just kill the whole thing anyways.

Quoted 62 lines

Aside: The reason why I abandoned making fuse2fs a fuseblk server is because I realized this exact trap -- the fuse server MUST have exclusive write access to the device at all times, or else it can race with other programs (e.g. tune2fs) and corrupt the filesystem. In fuseblk mode the kernel owns the exclusive access and but doesn't install that file in the server's fd table. At best the fuse server can pretend that it has exclusive write access, but the kernel can make that go away without telling the fuse server, which opens a world of hurt.

Quoted 4 lines

imo the only responsibility of the
kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

They do receive it because fuse_session_destroy calls ->destroy if no event has been received from the kernel after the fusedev shuts down.

Quoted 22 lines
Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 3 lines

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

It's not sufficient, because there might be other cached dirty metadata that needs to be flushed out to disk. A fuse server could respond to a FUSE_FLUSH by pushing out that inode's dirty metadata to disk but go no farther. Plumbing in FUSE_SYNCFS for iomap helps a lot in that regard because that's a signal that we need to push dirty ext4 bitmaps and group descriptors and whatnot out to storage; without it we end up doing all that at destroy time.

Quoted 10 lines
Quoted 9 lines
Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

Quoted 7 lines
Quoted 3 lines

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

I think it's worse than that -- fuse_send_destroy sets fuse_args::force and sends the request synchronously, which (afaict) means it jumps ahead of the backgrounded requests.

Hmm, where are you seeing that? afaict, args->force forces the request to be sent to userspace even if interrupted and it skips the fuse_block_alloc() check.

Thanks,
Joanne

#10 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

fs/fuse/dev.c static void end_polls(struct fuse_conn *fc) · line 2465

Quoted 5 lines
fs/fuse/dev.c +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 40 lines
Quoted 34 lines

Is the above assumption correct?

I don't see any fuse servers that actually *do* this, though. I perceive that there are a lot of fuse servers out there that aren't packaged in Debian, though, so is this actually a common thing for proprietary fuse servers which I wouldn't know about?

Downthread, Bernd suggested doing this in libfuse instead of making the fuse servers do it. He asks:

"There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

"->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()"

The answer to this is: fuse_file_release is always asynchronous now, so the FUSE_RELEASE is queued to the background and the kernel moves on with its life.

It's likely much more effective to put the reordering barrier in the library (ignoring all the vendored libfuse out there) assuming that the above assumption holds. I think it wouldn't be hard to have _do_open (fuse_lowlevel.c) increment a counter in fuse_session, decrement it in _do_release, and then _do_destroy would wait for it to hit zero.

Quoted 5 lines

For a single-threaded fuse server I think this might not even be an issue because the events are (AFAICT) processed in order. However, you'd have to be careful about how you did that for a multithreaded fuse server. You wouldn't want to spin in _do_destroy because that takes out a thread that could be doing work. Is there a way to park a request?

Quoted 3 lines

If the background requests are flushed before the destroy request, then this doesn't take out a thread because al the background requests will already have been or are being serviced.

<nod>

I'm still concerned about a few things with the libfuse approach though. The kernel is the initiator, so it knows the data dependencies between requests. Consequently, it's in the best position to know that if request R2 depends on R1, then it shouldn't issue R2 until it has received an acknowledgement for R1. The fuse server is the target, it shouldn't be second-guessing what the initiator wants.

The second concern is that if a request timeout is in effect, then all the time that libfuse spends waiting for other request to drain is charged to that request. IOWs, if the timeout is 60s and libfuse holds the FUSE_DESTROY for 40s, the fuse server only has 20s to reply to the request whereas the sysadmin might have assumed that the server would have a full 60s to flush the filesystem and exit.

If you're worried about no-timeout fuse servers hanging the unmount process, what about killing the fuse server? Or telling the kernel to abort the connection? Either should suffice to kill the wait_event loop.

The third thing is that the iomap patchset will change the unmount request sequence:

1. <some number of FUSE_RELEASEs>
2. FUSE_SYNCFS to tell the fuse server to write all its dirty data
3. FUSE_DESTROY to close the filesystem

If we put the ordering barrier in libfuse, then we'll have to modify libfuse to flush all of (1) before processing (2), and then wait for (2) to finish before processing (3). But libfuse doesn't know that a particular FUSE_SYNCFS will be succeeded by a FUSE_DESTROY. I could drop the SYNCFS and let DESTROY handle all the flushing. But again, the kernel already knows the ordering that it requires, so it should enforce that ordering directly.

(Sorry, I feel like I'm belaboring the point excessively, I'll stop)

The libfuse approach /does/ have the small advantage that it can start working on the FUSE_DESTROY as soon as the other workers quiesce because it doesn't have to wait for the kernel to see the last FUSE_RELEASE reply and generate the DESTROY request.

Quoted 16 lines
Quoted 12 lines

Note that both of these approaches come with the risk that the kernel could decide to time out and abort the FUSE_DESTROY while the server is still waiting for the counter to hit zero.

For a fuseblk filesystem this abort is very dangerous because the kernel releases its O_EXCL hold on the block device in kill_block_super before the fuse server has a chance to finish up and close the block device. The fuseblk server itself could not have opened the block device O_EXCL so that means there's a period where another process (or even another fuseblk mount) could open the bdev O_EXCL and both try to write to the block device.

Quoted 3 lines

(I actually have been wondering who uses the fuse request timeouts? In my testing even 30min wasn't sufficient to avoid aborts for some of the truncate/inactivation fstests.)

Quoted 5 lines

Meta uses fuse request timeouts. We saw a few cases of deadlocks in some buggy fuse server implementations, so we now enforce default timeouts. The timeout is set to a pretty large number though. Our main use of it is to free/cleanup system resources if the server is deadlocked.

If you can share, how long of a timeout? I've noticed that some clouds set their iscsi timeouts to 12h or more(!) and that's for a single SCSI command.

Quoted 2 lines

If it takes 30 minutes to do all the cleanup, then I think it's worse to have unmounting take that long, than to just do a quicker unmount

If you don't handle unlinked lists in a O(n) (or O(1) way) then unprivileged userspace programs can manipulate the filesystem so that it actually /can/ take hours to unmount. XFS, ext4, and now fuse4fs have learned that the hard way. ;)

Quoted 3 lines

and have lingering unlinked files on the server. As a user, if I were unmounting something and it took that long, I would probably just kill the whole thing anyways.

That very much depends on what you're going to do with that filesystem. If you're disposing of a container then, meh, fire away. Some people "use" FS_IOC_SHUTDOWN to "terminate" containers quickly.

Quoted 66 lines
Quoted 66 lines

Aside: The reason why I abandoned making fuse2fs a fuseblk server is because I realized this exact trap -- the fuse server MUST have exclusive write access to the device at all times, or else it can race with other programs (e.g. tune2fs) and corrupt the filesystem. In fuseblk mode the kernel owns the exclusive access and but doesn't install that file in the server's fd table. At best the fuse server can pretend that it has exclusive write access, but the kernel can make that go away without telling the fuse server, which opens a world of hurt.

Quoted 4 lines

imo the only responsibility of the
kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

They do receive it because fuse_session_destroy calls ->destroy if no event has been received from the kernel after the fusedev shuts down.

Quoted 22 lines
Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 3 lines

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

It's not sufficient, because there might be other cached dirty metadata that needs to be flushed out to disk. A fuse server could respond to a FUSE_FLUSH by pushing out that inode's dirty metadata to disk but go no farther. Plumbing in FUSE_SYNCFS for iomap helps a lot in that regard because that's a signal that we need to push dirty ext4 bitmaps and group descriptors and whatnot out to storage; without it we end up doing all that at destroy time.

Quoted 13 lines
Quoted 9 lines
Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

Quoted 7 lines
Quoted 3 lines

I think it's worse than that -- fuse_send_destroy sets fuse_args::force and sends the request synchronously, which (afaict) means it jumps ahead of the backgrounded requests.

Hmm, where are you seeing that? afaict, args->force forces the request to be sent to userspace even if interrupted and it skips the fuse_block_alloc() check.

Oh! You're right, the FUSE_DESTROY request is list_add_tail'd to fiq->pending, just like every other req, because they all go through fuse_dev_queue_req. Sorry about misreading that, but thank /you/ for pointing it out! :)

--D

Quoted 3 lines

Thanks,
Joanne

#11 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 175 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 40 lines
Quoted 34 lines

Is the above assumption correct?

I don't see any fuse servers that actually *do* this, though. I perceive that there are a lot of fuse servers out there that aren't packaged in Debian, though, so is this actually a common thing for proprietary fuse servers which I wouldn't know about?

Downthread, Bernd suggested doing this in libfuse instead of making the fuse servers do it. He asks:

"There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

"->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()"

The answer to this is: fuse_file_release is always asynchronous now, so the FUSE_RELEASE is queued to the background and the kernel moves on with its life.

It's likely much more effective to put the reordering barrier in the library (ignoring all the vendored libfuse out there) assuming that the above assumption holds. I think it wouldn't be hard to have _do_open (fuse_lowlevel.c) increment a counter in fuse_session, decrement it in _do_release, and then _do_destroy would wait for it to hit zero.

Quoted 5 lines

For a single-threaded fuse server I think this might not even be an issue because the events are (AFAICT) processed in order. However, you'd have to be careful about how you did that for a multithreaded fuse server. You wouldn't want to spin in _do_destroy because that takes out a thread that could be doing work. Is there a way to park a request?

Quoted 3 lines

If the background requests are flushed before the destroy request, then this doesn't take out a thread because al the background requests will already have been or are being serviced.

<nod>

I'm still concerned about a few things with the libfuse approach though. The kernel is the initiator, so it knows the data dependencies between requests. Consequently, it's in the best position to know that if request R2 depends on R1, then it shouldn't issue R2 until it has received an acknowledgement for R1. The fuse server is the target, it shouldn't be second-guessing what the initiator wants.

The second concern is that if a request timeout is in effect, then all the time that libfuse spends waiting for other request to drain is charged to that request. IOWs, if the timeout is 60s and libfuse holds the FUSE_DESTROY for 40s, the fuse server only has 20s to reply to the request whereas the sysadmin might have assumed that the server would have a full 60s to flush the filesystem and exit.

If you're worried about no-timeout fuse servers hanging the unmount process, what about killing the fuse server? Or telling the kernel to abort the connection? Either should suffice to kill the wait_event loop.

Quoted 6 lines

The third thing is that the iomap patchset will change the unmount request sequence:

1. <some number of FUSE_RELEASEs>
2. FUSE_SYNCFS to tell the fuse server to write all its dirty data
3. FUSE_DESTROY to close the filesystem

imo it's the responsibility of FUSE_DESTROY to write out any lingering dirty data before tearing down state and there shouldn't need to be an extra FUSE_SYNCFS issued before the destroy.

Quoted 9 lines

If we put the ordering barrier in libfuse, then we'll have to modify libfuse to flush all of (1) before processing (2), and then wait for (2) to finish before processing (3). But libfuse doesn't know that a particular FUSE_SYNCFS will be succeeded by a FUSE_DESTROY. I could drop the SYNCFS and let DESTROY handle all the flushing. But again, the kernel already knows the ordering that it requires, so it should enforce that ordering directly.

Quoted 6 lines

(Sorry, I feel like I'm belaboring the point excessively, I'll stop)

The libfuse approach /does/ have the small advantage that it can start working on the FUSE_DESTROY as soon as the other workers quiesce because it doesn't have to wait for the kernel to see the last FUSE_RELEASE reply and generate the DESTROY request.

imo the main advantage is that handling this in userspace offers servers a lot more flexibility for controlling unmount/destroy behavior. If we have this logic in the kernel, we're guaranteeing that all previous requests must be completed (no matter how long they take) before the server sees FUSE_DESTROY. For example if some servers in the future want to prioritize fast unmounts over having lingering unlinked files, then this allows for that. Or if the server wants to write out data while RELEASE is happening, they can do that too instead of having to wait for the RELEASE to finish.

I'm not sure if we even really do need to wait for RELEASE to finish before replying back to the DESTROY request. For unlinking files and writing data out to storage for example, can't you do all of that still even after replying back to the DESTROY request? The connection will be aborted but that seems fine, that just means the client can't communicate with the server. This would let the unmount finish quickly while meanwhile the server logic can run still even after the unmount / connection abort, and the server could then do/finish all the unlinking logic / writing to storage. Then when all of that is finished, the server could officially clean everything up and exit.

Quoted 23 lines
Quoted 17 lines
Quoted 13 lines

Note that both of these approaches come with the risk that the kernel could decide to time out and abort the FUSE_DESTROY while the server is still waiting for the counter to hit zero.

For a fuseblk filesystem this abort is very dangerous because the kernel releases its O_EXCL hold on the block device in kill_block_super before the fuse server has a chance to finish up and close the block device. The fuseblk server itself could not have opened the block device O_EXCL so that means there's a period where another process (or even another fuseblk mount) could open the bdev O_EXCL and both try to write to the block device.

Quoted 3 lines

(I actually have been wondering who uses the fuse request timeouts? In my testing even 30min wasn't sufficient to avoid aborts for some of the truncate/inactivation fstests.)

Quoted 5 lines

Meta uses fuse request timeouts. We saw a few cases of deadlocks in some buggy fuse server implementations, so we now enforce default timeouts. The timeout is set to a pretty large number though. Our main use of it is to free/cleanup system resources if the server is deadlocked.

Quoted 3 lines

If you can share, how long of a timeout? I've noticed that some clouds set their iscsi timeouts to 12h or more(!) and that's for a single SCSI command.

Right now the default is 30 minutes.

Thanks,
Joanne

Quoted 101 lines
Quoted 3 lines

If it takes 30 minutes to do all the cleanup, then I think it's worse to have unmounting take that long, than to just do a quicker unmount

If you don't handle unlinked lists in a O(n) (or O(1) way) then unprivileged userspace programs can manipulate the filesystem so that it actually /can/ take hours to unmount. XFS, ext4, and now fuse4fs have learned that the hard way. ;)

Quoted 3 lines

and have lingering unlinked files on the server. As a user, if I were unmounting something and it took that long, I would probably just kill the whole thing anyways.

That very much depends on what you're going to do with that filesystem. If you're disposing of a container then, meh, fire away. Some people "use" FS_IOC_SHUTDOWN to "terminate" containers quickly.

Quoted 66 lines
Quoted 66 lines

Aside: The reason why I abandoned making fuse2fs a fuseblk server is because I realized this exact trap -- the fuse server MUST have exclusive write access to the device at all times, or else it can race with other programs (e.g. tune2fs) and corrupt the filesystem. In fuseblk mode the kernel owns the exclusive access and but doesn't install that file in the server's fd table. At best the fuse server can pretend that it has exclusive write access, but the kernel can make that go away without telling the fuse server, which opens a world of hurt.

Quoted 4 lines

imo the only responsibility of the
kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

They do receive it because fuse_session_destroy calls ->destroy if no event has been received from the kernel after the fusedev shuts down.

Quoted 22 lines
Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 3 lines

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

It's not sufficient, because there might be other cached dirty metadata that needs to be flushed out to disk. A fuse server could respond to a FUSE_FLUSH by pushing out that inode's dirty metadata to disk but go no farther. Plumbing in FUSE_SYNCFS for iomap helps a lot in that regard because that's a signal that we need to push dirty ext4 bitmaps and group descriptors and whatnot out to storage; without it we end up doing all that at destroy time.

Quoted 13 lines
Quoted 9 lines
Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

Quoted 7 lines
Quoted 3 lines

I think it's worse than that -- fuse_send_destroy sets fuse_args::force and sends the request synchronously, which (afaict) means it jumps ahead of the backgrounded requests.

Hmm, where are you seeing that? afaict, args->force forces the request to be sent to userspace even if interrupted and it skips the fuse_block_alloc() check.

Oh! You're right, the FUSE_DESTROY request is list_add_tail'd to fiq->pending, just like every other req, because they all go through fuse_dev_queue_req. Sorry about misreading that, but thank /you/ for pointing it out! :)

--D

Quoted 3 lines

Thanks,
Joanne

#12 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 213 lines · Joanne Koong
Quoted 175 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 40 lines
Quoted 34 lines

Is the above assumption correct?

I don't see any fuse servers that actually *do* this, though. I perceive that there are a lot of fuse servers out there that aren't packaged in Debian, though, so is this actually a common thing for proprietary fuse servers which I wouldn't know about?

Downthread, Bernd suggested doing this in libfuse instead of making the fuse servers do it. He asks:

"There is something I don't understand though, how can FUSE_DESTROY happen before FUSE_RELEASE is completed?

"->release / fuse_release
fuse_release_common

      fuse_file_release
         fuse_file_put
            fuse_simple_background
            <userspace>
            <userspace-reply>
               fuse_release_end
                  iput()"

The answer to this is: fuse_file_release is always asynchronous now, so the FUSE_RELEASE is queued to the background and the kernel moves on with its life.

It's likely much more effective to put the reordering barrier in the library (ignoring all the vendored libfuse out there) assuming that the above assumption holds. I think it wouldn't be hard to have _do_open (fuse_lowlevel.c) increment a counter in fuse_session, decrement it in _do_release, and then _do_destroy would wait for it to hit zero.

Quoted 5 lines

For a single-threaded fuse server I think this might not even be an issue because the events are (AFAICT) processed in order. However, you'd have to be careful about how you did that for a multithreaded fuse server. You wouldn't want to spin in _do_destroy because that takes out a thread that could be doing work. Is there a way to park a request?

Quoted 3 lines

If the background requests are flushed before the destroy request, then this doesn't take out a thread because al the background requests will already have been or are being serviced.

<nod>

I'm still concerned about a few things with the libfuse approach though. The kernel is the initiator, so it knows the data dependencies between requests. Consequently, it's in the best position to know that if request R2 depends on R1, then it shouldn't issue R2 until it has received an acknowledgement for R1. The fuse server is the target, it shouldn't be second-guessing what the initiator wants.

The second concern is that if a request timeout is in effect, then all the time that libfuse spends waiting for other request to drain is charged to that request. IOWs, if the timeout is 60s and libfuse holds the FUSE_DESTROY for 40s, the fuse server only has 20s to reply to the request whereas the sysadmin might have assumed that the server would have a full 60s to flush the filesystem and exit.

If you're worried about no-timeout fuse servers hanging the unmount process, what about killing the fuse server? Or telling the kernel to abort the connection? Either should suffice to kill the wait_event loop.

Quoted 6 lines

The third thing is that the iomap patchset will change the unmount request sequence:

1. <some number of FUSE_RELEASEs>
2. FUSE_SYNCFS to tell the fuse server to write all its dirty data
3. FUSE_DESTROY to close the filesystem

imo it's the responsibility of FUSE_DESTROY to write out any lingering dirty data before tearing down state and there shouldn't need to be an extra FUSE_SYNCFS issued before the destroy.

Quoted 9 lines

If we put the ordering barrier in libfuse, then we'll have to modify libfuse to flush all of (1) before processing (2), and then wait for (2) to finish before processing (3). But libfuse doesn't know that a particular FUSE_SYNCFS will be succeeded by a FUSE_DESTROY. I could drop the SYNCFS and let DESTROY handle all the flushing. But again, the kernel already knows the ordering that it requires, so it should enforce that ordering directly.

Quoted 6 lines

(Sorry, I feel like I'm belaboring the point excessively, I'll stop)

The libfuse approach /does/ have the small advantage that it can start working on the FUSE_DESTROY as soon as the other workers quiesce because it doesn't have to wait for the kernel to see the last FUSE_RELEASE reply and generate the DESTROY request.

imo the main advantage is that handling this in userspace offers servers a lot more flexibility for controlling unmount/destroy behavior. If we have this logic in the kernel, we're guaranteeing that all previous requests must be completed (no matter how long they take) before the server sees FUSE_DESTROY. For example if some servers in the future want to prioritize fast unmounts over having lingering unlinked files, then this allows for that. Or if the server wants to write out data while RELEASE is happening, they can do that too instead of having to wait for the RELEASE to finish.

Quoted 10 lines

I'm not sure if we even really do need to wait for RELEASE to finish before replying back to the DESTROY request. For unlinking files and writing data out to storage for example, can't you do all of that still even after replying back to the DESTROY request? The connection will be aborted but that seems fine, that just means the client can't communicate with the server. This would let the unmount finish quickly while meanwhile the server logic can run still even after the unmount / connection abort, and the server could then do/finish all the unlinking logic / writing to storage. Then when all of that is finished, the server could officially clean everything up and exit.

No, because fuseblk and fuse-iomap servers MUST close the block devices before the umount(2) call returns so that an immediate mount(8) doesn't fail because the block device is still open O_EXCL. This is a fundamental behavior of all local filesystems because O_EXCL is the *only* mechanism that prevents two separate mounts of the same device, and mount(2) fails immediately if it can't open a block device O_EXCL.

fstests and many other scripts rely on the behavior that the block device is always free when umount returns. I know it's tempting to make regular unmount return ASAP even if the filesystem isn't quite done, but that's what umount -l is for.

--D

Quoted 129 lines
Quoted 18 lines
Quoted 12 lines
Quoted 11 lines

For a fuseblk filesystem this abort is very dangerous because the kernel releases its O_EXCL hold on the block device in kill_block_super before the fuse server has a chance to finish up and close the block device. The fuseblk server itself could not have opened the block device O_EXCL so that means there's a period where another process (or even another fuseblk mount) could open the bdev O_EXCL and both try to write to the block device.

(I actually have been wondering who uses the fuse request timeouts? In my testing even 30min wasn't sufficient to avoid aborts for some of the truncate/inactivation fstests.)

Quoted 5 lines

Meta uses fuse request timeouts. We saw a few cases of deadlocks in some buggy fuse server implementations, so we now enforce default timeouts. The timeout is set to a pretty large number though. Our main use of it is to free/cleanup system resources if the server is deadlocked.

Quoted 3 lines

If you can share, how long of a timeout? I've noticed that some clouds set their iscsi timeouts to 12h or more(!) and that's for a single SCSI command.

Right now the default is 30 minutes.

Thanks,
Joanne

Quoted 101 lines
Quoted 3 lines

If it takes 30 minutes to do all the cleanup, then I think it's worse to have unmounting take that long, than to just do a quicker unmount

If you don't handle unlinked lists in a O(n) (or O(1) way) then unprivileged userspace programs can manipulate the filesystem so that it actually /can/ take hours to unmount. XFS, ext4, and now fuse4fs have learned that the hard way. ;)

Quoted 3 lines

and have lingering unlinked files on the server. As a user, if I were unmounting something and it took that long, I would probably just kill the whole thing anyways.

That very much depends on what you're going to do with that filesystem. If you're disposing of a container then, meh, fire away. Some people "use" FS_IOC_SHUTDOWN to "terminate" containers quickly.

Quoted 66 lines
Quoted 66 lines

Aside: The reason why I abandoned making fuse2fs a fuseblk server is because I realized this exact trap -- the fuse server MUST have exclusive write access to the device at all times, or else it can race with other programs (e.g. tune2fs) and corrupt the filesystem. In fuseblk mode the kernel owns the exclusive access and but doesn't install that file in the server's fd table. At best the fuse server can pretend that it has exclusive write access, but the kernel can make that go away without telling the fuse server, which opens a world of hurt.

Quoted 4 lines

imo the only responsibility of the
kernel is to actually send the background requests before it sends the FUSE_DESTROY. I think non-fuseblk servers should also receive the FUSE_DESTROY request.

They do receive it because fuse_session_destroy calls ->destroy if no event has been received from the kernel after the fusedev shuts down.

Quoted 22 lines
Quoted 16 lines

Here, if you make a fuseblk server's ->destroy release all the remaining open files, you have an even worse problem, because that could race with an existing libfuse worker that's processing a FUSE_RELEASE for the same open file.

In short, the client has a FUSE_RELEASE request that pairs with the FUSE_OPEN request. During regular operations, an OPEN always ends with a RELEASE. I don't understand why unmount is special in that it aborts release requests without even sending them to the server; that sounds like a bug to me. Worse yet, I looked on Debian codesearch, and nearly all of the fuse servers I found do not appear to handle this correctly. My guess is that it's uncommon to close 100,000 unlinked open files on a fuse filesystem and immediately unmount it. Network filesystems can get away with not caring.

Quoted 5 lines

For fuse+iomap, I want unmount to send FUSE_SYNCFS after all open files have been RELEASEd so that client can know that (a) the filesystem (at least as far as the kernel cares) is quiesced, and (b) the server persisted all dirty metadata to disk. Only then would I send the FUSE_DESTROY.

Quoted 3 lines

Hmm, is FUSE_FLUSH not enough? As I recently learned (from Amir), every close() triggers a FUSE_FLUSH. For dirty metadata related to writeback, every release triggers a synchronous write_inode_now().

It's not sufficient, because there might be other cached dirty metadata that needs to be flushed out to disk. A fuse server could respond to a FUSE_FLUSH by pushing out that inode's dirty metadata to disk but go no farther. Plumbing in FUSE_SYNCFS for iomap helps a lot in that regard because that's a signal that we need to push dirty ext4 bitmaps and group descriptors and whatnot out to storage; without it we end up doing all that at destroy time.

Quoted 13 lines
Quoted 9 lines
Quoted 5 lines

We are already guaranteeing that the
background requests get sent before we issue the FUSE_DESTROY, so it seems to me like this is already enough and we could skip the wait because the server should make sure it completes the prior requests it's received before it executes the destruction logic.

That's just the thing -- fuse_conn_destroy calls fuse_abort_conn which aborts all the pending background requests so the server never sees them.

The FUSE_DESTROY request gets sent before fuse_abort_conn() is called, so to me, it seems like if we flush all the background requests and then send the FUSE_DESTROY, that suffices.

Quoted 7 lines
Quoted 3 lines

I think it's worse than that -- fuse_send_destroy sets fuse_args::force and sends the request synchronously, which (afaict) means it jumps ahead of the backgrounded requests.

Hmm, where are you seeing that? afaict, args->force forces the request to be sent to userspace even if interrupted and it skips the fuse_block_alloc() check.

Oh! You're right, the FUSE_DESTROY request is list_add_tail'd to fiq->pending, just like every other req, because they all go through fuse_dev_queue_req. Sorry about misreading that, but thank /you/ for pointing it out! :)

--D

Quoted 3 lines

Thanks,
Joanne

#13 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

In reply to Darrick J. Wong
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Thanks,
Bernd

#14 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

--D

Quoted 3 lines

Thanks,
Bernd

#15 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 119 lines · Darrick J. Wong
Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Quoted 7 lines

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

FWIW I tried this out over the weekend with the patch below and the wait_event() turned off in the kernel. It seems to work (though I only tried it cursorily with iouring) so if the kernel fuse developers would rather not have a wait_event() in the unmount path then I suppose this is a way to move ahead with this topic.

--D

From: Darrick J. Wong <[email protected]>
Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 55 insertions(+), 3 deletions(-)
lib/fuse_i.h +4 -0
index 0ce2c0134ed879..dfe9d9f067498e 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +51 -3

133 lines not on this page · raw message

#16 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 177 lines · Darrick J. Wong
Quoted 119 lines · Darrick J. Wong
Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Quoted 7 lines

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

FWIW I tried this out over the weekend with the patch below and the wait_event() turned off in the kernel. It seems to work (though I only tried it cursorily with iouring) so if the kernel fuse developers would rather not have a wait_event() in the unmount path then I suppose this is a way to move ahead with this topic.

--D

From: Darrick J. Wong <[email protected]>
Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 55 insertions(+), 3 deletions(-)
lib/fuse_i.h +4 -0
index 0ce2c0134ed879..dfe9d9f067498e 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +5 -0
index 12724ed66bdcc8..f12c6db0eb0e60 100644
@@ -52,6 +52,30 @@
 #define PARAM(inarg) (((char *)(inarg)) + sizeof(*(inarg)))
 #define OFFSET_MAX 0x7fffffffffffffffLL
 
+static inline void inc_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files++;
+	pthread_mutex_unlock(&se->lock);

lib/fuse_lowlevel.c line 69

Quoted 10 lines
lib/fuse_lowlevel.c +10 -0
+}
+
+static inline void dec_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files--;
+	if (!se->open_files)
+		pthread_cond_broadcast(&se->zero_open_files);
+	pthread_mutex_unlock(&se->lock);
+}

I think open files only decreases when destroy is received? Doesn't that give us the chance to use an atomic (C11) and then to broadcast only when FUSE_DESTROY is received? I.e. I would use an atomic for 'open_files', set something like 'se->destroy_received' and then trigger the broadcast only when that is set.

(A later further optimization with io-uring will be to have that counter per queue.)

Thanks,
Bernd

#17 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 188 lines · Bernd Schubert
Quoted 185 lines · Darrick J. Wong
Quoted 119 lines · Darrick J. Wong
Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Quoted 7 lines

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

FWIW I tried this out over the weekend with the patch below and the wait_event() turned off in the kernel. It seems to work (though I only tried it cursorily with iouring) so if the kernel fuse developers would rather not have a wait_event() in the unmount path then I suppose this is a way to move ahead with this topic.

--D

From: Darrick J. Wong <[email protected]>
Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 55 insertions(+), 3 deletions(-)
lib/fuse_i.h +4 -0
index 0ce2c0134ed879..dfe9d9f067498e 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +13 -0
index 12724ed66bdcc8..f12c6db0eb0e60 100644
@@ -52,6 +52,30 @@
 #define PARAM(inarg) (((char *)(inarg)) + sizeof(*(inarg)))
 #define OFFSET_MAX 0x7fffffffffffffffLL
 
+static inline void inc_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files++;
+	pthread_mutex_unlock(&se->lock);
+}
+
+static inline void dec_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files--;
+	if (!se->open_files)
+		pthread_cond_broadcast(&se->zero_open_files);
Quoted 8 lines

lib/fuse_lowlevel.c line 69

Quoted 2 lines
lib/fuse_lowlevel.c +2 -0
+	pthread_mutex_unlock(&se->lock);
+}

I think open files only decreases when destroy is received? Doesn't that give us the chance to use an atomic (C11) and then to broadcast only when FUSE_DESTROY is received? I.e. I would use an atomic for 'open_files', set something like 'se->destroy_received' and then trigger the broadcast only when that is set.

I'm sorry, but I'm not familiar enough with C11 atomics to know if that would work. I suppose it /has/ been 3 years since the kernel went from C89 to C11 but some of us are still old dinosaurs who cut their teeth on C back when the paint was still fresh on C90. ;)

I think it would be ok to define open_files as _Atomic and then do something like:

	if (atomic_fetch_sub(&se->open_files, -1) == 1)
		cnd_broadcast(&cse->zero_open_files);

without needing to take se->lock. I'm not sure how you'd handle races between a thread setting destroy_received and dec_open_files testing the flag, though. Maybe it'd be easier to bias open_files upward by one in the init method and downward by one in op_destroy so we'd never send the broadcast until unmount time?

--D

Quoted 7 lines

(A later further optimization with io-uring will be to have that counter per queue.)

Thanks,
Bernd

#18 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 198 lines · Darrick J. Wong
Quoted 188 lines · Bernd Schubert
Quoted 185 lines · Darrick J. Wong
Quoted 119 lines · Darrick J. Wong
Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines

Review

Quoted 5 lines
(quoted diff) +5 -0
+       while (wait_event_timeout(fc->blocked_waitq,
+                       !fc->connected || atomic_read(&fc->num_waiting) == 0,
+                       HZ) == 0) {
+               /* empty */
+       }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Quoted 7 lines

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

FWIW I tried this out over the weekend with the patch below and the wait_event() turned off in the kernel. It seems to work (though I only tried it cursorily with iouring) so if the kernel fuse developers would rather not have a wait_event() in the unmount path then I suppose this is a way to move ahead with this topic.

--D

From: Darrick J. Wong <[email protected]>
Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 55 insertions(+), 3 deletions(-)
lib/fuse_i.h +4 -0
index 0ce2c0134ed879..dfe9d9f067498e 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +13 -0
index 12724ed66bdcc8..f12c6db0eb0e60 100644
@@ -52,6 +52,30 @@
 #define PARAM(inarg) (((char *)(inarg)) + sizeof(*(inarg)))
 #define OFFSET_MAX 0x7fffffffffffffffLL
 
+static inline void inc_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files++;
+	pthread_mutex_unlock(&se->lock);
+}
+
+static inline void dec_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files--;
+	if (!se->open_files)
+		pthread_cond_broadcast(&se->zero_open_files);
Quoted 8 lines

lib/fuse_lowlevel.c line 69

Quoted 2 lines
lib/fuse_lowlevel.c +2 -0
+	pthread_mutex_unlock(&se->lock);
+}

I think open files only decreases when destroy is received? Doesn't that give us the chance to use an atomic (C11) and then to broadcast only when FUSE_DESTROY is received? I.e. I would use an atomic for 'open_files', set something like 'se->destroy_received' and then trigger the broadcast only when that is set.

Quoted 4 lines

I'm sorry, but I'm not familiar enough with C11 atomics to know if that would work. I suppose it /has/ been 3 years since the kernel went from C89 to C11 but some of us are still old dinosaurs who cut their teeth on C back when the paint was still fresh on C90. ;)

No worries, I'm personally catching up with C++ beyond C++98.

Quoted 4 lines

I think it would be ok to define open_files as _Atomic and then do something like:

Quoted 8 lines
	if (atomic_fetch_sub(&se->open_files, -1) == 1)
		cnd_broadcast(&cse->zero_open_files);

without needing to take se->lock. I'm not sure how you'd handle races between a thread setting destroy_received and dec_open_files testing the flag, though. Maybe it'd be easier to bias open_files upward by one in the init method and downward by one in op_destroy so we'd never send the broadcast until unmount time?

I link that very much. Your patch didn't apply in fuse_reply_create, because of your other changes, so I applied some parts manually. I would like to test and merge this patch
as soon as possible, as we actually got an external ticket about it around last week (tear down DLM issues) and generic/531 actually also fails with passthrough_hp

generic/531 - output mismatch (see /home/fusetests/src/xfstests-dev/results//generic/531.out.bad)
--- tests/generic/531.out 2023-02-02 15:37:23.979018084 +0100
+++ /home/fusetests/src/xfstests-dev/results//generic/531.out.bad 2025-11-10 15:30:23.253431465 +0100
@@ -1,2 +1,25 @@
QA output created by 531
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
...
(Run 'diff -u /home/fusetests/src/xfstests-dev/tests/generic/531.out /home/fusetests/src/xfstests-dev/res

My VM is currently busy with another patch set verification, I'm going to try it after that.

Can I push the version below to libfuse for review/merge?

Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

From: Darrick J. Wong <[email protected]>

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   51 +++++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 53 insertions(+), 2 deletions(-)
lib/fuse_i.h +4 -0
index d35e1e51d823..b603e52b1b85 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	_Atomic uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +49 -2

130 lines not on this page · raw message

Thanks,
Bernd

#19 lore raw

Re: [PATCH 1/5] fuse: flush pending fuse events before aborting the connection

Quoted 201 lines · Bernd Schubert
Quoted 198 lines · Darrick J. Wong
Quoted 196 lines · Bernd Schubert
Quoted 177 lines · Darrick J. Wong
Quoted 119 lines · Darrick J. Wong
Quoted 112 lines · Bernd Schubert
Quoted 102 lines · Darrick J. Wong

[I read this email backwards, like I do]

Quoted 75 lines · Joanne Koong
Quoted 67 lines · Darrick J. Wong

On Tue, Nov 04, 2025 at 11:22:26AM -0800, Joanne Koong wrote:

<snipping here because this thread has gotten very long>

Quoted 34 lines
Quoted 26 lines
Quoted 8 lines
Quoted 5 lines

+ while (wait_event_timeout(fc->blocked_waitq,
+ !fc->connected || atomic_read(&fc->num_waiting) == 0,
+ HZ) == 0) {
+ /* empty */
+ }

I'm wondering if it's necessary to wait here for all the pending requests to complete or abort?

I'm not 100% sure what the fuse client shutdown sequence is supposed to be. If someone kills a program with a large number of open unlinked files and immediately calls umount(), then the fuse client could be in the process of sending FUSE_RELEASE requests to the server.

[background info, feel free to speedread this paragraph]
For a non-fuseblk server, unmount aborts all pending requests and disconnects the fuse device. This means that the fuse server won't see all the FUSE_REQUESTs before libfuse calls ->destroy having observed the fusedev shutdown. The end result is that (on fuse2fs anyway) you end up with a lot of .fuseXXXXX files that nobody cleans up.

If you make ->destroy release all the remaining open files, now you run into a second problem, which is that if there are a lot of open unlinked files, freeing the inodes can collectively take enough time that the FUSE_DESTROY request times out.

Quoted 7 lines

On a fuseblk server with libfuse running in multithreaded mode, there can be several threads reading fuse requests from the fusedev. The kernel actually sends its own FUSE_DESTROY request, but there's no coordination between the fuse workers, which means that the fuse server can process FUSE_DESTROY at the same time it's processing FUSE_RELEASE. If ->destroy closes the filesystem before the FUSE_RELEASE requests are processed, you end up with the same .fuseXXXXX file cleanup problem.

Quoted 3 lines

imo it is the responsibility of the server to coordinate this and make sure it has handled all the requests it has received before it starts executing the destruction logic.

I think we're all saying that some sort of fuse request reordering barrier is needed here, but there's at least three opinions about where that barrier should be implemented. Clearly I think the barrier should be in the kernel, but let me think more about where it could go if it were somewhere else.

First, Joanne's suggestion for putting it in the fuse server itself:

I don't see how it's generally possible for the fuse server to know that it's processed all the requests that the kernel might have sent it. AFAICT each libfuse thread does roughly this:

1. read() a request from the fusedev fd
2. decode the request data and maybe do some allocations or transform it
3. call fuse server with request
4. fuse server does ... something with the request
5. fuse server finishes, hops back to libfuse / calls fuse_reply_XXX

Let's say thread 1 is at step 4 with a FUSE_DESTROY. How does it find out if there are other fuse worker threads that are somewhere in steps 2 or 3? AFAICT the library doesn't keep track of the number of threads that are waiting in fuse_session_receive_buf_internal, so fuse servers can't ask the library about that either.

Quoted 6 lines

Taking a narrower view, it might be possible for the fuse server to figure this out by maintaining an open resource count. It would increment this counter when a FUSE_{OPEN,CREATE} request succeeds and decrement it when FUSE_RELEASE comes in. Assuming that FUSE_RELEASE is the only kind of request that can be pending when a FUSE_DESTROY comes in, then destroy just has to wait for the counter to hit zero.

Quoted 11 lines

I was thinking this logic could be in libfuse's fuse_loop_mt.c. Where if there are X worker threads that are all running fuse_do_work( ) then if you get a FUSE_DESTROY on one of those threads that thread can set some se->destroyed field. At this point the other threads will have already called fuse_session_receive_buf_internal() on all the flushed background requests, so after they process it and return from fuse_session_process_buf_internal(), then they check if se->destroyed was set, and if it is they exit the thread, while in the thread that got the FUSE_DESTROY it sleeps until all the threads have completed and then it executes the destroy logic.That to me seems like the cleanest approach.

Hrm. Well now (scrolling to the bottom and back) that I know that the FUSE_DESTROY won't get put on the queue ahead of the FUSE_RELEASEs, I think that /could/ work.

One tricky thing with having worker threads check a flag and exit is that they can be sleeping in the kernel (from _fuse_session_receive_buf) when the "just go away" flag gets set. If the thread never wakes up, then it'll never exit. In theory you could have the FUSE_DESTROY thread call pthread_cancel on all the other worker threads to eliminate them once they emerge from PTHREAD_CANCEL_DISABLE state, but I still have nightmares from adventures in pthread_cancel at Sun in 2002. :P

Quoted 6 lines

Maybe an easier approach would be to have fuse_do_work increment a counter when it receives a buffer and decrement it when it finishes with that buffer. The FUSE_DESTROY thread merely has to wait for that counter to reach 1, at which point it's the only thread with a request to process, so it can call do_destroy. That at least would avoid adding a new user of pthread_cancel() into the mt loop code.

Quoted 5 lines

I will read through the rest (too tired right now) durig the weekend. I was also thinking about counter. And let's please also do this right also handling io-uring. I.e. all CQEs needs to have been handled. Without io-uring it would be probably a counter in decreased in fuse_free_req(), with io-uring it is a bit more complex.

Quoted 7 lines

Oh right, the uring backend.

Assuming that it's really true that the only requests pending during an unmount are going to be FUSE_RELEASE (nobody's actually said that's true) then it's *much* easier to count the number of open files in fuse_session and make _do_destroy in the lowlevel library wait until the open file count reaches zero.

FWIW I tried this out over the weekend with the patch below and the wait_event() turned off in the kernel. It seems to work (though I only tried it cursorily with iouring) so if the kernel fuse developers would rather not have a wait_event() in the unmount path then I suppose this is a way to move ahead with this topic.

--D

From: Darrick J. Wong <[email protected]>
Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 55 insertions(+), 3 deletions(-)
lib/fuse_i.h +4 -0
index 0ce2c0134ed879..dfe9d9f067498e 100644
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	uint64_t open_files;
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +5 -0
index 12724ed66bdcc8..f12c6db0eb0e60 100644
@@ -52,6 +52,30 @@
 #define PARAM(inarg) (((char *)(inarg)) + sizeof(*(inarg)))
 #define OFFSET_MAX 0x7fffffffffffffffLL
 
+static inline void inc_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files++;
+	pthread_mutex_unlock(&se->lock);

lib/fuse_lowlevel.c line 69

Quoted 10 lines
lib/fuse_lowlevel.c +10 -0
+}
+
+static inline void dec_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	se->open_files--;
+	if (!se->open_files)
+		pthread_cond_broadcast(&se->zero_open_files);
+	pthread_mutex_unlock(&se->lock);
+}

I think open files only decreases when destroy is received? Doesn't that give us the chance to use an atomic (C11) and then to broadcast only when FUSE_DESTROY is received? I.e. I would use an atomic for 'open_files', set something like 'se->destroy_received' and then trigger the broadcast only when that is set.

Quoted 6 lines
Quoted 4 lines

I'm sorry, but I'm not familiar enough with C11 atomics to know if that would work. I suppose it /has/ been 3 years since the kernel went from C89 to C11 but some of us are still old dinosaurs who cut their teeth on C back when the paint was still fresh on C90. ;)

No worries, I'm personally catching up with C++ beyond C++98.

Me too! I'm reading "Building a Debugger" which is chock full of C++17 and WHOAH!

Quoted 60 lines
Quoted 4 lines

I think it would be ok to define open_files as _Atomic and then do something like:

Quoted 8 lines
	if (atomic_fetch_sub(&se->open_files, -1) == 1)
		cnd_broadcast(&cse->zero_open_files);

without needing to take se->lock. I'm not sure how you'd handle races between a thread setting destroy_received and dec_open_files testing the flag, though. Maybe it'd be easier to bias open_files upward by one in the init method and downward by one in op_destroy so we'd never send the broadcast until unmount time?

I link that very much. Your patch didn't apply in fuse_reply_create, because of your other changes, so I applied some parts manually. I would like to test and merge this patch
as soon as possible, as we actually got an external ticket about it around last week (tear down DLM issues) and generic/531 actually also fails with passthrough_hp

generic/531 - output mismatch (see /home/fusetests/src/xfstests-dev/results//generic/531.out.bad)
--- tests/generic/531.out 2023-02-02 15:37:23.979018084 +0100
+++ /home/fusetests/src/xfstests-dev/results//generic/531.out.bad 2025-11-10 15:30:23.253431465 +0100
@@ -1,2 +1,25 @@
QA output created by 531
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
+open?: Bad file descriptor
...
(Run 'diff -u /home/fusetests/src/xfstests-dev/tests/generic/531.out /home/fusetests/src/xfstests-dev/res

My VM is currently busy with another patch set verification, I'm going to try it after that.

Can I push the version below to libfuse for review/merge?

Subject: [PATCH] libfuse: wait in do_destroy until all open files are closed

From: Darrick J. Wong <[email protected]>

Joanne suggests that libfuse should defer a FUSE_DESTROY request until all FUSE_RELEASEs have completed. Let's see if that works by tracking the count of open files.

---
 lib/fuse_i.h        |    4 ++++
 lib/fuse_lowlevel.c |   51 +++++++++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 53 insertions(+), 2 deletions(-)
lib/fuse_i.h +0 -0
index d35e1e51d823..b603e52b1b85 100644

lib/fuse_i.h struct fuse_session { · line 123

Quoted 7 lines
lib/fuse_i.h +4 -0
@@ -117,6 +117,10 @@ struct fuse_session {
 	 */
 	uint32_t conn_want;
 	uint64_t conn_want_ext;
+
+	/* destroy has to wait for all the open files to go away */
+	pthread_cond_t zero_open_files;
+	_Atomic uint64_t open_files;

Hrm. When we wired up xfsprogs with liburcu, one of the problems that we encountered is that not all platforms can handle 64-bit atomic integers (e.g. 32-bit systems). Does _Atomic make it work? Or at least fail the build if it can't?

(Hoping the answer isn't "subtly fails")

Quoted 8 lines
lib/fuse_i.h +0 -0
 };
 
 struct fuse_chan {
lib/fuse_lowlevel.c +0 -0
index d420b257b9dd..2e09027e6022 100644

lib/fuse_lowlevel.c line 57

Quoted 6 lines
lib/fuse_lowlevel.c +3 -0
@@ -52,6 +52,30 @@
 #define PARAM(inarg) (((char *)(inarg)) + sizeof(*(inarg)))
 #define OFFSET_MAX 0x7fffffffffffffffLL
 
+static inline void inc_open_files(struct fuse_session *se)
+{
+	se->open_files++;

Do regular increment and decrement work for variables with _Atomic attributes? (Pardon my ignorance, I honestly do not know.)

Quoted 117 lines
lib/fuse_lowlevel.c +42 -2
+}
+
+static inline void dec_open_files(struct fuse_session *se)
+{
+	int prev = atomic_fetch_sub(&se->open_files, 1);
+	if (unlikely(prev == 1)) {
+		pthread_mutex_lock(&se->lock);
+		pthread_cond_broadcast(&se->zero_open_files);
+		pthread_mutex_unlock(&se->lock);
+	}
+}
+
+static inline void wait_for_zero_open_files(struct fuse_session *se)
+{
+	pthread_mutex_lock(&se->lock);
+	while (se->open_files > 0) {
+		pthread_cond_wait(&se->zero_open_files, &se->lock);
+	}
+	pthread_mutex_unlock(&se->lock);
+}
+
 struct fuse_pollhandle {
 	uint64_t kh;
 	struct fuse_session *se;
@@ -522,17 +546,23 @@ int fuse_reply_entry(fuse_req_t req, const struct fuse_entry_param *e)
 int fuse_reply_create(fuse_req_t req, const struct fuse_entry_param *e,
 		      const struct fuse_file_info *f)
 {
+	struct fuse_session *se = req->se;
 	alignas(uint64_t) char buf[sizeof(struct fuse_entry_out) + sizeof(struct fuse_open_out)];
 	size_t entrysize = req->se->conn.proto_minor < 9 ?
 		FUSE_COMPAT_ENTRY_OUT_SIZE : sizeof(struct fuse_entry_out);
 	struct fuse_entry_out *earg = (struct fuse_entry_out *) buf;
 	struct fuse_open_out *oarg = (struct fuse_open_out *) (buf + entrysize);
+	int error;
 
 	memset(buf, 0, sizeof(buf));
 	fill_entry(earg, e);
 	fill_open(oarg, f);
-	return send_reply_ok(req, buf,
+	error = send_reply_ok(req, buf,
 			     entrysize + sizeof(struct fuse_open_out));
+	if (!error)
+		inc_open_files(se);
+
+	return error;
 }
 
 int fuse_reply_attr(fuse_req_t req, const struct stat *attr,
@@ -583,10 +613,15 @@ int fuse_passthrough_close(fuse_req_t req, int backing_id)
 int fuse_reply_open(fuse_req_t req, const struct fuse_file_info *f)
 {
 	struct fuse_open_out arg;
+	struct fuse_session *se = req->se;
+	int error;
 
 	memset(&arg, 0, sizeof(arg));
 	fill_open(&arg, f);
-	return send_reply_ok(req, &arg, sizeof(arg));
+	error = send_reply_ok(req, &arg, sizeof(arg));
+	if (!error)
+		inc_open_files(se);
+	return error;
 }
 
 static int do_fuse_reply_write(fuse_req_t req, size_t count)
@@ -1854,6 +1889,7 @@ static void _do_release(fuse_req_t req, const fuse_ino_t nodeid,
 {
 	(void)in_payload;
 	const struct fuse_release_in *arg = op_in;
+	struct fuse_session *se = req->se;
 	struct fuse_file_info fi;
 
 	memset(&fi, 0, sizeof(fi));
@@ -1872,6 +1908,7 @@ static void _do_release(fuse_req_t req, const fuse_ino_t nodeid,
 		req->se->op.release(req, nodeid, &fi);
 	else
 		fuse_reply_err(req, 0);
+	dec_open_files(se);
 }
 
 static void do_release(fuse_req_t req, const fuse_ino_t nodeid,
@@ -1976,6 +2013,7 @@ static void _do_releasedir(fuse_req_t req, const fuse_ino_t nodeid,
 {
 	(void)in_payload;
 	struct fuse_release_in *arg = (struct fuse_release_in *)op_in;
+	struct fuse_session *se = req->se;
 	struct fuse_file_info fi;
 
 	memset(&fi, 0, sizeof(fi));
@@ -1986,6 +2024,7 @@ static void _do_releasedir(fuse_req_t req, const fuse_ino_t nodeid,
 		req->se->op.releasedir(req, nodeid, &fi);
 	else
 		fuse_reply_err(req, 0);
+	dec_open_files(se);
 }
 
 static void do_releasedir(fuse_req_t req, const fuse_ino_t nodeid,
@@ -2996,6 +3035,9 @@ static void _do_destroy(fuse_req_t req, const fuse_ino_t nodeid,
 	(void)op_in;
 	(void)in_payload;
 
+	se->open_files--;
+	wait_for_zero_open_files(se);
+
 	mountpoint = atomic_exchange(&se->mountpoint, NULL);
 	free(mountpoint);
 
@@ -3824,6 +3866,7 @@ void fuse_session_destroy(struct fuse_session *se)
 		fuse_ll_pipe_free(llp);
 	pthread_key_delete(se->pipe_key);
 	sem_destroy(&se->mt_finish);
+	pthread_cond_destroy(&se->zero_open_files);
 	pthread_mutex_destroy(&se->mt_lock);
 	pthread_mutex_destroy(&se->lock);
 	free(se->cuse_data);

lib/fuse_lowlevel.c fuse_session_new_versioned(struct fuse_args *args, · line 4249

Quoted 5 lines
lib/fuse_lowlevel.c +2 -0
@@ -4202,6 +4245,9 @@ fuse_session_new_versioned(struct fuse_args *args,
 	sem_init(&se->mt_finish, 0, 0);
 	pthread_mutex_init(&se->mt_lock, NULL);
 
+	pthread_cond_init(&se->zero_open_files, NULL);
+	se->open_files = 1; /* decreased by FUSE_DESTROY */

I added a more verbose comment in today's revision of that patch:

	/*
	 * Bias the open file counter by 1 so that we only wake the
	 * condition variable once FUSE_DESTROY has been seen.
	 */

Modulo my n00b questions about integer operators being applied to _Atomic variables, this patch looks reasonable. Do you need the accompanying kernel patch to fix g/531 too?

--D

Quoted 16 lines
lib/fuse_lowlevel.c +2 -0
+
 	err = pthread_key_create(&se->pipe_key, fuse_ll_pipe_destructor);
 	if (err) {
 		fuse_log(FUSE_LOG_ERR, "fuse: failed to create thread specific key: %s\n",
@@ -4226,6 +4272,7 @@ fuse_session_new_versioned(struct fuse_args *args,
 
 out5:
 	sem_destroy(&se->mt_finish);
+	pthread_cond_destroy(&se->zero_open_files);
 	pthread_mutex_destroy(&se->mt_lock);
 	pthread_mutex_destroy(&se->lock);
 out4:

Thanks,
Bernd

#20 lore raw

PATCH 2/5 fuse: signal that a fuse inode should exhibit local fs behaviors

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a new fuse inode flag that indicates that the kernel should implement various local filesystem behaviors instead of passing vfs commands straight through to the fuse server and expecting the server to do all the work. For example, this means that we'll use the kernel to transform some ACL updates into mode changes, and later to do enforcement of the immutable and append iflags.

---
 fs/fuse/fuse_i.h |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +13 -1
index aaa8574fd72775..a8068bee90af57 100644
@@ -232,6 +232,11 @@ enum {
 	FUSE_I_BTIME,
 	/* Wants or already has page cache IO */
 	FUSE_I_CACHE_IO_MODE,
+	/*
+	 * Client has exclusive access to the inode, either because fs is local
+	 * or the fuse server has an exclusive "lease" on distributed fs
+	 */
+	FUSE_I_EXCLUSIVE,
 };
 
 struct fuse_conn;
@@ -1046,7 +1051,7 @@ static inline struct fuse_conn *get_fuse_conn(struct inode *inode)
 	return get_fuse_mount_super(inode->i_sb)->fc;
 }
 
-static inline struct fuse_inode *get_fuse_inode(struct inode *inode)
+static inline struct fuse_inode *get_fuse_inode(const struct inode *inode)
 {
 	return container_of(inode, struct fuse_inode, inode);
 }
@@ -1088,6 +1093,13 @@ static inline bool fuse_is_bad(struct inode *inode)
 	return unlikely(test_bit(FUSE_I_BAD, &get_fuse_inode(inode)->state));
 }
 
+static inline bool fuse_inode_is_exclusive(const struct inode *inode)
+{
+	const struct fuse_inode *fi = get_fuse_inode(inode);
+
+	return test_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
+
 static inline struct folio **fuse_folios_alloc(unsigned int nfolios, gfp_t flags,
 					       struct fuse_folio_desc **desc)
 {
Reviewed-by on v1 2/5
#21 lore raw

Re: [PATCH 2/5] fuse: signal that a fuse inode should exhibit local fs behaviors

Quoted 11 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a new fuse inode flag that indicates that the kernel should implement various local filesystem behaviors instead of passing vfs commands straight through to the fuse server and expecting the server to do all the work. For example, this means that we'll use the kernel to transform some ACL updates into mode changes, and later to do enforcement of the immutable and append iflags.

#22 lore raw

PATCH 3/5 fuse: implement file attributes mask for statx

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Actually copy the attributes/attributes_mask from userspace. Ignore file attributes bits that the VFS sets (or doesn't set) on its own.

---
 fs/fuse/fuse_i.h |   37 +++++++++++++++++++++++++++++++++++++
 fs/fuse/dir.c    |    4 ++++
 fs/fuse/inode.c  |    4 ++++
 3 files changed, 45 insertions(+)
fs/fuse/fuse_i.h +37 -0
index a8068bee90af57..8c47d103c8ffa6 100644
@@ -140,6 +140,10 @@ struct fuse_inode {
 	/** Version of last attribute change */
 	u64 attr_version;
 
+	/** statx file attributes */
+	u64 statx_attributes;
+	u64 statx_attributes_mask;
+
 	union {
 		/* read/write io cache (regular file only) */
 		struct {
@@ -1235,6 +1239,39 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
 				   u64 attr_valid, u32 cache_mask,
 				   u64 evict_ctr);
 
+/*
+ * These statx attribute flags are set by the VFS so mask them out of replies
+ * from the fuse server for local filesystems.  Nonlocal filesystems are
+ * responsible for enforcing and advertising these flags themselves.
+ */
+#define FUSE_STATX_LOCAL_VFS_ATTRIBUTES (STATX_ATTR_IMMUTABLE | \
+					 STATX_ATTR_APPEND)
+
+/*
+ * These statx attribute flags are set by the VFS so mask them out of replies
+ * from the fuse server.
+ */
+#define FUSE_STATX_VFS_ATTRIBUTES (STATX_ATTR_AUTOMOUNT | STATX_ATTR_DAX | \
+				   STATX_ATTR_MOUNT_ROOT)
+
+static inline u64 fuse_statx_attributes_mask(const struct inode *inode,
+					     const struct fuse_statx *sx)
+{
+	if (fuse_inode_is_exclusive(inode))
+		return sx->attributes_mask & ~(FUSE_STATX_VFS_ATTRIBUTES |
+					       FUSE_STATX_LOCAL_VFS_ATTRIBUTES);
+	return sx->attributes_mask & ~FUSE_STATX_VFS_ATTRIBUTES;
+}
+
+static inline u64 fuse_statx_attributes(const struct inode *inode,
+					const struct fuse_statx *sx)
+{
+	if (fuse_inode_is_exclusive(inode))
+		return sx->attributes & ~(FUSE_STATX_VFS_ATTRIBUTES |
+					  FUSE_STATX_LOCAL_VFS_ATTRIBUTES);
+	return sx->attributes & ~FUSE_STATX_VFS_ATTRIBUTES;
+}
+
 u32 fuse_get_cache_mask(struct inode *inode);
 
 /**
fs/fuse/dir.c +4 -0
index ecaec0fea3a132..636d47a5127ca1 100644
@@ -1271,6 +1271,8 @@ static int fuse_do_statx(struct mnt_idmap *idmap, struct inode *inode,
 		stat->result_mask = sx->mask & (STATX_BASIC_STATS | STATX_BTIME);
 		stat->btime.tv_sec = sx->btime.tv_sec;
 		stat->btime.tv_nsec = min_t(u32, sx->btime.tv_nsec, NSEC_PER_SEC - 1);
+		stat->attributes |= fuse_statx_attributes(inode, sx);
+		stat->attributes_mask |= fuse_statx_attributes_mask(inode, sx);
 		fuse_fillattr(idmap, inode, &attr, stat);
 		stat->result_mask |= STATX_TYPE;
 	}
@@ -1375,6 +1377,8 @@ static int fuse_update_get_attr(struct mnt_idmap *idmap, struct inode *inode,
 			stat->btime = fi->i_btime;
 			stat->result_mask |= STATX_BTIME;
 		}
+		stat->attributes = fi->statx_attributes;
+		stat->attributes_mask = fi->statx_attributes_mask;
 	}
 
 	return err;
fs/fuse/inode.c +4 -0
index d048d634ef46f5..76e5b7f5c980c2 100644
@@ -286,6 +286,10 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
 			fi->i_btime.tv_sec = sx->btime.tv_sec;
 			fi->i_btime.tv_nsec = sx->btime.tv_nsec;
 		}
+
+		fi->statx_attributes = fuse_statx_attributes(inode, sx);
+		fi->statx_attributes_mask = fuse_statx_attributes_mask(inode,
+								       sx);
 	}
 
 	if (attr->blksize)
#23 lore raw

Re: [PATCH 3/5] fuse: implement file attributes mask for statx

Quoted 16 lines
fs/fuse/fuse_i.h +4 -0
index a8068bee90af57..8c47d103c8ffa6 100644
@@ -140,6 +140,10 @@ struct fuse_inode {
        /** Version of last attribute change */
        u64 attr_version;
 
+       /** statx file attributes */
+       u64 statx_attributes;
+       u64 statx_attributes_mask;
+
        union {
                /* read/write io cache (regular file only) */
                struct {

fs/fuse/fuse_i.h void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr, · line 1248

Quoted 10 lines
fs/fuse/fuse_i.h +7 -0
@@ -1235,6 +1239,39 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
                                   u64 attr_valid, u32 cache_mask,
                                   u64 evict_ctr);
 
+/*
+ * These statx attribute flags are set by the VFS so mask them out of replies
+ * from the fuse server for local filesystems.  Nonlocal filesystems are
+ * responsible for enforcing and advertising these flags themselves.
+ */
+#define FUSE_STATX_LOCAL_VFS_ATTRIBUTES (STATX_ATTR_IMMUTABLE | \
+                                        STATX_ATTR_APPEND)

for STATX_ATTR_IMMUTABLE and STATX_ATTR_APPEND, I see in generic_fill_statx_attr() that they get set if the inode has the S_IMMUTABLE flag and the S_APPEND flag set, but I'm not seeing how this is relevant to fuse. I'm not seeing anywhere in the vfs layer that sets S_APPEND or STATX_ATTR_IMMUTABLE, I only see specific filesystems setting them, which fuse doesn't do. Is there something I'm missing?

Thanks,
Joanne

#24 lore raw

Re: [PATCH 3/5] fuse: implement file attributes mask for statx

Quoted 20 lines · Joanne Koong
Quoted 20 lines
fs/fuse/fuse_i.h +4 -0
index a8068bee90af57..8c47d103c8ffa6 100644
@@ -140,6 +140,10 @@ struct fuse_inode {
        /** Version of last attribute change */
        u64 attr_version;
 
+       /** statx file attributes */
+       u64 statx_attributes;
+       u64 statx_attributes_mask;
+
        union {
                /* read/write io cache (regular file only) */
                struct {
@@ -1235,6 +1239,39 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
                                   u64 attr_valid, u32 cache_mask,
                                   u64 evict_ctr);
 
Quoted 15 lines

fs/fuse/fuse_i.h void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr, · line 1248

Quoted 7 lines
fs/fuse/fuse_i.h +7 -0
+/*
+ * These statx attribute flags are set by the VFS so mask them out of replies
+ * from the fuse server for local filesystems.  Nonlocal filesystems are
+ * responsible for enforcing and advertising these flags themselves.
+ */
+#define FUSE_STATX_LOCAL_VFS_ATTRIBUTES (STATX_ATTR_IMMUTABLE | \
+                                        STATX_ATTR_APPEND)

for STATX_ATTR_IMMUTABLE and STATX_ATTR_APPEND, I see in generic_fill_statx_attr() that they get set if the inode has the S_IMMUTABLE flag and the S_APPEND flag set, but I'm not seeing how this is relevant to fuse. I'm not seeing anywhere in the vfs layer that sets S_APPEND or STATX_ATTR_IMMUTABLE, I only see specific filesystems setting them, which fuse doesn't do. Is there something I'm missing?

Ok, I see. In patchset 6/8 patch 3/9 [1], FUSE_ATTR_SYNC/FUSE_ATTR_IMMUTABLE/FUSE_ATTR_APPEND flags get added which signify that S_SYNC/S_IMMUTABLE/S_APPEND should get set on the inode. Hmm I'm confused why we would want to mask them out for local filesystems. If FUSE_ATTR_SYNC/FUSE_ATTR_IMMUTABLE/FUSE_ATTR_APPEND are getting passed in by the fuse server and getting enforced, why don't we want them to show up in stax?

Thanks,
Joanne

[1] https://lore.kernel.org/linux-fsdevel/176169811656.1426244.11474449087922753694.stgit@frogsfrogsfrogs/

Quoted 3 lines

Thanks,
Joanne

#25 lore raw

Re: [PATCH 3/5] fuse: implement file attributes mask for statx

Quoted 37 lines · Joanne Koong
Quoted 20 lines · Joanne Koong
Quoted 20 lines
fs/fuse/fuse_i.h +4 -0
index a8068bee90af57..8c47d103c8ffa6 100644
@@ -140,6 +140,10 @@ struct fuse_inode {
        /** Version of last attribute change */
        u64 attr_version;
 
+       /** statx file attributes */
+       u64 statx_attributes;
+       u64 statx_attributes_mask;
+
        union {
                /* read/write io cache (regular file only) */
                struct {
@@ -1235,6 +1239,39 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
                                   u64 attr_valid, u32 cache_mask,
                                   u64 evict_ctr);
 
Quoted 15 lines

fs/fuse/fuse_i.h void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr, · line 1248

Quoted 7 lines
fs/fuse/fuse_i.h +7 -0
+/*
+ * These statx attribute flags are set by the VFS so mask them out of replies
+ * from the fuse server for local filesystems.  Nonlocal filesystems are
+ * responsible for enforcing and advertising these flags themselves.
+ */
+#define FUSE_STATX_LOCAL_VFS_ATTRIBUTES (STATX_ATTR_IMMUTABLE | \
+                                        STATX_ATTR_APPEND)

for STATX_ATTR_IMMUTABLE and STATX_ATTR_APPEND, I see in generic_fill_statx_attr() that they get set if the inode has the S_IMMUTABLE flag and the S_APPEND flag set, but I'm not seeing how this is relevant to fuse. I'm not seeing anywhere in the vfs layer that sets S_APPEND or STATX_ATTR_IMMUTABLE, I only see specific filesystems setting them, which fuse doesn't do. Is there something I'm missing?

Quoted 3 lines

Ok, I see. In patchset 6/8 patch 3/9 [1], FUSE_ATTR_SYNC/FUSE_ATTR_IMMUTABLE/FUSE_ATTR_APPEND flags get added which signify that S_SYNC/S_IMMUTABLE/S_APPEND should get set on the

<nod> Originally I was going to hide /all/ of this behind the per-fuse_inode iomap flag, but the Miklos and I started talking about having a separate "behaves like local fs" flag for a few things so that non-iomap fuseblk servers could take advantage of them too. Right now it's limited to these vfs inode flags and the posix acl transformation functions since the assumption is that a regular fuse server either does the transformations on its own or forwards the request to a remote node which (presumably if it cares) does the transformation on its own.

Quoted 4 lines

inode. Hmm I'm confused why we would want to mask them out for local filesystems. If FUSE_ATTR_SYNC/FUSE_ATTR_IMMUTABLE/FUSE_ATTR_APPEND are getting passed in by the fuse server and getting enforced, why don't we want them to show up in stax?

We do, but the VFS sets those statx flags for us:
https://elixir.bootlin.com/linux/v6.17.7/source/fs/stat.c#L124

--D

Quoted 7 lines

Thanks,
Joanne

[1] https://lore.kernel.org/linux-fsdevel/176169811656.1426244.11474449087922753694.stgit@frogsfrogsfrogs/

Quoted 3 lines

Thanks,
Joanne

#26 lore raw

PATCH 4/5 fuse: update file mode when updating acls

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

If someone sets ACLs on a file that can be expressed fully as Unix DAC mode bits, most local filesystems will then update the mode bits and drop the ACL xattr to reduce inefficiency in the file access paths. Let's do that too. Note that means that we can setacl and end up with no ACL xattrs, so we also need to tolerate ENODATA returns from fuse_removexattr.

Note that here we define a "local" fuse filesystem as one that uses fuseblk mode; we'll shortly add fuse servers that use iomap for the file IO path to that list.

---
 fs/fuse/fuse_i.h |    2 +-
 fs/fuse/acl.c    |   43 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 43 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +1 -1
index 8c47d103c8ffa6..d550937770e16e 100644
@@ -1050,7 +1050,7 @@ static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
 	return get_fuse_mount_super(inode->i_sb);
 }
 
-static inline struct fuse_conn *get_fuse_conn(struct inode *inode)
+static inline struct fuse_conn *get_fuse_conn(const struct inode *inode)
 {
 	return get_fuse_mount_super(inode->i_sb)->fc;
 }
fs/fuse/acl.c +42 -1

73 lines not on this page · raw message

#27 lore raw

Re: [PATCH 4/5] fuse: update file mode when updating acls

Quoted 70 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

If someone sets ACLs on a file that can be expressed fully as Unix DAC mode bits, most local filesystems will then update the mode bits and drop the ACL xattr to reduce inefficiency in the file access paths. Let's do that too. Note that means that we can setacl and end up with no ACL xattrs, so we also need to tolerate ENODATA returns from fuse_removexattr.

Note that here we define a "local" fuse filesystem as one that uses fuseblk mode; we'll shortly add fuse servers that use iomap for the file IO path to that list.

---
 fs/fuse/fuse_i.h |    2 +-
 fs/fuse/acl.c    |   43 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 43 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +1 -1
index 8c47d103c8ffa6..d550937770e16e 100644
@@ -1050,7 +1050,7 @@ static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
        return get_fuse_mount_super(inode->i_sb);
 }
 
-static inline struct fuse_conn *get_fuse_conn(struct inode *inode)
+static inline struct fuse_conn *get_fuse_conn(const struct inode *inode)
 {
        return get_fuse_mount_super(inode->i_sb)->fc;
 }
fs/fuse/acl.c +14 -0
index 8f484b105f13ab..72bb4c94079b7b 100644
@@ -11,6 +11,18 @@
 #include <linux/posix_acl.h>
 #include <linux/posix_acl_xattr.h>
 
+/*
+ * If this fuse server behaves like a local filesystem, we can implement the
+ * kernel's optimizations for ACLs for local filesystems instead of passing
+ * the ACL requests straight through to another server.
+ */
+static inline bool fuse_inode_has_local_acls(const struct inode *inode)
+{
+       const struct fuse_conn *fc = get_fuse_conn(inode);
+
+       return fc->posix_acl && fuse_inode_is_exclusive(inode);
+}
+
 static struct posix_acl *__fuse_get_acl(struct fuse_conn *fc,
                                        struct inode *inode, int type, bool rcu)
 {
@@ -98,6 +110,7 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
        struct inode *inode = d_inode(dentry);
        struct fuse_conn *fc = get_fuse_conn(inode);
        const char *name;
+       umode_t mode = inode->i_mode;
        int ret;
 
        if (fuse_is_bad(inode))
@@ -113,6 +126,18 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
        else
                return -EINVAL;
 
+       /*

fs/fuse/acl.c int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry, · line 139

Quoted 10 lines
fs/fuse/acl.c +10 -0
+        * If the ACL can be represented entirely with changes to the mode
+        * bits, then most filesystems will update the mode bits and delete
+        * the ACL xattr.
+        */
+       if (acl && type == ACL_TYPE_ACCESS &&
+           fuse_inode_has_local_acls(inode)) {
+               ret = posix_acl_update_mode(idmap, inode, &mode, &acl);
+               if (ret)
+                       return ret;
+       }

nit: this could be inside the if (acl) block below.

I'm not too familiar with ACLs so i'll abstain from adding my Reviewed-by to this.

Thanks,
Joanne

Quoted 37 lines
fs/fuse/acl.c +18 -1
+
        if (acl) {
                unsigned int extra_flags = 0;
                /*
@@ -143,7 +168,7 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
                 * through POSIX ACLs. Such daemons don't expect setgid bits to
                 * be stripped.
                 */
-               if (fc->posix_acl &&
+               if (fc->posix_acl && mode == inode->i_mode &&
                    !in_group_or_capable(idmap, inode,
                                         i_gid_into_vfsgid(idmap, inode)))
                        extra_flags |= FUSE_SETXATTR_ACL_KILL_SGID;
@@ -152,6 +177,22 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
                kfree(value);
        } else {
                ret = fuse_removexattr(inode, name);
+               /* If the acl didn't exist to start with that's fine. */
+               if (ret == -ENODATA)
+                       ret = 0;
+       }
+
+       /* If we scheduled a mode update above, push that to userspace now. */
+       if (!ret) {
+               struct iattr attr = { };
+
+               if (mode != inode->i_mode) {
+                       attr.ia_valid |= ATTR_MODE;
+                       attr.ia_mode = mode;
+               }
+
+               if (attr.ia_valid)
+                       ret = fuse_do_setattr(idmap, dentry, &attr, NULL);
        }
 
        if (fc->posix_acl) {
#28 lore raw

Re: [PATCH 4/5] fuse: update file mode when updating acls

Quoted 84 lines · Joanne Koong
Quoted 70 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

If someone sets ACLs on a file that can be expressed fully as Unix DAC mode bits, most local filesystems will then update the mode bits and drop the ACL xattr to reduce inefficiency in the file access paths. Let's do that too. Note that means that we can setacl and end up with no ACL xattrs, so we also need to tolerate ENODATA returns from fuse_removexattr.

Note that here we define a "local" fuse filesystem as one that uses fuseblk mode; we'll shortly add fuse servers that use iomap for the file IO path to that list.

---
 fs/fuse/fuse_i.h |    2 +-
 fs/fuse/acl.c    |   43 ++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 43 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +1 -1
index 8c47d103c8ffa6..d550937770e16e 100644
@@ -1050,7 +1050,7 @@ static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
        return get_fuse_mount_super(inode->i_sb);
 }
 
-static inline struct fuse_conn *get_fuse_conn(struct inode *inode)
+static inline struct fuse_conn *get_fuse_conn(const struct inode *inode)
 {
        return get_fuse_mount_super(inode->i_sb)->fc;
 }
fs/fuse/acl.c +14 -0
index 8f484b105f13ab..72bb4c94079b7b 100644
@@ -11,6 +11,18 @@
 #include <linux/posix_acl.h>
 #include <linux/posix_acl_xattr.h>
 
+/*
+ * If this fuse server behaves like a local filesystem, we can implement the
+ * kernel's optimizations for ACLs for local filesystems instead of passing
+ * the ACL requests straight through to another server.
+ */
+static inline bool fuse_inode_has_local_acls(const struct inode *inode)
+{
+       const struct fuse_conn *fc = get_fuse_conn(inode);
+
+       return fc->posix_acl && fuse_inode_is_exclusive(inode);
+}
+
 static struct posix_acl *__fuse_get_acl(struct fuse_conn *fc,
                                        struct inode *inode, int type, bool rcu)
 {
@@ -98,6 +110,7 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
        struct inode *inode = d_inode(dentry);
        struct fuse_conn *fc = get_fuse_conn(inode);
        const char *name;
+       umode_t mode = inode->i_mode;
        int ret;
 
        if (fuse_is_bad(inode))
@@ -113,6 +126,18 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
        else
                return -EINVAL;
 
+       /*

fs/fuse/acl.c int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry, · line 139

Quoted 10 lines
fs/fuse/acl.c +10 -0
+        * If the ACL can be represented entirely with changes to the mode
+        * bits, then most filesystems will update the mode bits and delete
+        * the ACL xattr.
+        */
+       if (acl && type == ACL_TYPE_ACCESS &&
+           fuse_inode_has_local_acls(inode)) {
+               ret = posix_acl_update_mode(idmap, inode, &mode, &acl);
+               if (ret)
+                       return ret;
+       }

nit: this could be inside the if (acl) block below.

Quoted 2 lines

I'm not too familiar with ACLs so i'll abstain from adding my Reviewed-by to this.

posix_acl_update_mode can set acl to NULL.

--D

Quoted 40 lines

Thanks,
Joanne

Quoted 37 lines
fs/fuse/acl.c +18 -1
+
        if (acl) {
                unsigned int extra_flags = 0;
                /*
@@ -143,7 +168,7 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
                 * through POSIX ACLs. Such daemons don't expect setgid bits to
                 * be stripped.
                 */
-               if (fc->posix_acl &&
+               if (fc->posix_acl && mode == inode->i_mode &&
                    !in_group_or_capable(idmap, inode,
                                         i_gid_into_vfsgid(idmap, inode)))
                        extra_flags |= FUSE_SETXATTR_ACL_KILL_SGID;
@@ -152,6 +177,22 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
                kfree(value);
        } else {
                ret = fuse_removexattr(inode, name);
+               /* If the acl didn't exist to start with that's fine. */
+               if (ret == -ENODATA)
+                       ret = 0;
+       }
+
+       /* If we scheduled a mode update above, push that to userspace now. */
+       if (!ret) {
+               struct iattr attr = { };
+
+               if (mode != inode->i_mode) {
+                       attr.ia_valid |= ATTR_MODE;
+                       attr.ia_mode = mode;
+               }
+
+               if (attr.ia_valid)
+                       ret = fuse_do_setattr(idmap, dentry, &attr, NULL);
        }
 
        if (fc->posix_acl) {
#29 lore raw

PATCH 5/5 fuse: propagate default and file acls on creation

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

For local filesystems, propagate the default and file access ACLs to new children when creating them, just like the other in-kernel local filesystems.

---
 fs/fuse/fuse_i.h |    4 ++
 fs/fuse/acl.c    |   65 ++++++++++++++++++++++++++++++++++++++
 fs/fuse/dir.c    |   92 +++++++++++++++++++++++++++++++++++++++++-------------
 3 files changed, 138 insertions(+), 23 deletions(-)
fs/fuse/fuse_i.h +4 -0
index d550937770e16e..1316c3853f68dc 100644
@@ -1527,6 +1527,10 @@ struct posix_acl *fuse_get_acl(struct mnt_idmap *idmap,
 			       struct dentry *dentry, int type);
 int fuse_set_acl(struct mnt_idmap *, struct dentry *dentry,
 		 struct posix_acl *acl, int type);
+int fuse_acl_create(struct inode *dir, umode_t *mode,
+		    struct posix_acl **default_acl, struct posix_acl **acl);
+int fuse_init_acls(struct inode *inode, const struct posix_acl *default_acl,
+		   const struct posix_acl *acl);
 
 /* readdir.c */
 int fuse_readdir(struct file *file, struct dir_context *ctx);
fs/fuse/acl.c +65 -0

68 lines not on this page · raw message

fs/fuse/dir.c +69 -23

226 lines not on this page · raw message

#30 lore raw

Re: [PATCH 5/5] fuse: propagate default and file acls on creation

Quoted 6 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

For local filesystems, propagate the default and file access ACLs to new children when creating them, just like the other in-kernel local filesystems.

Hi everyone,

I'm trying out my AI review prompts on a few more trees, and I ran it on the fuse-iomap-cache branch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-cache

This was the latest email lore could find, apologies if I grabbed the wrong one.

Hopefully the review below is useful, please let me know if there are places it has gone wildly wrong. I kept the header to make it obvious exactly which commit I'd run through:

commit 72f7e38b8ab1d52b7e44818ba7db9335bc499476
Author: Darrick J. Wong <[email protected]>

fuse: propagate default and file acls on creation

For local filesystems, propagate the default and file access ACLs to new children when creating them, just like the other in-kernel local filesystems.

Quoted 4 lines
fs/fuse/acl.c +0 -0
index 72bb4c94079b7..f2cb7e8db4cad 100644

[ ... ]

Quoted 56 lines
fs/fuse/dir.c +11 -5
index b2dd3b189246e..3af81a063cc50 100644
@@ -821,26 +821,28 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 	struct fuse_entry_out outentry;
 	struct fuse_inode *fi;
 	struct fuse_file *ff;
+	struct posix_acl *default_acl = NULL, *acl = NULL;
 	int epoch, err;
 	bool trunc = flags & O_TRUNC;
 
 	/* Userspace expects S_IFREG in create mode */
 	BUG_ON((mode & S_IFMT) != S_IFREG);
 
+	err = fuse_acl_create(dir, &mode, &default_acl, &acl);
+	if (err)
+		return err;
+
 	epoch = atomic_read(&fm->fc->epoch);
 	forget = fuse_alloc_forget();
 	err = -ENOMEM;
 	if (!forget)
-		goto out_err;
+		goto out_acl_release;
 
 	err = -ENOMEM;
 	ff = fuse_file_alloc(fm, true);
 	if (!ff)
 		goto out_put_forget_req;
 
-	if (!fm->fc->dont_mask)
-		mode &= ~current_umask();
-
 	flags &= ~O_NOCTTY;
 	memset(&inarg, 0, sizeof(inarg));
 	memset(&outentry, 0, sizeof(outentry));
@@ -892,12 +894,16 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 		fuse_sync_release(NULL, ff, flags);
 		fuse_queue_forget(fm->fc, forget, outentry.nodeid, 1);
 		err = -ENOMEM;
-		goto out_err;
+		goto out_acl_release;
 	}
 	kfree(forget);
 	d_instantiate(entry, inode);
 	entry->d_time = epoch;
 	fuse_change_entry_timeout(entry, &outentry);
+
+	err = fuse_init_acls(inode, default_acl, acl);
+	if (err)
+		goto out_acl_release;
 	fuse_dir_changed(dir);
 	err = generic_file_open(inode, file);
 	if (!err) {

fs/fuse/dir.c static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir, · line 932

Quoted 9 lines
fs/fuse/dir.c +3 -1
@@ -919,7 +925,9 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 	fuse_file_free(ff);
 out_put_forget_req:
 	kfree(forget);
-out_err:
+out_acl_release:
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return err;
 }

Does this leak the ACL pointers on the success path? When fuse_acl_create() allocates non-NULL ACLs (occurs when IS_POSIXACL(dir) && fuse_inode_has_local_acls(dir) and the parent directory has default ACLs), and the file creation succeeds, the function returns directly at 'return err;' without releasing the ACLs via posix_acl_release().

The cleanup at out_acl_release is only reached on error paths. This would leak the posix_acl structures on every successful file creation when local ACLs are enabled.

Compare with create_new_entry() which correctly calls posix_acl_release() on both success and error paths (lines 1056-1057 and 1065-1066).

Quoted 46 lines
fs/fuse/dir.c +17 -5
@@ -979,14 +989,18 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 	struct fuse_forget_link *forget;
 	int epoch, err;
 
-	if (fuse_is_bad(dir))
-		return ERR_PTR(-EIO);
+	if (fuse_is_bad(dir)) {
+		err = -EIO;
+		goto out_acl_release;
+	}
 
 	epoch = atomic_read(&fm->fc->epoch);
 
 	forget = fuse_alloc_forget();
-	if (!forget)
-		return ERR_PTR(-ENOMEM);
+	if (!forget) {
+		err = -ENOMEM;
+		goto out_acl_release;
+	}
 
 	memset(&outarg, 0, sizeof(outarg));
 	args->nodeid = get_node_id(dir);
@@ -1016,7 +1030,8 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 			  &outarg.attr, ATTR_TIMEOUT(&outarg), 0, 0);
 	if (!inode) {
 		fuse_queue_forget(fm->fc, forget, outentry.nodeid, 1);
-		return ERR_PTR(-ENOMEM);
+		err = -ENOMEM;
+		goto out_acl_release;
 	}
 	kfree(forget);
 
@@ -1032,19 +1047,31 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 		entry->d_time = epoch;
 		fuse_change_entry_timeout(entry, &outarg);
 	}
+
+	err = fuse_init_acls(inode, default_acl, acl);
+	if (err)
+		goto out_acl_release;
 	fuse_dir_changed(dir);
+
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return d;

fs/fuse/dir.c static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun · line 1068

Quoted 10 lines
fs/fuse/dir.c +3 -0
 
 out_put_forget_req:
 	if (err == -EEXIST)
 		fuse_invalidate_entry(entry);
 	kfree(forget);
+ out_acl_release:
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return ERR_PTR(err);
 }

Chen Linxuan raised a concern in v5 about pairing fuse_acl_create and posix_acl_release together. While the author's response explained the design choice to have create_new_entry consume the ACL arguments, there is a memory leak when d_splice_alias returns an error:

fs/fuse/dir.c static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun · line 1071

Quoted 3 lines
fs/fuse/dir.c +0 -0
 		d = d_splice_alias(inode, entry);
 		if (IS_ERR(d))
 			return d;

The function returns ERR_PTR without releasing the ACL pointers. The normal path (lines 1056-1057) and error path (lines 1065-1066) both release ACLs, but the IS_ERR(d) path at line 1041 does not.

https://lore.kernel.org/all/CAC1kPDOv4sy3NPexFtdoROFi18b98W+PbP+9t8y4Jd5fQqCxCg@mail.gmail.com/

[ ... ]

#31 lore raw

Re: [PATCH 5/5] fuse: propagate default and file acls on creation

Quoted 8 lines · Chris Mason
Quoted 6 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

For local filesystems, propagate the default and file access ACLs to new children when creating them, just like the other in-kernel local filesystems.

Quoted 6 lines

Hi everyone,

I'm trying out my AI review prompts on a few more trees, and I ran it on the fuse-iomap-cache branch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-cache

Yessss some detailed review! For the first time in my Linux career I'm getting patch feedback before the patches are even posted!

So, thank you! :D

Quoted 94 lines

This was the latest email lore could find, apologies if I grabbed the wrong one.

Hopefully the review below is useful, please let me know if there are places it has gone wildly wrong. I kept the header to make it obvious exactly which commit I'd run through:

commit 72f7e38b8ab1d52b7e44818ba7db9335bc499476
Author: Darrick J. Wong <[email protected]>

fuse: propagate default and file acls on creation

For local filesystems, propagate the default and file access ACLs to new children when creating them, just like the other in-kernel local filesystems.

Quoted 4 lines
fs/fuse/acl.c +0 -0
index 72bb4c94079b7..f2cb7e8db4cad 100644

[ ... ]

Quoted 56 lines
fs/fuse/dir.c +11 -5
index b2dd3b189246e..3af81a063cc50 100644
@@ -821,26 +821,28 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 	struct fuse_entry_out outentry;
 	struct fuse_inode *fi;
 	struct fuse_file *ff;
+	struct posix_acl *default_acl = NULL, *acl = NULL;
 	int epoch, err;
 	bool trunc = flags & O_TRUNC;
 
 	/* Userspace expects S_IFREG in create mode */
 	BUG_ON((mode & S_IFMT) != S_IFREG);
 
+	err = fuse_acl_create(dir, &mode, &default_acl, &acl);
+	if (err)
+		return err;
+
 	epoch = atomic_read(&fm->fc->epoch);
 	forget = fuse_alloc_forget();
 	err = -ENOMEM;
 	if (!forget)
-		goto out_err;
+		goto out_acl_release;
 
 	err = -ENOMEM;
 	ff = fuse_file_alloc(fm, true);
 	if (!ff)
 		goto out_put_forget_req;
 
-	if (!fm->fc->dont_mask)
-		mode &= ~current_umask();
-
 	flags &= ~O_NOCTTY;
 	memset(&inarg, 0, sizeof(inarg));
 	memset(&outentry, 0, sizeof(outentry));
@@ -892,12 +894,16 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 		fuse_sync_release(NULL, ff, flags);
 		fuse_queue_forget(fm->fc, forget, outentry.nodeid, 1);
 		err = -ENOMEM;
-		goto out_err;
+		goto out_acl_release;
 	}
 	kfree(forget);
 	d_instantiate(entry, inode);
 	entry->d_time = epoch;
 	fuse_change_entry_timeout(entry, &outentry);
+
+	err = fuse_init_acls(inode, default_acl, acl);
+	if (err)
+		goto out_acl_release;
 	fuse_dir_changed(dir);
 	err = generic_file_open(inode, file);
 	if (!err) {

fs/fuse/dir.c static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir, · line 932

Quoted 9 lines
fs/fuse/dir.c +3 -1
@@ -919,7 +925,9 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 	fuse_file_free(ff);
 out_put_forget_req:
 	kfree(forget);
-out_err:
+out_acl_release:
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return err;
 }

Does this leak the ACL pointers on the success path? When fuse_acl_create() allocates non-NULL ACLs (occurs when IS_POSIXACL(dir) && fuse_inode_has_local_acls(dir) and the parent directory has default ACLs), and the file creation succeeds, the function returns directly at 'return err;' without releasing the ACLs via posix_acl_release().

Quoted 6 lines

The cleanup at out_acl_release is only reached on error paths. This would leak the posix_acl structures on every successful file creation when local ACLs are enabled.

Compare with create_new_entry() which correctly calls posix_acl_release() on both success and error paths (lines 1056-1057 and 1065-1066).

Oh, yeah, that is a pretty stupid memory leak, thanks for catching it.

Quoted 66 lines
Quoted 46 lines
fs/fuse/dir.c +17 -5
@@ -979,14 +989,18 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 	struct fuse_forget_link *forget;
 	int epoch, err;
 
-	if (fuse_is_bad(dir))
-		return ERR_PTR(-EIO);
+	if (fuse_is_bad(dir)) {
+		err = -EIO;
+		goto out_acl_release;
+	}
 
 	epoch = atomic_read(&fm->fc->epoch);
 
 	forget = fuse_alloc_forget();
-	if (!forget)
-		return ERR_PTR(-ENOMEM);
+	if (!forget) {
+		err = -ENOMEM;
+		goto out_acl_release;
+	}
 
 	memset(&outarg, 0, sizeof(outarg));
 	args->nodeid = get_node_id(dir);
@@ -1016,7 +1030,8 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 			  &outarg.attr, ATTR_TIMEOUT(&outarg), 0, 0);
 	if (!inode) {
 		fuse_queue_forget(fm->fc, forget, outentry.nodeid, 1);
-		return ERR_PTR(-ENOMEM);
+		err = -ENOMEM;
+		goto out_acl_release;
 	}
 	kfree(forget);
 
@@ -1032,19 +1047,31 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 		entry->d_time = epoch;
 		fuse_change_entry_timeout(entry, &outarg);
 	}
+
+	err = fuse_init_acls(inode, default_acl, acl);
+	if (err)
+		goto out_acl_release;
 	fuse_dir_changed(dir);
+
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return d;

fs/fuse/dir.c static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun · line 1068

Quoted 10 lines
fs/fuse/dir.c +3 -0
 
 out_put_forget_req:
 	if (err == -EEXIST)
 		fuse_invalidate_entry(entry);
 	kfree(forget);
+ out_acl_release:
+	posix_acl_release(default_acl);
+	posix_acl_release(acl);
 	return ERR_PTR(err);
 }

Chen Linxuan raised a concern in v5 about pairing fuse_acl_create and posix_acl_release together. While the author's response explained the design choice to have create_new_entry consume the ACL arguments, there is a memory leak when d_splice_alias returns an error:

fs/fuse/dir.c static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun · line 1071

Quoted 3 lines
fs/fuse/dir.c +0 -0
 		d = d_splice_alias(inode, entry);
 		if (IS_ERR(d))
 			return d;
Quoted 5 lines

The function returns ERR_PTR without releasing the ACL pointers. The normal path (lines 1056-1057) and error path (lines 1065-1066) both release ACLs, but the IS_ERR(d) path at line 1041 does not.

https://lore.kernel.org/all/CAC1kPDOv4sy3NPexFtdoROFi18b98W+PbP+9t8y4Jd5fQqCxCg@mail.gmail.com/

Whoops. Also a good catch; I'll change that to:

	d = d_splice_alias(inode, entry);
	if (IS_ERR(d)) {
		err = PTR_ERR(d);
		goto out_acl_release;
	}

--D

Quoted 3 lines

[ ... ]

#32 lore raw

PATCH v6 2/8 iomap: cleanups ahead of adding fuse support

In reply to Darrick J. Wong

Hi all,

In preparation for making fuse use the fs/iomap code for regular file data IO, fix a few bugs in fuse and apply a couple of tweaks to iomap. These patches can go in immediately.

If you're going to start using this code, I strongly recommend pulling from my git trees, which are linked below.

This has been running on the djcloud for months with no problems. Enjoy! Comments and questions are, as always, welcome.

--D

kernel git tree:
https://git.kernel.org/cgit/linux/kernel/git/djwong/xfs-linux.git/log/?h=iomap-fuse-prep
---
Commits in this patchset:
* iomap: allow NULL swap info bdev when activating swapfile

---
 fs/iomap/swapfile.c |   17 +++++++++++++++++
 1 file changed, 17 insertions(+)
#33 lore raw

PATCH 1/1 iomap: allow NULL swap info bdev when activating swapfile

From: Darrick J. Wong <[email protected]>

All current users of the iomap swapfile activation mechanism are block device filesystems. This means that claim_swapfile will set swap_info_struct::bdev to inode->i_sb->s_bdev of the swap file.

However, in the future there could be fuse+iomap filesystems that are block device based but don't set s_bdev. In this case, sis::bdev will be set to NULL when we enter iomap_swapfile_activate, and we can pick up a bdev from the first iomap mapping that the filesystem provides.

To make this work robustly, we must explicitly check that each mapping provides a bdev and that there's no way we can succeed at collecting swapfile pages without a block device.

---
 fs/iomap/swapfile.c |   17 +++++++++++++++++
 1 file changed, 17 insertions(+)
fs/iomap/swapfile.c +17 -0
index 0db77c449467a7..9d9f4e84437df5 100644
@@ -112,6 +112,13 @@ static int iomap_swapfile_iter(struct iomap_iter *iter,
 	if (iomap->flags & IOMAP_F_SHARED)
 		return iomap_swapfile_fail(isi, "has shared extents");
 
+	/* Swapfiles must be backed by a block device */
+	if (!iomap->bdev)
+		return iomap_swapfile_fail(isi, "is not on a block device");
+
+	if (iter->pos == 0 && !isi->sis->bdev)
+		isi->sis->bdev = iomap->bdev;
+
 	/* Only one bdev per swap file. */
 	if (iomap->bdev != isi->sis->bdev)
 		return iomap_swapfile_fail(isi, "outside the main device");
@@ -184,6 +191,16 @@ int iomap_swapfile_activate(struct swap_info_struct *sis,
 		return -EINVAL;
 	}
 
+	/*
+	 * If this swapfile doesn't have a block device, reject this useless
+	 * swapfile to prevent confusion later on.
+	 */
+	if (sis->bdev == NULL) {
+		pr_warn(
+ "swapon: No block device for swap file but usage pages?!\n");
+		return -EINVAL;
+	}
+
 	*pagespan = 1 + isi.highest_ppage - isi.lowest_ppage;
 	sis->max = isi.nr_pages;
 	sis->pages = isi.nr_pages - 1;
#34 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 10 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

All current users of the iomap swapfile activation mechanism are block device filesystems. This means that claim_swapfile will set swap_info_struct::bdev to inode->i_sb->s_bdev of the swap file.

However, in the future there could be fuse+iomap filesystems that are block device based but don't set s_bdev. In this case, sis::bdev will be set to NULL when we enter iomap_swapfile_activate, and we can pick up a bdev from the first iomap mapping that the filesystem provides.

Could, or will be? I find the way the swapfiles work right now disgusting to start with, but extending that bypass to fuse seems even worse.

#35 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 7 lines · Christoph Hellwig
Quoted 6 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

All current users of the iomap swapfile activation mechanism are block device filesystems. This means that claim_swapfile will set swap_info_struct::bdev to inode->i_sb->s_bdev of the swap file.

Quoted 8 lines
Quoted 4 lines

However, in the future there could be fuse+iomap filesystems that are block device based but don't set s_bdev. In this case, sis::bdev will be set to NULL when we enter iomap_swapfile_activate, and we can pick up a bdev from the first iomap mapping that the filesystem provides.

Could, or will be? I find the way the swapfiles work right now disgusting to start with, but extending that bypass to fuse seems even worse.

Yes, "Could", in the sense that a subsequent fuse patch wires up sending FUSE_IOMAP_BEGIN to the fuse server to ask for layouts for swapfiles, and the fuse server can reply with a mapping or EOPNOTSUPP to abort the swapon. (There's a separate FUSE_IOMAP_IOEND req at deactivation time).

"Already does" in the sense that fuse already supports swapfiles(!) if your filesystem implements FUSE_BMAP and attaches via fuseblk (aka ntfs3g).

--D

#36 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 5 lines · Darrick J. Wong
Quoted 5 lines
Quoted 4 lines

However, in the future there could be fuse+iomap filesystems that are block device based but don't set s_bdev. In this case, sis::bdev will be set to NULL when we enter iomap_swapfile_activate, and we can pick up a bdev from the first iomap mapping that the filesystem provides.

Quoted 8 lines
Quoted 3 lines

Could, or will be? I find the way the swapfiles work right now disgusting to start with, but extending that bypass to fuse seems even worse.

Yes, "Could", in the sense that a subsequent fuse patch wires up sending FUSE_IOMAP_BEGIN to the fuse server to ask for layouts for swapfiles, and the fuse server can reply with a mapping or EOPNOTSUPP to abort the swapon. (There's a separate FUSE_IOMAP_IOEND req at deactivation time).

Maybe spell that out.

Quoted 3 lines

"Already does" in the sense that fuse already supports swapfiles(!) if your filesystem implements FUSE_BMAP and attaches via fuseblk (aka ntfs3g).

Yikes. This is just such an amazingly bad idea.

#37 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 10 lines · Christoph Hellwig
Quoted 9 lines · Darrick J. Wong
Quoted 8 lines
Quoted 4 lines

However, in the future there could be fuse+iomap filesystems that are block device based but don't set s_bdev. In this case, sis::bdev will be set to NULL when we enter iomap_swapfile_activate, and we can pick up a bdev from the first iomap mapping that the filesystem provides.

Could, or will be? I find the way the swapfiles work right now disgusting to start with, but extending that bypass to fuse seems even worse.

Quoted 6 lines
Quoted 4 lines

Yes, "Could", in the sense that a subsequent fuse patch wires up sending FUSE_IOMAP_BEGIN to the fuse server to ask for layouts for swapfiles, and the fuse server can reply with a mapping or EOPNOTSUPP to abort the swapon. (There's a separate FUSE_IOMAP_IOEND req at deactivation time).

Maybe spell that out.

Will do.

Quoted 5 lines
Quoted 3 lines

"Already does" in the sense that fuse already supports swapfiles(!) if your filesystem implements FUSE_BMAP and attaches via fuseblk (aka ntfs3g).

Yikes. This is just such an amazingly bad idea.

Swapfiles in general (including doing it via iomap)? Or just the magic hooboo of "turn on this fugly bmapping call and bammo the kernel can take over your file at any time!!" ?

--D

#38 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 3 lines · Darrick J. Wong

Swapfiles in general (including doing it via iomap)? Or just the magic hooboo of "turn on this fugly bmapping call and bammo the kernel can take over your file at any time!!" ?

The latter and even more so when the mapping is farmed out to userspace.

#39 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

In reply to Christoph Hellwig
Quoted 6 lines · Christoph Hellwig
Quoted 4 lines

"Already does" in the sense that fuse already supports swapfiles(!) if your filesystem implements FUSE_BMAP and attaches via fuseblk (aka ntfs3g).

Yikes. This is just such an amazingly bad idea.

And even if a fuse does not support swapfiles, "problems in computer science can be solved by another level of indirection". Not that they should - but this sequence succeeds already:

mount -t sshfs root@localhost:/ /mnt
losetup /dev/loop7 /mnt/swapfile
swapon /dev/loop7

#40 lore raw

Re: [PATCH 1/1] iomap: allow NULL swap info bdev when activating swapfile

Quoted 9 lines · Jan Engelhardt
Quoted 6 lines · Christoph Hellwig
Quoted 4 lines

"Already does" in the sense that fuse already supports swapfiles(!) if your filesystem implements FUSE_BMAP and attaches via fuseblk (aka ntfs3g).

Yikes. This is just such an amazingly bad idea.

Quoted 7 lines

And even if a fuse does not support swapfiles, "problems in computer science can be solved by another level of indirection". Not that they should - but this sequence succeeds already:

mount -t sshfs root@localhost:/ /mnt
losetup /dev/loop7 /mnt/swapfile
swapon /dev/loop7

Amazing.

--D

#41 lore raw

PATCH v6 3/8 fuse: cleanups ahead of adding fuse support

In reply to Darrick J. Wong

Hi all,

In preparation for making fuse use the fs/iomap code for regular file data IO, fix a few bugs in fuse and apply a couple of tweaks to iomap.

If you're going to start using this code, I strongly recommend pulling from my git trees, which are linked below.

This has been running on the djcloud for months with no problems. Enjoy! Comments and questions are, as always, welcome.

--D

kernel git tree:
https://git.kernel.org/cgit/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-prep
---
Commits in this patchset:
* fuse: move the passthrough-specific code back to passthrough.c
* fuse_trace: move the passthrough-specific code back to passthrough.c

---
 fs/fuse/fuse_i.h          |   25 ++++++++++-
 fs/fuse/fuse_trace.h      |   35 ++++++++++++++++
 include/uapi/linux/fuse.h |    8 +++-
 fs/fuse/Kconfig           |    4 ++
 fs/fuse/Makefile          |    3 +
 fs/fuse/backing.c         |  101 ++++++++++++++++++++++++++++++++++-----------
 fs/fuse/dev.c             |    4 +-
 fs/fuse/inode.c           |    4 +-
 fs/fuse/passthrough.c     |   38 ++++++++++++++++-
 9 files changed, 188 insertions(+), 34 deletions(-)
#42 lore raw

PATCH 1/2 fuse: move the passthrough-specific code back to passthrough.c

From: Darrick J. Wong <[email protected]>

In preparation for iomap, move the passthrough-specific validation code back to passthrough.c and create a new Kconfig item for conditional compilation of backing.c. In the next patch, iomap will share the backing structures.

---
 fs/fuse/fuse_i.h          |   25 ++++++++++-
 include/uapi/linux/fuse.h |    8 +++-
 fs/fuse/Kconfig           |    4 ++
 fs/fuse/Makefile          |    3 +
 fs/fuse/backing.c         |   98 ++++++++++++++++++++++++++++++++++-----------
 fs/fuse/dev.c             |    4 +-
 fs/fuse/inode.c           |    4 +-
 fs/fuse/passthrough.c     |   38 +++++++++++++++++
 8 files changed, 149 insertions(+), 35 deletions(-)
fs/fuse/fuse_i.h +22 -3
index 1316c3853f68dc..7c7d255d817f1e 100644
@@ -96,10 +96,23 @@ struct fuse_submount_lookup {
 	struct fuse_forget_link *forget;
 };
 
+struct fuse_conn;
+
+/** Operations for subsystems that want to use a backing file */
+struct fuse_backing_ops {
+	int (*may_admin)(struct fuse_conn *fc, uint32_t flags);
+	int (*may_open)(struct fuse_conn *fc, struct file *file);
+	int (*may_close)(struct fuse_conn *fc, struct file *file);
+	unsigned int type;
+	int id_start;
+	int id_end;
+};
+
 /** Container for data related to mapping to backing file */
 struct fuse_backing {
 	struct file *file;
 	struct cred *cred;
+	const struct fuse_backing_ops *ops;
 
 	/** refcount */
 	refcount_t count;
@@ -972,7 +985,7 @@ struct fuse_conn {
 	/* New writepages go into this bucket */
 	struct fuse_sync_bucket __rcu *curr_bucket;
 
-#ifdef CONFIG_FUSE_PASSTHROUGH
+#ifdef CONFIG_FUSE_BACKING
 	/** IDR for backing files ids */
 	struct idr backing_files_map;
 #endif
@@ -1588,10 +1601,12 @@ void fuse_file_release(struct inode *inode, struct fuse_file *ff,
 		       unsigned int open_flags, fl_owner_t id, bool isdir);
 
 /* backing.c */
-#ifdef CONFIG_FUSE_PASSTHROUGH
+#ifdef CONFIG_FUSE_BACKING
 struct fuse_backing *fuse_backing_get(struct fuse_backing *fb);
 void fuse_backing_put(struct fuse_backing *fb);
-struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc, int backing_id);
+struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc,
+					 const struct fuse_backing_ops *ops,
+					 int backing_id);
 #else
 
 static inline struct fuse_backing *fuse_backing_get(struct fuse_backing *fb)
@@ -1646,6 +1661,10 @@ static inline struct file *fuse_file_passthrough(struct fuse_file *ff)
 #endif
 }
 
+#ifdef CONFIG_FUSE_PASSTHROUGH
+extern const struct fuse_backing_ops fuse_passthrough_backing_ops;
+#endif
+
 ssize_t fuse_passthrough_read_iter(struct kiocb *iocb, struct iov_iter *iter);
 ssize_t fuse_passthrough_write_iter(struct kiocb *iocb, struct iov_iter *iter);
 ssize_t fuse_passthrough_splice_read(struct file *in, loff_t *ppos,
include/uapi/linux/fuse.h +7 -1
index c13e1f9a2f12bd..18713cfaf09171 100644
@@ -1126,9 +1126,15 @@ struct fuse_notify_prune_out {
 	uint64_t	spare;
 };
 
+#define FUSE_BACKING_TYPE_MASK		(0xFF)
+#define FUSE_BACKING_TYPE_PASSTHROUGH	(0)
+#define FUSE_BACKING_MAX_TYPE		(FUSE_BACKING_TYPE_PASSTHROUGH)
+
+#define FUSE_BACKING_FLAGS_ALL		(FUSE_BACKING_TYPE_MASK)
+
 struct fuse_backing_map {
 	int32_t		fd;
-	uint32_t	flags;
+	uint32_t	flags; /* FUSE_BACKING_* */
 	uint64_t	padding;
 };
 
fs/fuse/Kconfig +4 -0
index 3a4ae632c94aa8..290d1c09e0b924 100644
@@ -59,12 +59,16 @@ config FUSE_PASSTHROUGH
 	default y
 	depends on FUSE_FS
 	select FS_STACK
+	select FUSE_BACKING
 	help
 	  This allows bypassing FUSE server by mapping specific FUSE operations
 	  to be performed directly on a backing file.
 
 	  If you want to allow passthrough operations, answer Y.
 
+config FUSE_BACKING
+	bool
+
 config FUSE_IO_URING
 	bool "FUSE communication over io-uring"
 	default y
fs/fuse/Makefile +2 -1
index 22ad9538dfc4b8..46041228e5be2c 100644
@@ -14,7 +14,8 @@ fuse-y := trace.o	# put trace.o first so we see ftrace errors sooner
 fuse-y += dev.o dir.o file.o inode.o control.o xattr.o acl.o readdir.o ioctl.o
 fuse-y += iomode.o
 fuse-$(CONFIG_FUSE_DAX) += dax.o
-fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o backing.o
+fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
+fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
 
fs/fuse/backing.c +73 -25

187 lines not on this page · raw message

fs/fuse/dev.c +2 -2
index ecc0a5304c59d1..12cc673df99151 100644
@@ -2662,7 +2662,7 @@ static long fuse_dev_ioctl_backing_open(struct file *file,
 	if (IS_ERR(fud))
 		return PTR_ERR(fud);
 
-	if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+	if (!IS_ENABLED(CONFIG_FUSE_BACKING))
 		return -EOPNOTSUPP;
 
 	if (copy_from_user(&map, argp, sizeof(map)))
@@ -2679,7 +2679,7 @@ static long fuse_dev_ioctl_backing_close(struct file *file, __u32 __user *argp)
 	if (IS_ERR(fud))
 		return PTR_ERR(fud);
 
-	if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+	if (!IS_ENABLED(CONFIG_FUSE_BACKING))
 		return -EOPNOTSUPP;
 
 	if (get_user(backing_id, argp))
fs/fuse/inode.c +2 -2
index 76e5b7f5c980c2..0cac7164afa298 100644
@@ -1004,7 +1004,7 @@ void fuse_conn_init(struct fuse_conn *fc, struct fuse_mount *fm,
 	fc->name_max = FUSE_NAME_LOW_MAX;
 	fc->timeout.req_timeout = 0;
 
-	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+	if (IS_ENABLED(CONFIG_FUSE_BACKING))
 		fuse_backing_files_init(fc);
 
 	INIT_LIST_HEAD(&fc->mounts);
@@ -1041,7 +1041,7 @@ void fuse_conn_put(struct fuse_conn *fc)
 			WARN_ON(atomic_read(&bucket->count) != 1);
 			kfree(bucket);
 		}
-		if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+		if (IS_ENABLED(CONFIG_FUSE_BACKING))
 			fuse_backing_files_free(fc);
 		call_rcu(&fc->rcu, delayed_release);
 	}
fs/fuse/passthrough.c +37 -1
index 72de97c03d0eeb..e1619bffb5d125 100644
@@ -162,7 +162,7 @@ struct fuse_backing *fuse_passthrough_open(struct file *file, int backing_id)
 		goto out;
 
 	err = -ENOENT;
-	fb = fuse_backing_lookup(fc, backing_id);
+	fb = fuse_backing_lookup(fc, &fuse_passthrough_backing_ops, backing_id);
 	if (!fb)
 		goto out;
 
@@ -195,3 +195,39 @@ void fuse_passthrough_release(struct fuse_file *ff, struct fuse_backing *fb)
 	put_cred(ff->cred);
 	ff->cred = NULL;
 }
+
+static int fuse_passthrough_may_admin(struct fuse_conn *fc, unsigned int flags)
+{
+	/* TODO: relax CAP_SYS_ADMIN once backing files are visible to lsof */
+	if (!fc->passthrough || !capable(CAP_SYS_ADMIN))
+		return -EPERM;
+
+	if (flags)
+		return -EINVAL;
+
+	return 0;
+}
+
+static int fuse_passthrough_may_open(struct fuse_conn *fc, struct file *file)
+{
+	struct super_block *backing_sb;
+	int res;
+
+	/* read/write/splice/mmap passthrough only relevant for regular files */
+	res = d_is_dir(file->f_path.dentry) ? -EISDIR : -EINVAL;
+	if (!d_is_reg(file->f_path.dentry))
+		return res;
+
+	backing_sb = file_inode(file)->i_sb;
+	if (backing_sb->s_stack_depth >= fc->max_stack_depth)
+		return -ELOOP;
+
+	return 0;
+}
+
+const struct fuse_backing_ops fuse_passthrough_backing_ops = {
+	.type = FUSE_BACKING_TYPE_PASSTHROUGH,
+	.id_start = 1,
+	.may_admin = fuse_passthrough_may_admin,
+	.may_open = fuse_passthrough_may_open,
+};
maintainer Reviewed-by on v1 1/2
#43 lore raw

Re: [PATCH 1/2] fuse: move the passthrough-specific code back to passthrough.c

Quoted 9 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

In preparation for iomap, move the passthrough-specific validation code back to passthrough.c and create a new Kconfig item for conditional compilation of backing.c. In the next patch, iomap will share the backing structures.

Quoted 427 lines
---
 fs/fuse/fuse_i.h          |   25 ++++++++++-
 include/uapi/linux/fuse.h |    8 +++-
 fs/fuse/Kconfig           |    4 ++
 fs/fuse/Makefile          |    3 +
 fs/fuse/backing.c         |   98 ++++++++++++++++++++++++++++++++++-----------
 fs/fuse/dev.c             |    4 +-
 fs/fuse/inode.c           |    4 +-
 fs/fuse/passthrough.c     |   38 +++++++++++++++++
 8 files changed, 149 insertions(+), 35 deletions(-)
fs/fuse/fuse_i.h +22 -3
index 1316c3853f68dc..7c7d255d817f1e 100644
@@ -96,10 +96,23 @@ struct fuse_submount_lookup {
        struct fuse_forget_link *forget;
 };
 
+struct fuse_conn;
+
+/** Operations for subsystems that want to use a backing file */
+struct fuse_backing_ops {
+       int (*may_admin)(struct fuse_conn *fc, uint32_t flags);
+       int (*may_open)(struct fuse_conn *fc, struct file *file);
+       int (*may_close)(struct fuse_conn *fc, struct file *file);
+       unsigned int type;
+       int id_start;
+       int id_end;
+};
+
 /** Container for data related to mapping to backing file */
 struct fuse_backing {
        struct file *file;
        struct cred *cred;
+       const struct fuse_backing_ops *ops;
 
        /** refcount */
        refcount_t count;
@@ -972,7 +985,7 @@ struct fuse_conn {
        /* New writepages go into this bucket */
        struct fuse_sync_bucket __rcu *curr_bucket;
 
-#ifdef CONFIG_FUSE_PASSTHROUGH
+#ifdef CONFIG_FUSE_BACKING
        /** IDR for backing files ids */
        struct idr backing_files_map;
 #endif
@@ -1588,10 +1601,12 @@ void fuse_file_release(struct inode *inode, struct fuse_file *ff,
                       unsigned int open_flags, fl_owner_t id, bool isdir);
 
 /* backing.c */
-#ifdef CONFIG_FUSE_PASSTHROUGH
+#ifdef CONFIG_FUSE_BACKING
 struct fuse_backing *fuse_backing_get(struct fuse_backing *fb);
 void fuse_backing_put(struct fuse_backing *fb);
-struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc, int backing_id);
+struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc,
+                                        const struct fuse_backing_ops *ops,
+                                        int backing_id);
 #else
 
 static inline struct fuse_backing *fuse_backing_get(struct fuse_backing *fb)
@@ -1646,6 +1661,10 @@ static inline struct file *fuse_file_passthrough(struct fuse_file *ff)
 #endif
 }
 
+#ifdef CONFIG_FUSE_PASSTHROUGH
+extern const struct fuse_backing_ops fuse_passthrough_backing_ops;
+#endif
+
 ssize_t fuse_passthrough_read_iter(struct kiocb *iocb, struct iov_iter *iter);
 ssize_t fuse_passthrough_write_iter(struct kiocb *iocb, struct iov_iter *iter);
 ssize_t fuse_passthrough_splice_read(struct file *in, loff_t *ppos,
include/uapi/linux/fuse.h +7 -1
index c13e1f9a2f12bd..18713cfaf09171 100644
@@ -1126,9 +1126,15 @@ struct fuse_notify_prune_out {
        uint64_t        spare;
 };
 
+#define FUSE_BACKING_TYPE_MASK         (0xFF)
+#define FUSE_BACKING_TYPE_PASSTHROUGH  (0)
+#define FUSE_BACKING_MAX_TYPE          (FUSE_BACKING_TYPE_PASSTHROUGH)
+
+#define FUSE_BACKING_FLAGS_ALL         (FUSE_BACKING_TYPE_MASK)
+
 struct fuse_backing_map {
        int32_t         fd;
-       uint32_t        flags;
+       uint32_t        flags; /* FUSE_BACKING_* */
        uint64_t        padding;
 };
 
fs/fuse/Kconfig +4 -0
index 3a4ae632c94aa8..290d1c09e0b924 100644
@@ -59,12 +59,16 @@ config FUSE_PASSTHROUGH
        default y
        depends on FUSE_FS
        select FS_STACK
+       select FUSE_BACKING
        help
          This allows bypassing FUSE server by mapping specific FUSE operations
          to be performed directly on a backing file.
 
          If you want to allow passthrough operations, answer Y.
 
+config FUSE_BACKING
+       bool
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/Makefile +2 -1
index 22ad9538dfc4b8..46041228e5be2c 100644
@@ -14,7 +14,8 @@ fuse-y := trace.o     # put trace.o first so we see ftrace errors sooner
 fuse-y += dev.o dir.o file.o inode.o control.o xattr.o acl.o readdir.o ioctl.o
 fuse-y += iomode.o
 fuse-$(CONFIG_FUSE_DAX) += dax.o
-fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o backing.o
+fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
+fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
 
fs/fuse/backing.c +73 -25
index 4afda419dd1416..f5efbffd0f456b 100644
@@ -6,6 +6,7 @@
  */
 
 #include "fuse_i.h"
+#include "fuse_trace.h"
 
 #include <linux/file.h>
 
@@ -44,7 +45,8 @@ static int fuse_backing_id_alloc(struct fuse_conn *fc, struct fuse_backing *fb)
        idr_preload(GFP_KERNEL);
        spin_lock(&fc->lock);
        /* FIXME: xarray might be space inefficient */
-       id = idr_alloc_cyclic(&fc->backing_files_map, fb, 1, 0, GFP_ATOMIC);
+       id = idr_alloc_cyclic(&fc->backing_files_map, fb, fb->ops->id_start,
+                             fb->ops->id_end, GFP_ATOMIC);
        spin_unlock(&fc->lock);
        idr_preload_end();
 
@@ -69,32 +71,53 @@ static int fuse_backing_id_free(int id, void *p, void *data)
        struct fuse_backing *fb = p;
 
        WARN_ON_ONCE(refcount_read(&fb->count) != 1);
+
        fuse_backing_free(fb);
        return 0;
 }
 
 void fuse_backing_files_free(struct fuse_conn *fc)
 {
-       idr_for_each(&fc->backing_files_map, fuse_backing_id_free, NULL);
+       idr_for_each(&fc->backing_files_map, fuse_backing_id_free, fc);
        idr_destroy(&fc->backing_files_map);
 }
 
+static inline const struct fuse_backing_ops *
+fuse_backing_ops_from_map(const struct fuse_backing_map *map)
+{
+       switch (map->flags & FUSE_BACKING_TYPE_MASK) {
+#ifdef CONFIG_FUSE_PASSTHROUGH
+       case FUSE_BACKING_TYPE_PASSTHROUGH:
+               return &fuse_passthrough_backing_ops;
+#endif
+       default:
+               break;
+       }
+
+       return NULL;
+}
+
 int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
 {
        struct file *file;
-       struct super_block *backing_sb;
        struct fuse_backing *fb = NULL;
+       const struct fuse_backing_ops *ops = fuse_backing_ops_from_map(map);
+       uint32_t op_flags = map->flags & ~FUSE_BACKING_TYPE_MASK;
        int res;
 
        pr_debug("%s: fd=%d flags=0x%x\n", __func__, map->fd, map->flags);
 
-       /* TODO: relax CAP_SYS_ADMIN once backing files are visible to lsof */
-       res = -EPERM;
-       if (!fc->passthrough || !capable(CAP_SYS_ADMIN))
+       res = -EOPNOTSUPP;
+       if (!ops)
+               goto out;
+       WARN_ON(ops->type != (map->flags & FUSE_BACKING_TYPE_MASK));
+
+       res = ops->may_admin ? ops->may_admin(fc, op_flags) : 0;
+       if (res)
                goto out;
 
        res = -EINVAL;
-       if (map->flags || map->padding)
+       if (map->padding)
                goto out;
 
        file = fget_raw(map->fd);
@@ -102,14 +125,8 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
        if (!file)
                goto out;
 
-       /* read/write/splice/mmap passthrough only relevant for regular files */
-       res = d_is_dir(file->f_path.dentry) ? -EISDIR : -EINVAL;
-       if (!d_is_reg(file->f_path.dentry))
-               goto out_fput;
-
-       backing_sb = file_inode(file)->i_sb;
-       res = -ELOOP;
-       if (backing_sb->s_stack_depth >= fc->max_stack_depth)
+       res = ops->may_open ? ops->may_open(fc, file) : 0;
+       if (res)
                goto out_fput;
 
        fb = kmalloc(sizeof(struct fuse_backing), GFP_KERNEL);
@@ -119,14 +136,15 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
 
        fb->file = file;
        fb->cred = prepare_creds();
+       fb->ops = ops;
        refcount_set(&fb->count, 1);
 
        res = fuse_backing_id_alloc(fc, fb);
        if (res < 0) {
                fuse_backing_free(fb);
                fb = NULL;
+               goto out;
        }
-
 out:
        pr_debug("%s: fb=0x%p, ret=%i\n", __func__, fb, res);
 
@@ -137,41 +155,71 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
        goto out;
 }
 
+static struct fuse_backing *__fuse_backing_lookup(struct fuse_conn *fc,
+                                                 int backing_id)
+{
+       struct fuse_backing *fb;
+
+       rcu_read_lock();
+       fb = idr_find(&fc->backing_files_map, backing_id);
+       fb = fuse_backing_get(fb);
+       rcu_read_unlock();
+
+       return fb;
+}
+
 int fuse_backing_close(struct fuse_conn *fc, int backing_id)
 {
-       struct fuse_backing *fb = NULL;
+       struct fuse_backing *fb, *test_fb;
+       const struct fuse_backing_ops *ops;
        int err;
 
        pr_debug("%s: backing_id=%d\n", __func__, backing_id);
 
-       /* TODO: relax CAP_SYS_ADMIN once backing files are visible to lsof */
-       err = -EPERM;
-       if (!fc->passthrough || !capable(CAP_SYS_ADMIN))
-               goto out;
-
        err = -EINVAL;
        if (backing_id <= 0)
                goto out;
 
        err = -ENOENT;
-       fb = fuse_backing_id_remove(fc, backing_id);
+       fb = __fuse_backing_lookup(fc, backing_id);
        if (!fb)
                goto out;
+       ops = fb->ops;
 
-       fuse_backing_put(fb);
+       err = ops->may_admin ? ops->may_admin(fc, 0) : 0;
+       if (err)
+               goto out_fb;
+
+       err = ops->may_close ? ops->may_close(fc, fb->file) : 0;
+       if (err)
+               goto out_fb;
+
+       err = -ENOENT;
+       test_fb = fuse_backing_id_remove(fc, backing_id);
+       if (!test_fb)
+               goto out_fb;
+
+       WARN_ON(fb != test_fb);
        err = 0;
+       fuse_backing_put(test_fb);
+out_fb:
+       fuse_backing_put(fb);
 out:
        pr_debug("%s: fb=0x%p, err=%i\n", __func__, fb, err);
 
        return err;
 }
 
-struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc, int backing_id)
+struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc,
+                                        const struct fuse_backing_ops *ops,
+                                        int backing_id)
 {
        struct fuse_backing *fb;
 
        rcu_read_lock();
        fb = idr_find(&fc->backing_files_map, backing_id);
+       if (fb && fb->ops != ops)
+               fb = NULL;
        fb = fuse_backing_get(fb);
        rcu_read_unlock();
 
fs/fuse/dev.c +2 -2
index ecc0a5304c59d1..12cc673df99151 100644
@@ -2662,7 +2662,7 @@ static long fuse_dev_ioctl_backing_open(struct file *file,
        if (IS_ERR(fud))
                return PTR_ERR(fud);
 
-       if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+       if (!IS_ENABLED(CONFIG_FUSE_BACKING))
                return -EOPNOTSUPP;
 
        if (copy_from_user(&map, argp, sizeof(map)))
@@ -2679,7 +2679,7 @@ static long fuse_dev_ioctl_backing_close(struct file *file, __u32 __user *argp)
        if (IS_ERR(fud))
                return PTR_ERR(fud);
 
-       if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+       if (!IS_ENABLED(CONFIG_FUSE_BACKING))
                return -EOPNOTSUPP;
 
        if (get_user(backing_id, argp))
fs/fuse/inode.c +2 -2
index 76e5b7f5c980c2..0cac7164afa298 100644
@@ -1004,7 +1004,7 @@ void fuse_conn_init(struct fuse_conn *fc, struct fuse_mount *fm,
        fc->name_max = FUSE_NAME_LOW_MAX;
        fc->timeout.req_timeout = 0;
 
-       if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+       if (IS_ENABLED(CONFIG_FUSE_BACKING))
                fuse_backing_files_init(fc);
 
        INIT_LIST_HEAD(&fc->mounts);
@@ -1041,7 +1041,7 @@ void fuse_conn_put(struct fuse_conn *fc)
                        WARN_ON(atomic_read(&bucket->count) != 1);
                        kfree(bucket);
                }
-               if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
+               if (IS_ENABLED(CONFIG_FUSE_BACKING))
                        fuse_backing_files_free(fc);
                call_rcu(&fc->rcu, delayed_release);
        }
fs/fuse/passthrough.c +37 -1
index 72de97c03d0eeb..e1619bffb5d125 100644
@@ -162,7 +162,7 @@ struct fuse_backing *fuse_passthrough_open(struct file *file, int backing_id)
                goto out;
 
        err = -ENOENT;
-       fb = fuse_backing_lookup(fc, backing_id);
+       fb = fuse_backing_lookup(fc, &fuse_passthrough_backing_ops, backing_id);
        if (!fb)
                goto out;
 
@@ -195,3 +195,39 @@ void fuse_passthrough_release(struct fuse_file *ff, struct fuse_backing *fb)
        put_cred(ff->cred);
        ff->cred = NULL;
 }
+
+static int fuse_passthrough_may_admin(struct fuse_conn *fc, unsigned int flags)
+{
+       /* TODO: relax CAP_SYS_ADMIN once backing files are visible to lsof */
+       if (!fc->passthrough || !capable(CAP_SYS_ADMIN))
+               return -EPERM;
+
+       if (flags)
+               return -EINVAL;
+
+       return 0;
+}
+
+static int fuse_passthrough_may_open(struct fuse_conn *fc, struct file *file)
+{
+       struct super_block *backing_sb;
+       int res;
+
+       /* read/write/splice/mmap passthrough only relevant for regular files */
+       res = d_is_dir(file->f_path.dentry) ? -EISDIR : -EINVAL;
+       if (!d_is_reg(file->f_path.dentry))
+               return res;
+
+       backing_sb = file_inode(file)->i_sb;
+       if (backing_sb->s_stack_depth >= fc->max_stack_depth)
+               return -ELOOP;
+
+       return 0;
+}
+
+const struct fuse_backing_ops fuse_passthrough_backing_ops = {
+       .type = FUSE_BACKING_TYPE_PASSTHROUGH,
+       .id_start = 1,
+       .may_admin = fuse_passthrough_may_admin,
+       .may_open = fuse_passthrough_may_open,
+};
#44 lore raw

PATCH 2/2 fuse_trace: move the passthrough-specific code back to passthrough.c

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/backing.c    |    5 +++++
 2 files changed, 40 insertions(+)
fs/fuse/fuse_trace.h +35 -0
index bbe9ddd8c71696..286a0845dc0898 100644
@@ -124,6 +124,41 @@ TRACE_EVENT(fuse_request_end,
 		  __entry->unique, __entry->len, __entry->error)
 );
 
+#ifdef CONFIG_FUSE_BACKING
+TRACE_EVENT(fuse_backing_class,
+	TP_PROTO(const struct fuse_conn *fc, unsigned int idx,
+		 const struct fuse_backing *fb),
+
+	TP_ARGS(fc, idx, fb),
+
+	TP_STRUCT__entry(
+		__field(dev_t,			connection)
+		__field(unsigned int,		idx)
+		__field(unsigned long,		ino)
+	),
+
+	TP_fast_assign(
+		struct inode *inode = file_inode(fb->file);
+
+		__entry->connection	=	fc->dev;
+		__entry->idx		=	idx;
+		__entry->ino		=	inode->i_ino;
+	),
+
+	TP_printk("connection %u idx %u ino 0x%lx",
+		  __entry->connection,
+		  __entry->idx,
+		  __entry->ino)
+);
+#define DEFINE_FUSE_BACKING_EVENT(name)		\
+DEFINE_EVENT(fuse_backing_class, name,		\
+	TP_PROTO(const struct fuse_conn *fc, unsigned int idx, \
+		 const struct fuse_backing *fb), \
+	TP_ARGS(fc, idx, fb))
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_open);
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
+#endif /* CONFIG_FUSE_BACKING */
+
 #endif /* _TRACE_FUSE_H */
 
 #undef TRACE_INCLUDE_PATH
fs/fuse/backing.c +5 -0
index f5efbffd0f456b..b83a3c1b2dff7a 100644
@@ -72,6 +72,7 @@ static int fuse_backing_id_free(int id, void *p, void *data)
 
 	WARN_ON_ONCE(refcount_read(&fb->count) != 1);
 
+	trace_fuse_backing_close((struct fuse_conn *)data, id, fb);
 	fuse_backing_free(fb);
 	return 0;
 }
@@ -145,6 +146,8 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
 		fb = NULL;
 		goto out;
 	}
+
+	trace_fuse_backing_open(fc, res, fb);
 out:
 	pr_debug("%s: fb=0x%p, ret=%i\n", __func__, fb, res);
 
@@ -194,6 +197,8 @@ int fuse_backing_close(struct fuse_conn *fc, int backing_id)
 	if (err)
 		goto out_fb;
 
+	trace_fuse_backing_close(fc, backing_id, fb);
+
 	err = -ENOENT;
 	test_fb = fuse_backing_id_remove(fc, backing_id);
 	if (!test_fb)
#45 lore raw

Re: [PATCH 2/2] fuse_trace: move the passthrough-specific code back to passthrough.c

Quoted 80 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/backing.c    |    5 +++++
 2 files changed, 40 insertions(+)
fs/fuse/fuse_trace.h +35 -0
index bbe9ddd8c71696..286a0845dc0898 100644
@@ -124,6 +124,41 @@ TRACE_EVENT(fuse_request_end,
                  __entry->unique, __entry->len, __entry->error)
 );
 
+#ifdef CONFIG_FUSE_BACKING
+TRACE_EVENT(fuse_backing_class,
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx,
+                const struct fuse_backing *fb),
+
+       TP_ARGS(fc, idx, fb),
+
+       TP_STRUCT__entry(
+               __field(dev_t,                  connection)
+               __field(unsigned int,           idx)
+               __field(unsigned long,          ino)
+       ),
+
+       TP_fast_assign(
+               struct inode *inode = file_inode(fb->file);
+
+               __entry->connection     =       fc->dev;
+               __entry->idx            =       idx;
+               __entry->ino            =       inode->i_ino;
+       ),
+
+       TP_printk("connection %u idx %u ino 0x%lx",
+                 __entry->connection,
+                 __entry->idx,
+                 __entry->ino)
+);
+#define DEFINE_FUSE_BACKING_EVENT(name)                \
+DEFINE_EVENT(fuse_backing_class, name,         \
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx, \
+                const struct fuse_backing *fb), \
+       TP_ARGS(fc, idx, fb))
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_open);
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
+#endif /* CONFIG_FUSE_BACKING */
+
 #endif /* _TRACE_FUSE_H */
 
 #undef TRACE_INCLUDE_PATH
fs/fuse/backing.c +3 -0
index f5efbffd0f456b..b83a3c1b2dff7a 100644
@@ -72,6 +72,7 @@ static int fuse_backing_id_free(int id, void *p, void *data)
 
        WARN_ON_ONCE(refcount_read(&fb->count) != 1);
 
+       trace_fuse_backing_close((struct fuse_conn *)data, id, fb);
        fuse_backing_free(fb);
        return 0;
 }
@@ -145,6 +146,8 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
                fb = NULL;
                goto out;
        }
+
+       trace_fuse_backing_open(fc, res, fb);
 out:
        pr_debug("%s: fb=0x%p, ret=%i\n", __func__, fb, res);
 

fs/fuse/backing.c int fuse_backing_close(struct fuse_conn *fc, int backing_id) · line 201

Quoted 5 lines
fs/fuse/backing.c +2 -0
@@ -194,6 +197,8 @@ int fuse_backing_close(struct fuse_conn *fc, int backing_id)
        if (err)
                goto out_fb;
 
+       trace_fuse_backing_close(fc, backing_id, fb);
+

If I'm understanding it correctly, the lines above (added from the previous patch) are

+ err = ops->may_admin ? ops->may_admin(fc, 0) : 0;
+ if (err)
+ goto out_fb;
+
+ err = ops->may_close ? ops->may_close(fc, fb->file) : 0;
+ if (err)
+ goto out_fb;

and will also do the close in the out_fb goto. So should the trace_fuse_backing_close() be moved to before the "err = ops->may_admin..." line so it doesn't get missed in the "if (err)..." cases?

Thanks,
Joanne

Quoted 4 lines
fs/fuse/backing.c +0 -0
        err = -ENOENT;
        test_fb = fuse_backing_id_remove(fc, backing_id);
        if (!test_fb)
#46 lore raw

Re: [PATCH 2/2] fuse_trace: move the passthrough-specific code back to passthrough.c

Quoted 92 lines · Joanne Koong
Quoted 80 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/backing.c    |    5 +++++
 2 files changed, 40 insertions(+)
fs/fuse/fuse_trace.h +35 -0
index bbe9ddd8c71696..286a0845dc0898 100644
@@ -124,6 +124,41 @@ TRACE_EVENT(fuse_request_end,
                  __entry->unique, __entry->len, __entry->error)
 );
 
+#ifdef CONFIG_FUSE_BACKING
+TRACE_EVENT(fuse_backing_class,
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx,
+                const struct fuse_backing *fb),
+
+       TP_ARGS(fc, idx, fb),
+
+       TP_STRUCT__entry(
+               __field(dev_t,                  connection)
+               __field(unsigned int,           idx)
+               __field(unsigned long,          ino)
+       ),
+
+       TP_fast_assign(
+               struct inode *inode = file_inode(fb->file);
+
+               __entry->connection     =       fc->dev;
+               __entry->idx            =       idx;
+               __entry->ino            =       inode->i_ino;
+       ),
+
+       TP_printk("connection %u idx %u ino 0x%lx",
+                 __entry->connection,
+                 __entry->idx,
+                 __entry->ino)
+);
+#define DEFINE_FUSE_BACKING_EVENT(name)                \
+DEFINE_EVENT(fuse_backing_class, name,         \
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx, \
+                const struct fuse_backing *fb), \
+       TP_ARGS(fc, idx, fb))
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_open);
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
+#endif /* CONFIG_FUSE_BACKING */
+
 #endif /* _TRACE_FUSE_H */
 
 #undef TRACE_INCLUDE_PATH
fs/fuse/backing.c +3 -0
index f5efbffd0f456b..b83a3c1b2dff7a 100644
@@ -72,6 +72,7 @@ static int fuse_backing_id_free(int id, void *p, void *data)
 
        WARN_ON_ONCE(refcount_read(&fb->count) != 1);
 
+       trace_fuse_backing_close((struct fuse_conn *)data, id, fb);
        fuse_backing_free(fb);
        return 0;
 }
@@ -145,6 +146,8 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
                fb = NULL;
                goto out;
        }
+
+       trace_fuse_backing_open(fc, res, fb);
 out:
        pr_debug("%s: fb=0x%p, ret=%i\n", __func__, fb, res);
 

fs/fuse/backing.c int fuse_backing_close(struct fuse_conn *fc, int backing_id) · line 201

Quoted 5 lines
fs/fuse/backing.c +2 -0
@@ -194,6 +197,8 @@ int fuse_backing_close(struct fuse_conn *fc, int backing_id)
        if (err)
                goto out_fb;
 
+       trace_fuse_backing_close(fc, backing_id, fb);
+

If I'm understanding it correctly, the lines above (added from the previous patch) are

+ err = ops->may_admin ? ops->may_admin(fc, 0) : 0;
+ if (err)

Review

Quoted 5 lines
(quoted diff) +5 -0
+       goto out_fb;
+
+ err = ops->may_close ? ops->may_close(fc, fb->file) : 0;
+ if (err)
+        goto out_fb;

That's correct.

Quoted 4 lines

and will also do the close in the out_fb goto. So should the trace_fuse_backing_close() be moved to before the "err = ops->may_admin..." line so it doesn't get missed in the "if (err)..." cases?

No. If either ->may_admin or ->may_close return nonzero, then this function drops the active reference to @fb that it obtained from __fuse_backing_lookup without calling fuse_backing_id_remove. Therefore, the fuse connection retains its mapping of backing_id to a fuse_backing object, which means that nothing is closed.

--D

Quoted 7 lines

Thanks,
Joanne

Quoted 4 lines
fs/fuse/backing.c +0 -0
        err = -ENOENT;
        test_fb = fuse_backing_id_remove(fc, backing_id);
        if (!test_fb)
Reviewed-by
#47 lore raw

Re: [PATCH 2/2] fuse_trace: move the passthrough-specific code back to passthrough.c

Quoted 107 lines · Darrick J. Wong
Quoted 92 lines · Joanne Koong
Quoted 80 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   35 +++++++++++++++++++++++++++++++++++
 fs/fuse/backing.c    |    5 +++++
 2 files changed, 40 insertions(+)
fs/fuse/fuse_trace.h +35 -0
index bbe9ddd8c71696..286a0845dc0898 100644
@@ -124,6 +124,41 @@ TRACE_EVENT(fuse_request_end,
                  __entry->unique, __entry->len, __entry->error)
 );
 
+#ifdef CONFIG_FUSE_BACKING
+TRACE_EVENT(fuse_backing_class,
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx,
+                const struct fuse_backing *fb),
+
+       TP_ARGS(fc, idx, fb),
+
+       TP_STRUCT__entry(
+               __field(dev_t,                  connection)
+               __field(unsigned int,           idx)
+               __field(unsigned long,          ino)
+       ),
+
+       TP_fast_assign(
+               struct inode *inode = file_inode(fb->file);
+
+               __entry->connection     =       fc->dev;
+               __entry->idx            =       idx;
+               __entry->ino            =       inode->i_ino;
+       ),
+
+       TP_printk("connection %u idx %u ino 0x%lx",
+                 __entry->connection,
+                 __entry->idx,
+                 __entry->ino)
+);
+#define DEFINE_FUSE_BACKING_EVENT(name)                \
+DEFINE_EVENT(fuse_backing_class, name,         \
+       TP_PROTO(const struct fuse_conn *fc, unsigned int idx, \
+                const struct fuse_backing *fb), \
+       TP_ARGS(fc, idx, fb))
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_open);
+DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
+#endif /* CONFIG_FUSE_BACKING */
+
 #endif /* _TRACE_FUSE_H */
 
 #undef TRACE_INCLUDE_PATH
fs/fuse/backing.c +3 -0
index f5efbffd0f456b..b83a3c1b2dff7a 100644
@@ -72,6 +72,7 @@ static int fuse_backing_id_free(int id, void *p, void *data)
 
        WARN_ON_ONCE(refcount_read(&fb->count) != 1);
 
+       trace_fuse_backing_close((struct fuse_conn *)data, id, fb);
        fuse_backing_free(fb);
        return 0;
 }
@@ -145,6 +146,8 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
                fb = NULL;
                goto out;
        }
+
+       trace_fuse_backing_open(fc, res, fb);
 out:
        pr_debug("%s: fb=0x%p, ret=%i\n", __func__, fb, res);
 

fs/fuse/backing.c int fuse_backing_close(struct fuse_conn *fc, int backing_id) · line 201

Quoted 5 lines
fs/fuse/backing.c +2 -0
@@ -194,6 +197,8 @@ int fuse_backing_close(struct fuse_conn *fc, int backing_id)
        if (err)
                goto out_fb;
 
+       trace_fuse_backing_close(fc, backing_id, fb);
+

If I'm understanding it correctly, the lines above (added from the previous patch) are

+ err = ops->may_admin ? ops->may_admin(fc, 0) : 0;
+ if (err)

Review

Quoted 5 lines
(quoted diff) +5 -0
+       goto out_fb;
+
+ err = ops->may_close ? ops->may_close(fc, fb->file) : 0;
+ if (err)
+        goto out_fb;

That's correct.

Quoted 4 lines

and will also do the close in the out_fb goto. So should the trace_fuse_backing_close() be moved to before the "err = ops->may_admin..." line so it doesn't get missed in the "if (err)..." cases?

Quoted 7 lines

No. If either ->may_admin or ->may_close return nonzero, then this function drops the active reference to @fb that it obtained from __fuse_backing_lookup without calling fuse_backing_id_remove. Therefore, the fuse connection retains its mapping of backing_id to a fuse_backing object, which means that nothing is closed.

--D

That makes sense, thanks for the explanation.

Quoted 8 lines
Quoted 8 lines

Thanks,
Joanne

Quoted 4 lines
fs/fuse/backing.c +0 -0
        err = -ENOENT;
        test_fb = fuse_backing_id_remove(fc, backing_id);
        if (!test_fb)
#48 lore raw

PATCH v6 4/8 fuse: allow servers to use iomap for better file IO performance

In reply to Darrick J. Wong

Hi all,

This series connects fuse (the userspace filesystem layer) to fs-iomap to get fuse servers out of the business of handling file I/O themselves. By keeping the IO path mostly within the kernel, we can dramatically improve the speed of disk-based filesystems. This enables us to move all the filesystem metadata parsing code out of the kernel and into userspace, which means that we can containerize them for security without losing a lot of performance.

If you're going to start using this code, I strongly recommend pulling from my git trees, which are linked below.

This has been running on the djcloud for months with no problems. Enjoy! Comments and questions are, as always, welcome.

--D

kernel git tree:
https://git.kernel.org/cgit/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-fileio
---
Commits in this patchset:
* fuse: implement the basic iomap mechanisms
* fuse_trace: implement the basic iomap mechanisms
* fuse: make debugging configurable at runtime
* fuse: adapt FUSE_DEV_IOC_BACKING_{OPEN,CLOSE} to add new iomap devices
* fuse_trace: adapt FUSE_DEV_IOC_BACKING_{OPEN,CLOSE} to add new iomap devices
* fuse: flush events and send FUSE_SYNCFS and FUSE_DESTROY on unmount
* fuse: create a per-inode flag for toggling iomap
* fuse_trace: create a per-inode flag for toggling iomap
* fuse: isolate the other regular file IO paths from iomap
* fuse: implement basic iomap reporting such as FIEMAP and SEEK_{DATA,HOLE}
* fuse_trace: implement basic iomap reporting such as FIEMAP and SEEK_{DATA,HOLE}
* fuse: implement direct IO with iomap
* fuse_trace: implement direct IO with iomap
* fuse: implement buffered IO with iomap
* fuse_trace: implement buffered IO with iomap
* fuse: implement large folios for iomap pagecache files
* fuse: use an unrestricted backing device with iomap pagecache io
* fuse: advertise support for iomap
* fuse: query filesystem geometry when using iomap
* fuse_trace: query filesystem geometry when using iomap
* fuse: implement fadvise for iomap files
* fuse: invalidate ranges of block devices being used for iomap
* fuse_trace: invalidate ranges of block devices being used for iomap
* fuse: implement inline data file IO via iomap
* fuse_trace: implement inline data file IO via iomap
* fuse: allow more statx fields
* fuse: support atomic writes with iomap
* fuse_trace: support atomic writes with iomap
* fuse: disable direct reclaim for any fuse server that uses iomap
* fuse: enable swapfile activation on iomap
* fuse: implement freeze and shutdowns for iomap filesystems

---
 fs/fuse/fuse_i.h          |  161 +++
 fs/fuse/fuse_trace.h      |  939 +++++++++++++++++++
 fs/fuse/iomap_i.h         |   52 +
 include/uapi/linux/fuse.h |  219 ++++
 fs/fuse/Kconfig           |   48 +
 fs/fuse/Makefile          |    1 
 fs/fuse/backing.c         |   12 
 fs/fuse/dev.c             |   30 +
 fs/fuse/dir.c             |  120 ++
 fs/fuse/file.c            |  133 ++-
 fs/fuse/file_iomap.c      | 2230 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |  162 +++
 fs/fuse/iomode.c          |    2 
 fs/fuse/trace.c           |    2 
 14 files changed, 4056 insertions(+), 55 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
#49 lore raw

PATCH 1/31 fuse: implement the basic iomap mechanisms

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

---
 fs/fuse/fuse_i.h          |   22 ++
 fs/fuse/iomap_i.h         |   36 ++++
 include/uapi/linux/fuse.h |   90 +++++++++
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1 
 fs/fuse/file_iomap.c      |  434 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    8 +
 7 files changed, 621 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
fs/fuse/fuse_i.h +21 -1
index 7c7d255d817f1e..45be59df7ae592 100644
@@ -929,6 +929,9 @@ struct fuse_conn {
 	/* Is synchronous FUSE_INIT allowed? */
 	unsigned int sync_init:1;
 
+	/* Enable fs/iomap for file operations */
+	unsigned int iomap:1;
+
 	/* Use io_uring for communication */
 	unsigned int io_uring;
 
@@ -1053,12 +1056,17 @@ static inline struct fuse_mount *get_fuse_mount_super(struct super_block *sb)
 	return sb->s_fs_info;
 }
 
+static inline const struct fuse_mount *get_fuse_mount_super_c(const struct super_block *sb)
+{
+	return sb->s_fs_info;
+}
+
 static inline struct fuse_conn *get_fuse_conn_super(struct super_block *sb)
 {
 	return get_fuse_mount_super(sb)->fc;
 }
 
-static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
+static inline struct fuse_mount *get_fuse_mount(const struct inode *inode)
 {
 	return get_fuse_mount_super(inode->i_sb);
 }
@@ -1683,4 +1691,16 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()	do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+bool fuse_iomap_enabled(void);
+
+static inline bool fuse_has_iomap(const struct inode *inode)
+{
+	return get_fuse_conn(inode)->iomap;
+}
+#else
+# define fuse_iomap_enabled(...)		(false)
+# define fuse_has_iomap(...)			(false)
+#endif
+
 #endif /* _FS_FUSE_I_H */
fs/fuse/iomap_i.h new file +36 -0
new file mode 100644
index 00000000000000..d773f728579d1d
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#ifndef _FS_FUSE_IOMAP_I_H
+#define _FS_FUSE_IOMAP_I_H
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+# define ASSERT(condition) do {						\
+	int __cond = !!(condition);					\
+	WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+} while (0)
+# define BAD_DATA(condition) ({						\
+	int __cond = !!(condition);					\
+	WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+})
+#else
+# define ASSERT(condition)
+# define BAD_DATA(condition) ({						\
+	int __cond = !!(condition);					\
+	unlikely(__cond);						\
+})
+#endif /* CONFIG_FUSE_IOMAP_DEBUG */
+
+enum fuse_iomap_iodir {
+	READ_MAPPING,
+	WRITE_MAPPING,
+};
+
+#define EFSCORRUPTED	EUCLEAN
+
+#endif /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_I_H */
include/uapi/linux/fuse.h +89 -1

124 lines not on this page · raw message

fs/fuse/Kconfig +32 -0
index 290d1c09e0b924..934d48076a010c 100644
@@ -69,6 +69,38 @@ config FUSE_PASSTHROUGH
 config FUSE_BACKING
 	bool
 
+config FUSE_IOMAP
+	bool "FUSE file IO over iomap"
+	default y
+	depends on FUSE_FS
+	depends on BLOCK
+	select FS_IOMAP
+	help
+	  Enable fuse servers to operate the regular file I/O path through
+	  the fs-iomap library in the kernel.  This enables higher performance
+	  userspace filesystems by keeping the performance critical parts in
+	  the kernel while delegating the difficult metadata parsing parts to
+	  an easily-contained userspace program.
+
+	  This feature is considered EXPERIMENTAL.  Use with caution!
+
+	  If unsure, say N.
+
+config FUSE_IOMAP_BY_DEFAULT
+	bool "FUSE file I/O over iomap by default"
+	default n
+	depends on FUSE_IOMAP
+	help
+	  Enable sending FUSE file I/O over iomap by default.
+
+config FUSE_IOMAP_DEBUG
+	bool "Debug FUSE file IO over iomap"
+	default y
+	depends on FUSE_IOMAP
+	help
+	  Enable debugging assertions for the fuse iomap code paths and logging
+	  of bad iomap file mapping data being sent to the kernel.
+
 config FUSE_IO_URING
 	bool "FUSE communication over io-uring"
 	default y
fs/fuse/Makefile +1 -0
index 46041228e5be2c..27be39317701d6 100644
@@ -18,5 +18,6 @@ fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
 fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
+fuse-$(CONFIG_FUSE_IOMAP) += file_iomap.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/file_iomap.c new file +434 -0

434 lines not on this page · raw message

fs/fuse/inode.c +8 -0
index 0cac7164afa298..1eea8dc6e723c6 100644
@@ -1457,6 +1457,12 @@ static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
 
 			if (flags & FUSE_REQUEST_TIMEOUT)
 				timeout = arg->request_timeout;
+
+			if ((flags & FUSE_IOMAP) && fuse_iomap_enabled()) {
+				fc->iomap = 1;
+				pr_warn(
+ "EXPERIMENTAL iomap feature enabled.  Use at your own risk!");
+			}
 		} else {
 			ra_pages = fc->max_read / PAGE_SIZE;
 			fc->no_lock = 1;
@@ -1525,6 +1531,8 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
 	 */
 	if (fuse_uring_enabled())
 		flags |= FUSE_OVER_IO_URING;
+	if (fuse_iomap_enabled())
+		flags |= FUSE_IOMAP;
 
 	ia->in.flags = flags;
 	ia->in.flags2 = flags >> 32;
#50 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

Quoted 35 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

---
 fs/fuse/fuse_i.h          |   22 ++
 fs/fuse/iomap_i.h         |   36 ++++
 include/uapi/linux/fuse.h |   90 +++++++++
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1
 fs/fuse/file_iomap.c      |  434 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    8 +
 7 files changed, 621 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
fs/fuse/fuse_i.h +3 -0
index 7c7d255d817f1e..45be59df7ae592 100644
@@ -929,6 +929,9 @@ struct fuse_conn {
        /* Is synchronous FUSE_INIT allowed? */
        unsigned int sync_init:1;
 
+       /* Enable fs/iomap for file operations */
+       unsigned int iomap:1;
+
        /* Use io_uring for communication */
        unsigned int io_uring;
 

fs/fuse/fuse_i.h static inline struct fuse_mount *get_fuse_mount_super(struct super_block *sb) · line 1062

Quoted 7 lines
fs/fuse/fuse_i.h +4 -0
@@ -1053,12 +1056,17 @@ static inline struct fuse_mount *get_fuse_mount_super(struct super_block *sb)
        return sb->s_fs_info;
 }
 
+static inline const struct fuse_mount *get_fuse_mount_super_c(const struct super_block *sb)
+{
+       return sb->s_fs_info;
+}

I'm not seeing this getting used anywhere - did you mean to remove this?

Quoted 75 lines
fs/fuse/fuse_i.h +14 -1
+
 static inline struct fuse_conn *get_fuse_conn_super(struct super_block *sb)
 {
        return get_fuse_mount_super(sb)->fc;
 }
 
-static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
+static inline struct fuse_mount *get_fuse_mount(const struct inode *inode)
 {
        return get_fuse_mount_super(inode->i_sb);
 }
@@ -1683,4 +1691,16 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()       do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+bool fuse_iomap_enabled(void);
+
+static inline bool fuse_has_iomap(const struct inode *inode)
+{
+       return get_fuse_conn(inode)->iomap;
+}
+#else
+# define fuse_iomap_enabled(...)               (false)
+# define fuse_has_iomap(...)                   (false)
+#endif
+
 #endif /* _FS_FUSE_I_H */
fs/fuse/iomap_i.h new file +36 -0
new file mode 100644
index 00000000000000..d773f728579d1d
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#ifndef _FS_FUSE_IOMAP_I_H
+#define _FS_FUSE_IOMAP_I_H
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+# define ASSERT(condition) do {                                                \
+       int __cond = !!(condition);                                     \
+       WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+} while (0)
+# define BAD_DATA(condition) ({                                                \
+       int __cond = !!(condition);                                     \
+       WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+})
+#else
+# define ASSERT(condition)
+# define BAD_DATA(condition) ({                                                \
+       int __cond = !!(condition);                                     \
+       unlikely(__cond);                                               \
+})
+#endif /* CONFIG_FUSE_IOMAP_DEBUG */
+
+enum fuse_iomap_iodir {
+       READ_MAPPING,
+       WRITE_MAPPING,
+};
+
+#define EFSCORRUPTED   EUCLEAN
+
+#endif /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_I_H */
include/uapi/linux/fuse.h +0 -0
index 18713cfaf09171..7d709cf12b41a7 100644

include/uapi/linux/fuse.h line 244

Quoted 5 lines
include/uapi/linux/fuse.h +2 -0
@@ -240,6 +240,9 @@
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.99

Should this be changed to something like 7.46 now that this patch is submitted for merging into the tree?

include/uapi/linux/fuse.h line 281

Quoted 10 lines
include/uapi/linux/fuse.h +2 -1
+ *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  */
 
 #ifndef _LINUX_FUSE_H
@@ -275,7 +278,7 @@
 #define FUSE_KERNEL_VERSION 7
 
 /** Minor version number of this interface */
-#define FUSE_KERNEL_MINOR_VERSION 45
+#define FUSE_KERNEL_MINOR_VERSION 99

Same question here

Quoted 43 lines
include/uapi/linux/fuse.h +15 -0
 /** The node ID of the root inode */
 #define FUSE_ROOT_ID 1
@@ -448,6 +451,7 @@ struct fuse_file_lock {
  * FUSE_OVER_IO_URING: Indicate that client supports io-uring
  * FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
  *                      init_out.request_timeout contains the timeout (in secs)
+ * FUSE_IOMAP: Client supports iomap for regular file operations.
  */
 #define FUSE_ASYNC_READ                (1 << 0)
 #define FUSE_POSIX_LOCKS       (1 << 1)
@@ -495,6 +499,7 @@ struct fuse_file_lock {
 #define FUSE_ALLOW_IDMAP       (1ULL << 40)
 #define FUSE_OVER_IO_URING     (1ULL << 41)
 #define FUSE_REQUEST_TIMEOUT   (1ULL << 42)
+#define FUSE_IOMAP             (1ULL << 43)
 
 /**
  * CUSE INIT request/reply flags
@@ -664,6 +669,9 @@ enum fuse_opcode {
        FUSE_STATX              = 52,
        FUSE_COPY_FILE_RANGE_64 = 53,
 
+       FUSE_IOMAP_BEGIN        = 4094,
+       FUSE_IOMAP_END          = 4095,
+
        /* CUSE specific operations */
        CUSE_INIT               = 4096,
 
@@ -1314,4 +1322,84 @@ struct fuse_uring_cmd_req {
        uint8_t padding[6];
 };
 
+/* mapping types; see corresponding IOMAP_TYPE_ */
+#define FUSE_IOMAP_TYPE_HOLE           (0)
+#define FUSE_IOMAP_TYPE_DELALLOC       (1)
+#define FUSE_IOMAP_TYPE_MAPPED         (2)
+#define FUSE_IOMAP_TYPE_UNWRITTEN      (3)
+#define FUSE_IOMAP_TYPE_INLINE         (4)
+
+/* fuse-specific mapping type indicating that writes use the read mapping */
+#define FUSE_IOMAP_TYPE_PURE_OVERWRITE (255)
+

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1344

Quoted 10 lines
include/uapi/linux/fuse.h +10 -0
+#define FUSE_IOMAP_DEV_NULL            (0U)    /* null device cookie */
+
+/* mapping flags passed back from iomap_begin; see corresponding IOMAP_F_ */
+#define FUSE_IOMAP_F_NEW               (1U << 0)
+#define FUSE_IOMAP_F_DIRTY             (1U << 1)
+#define FUSE_IOMAP_F_SHARED            (1U << 2)
+#define FUSE_IOMAP_F_MERGED            (1U << 3)
+#define FUSE_IOMAP_F_BOUNDARY          (1U << 4)
+#define FUSE_IOMAP_F_ANON_WRITE                (1U << 5)
+#define FUSE_IOMAP_F_ATOMIC_BIO                (1U << 6)

Do you think it makes sense to have the fuse iomap constants mirror the in-kernel iomap ones? Maybe I'm mistaken but it seems like the fuse iomap capabilities won't diverge too much from fs/iomap ones? I like that if they're mirrored, then it makes it simpler instead of needing to convert back and forth.

Quoted 20 lines
include/uapi/linux/fuse.h +20 -0
+
+/* fuse-specific mapping flag asking for ->iomap_end call */
+#define FUSE_IOMAP_F_WANT_IOMAP_END    (1U << 7)
+
+/* mapping flags passed to iomap_end */
+#define FUSE_IOMAP_F_SIZE_CHANGED      (1U << 8)
+#define FUSE_IOMAP_F_STALE             (1U << 9)
+
+/* operation flags from iomap; see corresponding IOMAP_* */
+#define FUSE_IOMAP_OP_WRITE            (1U << 0)
+#define FUSE_IOMAP_OP_ZERO             (1U << 1)
+#define FUSE_IOMAP_OP_REPORT           (1U << 2)
+#define FUSE_IOMAP_OP_FAULT            (1U << 3)
+#define FUSE_IOMAP_OP_DIRECT           (1U << 4)
+#define FUSE_IOMAP_OP_NOWAIT           (1U << 5)
+#define FUSE_IOMAP_OP_OVERWRITE_ONLY   (1U << 6)
+#define FUSE_IOMAP_OP_UNSHARE          (1U << 7)
+#define FUSE_IOMAP_OP_DAX              (1U << 8)
+#define FUSE_IOMAP_OP_ATOMIC           (1U << 9)
+#define FUSE_IOMAP_OP_DONTCACHE                (1U << 10)

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1374

Quoted 10 lines
include/uapi/linux/fuse.h +10 -0
+
+#define FUSE_IOMAP_NULL_ADDR           (-1ULL) /* addr is not valid */
+
+struct fuse_iomap_io {
+       uint64_t offset;        /* file offset of mapping, bytes */
+       uint64_t length;        /* length of mapping, bytes */
+       uint64_t addr;          /* disk offset of mapping, bytes */
+       uint16_t type;          /* FUSE_IOMAP_TYPE_* */
+       uint16_t flags;         /* FUSE_IOMAP_F_* */
+       uint32_t dev;           /* device cookie */

Do you think it's a good idea to add a reserved field here in case we end up needing it in the future?

Quoted 6 lines
include/uapi/linux/fuse.h +6 -0
+};
+
+struct fuse_iomap_begin_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1390

Quoted 10 lines
include/uapi/linux/fuse.h +10 -0
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+};
+
+struct fuse_iomap_begin_out {
+       /* read file data from here */
+       struct fuse_iomap_io    read;
+
+       /* write file data to here, if applicable */
+       struct fuse_iomap_io    write;

Same question here

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1399

Quoted 9 lines
include/uapi/linux/fuse.h +9 -0
+};
+
+struct fuse_iomap_end_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+       int64_t written;        /* bytes processed */

On the fs/iomap side, I see that written is passed through by iomap_iter() to ->iomap_end through 'ssize_t advanced' but it's not clear to me why advanced needs to be signed. I think it used to also represent the error status, but it looks like now that's represented through iter->status and 'advanced' strictly reflects the number of bytes written. As such, do you think it makes sense to change 'advanced' to loff_t and have written be uint64_t instead?

Quoted 27 lines
include/uapi/linux/fuse.h +5 -0
+
+       /* mapping that the kernel acted upon */
+       struct fuse_iomap_io    map;
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/Kconfig +13 -0
index 290d1c09e0b924..934d48076a010c 100644
@@ -69,6 +69,38 @@ config FUSE_PASSTHROUGH
 config FUSE_BACKING
        bool
 
+config FUSE_IOMAP
+       bool "FUSE file IO over iomap"
+       default y
+       depends on FUSE_FS
+       depends on BLOCK
+       select FS_IOMAP
+       help
+         Enable fuse servers to operate the regular file I/O path through
+         the fs-iomap library in the kernel.  This enables higher performance
+         userspace filesystems by keeping the performance critical parts in
+         the kernel while delegating the difficult metadata parsing parts to
+         an easily-contained userspace program.
+

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 94

Quoted 10 lines
fs/fuse/Kconfig +10 -0
+         This feature is considered EXPERIMENTAL.  Use with caution!
+
+         If unsure, say N.
+
+config FUSE_IOMAP_BY_DEFAULT
+       bool "FUSE file I/O over iomap by default"
+       default n
+       depends on FUSE_IOMAP
+       help
+         Enable sending FUSE file I/O over iomap by default.

I'm not really sure what the general linux preference is for adding new configs, but assuming it errs towards less configs than more, imo it seems easy enough to just set the enable_iomap module param to true manually instead of needing this config for it, especially since the param only needs to be set once.

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 102

Quoted 8 lines
fs/fuse/Kconfig +8 -0
+
+config FUSE_IOMAP_DEBUG
+       bool "Debug FUSE file IO over iomap"
+       default y
+       depends on FUSE_IOMAP
+       help
+         Enable debugging assertions for the fuse iomap code paths and logging
+         of bad iomap file mapping data being sent to the kernel.

I'm wondering if it makes sense to make this a general FUSE_DEBUG config so we can reuse this more generally

Quoted 266 lines
fs/fuse/Kconfig +1 -0
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/Makefile +1 -0
index 46041228e5be2c..27be39317701d6 100644
@@ -18,5 +18,6 @@ fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
 fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
+fuse-$(CONFIG_FUSE_IOMAP) += file_iomap.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/file_iomap.c new file +244 -0
new file mode 100644
index 00000000000000..d564d60d0f1779
@@ -0,0 +1,434 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#include <linux/iomap.h>
+#include "fuse_i.h"
+#include "fuse_trace.h"
+#include "iomap_i.h"
+
+static bool __read_mostly enable_iomap =
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
+       true;
+#else
+       false;
+#endif
+module_param(enable_iomap, bool, 0644);
+MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
+
+bool fuse_iomap_enabled(void)
+{
+       /* Don't let anyone touch iomap until the end of the patchset. */
+       return false;
+
+       /*
+        * There are fears that a fuse+iomap server could somehow DoS the
+        * system by doing things like going out to lunch during a writeback
+        * related iomap request.  Only allow iomap access if the fuse server
+        * has rawio capabilities since those processes can mess things up
+        * quite well even without our help.
+        */
+       return enable_iomap && has_capability_noaudit(current, CAP_SYS_RAWIO);
+}
+
+/* Convert IOMAP_* mapping types to FUSE_IOMAP_TYPE_* */
+#define XMAP(word) \
+       case IOMAP_##word: \
+               return FUSE_IOMAP_TYPE_##word
+static inline uint16_t fuse_iomap_type_to_server(uint16_t iomap_type)
+{
+       switch (iomap_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Convert FUSE_IOMAP_TYPE_* to IOMAP_* mapping types */
+#define XMAP(word) \
+       case FUSE_IOMAP_TYPE_##word: \
+               return IOMAP_##word
+static inline uint16_t fuse_iomap_type_from_server(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Validate FUSE_IOMAP_TYPE_* */
+static inline bool fuse_iomap_check_type(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+       case FUSE_IOMAP_TYPE_INLINE:
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               return true;
+       }
+
+       return false;
+}
+
+#define FUSE_IOMAP_F_ALL (FUSE_IOMAP_F_NEW | \
+                         FUSE_IOMAP_F_DIRTY | \
+                         FUSE_IOMAP_F_SHARED | \
+                         FUSE_IOMAP_F_MERGED | \
+                         FUSE_IOMAP_F_BOUNDARY | \
+                         FUSE_IOMAP_F_ANON_WRITE | \
+                         FUSE_IOMAP_F_ATOMIC_BIO | \
+                         FUSE_IOMAP_F_WANT_IOMAP_END)
+
+static inline bool fuse_iomap_check_flags(uint16_t flags)
+{
+       return (flags & ~FUSE_IOMAP_F_ALL) == 0;
+}
+
+/* Convert IOMAP_F_* mapping state flags to FUSE_IOMAP_F_* */
+#define XMAP(word) \
+       if (iomap_f_flags & IOMAP_F_##word) \
+               ret |= FUSE_IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (iomap_f_flags & IOMAP_F_##iword) \
+               ret |= FUSE_IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_to_server(uint16_t iomap_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(PRIVATE, WANT_IOMAP_END);
+
+       XMAP(SIZE_CHANGED);
+       XMAP(STALE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert FUSE_IOMAP_F_* to IOMAP_F_* mapping state flags */
+#define XMAP(word) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##word) \
+               ret |= IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##iword) \
+               ret |= IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_from_server(uint16_t fuse_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(WANT_IOMAP_END, PRIVATE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert IOMAP_* operation flags to FUSE_IOMAP_OP_* */
+#define XMAP(word) \
+       if (iomap_op_flags & IOMAP_##word) \
+               ret |= FUSE_IOMAP_OP_##word
+static inline uint32_t fuse_iomap_op_to_server(unsigned iomap_op_flags)
+{
+       uint32_t ret = 0;
+
+       XMAP(WRITE);
+       XMAP(ZERO);
+       XMAP(REPORT);
+       XMAP(FAULT);
+       XMAP(DIRECT);
+       XMAP(NOWAIT);
+       XMAP(OVERWRITE_ONLY);
+       XMAP(UNSHARE);
+       XMAP(DAX);
+       XMAP(ATOMIC);
+       XMAP(DONTCACHE);
+
+       return ret;
+}
+#undef XMAP
+
+/* Validate an iomap mapping. */
+static inline bool fuse_iomap_check_mapping(const struct inode *inode,
+                                           const struct fuse_iomap_io *map,
+                                           enum fuse_iomap_iodir iodir)
+{
+       const unsigned int blocksize = i_blocksize(inode);
+       uint64_t end;
+
+       /* Type and flags must be known */
+       if (BAD_DATA(!fuse_iomap_check_type(map->type)))
+               return false;
+       if (BAD_DATA(!fuse_iomap_check_flags(map->flags)))
+               return false;
+
+       /* No zero-length mappings */
+       if (BAD_DATA(map->length == 0))
+               return false;
+
+       /* File range must be aligned to blocksize */
+       if (BAD_DATA(!IS_ALIGNED(map->offset, blocksize)))
+               return false;
+       if (BAD_DATA(!IS_ALIGNED(map->length, blocksize)))
+               return false;
+
+       /* No overflows in the file range */
+       if (BAD_DATA(check_add_overflow(map->offset, map->length, &end)))
+               return false;
+
+       /* File range cannot start past maxbytes */
+       if (BAD_DATA(map->offset >= inode->i_sb->s_maxbytes))
+               return false;
+
+       switch (map->type) {
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+               /* Mappings backed by space must have a device/addr */
+               if (BAD_DATA(map->dev == FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr == FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_INLINE:
+               /* Mappings not backed by space cannot have a device addr. */
+               if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr != FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               /* "Pure overwrite" only allowed for write mapping */
+               if (BAD_DATA(iodir != WRITE_MAPPING))
+                       return false;
+               break;
+       default:
+               /* should have been caught already */
+               ASSERT(0);
+               return false;
+       }
+
+       /* XXX: we don't support devices yet */
 
+       if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+               return false;
+

fs/fuse/file_iomap.c line 254

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+       /* No overflows in the device range, if supplied */
+       if (map->addr != FUSE_IOMAP_NULL_ADDR &&
+           BAD_DATA(check_add_overflow(map->addr, map->length, &end)))
+               return false;
+
+       return true;
+}
+
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct inode *inode,

Maybe worth adding a const in front of struct inode?

Quoted 11 lines
fs/fuse/file_iomap.c new file +11 -0
+                                         struct iomap *iomap,
+                                         const struct fuse_iomap_io *fmap)
+{
+       iomap->addr = fmap->addr;
+       iomap->offset = fmap->offset;
+       iomap->length = fmap->length;
+       iomap->type = fuse_iomap_type_from_server(fmap->type);
+       iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+       iomap->bdev = inode->i_sb->s_bdev; /* XXX */
+}
+

fs/fuse/file_iomap.c line 275

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+                                       const struct iomap *iomap)
+{
+       fmap->addr = FUSE_IOMAP_NULL_ADDR; /* XXX */
+       fmap->offset = iomap->offset;
+       fmap->length = iomap->length;
+       fmap->type = fuse_iomap_type_to_server(iomap->type);
+       fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+       fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */

AFAICT, this only gets used for sending the FUSE_IOMAP_END request. Is passing the iomap->addr to fmap->addr and inode->i_sb->s_bdev to fmap->dev not useful to the server here?

Also, did you mean to leave in the /* XXX */ comments?

Quoted 123 lines
fs/fuse/file_iomap.c new file +123 -0
+}
+
+/* Check the incoming _begin mappings to make sure they're not nonsense. */
+static inline int
+fuse_iomap_begin_validate(const struct inode *inode,
+                         unsigned opflags, loff_t pos,
+                         const struct fuse_iomap_begin_out *outarg)
+{
+       /* Make sure the mappings aren't garbage */
+       if (!fuse_iomap_check_mapping(inode, &outarg->read, READ_MAPPING))
+               return -EFSCORRUPTED;
+
+       if (!fuse_iomap_check_mapping(inode, &outarg->write, WRITE_MAPPING))
+               return -EFSCORRUPTED;
+
+       /*
+        * Must have returned a mapping for at least the first byte in the
+        * range.  The main mapping check already validated that the length
+        * is nonzero and there is no overflow in computing end.
+        */
+       if (BAD_DATA(outarg->read.offset > pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset > pos))
+               return -EFSCORRUPTED;
+
+       if (BAD_DATA(outarg->read.offset + outarg->read.length <= pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset + outarg->write.length <= pos))
+               return -EFSCORRUPTED;
+
+       return 0;
+}
+
+static inline bool fuse_is_iomap_file_write(unsigned int opflags)
+{
+       return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE);
+}
+
+static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
+                           unsigned opflags, struct iomap *iomap,
+                           struct iomap *srcmap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_iomap_begin_in inarg = {
+               .attr_ino = fi->orig_ino,
+               .opflags = fuse_iomap_op_to_server(opflags),
+               .pos = pos,
+               .count = count,
+       };
+       struct fuse_iomap_begin_out outarg = { };
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       FUSE_ARGS(args);
+       int err;
+
+       args.opcode = FUSE_IOMAP_BEGIN;
+       args.nodeid = get_node_id(inode);
+       args.in_numargs = 1;
+       args.in_args[0].size = sizeof(inarg);
+       args.in_args[0].value = &inarg;
+       args.out_numargs = 1;
+       args.out_args[0].size = sizeof(outarg);
+       args.out_args[0].value = &outarg;
+       err = fuse_simple_request(fm, &args);
+       if (err)
+               return err;
+
+       err = fuse_iomap_begin_validate(inode, opflags, pos, &outarg);
+       if (err)
+               return err;
+
+       if (fuse_is_iomap_file_write(opflags) &&
+           outarg.write.type != FUSE_IOMAP_TYPE_PURE_OVERWRITE) {
+               /*
+                * For an out of place write, we must supply the write mapping
+                * via @iomap, and the read mapping via @srcmap.
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.write);
+               fuse_iomap_from_server(inode, srcmap, &outarg.read);
+       } else {
+               /*
+                * For everything else (reads, reporting, and pure overwrites),
+                * we can return the sole mapping through @iomap and leave
+                * @srcmap unchanged from its default (HOLE).
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.read);
+       }
+
+       return 0;
+}
+
+/* Decide if we send FUSE_IOMAP_END to the fuse server */
+static bool fuse_should_send_iomap_end(const struct iomap *iomap,
+                                      unsigned int opflags, loff_t count,
+                                      ssize_t written)
+{
+       /* fuse server demanded an iomap_end call. */
+       if (iomap->flags & FUSE_IOMAP_F_WANT_IOMAP_END)
+               return true;
+
+       /* Reads and reporting should never affect the filesystem metadata */
+       if (!fuse_is_iomap_file_write(opflags))
+               return false;
+
+       /* Appending writes get an iomap_end call */
+       if (iomap->flags & IOMAP_F_SIZE_CHANGED)
+               return true;
+
+       /* Short writes get an iomap_end call to clean up delalloc */
+       return written < count;
+}
+
+static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
+                         ssize_t written, unsigned opflags,
+                         struct iomap *iomap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       int err = 0;
+
+       if (fuse_should_send_iomap_end(iomap, opflags, count, written)) {
+               struct fuse_iomap_end_in inarg = {
+                       .opflags = fuse_iomap_op_to_server(opflags),
+                       .attr_ino = fi->orig_ino,

fs/fuse/file_iomap.c line 408

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+                       .pos = pos,
+                       .count = count,
+                       .written = written,
+               };
+               FUSE_ARGS(args);
+
+               fuse_iomap_to_server(&inarg.map, iomap);
+
+               args.opcode = FUSE_IOMAP_END;
+               args.nodeid = get_node_id(inode);

Just curious about this - does it make sense to set args.force here for this opcode? It seems like it serves the same sort of purpose a flush request (which sets args.force) does?

Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+               args.in_numargs = 1;
+               args.in_args[0].size = sizeof(inarg);
+               args.in_args[0].value = &inarg;
+               err = fuse_simple_request(fm, &args);

fs/fuse/file_iomap.c line 422

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+               switch (err) {
+               case -ENOSYS:
+                       /*
+                        * libfuse returns ENOSYS for servers that don't
+                        * implement iomap_end
+                        */
+                       err = 0;
+                       break;
+               case 0:
+                       break;

Is this case 0 needed separately from the default case?

Thanks,
Joanne

Quoted 39 lines
fs/fuse/file_iomap.c new file +12 -0
+               default:
+                       break;
+               }
+       }
+
+       return err;
+}
+
+const struct iomap_ops fuse_iomap_ops = {
+       .iomap_begin            = fuse_iomap_begin,
+       .iomap_end              = fuse_iomap_end,
+};
fs/fuse/inode.c +8 -0
index 0cac7164afa298..1eea8dc6e723c6 100644
@@ -1457,6 +1457,12 @@ static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
 
                        if (flags & FUSE_REQUEST_TIMEOUT)
                                timeout = arg->request_timeout;
+
+                       if ((flags & FUSE_IOMAP) && fuse_iomap_enabled()) {
+                               fc->iomap = 1;
+                               pr_warn(
+ "EXPERIMENTAL iomap feature enabled.  Use at your own risk!");
+                       }
                } else {
                        ra_pages = fc->max_read / PAGE_SIZE;
                        fc->no_lock = 1;
@@ -1525,6 +1531,8 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
         */
        if (fuse_uring_enabled())
                flags |= FUSE_OVER_IO_URING;
+       if (fuse_iomap_enabled())
+               flags |= FUSE_IOMAP;
 
        ia->in.flags = flags;
        ia->in.flags2 = flags >> 32;
#51 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

Quoted 39 lines · Joanne Koong
Quoted 38 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

---
 fs/fuse/fuse_i.h          |   22 ++
 fs/fuse/iomap_i.h         |   36 ++++
 include/uapi/linux/fuse.h |   90 +++++++++
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1
 fs/fuse/file_iomap.c      |  434 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    8 +
 7 files changed, 621 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
fs/fuse/fuse_i.h +3 -0
index 7c7d255d817f1e..45be59df7ae592 100644
@@ -929,6 +929,9 @@ struct fuse_conn {
        /* Is synchronous FUSE_INIT allowed? */
        unsigned int sync_init:1;
 
+       /* Enable fs/iomap for file operations */
+       unsigned int iomap:1;
+
        /* Use io_uring for communication */
        unsigned int io_uring;
 
@@ -1053,12 +1056,17 @@ static inline struct fuse_mount *get_fuse_mount_super(struct super_block *sb)
        return sb->s_fs_info;
 }
 
Quoted 6 lines

fs/fuse/fuse_i.h static inline struct fuse_mount *get_fuse_mount_super(struct super_block *sb) · line 1062

Quoted 4 lines
fs/fuse/fuse_i.h +4 -0
+static inline const struct fuse_mount *get_fuse_mount_super_c(const struct super_block *sb)
+{
+       return sb->s_fs_info;
+}

I'm not seeing this getting used anywhere - did you mean to remove this?

Yeah.

Quoted 75 lines
Quoted 75 lines
fs/fuse/fuse_i.h +14 -1
+
 static inline struct fuse_conn *get_fuse_conn_super(struct super_block *sb)
 {
        return get_fuse_mount_super(sb)->fc;
 }
 
-static inline struct fuse_mount *get_fuse_mount(struct inode *inode)
+static inline struct fuse_mount *get_fuse_mount(const struct inode *inode)
 {
        return get_fuse_mount_super(inode->i_sb);
 }
@@ -1683,4 +1691,16 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()       do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+bool fuse_iomap_enabled(void);
+
+static inline bool fuse_has_iomap(const struct inode *inode)
+{
+       return get_fuse_conn(inode)->iomap;
+}
+#else
+# define fuse_iomap_enabled(...)               (false)
+# define fuse_has_iomap(...)                   (false)
+#endif
+
 #endif /* _FS_FUSE_I_H */
fs/fuse/iomap_i.h new file +36 -0
new file mode 100644
index 00000000000000..d773f728579d1d
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#ifndef _FS_FUSE_IOMAP_I_H
+#define _FS_FUSE_IOMAP_I_H
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+# define ASSERT(condition) do {                                                \
+       int __cond = !!(condition);                                     \
+       WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+} while (0)
+# define BAD_DATA(condition) ({                                                \
+       int __cond = !!(condition);                                     \
+       WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+})
+#else
+# define ASSERT(condition)
+# define BAD_DATA(condition) ({                                                \
+       int __cond = !!(condition);                                     \
+       unlikely(__cond);                                               \
+})
+#endif /* CONFIG_FUSE_IOMAP_DEBUG */
+
+enum fuse_iomap_iodir {
+       READ_MAPPING,
+       WRITE_MAPPING,
+};
+
+#define EFSCORRUPTED   EUCLEAN
+
+#endif /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_I_H */
include/uapi/linux/fuse.h +0 -0
index 18713cfaf09171..7d709cf12b41a7 100644
@@ -240,6 +240,9 @@
Quoted 8 lines

include/uapi/linux/fuse.h line 244

Quoted 5 lines
include/uapi/linux/fuse.h +2 -0
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.99

Should this be changed to something like 7.46 now that this patch is submitted for merging into the tree?

When review of this patchset nears completion I'll change the 99s to 46 or whatever the fuse/libfuse minor version happens to be at that point.

Nobody's touched this series since 29 October (during 6.19 development) and I've been busy with xfs_healer so I'm not submitting this for 7.0 either.

Quoted 64 lines

include/uapi/linux/fuse.h line 281

Quoted 10 lines
include/uapi/linux/fuse.h +2 -1
+ *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  */
 
 #ifndef _LINUX_FUSE_H
@@ -275,7 +278,7 @@
 #define FUSE_KERNEL_VERSION 7
 
 /** Minor version number of this interface */
-#define FUSE_KERNEL_MINOR_VERSION 45
+#define FUSE_KERNEL_MINOR_VERSION 99

Same question here

Quoted 51 lines
include/uapi/linux/fuse.h +23 -0
 /** The node ID of the root inode */
 #define FUSE_ROOT_ID 1
@@ -448,6 +451,7 @@ struct fuse_file_lock {
  * FUSE_OVER_IO_URING: Indicate that client supports io-uring
  * FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
  *                      init_out.request_timeout contains the timeout (in secs)
+ * FUSE_IOMAP: Client supports iomap for regular file operations.
  */
 #define FUSE_ASYNC_READ                (1 << 0)
 #define FUSE_POSIX_LOCKS       (1 << 1)
@@ -495,6 +499,7 @@ struct fuse_file_lock {
 #define FUSE_ALLOW_IDMAP       (1ULL << 40)
 #define FUSE_OVER_IO_URING     (1ULL << 41)
 #define FUSE_REQUEST_TIMEOUT   (1ULL << 42)
+#define FUSE_IOMAP             (1ULL << 43)
 
 /**
  * CUSE INIT request/reply flags
@@ -664,6 +669,9 @@ enum fuse_opcode {
        FUSE_STATX              = 52,
        FUSE_COPY_FILE_RANGE_64 = 53,
 
+       FUSE_IOMAP_BEGIN        = 4094,
+       FUSE_IOMAP_END          = 4095,
+
        /* CUSE specific operations */
        CUSE_INIT               = 4096,
 
@@ -1314,4 +1322,84 @@ struct fuse_uring_cmd_req {
        uint8_t padding[6];
 };
 
+/* mapping types; see corresponding IOMAP_TYPE_ */
+#define FUSE_IOMAP_TYPE_HOLE           (0)
+#define FUSE_IOMAP_TYPE_DELALLOC       (1)
+#define FUSE_IOMAP_TYPE_MAPPED         (2)
+#define FUSE_IOMAP_TYPE_UNWRITTEN      (3)
+#define FUSE_IOMAP_TYPE_INLINE         (4)
+
+/* fuse-specific mapping type indicating that writes use the read mapping */
+#define FUSE_IOMAP_TYPE_PURE_OVERWRITE (255)
+
+#define FUSE_IOMAP_DEV_NULL            (0U)    /* null device cookie */
+
+/* mapping flags passed back from iomap_begin; see corresponding IOMAP_F_ */
+#define FUSE_IOMAP_F_NEW               (1U << 0)
+#define FUSE_IOMAP_F_DIRTY             (1U << 1)
+#define FUSE_IOMAP_F_SHARED            (1U << 2)
+#define FUSE_IOMAP_F_MERGED            (1U << 3)
+#define FUSE_IOMAP_F_BOUNDARY          (1U << 4)
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1344

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+#define FUSE_IOMAP_F_ANON_WRITE                (1U << 5)
+#define FUSE_IOMAP_F_ATOMIC_BIO                (1U << 6)

Do you think it makes sense to have the fuse iomap constants mirror the in-kernel iomap ones? Maybe I'm mistaken but it seems like the fuse iomap capabilities won't diverge too much from fs/iomap ones? I like that if they're mirrored, then it makes it simpler instead of needing to convert back and forth.

"Mirrored"? As in, having the define use a symbol:

#define FUSE_IOMAP_F_NEW IOMAP_F_NEW

instead of defining it to be a specific numerical constant like it is here?

<confused>

This might not be answering your question, but as an old iomap maintainer I want the kernel iomap api and the fuse iomap uabi to be as decoupled as they can be; and trust the compiler to notice that the flag and enum constants are the same and not do anything too stupid with the translation.

Quoted 24 lines
Quoted 24 lines
include/uapi/linux/fuse.h +24 -0
+/* fuse-specific mapping flag asking for ->iomap_end call */
+#define FUSE_IOMAP_F_WANT_IOMAP_END    (1U << 7)
+
+/* mapping flags passed to iomap_end */
+#define FUSE_IOMAP_F_SIZE_CHANGED      (1U << 8)
+#define FUSE_IOMAP_F_STALE             (1U << 9)
+
+/* operation flags from iomap; see corresponding IOMAP_* */
+#define FUSE_IOMAP_OP_WRITE            (1U << 0)
+#define FUSE_IOMAP_OP_ZERO             (1U << 1)
+#define FUSE_IOMAP_OP_REPORT           (1U << 2)
+#define FUSE_IOMAP_OP_FAULT            (1U << 3)
+#define FUSE_IOMAP_OP_DIRECT           (1U << 4)
+#define FUSE_IOMAP_OP_NOWAIT           (1U << 5)
+#define FUSE_IOMAP_OP_OVERWRITE_ONLY   (1U << 6)
+#define FUSE_IOMAP_OP_UNSHARE          (1U << 7)
+#define FUSE_IOMAP_OP_DAX              (1U << 8)
+#define FUSE_IOMAP_OP_ATOMIC           (1U << 9)
+#define FUSE_IOMAP_OP_DONTCACHE                (1U << 10)
+
+#define FUSE_IOMAP_NULL_ADDR           (-1ULL) /* addr is not valid */
+
+struct fuse_iomap_io {
+       uint64_t offset;        /* file offset of mapping, bytes */
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1374

Quoted 5 lines
include/uapi/linux/fuse.h +5 -0
+       uint64_t length;        /* length of mapping, bytes */
+       uint64_t addr;          /* disk offset of mapping, bytes */
+       uint16_t type;          /* FUSE_IOMAP_TYPE_* */
+       uint16_t flags;         /* FUSE_IOMAP_F_* */
+       uint32_t dev;           /* device cookie */

Do you think it's a good idea to add a reserved field here in case we end up needing it in the future?

I'm open to the idea of pre-padding the structs, though that's extra copy overhead until they get used for something.

Does that fuse-iouring-zerocopy patchset that you're working on enable the kernel to avoid copying fuse command data around? I haven't read it in sufficient (or any) detail to know the answer to that question.

Second: how easy is it to send a variable sized fuse command to userspace? It looks like some commands like FUSE_WRITE do things like:

	if (ff->fm->fc->minor < 9)
		args->in_args[0].size = FUSE_COMPAT_WRITE_IN_SIZE;
	else
		args->in_args[0].size = sizeof(ia->write.in);
	args->in_args[0].value = &ia->write.in;
	args->in_args[1].size = count;

Which means that future expansion can (in theory) bump the minor version and send larer commands.

It also looks like the kernel can support receiving variable-sized responses, like FUSE_READ does:

	args->out_argvar = true;
	args->out_numargs = 1;
	args->out_args[0].size = count;

I think this means that if we ever needed to expand the _out struct to allow the fuse server to send back a more lengthy response, we could potentially do that without needing a minor protocol version bump.

Quoted 10 lines
Quoted 10 lines
include/uapi/linux/fuse.h +10 -0
+};
+
+struct fuse_iomap_begin_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+};
+
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1390

Quoted 6 lines
include/uapi/linux/fuse.h +6 -0
+struct fuse_iomap_begin_out {
+       /* read file data from here */
+       struct fuse_iomap_io    read;
+
+       /* write file data to here, if applicable */
+       struct fuse_iomap_io    write;

Same question here

How much padding do you want? fuse_iomap_io is conveniently half a cacheline right now...

Quoted 10 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1399

Quoted 9 lines
include/uapi/linux/fuse.h +9 -0
+};
+
+struct fuse_iomap_end_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+       int64_t written;        /* bytes processed */
Quoted 7 lines

On the fs/iomap side, I see that written is passed through by iomap_iter() to ->iomap_end through 'ssize_t advanced' but it's not clear to me why advanced needs to be signed. I think it used to also represent the error status, but it looks like now that's represented through iter->status and 'advanced' strictly reflects the number of bytes written. As such, do you think it makes sense to change 'advanced' to loff_t and have written be uint64_t instead?

Not quite -- back in the bad old days, iomap_iter::processed was a s64 value that the iteration loop had to set to one of:

* a positive number for positive progress
* zero to stop the iteration
* a negative errno to fail out

Nowadays we just move iomap_iter::pos forward via iomap_iter_advance or set status to a negative number to end the iteration.

So yes, I think @advanced should be widened to 64-bits since iomap operations can jump more than 2GB per iter step. Practically speaking I think this hasn't yet been a problem because the only operations that can do that (fiemap, seek, swap) also don't have any client filesystems that implement iomap_end; or they do but never send mappings large enough to cause problems.

iomap iters can't go backwards so @advanced could be u64 as well.

Also the name of the ->iomap_end parameter could be changed to "advanced" because iomap_end could in theory be called for any operation, not just writes. That's a throwback to the days when the iomap code was just part of xfs. It also is an unsigned quantity.

Quoted 35 lines
Quoted 35 lines
include/uapi/linux/fuse.h +5 -0
+
+       /* mapping that the kernel acted upon */
+       struct fuse_iomap_io    map;
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/Kconfig +21 -0
index 290d1c09e0b924..934d48076a010c 100644
@@ -69,6 +69,38 @@ config FUSE_PASSTHROUGH
 config FUSE_BACKING
        bool
 
+config FUSE_IOMAP
+       bool "FUSE file IO over iomap"
+       default y
+       depends on FUSE_FS
+       depends on BLOCK
+       select FS_IOMAP
+       help
+         Enable fuse servers to operate the regular file I/O path through
+         the fs-iomap library in the kernel.  This enables higher performance
+         userspace filesystems by keeping the performance critical parts in
+         the kernel while delegating the difficult metadata parsing parts to
+         an easily-contained userspace program.
+
+         This feature is considered EXPERIMENTAL.  Use with caution!
+
+         If unsure, say N.
+
+config FUSE_IOMAP_BY_DEFAULT
+       bool "FUSE file I/O over iomap by default"
+       default n
+       depends on FUSE_IOMAP
Quoted 8 lines

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 94

Quoted 2 lines
fs/fuse/Kconfig +2 -0
+       help
+         Enable sending FUSE file I/O over iomap by default.

I'm not really sure what the general linux preference is for adding new configs, but assuming it errs towards less configs than more, imo it seems easy enough to just set the enable_iomap module param to true manually instead of needing this config for it, especially since the param only needs to be set once.

/me doesn't know what the norm is in fuse-land -- for xfs I've preferred to have a kconfig option for experimental code so that distros can turn off experimental stuff they don't want to support.

OTOH they can also patch it out or affix the module param to 0.

Also I'm not sure if the kernel tinyfication project is still active, for a while they were advocating strongly for more kconfig options so that people building embedded kernels could turn off big chunks of functionality they'd never need.

Quoted 11 lines

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 102

Quoted 8 lines
fs/fuse/Kconfig +8 -0
+
+config FUSE_IOMAP_DEBUG
+       bool "Debug FUSE file IO over iomap"
+       default y
+       depends on FUSE_IOMAP
+       help
+         Enable debugging assertions for the fuse iomap code paths and logging
+         of bad iomap file mapping data being sent to the kernel.

I'm wondering if it makes sense to make this a general FUSE_DEBUG config so we can reuse this more generally

In general yes but I highly recommend that everyone look at the static labels and auto-ftracing stuff enabled by the next few debug patches before anyone commits to spreading that enhanced observability / brain disease to the rest of fuse. ;)

Quoted 263 lines
Quoted 262 lines
fs/fuse/Kconfig +1 -0
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/Makefile +1 -0
index 46041228e5be2c..27be39317701d6 100644
@@ -18,5 +18,6 @@ fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
 fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
+fuse-$(CONFIG_FUSE_IOMAP) += file_iomap.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/file_iomap.c new file +241 -0
new file mode 100644
index 00000000000000..d564d60d0f1779
@@ -0,0 +1,434 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#include <linux/iomap.h>
+#include "fuse_i.h"
+#include "fuse_trace.h"
+#include "iomap_i.h"
+
+static bool __read_mostly enable_iomap =
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
+       true;
+#else
+       false;
+#endif
+module_param(enable_iomap, bool, 0644);
+MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
+
+bool fuse_iomap_enabled(void)
+{
+       /* Don't let anyone touch iomap until the end of the patchset. */
+       return false;
+
+       /*
+        * There are fears that a fuse+iomap server could somehow DoS the
+        * system by doing things like going out to lunch during a writeback
+        * related iomap request.  Only allow iomap access if the fuse server
+        * has rawio capabilities since those processes can mess things up
+        * quite well even without our help.
+        */
+       return enable_iomap && has_capability_noaudit(current, CAP_SYS_RAWIO);
+}
+
+/* Convert IOMAP_* mapping types to FUSE_IOMAP_TYPE_* */
+#define XMAP(word) \
+       case IOMAP_##word: \
+               return FUSE_IOMAP_TYPE_##word
+static inline uint16_t fuse_iomap_type_to_server(uint16_t iomap_type)
+{
+       switch (iomap_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Convert FUSE_IOMAP_TYPE_* to IOMAP_* mapping types */
+#define XMAP(word) \
+       case FUSE_IOMAP_TYPE_##word: \
+               return IOMAP_##word
+static inline uint16_t fuse_iomap_type_from_server(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Validate FUSE_IOMAP_TYPE_* */
+static inline bool fuse_iomap_check_type(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+       case FUSE_IOMAP_TYPE_INLINE:
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               return true;
+       }
+
+       return false;
+}
+
+#define FUSE_IOMAP_F_ALL (FUSE_IOMAP_F_NEW | \
+                         FUSE_IOMAP_F_DIRTY | \
+                         FUSE_IOMAP_F_SHARED | \
+                         FUSE_IOMAP_F_MERGED | \
+                         FUSE_IOMAP_F_BOUNDARY | \
+                         FUSE_IOMAP_F_ANON_WRITE | \
+                         FUSE_IOMAP_F_ATOMIC_BIO | \
+                         FUSE_IOMAP_F_WANT_IOMAP_END)
+
+static inline bool fuse_iomap_check_flags(uint16_t flags)
+{
+       return (flags & ~FUSE_IOMAP_F_ALL) == 0;
+}
+
+/* Convert IOMAP_F_* mapping state flags to FUSE_IOMAP_F_* */
+#define XMAP(word) \
+       if (iomap_f_flags & IOMAP_F_##word) \
+               ret |= FUSE_IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (iomap_f_flags & IOMAP_F_##iword) \
+               ret |= FUSE_IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_to_server(uint16_t iomap_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(PRIVATE, WANT_IOMAP_END);
+
+       XMAP(SIZE_CHANGED);
+       XMAP(STALE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert FUSE_IOMAP_F_* to IOMAP_F_* mapping state flags */
+#define XMAP(word) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##word) \
+               ret |= IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##iword) \
+               ret |= IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_from_server(uint16_t fuse_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(WANT_IOMAP_END, PRIVATE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert IOMAP_* operation flags to FUSE_IOMAP_OP_* */
+#define XMAP(word) \
+       if (iomap_op_flags & IOMAP_##word) \
+               ret |= FUSE_IOMAP_OP_##word
+static inline uint32_t fuse_iomap_op_to_server(unsigned iomap_op_flags)
+{
+       uint32_t ret = 0;
+
+       XMAP(WRITE);
+       XMAP(ZERO);
+       XMAP(REPORT);
+       XMAP(FAULT);
+       XMAP(DIRECT);
+       XMAP(NOWAIT);
+       XMAP(OVERWRITE_ONLY);
+       XMAP(UNSHARE);
+       XMAP(DAX);
+       XMAP(ATOMIC);
+       XMAP(DONTCACHE);
+
+       return ret;
+}
+#undef XMAP
+
+/* Validate an iomap mapping. */
+static inline bool fuse_iomap_check_mapping(const struct inode *inode,
+                                           const struct fuse_iomap_io *map,
+                                           enum fuse_iomap_iodir iodir)
+{
+       const unsigned int blocksize = i_blocksize(inode);
+       uint64_t end;
+
+       /* Type and flags must be known */
+       if (BAD_DATA(!fuse_iomap_check_type(map->type)))
+               return false;
+       if (BAD_DATA(!fuse_iomap_check_flags(map->flags)))
+               return false;
+
+       /* No zero-length mappings */
+       if (BAD_DATA(map->length == 0))
+               return false;
+
+       /* File range must be aligned to blocksize */
+       if (BAD_DATA(!IS_ALIGNED(map->offset, blocksize)))
+               return false;
+       if (BAD_DATA(!IS_ALIGNED(map->length, blocksize)))
+               return false;
+
+       /* No overflows in the file range */
+       if (BAD_DATA(check_add_overflow(map->offset, map->length, &end)))
+               return false;
+
+       /* File range cannot start past maxbytes */
+       if (BAD_DATA(map->offset >= inode->i_sb->s_maxbytes))
+               return false;
+
+       switch (map->type) {
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+               /* Mappings backed by space must have a device/addr */
+               if (BAD_DATA(map->dev == FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr == FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_INLINE:
+               /* Mappings not backed by space cannot have a device addr. */
+               if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr != FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               /* "Pure overwrite" only allowed for write mapping */
+               if (BAD_DATA(iodir != WRITE_MAPPING))
+                       return false;
+               break;
+       default:
+               /* should have been caught already */
+               ASSERT(0);
+               return false;
+       }
+
+       /* XXX: we don't support devices yet */
Quoted 15 lines

fs/fuse/file_iomap.c line 254

Quoted 13 lines
fs/fuse/file_iomap.c new file +13 -0
+       if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+               return false;
+
+       /* No overflows in the device range, if supplied */
+       if (map->addr != FUSE_IOMAP_NULL_ADDR &&
+           BAD_DATA(check_add_overflow(map->addr, map->length, &end)))
+               return false;
+
+       return true;
+}
+
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct inode *inode,

Maybe worth adding a const in front of struct inode?

It can go away in a patch or two when we wire up bdev support.

Though considering that fuse_iomap_enabled returns false all the way to the end of the patchset I guess I could just set bdev to null and skip passing in the inode at all.

Quoted 17 lines
Quoted 17 lines
fs/fuse/file_iomap.c new file +17 -0
+                                         struct iomap *iomap,
+                                         const struct fuse_iomap_io *fmap)
+{
+       iomap->addr = fmap->addr;
+       iomap->offset = fmap->offset;
+       iomap->length = fmap->length;
+       iomap->type = fuse_iomap_type_from_server(fmap->type);
+       iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+       iomap->bdev = inode->i_sb->s_bdev; /* XXX */
+}
+
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+                                       const struct iomap *iomap)
+{
+       fmap->addr = FUSE_IOMAP_NULL_ADDR; /* XXX */
+       fmap->offset = iomap->offset;
Quoted 8 lines

fs/fuse/file_iomap.c line 275

Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+       fmap->length = iomap->length;
+       fmap->type = fuse_iomap_type_to_server(iomap->type);
+       fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+       fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */

AFAICT, this only gets used for sending the FUSE_IOMAP_END request. Is passing the iomap->addr to fmap->addr and inode->i_sb->s_bdev to fmap->dev not useful to the server here?

So far the only fields I've needed in fuse4fs are the offset/count/written fields as provided by iomap_iter, and the flags field from the mapping. The addr field isn't necessary for fuse4fs because the fuse server would know if the mapping had changed. OTOH it's probably harmless to send it along.

Hrm. I probably need a way to look up the backing_id from the iomap bdev.

Looking further ahead at the ioend patch, I just realized that iomap ioends can tell you the new address of a write-append operation but they don't tell you which device. I guess you can read that from the ioend->io_bio.bi_bdev.

Quoted 1 line

Also, did you mean to leave in the /* XXX */ comments?

Yes, because they're a reminder to come back and check if I /ever/ needed them.

Quoted 129 lines
Quoted 129 lines
fs/fuse/file_iomap.c new file +129 -0
+}
+
+/* Check the incoming _begin mappings to make sure they're not nonsense. */
+static inline int
+fuse_iomap_begin_validate(const struct inode *inode,
+                         unsigned opflags, loff_t pos,
+                         const struct fuse_iomap_begin_out *outarg)
+{
+       /* Make sure the mappings aren't garbage */
+       if (!fuse_iomap_check_mapping(inode, &outarg->read, READ_MAPPING))
+               return -EFSCORRUPTED;
+
+       if (!fuse_iomap_check_mapping(inode, &outarg->write, WRITE_MAPPING))
+               return -EFSCORRUPTED;
+
+       /*
+        * Must have returned a mapping for at least the first byte in the
+        * range.  The main mapping check already validated that the length
+        * is nonzero and there is no overflow in computing end.
+        */
+       if (BAD_DATA(outarg->read.offset > pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset > pos))
+               return -EFSCORRUPTED;
+
+       if (BAD_DATA(outarg->read.offset + outarg->read.length <= pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset + outarg->write.length <= pos))
+               return -EFSCORRUPTED;
+
+       return 0;
+}
+
+static inline bool fuse_is_iomap_file_write(unsigned int opflags)
+{
+       return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE);
+}
+
+static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
+                           unsigned opflags, struct iomap *iomap,
+                           struct iomap *srcmap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_iomap_begin_in inarg = {
+               .attr_ino = fi->orig_ino,
+               .opflags = fuse_iomap_op_to_server(opflags),
+               .pos = pos,
+               .count = count,
+       };
+       struct fuse_iomap_begin_out outarg = { };
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       FUSE_ARGS(args);
+       int err;
+
+       args.opcode = FUSE_IOMAP_BEGIN;
+       args.nodeid = get_node_id(inode);
+       args.in_numargs = 1;
+       args.in_args[0].size = sizeof(inarg);
+       args.in_args[0].value = &inarg;
+       args.out_numargs = 1;
+       args.out_args[0].size = sizeof(outarg);
+       args.out_args[0].value = &outarg;
+       err = fuse_simple_request(fm, &args);
+       if (err)
+               return err;
+
+       err = fuse_iomap_begin_validate(inode, opflags, pos, &outarg);
+       if (err)
+               return err;
+
+       if (fuse_is_iomap_file_write(opflags) &&
+           outarg.write.type != FUSE_IOMAP_TYPE_PURE_OVERWRITE) {
+               /*
+                * For an out of place write, we must supply the write mapping
+                * via @iomap, and the read mapping via @srcmap.
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.write);
+               fuse_iomap_from_server(inode, srcmap, &outarg.read);
+       } else {
+               /*
+                * For everything else (reads, reporting, and pure overwrites),
+                * we can return the sole mapping through @iomap and leave
+                * @srcmap unchanged from its default (HOLE).
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.read);
+       }
+
+       return 0;
+}
+
+/* Decide if we send FUSE_IOMAP_END to the fuse server */
+static bool fuse_should_send_iomap_end(const struct iomap *iomap,
+                                      unsigned int opflags, loff_t count,
+                                      ssize_t written)
+{
+       /* fuse server demanded an iomap_end call. */
+       if (iomap->flags & FUSE_IOMAP_F_WANT_IOMAP_END)
+               return true;
+
+       /* Reads and reporting should never affect the filesystem metadata */
+       if (!fuse_is_iomap_file_write(opflags))
+               return false;
+
+       /* Appending writes get an iomap_end call */
+       if (iomap->flags & IOMAP_F_SIZE_CHANGED)
+               return true;
+
+       /* Short writes get an iomap_end call to clean up delalloc */
+       return written < count;
+}
+
+static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
+                         ssize_t written, unsigned opflags,
+                         struct iomap *iomap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       int err = 0;
+
+       if (fuse_should_send_iomap_end(iomap, opflags, count, written)) {
+               struct fuse_iomap_end_in inarg = {
+                       .opflags = fuse_iomap_op_to_server(opflags),
+                       .attr_ino = fi->orig_ino,
+                       .pos = pos,
+                       .count = count,
+                       .written = written,
+               };
+               FUSE_ARGS(args);
+
Quoted 8 lines

fs/fuse/file_iomap.c line 408

Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+               fuse_iomap_to_server(&inarg.map, iomap);
+
+               args.opcode = FUSE_IOMAP_END;
+               args.nodeid = get_node_id(inode);

Just curious about this - does it make sense to set args.force here for this opcode? It seems like it serves the same sort of purpose a flush request (which sets args.force) does?

What does args.force do? There's no documentation of what behaviors these fields are supposed to trigger.

Quoted 15 lines
Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+               args.in_numargs = 1;
+               args.in_args[0].size = sizeof(inarg);
+               args.in_args[0].value = &inarg;
+               err = fuse_simple_request(fm, &args);

fs/fuse/file_iomap.c line 422

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+               switch (err) {
+               case -ENOSYS:
+                       /*
+                        * libfuse returns ENOSYS for servers that don't
+                        * implement iomap_end
+                        */
+                       err = 0;
+                       break;
+               case 0:
+                       break;
Quoted 1 line

Is this case 0 needed separately from the default case?

Nah, that's just me absorbing functional brogrammerisms. ;)

--D

Quoted 42 lines

Thanks,
Joanne

Quoted 39 lines
fs/fuse/file_iomap.c new file +12 -0
+               default:
+                       break;
+               }
+       }
+
+       return err;
+}
+
+const struct iomap_ops fuse_iomap_ops = {
+       .iomap_begin            = fuse_iomap_begin,
+       .iomap_end              = fuse_iomap_end,
+};
fs/fuse/inode.c +8 -0
index 0cac7164afa298..1eea8dc6e723c6 100644
@@ -1457,6 +1457,12 @@ static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
 
                        if (flags & FUSE_REQUEST_TIMEOUT)
                                timeout = arg->request_timeout;
+
+                       if ((flags & FUSE_IOMAP) && fuse_iomap_enabled()) {
+                               fc->iomap = 1;
+                               pr_warn(
+ "EXPERIMENTAL iomap feature enabled.  Use at your own risk!");
+                       }
                } else {
                        ra_pages = fc->max_read / PAGE_SIZE;
                        fc->no_lock = 1;
@@ -1525,6 +1531,8 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
         */
        if (fuse_uring_enabled())
                flags |= FUSE_OVER_IO_URING;
+       if (fuse_iomap_enabled())
+               flags |= FUSE_IOMAP;
 
        ia->in.flags = flags;
        ia->in.flags2 = flags >> 32;
#52 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

Quoted 41 lines · Darrick J. Wong
Quoted 30 lines · Joanne Koong
Quoted 29 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

---
 fs/fuse/fuse_i.h          |   22 ++
 fs/fuse/iomap_i.h         |   36 ++++
 include/uapi/linux/fuse.h |   90 +++++++++
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1
 fs/fuse/file_iomap.c      |  434 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    8 +
 7 files changed, 621 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
fs/fuse/fuse_i.h +0 -0
index 7c7d255d817f1e..45be59df7ae592 100644
include/uapi/linux/fuse.h +0 -0
index 18713cfaf09171..7d709cf12b41a7 100644
@@ -240,6 +240,9 @@
Quoted 8 lines

include/uapi/linux/fuse.h line 244

Quoted 5 lines
include/uapi/linux/fuse.h +2 -0
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.99

Should this be changed to something like 7.46 now that this patch is submitted for merging into the tree?

Quoted 3 lines

When review of this patchset nears completion I'll change the 99s to 46 or whatever the fuse/libfuse minor version happens to be at that point.

Sounds good.

Quoted 28 lines

Nobody's touched this series since 29 October (during 6.19 development) and I've been busy with xfs_healer so I'm not submitting this for 7.0 either.

Quoted 14 lines
Quoted 14 lines
include/uapi/linux/fuse.h +12 -0
+ *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  */
 
+/* fuse-specific mapping type indicating that writes use the read mapping */
+#define FUSE_IOMAP_TYPE_PURE_OVERWRITE (255)
+
+#define FUSE_IOMAP_DEV_NULL            (0U)    /* null device cookie */
+
+/* mapping flags passed back from iomap_begin; see corresponding IOMAP_F_ */
+#define FUSE_IOMAP_F_NEW               (1U << 0)
+#define FUSE_IOMAP_F_DIRTY             (1U << 1)
+#define FUSE_IOMAP_F_SHARED            (1U << 2)
+#define FUSE_IOMAP_F_MERGED            (1U << 3)
+#define FUSE_IOMAP_F_BOUNDARY          (1U << 4)
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1344

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+#define FUSE_IOMAP_F_ANON_WRITE                (1U << 5)
+#define FUSE_IOMAP_F_ATOMIC_BIO                (1U << 6)

Do you think it makes sense to have the fuse iomap constants mirror the in-kernel iomap ones? Maybe I'm mistaken but it seems like the fuse iomap capabilities won't diverge too much from fs/iomap ones? I like that if they're mirrored, then it makes it simpler instead of needing to convert back and forth.

Quoted 6 lines

"Mirrored"? As in, having the define use a symbol:

#define FUSE_IOMAP_F_NEW IOMAP_F_NEW

instead of defining it to be a specific numerical constant like it is here?

I was thinking keeping it like it is with defining it to a specific numerical constant, but having the number correspond to the number iomap.h uses and having static asserts to ensure they match, and then being able to just pass struct fuse_iomap_io's flags directly to iomap->flags and vice versa. But I guess the iomap constants could change at any time since it's not a uapi.

Quoted 8 lines

<confused>

This might not be answering your question, but as an old iomap maintainer I want the kernel iomap api and the fuse iomap uabi to be as decoupled as they can be; and trust the compiler to notice that the flag and enum constants are the same and not do anything too stupid with the translation.

Gotcha, that makes sense.

Quoted 34 lines
Quoted 25 lines
Quoted 25 lines
include/uapi/linux/fuse.h +24 -0
+/* fuse-specific mapping flag asking for ->iomap_end call */
+#define FUSE_IOMAP_F_WANT_IOMAP_END    (1U << 7)
+
+/* mapping flags passed to iomap_end */
+#define FUSE_IOMAP_F_SIZE_CHANGED      (1U << 8)
+#define FUSE_IOMAP_F_STALE             (1U << 9)
+
+/* operation flags from iomap; see corresponding IOMAP_* */
+#define FUSE_IOMAP_OP_WRITE            (1U << 0)
+#define FUSE_IOMAP_OP_ZERO             (1U << 1)
+#define FUSE_IOMAP_OP_REPORT           (1U << 2)
+#define FUSE_IOMAP_OP_FAULT            (1U << 3)
+#define FUSE_IOMAP_OP_DIRECT           (1U << 4)
+#define FUSE_IOMAP_OP_NOWAIT           (1U << 5)
+#define FUSE_IOMAP_OP_OVERWRITE_ONLY   (1U << 6)
+#define FUSE_IOMAP_OP_UNSHARE          (1U << 7)
+#define FUSE_IOMAP_OP_DAX              (1U << 8)
+#define FUSE_IOMAP_OP_ATOMIC           (1U << 9)
+#define FUSE_IOMAP_OP_DONTCACHE                (1U << 10)
+
+#define FUSE_IOMAP_NULL_ADDR           (-1ULL) /* addr is not valid */
+
+struct fuse_iomap_io {
+       uint64_t offset;        /* file offset of mapping, bytes */
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1374

Quoted 5 lines
include/uapi/linux/fuse.h +5 -0
+       uint64_t length;        /* length of mapping, bytes */
+       uint64_t addr;          /* disk offset of mapping, bytes */
+       uint16_t type;          /* FUSE_IOMAP_TYPE_* */
+       uint16_t flags;         /* FUSE_IOMAP_F_* */
+       uint32_t dev;           /* device cookie */

Do you think it's a good idea to add a reserved field here in case we end up needing it in the future?

Quoted 2 lines

I'm open to the idea of pre-padding the structs, though that's extra copy overhead until they get used for something.

Bernd would know better than me on this, but iirc, fuse generally tries to prepad structs to avoid having to deal with backwards compatibility issues if future fields get added.

Quoted 4 lines

Does that fuse-iouring-zerocopy patchset that you're working on enable the kernel to avoid copying fuse command data around? I haven't read it in sufficient (or any) detail to know the answer to that question.

No, only the payload bypasses the copy. All the header stuff would have to get copied out to the ring.

Quoted 17 lines

Second: how easy is it to send a variable sized fuse command to userspace? It looks like some commands like FUSE_WRITE do things like:

        if (ff->fm->fc->minor < 9)
                args->in_args[0].size = FUSE_COMPAT_WRITE_IN_SIZE;
        else
                args->in_args[0].size = sizeof(ia->write.in);
        args->in_args[0].value = &ia->write.in;
        args->in_args[1].size = count;

Which means that future expansion can (in theory) bump the minor version and send larer commands.

It also looks like the kernel can support receiving variable-sized responses, like FUSE_READ does:

Quoted 7 lines
        args->out_argvar = true;
        args->out_numargs = 1;
        args->out_args[0].size = count;

I think this means that if we ever needed to expand the _out struct to allow the fuse server to send back a more lengthy response, we could potentially do that without needing a minor protocol version bump.

I'm not sure, Bernd or Miklos would know more, but my general impression has been that we try to avoid doing the FUSE_COMPAT_ stuff if we can.

Quoted 58 lines
Quoted 11 lines
Quoted 11 lines
include/uapi/linux/fuse.h +10 -0
+};
+
+struct fuse_iomap_begin_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+};
+
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1390

Quoted 6 lines
include/uapi/linux/fuse.h +6 -0
+struct fuse_iomap_begin_out {
+       /* read file data from here */
+       struct fuse_iomap_io    read;
+
+       /* write file data to here, if applicable */
+       struct fuse_iomap_io    write;

Same question here

How much padding do you want? fuse_iomap_io is conveniently half a cacheline right now...

Quoted 10 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1399

Quoted 9 lines
include/uapi/linux/fuse.h +9 -0
+};
+
+struct fuse_iomap_end_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+       int64_t written;        /* bytes processed */
Quoted 7 lines

On the fs/iomap side, I see that written is passed through by iomap_iter() to ->iomap_end through 'ssize_t advanced' but it's not clear to me why advanced needs to be signed. I think it used to also represent the error status, but it looks like now that's represented through iter->status and 'advanced' strictly reflects the number of bytes written. As such, do you think it makes sense to change 'advanced' to loff_t and have written be uint64_t instead?

Not quite -- back in the bad old days, iomap_iter::processed was a s64 value that the iteration loop had to set to one of:

* a positive number for positive progress
* zero to stop the iteration
* a negative errno to fail out

Nowadays we just move iomap_iter::pos forward via iomap_iter_advance or set status to a negative number to end the iteration.

So yes, I think @advanced should be widened to 64-bits since iomap operations can jump more than 2GB per iter step. Practically speaking I think this hasn't yet been a problem because the only operations that can do that (fiemap, seek, swap) also don't have any client filesystems that implement iomap_end; or they do but never send mappings large enough to cause problems.

Quoted 6 lines

iomap iters can't go backwards so @advanced could be u64 as well.

Also the name of the ->iomap_end parameter could be changed to "advanced" because iomap_end could in theory be called for any operation, not just writes. That's a throwback to the days when the iomap code was just part of xfs. It also is an unsigned quantity.

That makes sense, thanks for the context.

Quoted 398 lines
Quoted 36 lines
Quoted 36 lines
include/uapi/linux/fuse.h +5 -0
+
+       /* mapping that the kernel acted upon */
+       struct fuse_iomap_io    map;
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/Kconfig +21 -0
index 290d1c09e0b924..934d48076a010c 100644
@@ -69,6 +69,38 @@ config FUSE_PASSTHROUGH
 config FUSE_BACKING
        bool
 
+config FUSE_IOMAP
+       bool "FUSE file IO over iomap"
+       default y
+       depends on FUSE_FS
+       depends on BLOCK
+       select FS_IOMAP
+       help
+         Enable fuse servers to operate the regular file I/O path through
+         the fs-iomap library in the kernel.  This enables higher performance
+         userspace filesystems by keeping the performance critical parts in
+         the kernel while delegating the difficult metadata parsing parts to
+         an easily-contained userspace program.
+
+         This feature is considered EXPERIMENTAL.  Use with caution!
+
+         If unsure, say N.
+
+config FUSE_IOMAP_BY_DEFAULT
+       bool "FUSE file I/O over iomap by default"
+       default n
+       depends on FUSE_IOMAP
Quoted 8 lines

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 94

Quoted 2 lines
fs/fuse/Kconfig +2 -0
+       help
+         Enable sending FUSE file I/O over iomap by default.

I'm not really sure what the general linux preference is for adding new configs, but assuming it errs towards less configs than more, imo it seems easy enough to just set the enable_iomap module param to true manually instead of needing this config for it, especially since the param only needs to be set once.

/me doesn't know what the norm is in fuse-land -- for xfs I've preferred to have a kconfig option for experimental code so that distros can turn off experimental stuff they don't want to support.

OTOH they can also patch it out or affix the module param to 0.

Also I'm not sure if the kernel tinyfication project is still active, for a while they were advocating strongly for more kconfig options so that people building embedded kernels could turn off big chunks of functionality they'd never need.

Quoted 11 lines

fs/fuse/Kconfig config FUSE_PASSTHROUGH · line 102

Quoted 8 lines
fs/fuse/Kconfig +8 -0
+
+config FUSE_IOMAP_DEBUG
+       bool "Debug FUSE file IO over iomap"
+       default y
+       depends on FUSE_IOMAP
+       help
+         Enable debugging assertions for the fuse iomap code paths and logging
+         of bad iomap file mapping data being sent to the kernel.

I'm wondering if it makes sense to make this a general FUSE_DEBUG config so we can reuse this more generally

In general yes but I highly recommend that everyone look at the static labels and auto-ftracing stuff enabled by the next few debug patches before anyone commits to spreading that enhanced observability / brain disease to the rest of fuse. ;)

Quoted 263 lines
Quoted 262 lines
fs/fuse/Kconfig +1 -0
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/Makefile +1 -0
index 46041228e5be2c..27be39317701d6 100644
@@ -18,5 +18,6 @@ fuse-$(CONFIG_FUSE_PASSTHROUGH) += passthrough.o
 fuse-$(CONFIG_FUSE_BACKING) += backing.o
 fuse-$(CONFIG_SYSCTL) += sysctl.o
 fuse-$(CONFIG_FUSE_IO_URING) += dev_uring.o
+fuse-$(CONFIG_FUSE_IOMAP) += file_iomap.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/file_iomap.c new file +241 -0
new file mode 100644
index 00000000000000..d564d60d0f1779
@@ -0,0 +1,434 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#include <linux/iomap.h>
+#include "fuse_i.h"
+#include "fuse_trace.h"
+#include "iomap_i.h"
+
+static bool __read_mostly enable_iomap =
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
+       true;
+#else
+       false;
+#endif
+module_param(enable_iomap, bool, 0644);
+MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
+
+bool fuse_iomap_enabled(void)
+{
+       /* Don't let anyone touch iomap until the end of the patchset. */
+       return false;
+
+       /*
+        * There are fears that a fuse+iomap server could somehow DoS the
+        * system by doing things like going out to lunch during a writeback
+        * related iomap request.  Only allow iomap access if the fuse server
+        * has rawio capabilities since those processes can mess things up
+        * quite well even without our help.
+        */
+       return enable_iomap && has_capability_noaudit(current, CAP_SYS_RAWIO);
+}
+
+/* Convert IOMAP_* mapping types to FUSE_IOMAP_TYPE_* */
+#define XMAP(word) \
+       case IOMAP_##word: \
+               return FUSE_IOMAP_TYPE_##word
+static inline uint16_t fuse_iomap_type_to_server(uint16_t iomap_type)
+{
+       switch (iomap_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Convert FUSE_IOMAP_TYPE_* to IOMAP_* mapping types */
+#define XMAP(word) \
+       case FUSE_IOMAP_TYPE_##word: \
+               return IOMAP_##word
+static inline uint16_t fuse_iomap_type_from_server(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       XMAP(HOLE);
+       XMAP(DELALLOC);
+       XMAP(MAPPED);
+       XMAP(UNWRITTEN);
+       XMAP(INLINE);
+       default:
+               ASSERT(0);
+       }
+       return 0;
+}
+#undef XMAP
+
+/* Validate FUSE_IOMAP_TYPE_* */
+static inline bool fuse_iomap_check_type(uint16_t fuse_type)
+{
+       switch (fuse_type) {
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+       case FUSE_IOMAP_TYPE_INLINE:
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               return true;
+       }
+
+       return false;
+}
+
+#define FUSE_IOMAP_F_ALL (FUSE_IOMAP_F_NEW | \
+                         FUSE_IOMAP_F_DIRTY | \
+                         FUSE_IOMAP_F_SHARED | \
+                         FUSE_IOMAP_F_MERGED | \
+                         FUSE_IOMAP_F_BOUNDARY | \
+                         FUSE_IOMAP_F_ANON_WRITE | \
+                         FUSE_IOMAP_F_ATOMIC_BIO | \
+                         FUSE_IOMAP_F_WANT_IOMAP_END)
+
+static inline bool fuse_iomap_check_flags(uint16_t flags)
+{
+       return (flags & ~FUSE_IOMAP_F_ALL) == 0;
+}
+
+/* Convert IOMAP_F_* mapping state flags to FUSE_IOMAP_F_* */
+#define XMAP(word) \
+       if (iomap_f_flags & IOMAP_F_##word) \
+               ret |= FUSE_IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (iomap_f_flags & IOMAP_F_##iword) \
+               ret |= FUSE_IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_to_server(uint16_t iomap_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(PRIVATE, WANT_IOMAP_END);
+
+       XMAP(SIZE_CHANGED);
+       XMAP(STALE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert FUSE_IOMAP_F_* to IOMAP_F_* mapping state flags */
+#define XMAP(word) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##word) \
+               ret |= IOMAP_F_##word
+#define YMAP(iword, oword) \
+       if (fuse_f_flags & FUSE_IOMAP_F_##iword) \
+               ret |= IOMAP_F_##oword
+static inline uint16_t fuse_iomap_flags_from_server(uint16_t fuse_f_flags)
+{
+       uint16_t ret = 0;
+
+       XMAP(NEW);
+       XMAP(DIRTY);
+       XMAP(SHARED);
+       XMAP(MERGED);
+       XMAP(BOUNDARY);
+       XMAP(ANON_WRITE);
+       XMAP(ATOMIC_BIO);
+       YMAP(WANT_IOMAP_END, PRIVATE);
+
+       return ret;
+}
+#undef YMAP
+#undef XMAP
+
+/* Convert IOMAP_* operation flags to FUSE_IOMAP_OP_* */
+#define XMAP(word) \
+       if (iomap_op_flags & IOMAP_##word) \
+               ret |= FUSE_IOMAP_OP_##word
+static inline uint32_t fuse_iomap_op_to_server(unsigned iomap_op_flags)
+{
+       uint32_t ret = 0;
+
+       XMAP(WRITE);
+       XMAP(ZERO);
+       XMAP(REPORT);
+       XMAP(FAULT);
+       XMAP(DIRECT);
+       XMAP(NOWAIT);
+       XMAP(OVERWRITE_ONLY);
+       XMAP(UNSHARE);
+       XMAP(DAX);
+       XMAP(ATOMIC);
+       XMAP(DONTCACHE);
+
+       return ret;
+}
+#undef XMAP
+
+/* Validate an iomap mapping. */
+static inline bool fuse_iomap_check_mapping(const struct inode *inode,
+                                           const struct fuse_iomap_io *map,
+                                           enum fuse_iomap_iodir iodir)
+{
+       const unsigned int blocksize = i_blocksize(inode);
+       uint64_t end;
+
+       /* Type and flags must be known */
+       if (BAD_DATA(!fuse_iomap_check_type(map->type)))
+               return false;
+       if (BAD_DATA(!fuse_iomap_check_flags(map->flags)))
+               return false;
+
+       /* No zero-length mappings */
+       if (BAD_DATA(map->length == 0))
+               return false;
+
+       /* File range must be aligned to blocksize */
+       if (BAD_DATA(!IS_ALIGNED(map->offset, blocksize)))
+               return false;
+       if (BAD_DATA(!IS_ALIGNED(map->length, blocksize)))
+               return false;
+
+       /* No overflows in the file range */
+       if (BAD_DATA(check_add_overflow(map->offset, map->length, &end)))
+               return false;
+
+       /* File range cannot start past maxbytes */
+       if (BAD_DATA(map->offset >= inode->i_sb->s_maxbytes))
+               return false;
+
+       switch (map->type) {
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+               /* Mappings backed by space must have a device/addr */
+               if (BAD_DATA(map->dev == FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr == FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_DELALLOC:
+       case FUSE_IOMAP_TYPE_HOLE:
+       case FUSE_IOMAP_TYPE_INLINE:
+               /* Mappings not backed by space cannot have a device addr. */
+               if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+                       return false;
+               if (BAD_DATA(map->addr != FUSE_IOMAP_NULL_ADDR))
+                       return false;
+               break;
+       case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+               /* "Pure overwrite" only allowed for write mapping */
+               if (BAD_DATA(iodir != WRITE_MAPPING))
+                       return false;
+               break;
+       default:
+               /* should have been caught already */
+               ASSERT(0);
+               return false;
+       }
+
+       /* XXX: we don't support devices yet */
Quoted 15 lines

fs/fuse/file_iomap.c line 254

Quoted 13 lines
fs/fuse/file_iomap.c new file +13 -0
+       if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
+               return false;
+
+       /* No overflows in the device range, if supplied */
+       if (map->addr != FUSE_IOMAP_NULL_ADDR &&
+           BAD_DATA(check_add_overflow(map->addr, map->length, &end)))
+               return false;
+
+       return true;
+}
+
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct inode *inode,

Maybe worth adding a const in front of struct inode?

It can go away in a patch or two when we wire up bdev support.

Though considering that fuse_iomap_enabled returns false all the way to the end of the patchset I guess I could just set bdev to null and skip passing in the inode at all.

Quoted 17 lines
Quoted 17 lines
fs/fuse/file_iomap.c new file +17 -0
+                                         struct iomap *iomap,
+                                         const struct fuse_iomap_io *fmap)
+{
+       iomap->addr = fmap->addr;
+       iomap->offset = fmap->offset;
+       iomap->length = fmap->length;
+       iomap->type = fuse_iomap_type_from_server(fmap->type);
+       iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+       iomap->bdev = inode->i_sb->s_bdev; /* XXX */
+}
+
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+                                       const struct iomap *iomap)
+{
+       fmap->addr = FUSE_IOMAP_NULL_ADDR; /* XXX */
+       fmap->offset = iomap->offset;
Quoted 8 lines

fs/fuse/file_iomap.c line 275

Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+       fmap->length = iomap->length;
+       fmap->type = fuse_iomap_type_to_server(iomap->type);
+       fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+       fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */

AFAICT, this only gets used for sending the FUSE_IOMAP_END request. Is passing the iomap->addr to fmap->addr and inode->i_sb->s_bdev to fmap->dev not useful to the server here?

So far the only fields I've needed in fuse4fs are the offset/count/written fields as provided by iomap_iter, and the flags field from the mapping. The addr field isn't necessary for fuse4fs because the fuse server would know if the mapping had changed. OTOH it's probably harmless to send it along.

Hrm. I probably need a way to look up the backing_id from the iomap bdev.

Looking further ahead at the ioend patch, I just realized that iomap ioends can tell you the new address of a write-append operation but they don't tell you which device. I guess you can read that from the ioend->io_bio.bi_bdev.

Quoted 4 lines
Quoted 1 line

Also, did you mean to leave in the /* XXX */ comments?

Yes, because they're a reminder to come back and check if I /ever/ needed them.

Makes sense, seems like you're planning to remove them when the patch is ready to merge, if I understand correctly.

Quoted 139 lines
Quoted 130 lines
Quoted 130 lines
fs/fuse/file_iomap.c new file +129 -0
+}
+
+/* Check the incoming _begin mappings to make sure they're not nonsense. */
+static inline int
+fuse_iomap_begin_validate(const struct inode *inode,
+                         unsigned opflags, loff_t pos,
+                         const struct fuse_iomap_begin_out *outarg)
+{
+       /* Make sure the mappings aren't garbage */
+       if (!fuse_iomap_check_mapping(inode, &outarg->read, READ_MAPPING))
+               return -EFSCORRUPTED;
+
+       if (!fuse_iomap_check_mapping(inode, &outarg->write, WRITE_MAPPING))
+               return -EFSCORRUPTED;
+
+       /*
+        * Must have returned a mapping for at least the first byte in the
+        * range.  The main mapping check already validated that the length
+        * is nonzero and there is no overflow in computing end.
+        */
+       if (BAD_DATA(outarg->read.offset > pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset > pos))
+               return -EFSCORRUPTED;
+
+       if (BAD_DATA(outarg->read.offset + outarg->read.length <= pos))
+               return -EFSCORRUPTED;
+       if (BAD_DATA(outarg->write.offset + outarg->write.length <= pos))
+               return -EFSCORRUPTED;
+
+       return 0;
+}
+
+static inline bool fuse_is_iomap_file_write(unsigned int opflags)
+{
+       return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE);
+}
+
+static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
+                           unsigned opflags, struct iomap *iomap,
+                           struct iomap *srcmap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_iomap_begin_in inarg = {
+               .attr_ino = fi->orig_ino,
+               .opflags = fuse_iomap_op_to_server(opflags),
+               .pos = pos,
+               .count = count,
+       };
+       struct fuse_iomap_begin_out outarg = { };
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       FUSE_ARGS(args);
+       int err;
+
+       args.opcode = FUSE_IOMAP_BEGIN;
+       args.nodeid = get_node_id(inode);
+       args.in_numargs = 1;
+       args.in_args[0].size = sizeof(inarg);
+       args.in_args[0].value = &inarg;
+       args.out_numargs = 1;
+       args.out_args[0].size = sizeof(outarg);
+       args.out_args[0].value = &outarg;
+       err = fuse_simple_request(fm, &args);
+       if (err)
+               return err;
+
+       err = fuse_iomap_begin_validate(inode, opflags, pos, &outarg);
+       if (err)
+               return err;
+
+       if (fuse_is_iomap_file_write(opflags) &&
+           outarg.write.type != FUSE_IOMAP_TYPE_PURE_OVERWRITE) {
+               /*
+                * For an out of place write, we must supply the write mapping
+                * via @iomap, and the read mapping via @srcmap.
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.write);
+               fuse_iomap_from_server(inode, srcmap, &outarg.read);
+       } else {
+               /*
+                * For everything else (reads, reporting, and pure overwrites),
+                * we can return the sole mapping through @iomap and leave
+                * @srcmap unchanged from its default (HOLE).
+                */
+               fuse_iomap_from_server(inode, iomap, &outarg.read);
+       }
+
+       return 0;
+}
+
+/* Decide if we send FUSE_IOMAP_END to the fuse server */
+static bool fuse_should_send_iomap_end(const struct iomap *iomap,
+                                      unsigned int opflags, loff_t count,
+                                      ssize_t written)
+{
+       /* fuse server demanded an iomap_end call. */
+       if (iomap->flags & FUSE_IOMAP_F_WANT_IOMAP_END)
+               return true;
+
+       /* Reads and reporting should never affect the filesystem metadata */
+       if (!fuse_is_iomap_file_write(opflags))
+               return false;
+
+       /* Appending writes get an iomap_end call */
+       if (iomap->flags & IOMAP_F_SIZE_CHANGED)
+               return true;
+
+       /* Short writes get an iomap_end call to clean up delalloc */
+       return written < count;
+}
+
+static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
+                         ssize_t written, unsigned opflags,
+                         struct iomap *iomap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       int err = 0;
+
+       if (fuse_should_send_iomap_end(iomap, opflags, count, written)) {
+               struct fuse_iomap_end_in inarg = {
+                       .opflags = fuse_iomap_op_to_server(opflags),
+                       .attr_ino = fi->orig_ino,
+                       .pos = pos,
+                       .count = count,
+                       .written = written,
+               };
+               FUSE_ARGS(args);
+
Quoted 8 lines

fs/fuse/file_iomap.c line 408

Quoted 4 lines
fs/fuse/file_iomap.c new file +4 -0
+               fuse_iomap_to_server(&inarg.map, iomap);
+
+               args.opcode = FUSE_IOMAP_END;
+               args.nodeid = get_node_id(inode);

Just curious about this - does it make sense to set args.force here for this opcode? It seems like it serves the same sort of purpose a flush request (which sets args.force) does?

Quoted 2 lines

What does args.force do? There's no documentation of what behaviors these fields are supposed to trigger.

The args.force forces the request to be sent even if it gets interrupted by a signal. It'll also bypass the fuse_block_alloc() check when sending the request, but I don't think that's too relevant to this case.

Thanks,
Joanne

Quoted 64 lines
Quoted 16 lines
Quoted 5 lines
fs/fuse/file_iomap.c new file +4 -0
+               args.in_numargs = 1;
+               args.in_args[0].size = sizeof(inarg);
+               args.in_args[0].value = &inarg;
+               err = fuse_simple_request(fm, &args);

fs/fuse/file_iomap.c line 422

Quoted 10 lines
fs/fuse/file_iomap.c new file +10 -0
+               switch (err) {
+               case -ENOSYS:
+                       /*
+                        * libfuse returns ENOSYS for servers that don't
+                        * implement iomap_end
+                        */
+                       err = 0;
+                       break;
+               case 0:
+                       break;
Quoted 1 line

Is this case 0 needed separately from the default case?

Nah, that's just me absorbing functional brogrammerisms. ;)

--D

Quoted 42 lines

Thanks,
Joanne

Quoted 39 lines
fs/fuse/file_iomap.c new file +12 -0
+               default:
+                       break;
+               }
+       }
+
+       return err;
+}
+
+const struct iomap_ops fuse_iomap_ops = {
+       .iomap_begin            = fuse_iomap_begin,
+       .iomap_end              = fuse_iomap_end,
+};
fs/fuse/inode.c +8 -0
index 0cac7164afa298..1eea8dc6e723c6 100644
@@ -1457,6 +1457,12 @@ static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
 
                        if (flags & FUSE_REQUEST_TIMEOUT)
                                timeout = arg->request_timeout;
+
+                       if ((flags & FUSE_IOMAP) && fuse_iomap_enabled()) {
+                               fc->iomap = 1;
+                               pr_warn(
+ "EXPERIMENTAL iomap feature enabled.  Use at your own risk!");
+                       }
                } else {
                        ra_pages = fc->max_read / PAGE_SIZE;
                        fc->no_lock = 1;
@@ -1525,6 +1531,8 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
         */
        if (fuse_uring_enabled())
                flags |= FUSE_OVER_IO_URING;
+       if (fuse_iomap_enabled())
+               flags |= FUSE_IOMAP;
 
        ia->in.flags = flags;
        ia->in.flags2 = flags >> 32;
#53 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

Quoted 42 lines · Joanne Koong
Quoted 41 lines · Darrick J. Wong
Quoted 38 lines · Joanne Koong
Quoted 29 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

---
 fs/fuse/fuse_i.h          |   22 ++
 fs/fuse/iomap_i.h         |   36 ++++
 include/uapi/linux/fuse.h |   90 +++++++++
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1
 fs/fuse/file_iomap.c      |  434 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    8 +
 7 files changed, 621 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/iomap_i.h
 create mode 100644 fs/fuse/file_iomap.c
fs/fuse/fuse_i.h +0 -0
index 7c7d255d817f1e..45be59df7ae592 100644
include/uapi/linux/fuse.h +0 -0
index 18713cfaf09171..7d709cf12b41a7 100644

include/uapi/linux/fuse.h line 244

Quoted 5 lines
include/uapi/linux/fuse.h +2 -0
@@ -240,6 +240,9 @@
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.99

Should this be changed to something like 7.46 now that this patch is submitted for merging into the tree?

Quoted 5 lines
Quoted 3 lines

When review of this patchset nears completion I'll change the 99s to 46 or whatever the fuse/libfuse minor version happens to be at that point.

Sounds good.

I'll add another XXX comment here to increase the likelihood it doesn't get missed.

Quoted 35 lines
Quoted 28 lines

Nobody's touched this series since 29 October (during 6.19 development) and I've been busy with xfs_healer so I'm not submitting this for 7.0 either.

Quoted 14 lines
Quoted 14 lines
include/uapi/linux/fuse.h +12 -0
+ *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  */
 
+/* fuse-specific mapping type indicating that writes use the read mapping */
+#define FUSE_IOMAP_TYPE_PURE_OVERWRITE (255)
+
+#define FUSE_IOMAP_DEV_NULL            (0U)    /* null device cookie */
+
+/* mapping flags passed back from iomap_begin; see corresponding IOMAP_F_ */
+#define FUSE_IOMAP_F_NEW               (1U << 0)
+#define FUSE_IOMAP_F_DIRTY             (1U << 1)
+#define FUSE_IOMAP_F_SHARED            (1U << 2)
+#define FUSE_IOMAP_F_MERGED            (1U << 3)
+#define FUSE_IOMAP_F_BOUNDARY          (1U << 4)
Quoted 8 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1344

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+#define FUSE_IOMAP_F_ANON_WRITE                (1U << 5)
+#define FUSE_IOMAP_F_ATOMIC_BIO                (1U << 6)

Do you think it makes sense to have the fuse iomap constants mirror the in-kernel iomap ones? Maybe I'm mistaken but it seems like the fuse iomap capabilities won't diverge too much from fs/iomap ones? I like that if they're mirrored, then it makes it simpler instead of needing to convert back and forth.

Quoted 6 lines

"Mirrored"? As in, having the define use a symbol:

#define FUSE_IOMAP_F_NEW IOMAP_F_NEW

instead of defining it to be a specific numerical constant like it is here?

Quoted 6 lines

I was thinking keeping it like it is with defining it to a specific numerical constant, but having the number correspond to the number iomap.h uses and having static asserts to ensure they match, and then being able to just pass struct fuse_iomap_io's flags directly to iomap->flags and vice versa. But I guess the iomap constants could change at any time since it's not a uapi.

Yep. iomap's api stability is only guaranteed until the mtime changes on include/linux/iomap.h.

I actually /did/ do the static assert thing earlier in the lifetime of this patchset, but then I godbolted what the conversion functions were actually doing and observed that gcc and clang are smart enough to collapse all the C code into the appropriate masking if you compile with -O2.

<snip>

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1374

Quoted 7 lines
include/uapi/linux/fuse.h +7 -0
+struct fuse_iomap_io {
+       uint64_t offset;        /* file offset of mapping, bytes */
+       uint64_t length;        /* length of mapping, bytes */
+       uint64_t addr;          /* disk offset of mapping, bytes */
+       uint16_t type;          /* FUSE_IOMAP_TYPE_* */
+       uint16_t flags;         /* FUSE_IOMAP_F_* */
+       uint32_t dev;           /* device cookie */

Do you think it's a good idea to add a reserved field here in case we end up needing it in the future?

Quoted 6 lines
Quoted 2 lines

I'm open to the idea of pre-padding the structs, though that's extra copy overhead until they get used for something.

Bernd would know better than me on this, but iirc, fuse generally tries to prepad structs to avoid having to deal with backwards compatibility issues if future fields get added.

<nod> for xfs I've generally added one u64 unless two would round us up to a cacheline... or just defined the struct size to be something insane like 512 bytes.

Quoted 7 lines
Quoted 4 lines

Does that fuse-iouring-zerocopy patchset that you're working on enable the kernel to avoid copying fuse command data around? I haven't read it in sufficient (or any) detail to know the answer to that question.

No, only the payload bypasses the copy. All the header stuff would have to get copied out to the ring.

D'oh! :/

Quoted 21 lines
Quoted 21 lines

Second: how easy is it to send a variable sized fuse command to userspace? It looks like some commands like FUSE_WRITE do things like:

        if (ff->fm->fc->minor < 9)
                args->in_args[0].size = FUSE_COMPAT_WRITE_IN_SIZE;
        else
                args->in_args[0].size = sizeof(ia->write.in);
        args->in_args[0].value = &ia->write.in;
        args->in_args[1].size = count;

Which means that future expansion can (in theory) bump the minor version and send larer commands.

It also looks like the kernel can support receiving variable-sized responses, like FUSE_READ does:

        args->out_argvar = true;
        args->out_numargs = 1;
        args->out_args[0].size = count;
Quoted 7 lines
Quoted 3 lines

I think this means that if we ever needed to expand the _out struct to allow the fuse server to send back a more lengthy response, we could potentially do that without needing a minor protocol version bump.

I'm not sure, Bernd or Miklos would know more, but my general impression has been that we try to avoid doing the FUSE_COMPAT_ stuff if we can.

<nod> revving the minor protocol version will take time to propagate.

<snip>

Quoted 21 lines
Quoted 21 lines
Quoted 10 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1399

Quoted 9 lines
include/uapi/linux/fuse.h +9 -0
+};
+
+struct fuse_iomap_end_in {
+       uint32_t opflags;       /* FUSE_IOMAP_OP_* */
+       uint32_t reserved;      /* zero */
+       uint64_t attr_ino;      /* matches fuse_attr:ino */
+       uint64_t pos;           /* file position, in bytes */
+       uint64_t count;         /* operation length, in bytes */
+       int64_t written;        /* bytes processed */
Quoted 7 lines

On the fs/iomap side, I see that written is passed through by iomap_iter() to ->iomap_end through 'ssize_t advanced' but it's not clear to me why advanced needs to be signed. I think it used to also represent the error status, but it looks like now that's represented through iter->status and 'advanced' strictly reflects the number of bytes written. As such, do you think it makes sense to change 'advanced' to loff_t and have written be uint64_t instead?

Not quite -- back in the bad old days, iomap_iter::processed was a s64 value that the iteration loop had to set to one of:

Quoted 6 lines
Quoted 6 lines

* a positive number for positive progress
* zero to stop the iteration
* a negative errno to fail out

Nowadays we just move iomap_iter::pos forward via iomap_iter_advance or set status to a negative number to end the iteration.

Slight inaccuracy: one sets iter->status to a negative number to fail out of the iteration. To end early, they should call iomap_iter without calling iomap_iter_advance.

Quoted 7 lines
Quoted 7 lines

So yes, I think @advanced should be widened to 64-bits since iomap operations can jump more than 2GB per iter step. Practically speaking I think this hasn't yet been a problem because the only operations that can do that (fiemap, seek, swap) also don't have any client filesystems that implement iomap_end; or they do but never send mappings large enough to cause problems.

Quoted 8 lines
Quoted 6 lines

iomap iters can't go backwards so @advanced could be u64 as well.

Also the name of the ->iomap_end parameter could be changed to "advanced" because iomap_end could in theory be called for any operation, not just writes. That's a throwback to the days when the iomap code was just part of xfs. It also is an unsigned quantity.

That makes sense, thanks for the context.

<nod>

<snip>

Quoted 10 lines
Quoted 10 lines
Quoted 4 lines

include/uapi/linux/fuse.h

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct inode *inode,

Maybe worth adding a const in front of struct inode?

It can go away in a patch or two when we wire up bdev support.

Though considering that fuse_iomap_enabled returns false all the way to the end of the patchset I guess I could just set bdev to null and skip passing in the inode at all.

Done.

Quoted 40 lines
Quoted 40 lines
Quoted 17 lines
Quoted 17 lines
include/uapi/linux/fuse.h +17 -0
+                                         struct iomap *iomap,
+                                         const struct fuse_iomap_io *fmap)
+{
+       iomap->addr = fmap->addr;
+       iomap->offset = fmap->offset;
+       iomap->length = fmap->length;
+       iomap->type = fuse_iomap_type_from_server(fmap->type);
+       iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+       iomap->bdev = inode->i_sb->s_bdev; /* XXX */
+}
+
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+                                       const struct iomap *iomap)
+{
+       fmap->addr = FUSE_IOMAP_NULL_ADDR; /* XXX */
+       fmap->offset = iomap->offset;
Quoted 8 lines

include/uapi/linux/fuse.h

Quoted 4 lines
include/uapi/linux/fuse.h +4 -0
+       fmap->length = iomap->length;
+       fmap->type = fuse_iomap_type_to_server(iomap->type);
+       fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+       fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */

AFAICT, this only gets used for sending the FUSE_IOMAP_END request. Is passing the iomap->addr to fmap->addr and inode->i_sb->s_bdev to fmap->dev not useful to the server here?

So far the only fields I've needed in fuse4fs are the offset/count/written fields as provided by iomap_iter, and the flags field from the mapping. The addr field isn't necessary for fuse4fs because the fuse server would know if the mapping had changed. OTOH it's probably harmless to send it along.

Hrm. I probably need a way to look up the backing_id from the iomap bdev.

Looking further ahead at the ioend patch, I just realized that iomap ioends can tell you the new address of a write-append operation but they don't tell you which device. I guess you can read that from the ioend->io_bio.bi_bdev.

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

Also, did you mean to leave in the /* XXX */ comments?

Yes, because they're a reminder to come back and check if I /ever/ needed them.

Makes sense, seems like you're planning to remove them when the patch is ready to merge, if I understand correctly.

Yeah. I also fixed this fuse_iomap_to_server to set fmap->dev.

<snip>

Quoted 27 lines
Quoted 27 lines
Quoted 26 lines
Quoted 12 lines
include/uapi/linux/fuse.h +12 -0
+static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
+                         ssize_t written, unsigned opflags,
+                         struct iomap *iomap)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+       struct fuse_mount *fm = get_fuse_mount(inode);
+       int err = 0;
+
+       if (fuse_should_send_iomap_end(iomap, opflags, count, written)) {
+               struct fuse_iomap_end_in inarg = {
+                       .opflags = fuse_iomap_op_to_server(opflags),
+                       .attr_ino = fi->orig_ino,

include/uapi/linux/fuse.h

Quoted 10 lines
include/uapi/linux/fuse.h +10 -0
+                       .pos = pos,
+                       .count = count,
+                       .written = written,
+               };
+               FUSE_ARGS(args);
+
+               fuse_iomap_to_server(&inarg.map, iomap);
+
+               args.opcode = FUSE_IOMAP_END;
+               args.nodeid = get_node_id(inode);

Just curious about this - does it make sense to set args.force here for this opcode? It seems like it serves the same sort of purpose a flush request (which sets args.force) does?

Quoted 7 lines
Quoted 2 lines

What does args.force do? There's no documentation of what behaviors these fields are supposed to trigger.

The args.force forces the request to be sent even if it gets interrupted by a signal. It'll also bypass the fuse_block_alloc() check when sending the request, but I don't think that's too relevant to this case.

Hrm. For iomap_begin I think it's ok if a signal kills the IO operation. For iomap_end ... I guess we really should force the command out to the server in case it needs to clean up, even if the user is hammering on kill -9.

For iomap_ioend the same probably applies, but it's called from workqueue context so there's not going to be a fatal signal. But maybe we should do that, just in case someone develops motivation to make directio completions run in the caller's context or something.

--D

#54 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

In reply to Darrick J. Wong
Quoted 5 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

Hi everyone,

I'm trying out my AI review prompts on a few more trees, and I ran it on the fuse-iomap-cache branch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-cache

This was the latest email lore could find, apologies if I grabbed the wrong one.

Hopefully the review below is useful, please let me know if there are places it has gone wildly wrong. I kept the header to make it obvious exactly which commit I'd run through:

(I don't fully understand why it calls out commit b3f5bd5243, looks like it's probably just the last place that changes nearby code)

commit 99dffae5966f9647a430fa4c9198e2d2dacae172
Author: Darrick J. Wong <[email protected]>

fuse: implement the basic iomap mechanisms

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

Quoted 5 lines
fs/fuse/fuse_iomap.c new file +0 -0
new file mode 100644
index 0000000000000..d1c2c2e1e68b8

[ ... ]

Quoted 1 line
fs/fuse/fuse_iomap.c new file +0 -0
@@ -0,0 +1,430 @@

[ ... ]

Quoted 7 lines
fs/fuse/fuse_iomap.c new file +7 -0
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct iomap *iomap,
+					  const struct fuse_iomap_io *fmap)
+{
+	iomap->addr = fmap->addr;
+	iomap->offset = fmap->offset;
+	iomap->length = fmap->length;

fs/fuse/fuse_iomap.c

Quoted 10 lines
fs/fuse/fuse_iomap.c new file +10 -0
+	iomap->type = fuse_iomap_type_from_server(fmap->type);
+	iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+	iomap->bdev = NULL; /* XXX */
+}
+
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+					const struct iomap *iomap)
+{
+	fmap->addr = fmap->addr;
                     ^^^^

Does fmap->addr get the wrong value here? Looking at fuse_iomap_from_server() just above, it correctly does iomap->addr = fmap->addr. This function appears to have the reverse bug, assigning fmap->addr to itself instead of fmap->addr = iomap->addr. The other fields (offset, length, type, flags) all correctly copy from iomap.

This would cause fuse_iomap_end() to send uninitialized or garbage data in the addr field when calling fuse_iomap_to_server(&inarg.map, iomap).

This bug persists unfixed through commit b3f5bd524315 later in the series.

Quoted 6 lines
fs/fuse/fuse_iomap.c new file +6 -0
+	fmap->offset = iomap->offset;
+	fmap->length = iomap->length;
+	fmap->type = fuse_iomap_type_to_server(iomap->type);
+	fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+	fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */
+}
#55 lore raw

Re: [PATCH 01/31] fuse: implement the basic iomap mechanisms

Quoted 68 lines · Chris Mason
Quoted 5 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

Hi everyone,

I'm trying out my AI review prompts on a few more trees, and I ran it on the fuse-iomap-cache branch:

https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=fuse-iomap-cache

This was the latest email lore could find, apologies if I grabbed the wrong one.

Hopefully the review below is useful, please let me know if there are places it has gone wildly wrong. I kept the header to make it obvious exactly which commit I'd run through:

(I don't fully understand why it calls out commit b3f5bd5243, looks like it's probably just the last place that changes nearby code)

commit 99dffae5966f9647a430fa4c9198e2d2dacae172
Author: Darrick J. Wong <[email protected]>

fuse: implement the basic iomap mechanisms

Implement functions to enable upcalling of iomap_begin and iomap_end to userspace fuse servers.

Quoted 5 lines
fs/fuse/fuse_iomap.c new file +0 -0
new file mode 100644
index 0000000000000..d1c2c2e1e68b8

[ ... ]

Quoted 1 line
fs/fuse/fuse_iomap.c new file +0 -0
@@ -0,0 +1,430 @@

[ ... ]

Quoted 7 lines
fs/fuse/fuse_iomap.c new file +7 -0
+/* Convert a mapping from the server into something the kernel can use */
+static inline void fuse_iomap_from_server(struct iomap *iomap,
+					  const struct fuse_iomap_io *fmap)
+{
+	iomap->addr = fmap->addr;
+	iomap->offset = fmap->offset;
+	iomap->length = fmap->length;

fs/fuse/fuse_iomap.c

Quoted 10 lines
fs/fuse/fuse_iomap.c new file +10 -0
+	iomap->type = fuse_iomap_type_from_server(fmap->type);
+	iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
+	iomap->bdev = NULL; /* XXX */
+}
+
+/* Convert a mapping from the kernel into something the server can use */
+static inline void fuse_iomap_to_server(struct fuse_iomap_io *fmap,
+					const struct iomap *iomap)
+{
+	fmap->addr = fmap->addr;
                     ^^^^

Does fmap->addr get the wrong value here? Looking at fuse_iomap_from_server() just above, it correctly does iomap->addr = fmap->addr. This function appears to have the reverse bug, assigning fmap->addr to itself instead of fmap->addr = iomap->addr. The other fields (offset, length, type, flags) all correctly copy from iomap.

Quoted 5 lines

This would cause fuse_iomap_end() to send uninitialized or garbage data in the addr field when calling fuse_iomap_to_server(&inarg.map, iomap).

This bug persists unfixed through commit b3f5bd524315 later in the series.

Yep, that's a copy-paste error from above; good catch!

--D

Quoted 8 lines
Quoted 6 lines
fs/fuse/fuse_iomap.c new file +6 -0
+	fmap->offset = iomap->offset;
+	fmap->length = iomap->length;
+	fmap->type = fuse_iomap_type_to_server(iomap->type);
+	fmap->flags = fuse_iomap_flags_to_server(iomap->flags);
+	fmap->dev = FUSE_IOMAP_DEV_NULL; /* XXX */
+}
#56 lore raw

PATCH 2/31 fuse_trace: implement the basic iomap mechanisms

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |  295 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/iomap_i.h    |    6 +
 fs/fuse/file_iomap.c |   12 ++
 3 files changed, 312 insertions(+), 1 deletion(-)
fs/fuse/fuse_trace.h +295 -0
index 286a0845dc0898..c0878253e7c6ad 100644
@@ -58,6 +58,8 @@
 	EM( FUSE_SYNCFS,		"FUSE_SYNCFS")		\
 	EM( FUSE_TMPFILE,		"FUSE_TMPFILE")		\
 	EM( FUSE_STATX,			"FUSE_STATX")		\
+	EM( FUSE_IOMAP_BEGIN,		"FUSE_IOMAP_BEGIN")	\
+	EM( FUSE_IOMAP_END,		"FUSE_IOMAP_END")	\
 	EMe(CUSE_INIT,			"CUSE_INIT")
 
 /*
@@ -77,6 +79,54 @@ OPCODES
 #define EM(a, b)	{a, b},
 #define EMe(a, b)	{a, b}
 
+/* tracepoint boilerplate so we don't have to keep doing this */
+#define FUSE_INODE_FIELDS \
+		__field(dev_t,			connection) \
+		__field(uint64_t,		ino) \
+		__field(uint64_t,		nodeid) \
+		__field(loff_t,			isize)
+
+#define FUSE_INODE_ASSIGN(inode, fi, fm) \
+		const struct fuse_inode *fi = get_fuse_inode(inode); \
+		const struct fuse_mount *fm = get_fuse_mount(inode); \
+\
+		__entry->connection	=	(fm)->fc->dev; \
+		__entry->ino		=	(fi)->orig_ino; \
+		__entry->nodeid		=	(fi)->nodeid; \
+		__entry->isize		=	i_size_read(inode)
+
+#define FUSE_INODE_FMT \
+		"connection %u ino %llu nodeid %llu isize 0x%llx"
+
+#define FUSE_INODE_PRINTK_ARGS \
+		__entry->connection, \
+		__entry->ino, \
+		__entry->nodeid, \
+		__entry->isize
+
+#define FUSE_FILE_RANGE_FIELDS(prefix) \
+		__field(loff_t,			prefix##offset) \
+		__field(loff_t,			prefix##length)
+
+#define FUSE_FILE_RANGE_FMT(prefix) \
+		" " prefix "pos 0x%llx length 0x%llx"
+
+#define FUSE_FILE_RANGE_PRINTK_ARGS(prefix) \
+		__entry->prefix##offset, \
+		__entry->prefix##length
+
+/* combinations of boilerplate to reduce typing further */
+#define FUSE_IO_RANGE_FIELDS(prefix) \
+		FUSE_INODE_FIELDS \
+		FUSE_FILE_RANGE_FIELDS(prefix)
+
+#define FUSE_IO_RANGE_FMT(prefix) \
+		FUSE_INODE_FMT FUSE_FILE_RANGE_FMT(prefix)
+
+#define FUSE_IO_RANGE_PRINTK_ARGS(prefix) \
+		FUSE_INODE_PRINTK_ARGS, \
+		FUSE_FILE_RANGE_PRINTK_ARGS(prefix)
+
 TRACE_EVENT(fuse_request_send,
 	TP_PROTO(const struct fuse_req *req),
 
@@ -159,6 +209,251 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_open);
 DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 #endif /* CONFIG_FUSE_BACKING */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+
+/* tracepoint boilerplate so we don't have to keep doing this */
+#define FUSE_IOMAP_OPFLAGS_FIELD \
+		__field(unsigned,		opflags)
+
+#define FUSE_IOMAP_OPFLAGS_FMT \
+		" opflags (%s)"
+
+#define FUSE_IOMAP_OPFLAGS_PRINTK_ARG \
+		__print_flags(__entry->opflags, "|", FUSE_IOMAP_OP_STRINGS)
+
+#define FUSE_IOMAP_MAP_FIELDS(prefix) \
+		__field(uint64_t,		prefix##offset) \
+		__field(uint64_t,		prefix##length) \
+		__field(uint64_t,		prefix##addr) \
+		__field(uint32_t,		prefix##dev) \
+		__field(uint16_t,		prefix##type) \
+		__field(uint16_t,		prefix##flags)
+
+#define FUSE_IOMAP_MAP_FMT(prefix) \
+		" " prefix "offset 0x%llx length 0x%llx type %s dev %u addr 0x%llx mapflags (%s)"
+
+#define FUSE_IOMAP_MAP_PRINTK_ARGS(prefix) \
+		__entry->prefix##offset, \
+		__entry->prefix##length, \
+		__print_symbolic(__entry->prefix##type, FUSE_IOMAP_TYPE_STRINGS), \
+		__entry->prefix##dev, \
+		__entry->prefix##addr, \
+		__print_flags(__entry->prefix##flags, "|", FUSE_IOMAP_F_STRINGS)
+
+/* combinations of boilerplate to reduce typing further */
+#define FUSE_IOMAP_OP_FIELDS(prefix) \
+		FUSE_INODE_FIELDS \
+		FUSE_IOMAP_OPFLAGS_FIELD \
+		FUSE_FILE_RANGE_FIELDS(prefix)
+
+#define FUSE_IOMAP_OP_FMT(prefix) \
+		FUSE_INODE_FMT FUSE_IOMAP_OPFLAGS_FMT FUSE_FILE_RANGE_FMT(prefix)
+
+#define FUSE_IOMAP_OP_PRINTK_ARGS(prefix) \
+		FUSE_INODE_PRINTK_ARGS, \
+		FUSE_IOMAP_OPFLAGS_PRINTK_ARG, \
+		FUSE_FILE_RANGE_PRINTK_ARGS(prefix)
+
+/* string decoding */
+#define FUSE_IOMAP_F_STRINGS \
+	{ FUSE_IOMAP_F_NEW,			"new" }, \
+	{ FUSE_IOMAP_F_DIRTY,			"dirty" }, \
+	{ FUSE_IOMAP_F_SHARED,			"shared" }, \
+	{ FUSE_IOMAP_F_MERGED,			"merged" }, \
+	{ FUSE_IOMAP_F_BOUNDARY,		"boundary" }, \
+	{ FUSE_IOMAP_F_ANON_WRITE,		"anon_write" }, \
+	{ FUSE_IOMAP_F_ATOMIC_BIO,		"atomic" }, \
+	{ FUSE_IOMAP_F_WANT_IOMAP_END,		"iomap_end" }, \
+	{ FUSE_IOMAP_F_SIZE_CHANGED,		"append" }, \
+	{ FUSE_IOMAP_F_STALE,			"stale" }
+
+#define FUSE_IOMAP_OP_STRINGS \
+	{ FUSE_IOMAP_OP_WRITE,			"write" }, \
+	{ FUSE_IOMAP_OP_ZERO,			"zero" }, \
+	{ FUSE_IOMAP_OP_REPORT,			"report" }, \
+	{ FUSE_IOMAP_OP_FAULT,			"fault" }, \
+	{ FUSE_IOMAP_OP_DIRECT,			"direct" }, \
+	{ FUSE_IOMAP_OP_NOWAIT,			"nowait" }, \
+	{ FUSE_IOMAP_OP_OVERWRITE_ONLY,		"overwrite" }, \
+	{ FUSE_IOMAP_OP_UNSHARE,		"unshare" }, \
+	{ FUSE_IOMAP_OP_DAX,			"fsdax" }, \
+	{ FUSE_IOMAP_OP_ATOMIC,			"atomic" }, \
+	{ FUSE_IOMAP_OP_DONTCACHE,		"dontcache" }
+
+#define FUSE_IOMAP_TYPE_STRINGS \
+	{ FUSE_IOMAP_TYPE_PURE_OVERWRITE,	"overwrite" }, \
+	{ FUSE_IOMAP_TYPE_HOLE,			"hole" }, \
+	{ FUSE_IOMAP_TYPE_DELALLOC,		"delalloc" }, \
+	{ FUSE_IOMAP_TYPE_MAPPED,		"mapped" }, \
+	{ FUSE_IOMAP_TYPE_UNWRITTEN,		"unwritten" }, \
+	{ FUSE_IOMAP_TYPE_INLINE,		"inline" }
+
+DECLARE_EVENT_CLASS(fuse_iomap_check_class,
+	TP_PROTO(const char *func, int line, const char *condition),
+
+	TP_ARGS(func, line, condition),
+
+	TP_STRUCT__entry(
+		__string(func,			func)
+		__field(int,			line)
+		__string(condition,		condition)
+	),
+
+	TP_fast_assign(
+		__assign_str(func);
+		__assign_str(condition);
+		__entry->line		=	line;
+	),
+
+	TP_printk("func %s line %d condition %s", __get_str(func),
+		  __entry->line, __get_str(condition))
+);
+#define DEFINE_FUSE_IOMAP_CHECK_EVENT(name)	\
+DEFINE_EVENT(fuse_iomap_check_class, name,	\
+	TP_PROTO(const char *func, int line, const char *condition), \
+	TP_ARGS(func, line, condition))
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+DEFINE_FUSE_IOMAP_CHECK_EVENT(fuse_iomap_assert);
+#endif
+DEFINE_FUSE_IOMAP_CHECK_EVENT(fuse_iomap_bad_data);
+
+TRACE_EVENT(fuse_iomap_begin,
+	TP_PROTO(const struct inode *inode, loff_t pos, loff_t count,
+		 unsigned opflags),
+
+	TP_ARGS(inode, pos, count, opflags),
+
+	TP_STRUCT__entry(
+		FUSE_IOMAP_OP_FIELDS()
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	pos;
+		__entry->length		=	count;
+		__entry->opflags	=	opflags;
+	),
+
+	TP_printk(FUSE_IOMAP_OP_FMT(),
+		  FUSE_IOMAP_OP_PRINTK_ARGS())
+);
+
+TRACE_EVENT(fuse_iomap_begin_error,
+	TP_PROTO(const struct inode *inode, loff_t pos, loff_t count,
+		 unsigned opflags, int error),
+
+	TP_ARGS(inode, pos, count, opflags, error),
+
+	TP_STRUCT__entry(
+		FUSE_IOMAP_OP_FIELDS()
+		__field(int,			error)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	pos;
+		__entry->length		=	count;
+		__entry->opflags	=	opflags;
+		__entry->error		=	error;
+	),
+
+	TP_printk(FUSE_IOMAP_OP_FMT() " err %d",
+		  FUSE_IOMAP_OP_PRINTK_ARGS(),
+		  __entry->error)
+);
+
+DECLARE_EVENT_CLASS(fuse_iomap_mapping_class,
+	TP_PROTO(const struct inode *inode, const struct fuse_iomap_io *map),
+
+	TP_ARGS(inode, map),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		FUSE_IOMAP_MAP_FIELDS(map)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->mapoffset	=	map->offset;
+		__entry->maplength	=	map->length;
+		__entry->mapdev		=	map->dev;
+		__entry->mapaddr	=	map->addr;
+		__entry->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+	),
+
+	TP_printk(FUSE_INODE_FMT FUSE_IOMAP_MAP_FMT(),
+		  FUSE_INODE_PRINTK_ARGS,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map))
+);
+#define DEFINE_FUSE_IOMAP_MAPPING_EVENT(name)	\
+DEFINE_EVENT(fuse_iomap_mapping_class, name,	\
+	TP_PROTO(const struct inode *inode, const struct fuse_iomap_io *map), \
+	TP_ARGS(inode, map))
+DEFINE_FUSE_IOMAP_MAPPING_EVENT(fuse_iomap_read_map);
+DEFINE_FUSE_IOMAP_MAPPING_EVENT(fuse_iomap_write_map);
+
+TRACE_EVENT(fuse_iomap_end,
+	TP_PROTO(const struct inode *inode,
+		 const struct fuse_iomap_end_in *inarg),
+
+	TP_ARGS(inode, inarg),
+
+	TP_STRUCT__entry(
+		FUSE_IOMAP_OP_FIELDS()
+		__field(size_t,			written)
+		FUSE_IOMAP_MAP_FIELDS(map)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->opflags	=	inarg->opflags;
+		__entry->written	=	inarg->written;
+		__entry->offset		=	inarg->pos;
+		__entry->length		=	inarg->count;
+
+		__entry->mapoffset	=	inarg->map.offset;
+		__entry->maplength	=	inarg->map.length;
+		__entry->mapdev		=	inarg->map.dev;
+		__entry->mapaddr	=	inarg->map.addr;
+		__entry->maptype	=	inarg->map.type;
+		__entry->mapflags	=	inarg->map.flags;
+	),
+
+	TP_printk(FUSE_IOMAP_OP_FMT() " written %zd" FUSE_IOMAP_MAP_FMT(),
+		  FUSE_IOMAP_OP_PRINTK_ARGS(),
+		  __entry->written,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map))
+);
+
+TRACE_EVENT(fuse_iomap_end_error,
+	TP_PROTO(const struct inode *inode,
+		 const struct fuse_iomap_end_in *inarg, int error),
+
+	TP_ARGS(inode, inarg, error),
+
+	TP_STRUCT__entry(
+		FUSE_IOMAP_OP_FIELDS()
+		__field(size_t,			written)
+		__field(int,			error)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	inarg->pos;
+		__entry->length		=	inarg->count;
+		__entry->opflags	=	inarg->opflags;
+		__entry->written	=	inarg->written;
+		__entry->error		=	error;
+	),
+
+	TP_printk(FUSE_IOMAP_OP_FMT() " written %zd error %d",
+		  FUSE_IOMAP_OP_PRINTK_ARGS(),
+		  __entry->written,
+		  __entry->error)
+);
+#endif /* CONFIG_FUSE_IOMAP */
+
 #endif /* _TRACE_FUSE_H */
 
 #undef TRACE_INCLUDE_PATH
fs/fuse/iomap_i.h +6 -0
index d773f728579d1d..6d9ce9c0f40a04 100644
@@ -10,16 +10,22 @@
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
 # define ASSERT(condition) do {						\
 	int __cond = !!(condition);					\
+	if (unlikely(!__cond))						\
+		trace_fuse_iomap_assert(__func__, __LINE__, #condition); \
 	WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
 } while (0)
 # define BAD_DATA(condition) ({						\
 	int __cond = !!(condition);					\
+	if (unlikely(__cond))						\
+		trace_fuse_iomap_bad_data(__func__, __LINE__, #condition); \
 	WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
 })
 #else
 # define ASSERT(condition)
 # define BAD_DATA(condition) ({						\
 	int __cond = !!(condition);					\
+	if (unlikely(__cond))						\
+		trace_fuse_iomap_bad_data(__func__, __LINE__, #condition); \
 	unlikely(__cond);						\
 })
 #endif /* CONFIG_FUSE_IOMAP_DEBUG */
fs/fuse/file_iomap.c +11 -1
index d564d60d0f1779..a88f5d8d2bce15 100644
@@ -327,6 +327,8 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 	FUSE_ARGS(args);
 	int err;
 
+	trace_fuse_iomap_begin(inode, pos, count, opflags);
+
 	args.opcode = FUSE_IOMAP_BEGIN;
 	args.nodeid = get_node_id(inode);
 	args.in_numargs = 1;
@@ -336,8 +338,13 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 	args.out_args[0].size = sizeof(outarg);
 	args.out_args[0].value = &outarg;
 	err = fuse_simple_request(fm, &args);
-	if (err)
+	if (err) {
+		trace_fuse_iomap_begin_error(inode, pos, count, opflags, err);
 		return err;
+	}
+
+	trace_fuse_iomap_read_map(inode, &outarg.read);
+	trace_fuse_iomap_write_map(inode, &outarg.write);
 
 	err = fuse_iomap_begin_validate(inode, opflags, pos, &outarg);
 	if (err)
@@ -404,6 +411,8 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 
 		fuse_iomap_to_server(&inarg.map, iomap);
 
+		trace_fuse_iomap_end(inode, &inarg);
+
 		args.opcode = FUSE_IOMAP_END;
 		args.nodeid = get_node_id(inode);
 		args.in_numargs = 1;
@@ -421,6 +430,7 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 		case 0:
 			break;
 		default:
+			trace_fuse_iomap_end_error(inode, &inarg, err);
 			break;
 		}
 	}
#57 lore raw

PATCH 3/31 fuse: make debugging configurable at runtime

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Use static keys so that we can configure debugging assertions and dmesg warnings at runtime. By default this is turned off so the cost is merely scanning a nop sled. However, fuse server developers can turn it on for their debugging systems.

---
 fs/fuse/fuse_i.h     |    8 +++++
 fs/fuse/iomap_i.h    |   16 ++++++++--
 fs/fuse/Kconfig      |   15 +++++++++
 fs/fuse/file_iomap.c |   81 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    7 ++++
 5 files changed, 124 insertions(+), 3 deletions(-)
fs/fuse/fuse_i.h +8 -0
index 45be59df7ae592..61fb65f3604d61 100644
@@ -1691,6 +1691,14 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()	do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+int fuse_iomap_sysfs_init(struct kobject *kobj);
+void fuse_iomap_sysfs_cleanup(struct kobject *kobj);
+#else
+# define fuse_iomap_sysfs_init(...)		(0)
+# define fuse_iomap_sysfs_cleanup(...)		((void)0)
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 bool fuse_iomap_enabled(void);
 
fs/fuse/iomap_i.h +13 -3
index 6d9ce9c0f40a04..3615ec76c0dec0 100644
@@ -6,19 +6,29 @@
 #ifndef _FS_FUSE_IOMAP_I_H
 #define _FS_FUSE_IOMAP_I_H
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DECLARE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DECLARE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
-# define ASSERT(condition) do {						\
+# define ASSERT(condition) \
+while (static_branch_unlikely(&fuse_iomap_debug)) {			\
 	int __cond = !!(condition);					\
 	if (unlikely(!__cond))						\
 		trace_fuse_iomap_assert(__func__, __LINE__, #condition); \
 	WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
-} while (0)
+	break;								\
+}
 # define BAD_DATA(condition) ({						\
 	int __cond = !!(condition);					\
 	if (unlikely(__cond))						\
 		trace_fuse_iomap_bad_data(__func__, __LINE__, #condition); \
-	WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+	if (static_branch_unlikely(&fuse_iomap_debug))			\
+		WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+	unlikely(__cond);								\
 })
 #else
 # define ASSERT(condition)
fs/fuse/Kconfig +15 -0
index 934d48076a010c..bb867afe6e867c 100644
@@ -101,6 +101,21 @@ config FUSE_IOMAP_DEBUG
 	  Enable debugging assertions for the fuse iomap code paths and logging
 	  of bad iomap file mapping data being sent to the kernel.
 
+	  Say N here if you don't want any debugging code code compiled in at
+	  all.
+
+config FUSE_IOMAP_DEBUG_BY_DEFAULT
+	bool "Debug FUSE file IO over iomap at boot time"
+	default n
+	depends on FUSE_IOMAP_DEBUG
+	help
+	  At boot time, enable debugging assertions for the fuse iomap code
+	  paths and warnings about bad iomap file mapping data.  This enables
+	  fuse server authors to control debugging at runtime even on a
+	  distribution kernel while avoiding most of the overhead on production
+	  systems.  The setting can be changed at runtime via
+	  /sys/fs/fuse/iomap/debug.
+
 config FUSE_IO_URING
 	bool "FUSE communication over io-uring"
 	default y
fs/fuse/file_iomap.c +81 -0

93 lines not on this page · raw message

fs/fuse/inode.c +7 -0
index 1eea8dc6e723c6..eec711302a4a13 100644
@@ -2277,8 +2277,14 @@ static int fuse_sysfs_init(void)
 	if (err)
 		goto out_fuse_unregister;
 
+	err = fuse_iomap_sysfs_init(fuse_kobj);
+	if (err)
+		goto out_fuse_connections;
+
 	return 0;
 
+ out_fuse_connections:
+	sysfs_remove_mount_point(fuse_kobj, "connections");
  out_fuse_unregister:
 	kobject_put(fuse_kobj);
  out_err:
@@ -2287,6 +2293,7 @@ static int fuse_sysfs_init(void)
 
 static void fuse_sysfs_cleanup(void)
 {
+	fuse_iomap_sysfs_cleanup(fuse_kobj);
 	sysfs_remove_mount_point(fuse_kobj, "connections");
 	kobject_put(fuse_kobj);
 }
#58 lore raw

Re: [PATCH 03/31] fuse: make debugging configurable at runtime

Quoted 182 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Use static keys so that we can configure debugging assertions and dmesg warnings at runtime. By default this is turned off so the cost is merely scanning a nop sled. However, fuse server developers can turn it on for their debugging systems.

---
 fs/fuse/fuse_i.h     |    8 +++++
 fs/fuse/iomap_i.h    |   16 ++++++++--
 fs/fuse/Kconfig      |   15 +++++++++
 fs/fuse/file_iomap.c |   81 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    7 ++++
 5 files changed, 124 insertions(+), 3 deletions(-)
fs/fuse/fuse_i.h +8 -0
index 45be59df7ae592..61fb65f3604d61 100644
@@ -1691,6 +1691,14 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()       do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+int fuse_iomap_sysfs_init(struct kobject *kobj);
+void fuse_iomap_sysfs_cleanup(struct kobject *kobj);
+#else
+# define fuse_iomap_sysfs_init(...)            (0)
+# define fuse_iomap_sysfs_cleanup(...)         ((void)0)
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 bool fuse_iomap_enabled(void);
 
fs/fuse/iomap_i.h +13 -3
index 6d9ce9c0f40a04..3615ec76c0dec0 100644
@@ -6,19 +6,29 @@
 #ifndef _FS_FUSE_IOMAP_I_H
 #define _FS_FUSE_IOMAP_I_H
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DECLARE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DECLARE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
-# define ASSERT(condition) do {                                                \
+# define ASSERT(condition) \
+while (static_branch_unlikely(&fuse_iomap_debug)) {                    \
        int __cond = !!(condition);                                     \
        if (unlikely(!__cond))                                          \
                trace_fuse_iomap_assert(__func__, __LINE__, #condition); \
        WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
-} while (0)
+       break;                                                          \
+}
 # define BAD_DATA(condition) ({                                                \
        int __cond = !!(condition);                                     \
        if (unlikely(__cond))                                           \
                trace_fuse_iomap_bad_data(__func__, __LINE__, #condition); \
-       WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+       if (static_branch_unlikely(&fuse_iomap_debug))                  \
+               WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+       unlikely(__cond);                                                               \
 })
 #else
 # define ASSERT(condition)
fs/fuse/Kconfig +15 -0
index 934d48076a010c..bb867afe6e867c 100644
@@ -101,6 +101,21 @@ config FUSE_IOMAP_DEBUG
          Enable debugging assertions for the fuse iomap code paths and logging
          of bad iomap file mapping data being sent to the kernel.
 
+         Say N here if you don't want any debugging code code compiled in at
+         all.
+
+config FUSE_IOMAP_DEBUG_BY_DEFAULT
+       bool "Debug FUSE file IO over iomap at boot time"
+       default n
+       depends on FUSE_IOMAP_DEBUG
+       help
+         At boot time, enable debugging assertions for the fuse iomap code
+         paths and warnings about bad iomap file mapping data.  This enables
+         fuse server authors to control debugging at runtime even on a
+         distribution kernel while avoiding most of the overhead on production
+         systems.  The setting can be changed at runtime via
+         /sys/fs/fuse/iomap/debug.
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/file_iomap.c +67 -0
index a88f5d8d2bce15..b6fc70068c5542 100644
@@ -8,6 +8,12 @@
 #include "fuse_trace.h"
 #include "iomap_i.h"
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DEFINE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DEFINE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
        true;
@@ -17,6 +23,81 @@ static bool __read_mostly enable_iomap =
 module_param(enable_iomap, bool, 0644);
 MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+static struct kobject *iomap_kobj;
+
+static ssize_t fuse_iomap_debug_show(struct kobject *kobject,
+                                    struct kobj_attribute *a, char *buf)
+{
+       return sysfs_emit(buf, "%d\n", !!static_key_enabled(&fuse_iomap_debug));
+}
+
+static ssize_t fuse_iomap_debug_store(struct kobject *kobject,
+                                     struct kobj_attribute *a,
+                                     const char *buf, size_t count)
+{
+       int ret;
+       int val;
+
+       ret = kstrtoint(buf, 0, &val);
+       if (ret)
+               return ret;
+
+       if (val < 0 || val > 1)
+               return -EINVAL;
+
+       if (val)
+               static_branch_enable(&fuse_iomap_debug);
+       else
+               static_branch_disable(&fuse_iomap_debug);
+
+       return count;
+}
+
+#define __INIT_KOBJ_ATTR(_name, _mode, _show, _store)                  \
+{                                                                      \
+       .attr   = { .name = __stringify(_name), .mode = _mode },        \
+       .show   = _show,                                                \
+       .store  = _store,                                               \
+}
+
+#define FUSE_ATTR_RW(_name, _show, _store)                     \
+       static struct kobj_attribute fuse_attr_##_name =        \
+                       __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
+
+#define FUSE_ATTR_PTR(_name)                                   \
+       (&fuse_attr_##_name.attr)
+
+FUSE_ATTR_RW(debug, fuse_iomap_debug_show, fuse_iomap_debug_store);
+
+static const struct attribute *fuse_iomap_attrs[] = {
+       FUSE_ATTR_PTR(debug),
+       NULL,
+};
+
+int fuse_iomap_sysfs_init(struct kobject *fuse_kobj)
+{
+       int error;
+
+       iomap_kobj = kobject_create_and_add("iomap", fuse_kobj);
+       if (!iomap_kobj)
+               return -ENOMEM;
+
+       error = sysfs_create_files(iomap_kobj, fuse_iomap_attrs);

fs/fuse/file_iomap.c static bool __read_mostly enable_iomap = · line 96

Quoted 10 lines
fs/fuse/file_iomap.c +10 -0
+       if (error) {
+               kobject_put(iomap_kobj);
+               return error;
+       }
+
+       return 0;
+}
+
+void fuse_iomap_sysfs_cleanup(struct kobject *fuse_kobj)
+{

Is sysfs_remove_files() also needed here?

Quoted 28 lines
fs/fuse/file_iomap.c +4 -0
+       kobject_put(iomap_kobj);
+}
+#endif /* IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG) */
+
 bool fuse_iomap_enabled(void)
 {
        /* Don't let anyone touch iomap until the end of the patchset. */
fs/fuse/inode.c +6 -0
index 1eea8dc6e723c6..eec711302a4a13 100644
@@ -2277,8 +2277,14 @@ static int fuse_sysfs_init(void)
        if (err)
                goto out_fuse_unregister;
 
+       err = fuse_iomap_sysfs_init(fuse_kobj);
+       if (err)
+               goto out_fuse_connections;
+
        return 0;
 
+ out_fuse_connections:
+       sysfs_remove_mount_point(fuse_kobj, "connections");
  out_fuse_unregister:
        kobject_put(fuse_kobj);
  out_err:

fs/fuse/inode.c static int fuse_sysfs_init(void) · line 2299

Quoted 7 lines
fs/fuse/inode.c +1 -0
@@ -2287,6 +2293,7 @@ static int fuse_sysfs_init(void)
 
 static void fuse_sysfs_cleanup(void)
 {
+       fuse_iomap_sysfs_cleanup(fuse_kobj);
        sysfs_remove_mount_point(fuse_kobj, "connections");
        kobject_put(fuse_kobj);
 }

Could you explain why it's better that this goes through sysfs than through a module param?

Thanks,
Joanne

#59 lore raw

Re: [PATCH 03/31] fuse: make debugging configurable at runtime

Quoted 187 lines · Joanne Koong
Quoted 186 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Use static keys so that we can configure debugging assertions and dmesg warnings at runtime. By default this is turned off so the cost is merely scanning a nop sled. However, fuse server developers can turn it on for their debugging systems.

---
 fs/fuse/fuse_i.h     |    8 +++++
 fs/fuse/iomap_i.h    |   16 ++++++++--
 fs/fuse/Kconfig      |   15 +++++++++
 fs/fuse/file_iomap.c |   81 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    7 ++++
 5 files changed, 124 insertions(+), 3 deletions(-)
fs/fuse/fuse_i.h +8 -0
index 45be59df7ae592..61fb65f3604d61 100644
@@ -1691,6 +1691,14 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()       do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+int fuse_iomap_sysfs_init(struct kobject *kobj);
+void fuse_iomap_sysfs_cleanup(struct kobject *kobj);
+#else
+# define fuse_iomap_sysfs_init(...)            (0)
+# define fuse_iomap_sysfs_cleanup(...)         ((void)0)
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 bool fuse_iomap_enabled(void);
 
fs/fuse/iomap_i.h +13 -3
index 6d9ce9c0f40a04..3615ec76c0dec0 100644
@@ -6,19 +6,29 @@
 #ifndef _FS_FUSE_IOMAP_I_H
 #define _FS_FUSE_IOMAP_I_H
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DECLARE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DECLARE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
-# define ASSERT(condition) do {                                                \
+# define ASSERT(condition) \
+while (static_branch_unlikely(&fuse_iomap_debug)) {                    \
        int __cond = !!(condition);                                     \
        if (unlikely(!__cond))                                          \
                trace_fuse_iomap_assert(__func__, __LINE__, #condition); \
        WARN(!__cond, "Assertion failed: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
-} while (0)
+       break;                                                          \
+}
 # define BAD_DATA(condition) ({                                                \
        int __cond = !!(condition);                                     \
        if (unlikely(__cond))                                           \
                trace_fuse_iomap_bad_data(__func__, __LINE__, #condition); \
-       WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+       if (static_branch_unlikely(&fuse_iomap_debug))                  \
+               WARN(__cond, "Bad mapping: %s, func: %s, line: %d", #condition, __func__, __LINE__); \
+       unlikely(__cond);                                                               \
 })
 #else
 # define ASSERT(condition)
fs/fuse/Kconfig +15 -0
index 934d48076a010c..bb867afe6e867c 100644
@@ -101,6 +101,21 @@ config FUSE_IOMAP_DEBUG
          Enable debugging assertions for the fuse iomap code paths and logging
          of bad iomap file mapping data being sent to the kernel.
 
+         Say N here if you don't want any debugging code code compiled in at
+         all.
+
+config FUSE_IOMAP_DEBUG_BY_DEFAULT
+       bool "Debug FUSE file IO over iomap at boot time"
+       default n
+       depends on FUSE_IOMAP_DEBUG
+       help
+         At boot time, enable debugging assertions for the fuse iomap code
+         paths and warnings about bad iomap file mapping data.  This enables
+         fuse server authors to control debugging at runtime even on a
+         distribution kernel while avoiding most of the overhead on production
+         systems.  The setting can be changed at runtime via
+         /sys/fs/fuse/iomap/debug.
+
 config FUSE_IO_URING
        bool "FUSE communication over io-uring"
        default y
fs/fuse/file_iomap.c +71 -0
index a88f5d8d2bce15..b6fc70068c5542 100644
@@ -8,6 +8,12 @@
 #include "fuse_trace.h"
 #include "iomap_i.h"
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DEFINE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DEFINE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
        true;
@@ -17,6 +23,81 @@ static bool __read_mostly enable_iomap =
 module_param(enable_iomap, bool, 0644);
 MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+static struct kobject *iomap_kobj;
+
+static ssize_t fuse_iomap_debug_show(struct kobject *kobject,
+                                    struct kobj_attribute *a, char *buf)
+{
+       return sysfs_emit(buf, "%d\n", !!static_key_enabled(&fuse_iomap_debug));
+}
+
+static ssize_t fuse_iomap_debug_store(struct kobject *kobject,
+                                     struct kobj_attribute *a,
+                                     const char *buf, size_t count)
+{
+       int ret;
+       int val;
+
+       ret = kstrtoint(buf, 0, &val);
+       if (ret)
+               return ret;
+
+       if (val < 0 || val > 1)
+               return -EINVAL;
+
+       if (val)
+               static_branch_enable(&fuse_iomap_debug);
+       else
+               static_branch_disable(&fuse_iomap_debug);
+
+       return count;
+}
+
+#define __INIT_KOBJ_ATTR(_name, _mode, _show, _store)                  \
+{                                                                      \
+       .attr   = { .name = __stringify(_name), .mode = _mode },        \
+       .show   = _show,                                                \
+       .store  = _store,                                               \
+}
+
+#define FUSE_ATTR_RW(_name, _show, _store)                     \
+       static struct kobj_attribute fuse_attr_##_name =        \
+                       __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
+
+#define FUSE_ATTR_PTR(_name)                                   \
+       (&fuse_attr_##_name.attr)
+
+FUSE_ATTR_RW(debug, fuse_iomap_debug_show, fuse_iomap_debug_store);
+
+static const struct attribute *fuse_iomap_attrs[] = {
+       FUSE_ATTR_PTR(debug),
+       NULL,
+};
+
+int fuse_iomap_sysfs_init(struct kobject *fuse_kobj)
+{
+       int error;
+
+       iomap_kobj = kobject_create_and_add("iomap", fuse_kobj);
+       if (!iomap_kobj)
+               return -ENOMEM;
+
+       error = sysfs_create_files(iomap_kobj, fuse_iomap_attrs);
+       if (error) {
+               kobject_put(iomap_kobj);
+               return error;
+       }
Quoted 8 lines

fs/fuse/file_iomap.c static bool __read_mostly enable_iomap = · line 96

Quoted 6 lines
fs/fuse/file_iomap.c +6 -0
+
+       return 0;
+}
+
+void fuse_iomap_sysfs_cleanup(struct kobject *fuse_kobj)
+{

Is sysfs_remove_files() also needed here?

kobject_put is supposed to tear down the attrs that sysfs_create_files attaches to iomap_kobj. Though you're right to be suspicious -- there are a lot of places that explicitly call sysfs_remove_files to undo sysfs_create_files; and also a lot of places that just let kobject_put do the dirty work.

Quoted 28 lines
Quoted 28 lines
fs/fuse/file_iomap.c +4 -0
+       kobject_put(iomap_kobj);
+}
+#endif /* IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG) */
+
 bool fuse_iomap_enabled(void)
 {
        /* Don't let anyone touch iomap until the end of the patchset. */
fs/fuse/inode.c +6 -0
index 1eea8dc6e723c6..eec711302a4a13 100644
@@ -2277,8 +2277,14 @@ static int fuse_sysfs_init(void)
        if (err)
                goto out_fuse_unregister;
 
+       err = fuse_iomap_sysfs_init(fuse_kobj);
+       if (err)
+               goto out_fuse_connections;
+
        return 0;
 
+ out_fuse_connections:
+       sysfs_remove_mount_point(fuse_kobj, "connections");
  out_fuse_unregister:
        kobject_put(fuse_kobj);
  out_err:
@@ -2287,6 +2293,7 @@ static int fuse_sysfs_init(void)
 
Quoted 9 lines

fs/fuse/inode.c static int fuse_sysfs_init(void) · line 2299

Quoted 7 lines
fs/fuse/inode.c +1 -0
 static void fuse_sysfs_cleanup(void)
 {
+       fuse_iomap_sysfs_cleanup(fuse_kobj);
        sysfs_remove_mount_point(fuse_kobj, "connections");
        kobject_put(fuse_kobj);
 }

Could you explain why it's better that this goes through sysfs than through a module param?

You can dynamically enable debugging on a production system. I (by which I really mean the support org) wishes they could do that with XFS.

Module parameters don't come with setter functions so you can't call static_branch_{enable,disable} when the parameter value updates.

--D

Quoted 2 lines

Thanks,
Joanne

#60 lore raw

Re: [PATCH 03/31] fuse: make debugging configurable at runtime

Quoted 116 lines · Darrick J. Wong
Quoted 105 lines · Joanne Koong
Quoted 104 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Use static keys so that we can configure debugging assertions and dmesg warnings at runtime. By default this is turned off so the cost is merely scanning a nop sled. However, fuse server developers can turn it on for their debugging systems.

---
 fs/fuse/fuse_i.h     |    8 +++++
 fs/fuse/iomap_i.h    |   16 ++++++++--
 fs/fuse/Kconfig      |   15 +++++++++
 fs/fuse/file_iomap.c |   81 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    7 ++++
 5 files changed, 124 insertions(+), 3 deletions(-)
fs/fuse/file_iomap.c +71 -0
index a88f5d8d2bce15..b6fc70068c5542 100644
@@ -8,6 +8,12 @@
 #include "fuse_trace.h"
 #include "iomap_i.h"
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DEFINE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DEFINE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
        true;
@@ -17,6 +23,81 @@ static bool __read_mostly enable_iomap =
 module_param(enable_iomap, bool, 0644);
 MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+static struct kobject *iomap_kobj;
+
+static ssize_t fuse_iomap_debug_show(struct kobject *kobject,
+                                    struct kobj_attribute *a, char *buf)
+{
+       return sysfs_emit(buf, "%d\n", !!static_key_enabled(&fuse_iomap_debug));
+}
+
+static ssize_t fuse_iomap_debug_store(struct kobject *kobject,
+                                     struct kobj_attribute *a,
+                                     const char *buf, size_t count)
+{
+       int ret;
+       int val;
+
+       ret = kstrtoint(buf, 0, &val);
+       if (ret)
+               return ret;
+
+       if (val < 0 || val > 1)
+               return -EINVAL;
+
+       if (val)
+               static_branch_enable(&fuse_iomap_debug);
+       else
+               static_branch_disable(&fuse_iomap_debug);
+
+       return count;
+}
+
+#define __INIT_KOBJ_ATTR(_name, _mode, _show, _store)                  \
+{                                                                      \
+       .attr   = { .name = __stringify(_name), .mode = _mode },        \
+       .show   = _show,                                                \
+       .store  = _store,                                               \
+}
+
+#define FUSE_ATTR_RW(_name, _show, _store)                     \
+       static struct kobj_attribute fuse_attr_##_name =        \
+                       __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
+
+#define FUSE_ATTR_PTR(_name)                                   \
+       (&fuse_attr_##_name.attr)
+
+FUSE_ATTR_RW(debug, fuse_iomap_debug_show, fuse_iomap_debug_store);
+
+static const struct attribute *fuse_iomap_attrs[] = {
+       FUSE_ATTR_PTR(debug),
+       NULL,
+};
+
+int fuse_iomap_sysfs_init(struct kobject *fuse_kobj)
+{
+       int error;
+
+       iomap_kobj = kobject_create_and_add("iomap", fuse_kobj);
+       if (!iomap_kobj)
+               return -ENOMEM;
+
+       error = sysfs_create_files(iomap_kobj, fuse_iomap_attrs);
+       if (error) {
+               kobject_put(iomap_kobj);
+               return error;
+       }
Quoted 8 lines

fs/fuse/file_iomap.c static bool __read_mostly enable_iomap = · line 96

Quoted 6 lines
fs/fuse/file_iomap.c +6 -0
+
+       return 0;
+}
+
+void fuse_iomap_sysfs_cleanup(struct kobject *fuse_kobj)
+{

Is sysfs_remove_files() also needed here?

Quoted 5 lines

kobject_put is supposed to tear down the attrs that sysfs_create_files attaches to iomap_kobj. Though you're right to be suspicious -- there are a lot of places that explicitly call sysfs_remove_files to undo sysfs_create_files; and also a lot of places that just let kobject_put do the dirty work.

Makes sense, thanks for the context.

Quoted 39 lines
Quoted 29 lines
Quoted 29 lines
fs/fuse/file_iomap.c +4 -0
+       kobject_put(iomap_kobj);
+}
+#endif /* IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG) */
+
 bool fuse_iomap_enabled(void)
 {
        /* Don't let anyone touch iomap until the end of the patchset. */
fs/fuse/inode.c +6 -0
index 1eea8dc6e723c6..eec711302a4a13 100644
@@ -2277,8 +2277,14 @@ static int fuse_sysfs_init(void)
        if (err)
                goto out_fuse_unregister;
 
+       err = fuse_iomap_sysfs_init(fuse_kobj);
+       if (err)
+               goto out_fuse_connections;
+
        return 0;
 
+ out_fuse_connections:
+       sysfs_remove_mount_point(fuse_kobj, "connections");
  out_fuse_unregister:
        kobject_put(fuse_kobj);
  out_err:
@@ -2287,6 +2293,7 @@ static int fuse_sysfs_init(void)
 
Quoted 9 lines

fs/fuse/inode.c static int fuse_sysfs_init(void) · line 2299

Quoted 7 lines
fs/fuse/inode.c +1 -0
 static void fuse_sysfs_cleanup(void)
 {
+       fuse_iomap_sysfs_cleanup(fuse_kobj);
        sysfs_remove_mount_point(fuse_kobj, "connections");
        kobject_put(fuse_kobj);
 }

Could you explain why it's better that this goes through sysfs than through a module param?

Quoted 6 lines

You can dynamically enable debugging on a production system. I (by which I really mean the support org) wishes they could do that with XFS.

Module parameters don't come with setter functions so you can't call static_branch_{enable,disable} when the parameter value updates.

Ohh I thought the "module_param_cb()" stuff does let you do that and can be dynamically enabled/disabled as well? I mostly ask because it feels like it'd be nicer from a user POV if all the config stuff (eg enable uring, enable iomap, etc.) is in one place.

Thanks,
Joanne

Quoted 4 lines

--D

Quoted 2 lines

Thanks,
Joanne

#61 lore raw

Re: [PATCH 03/31] fuse: make debugging configurable at runtime

Quoted 166 lines · Joanne Koong
Quoted 116 lines · Darrick J. Wong
Quoted 105 lines · Joanne Koong
Quoted 104 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Use static keys so that we can configure debugging assertions and dmesg warnings at runtime. By default this is turned off so the cost is merely scanning a nop sled. However, fuse server developers can turn it on for their debugging systems.

---
 fs/fuse/fuse_i.h     |    8 +++++
 fs/fuse/iomap_i.h    |   16 ++++++++--
 fs/fuse/Kconfig      |   15 +++++++++
 fs/fuse/file_iomap.c |   81 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    7 ++++
 5 files changed, 124 insertions(+), 3 deletions(-)
fs/fuse/file_iomap.c +71 -0
index a88f5d8d2bce15..b6fc70068c5542 100644
@@ -8,6 +8,12 @@
 #include "fuse_trace.h"
 #include "iomap_i.h"
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_DEFAULT)
+DEFINE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DEFINE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif
+
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
        true;
@@ -17,6 +23,81 @@ static bool __read_mostly enable_iomap =
 module_param(enable_iomap, bool, 0644);
 MODULE_PARM_DESC(enable_iomap, "Enable file I/O through iomap");
 
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+static struct kobject *iomap_kobj;
+
+static ssize_t fuse_iomap_debug_show(struct kobject *kobject,
+                                    struct kobj_attribute *a, char *buf)
+{
+       return sysfs_emit(buf, "%d\n", !!static_key_enabled(&fuse_iomap_debug));
+}
+
+static ssize_t fuse_iomap_debug_store(struct kobject *kobject,
+                                     struct kobj_attribute *a,
+                                     const char *buf, size_t count)
+{
+       int ret;
+       int val;
+
+       ret = kstrtoint(buf, 0, &val);
+       if (ret)
+               return ret;
+
+       if (val < 0 || val > 1)
+               return -EINVAL;
+
+       if (val)
+               static_branch_enable(&fuse_iomap_debug);
+       else
+               static_branch_disable(&fuse_iomap_debug);
+
+       return count;
+}
+
+#define __INIT_KOBJ_ATTR(_name, _mode, _show, _store)                  \
+{                                                                      \
+       .attr   = { .name = __stringify(_name), .mode = _mode },        \
+       .show   = _show,                                                \
+       .store  = _store,                                               \
+}
+
+#define FUSE_ATTR_RW(_name, _show, _store)                     \
+       static struct kobj_attribute fuse_attr_##_name =        \
+                       __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
+
+#define FUSE_ATTR_PTR(_name)                                   \
+       (&fuse_attr_##_name.attr)
+
+FUSE_ATTR_RW(debug, fuse_iomap_debug_show, fuse_iomap_debug_store);
+
+static const struct attribute *fuse_iomap_attrs[] = {
+       FUSE_ATTR_PTR(debug),
+       NULL,
+};
+
+int fuse_iomap_sysfs_init(struct kobject *fuse_kobj)
+{
+       int error;
+
+       iomap_kobj = kobject_create_and_add("iomap", fuse_kobj);
+       if (!iomap_kobj)
+               return -ENOMEM;
+
+       error = sysfs_create_files(iomap_kobj, fuse_iomap_attrs);
+       if (error) {
+               kobject_put(iomap_kobj);
+               return error;
+       }
Quoted 8 lines

fs/fuse/file_iomap.c static bool __read_mostly enable_iomap = · line 96

Quoted 6 lines
fs/fuse/file_iomap.c +6 -0
+
+       return 0;
+}
+
+void fuse_iomap_sysfs_cleanup(struct kobject *fuse_kobj)
+{

Is sysfs_remove_files() also needed here?

Quoted 5 lines

kobject_put is supposed to tear down the attrs that sysfs_create_files attaches to iomap_kobj. Though you're right to be suspicious -- there are a lot of places that explicitly call sysfs_remove_files to undo sysfs_create_files; and also a lot of places that just let kobject_put do the dirty work.

Makes sense, thanks for the context.

Quoted 42 lines
Quoted 29 lines
Quoted 29 lines
fs/fuse/file_iomap.c +4 -0
+       kobject_put(iomap_kobj);
+}
+#endif /* IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG) */
+
 bool fuse_iomap_enabled(void)
 {
        /* Don't let anyone touch iomap until the end of the patchset. */
fs/fuse/inode.c +6 -0
index 1eea8dc6e723c6..eec711302a4a13 100644
@@ -2277,8 +2277,14 @@ static int fuse_sysfs_init(void)
        if (err)
                goto out_fuse_unregister;
 
+       err = fuse_iomap_sysfs_init(fuse_kobj);
+       if (err)
+               goto out_fuse_connections;
+
        return 0;
 
+ out_fuse_connections:
+       sysfs_remove_mount_point(fuse_kobj, "connections");
  out_fuse_unregister:
        kobject_put(fuse_kobj);
  out_err:
@@ -2287,6 +2293,7 @@ static int fuse_sysfs_init(void)
 
Quoted 9 lines

fs/fuse/inode.c static int fuse_sysfs_init(void) · line 2299

Quoted 7 lines
fs/fuse/inode.c +1 -0
 static void fuse_sysfs_cleanup(void)
 {
+       fuse_iomap_sysfs_cleanup(fuse_kobj);
        sysfs_remove_mount_point(fuse_kobj, "connections");
        kobject_put(fuse_kobj);
 }

Could you explain why it's better that this goes through sysfs than through a module param?

You can dynamically enable debugging on a production system. I (by which I really mean the support org) wishes they could do that with XFS.

Quoted 8 lines
Quoted 3 lines

Module parameters don't come with setter functions so you can't call static_branch_{enable,disable} when the parameter value updates.

Ohh I thought the "module_param_cb()" stuff does let you do that and can be dynamically enabled/disabled as well? I mostly ask because it feels like it'd be nicer from a user POV if all the config stuff (eg enable uring, enable iomap, etc.) is in one place.

TIL today.

HAH well that's been there since 2.6.0. Silly me, that's been there forever.

I'll switch it to a magic module parameter that has a setter. Much easier than thinking about /anything/ related to sysfs.

--D

Quoted 7 lines

Thanks,
Joanne

Quoted 4 lines

--D

Quoted 2 lines

Thanks,
Joanne

#62 lore raw

PATCH 4/31 fuse: adapt FUSE_DEV_IOC_BACKING_{OPEN,CLOSE} to add new iomap devices

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Enable the use of the backing file open/close ioctls so that fuse servers can register block devices for use with iomap.

---
 fs/fuse/fuse_i.h          |    5 ++
 include/uapi/linux/fuse.h |    3 +
 fs/fuse/Kconfig           |    1 
 fs/fuse/backing.c         |   12 +++++
 fs/fuse/file_iomap.c      |  101 +++++++++++++++++++++++++++++++++++++++++----
 fs/fuse/trace.c           |    1 
 6 files changed, 113 insertions(+), 10 deletions(-)
fs/fuse/fuse_i.h +5 -0
index 61fb65f3604d61..274de907257d94 100644
@@ -97,12 +97,14 @@ struct fuse_submount_lookup {
 };
 
 struct fuse_conn;
+struct fuse_backing;
 
 /** Operations for subsystems that want to use a backing file */
 struct fuse_backing_ops {
 	int (*may_admin)(struct fuse_conn *fc, uint32_t flags);
 	int (*may_open)(struct fuse_conn *fc, struct file *file);
 	int (*may_close)(struct fuse_conn *fc, struct file *file);
+	int (*post_open)(struct fuse_conn *fc, struct fuse_backing *fb);
 	unsigned int type;
 	int id_start;
 	int id_end;
@@ -112,6 +114,7 @@ struct fuse_backing_ops {
 struct fuse_backing {
 	struct file *file;
 	struct cred *cred;
+	struct block_device *bdev;
 	const struct fuse_backing_ops *ops;
 
 	/** refcount */
@@ -1706,6 +1709,8 @@ static inline bool fuse_has_iomap(const struct inode *inode)
 {
 	return get_fuse_conn(inode)->iomap;
 }
+
+extern const struct fuse_backing_ops fuse_iomap_backing_ops;
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
include/uapi/linux/fuse.h +2 -1
index 7d709cf12b41a7..e571f8ceecbfad 100644
@@ -1136,7 +1136,8 @@ struct fuse_notify_prune_out {
 
 #define FUSE_BACKING_TYPE_MASK		(0xFF)
 #define FUSE_BACKING_TYPE_PASSTHROUGH	(0)
-#define FUSE_BACKING_MAX_TYPE		(FUSE_BACKING_TYPE_PASSTHROUGH)
+#define FUSE_BACKING_TYPE_IOMAP		(1)
+#define FUSE_BACKING_MAX_TYPE		(FUSE_BACKING_TYPE_IOMAP)
 
 #define FUSE_BACKING_FLAGS_ALL		(FUSE_BACKING_TYPE_MASK)
 
fs/fuse/Kconfig +1 -0
index bb867afe6e867c..52803c533f47f9 100644
@@ -75,6 +75,7 @@ config FUSE_IOMAP
 	depends on FUSE_FS
 	depends on BLOCK
 	select FS_IOMAP
+	select FUSE_BACKING
 	help
 	  Enable fuse servers to operate the regular file I/O path through
 	  the fs-iomap library in the kernel.  This enables higher performance
fs/fuse/backing.c +12 -0
index b83a3c1b2dff7a..7786f6e5fd02f2 100644
@@ -90,6 +90,10 @@ fuse_backing_ops_from_map(const struct fuse_backing_map *map)
 #ifdef CONFIG_FUSE_PASSTHROUGH
 	case FUSE_BACKING_TYPE_PASSTHROUGH:
 		return &fuse_passthrough_backing_ops;
+#endif
+#ifdef CONFIG_FUSE_IOMAP
+	case FUSE_BACKING_TYPE_IOMAP:
+		return &fuse_iomap_backing_ops;
 #endif
 	default:
 		break;
@@ -138,8 +142,16 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
 	fb->file = file;
 	fb->cred = prepare_creds();
 	fb->ops = ops;
+	fb->bdev = NULL;
 	refcount_set(&fb->count, 1);
 
+	res = ops->post_open ? ops->post_open(fc, fb) : 0;
+	if (res) {
+		fuse_backing_free(fb);
+		fb = NULL;
+		goto out;
+	}
+
 	res = fuse_backing_id_alloc(fc, fb);
 	if (res < 0) {
 		fuse_backing_free(fb);
fs/fuse/file_iomap.c +92 -9

154 lines not on this page · raw message

fs/fuse/trace.c +1 -0
index 93bd72efc98cd0..68d2eecb8559a5 100644
@@ -6,6 +6,7 @@
 #include "dev_uring_i.h"
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
+#include "iomap_i.h"
 
 #include <linux/pagemap.h>
 
maintainer Reviewed-by on v1 4/31
#63 lore raw

Re: [PATCH 04/31] fuse: adapt FUSE_DEV_IOC_BACKING_{OPEN,CLOSE} to add new iomap devices

Quoted 8 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Enable the use of the backing file open/close ioctls so that fuse servers can register block devices for use with iomap.

---

Quoted 282 lines
 fs/fuse/fuse_i.h          |    5 ++
 include/uapi/linux/fuse.h |    3 +
 fs/fuse/Kconfig           |    1
 fs/fuse/backing.c         |   12 +++++
 fs/fuse/file_iomap.c      |  101 +++++++++++++++++++++++++++++++++++++++++----
 fs/fuse/trace.c           |    1
 6 files changed, 113 insertions(+), 10 deletions(-)
fs/fuse/fuse_i.h +5 -0
index 61fb65f3604d61..274de907257d94 100644
@@ -97,12 +97,14 @@ struct fuse_submount_lookup {
 };
 
 struct fuse_conn;
+struct fuse_backing;
 
 /** Operations for subsystems that want to use a backing file */
 struct fuse_backing_ops {
        int (*may_admin)(struct fuse_conn *fc, uint32_t flags);
        int (*may_open)(struct fuse_conn *fc, struct file *file);
        int (*may_close)(struct fuse_conn *fc, struct file *file);
+       int (*post_open)(struct fuse_conn *fc, struct fuse_backing *fb);
        unsigned int type;
        int id_start;
        int id_end;
@@ -112,6 +114,7 @@ struct fuse_backing_ops {
 struct fuse_backing {
        struct file *file;
        struct cred *cred;
+       struct block_device *bdev;
        const struct fuse_backing_ops *ops;
 
        /** refcount */
@@ -1706,6 +1709,8 @@ static inline bool fuse_has_iomap(const struct inode *inode)
 {
        return get_fuse_conn(inode)->iomap;
 }
+
+extern const struct fuse_backing_ops fuse_iomap_backing_ops;
 #else
 # define fuse_iomap_enabled(...)               (false)
 # define fuse_has_iomap(...)                   (false)
include/uapi/linux/fuse.h +2 -1
index 7d709cf12b41a7..e571f8ceecbfad 100644
@@ -1136,7 +1136,8 @@ struct fuse_notify_prune_out {
 
 #define FUSE_BACKING_TYPE_MASK         (0xFF)
 #define FUSE_BACKING_TYPE_PASSTHROUGH  (0)
-#define FUSE_BACKING_MAX_TYPE          (FUSE_BACKING_TYPE_PASSTHROUGH)
+#define FUSE_BACKING_TYPE_IOMAP                (1)
+#define FUSE_BACKING_MAX_TYPE          (FUSE_BACKING_TYPE_IOMAP)
 
 #define FUSE_BACKING_FLAGS_ALL         (FUSE_BACKING_TYPE_MASK)
 
fs/fuse/Kconfig +1 -0
index bb867afe6e867c..52803c533f47f9 100644
@@ -75,6 +75,7 @@ config FUSE_IOMAP
        depends on FUSE_FS
        depends on BLOCK
        select FS_IOMAP
+       select FUSE_BACKING
        help
          Enable fuse servers to operate the regular file I/O path through
          the fs-iomap library in the kernel.  This enables higher performance
fs/fuse/backing.c +12 -0
index b83a3c1b2dff7a..7786f6e5fd02f2 100644
@@ -90,6 +90,10 @@ fuse_backing_ops_from_map(const struct fuse_backing_map *map)
 #ifdef CONFIG_FUSE_PASSTHROUGH
        case FUSE_BACKING_TYPE_PASSTHROUGH:
                return &fuse_passthrough_backing_ops;
+#endif
+#ifdef CONFIG_FUSE_IOMAP
+       case FUSE_BACKING_TYPE_IOMAP:
+               return &fuse_iomap_backing_ops;
 #endif
        default:
                break;
@@ -138,8 +142,16 @@ int fuse_backing_open(struct fuse_conn *fc, struct fuse_backing_map *map)
        fb->file = file;
        fb->cred = prepare_creds();
        fb->ops = ops;
+       fb->bdev = NULL;
        refcount_set(&fb->count, 1);
 
+       res = ops->post_open ? ops->post_open(fc, fb) : 0;
+       if (res) {
+               fuse_backing_free(fb);
+               fb = NULL;
+               goto out;
+       }
+
        res = fuse_backing_id_alloc(fc, fb);
        if (res < 0) {
                fuse_backing_free(fb);
fs/fuse/file_iomap.c +92 -9
index b6fc70068c5542..e4fea3bdc0c2ce 100644
@@ -319,10 +319,6 @@ static inline bool fuse_iomap_check_mapping(const struct inode *inode,
                return false;
        }
 
-       /* XXX: we don't support devices yet */
-       if (BAD_DATA(map->dev != FUSE_IOMAP_DEV_NULL))
-               return false;
-
        /* No overflows in the device range, if supplied */
        if (map->addr != FUSE_IOMAP_NULL_ADDR &&
            BAD_DATA(check_add_overflow(map->addr, map->length, &end)))
@@ -334,6 +330,7 @@ static inline bool fuse_iomap_check_mapping(const struct inode *inode,
 /* Convert a mapping from the server into something the kernel can use */
 static inline void fuse_iomap_from_server(struct inode *inode,
                                          struct iomap *iomap,
+                                         const struct fuse_backing *fb,
                                          const struct fuse_iomap_io *fmap)
 {
        iomap->addr = fmap->addr;
@@ -341,7 +338,9 @@ static inline void fuse_iomap_from_server(struct inode *inode,
        iomap->length = fmap->length;
        iomap->type = fuse_iomap_type_from_server(fmap->type);
        iomap->flags = fuse_iomap_flags_from_server(fmap->flags);
-       iomap->bdev = inode->i_sb->s_bdev; /* XXX */
+
+       iomap->bdev = fb ? fb->bdev : NULL;
+       iomap->dax_dev = NULL;
 }
 
 /* Convert a mapping from the kernel into something the server can use */
@@ -392,6 +391,27 @@ static inline bool fuse_is_iomap_file_write(unsigned int opflags)
        return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE);
 }
 
+static inline struct fuse_backing *
+fuse_iomap_find_dev(struct fuse_conn *fc, const struct fuse_iomap_io *map)
+{
+       struct fuse_backing *ret = NULL;
+
+       if (map->dev != FUSE_IOMAP_DEV_NULL && map->dev < INT_MAX)
+               ret = fuse_backing_lookup(fc, &fuse_iomap_backing_ops,
+                                         map->dev);
+
+       switch (map->type) {
+       case FUSE_IOMAP_TYPE_MAPPED:
+       case FUSE_IOMAP_TYPE_UNWRITTEN:
+               /* Mappings backed by space must have a device/addr */
+               if (BAD_DATA(ret == NULL))
+                       return ERR_PTR(-EFSCORRUPTED);
+               break;
+       }
+
+       return ret;
+}
+
 static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
                            unsigned opflags, struct iomap *iomap,
                            struct iomap *srcmap)
@@ -405,6 +425,8 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
        };
        struct fuse_iomap_begin_out outarg = { };
        struct fuse_mount *fm = get_fuse_mount(inode);
+       struct fuse_backing *read_dev = NULL;
+       struct fuse_backing *write_dev = NULL;
        FUSE_ARGS(args);
        int err;
 
@@ -431,24 +453,44 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
        if (err)
                return err;
 
+       read_dev = fuse_iomap_find_dev(fm->fc, &outarg.read);
+       if (IS_ERR(read_dev))
+               return PTR_ERR(read_dev);
+
        if (fuse_is_iomap_file_write(opflags) &&
            outarg.write.type != FUSE_IOMAP_TYPE_PURE_OVERWRITE) {
+               /* open the write device */
+               write_dev = fuse_iomap_find_dev(fm->fc, &outarg.write);
+               if (IS_ERR(write_dev)) {
+                       err = PTR_ERR(write_dev);
+                       goto out_read_dev;
+               }
+
                /*
                 * For an out of place write, we must supply the write mapping
                 * via @iomap, and the read mapping via @srcmap.
                 */
-               fuse_iomap_from_server(inode, iomap, &outarg.write);
-               fuse_iomap_from_server(inode, srcmap, &outarg.read);
+               fuse_iomap_from_server(inode, iomap, write_dev, &outarg.write);
+               fuse_iomap_from_server(inode, srcmap, read_dev, &outarg.read);
        } else {
                /*
                 * For everything else (reads, reporting, and pure overwrites),
                 * we can return the sole mapping through @iomap and leave
                 * @srcmap unchanged from its default (HOLE).
                 */
-               fuse_iomap_from_server(inode, iomap, &outarg.read);
+               fuse_iomap_from_server(inode, iomap, read_dev, &outarg.read);
        }
 
-       return 0;
+       /*
+        * XXX: if we ever want to support closing devices, we need a way to
+        * track the fuse_backing refcount all the way through bio endios.
+        * For now we put the refcount here because you can't remove an iomap
+        * device until unmount time.
+        */
+       fuse_backing_put(write_dev);
+out_read_dev:
+       fuse_backing_put(read_dev);
+       return err;
 }
 
 /* Decide if we send FUSE_IOMAP_END to the fuse server */
@@ -523,3 +565,44 @@ const struct iomap_ops fuse_iomap_ops = {
        .iomap_begin            = fuse_iomap_begin,
        .iomap_end              = fuse_iomap_end,
 };
+
+static int fuse_iomap_may_admin(struct fuse_conn *fc, unsigned int flags)
+{
+       if (!fc->iomap)
+               return -EPERM;
+
+       if (flags)
+               return -EINVAL;
+
+       return 0;
+}
+
+static int fuse_iomap_may_open(struct fuse_conn *fc, struct file *file)
+{
+       if (!S_ISBLK(file_inode(file)->i_mode))
+               return -ENODEV;
+
+       return 0;
+}
+
+static int fuse_iomap_post_open(struct fuse_conn *fc, struct fuse_backing *fb)
+{
+       fb->bdev = I_BDEV(fb->file->f_mapping->host);
+       return 0;
+}
+
+static int fuse_iomap_may_close(struct fuse_conn *fc, struct file *file)
+{
+       /* We only support closing iomap block devices at unmount */
+       return -EBUSY;
+}
+
+const struct fuse_backing_ops fuse_iomap_backing_ops = {
+       .type = FUSE_BACKING_TYPE_IOMAP,
+       .id_start = 1,
+       .id_end = 1025,         /* maximum 1024 block devices */
+       .may_admin = fuse_iomap_may_admin,
+       .may_open = fuse_iomap_may_open,
+       .may_close = fuse_iomap_may_close,
+       .post_open = fuse_iomap_post_open,
+};
fs/fuse/trace.c +1 -0
index 93bd72efc98cd0..68d2eecb8559a5 100644
@@ -6,6 +6,7 @@
 #include "dev_uring_i.h"
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
+#include "iomap_i.h"
 
 #include <linux/pagemap.h>
 
#64 lore raw

PATCH 5/31 fuse_trace: adapt FUSE_DEV_IOC_BACKING_{OPEN,CLOSE} to add new iomap devices

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Enhance the existing backing file tracepoints to report the subsystem that's actually using the backing file.

---
 fs/fuse/fuse_trace.h |   42 +++++++++++++++++++++++++++++++++++++++---
 1 file changed, 39 insertions(+), 3 deletions(-)
fs/fuse/fuse_trace.h +39 -3
index c0878253e7c6ad..af21654d797f45 100644
@@ -175,6 +175,10 @@ TRACE_EVENT(fuse_request_end,
 );
 
 #ifdef CONFIG_FUSE_BACKING
+#define FUSE_BACKING_FLAG_STRINGS \
+	{ FUSE_BACKING_TYPE_PASSTHROUGH,	"pass" }, \
+	{ FUSE_BACKING_TYPE_IOMAP,		"iomap" }
+
 TRACE_EVENT(fuse_backing_class,
 	TP_PROTO(const struct fuse_conn *fc, unsigned int idx,
 		 const struct fuse_backing *fb),
@@ -184,7 +188,9 @@ TRACE_EVENT(fuse_backing_class,
 	TP_STRUCT__entry(
 		__field(dev_t,			connection)
 		__field(unsigned int,		idx)
+		__field(unsigned int,		type)
 		__field(unsigned long,		ino)
+		__field(dev_t,			rdev)
 	),
 
 	TP_fast_assign(
@@ -193,12 +199,19 @@ TRACE_EVENT(fuse_backing_class,
 		__entry->connection	=	fc->dev;
 		__entry->idx		=	idx;
 		__entry->ino		=	inode->i_ino;
+		__entry->type		=	fb->ops->type;
+		if (fb->ops->type == FUSE_BACKING_TYPE_IOMAP)
+			__entry->rdev	=	inode->i_rdev;
+		else
+			__entry->rdev	=	0;
 	),
 
-	TP_printk("connection %u idx %u ino 0x%lx",
+	TP_printk("connection %u idx %u type %s ino 0x%lx rdev %u:%u",
 		  __entry->connection,
 		  __entry->idx,
-		  __entry->ino)
+		  __print_symbolic(__entry->type, FUSE_BACKING_FLAG_STRINGS),
+		  __entry->ino,
+		  MAJOR(__entry->rdev), MINOR(__entry->rdev))
 );
 #define DEFINE_FUSE_BACKING_EVENT(name)		\
 DEFINE_EVENT(fuse_backing_class, name,		\
@@ -210,7 +223,6 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 #endif /* CONFIG_FUSE_BACKING */
 
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
-
 /* tracepoint boilerplate so we don't have to keep doing this */
 #define FUSE_IOMAP_OPFLAGS_FIELD \
 		__field(unsigned,		opflags)
@@ -452,6 +464,30 @@ TRACE_EVENT(fuse_iomap_end_error,
 		  __entry->written,
 		  __entry->error)
 );
+
+TRACE_EVENT(fuse_iomap_dev_add,
+	TP_PROTO(const struct fuse_conn *fc,
+		 const struct fuse_backing_map *map),
+
+	TP_ARGS(fc, map),
+
+	TP_STRUCT__entry(
+		__field(dev_t,			connection)
+		__field(int,			fd)
+		__field(unsigned int,		flags)
+	),
+
+	TP_fast_assign(
+		__entry->connection	=	fc->dev;
+		__entry->fd		=	map->fd;
+		__entry->flags		=	map->flags;
+	),
+
+	TP_printk("connection %u fd %d flags 0x%x",
+		  __entry->connection,
+		  __entry->fd,
+		  __entry->flags)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
#65 lore raw

PATCH 6/31 fuse: flush events and send FUSE_SYNCFS and FUSE_DESTROY on unmount

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

At unmount time, there are a few things that we need to ask the fuse server to do.

First, we need to flush queued events to userspace to give the fuse server a chance to process the events. This is how we make sure that the server processes FUSE_RELEASE events before the connection goes down.

Second, to ensure that all those metadata updates are persisted to disk before tell the fuse server to destroy itself, send FUSE_SYNCFS after waiting for the queued events.

Finally, we need to send FUSE_DESTROY to the fuse server so that it closes the filesystem and the device fds before unmount returns. That way, a script that does something like "umount /dev/sda ; e2fsck -fn /dev/sda" will not fail the e2fsck because the fd closure races with e2fsck startup. Obviously, we need to wait for FUSE_SYNCFS.

This is a major behavior change and who knows what might break existing code, so we hide it behind iomap mode.

---
 fs/fuse/fuse_i.h     |    8 ++++++++
 fs/fuse/file_iomap.c |   29 +++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    9 +++++++--
 3 files changed, 44 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +8 -0
index 274de907257d94..839d4f2ada4656 100644
@@ -1430,6 +1430,9 @@ int fuse_init_fs_context_submount(struct fs_context *fsc);
  */
 void fuse_conn_destroy(struct fuse_mount *fm);
 
+/* Send the FUSE_DESTROY command. */
+void fuse_send_destroy(struct fuse_mount *fm);
+
 /* Drop the connection and free the fuse mount */
 void fuse_mount_destroy(struct fuse_mount *fm);
 
@@ -1711,9 +1714,14 @@ static inline bool fuse_has_iomap(const struct inode *inode)
 }
 
 extern const struct fuse_backing_ops fuse_iomap_backing_ops;
+
+void fuse_iomap_mount(struct fuse_mount *fm);
+void fuse_iomap_unmount(struct fuse_mount *fm);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
+# define fuse_iomap_mount(...)			((void)0)
+# define fuse_iomap_unmount(...)		((void)0)
 #endif
 
 #endif /* _FS_FUSE_I_H */
fs/fuse/file_iomap.c +29 -0
index e4fea3bdc0c2ce..1b9e1bf2f799a3 100644
@@ -606,3 +606,32 @@ const struct fuse_backing_ops fuse_iomap_backing_ops = {
 	.may_close = fuse_iomap_may_close,
 	.post_open = fuse_iomap_post_open,
 };
+
+void fuse_iomap_mount(struct fuse_mount *fm)
+{
+	struct fuse_conn *fc = fm->fc;
+
+	/*
+	 * Enable syncfs for iomap fuse servers so that we can send a final
+	 * flush at unmount time.  This also means that we can support
+	 * freeze/thaw properly.
+	 */
+	fc->sync_fs = true;
+}
+
+void fuse_iomap_unmount(struct fuse_mount *fm)
+{
+	struct fuse_conn *fc = fm->fc;
+
+	/*
+	 * Flush all pending commands, then issue a syncfs, flush the syncfs,
+	 * and send a destroy command.  This gives the fuse server a chance to
+	 * process all the pending releases, write the last bits of metadata
+	 * changes to disk, and close the iomap block devices before we return
+	 * from the umount call.
+	 */
+	fuse_flush_requests_and_wait(fc);
+	sync_filesystem(fm->sb);
+	fuse_flush_requests_and_wait(fc);
+	fuse_send_destroy(fm);
+}
fs/fuse/inode.c +7 -2
index eec711302a4a13..271356fa3be3ea 100644
@@ -632,7 +632,7 @@ static void fuse_umount_begin(struct super_block *sb)
 		retire_super(sb);
 }
 
-static void fuse_send_destroy(struct fuse_mount *fm)
+void fuse_send_destroy(struct fuse_mount *fm)
 {
 	if (fm->fc->conn_init) {
 		FUSE_ARGS(args);
@@ -1471,6 +1471,9 @@ static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
 
 		init_server_timeout(fc, timeout);
 
+		if (fc->iomap)
+			fuse_iomap_mount(fm);
+
 		fm->sb->s_bdi->ra_pages =
 				min(fm->sb->s_bdi->ra_pages, ra_pages);
 		fc->minor = arg->minor;
@@ -2106,7 +2109,9 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
 	struct fuse_conn *fc = fm->fc;
 
-	if (fc->destroy) {
+	if (fc->iomap) {
+		fuse_iomap_unmount(fm);
+	} else if (fc->destroy) {
 		/*
 		 * Flush all pending requests (most of which will be
 		 * FUSE_RELEASE) before sending FUSE_DESTROY, because the fuse
#66 lore raw

PATCH 7/31 fuse: create a per-inode flag for toggling iomap

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/fuse_i.h +17 -0
index 839d4f2ada4656..c7aeb324fe599e 100644
@@ -257,6 +257,8 @@ enum {
 	 * or the fuse server has an exclusive "lease" on distributed fs
 	 */
 	FUSE_I_EXCLUSIVE,
+	/* Use iomap for this inode */
+	FUSE_I_IOMAP,
 };
 
 struct fuse_conn;
@@ -1717,11 +1719,26 @@ extern const struct fuse_backing_ops fuse_iomap_backing_ops;
 
 void fuse_iomap_mount(struct fuse_mount *fm);
 void fuse_iomap_unmount(struct fuse_mount *fm);
+
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_evict_inode(struct inode *inode);
+
+static inline bool fuse_inode_has_iomap(const struct inode *inode)
+{
+	const struct fuse_inode *fi = get_fuse_inode(inode);
+
+	return test_bit(FUSE_I_IOMAP, &fi->state);
+}
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
 # define fuse_iomap_mount(...)			((void)0)
 # define fuse_iomap_unmount(...)		((void)0)
+# define fuse_iomap_init_reg_inode(...)		((void)0)
+# define fuse_iomap_init_nonreg_inode(...)	((void)0)
+# define fuse_iomap_evict_inode(...)		((void)0)
+# define fuse_inode_has_iomap(...)		(false)
 #endif
 
 #endif /* _FS_FUSE_I_H */
include/uapi/linux/fuse.h +3 -0
index e571f8ceecbfad..e949bfe022c3b0 100644
@@ -243,6 +243,7 @@
  *
  *  7.99
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
+ *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -583,9 +584,11 @@ struct fuse_file_lock {
  *
  * FUSE_ATTR_SUBMOUNT: Object is a submount root
  * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode
+ * FUSE_ATTR_IOMAP: Use iomap for this inode
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX		(1 << 1)
+#define FUSE_ATTR_IOMAP		(1 << 2)
 
 /**
  * Open flags
fs/fuse/file.c +1 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644
@@ -3135,6 +3135,7 @@ void fuse_init_file_inode(struct inode *inode, unsigned int flags)
 	init_waitqueue_head(&fi->page_waitq);
 	init_waitqueue_head(&fi->direct_io_waitq);
 
+	fuse_iomap_init_reg_inode(inode, flags);
 	if (IS_ENABLED(CONFIG_FUSE_DAX))
 		fuse_dax_inode_init(inode, flags);
 }
fs/fuse/file_iomap.c +49 -0

52 lines not on this page · raw message

fs/fuse/inode.c +20 -6
index 271356fa3be3ea..9b9e7b2dd0d928 100644
@@ -196,6 +196,8 @@ static void fuse_evict_inode(struct inode *inode)
 		WARN_ON(!list_empty(&fi->write_files));
 		WARN_ON(!list_empty(&fi->queued_writes));
 	}
+
+	fuse_iomap_evict_inode(inode);
 }
 
 static int fuse_reconfigure(struct fs_context *fsc)
@@ -428,20 +430,32 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
 	inode->i_size = attr->size;
 	inode_set_mtime(inode, attr->mtime, attr->mtimensec);
 	inode_set_ctime(inode, attr->ctime, attr->ctimensec);
-	if (S_ISREG(inode->i_mode)) {
+	switch (inode->i_mode & S_IFMT) {
+	case S_IFREG:
 		fuse_init_common(inode);
 		fuse_init_file_inode(inode, attr->flags);
-	} else if (S_ISDIR(inode->i_mode))
+		break;
+	case S_IFDIR:
 		fuse_init_dir(inode);
-	else if (S_ISLNK(inode->i_mode))
+		fuse_iomap_init_nonreg_inode(inode, attr->flags);
+		break;
+	case S_IFLNK:
 		fuse_init_symlink(inode);
-	else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
-		 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
+		fuse_iomap_init_nonreg_inode(inode, attr->flags);
+		break;
+	case S_IFCHR:
+	case S_IFBLK:
+	case S_IFIFO:
+	case S_IFSOCK:
 		fuse_init_common(inode);
 		init_special_inode(inode, inode->i_mode,
 				   new_decode_dev(attr->rdev));
-	} else
+		fuse_iomap_init_nonreg_inode(inode, attr->flags);
+		break;
+	default:
 		BUG();
+		break;
+	}
 	/*
 	 * Ensure that we don't cache acls for daemons without FUSE_POSIX_ACL
 	 * so they see the exact same behavior as before.
Reviewed-by on v1 7/31
#67 lore raw

Re: [PATCH 07/31] fuse: create a per-inode flag for toggling iomap

Quoted 9 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

The logic in this makes sense to me, left just a few comments below.

Quoted 78 lines
---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/fuse_i.h +17 -0
index 839d4f2ada4656..c7aeb324fe599e 100644
@@ -257,6 +257,8 @@ enum {
         * or the fuse server has an exclusive "lease" on distributed fs
         */
        FUSE_I_EXCLUSIVE,
+       /* Use iomap for this inode */
+       FUSE_I_IOMAP,
 };
 
 struct fuse_conn;
@@ -1717,11 +1719,26 @@ extern const struct fuse_backing_ops fuse_iomap_backing_ops;
 
 void fuse_iomap_mount(struct fuse_mount *fm);
 void fuse_iomap_unmount(struct fuse_mount *fm);
+
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_evict_inode(struct inode *inode);
+
+static inline bool fuse_inode_has_iomap(const struct inode *inode)
+{
+       const struct fuse_inode *fi = get_fuse_inode(inode);
+
+       return test_bit(FUSE_I_IOMAP, &fi->state);
+}
 #else
 # define fuse_iomap_enabled(...)               (false)
 # define fuse_has_iomap(...)                   (false)
 # define fuse_iomap_mount(...)                 ((void)0)
 # define fuse_iomap_unmount(...)               ((void)0)
+# define fuse_iomap_init_reg_inode(...)                ((void)0)
+# define fuse_iomap_init_nonreg_inode(...)     ((void)0)
+# define fuse_iomap_evict_inode(...)           ((void)0)
+# define fuse_inode_has_iomap(...)             (false)
 #endif
 
 #endif /* _FS_FUSE_I_H */
include/uapi/linux/fuse.h +3 -0
index e571f8ceecbfad..e949bfe022c3b0 100644
@@ -243,6 +243,7 @@
  *
  *  7.99
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
+ *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -583,9 +584,11 @@ struct fuse_file_lock {
  *
  * FUSE_ATTR_SUBMOUNT: Object is a submount root
  * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode
+ * FUSE_ATTR_IOMAP: Use iomap for this inode
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX          (1 << 1)
+#define FUSE_ATTR_IOMAP                (1 << 2)
 
 /**
  * Open flags
fs/fuse/file.c +0 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644

fs/fuse/file.c void fuse_init_file_inode(struct inode *inode, unsigned int flags) · line 3138

Quoted 4 lines
fs/fuse/file.c +1 -0
@@ -3135,6 +3135,7 @@ void fuse_init_file_inode(struct inode *inode, unsigned int flags)
        init_waitqueue_head(&fi->page_waitq);
        init_waitqueue_head(&fi->direct_io_waitq);
 
+       fuse_iomap_init_reg_inode(inode, flags);

imo it's a bit confusing to have this here when the rest of the fuse_iomap_init_nonreg_inode() calls happen inside the switch case statement. Maybe it makes sense to have this inside the switch case like the fuse_iomap_init_nonreg_inode() calls, or alternatively move the fuse_iomap_init_nonreg_inode() calls into their corresponding helpers (eg fuse_init_dir(), etc.), so that it's consistent?

Quoted 46 lines
fs/fuse/file.c +0 -0
        if (IS_ENABLED(CONFIG_FUSE_DAX))
                fuse_dax_inode_init(inode, flags);
 }
fs/fuse/file_iomap.c +35 -0
index 1b9e1bf2f799a3..fc0d5f135bacf9 100644
@@ -635,3 +635,52 @@ void fuse_iomap_unmount(struct fuse_mount *fm)
        fuse_flush_requests_and_wait(fc);
        fuse_send_destroy(fm);
 }
+
+static inline void fuse_inode_set_iomap(struct inode *inode)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       set_bit(FUSE_I_IOMAP, &fi->state);
+}
+
+static inline void fuse_inode_clear_iomap(struct inode *inode)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       clear_bit(FUSE_I_IOMAP, &fi->state);
+}
+
+void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(!S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP))
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
+
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP)) {
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);

fs/fuse/file_iomap.c void fuse_iomap_unmount(struct fuse_mount *fm) · line 682

Quoted 10 lines
fs/fuse/file_iomap.c +10 -0
+               fuse_inode_set_iomap(inode);
+       }
+}
+
+void fuse_iomap_evict_inode(struct inode *inode)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       if (fuse_inode_has_iomap(inode))

If I'm understanding this correctly, a fuse inode can't have FUSE_I_IOMAP set on it if conn>iomap is not enabled, correct? Maybe it makes sense to just return if (!conn->iomap) at the very beginning, to make that more clear?

Quoted 41 lines
fs/fuse/file_iomap.c +4 -0
+               fuse_inode_clear_iomap(inode);
+       if (conn->iomap && fuse_inode_is_exclusive(inode))
+               clear_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
fs/fuse/inode.c +13 -5
index 271356fa3be3ea..9b9e7b2dd0d928 100644
@@ -196,6 +196,8 @@ static void fuse_evict_inode(struct inode *inode)
                WARN_ON(!list_empty(&fi->write_files));
                WARN_ON(!list_empty(&fi->queued_writes));
        }
+
+       fuse_iomap_evict_inode(inode);
 }
 
 static int fuse_reconfigure(struct fs_context *fsc)
@@ -428,20 +430,32 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
        inode->i_size = attr->size;
        inode_set_mtime(inode, attr->mtime, attr->mtimensec);
        inode_set_ctime(inode, attr->ctime, attr->ctimensec);
-       if (S_ISREG(inode->i_mode)) {
+       switch (inode->i_mode & S_IFMT) {
+       case S_IFREG:
                fuse_init_common(inode);
                fuse_init_file_inode(inode, attr->flags);
-       } else if (S_ISDIR(inode->i_mode))
+               break;
+       case S_IFDIR:
                fuse_init_dir(inode);
-       else if (S_ISLNK(inode->i_mode))
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       case S_IFLNK:
                fuse_init_symlink(inode);
-       else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
-                S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       case S_IFCHR:
+       case S_IFBLK:

fs/fuse/inode.c static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr, · line 456

Quoted 10 lines
fs/fuse/inode.c +5 -1
+       case S_IFIFO:
+       case S_IFSOCK:
                fuse_init_common(inode);
                init_special_inode(inode, inode->i_mode,
                                   new_decode_dev(attr->rdev));
-       } else
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       default:
                BUG();

Just thinking out loud here and curious to hear whether you like this idea or not: another option is calling

if (conn->iomap)

    fuse_iomap_init_inode();

at the end, where fuse_iomap_init_inode() would be something like:

void fuse_iomap_init_inode(struct inode *inode, unsigned attr_flags)

{
    struct fuse_inode *fi = get_fuse_inode(inode);

    if (attr_flags & FUSE_ATTR_IOMAP)
          set_bit(FUSE_I_EXCLUSIVE, &fi->state);

    if (S_ISREG(inode->i_mode))
            fuse_inode_set_iomap(inode);
}

which seems simpler to me than having both fuse_iomap_init_nonreg_inode() and fuse_iomap_init_reg_inode() function and invoking it per i_mode case.

Thanks,
Joanne

Quoted 6 lines
fs/fuse/inode.c +2 -0
+               break;
+       }
        /*
         * Ensure that we don't cache acls for daemons without FUSE_POSIX_ACL
         * so they see the exact same behavior as before.
#68 lore raw

Re: [PATCH 07/31] fuse: create a per-inode flag for toggling iomap

Quoted 9 lines · Joanne Koong
Quoted 8 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

Quoted 5 lines
Quoted 1 line

The logic in this makes sense to me, left just a few comments below.

Thanks!

Quoted 81 lines
Quoted 81 lines
---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/fuse_i.h +17 -0
index 839d4f2ada4656..c7aeb324fe599e 100644
@@ -257,6 +257,8 @@ enum {
         * or the fuse server has an exclusive "lease" on distributed fs
         */
        FUSE_I_EXCLUSIVE,
+       /* Use iomap for this inode */
+       FUSE_I_IOMAP,
 };
 
 struct fuse_conn;
@@ -1717,11 +1719,26 @@ extern const struct fuse_backing_ops fuse_iomap_backing_ops;
 
 void fuse_iomap_mount(struct fuse_mount *fm);
 void fuse_iomap_unmount(struct fuse_mount *fm);
+
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags);
+void fuse_iomap_evict_inode(struct inode *inode);
+
+static inline bool fuse_inode_has_iomap(const struct inode *inode)
+{
+       const struct fuse_inode *fi = get_fuse_inode(inode);
+
+       return test_bit(FUSE_I_IOMAP, &fi->state);
+}
 #else
 # define fuse_iomap_enabled(...)               (false)
 # define fuse_has_iomap(...)                   (false)
 # define fuse_iomap_mount(...)                 ((void)0)
 # define fuse_iomap_unmount(...)               ((void)0)
+# define fuse_iomap_init_reg_inode(...)                ((void)0)
+# define fuse_iomap_init_nonreg_inode(...)     ((void)0)
+# define fuse_iomap_evict_inode(...)           ((void)0)
+# define fuse_inode_has_iomap(...)             (false)
 #endif
 
 #endif /* _FS_FUSE_I_H */
include/uapi/linux/fuse.h +3 -0
index e571f8ceecbfad..e949bfe022c3b0 100644
@@ -243,6 +243,7 @@
  *
  *  7.99
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
+ *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -583,9 +584,11 @@ struct fuse_file_lock {
  *
  * FUSE_ATTR_SUBMOUNT: Object is a submount root
  * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode
+ * FUSE_ATTR_IOMAP: Use iomap for this inode
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX          (1 << 1)
+#define FUSE_ATTR_IOMAP                (1 << 2)
 
 /**
  * Open flags
fs/fuse/file.c +0 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644
@@ -3135,6 +3135,7 @@ void fuse_init_file_inode(struct inode *inode, unsigned int flags)
        init_waitqueue_head(&fi->page_waitq);
        init_waitqueue_head(&fi->direct_io_waitq);
 
Quoted 8 lines

fs/fuse/file.c void fuse_init_file_inode(struct inode *inode, unsigned int flags) · line 3138

Quoted 1 line
fs/fuse/file.c +1 -0
+       fuse_iomap_init_reg_inode(inode, flags);

imo it's a bit confusing to have this here when the rest of the fuse_iomap_init_nonreg_inode() calls happen inside the switch case statement. Maybe it makes sense to have this inside the switch case like the fuse_iomap_init_nonreg_inode() calls, or alternatively move the fuse_iomap_init_nonreg_inode() calls into their corresponding helpers (eg fuse_init_dir(), etc.), so that it's consistent?

Ah, that. Originally I /did/ have it in the switch statement in fuse_init_inode. Then I started trying to work on fsdax support (HA!) for which it became necessary to move the fuse_iomap_init_reg_inode call to fuse_init_file_inode and pass it a pointer to args->flags so that it could clear FUSE_ATTR_DAX so that the other fuse dax io paths wouldn't try to install themselves.

I never got fsdax working properly so that's why it's never been attached to my fuse-iomap patches. Maybe that'll happen some day in the meantime ... should fuse_iomap_init_reg_inode move back to the switch?

Quoted 51 lines
Quoted 51 lines
fs/fuse/file.c +0 -0
        if (IS_ENABLED(CONFIG_FUSE_DAX))
                fuse_dax_inode_init(inode, flags);
 }
fs/fuse/file_iomap.c +40 -0
index 1b9e1bf2f799a3..fc0d5f135bacf9 100644
@@ -635,3 +635,52 @@ void fuse_iomap_unmount(struct fuse_mount *fm)
        fuse_flush_requests_and_wait(fc);
        fuse_send_destroy(fm);
 }
+
+static inline void fuse_inode_set_iomap(struct inode *inode)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       set_bit(FUSE_I_IOMAP, &fi->state);
+}
+
+static inline void fuse_inode_clear_iomap(struct inode *inode)
+{
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       clear_bit(FUSE_I_IOMAP, &fi->state);
+}
+
+void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(!S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP))
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
+
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP)) {
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+               fuse_inode_set_iomap(inode);
+       }
+}
+
+void fuse_iomap_evict_inode(struct inode *inode)
Quoted 8 lines

fs/fuse/file_iomap.c void fuse_iomap_unmount(struct fuse_mount *fm) · line 682

Quoted 5 lines
fs/fuse/file_iomap.c +5 -0
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       if (fuse_inode_has_iomap(inode))

If I'm understanding this correctly, a fuse inode can't have FUSE_I_IOMAP set on it if conn>iomap is not enabled, correct?

Correct.

Quoted 2 lines

Maybe it makes sense to just return if (!conn->iomap) at the very beginning, to make that more clear?

<shrug> fuse_inode_has_iomap only checks FUSE_I_IOMAP...

Quoted 3 lines

fs/fuse/file_iomap.c void fuse_iomap_unmount(struct fuse_mount *fm) · line 685

Quoted 3 lines
fs/fuse/file_iomap.c +3 -0
+               fuse_inode_clear_iomap(inode);
+       if (conn->iomap && fuse_inode_is_exclusive(inode))
+               clear_bit(FUSE_I_EXCLUSIVE, &fi->state);

...but I wasn't going to assume that iomap is the only way that FUSE_I_EXCLUSIVE could get set.

On the other hand, for non-regular files we set FUSE_I_EXCLUSIVE only if conn->iomap is nonzero *and* attr->flags contains FUSE_ATTR_IOMAP. So this clearing code isn't quite the same as the setting code.

I wonder if that means we should set FUSE_I_IOMAP for non-regular files? They don't use iomap itself, but I suppose it would be neat if "iomap directories" also meant that timestamps and whatnot worked in the same as they do for regular files.

Quoted 68 lines
Quoted 38 lines
fs/fuse/file_iomap.c +1 -0
+}
fs/fuse/inode.c +13 -5
index 271356fa3be3ea..9b9e7b2dd0d928 100644
@@ -196,6 +196,8 @@ static void fuse_evict_inode(struct inode *inode)
                WARN_ON(!list_empty(&fi->write_files));
                WARN_ON(!list_empty(&fi->queued_writes));
        }
+
+       fuse_iomap_evict_inode(inode);
 }
 
 static int fuse_reconfigure(struct fs_context *fsc)
@@ -428,20 +430,32 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
        inode->i_size = attr->size;
        inode_set_mtime(inode, attr->mtime, attr->mtimensec);
        inode_set_ctime(inode, attr->ctime, attr->ctimensec);
-       if (S_ISREG(inode->i_mode)) {
+       switch (inode->i_mode & S_IFMT) {
+       case S_IFREG:
                fuse_init_common(inode);
                fuse_init_file_inode(inode, attr->flags);
-       } else if (S_ISDIR(inode->i_mode))
+               break;
+       case S_IFDIR:
                fuse_init_dir(inode);
-       else if (S_ISLNK(inode->i_mode))
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       case S_IFLNK:
                fuse_init_symlink(inode);
-       else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
-                S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       case S_IFCHR:
+       case S_IFBLK:

fs/fuse/inode.c static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr, · line 456

Quoted 10 lines
fs/fuse/inode.c +5 -1
+       case S_IFIFO:
+       case S_IFSOCK:
                fuse_init_common(inode);
                init_special_inode(inode, inode->i_mode,
                                   new_decode_dev(attr->rdev));
-       } else
+               fuse_iomap_init_nonreg_inode(inode, attr->flags);
+               break;
+       default:
                BUG();

Just thinking out loud here and curious to hear whether you like this idea or not: another option is calling

if (conn->iomap)

    fuse_iomap_init_inode();

at the end, where fuse_iomap_init_inode() would be something like:

void fuse_iomap_init_inode(struct inode *inode, unsigned attr_flags)

{
    struct fuse_inode *fi = get_fuse_inode(inode);

    if (attr_flags & FUSE_ATTR_IOMAP)
          set_bit(FUSE_I_EXCLUSIVE, &fi->state);

    if (S_ISREG(inode->i_mode))
            fuse_inode_set_iomap(inode);
}
Quoted 3 lines

which seems simpler to me than having both fuse_iomap_init_nonreg_inode() and fuse_iomap_init_reg_inode() function and invoking it per i_mode case.

Yeah that would be simpler, but for that weird fsdax enabling quirk I mentioned earlier.

Hrmm, I could also modify fuse_dax_inode_init to return without doing anything if FUSE_ATTR_IOMAP is set.

--D

Quoted 10 lines

Thanks,
Joanne

Quoted 6 lines
fs/fuse/inode.c +2 -0
+               break;
+       }
        /*
         * Ensure that we don't cache acls for daemons without FUSE_POSIX_ACL
         * so they see the exact same behavior as before.
#69 lore raw

Re: [PATCH 07/31] fuse: create a per-inode flag for toggling iomap

Quoted 68 lines · Darrick J. Wong
Quoted 9 lines · Joanne Koong
Quoted 8 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

Quoted 5 lines
Quoted 1 line

The logic in this makes sense to me, left just a few comments below.

Thanks!

Quoted 26 lines
Quoted 26 lines
---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/file.c +14 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP)) {
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+               fuse_inode_set_iomap(inode);
+       }
+}
+
+void fuse_iomap_evict_inode(struct inode *inode)
Quoted 8 lines

fs/fuse/file.c

Quoted 5 lines
fs/fuse/file.c +5 -0
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       if (fuse_inode_has_iomap(inode))

If I'm understanding this correctly, a fuse inode can't have FUSE_I_IOMAP set on it if conn>iomap is not enabled, correct?

Correct.

Quoted 2 lines

Maybe it makes sense to just return if (!conn->iomap) at the very beginning, to make that more clear?

<shrug> fuse_inode_has_iomap only checks FUSE_I_IOMAP...

Quoted 3 lines

fs/fuse/file.c

Quoted 3 lines
fs/fuse/file.c +3 -0
+               fuse_inode_clear_iomap(inode);
+       if (conn->iomap && fuse_inode_is_exclusive(inode))
+               clear_bit(FUSE_I_EXCLUSIVE, &fi->state);

...but I wasn't going to assume that iomap is the only way that FUSE_I_EXCLUSIVE could get set.

Quoted 9 lines

On the other hand, for non-regular files we set FUSE_I_EXCLUSIVE only if conn->iomap is nonzero *and* attr->flags contains FUSE_ATTR_IOMAP. So this clearing code isn't quite the same as the setting code.

I wonder if that means we should set FUSE_I_IOMAP for non-regular files? They don't use iomap itself, but I suppose it would be neat if "iomap directories" also meant that timestamps and whatnot worked in the same as they do for regular files.

That seems like a good idea to me. I think that also makes the mental model (at least for me) simpler.

Thanks,
Joanne

#70 lore raw

Re: [PATCH 07/31] fuse: create a per-inode flag for toggling iomap

Quoted 73 lines · Joanne Koong
Quoted 72 lines · Darrick J. Wong
Quoted 9 lines · Joanne Koong
Quoted 8 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

Quoted 5 lines
Quoted 1 line

The logic in this makes sense to me, left just a few comments below.

Thanks!

Quoted 26 lines
Quoted 26 lines
---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/file.c +14 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP)) {
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+               fuse_inode_set_iomap(inode);
+       }
+}
+
+void fuse_iomap_evict_inode(struct inode *inode)
Quoted 8 lines

fs/fuse/file.c

Quoted 5 lines
fs/fuse/file.c +5 -0
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       if (fuse_inode_has_iomap(inode))

If I'm understanding this correctly, a fuse inode can't have FUSE_I_IOMAP set on it if conn>iomap is not enabled, correct?

Correct.

Quoted 2 lines

Maybe it makes sense to just return if (!conn->iomap) at the very beginning, to make that more clear?

<shrug> fuse_inode_has_iomap only checks FUSE_I_IOMAP...

Quoted 3 lines

fs/fuse/file.c

Quoted 3 lines
fs/fuse/file.c +3 -0
+               fuse_inode_clear_iomap(inode);
+       if (conn->iomap && fuse_inode_is_exclusive(inode))
+               clear_bit(FUSE_I_EXCLUSIVE, &fi->state);

...but I wasn't going to assume that iomap is the only way that FUSE_I_EXCLUSIVE could get set.

On the other hand, for non-regular files we set FUSE_I_EXCLUSIVE only if conn->iomap is nonzero *and* attr->flags contains FUSE_ATTR_IOMAP. So this clearing code isn't quite the same as the setting code.

Quoted 8 lines
Quoted 5 lines

I wonder if that means we should set FUSE_I_IOMAP for non-regular files? They don't use iomap itself, but I suppose it would be neat if "iomap directories" also meant that timestamps and whatnot worked in the same as they do for regular files.

That seems like a good idea to me. I think that also makes the mental model (at least for me) simpler.

I tried that, and generic/476 immediately broke. I'll get back to that next week, but turning it on unconditionally is not trivial unfortunately. :/

--D

Quoted 2 lines

Thanks,
Joanne

#71 lore raw

Re: [PATCH 07/31] fuse: create a per-inode flag for toggling iomap

Quoted 80 lines · Darrick J. Wong
Quoted 79 lines · Joanne Koong
Quoted 77 lines · Darrick J. Wong
Quoted 9 lines · Joanne Koong
Quoted 8 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Create a per-inode flag to control whether or not this inode actually uses iomap. This is required for non-regular files because iomap doesn't apply there; and enables fuse filesystems to provide some non-iomap files if desired.

Quoted 5 lines
Quoted 1 line

The logic in this makes sense to me, left just a few comments below.

Thanks!

Quoted 26 lines
Quoted 26 lines
---
 fs/fuse/fuse_i.h          |   17 ++++++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/file.c            |    1 +
 fs/fuse/file_iomap.c      |   49 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   26 ++++++++++++++++++------
 5 files changed, 90 insertions(+), 6 deletions(-)
fs/fuse/file.c +14 -0
index f1ef77a0be05bb..42c85c19f3b13b 100644
+void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       ASSERT(S_ISREG(inode->i_mode));
+
+       if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP)) {
+               set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+               fuse_inode_set_iomap(inode);
+       }
+}
+
+void fuse_iomap_evict_inode(struct inode *inode)
Quoted 8 lines

fs/fuse/file.c

Quoted 5 lines
fs/fuse/file.c +5 -0
+{
+       struct fuse_conn *conn = get_fuse_conn(inode);
+       struct fuse_inode *fi = get_fuse_inode(inode);
+
+       if (fuse_inode_has_iomap(inode))

If I'm understanding this correctly, a fuse inode can't have FUSE_I_IOMAP set on it if conn>iomap is not enabled, correct?

Correct.

Quoted 2 lines

Maybe it makes sense to just return if (!conn->iomap) at the very beginning, to make that more clear?

<shrug> fuse_inode_has_iomap only checks FUSE_I_IOMAP...

Quoted 3 lines

fs/fuse/file.c

Quoted 3 lines
fs/fuse/file.c +3 -0
+               fuse_inode_clear_iomap(inode);
+       if (conn->iomap && fuse_inode_is_exclusive(inode))
+               clear_bit(FUSE_I_EXCLUSIVE, &fi->state);

...but I wasn't going to assume that iomap is the only way that FUSE_I_EXCLUSIVE could get set.

On the other hand, for non-regular files we set FUSE_I_EXCLUSIVE only if conn->iomap is nonzero *and* attr->flags contains FUSE_ATTR_IOMAP. So this clearing code isn't quite the same as the setting code.

I wonder if that means we should set FUSE_I_IOMAP for non-regular files? They don't use iomap itself, but I suppose it would be neat if "iomap directories" also meant that timestamps and whatnot worked in the same as they do for regular files.

Quoted 6 lines
Quoted 2 lines

That seems like a good idea to me. I think that also makes the mental model (at least for me) simpler.

I tried that, and generic/476 immediately broke. I'll get back to that next week, but turning it on unconditionally is not trivial unfortunately. :/

I've tentatively fixed this by defining a FUSE_ATTR_EXCLUSIVE flag in the uapi so that the fuse server can tell the kernel which files are "exclusive" files, and hence which ones should have FUSE_I_EXCLUSIVE set.

(These are ofc files where the kernel can transmogrify ACLs into i_mode changes and do ACL inheritance because there is no other principal that could be writing to the ondisk metadata.)

--D

Quoted 5 lines

--D

Quoted 2 lines

Thanks,
Joanne

#72 lore raw

PATCH 8/31 fuse_trace: create a per-inode flag for toggling iomap

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   44 ++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/file_iomap.c |    6 ++++++
 2 files changed, 50 insertions(+)
fs/fuse/fuse_trace.h +44 -0
index af21654d797f45..fac981e2a30df0 100644
@@ -300,6 +300,25 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 	{ FUSE_IOMAP_TYPE_UNWRITTEN,		"unwritten" }, \
 	{ FUSE_IOMAP_TYPE_INLINE,		"inline" }
 
+TRACE_DEFINE_ENUM(FUSE_I_ADVISE_RDPLUS);
+TRACE_DEFINE_ENUM(FUSE_I_INIT_RDPLUS);
+TRACE_DEFINE_ENUM(FUSE_I_SIZE_UNSTABLE);
+TRACE_DEFINE_ENUM(FUSE_I_BAD);
+TRACE_DEFINE_ENUM(FUSE_I_BTIME);
+TRACE_DEFINE_ENUM(FUSE_I_CACHE_IO_MODE);
+TRACE_DEFINE_ENUM(FUSE_I_EXCLUSIVE);
+TRACE_DEFINE_ENUM(FUSE_I_IOMAP);
+
+#define FUSE_IFLAG_STRINGS \
+	{ 1 << FUSE_I_ADVISE_RDPLUS,		"advise_rdplus" }, \
+	{ 1 << FUSE_I_INIT_RDPLUS,		"init_rdplus" }, \
+	{ 1 << FUSE_I_SIZE_UNSTABLE,		"size_unstable" }, \
+	{ 1 << FUSE_I_BAD,			"bad" }, \
+	{ 1 << FUSE_I_BTIME,			"btime" }, \
+	{ 1 << FUSE_I_CACHE_IO_MODE,		"cacheio" }, \
+	{ 1 << FUSE_I_EXCLUSIVE,		"excl" }, \
+	{ 1 << FUSE_I_IOMAP,			"iomap" }
+
 DECLARE_EVENT_CLASS(fuse_iomap_check_class,
 	TP_PROTO(const char *func, int line, const char *condition),
 
@@ -488,6 +507,31 @@ TRACE_EVENT(fuse_iomap_dev_add,
 		  __entry->fd,
 		  __entry->flags)
 );
+
+DECLARE_EVENT_CLASS(fuse_inode_state_class,
+	TP_PROTO(const struct inode *inode),
+	TP_ARGS(inode),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(unsigned long,		state)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->state		=	fi->state;
+	),
+
+	TP_printk(FUSE_INODE_FMT " state (%s)",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __print_flags(__entry->state, "|", FUSE_IFLAG_STRINGS))
+);
+#define DEFINE_FUSE_INODE_STATE_EVENT(name)	\
+DEFINE_EVENT(fuse_inode_state_class, name,	\
+	TP_PROTO(const struct inode *inode),	\
+	TP_ARGS(inode))
+DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_init_inode);
+DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_evict_inode);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/file_iomap.c +6 -0
index fc0d5f135bacf9..66a7b8faa31ac2 100644
@@ -659,6 +659,8 @@ void fuse_iomap_init_nonreg_inode(struct inode *inode, unsigned attr_flags)
 
 	if (conn->iomap && (attr_flags & FUSE_ATTR_IOMAP))
 		set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+
+	trace_fuse_iomap_init_inode(inode);
 }
 
 void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
@@ -672,6 +674,8 @@ void fuse_iomap_init_reg_inode(struct inode *inode, unsigned attr_flags)
 		set_bit(FUSE_I_EXCLUSIVE, &fi->state);
 		fuse_inode_set_iomap(inode);
 	}
+
+	trace_fuse_iomap_init_inode(inode);
 }
 
 void fuse_iomap_evict_inode(struct inode *inode)
@@ -679,6 +683,8 @@ void fuse_iomap_evict_inode(struct inode *inode)
 	struct fuse_conn *conn = get_fuse_conn(inode);
 	struct fuse_inode *fi = get_fuse_inode(inode);
 
+	trace_fuse_iomap_evict_inode(inode);
+
 	if (fuse_inode_has_iomap(inode))
 		fuse_inode_clear_iomap(inode);
 	if (conn->iomap && fuse_inode_is_exclusive(inode))
#73 lore raw

PATCH 9/31 fuse: isolate the other regular file IO paths from iomap

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

iomap completely takes over all regular file IO, so we don't need to access any of the other mechanisms at all. Gate them off so that we can eventually overlay them with a union to save space in struct fuse_inode.

---
 fs/fuse/dir.c    |   14 +++++++++-----
 fs/fuse/file.c   |   18 +++++++++++++-----
 fs/fuse/inode.c  |    3 ++-
 fs/fuse/iomode.c |    2 +-
 4 files changed, 25 insertions(+), 12 deletions(-)
fs/fuse/dir.c +9 -5
index 3c222b99d6e699..18eb1bb192bb58 100644
@@ -1991,6 +1991,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	FUSE_ARGS(args);
 	struct fuse_setattr_in inarg;
 	struct fuse_attr_out outarg;
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	bool is_truncate = false;
 	bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode);
 	loff_t oldsize;
@@ -2048,12 +2049,15 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		if (err)
 			return err;
 
-		fuse_set_nowrite(inode);
-		fuse_release_nowrite(inode);
+		if (!is_iomap) {
+			fuse_set_nowrite(inode);
+			fuse_release_nowrite(inode);
+		}
 	}
 
 	if (is_truncate) {
-		fuse_set_nowrite(inode);
+		if (!is_iomap)
+			fuse_set_nowrite(inode);
 		set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
 		if (trust_local_cmtime && attr->ia_size != inode->i_size)
 			attr->ia_valid |= ATTR_MTIME | ATTR_CTIME;
@@ -2125,7 +2129,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	if (!is_wb || is_truncate)
 		i_size_write(inode, outarg.attr.size);
 
-	if (is_truncate) {
+	if (is_truncate && !is_iomap) {
 		/* NOTE: this may release/reacquire fi->lock */
 		__fuse_release_nowrite(inode);
 	}
@@ -2149,7 +2153,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	return 0;
 
 error:
-	if (is_truncate)
+	if (is_truncate && !is_iomap)
 		fuse_release_nowrite(inode);
 
 	clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
fs/fuse/file.c +13 -5
index 42c85c19f3b13b..bd9c208a46c78d 100644
@@ -238,6 +238,7 @@ static int fuse_open(struct inode *inode, struct file *file)
 	struct fuse_conn *fc = fm->fc;
 	struct fuse_file *ff;
 	int err;
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	bool is_truncate = (file->f_flags & O_TRUNC) && fc->atomic_o_trunc;
 	bool is_wb_truncate = is_truncate && fc->writeback_cache;
 	bool dax_truncate = is_truncate && FUSE_IS_DAX(inode);
@@ -259,7 +260,7 @@ static int fuse_open(struct inode *inode, struct file *file)
 			goto out_inode_unlock;
 	}
 
-	if (is_wb_truncate || dax_truncate)
+	if ((is_wb_truncate || dax_truncate) && !is_iomap)
 		fuse_set_nowrite(inode);
 
 	err = fuse_do_open(fm, get_node_id(inode), file, false);
@@ -272,7 +273,7 @@ static int fuse_open(struct inode *inode, struct file *file)
 			fuse_truncate_update_attr(inode, file);
 	}
 
-	if (is_wb_truncate || dax_truncate)
+	if ((is_wb_truncate || dax_truncate) && !is_iomap)
 		fuse_release_nowrite(inode);
 	if (!err) {
 		if (is_truncate)
@@ -520,12 +521,14 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 {
 	struct inode *inode = file->f_mapping->host;
 	struct fuse_conn *fc = get_fuse_conn(inode);
+	const bool need_sync_writes = !fuse_inode_has_iomap(inode);
 	int err;
 
 	if (fuse_is_bad(inode))
 		return -EIO;
 
-	inode_lock(inode);
+	if (need_sync_writes)
+		inode_lock(inode);
 
 	/*
 	 * Start writeback against all dirty pages of the inode, then
@@ -536,7 +539,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 	if (err)
 		goto out;
 
-	fuse_sync_writes(inode);
+	if (need_sync_writes)
+		fuse_sync_writes(inode);
 
 	/*
 	 * Due to implementation of fuse writeback
@@ -560,7 +564,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 		err = 0;
 	}
 out:
-	inode_unlock(inode);
+	if (need_sync_writes)
+		inode_unlock(inode);
 
 	return err;
 }
@@ -1942,6 +1947,9 @@ static struct fuse_file *__fuse_write_file_get(struct fuse_inode *fi)
 {
 	struct fuse_file *ff;
 
+	if (fuse_inode_has_iomap(&fi->inode))
+		return NULL;
+
 	spin_lock(&fi->lock);
 	ff = list_first_entry_or_null(&fi->write_files, struct fuse_file,
 				      write_entry);
fs/fuse/inode.c +2 -1
index 9b9e7b2dd0d928..7602595006a19d 100644
@@ -191,7 +191,8 @@ static void fuse_evict_inode(struct inode *inode)
 		if (inode->i_nlink > 0)
 			atomic64_inc(&fc->evict_ctr);
 	}
-	if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode)) {
+	if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode) &&
+	    !fuse_inode_has_iomap(inode)) {
 		WARN_ON(fi->iocachectr != 0);
 		WARN_ON(!list_empty(&fi->write_files));
 		WARN_ON(!list_empty(&fi->queued_writes));
fs/fuse/iomode.c +1 -1
index 3728933188f307..0a534e5a6db5f6 100644
@@ -203,7 +203,7 @@ int fuse_file_io_open(struct file *file, struct inode *inode)
 	 * io modes are not relevant with DAX and with server that does not
 	 * implement open.
 	 */
-	if (FUSE_IS_DAX(inode) || !ff->args)
+	if (fuse_inode_has_iomap(inode) || FUSE_IS_DAX(inode) || !ff->args)
 		return 0;
 
 	/*
maintainer
#74 lore raw

Re: [PATCH 09/31] fuse: isolate the other regular file IO paths from iomap

Quoted 9 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

iomap completely takes over all regular file IO, so we don't need to access any of the other mechanisms at all. Gate them off so that we can eventually overlay them with a union to save space in struct fuse_inode.

---

I apologize for providing criticism which is not very productive.

Looking at this I don't feel much confidence to say that all cases are covered and worse, I don't have much confidence that future coder won't easily write some code that accesses the wrong side of the union.

I don't really have great ideas on how to improve.
Maybe at least some of the gates can be inside the _nowrite accessors?

Please don't take this as any sort of objection to this patch.

Thanks,
Amir.

Quoted 161 lines
 fs/fuse/dir.c    |   14 +++++++++-----
 fs/fuse/file.c   |   18 +++++++++++++-----
 fs/fuse/inode.c  |    3 ++-
 fs/fuse/iomode.c |    2 +-
 4 files changed, 25 insertions(+), 12 deletions(-)
fs/fuse/dir.c +9 -5
index 3c222b99d6e699..18eb1bb192bb58 100644
@@ -1991,6 +1991,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        FUSE_ARGS(args);
        struct fuse_setattr_in inarg;
        struct fuse_attr_out outarg;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = false;
        bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode);
        loff_t oldsize;
@@ -2048,12 +2049,15 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
                if (err)
                        return err;
 
-               fuse_set_nowrite(inode);
-               fuse_release_nowrite(inode);
+               if (!is_iomap) {
+                       fuse_set_nowrite(inode);
+                       fuse_release_nowrite(inode);
+               }
        }
 
        if (is_truncate) {
-               fuse_set_nowrite(inode);
+               if (!is_iomap)
+                       fuse_set_nowrite(inode);
                set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
                if (trust_local_cmtime && attr->ia_size != inode->i_size)
                        attr->ia_valid |= ATTR_MTIME | ATTR_CTIME;
@@ -2125,7 +2129,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        if (!is_wb || is_truncate)
                i_size_write(inode, outarg.attr.size);
 
-       if (is_truncate) {
+       if (is_truncate && !is_iomap) {
                /* NOTE: this may release/reacquire fi->lock */
                __fuse_release_nowrite(inode);
        }
@@ -2149,7 +2153,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        return 0;
 
 error:
-       if (is_truncate)
+       if (is_truncate && !is_iomap)
                fuse_release_nowrite(inode);
 
        clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
fs/fuse/file.c +13 -5
index 42c85c19f3b13b..bd9c208a46c78d 100644
@@ -238,6 +238,7 @@ static int fuse_open(struct inode *inode, struct file *file)
        struct fuse_conn *fc = fm->fc;
        struct fuse_file *ff;
        int err;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = (file->f_flags & O_TRUNC) && fc->atomic_o_trunc;
        bool is_wb_truncate = is_truncate && fc->writeback_cache;
        bool dax_truncate = is_truncate && FUSE_IS_DAX(inode);
@@ -259,7 +260,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        goto out_inode_unlock;
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_set_nowrite(inode);
 
        err = fuse_do_open(fm, get_node_id(inode), file, false);
@@ -272,7 +273,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        fuse_truncate_update_attr(inode, file);
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_release_nowrite(inode);
        if (!err) {
                if (is_truncate)
@@ -520,12 +521,14 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 {
        struct inode *inode = file->f_mapping->host;
        struct fuse_conn *fc = get_fuse_conn(inode);
+       const bool need_sync_writes = !fuse_inode_has_iomap(inode);
        int err;
 
        if (fuse_is_bad(inode))
                return -EIO;
 
-       inode_lock(inode);
+       if (need_sync_writes)
+               inode_lock(inode);
 
        /*
         * Start writeback against all dirty pages of the inode, then
@@ -536,7 +539,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
        if (err)
                goto out;
 
-       fuse_sync_writes(inode);
+       if (need_sync_writes)
+               fuse_sync_writes(inode);
 
        /*
         * Due to implementation of fuse writeback
@@ -560,7 +564,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
                err = 0;
        }
 out:
-       inode_unlock(inode);
+       if (need_sync_writes)
+               inode_unlock(inode);
 
        return err;
 }
@@ -1942,6 +1947,9 @@ static struct fuse_file *__fuse_write_file_get(struct fuse_inode *fi)
 {
        struct fuse_file *ff;
 
+       if (fuse_inode_has_iomap(&fi->inode))
+               return NULL;
+
        spin_lock(&fi->lock);
        ff = list_first_entry_or_null(&fi->write_files, struct fuse_file,
                                      write_entry);
fs/fuse/inode.c +2 -1
index 9b9e7b2dd0d928..7602595006a19d 100644
@@ -191,7 +191,8 @@ static void fuse_evict_inode(struct inode *inode)
                if (inode->i_nlink > 0)
                        atomic64_inc(&fc->evict_ctr);
        }
-       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode)) {
+       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode) &&
+           !fuse_inode_has_iomap(inode)) {
                WARN_ON(fi->iocachectr != 0);
                WARN_ON(!list_empty(&fi->write_files));
                WARN_ON(!list_empty(&fi->queued_writes));
fs/fuse/iomode.c +1 -1
index 3728933188f307..0a534e5a6db5f6 100644
@@ -203,7 +203,7 @@ int fuse_file_io_open(struct file *file, struct inode *inode)
         * io modes are not relevant with DAX and with server that does not
         * implement open.
         */
-       if (FUSE_IS_DAX(inode) || !ff->args)
+       if (fuse_inode_has_iomap(inode) || FUSE_IS_DAX(inode) || !ff->args)
                return 0;
 
        /*
#75 lore raw

Re: [PATCH 09/31] fuse: isolate the other regular file IO paths from iomap

Quoted 13 lines · Amir Goldstein
Quoted 9 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

iomap completely takes over all regular file IO, so we don't need to access any of the other mechanisms at all. Gate them off so that we can eventually overlay them with a union to save space in struct fuse_inode.

---

I apologize for providing criticism which is not very productive.

Quoted 8 lines

Looking at this I don't feel much confidence to say that all cases are covered and worse, I don't have much confidence that future coder won't easily write some code that accesses the wrong side of the union.

I don't really have great ideas on how to improve.
Maybe at least some of the gates can be inside the _nowrite accessors?

Please don't take this as any sort of objection to this patch.

I'll happily drop "fuse: overlay iomap inode info in struct fuse_inode" because C unions are ***awful bug nests anyway. Maybe someday when we're porting fuse to Rust. ;)

--D

Quoted 164 lines

Thanks,
Amir.

Quoted 161 lines
 fs/fuse/dir.c    |   14 +++++++++-----
 fs/fuse/file.c   |   18 +++++++++++++-----
 fs/fuse/inode.c  |    3 ++-
 fs/fuse/iomode.c |    2 +-
 4 files changed, 25 insertions(+), 12 deletions(-)
fs/fuse/dir.c +9 -5
index 3c222b99d6e699..18eb1bb192bb58 100644
@@ -1991,6 +1991,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        FUSE_ARGS(args);
        struct fuse_setattr_in inarg;
        struct fuse_attr_out outarg;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = false;
        bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode);
        loff_t oldsize;
@@ -2048,12 +2049,15 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
                if (err)
                        return err;
 
-               fuse_set_nowrite(inode);
-               fuse_release_nowrite(inode);
+               if (!is_iomap) {
+                       fuse_set_nowrite(inode);
+                       fuse_release_nowrite(inode);
+               }
        }
 
        if (is_truncate) {
-               fuse_set_nowrite(inode);
+               if (!is_iomap)
+                       fuse_set_nowrite(inode);
                set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
                if (trust_local_cmtime && attr->ia_size != inode->i_size)
                        attr->ia_valid |= ATTR_MTIME | ATTR_CTIME;
@@ -2125,7 +2129,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        if (!is_wb || is_truncate)
                i_size_write(inode, outarg.attr.size);
 
-       if (is_truncate) {
+       if (is_truncate && !is_iomap) {
                /* NOTE: this may release/reacquire fi->lock */
                __fuse_release_nowrite(inode);
        }
@@ -2149,7 +2153,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        return 0;
 
 error:
-       if (is_truncate)
+       if (is_truncate && !is_iomap)
                fuse_release_nowrite(inode);
 
        clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
fs/fuse/file.c +13 -5
index 42c85c19f3b13b..bd9c208a46c78d 100644
@@ -238,6 +238,7 @@ static int fuse_open(struct inode *inode, struct file *file)
        struct fuse_conn *fc = fm->fc;
        struct fuse_file *ff;
        int err;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = (file->f_flags & O_TRUNC) && fc->atomic_o_trunc;
        bool is_wb_truncate = is_truncate && fc->writeback_cache;
        bool dax_truncate = is_truncate && FUSE_IS_DAX(inode);
@@ -259,7 +260,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        goto out_inode_unlock;
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_set_nowrite(inode);
 
        err = fuse_do_open(fm, get_node_id(inode), file, false);
@@ -272,7 +273,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        fuse_truncate_update_attr(inode, file);
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_release_nowrite(inode);
        if (!err) {
                if (is_truncate)
@@ -520,12 +521,14 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 {
        struct inode *inode = file->f_mapping->host;
        struct fuse_conn *fc = get_fuse_conn(inode);
+       const bool need_sync_writes = !fuse_inode_has_iomap(inode);
        int err;
 
        if (fuse_is_bad(inode))
                return -EIO;
 
-       inode_lock(inode);
+       if (need_sync_writes)
+               inode_lock(inode);
 
        /*
         * Start writeback against all dirty pages of the inode, then
@@ -536,7 +539,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
        if (err)
                goto out;
 
-       fuse_sync_writes(inode);
+       if (need_sync_writes)
+               fuse_sync_writes(inode);
 
        /*
         * Due to implementation of fuse writeback
@@ -560,7 +564,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
                err = 0;
        }
 out:
-       inode_unlock(inode);
+       if (need_sync_writes)
+               inode_unlock(inode);
 
        return err;
 }
@@ -1942,6 +1947,9 @@ static struct fuse_file *__fuse_write_file_get(struct fuse_inode *fi)
 {
        struct fuse_file *ff;
 
+       if (fuse_inode_has_iomap(&fi->inode))
+               return NULL;
+
        spin_lock(&fi->lock);
        ff = list_first_entry_or_null(&fi->write_files, struct fuse_file,
                                      write_entry);
fs/fuse/inode.c +2 -1
index 9b9e7b2dd0d928..7602595006a19d 100644
@@ -191,7 +191,8 @@ static void fuse_evict_inode(struct inode *inode)
                if (inode->i_nlink > 0)
                        atomic64_inc(&fc->evict_ctr);
        }
-       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode)) {
+       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode) &&
+           !fuse_inode_has_iomap(inode)) {
                WARN_ON(fi->iocachectr != 0);
                WARN_ON(!list_empty(&fi->write_files));
                WARN_ON(!list_empty(&fi->queued_writes));
fs/fuse/iomode.c +1 -1
index 3728933188f307..0a534e5a6db5f6 100644
@@ -203,7 +203,7 @@ int fuse_file_io_open(struct file *file, struct inode *inode)
         * io modes are not relevant with DAX and with server that does not
         * implement open.
         */
-       if (FUSE_IS_DAX(inode) || !ff->args)
+       if (fuse_inode_has_iomap(inode) || FUSE_IS_DAX(inode) || !ff->args)
                return 0;
 
        /*
#76 lore raw

Re: [PATCH 09/31] fuse: isolate the other regular file IO paths from iomap

Quoted 18 lines · Darrick J. Wong
Quoted 17 lines · Amir Goldstein
Quoted 9 lines · Darrick J. Wong

From: Darrick J. Wong <[email protected]>

iomap completely takes over all regular file IO, so we don't need to access any of the other mechanisms at all. Gate them off so that we can eventually overlay them with a union to save space in struct fuse_inode.

---

I apologize for providing criticism which is not very productive.

Looking at this I don't feel much confidence to say that all cases are covered and worse, I don't have much confidence that future coder won't easily write some code that accesses the wrong side of the union.

Quoted 8 lines
Quoted 4 lines

I don't really have great ideas on how to improve.
Maybe at least some of the gates can be inside the _nowrite accessors?

Please don't take this as any sort of objection to this patch.

I'll happily drop "fuse: overlay iomap inode info in struct fuse_inode" because C unions are ***awful bug nests anyway. Maybe someday when we're porting fuse to Rust. ;)

I should add that gating the !iomap code paths mean that we don't have to waste time messing around with otherwise unused data structures, so I'll keep this patch even if I drop the unionizing one.

--D

Quoted 166 lines
Quoted 165 lines

Thanks,
Amir.

Quoted 161 lines
 fs/fuse/dir.c    |   14 +++++++++-----
 fs/fuse/file.c   |   18 +++++++++++++-----
 fs/fuse/inode.c  |    3 ++-
 fs/fuse/iomode.c |    2 +-
 4 files changed, 25 insertions(+), 12 deletions(-)
fs/fuse/dir.c +9 -5
index 3c222b99d6e699..18eb1bb192bb58 100644
@@ -1991,6 +1991,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        FUSE_ARGS(args);
        struct fuse_setattr_in inarg;
        struct fuse_attr_out outarg;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = false;
        bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode);
        loff_t oldsize;
@@ -2048,12 +2049,15 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
                if (err)
                        return err;
 
-               fuse_set_nowrite(inode);
-               fuse_release_nowrite(inode);
+               if (!is_iomap) {
+                       fuse_set_nowrite(inode);
+                       fuse_release_nowrite(inode);
+               }
        }
 
        if (is_truncate) {
-               fuse_set_nowrite(inode);
+               if (!is_iomap)
+                       fuse_set_nowrite(inode);
                set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
                if (trust_local_cmtime && attr->ia_size != inode->i_size)
                        attr->ia_valid |= ATTR_MTIME | ATTR_CTIME;
@@ -2125,7 +2129,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        if (!is_wb || is_truncate)
                i_size_write(inode, outarg.attr.size);
 
-       if (is_truncate) {
+       if (is_truncate && !is_iomap) {
                /* NOTE: this may release/reacquire fi->lock */
                __fuse_release_nowrite(inode);
        }
@@ -2149,7 +2153,7 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
        return 0;
 
 error:
-       if (is_truncate)
+       if (is_truncate && !is_iomap)
                fuse_release_nowrite(inode);
 
        clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
fs/fuse/file.c +13 -5
index 42c85c19f3b13b..bd9c208a46c78d 100644
@@ -238,6 +238,7 @@ static int fuse_open(struct inode *inode, struct file *file)
        struct fuse_conn *fc = fm->fc;
        struct fuse_file *ff;
        int err;
+       const bool is_iomap = fuse_inode_has_iomap(inode);
        bool is_truncate = (file->f_flags & O_TRUNC) && fc->atomic_o_trunc;
        bool is_wb_truncate = is_truncate && fc->writeback_cache;
        bool dax_truncate = is_truncate && FUSE_IS_DAX(inode);
@@ -259,7 +260,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        goto out_inode_unlock;
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_set_nowrite(inode);
 
        err = fuse_do_open(fm, get_node_id(inode), file, false);
@@ -272,7 +273,7 @@ static int fuse_open(struct inode *inode, struct file *file)
                        fuse_truncate_update_attr(inode, file);
        }
 
-       if (is_wb_truncate || dax_truncate)
+       if ((is_wb_truncate || dax_truncate) && !is_iomap)
                fuse_release_nowrite(inode);
        if (!err) {
                if (is_truncate)
@@ -520,12 +521,14 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
 {
        struct inode *inode = file->f_mapping->host;
        struct fuse_conn *fc = get_fuse_conn(inode);
+       const bool need_sync_writes = !fuse_inode_has_iomap(inode);
        int err;
 
        if (fuse_is_bad(inode))
                return -EIO;
 
-       inode_lock(inode);
+       if (need_sync_writes)
+               inode_lock(inode);
 
        /*
         * Start writeback against all dirty pages of the inode, then
@@ -536,7 +539,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
        if (err)
                goto out;
 
-       fuse_sync_writes(inode);
+       if (need_sync_writes)
+               fuse_sync_writes(inode);
 
        /*
         * Due to implementation of fuse writeback
@@ -560,7 +564,8 @@ static int fuse_fsync(struct file *file, loff_t start, loff_t end,
                err = 0;
        }
 out:
-       inode_unlock(inode);
+       if (need_sync_writes)
+               inode_unlock(inode);
 
        return err;
 }
@@ -1942,6 +1947,9 @@ static struct fuse_file *__fuse_write_file_get(struct fuse_inode *fi)
 {
        struct fuse_file *ff;
 
+       if (fuse_inode_has_iomap(&fi->inode))
+               return NULL;
+
        spin_lock(&fi->lock);
        ff = list_first_entry_or_null(&fi->write_files, struct fuse_file,
                                      write_entry);
fs/fuse/inode.c +2 -1
index 9b9e7b2dd0d928..7602595006a19d 100644
@@ -191,7 +191,8 @@ static void fuse_evict_inode(struct inode *inode)
                if (inode->i_nlink > 0)
                        atomic64_inc(&fc->evict_ctr);
        }
-       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode)) {
+       if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode) &&
+           !fuse_inode_has_iomap(inode)) {
                WARN_ON(fi->iocachectr != 0);
                WARN_ON(!list_empty(&fi->write_files));
                WARN_ON(!list_empty(&fi->queued_writes));
fs/fuse/iomode.c +1 -1
index 3728933188f307..0a534e5a6db5f6 100644
@@ -203,7 +203,7 @@ int fuse_file_io_open(struct file *file, struct inode *inode)
         * io modes are not relevant with DAX and with server that does not
         * implement open.
         */
-       if (FUSE_IS_DAX(inode) || !ff->args)
+       if (fuse_inode_has_iomap(inode) || FUSE_IS_DAX(inode) || !ff->args)
                return 0;
 
        /*
#77 lore raw

PATCH 10/31 fuse: implement basic iomap reporting such as FIEMAP and SEEK_{DATA,HOLE}

In reply to Darrick J. Wong

From: Darrick J. Wong <[email protected]>

Implement the basic file mapping reporting functions like FIEMAP, BMAP, and SEEK_DATA/HOLE.

---
 fs/fuse/fuse_i.h     |    8 ++++++
 fs/fuse/dir.c        |    1 +
 fs/fuse/file.c       |   13 ++++++++++
 fs/fuse/file_iomap.c |   68 +++++++++++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 89 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +8 -0
index c7aeb324fe599e..6fe8aa1845b98d 100644
@@ -1730,6 +1730,11 @@ static inline bool fuse_inode_has_iomap(const struct inode *inode)
 
 	return test_bit(FUSE_I_IOMAP, &fi->state);
 }
+
+int fuse_iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
+		      u64 start, u64 length);
+loff_t fuse_iomap_lseek(struct file *file, loff_t offset, int whence);
+sector_t fuse_iomap_bmap(struct address_space *mapping, sector_t block);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -1739,6 +1744,9 @@ static inline bool fuse_inode_has_iomap(const struct inode *inode)
 # define fuse_iomap_init_nonreg_inode(...)	((void)0)
 # define fuse_iomap_evict_inode(...)		((void)0)
 # define fuse_inode_has_iomap(...)		(false)
+# define fuse_iomap_fiemap			NULL
+# define fuse_iomap_lseek(...)			(-ENOSYS)
+# define fuse_iomap_bmap(...)			(-ENOSYS)
 #endif
 
 #endif /* _FS_FUSE_I_H */
fs/fuse/dir.c +1 -0
index 18eb1bb192bb58..bafc386f2f4d3a 100644
@@ -2296,6 +2296,7 @@ static const struct inode_operations fuse_common_inode_operations = {
 	.set_acl	= fuse_set_acl,
 	.fileattr_get	= fuse_fileattr_get,
 	.fileattr_set	= fuse_fileattr_set,
+	.fiemap		= fuse_iomap_fiemap,
 };
 
 static const struct inode_operations fuse_symlink_inode_operations = {
fs/fuse/file.c +13 -0
index bd9c208a46c78d..8a981f41b1dbd0 100644
@@ -2512,6 +2512,12 @@ static sector_t fuse_bmap(struct address_space *mapping, sector_t block)
 	struct fuse_bmap_out outarg;
 	int err;
 
+	if (fuse_inode_has_iomap(inode)) {
+		sector_t alt_sec = fuse_iomap_bmap(mapping, block);
+		if (alt_sec > 0)
+			return alt_sec;
+	}
+
 	if (!inode->i_sb->s_bdev || fm->fc->no_bmap)
 		return 0;
 
@@ -2547,6 +2553,13 @@ static loff_t fuse_lseek(struct file *file, loff_t offset, int whence)
 	struct fuse_lseek_out outarg;
 	int err;
 
+	if (fuse_inode_has_iomap(inode)) {
+		loff_t alt_pos = fuse_iomap_lseek(file, offset, whence);
+
+		if (alt_pos >= 0 || (alt_pos < 0 && alt_pos != -ENOSYS))
+			return alt_pos;
+	}
+
 	if (fm->fc->no_lseek)
 		goto fallback;
 
fs/fuse/file_iomap.c +67 -1

83 lines not on this page · raw message