Skip to contentSkip to conversation

fuse/libfuse/e2fsprogs: containerize ext4 for safer operation

PATCH In review Darrick J. Wong 8 participants 231 messages Feb 23 – Apr 29 Page 1 of 3

Subsystems (9)
Stable branch VFS Library code BPF +5 more subsystems
lore
Share & tools
lore
#0 lore raw

PATCH v7 1/1 fuse/libfuse/e2fsprogs: containerize ext4 for safer operation

This is the seventh 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.

Demi Marie Obenour pointed out that libguestfs exists. That project creates a minimum rootfs, spins up a libvirt VM with a disk image attached, and has a fuse server that can talk to the VM to provide file access. This provides the safety and isolation that I discussed above, though the performance is not great, the memory and disk space consumption are rather amazing (500MB and 350MB, respectively!), and startup times are very slow. This project avoids those overheads, though I concede that libguestfs already exists and probably works in more places than, say, lklfuse.

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 can 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 sixth RFC:

1. Setting current->flags didn't work for fuse servers running inside a systemd service, so that's now fixed.

2. Joanne and I worked together to build a prototype of allowing the fuse server to override the iomap ops via the BPF struct_ops device. This might take care of the interleaved mapping code in John Groves' famfs patchset. This worked great back when my dev branch was based off of 6.19.

Unfortunately it's broken in 7.0-rc1 because ... something changed in how BTF gets generated and now I get weird compiler warnings and the kernel build fails. I don't currently know what in gcc 14.2 is allergic let alone how to fix this. :(

The BPF parts of this submission are RFC because at this point I still have a lot of unresolved questions, such as:

a> If you're building a file server for a distro package, there seems
to be very little consistency as to where vmlinux.h might be found.

b> Can we just compile the bpf at runtime? That would introduce a
lot of runtime dependencies (bpftool, clang, etc.) and precludes the possibility of vendor-signed bpf binaries.

c> Are the memory protections implemented by the RFC series adequate
to prevent data theft and/or kernel memory corruption? struct ops seem to have a lot of capabilities.

d> Does anyone else in filesystem-land think this is a good idea?

3. The mapping cache isn't invalidated at file close anymore.

4. Cleaned up the header files so that we're not just dumping tons of symbols in fuse_i.h.

5. Various review complaints from Chris Mason's AI reviewer.

There are some warts remaining:

a. I would like to continue the 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.

e. I've dropped the fstests part of the patchbomb because v6 was just
way too long.

I would like to get the main parts of this submission reviewed for 7.1 now that this has been collecting comments and tweaks in non-rfc status for 3.5 months.

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

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

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

fstests:
https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfstests-dev.git/log/?h=fuse2fs

--Darrick

#1 lore raw

PATCH v7 1/9 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.

With a bit of luck, this should all go splendidly. 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_RELEASE requests before sending FUSE_DESTROY
* fuse: quiet down complaints in fuse_conn_limit_write
* 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  |   48 ++++++++++++++++++++++++
 fs/fuse/acl.c     |  105 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 fs/fuse/control.c |    4 +-
 fs/fuse/dev.c     |   19 ++++++++++
 fs/fuse/dir.c     |  105 ++++++++++++++++++++++++++++++++++++++++-------------
 fs/fuse/inode.c   |   16 ++++++++
 6 files changed, 267 insertions(+), 30 deletions(-)
#2 lore raw

PATCH 1/5 fuse: flush pending FUSE_RELEASE requests before sending FUSE_DESTROY

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 write all of its pending changes to the block device before replying to the DESTROY request because the kernel releases its O_EXCL hold on the block device. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

For fuse-iomap servers this will also be a problem because iomap servers are expected to release all exclusively-held resources before unmount returns from the kernel.

Create a function to push all the background requests to the queue before sending FUSE_DESTROY. That way, all the pending file release events are processed by the fuse server before it tears itself down, and we don't end up with a corrupt filesystem.

Note that multithreaded fuse servers will need to track the number of open files and defer a FUSE_DESTROY request until that number reaches zero. An earlier version of this patch made the kernel wait for the RELEASE acknowledgements before sending DESTROY, but the kernel people weren't comfortable with adding blocking waits to unmount.

---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   19 +++++++++++++++++++
 fs/fuse/inode.c  |   12 +++++++++++-
 3 files changed, 35 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +5 -0
index 7f16049387d15e..1d4beca5c7018d 100644
@@ -1287,6 +1287,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 but do not wait for them.
+ */
+void fuse_flush_requests(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +19 -0
index 0b0241f47170d4..ac9d7a7b3f5e68 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,24 @@ 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(struct fuse_conn *fc)
+{
+	spin_lock(&fc->lock);
+	spin_lock(&fc->bg_lock);
+	if (fc->connected) {
+		/* Push all the background requests to the queue. */
+		fc->blocked = 0;
+		fc->max_background = UINT_MAX;
+		flush_bg_queue(fc);
+	}
+	spin_unlock(&fc->bg_lock);
+	spin_unlock(&fc->lock);
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +11 -1
index e57b8af06be93e..58c3351b467221 100644
@@ -2086,8 +2086,18 @@ 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.  We don't wait, so libfuse
+		 * has to do that for us.
+		 */
+		fuse_flush_requests(fc);
 		fuse_send_destroy(fm);
+	}
 
 	fuse_abort_conn(fc);
 	fuse_wait_aborted(fc);
Reviewed-by on v1 1/5
#3 lore raw

Re: [PATCH 1/5] fuse: flush pending FUSE_RELEASE requests before sending FUSE_DESTROY

Quoted 42 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 write all of its pending changes to the block device before replying to the DESTROY request because the kernel releases its O_EXCL hold on the block device. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

For fuse-iomap servers this will also be a problem because iomap servers are expected to release all exclusively-held resources before unmount returns from the kernel.

Create a function to push all the background requests to the queue before sending FUSE_DESTROY. That way, all the pending file release events are processed by the fuse server before it tears itself down, and we don't end up with a corrupt filesystem.

Quoted 7 lines

Note that multithreaded fuse servers will need to track the number of open files and defer a FUSE_DESTROY request until that number reaches zero. An earlier version of this patch made the kernel wait for the RELEASE acknowledgements before sending DESTROY, but the kernel people weren't comfortable with adding blocking waits to unmount.

Overall LGTM, left a few comments below

Quoted 12 lines
---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   19 +++++++++++++++++++
 fs/fuse/inode.c  |   12 +++++++++++-
 3 files changed, 35 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +0 -0
index 7f16049387d15e..1d4beca5c7018d 100644

fs/fuse/fuse_i.h void fuse_request_end(struct fuse_req *req); · line 1292

Quoted 6 lines
fs/fuse/fuse_i.h +3 -0
@@ -1287,6 +1287,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 but do not wait for them.
+ */

nit: /* */ comment style

Quoted 10 lines
fs/fuse/fuse_i.h +2 -0
+void fuse_flush_requests(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
fs/fuse/dev.c +0 -0
index 0b0241f47170d4..ac9d7a7b3f5e68 100644

fs/fuse/dev.c line 27

Quoted 4 lines
fs/fuse/dev.c +1 -0
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>

I don't think you meant to add this?

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

Quoted 9 lines
fs/fuse/dev.c +2 -0
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,24 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
+/*
+ * Flush all pending requests and wait for them.  Only call this function when

I think you meant "don't wait" for them?

Quoted 26 lines
fs/fuse/dev.c +16 -0
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);
+       spin_lock(&fc->bg_lock);
+       if (fc->connected) {
+               /* Push all the background requests to the queue. */
+               fc->blocked = 0;
+               fc->max_background = UINT_MAX;
+               flush_bg_queue(fc);
+       }
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +0 -0
index e57b8af06be93e..58c3351b467221 100644
@@ -2086,8 +2086,18 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;

fs/fuse/inode.c void fuse_conn_destroy(struct fuse_mount *fm) · line 2096

Quoted 10 lines
fs/fuse/inode.c +8 -1
 
-       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.  We don't wait, so libfuse
+                * has to do that for us.

nit: imo the "because the fuse server must close the filesystem before replying to the destroy message, because..." part is confusing. Even if that weren't true, the pending requests would still have to be sent before the destroy, no? i think it would be less confusing if that part of the paragraph was removed. I think it might be better to remove the "we don't wait, so libfuse has to do that for us" part too or rewording it to something like "flushed requests are sent before the FUSE_DESTROY. Userspace is responsible for ensuring flushed requests are handled before replying to the FUSE_DESTROY".

Thanks,
Joanne

Quoted 8 lines
fs/fuse/inode.c +3 -0
+                */
+               fuse_flush_requests(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#4 lore raw

Re: [PATCH 1/5] fuse: flush pending FUSE_RELEASE requests before sending FUSE_DESTROY

Quoted 49 lines · Joanne Koong
Quoted 48 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 write all of its pending changes to the block device before replying to the DESTROY request because the kernel releases its O_EXCL hold on the block device. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

For fuse-iomap servers this will also be a problem because iomap servers are expected to release all exclusively-held resources before unmount returns from the kernel.

Create a function to push all the background requests to the queue before sending FUSE_DESTROY. That way, all the pending file release events are processed by the fuse server before it tears itself down, and we don't end up with a corrupt filesystem.

Note that multithreaded fuse servers will need to track the number of open files and defer a FUSE_DESTROY request until that number reaches zero. An earlier version of this patch made the kernel wait for the RELEASE acknowledgements before sending DESTROY, but the kernel people weren't comfortable with adding blocking waits to unmount.

Quoted 5 lines
Quoted 1 line

Overall LGTM, left a few comments below

Thanks!

Quoted 15 lines
Quoted 15 lines
---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   19 +++++++++++++++++++
 fs/fuse/inode.c  |   12 +++++++++++-
 3 files changed, 35 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +0 -0
index 7f16049387d15e..1d4beca5c7018d 100644
@@ -1287,6 +1287,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);
 
Quoted 5 lines

fs/fuse/fuse_i.h void fuse_request_end(struct fuse_req *req); · line 1292

Quoted 3 lines
fs/fuse/fuse_i.h +3 -0
+/**
+ * Flush all pending requests but do not wait for them.
+ */

nit: /* */ comment style

I'm very confused by the comment style in this header file. Some of them look like kerneldoc comments (albeit not documenting the sole parameter), but others are just regular C comments.

<shrug> I sorta dislike kerneldoc's fussiness so I'll change it to a C comment so that I don't have to propagate this "@param fc fuse connection" verbosity.

Quoted 5 lines
Quoted 5 lines
fs/fuse/fuse_i.h +2 -0
+void fuse_flush_requests(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
Quoted 11 lines

fs/fuse/dev.c line 27

Quoted 9 lines
fs/fuse/dev.c +1 -0
index 0b0241f47170d4..ac9d7a7b3f5e68 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>

I don't think you meant to add this?

Yep, that was added for a previous iteration and can go away now.

Quoted 11 lines

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

Quoted 9 lines
fs/fuse/dev.c +2 -0
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,24 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
+/*
+ * Flush all pending requests and wait for them.  Only call this function when

I think you meant "don't wait" for them?

Right. Fixed.

Quoted 38 lines
Quoted 26 lines
fs/fuse/dev.c +16 -0
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);
+       spin_lock(&fc->bg_lock);
+       if (fc->connected) {
+               /* Push all the background requests to the queue. */
+               fc->blocked = 0;
+               fc->max_background = UINT_MAX;
+               flush_bg_queue(fc);
+       }
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +0 -0
index e57b8af06be93e..58c3351b467221 100644
@@ -2086,8 +2086,18 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;

fs/fuse/inode.c void fuse_conn_destroy(struct fuse_mount *fm) · line 2096

Quoted 10 lines
fs/fuse/inode.c +8 -1
 
-       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.  We don't wait, so libfuse
+                * has to do that for us.

nit: imo the "because the fuse server must close the filesystem before

Quoted 8 lines

replying to the destroy message, because..." part is confusing. Even if that weren't true, the pending requests would still have to be sent before the destroy, no? i think it would be less confusing if that part of the paragraph was removed. I think it might be better to remove the "we don't wait, so libfuse has to do that for us" part too or rewording it to something like "flushed requests are sent before the FUSE_DESTROY. Userspace is responsible for ensuring flushed requests are handled before replying to the FUSE_DESTROY".

How about I simplify it to:

/*
* Flush all pending requests before sending FUSE_DESTROY. The
* fuse server must reply to the flushed requests before
* handling FUSE_DESTROY because unmount is about to release
* its O_EXCL hold on the block device.
*/

--D

Quoted 13 lines

Thanks,
Joanne

Quoted 8 lines
fs/fuse/inode.c +3 -0
+                */
+               fuse_flush_requests(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#5 lore raw

Re: [PATCH 1/5] fuse: flush pending FUSE_RELEASE requests before sending FUSE_DESTROY

Quoted 80 lines · Darrick J. Wong
Quoted 49 lines · Joanne Koong
Quoted 48 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 write all of its pending changes to the block device before replying to the DESTROY request because the kernel releases its O_EXCL hold on the block device. This means that the kernel must flush all pending FUSE_RELEASE requests before issuing FUSE_DESTROY.

For fuse-iomap servers this will also be a problem because iomap servers are expected to release all exclusively-held resources before unmount returns from the kernel.

Create a function to push all the background requests to the queue before sending FUSE_DESTROY. That way, all the pending file release events are processed by the fuse server before it tears itself down, and we don't end up with a corrupt filesystem.

Note that multithreaded fuse servers will need to track the number of open files and defer a FUSE_DESTROY request until that number reaches zero. An earlier version of this patch made the kernel wait for the RELEASE acknowledgements before sending DESTROY, but the kernel people weren't comfortable with adding blocking waits to unmount.

Quoted 5 lines
Quoted 1 line

Overall LGTM, left a few comments below

Thanks!

Quoted 15 lines
Quoted 15 lines
---
 fs/fuse/fuse_i.h |    5 +++++
 fs/fuse/dev.c    |   19 +++++++++++++++++++
 fs/fuse/inode.c  |   12 +++++++++++-
 3 files changed, 35 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +0 -0
index 7f16049387d15e..1d4beca5c7018d 100644
@@ -1287,6 +1287,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);
 
Quoted 5 lines

fs/fuse/fuse_i.h void fuse_request_end(struct fuse_req *req); · line 1292

Quoted 3 lines
fs/fuse/fuse_i.h +3 -0
+/**
+ * Flush all pending requests but do not wait for them.
+ */

nit: /* */ comment style

Quoted 3 lines

I'm very confused by the comment style in this header file. Some of them look like kerneldoc comments (albeit not documenting the sole parameter), but others are just regular C comments.

Oh I see your confusion now. Yeah the comment styles in this .h file are kind of all over the place. Most of the functions don't even have comments.

Quoted 85 lines

<shrug> I sorta dislike kerneldoc's fussiness so I'll change it to a C comment so that I don't have to propagate this "@param fc fuse connection" verbosity.

Quoted 5 lines
Quoted 5 lines
fs/fuse/fuse_i.h +2 -0
+void fuse_flush_requests(struct fuse_conn *fc);
+
 /* Check if any requests timed out */
 void fuse_check_timeout(struct work_struct *work);
 
Quoted 11 lines

fs/fuse/dev.c line 27

Quoted 9 lines
fs/fuse/dev.c +1 -0
index 0b0241f47170d4..ac9d7a7b3f5e68 100644
@@ -24,6 +24,7 @@
 #include <linux/splice.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
+#include <linux/nmi.h>

I don't think you meant to add this?

Yep, that was added for a previous iteration and can go away now.

Quoted 11 lines

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

Quoted 9 lines
fs/fuse/dev.c +2 -0
 #include "fuse_trace.h"
 
@@ -2430,6 +2431,24 @@ static void end_polls(struct fuse_conn *fc)
        }
 }
 
+/*
+ * Flush all pending requests and wait for them.  Only call this function when

I think you meant "don't wait" for them?

Right. Fixed.

Quoted 38 lines
Quoted 26 lines
fs/fuse/dev.c +16 -0
+ * it is no longer possible for other threads to add requests.
+ */
+void fuse_flush_requests(struct fuse_conn *fc)
+{
+       spin_lock(&fc->lock);
+       spin_lock(&fc->bg_lock);
+       if (fc->connected) {
+               /* Push all the background requests to the queue. */
+               fc->blocked = 0;
+               fc->max_background = UINT_MAX;
+               flush_bg_queue(fc);
+       }
+       spin_unlock(&fc->bg_lock);
+       spin_unlock(&fc->lock);
+}
+
 /*
  * Abort all requests.
  *
fs/fuse/inode.c +0 -0
index e57b8af06be93e..58c3351b467221 100644
@@ -2086,8 +2086,18 @@ void fuse_conn_destroy(struct fuse_mount *fm)
 {
        struct fuse_conn *fc = fm->fc;

fs/fuse/inode.c void fuse_conn_destroy(struct fuse_mount *fm) · line 2096

Quoted 10 lines
fs/fuse/inode.c +8 -1
 
-       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.  We don't wait, so libfuse
+                * has to do that for us.

nit: imo the "because the fuse server must close the filesystem before

Quoted 8 lines

replying to the destroy message, because..." part is confusing. Even if that weren't true, the pending requests would still have to be sent before the destroy, no? i think it would be less confusing if that part of the paragraph was removed. I think it might be better to remove the "we don't wait, so libfuse has to do that for us" part too or rewording it to something like "flushed requests are sent before the FUSE_DESTROY. Userspace is responsible for ensuring flushed requests are handled before replying to the FUSE_DESTROY".

Quoted 8 lines

How about I simplify it to:

/*
* Flush all pending requests before sending FUSE_DESTROY. The
* fuse server must reply to the flushed requests before
* handling FUSE_DESTROY because unmount is about to release
* its O_EXCL hold on the block device.
*/

This sounds a lot better to me.

Thanks,
Joanne

Quoted 16 lines

--D

Quoted 13 lines

Thanks,
Joanne

Quoted 8 lines
fs/fuse/inode.c +3 -0
+                */
+               fuse_flush_requests(fc);
                fuse_send_destroy(fm);
+       }
 
        fuse_abort_conn(fc);
        fuse_wait_aborted(fc);
#6 lore raw

PATCH 2/5 fuse: quiet down complaints in fuse_conn_limit_write

In reply to Darrick J. Wong

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

gcc 15 complains about an uninitialized variable val that is passed by reference into fuse_conn_limit_write:

control.c: In function ‘fuse_conn_congestion_threshold_write’:
include/asm-generic/rwonce.h:55:37: warning: ‘val’ may be used uninitialized [-Wmaybe-uninitialized]

    55 |         *(volatile typeof(x) *)&(x) = (val);                            \
       |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
 include/asm-generic/rwonce.h:61:9: note: in expansion of macro ‘__WRITE_ONCE’
    61 |         __WRITE_ONCE(x, val);                                           \
       |         ^~~~~~~~~~~~
 control.c:178:9: note: in expansion of macro ‘WRITE_ONCE’
   178 |         WRITE_ONCE(fc->congestion_threshold, val);
       |         ^~~~~~~~~~

control.c:166:18: note: ‘val’ was declared here
166 | unsigned val;
| ^~~

Unfortunately there's enough macro spew involved in kstrtoul_from_user that I think gcc gives up on its analysis and sprays the above warning. AFAICT it's not actually a bug, but we could just zero-initialize the variable to enable using -Wmaybe-uninitialized to find real problems.

Previously we would use some weird uninitialized_var annotation to quiet down the warnings, so clearly this code has been like this for quite some time.

Cc <[email protected]> # v5.9
Fixes 3f649ab728cda8 ("treewide: Remove uninitialized_var() usage")
---
 fs/fuse/control.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/fuse/control.c +2 -2
index 140bd5730d9984..073c2d8e4dfc7c 100644
@@ -121,7 +121,7 @@ static ssize_t fuse_conn_max_background_write(struct file *file,
 					      const char __user *buf,
 					      size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	ssize_t ret;
 
 	ret = fuse_conn_limit_write(file, buf, count, ppos, &val,
@@ -163,7 +163,7 @@ static ssize_t fuse_conn_congestion_threshold_write(struct file *file,
 						    const char __user *buf,
 						    size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	struct fuse_conn *fc;
 	ssize_t ret;
 
Reviewed-by on v1 2/5
#7 lore raw

Re: [PATCH 2/5] fuse: quiet down complaints in fuse_conn_limit_write

Quoted 52 lines · Darrick J. Wong

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

gcc 15 complains about an uninitialized variable val that is passed by reference into fuse_conn_limit_write:

control.c: In function ‘fuse_conn_congestion_threshold_write’:
include/asm-generic/rwonce.h:55:37: warning: ‘val’ may be used uninitialized [-Wmaybe-uninitialized]

    55 |         *(volatile typeof(x) *)&(x) = (val);                            \
       |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
 include/asm-generic/rwonce.h:61:9: note: in expansion of macro ‘__WRITE_ONCE’
    61 |         __WRITE_ONCE(x, val);                                           \
       |         ^~~~~~~~~~~~
 control.c:178:9: note: in expansion of macro ‘WRITE_ONCE’
   178 |         WRITE_ONCE(fc->congestion_threshold, val);
       |         ^~~~~~~~~~

control.c:166:18: note: ‘val’ was declared here
166 | unsigned val;
| ^~~

Unfortunately there's enough macro spew involved in kstrtoul_from_user that I think gcc gives up on its analysis and sprays the above warning. AFAICT it's not actually a bug, but we could just zero-initialize the variable to enable using -Wmaybe-uninitialized to find real problems.

Previously we would use some weird uninitialized_var annotation to quiet down the warnings, so clearly this code has been like this for quite some time.

Cc <[email protected]> # v5.9
Fixes 3f649ab728cda8 ("treewide: Remove uninitialized_var() usage")
---
 fs/fuse/control.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/fuse/control.c +1 -1
index 140bd5730d9984..073c2d8e4dfc7c 100644
@@ -121,7 +121,7 @@ static ssize_t fuse_conn_max_background_write(struct file *file,
 					      const char __user *buf,
 					      size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	ssize_t ret;
 
 	ret = fuse_conn_limit_write(file, buf, count, ppos, &val,

fs/fuse/control.c static ssize_t fuse_conn_congestion_threshold_write(struct file *file, · line 169

Quoted 8 lines
fs/fuse/control.c +1 -1
@@ -163,7 +163,7 @@ static ssize_t fuse_conn_congestion_threshold_write(struct file *file,
 						    const char __user *buf,
 						    size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	struct fuse_conn *fc;
 	ssize_t ret;
 

This looks good to me. Trivial fix for an annoying problem.

#8 lore raw

Re: [PATCH 2/5] fuse: quiet down complaints in fuse_conn_limit_write

Quoted 63 lines · Horst Birthelmer
Quoted 52 lines · Darrick J. Wong

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

gcc 15 complains about an uninitialized variable val that is passed by reference into fuse_conn_limit_write:

control.c: In function ‘fuse_conn_congestion_threshold_write’:
include/asm-generic/rwonce.h:55:37: warning: ‘val’ may be used uninitialized [-Wmaybe-uninitialized]

    55 |         *(volatile typeof(x) *)&(x) = (val);                            \
       |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
 include/asm-generic/rwonce.h:61:9: note: in expansion of macro ‘__WRITE_ONCE’
    61 |         __WRITE_ONCE(x, val);                                           \
       |         ^~~~~~~~~~~~
 control.c:178:9: note: in expansion of macro ‘WRITE_ONCE’
   178 |         WRITE_ONCE(fc->congestion_threshold, val);
       |         ^~~~~~~~~~

control.c:166:18: note: ‘val’ was declared here
166 | unsigned val;
| ^~~

Unfortunately there's enough macro spew involved in kstrtoul_from_user that I think gcc gives up on its analysis and sprays the above warning. AFAICT it's not actually a bug, but we could just zero-initialize the variable to enable using -Wmaybe-uninitialized to find real problems.

Previously we would use some weird uninitialized_var annotation to quiet down the warnings, so clearly this code has been like this for quite some time.

Cc <[email protected]> # v5.9
Fixes 3f649ab728cda8 ("treewide: Remove uninitialized_var() usage")
---
 fs/fuse/control.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/fuse/control.c +1 -1
index 140bd5730d9984..073c2d8e4dfc7c 100644
@@ -121,7 +121,7 @@ static ssize_t fuse_conn_max_background_write(struct file *file,
 					      const char __user *buf,
 					      size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	ssize_t ret;
 
 	ret = fuse_conn_limit_write(file, buf, count, ppos, &val,

fs/fuse/control.c static ssize_t fuse_conn_congestion_threshold_write(struct file *file, · line 169

Quoted 8 lines
fs/fuse/control.c +1 -1
@@ -163,7 +163,7 @@ static ssize_t fuse_conn_congestion_threshold_write(struct file *file,
 						    const char __user *buf,
 						    size_t count, loff_t *ppos)
 {
-	unsigned val;
+	unsigned val = 0;
 	struct fuse_conn *fc;
 	ssize_t ret;
 

This looks good to me. Trivial fix for an annoying problem.

Quoted 1 line

Thanks for the review!

--D

Reviewed-by on v1 2/5
#9 lore raw

Re: [PATCH 2/5] fuse: quiet down complaints in fuse_conn_limit_write

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

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

gcc 15 complains about an uninitialized variable val that is passed by reference into fuse_conn_limit_write:

control.c: In function ‘fuse_conn_congestion_threshold_write’:
include/asm-generic/rwonce.h:55:37: warning: ‘val’ may be used uninitialized [-Wmaybe-uninitialized]

    55 |         *(volatile typeof(x) *)&(x) = (val);                            \
       |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
 include/asm-generic/rwonce.h:61:9: note: in expansion of macro ‘__WRITE_ONCE’
    61 |         __WRITE_ONCE(x, val);                                           \
       |         ^~~~~~~~~~~~
 control.c:178:9: note: in expansion of macro ‘WRITE_ONCE’
   178 |         WRITE_ONCE(fc->congestion_threshold, val);
       |         ^~~~~~~~~~

control.c:166:18: note: ‘val’ was declared here
166 | unsigned val;
| ^~~

Unfortunately there's enough macro spew involved in kstrtoul_from_user that I think gcc gives up on its analysis and sprays the above warning. AFAICT it's not actually a bug, but we could just zero-initialize the variable to enable using -Wmaybe-uninitialized to find real problems.

Quoted 7 lines

Previously we would use some weird uninitialized_var annotation to quiet down the warnings, so clearly this code has been like this for quite some time.

Cc <[email protected]> # v5.9
Fixes 3f649ab728cda8 ("treewide: Remove uninitialized_var() usage")

Makes sense to me.

Quoted 28 lines
---
 fs/fuse/control.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/fuse/control.c +2 -2
index 140bd5730d9984..073c2d8e4dfc7c 100644
@@ -121,7 +121,7 @@ static ssize_t fuse_conn_max_background_write(struct file *file,
                                              const char __user *buf,
                                              size_t count, loff_t *ppos)
 {
-       unsigned val;
+       unsigned val = 0;
        ssize_t ret;
 
        ret = fuse_conn_limit_write(file, buf, count, ppos, &val,
@@ -163,7 +163,7 @@ static ssize_t fuse_conn_congestion_threshold_write(struct file *file,
                                                    const char __user *buf,
                                                    size_t count, loff_t *ppos)
 {
-       unsigned val;
+       unsigned val = 0;
        struct fuse_conn *fc;
        ssize_t ret;
 
maintainer Applied
#10 lore raw

Re: [PATCH 2/5] fuse: quiet down complaints in fuse_conn_limit_write

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

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

gcc 15 complains about an uninitialized variable val that is passed by reference into fuse_conn_limit_write:

control.c: In function ‘fuse_conn_congestion_threshold_write’:
include/asm-generic/rwonce.h:55:37: warning: ‘val’ may be used uninitialized [-Wmaybe-uninitialized]

    55 |         *(volatile typeof(x) *)&(x) = (val);                            \
       |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
 include/asm-generic/rwonce.h:61:9: note: in expansion of macro ‘__WRITE_ONCE’
    61 |         __WRITE_ONCE(x, val);                                           \
       |         ^~~~~~~~~~~~
 control.c:178:9: note: in expansion of macro ‘WRITE_ONCE’
   178 |         WRITE_ONCE(fc->congestion_threshold, val);
       |         ^~~~~~~~~~

control.c:166:18: note: ‘val’ was declared here
166 | unsigned val;
| ^~~

Unfortunately there's enough macro spew involved in kstrtoul_from_user that I think gcc gives up on its analysis and sprays the above warning. AFAICT it's not actually a bug, but we could just zero-initialize the variable to enable using -Wmaybe-uninitialized to find real problems.

Quoted 7 lines

Previously we would use some weird uninitialized_var annotation to quiet down the warnings, so clearly this code has been like this for quite some time.

Cc <[email protected]> # v5.9
Fixes 3f649ab728cda8 ("treewide: Remove uninitialized_var() usage")

Applied, thanks.

Miklos

#11 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 1d4beca5c7018d..79793db3e9a743 100644
@@ -147,6 +147,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 {
@@ -1236,6 +1240,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 7ac6b232ef1232..10fa47e969292f 100644
@@ -1464,6 +1464,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;
 	}
@@ -1568,6 +1570,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 58c3351b467221..ff8b94cb02e63c 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)
#12 lore raw

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

Quoted 84 lines · 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 1d4beca5c7018d..79793db3e9a743 100644
@@ -147,6 +147,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 {
@@ -1236,6 +1240,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 +2 -0
index 7ac6b232ef1232..10fa47e969292f 100644
@@ -1464,6 +1464,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;
        }

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

Quoted 5 lines
fs/fuse/dir.c +2 -0
@@ -1568,6 +1570,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;

Do these need to be |= so we don't overwrite any vfs attributes stored in stat already?

Thanks,
Joanne

Quoted 19 lines
fs/fuse/dir.c +0 -0
        }
 
        return err;
fs/fuse/inode.c +4 -0
index 58c3351b467221..ff8b94cb02e63c 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)
#13 lore raw

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

Quoted 85 lines · Joanne Koong
Quoted 84 lines · 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 1d4beca5c7018d..79793db3e9a743 100644
@@ -147,6 +147,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 {
@@ -1236,6 +1240,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 +2 -0
index 7ac6b232ef1232..10fa47e969292f 100644
@@ -1464,6 +1464,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;
        }
@@ -1568,6 +1570,8 @@ static int fuse_update_get_attr(struct mnt_idmap *idmap, struct inode *inode,
Quoted 8 lines

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

Quoted 5 lines
fs/fuse/dir.c +2 -0
                        stat->btime = fi->i_btime;
                        stat->result_mask |= STATX_BTIME;
                }
+               stat->attributes = fi->statx_attributes;
+               stat->attributes_mask = fi->statx_attributes_mask;

Do these need to be |= so we don't overwrite any vfs attributes stored in stat already?

Ackpth yes. Good catch!

--D

Quoted 23 lines

Thanks,
Joanne

Quoted 19 lines
fs/fuse/dir.c +0 -0
        }
 
        return err;
fs/fuse/inode.c +4 -0
index 58c3351b467221..ff8b94cb02e63c 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)
#14 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 79793db3e9a743..a1880599455c0a 100644
@@ -1051,7 +1051,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

#15 lore raw

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

Quoted 60 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/acl.c +18 -0
index cbde6ac1add35a..f2b959efd67490 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;
 
+       /*
+        * 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.
+        */

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

Quoted 10 lines
fs/fuse/acl.c +7 -0
+       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;
+       }
+
        if (acl) {
                unsigned int extra_flags = 0;
                /*

I think this sentence in this comment block "Fuse userspace is responsible for updating access permissions in the inode, if needed" needs some updating now, since this is only now true for non-local fuse servers

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

Quoted 6 lines
fs/fuse/acl.c +1 -1
@@ -139,7 +164,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 &&

Maybe a bit verbose but imo it'd be clearer if we had a separate boolean tracking the case where the kernel updated the mode bits, instead of using "mode == inode->i_mode" here and below for the fuse_do_setattr() logic block. That makes it more clear here to reason about (eg it'd at least make it more obvious here that we don't need to strip sgid since the kernel already did that when it updated the mode bits earlier)

Quoted 14 lines
fs/fuse/acl.c +7 -0
                    !in_group_or_capable(idmap, inode,
                                         i_gid_into_vfsgid(idmap, inode)))
                        extra_flags |= FUSE_SETXATTR_ACL_KILL_SGID;
@@ -148,6 +173,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) {

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

Quoted 10 lines
fs/fuse/acl.c +9 -0
+               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);
        }

I think this logic reads clearer if it's restructured to

if (!ret && mode != inode->i_mode) {
    struct iattr attr = {
            .ia_valid = ATTR_MODE,
            .ia_mode = mode,
     };

    ret = fuse_do_setattr(idmap, dentry, &attr, NULL);
}

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

Quoted 3 lines
fs/fuse/acl.c +0 -0
        if (fc->posix_acl) {
 

For local / exclusive servers, the kernel already has / sets the refreshed attributes, so we could probably skip the invalidation logic here for that case since the cache is already uptodate?

Thanks,
Joanne

#16 lore raw

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

Quoted 68 lines · Joanne Koong
Quoted 67 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/acl.c +25 -0
index cbde6ac1add35a..f2b959efd67490 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;
 
+       /*
+        * 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;
+       }
+
Quoted 8 lines

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

Quoted 3 lines
fs/fuse/acl.c +0 -0
        if (acl) {
                unsigned int extra_flags = 0;
                /*

I think this sentence in this comment block "Fuse userspace is responsible for updating access permissions in the inode, if needed" needs some updating now, since this is only now true for non-local fuse servers

Done.

/*
* For non-local filesystems, fuse userspace is responsible for
* updating access permissions in the inode, if needed.
* fuse_setxattr invalidates the inode attributes, which will
* force them to be refreshed the next time they are used, and
* it also updates i_ctime.
*/

Quoted 15 lines

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

Quoted 7 lines
fs/fuse/acl.c +1 -1
@@ -139,7 +164,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 &&

Maybe a bit verbose but imo it'd be clearer if we had a separate boolean tracking the case where the kernel updated the mode bits, instead of using "mode == inode->i_mode" here and below for the fuse_do_setattr() logic block. That makes it more clear here to reason about (eg it'd at least make it more obvious here that we don't need to strip sgid since the kernel already did that when it updated the mode bits earlier)

Yeah, this could be keyed off fuse_inode_has_local_acls().

Quoted 38 lines
Quoted 15 lines
fs/fuse/acl.c +7 -0
                    !in_group_or_capable(idmap, inode,
                                         i_gid_into_vfsgid(idmap, inode)))
                        extra_flags |= FUSE_SETXATTR_ACL_KILL_SGID;
@@ -148,6 +173,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) {

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

Quoted 10 lines
fs/fuse/acl.c +9 -0
+               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);
        }

I think this logic reads clearer if it's restructured to

if (!ret && mode != inode->i_mode) {
    struct iattr attr = {
            .ia_valid = ATTR_MODE,
            .ia_mode = mode,
     };

    ret = fuse_do_setattr(idmap, dentry, &attr, NULL);
}
Quoted 1 line
Quoted 6 lines
Quoted 2 lines
        if (fc->posix_acl) {

For local / exclusive servers, the kernel already has / sets the refreshed attributes, so we could probably skip the invalidation logic here for that case since the cache is already uptodate?

I could, but down in the iomap patchset I add more logic to update the ctime:

	struct iattr attr = { };

	/*
	 * When we're running in iomap mode, we need to update mode and
	 * ctime ourselves instead of letting the fuse server figure
	 * that out.
	 */
	if (is_iomap) {
		attr.ia_valid |= ATTR_CTIME;
		inode_set_ctime_current(inode);
		attr.ia_ctime = inode_get_ctime(inode);
	}

	/*
	 * If we scheduled a mode update above, push that to userspace
	 * now.
	 */
	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);

In non-iomap "local acls" mode the server's still expected to update ctime in set/removexattr. OTOH I guess that is ... 65-16=49 patches from now so maybe it's worth the churn?

Either way thanks for getting back to this. :)

--D

Quoted 3 lines

Thanks,
Joanne

#17 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    |   62 +++++++++++++++++++++++++++++++++
 fs/fuse/dir.c    |  101 +++++++++++++++++++++++++++++++++++++++++-------------
 3 files changed, 142 insertions(+), 25 deletions(-)
fs/fuse/fuse_i.h +4 -0
index a1880599455c0a..77b581ecf48a16 100644
@@ -1533,6 +1533,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 +62 -0

71 lines not on this page · raw message

fs/fuse/dir.c +76 -25

246 lines not on this page · raw message

#18 lore raw

PATCH v7 2/9 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.

With a bit of luck, this should all go splendidly. 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 directio callers to supply _COMP_WORK
* iomap: allow NULL swap info bdev when activating swapfile

---
 include/linux/iomap.h |    3 +++
 fs/iomap/direct-io.c  |    5 +++--
 fs/iomap/swapfile.c   |   17 +++++++++++++++++
 3 files changed, 23 insertions(+), 2 deletions(-)
#19 lore raw

PATCH 1/2 iomap: allow directio callers to supply _COMP_WORK

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

Allow callers of iomap_dio_rw to specify the _COMP_WORK flag if they require that all directio ioend completions occur in process context. The upcoming fuse-iomap patchset needs this because fuse requests (specifically FUSE_IOMAP_IOEND) cannot be sent from interrupt context.

---
 include/linux/iomap.h |    3 +++
 fs/iomap/direct-io.c  |    5 +++--
 2 files changed, 6 insertions(+), 2 deletions(-)
include/linux/iomap.h +3 -0
index 99b7209dabd77c..a47befc23a8a2d 100644
@@ -575,6 +575,9 @@ struct iomap_dio_ops {
  */
 #define IOMAP_DIO_BOUNCE		(1 << 4)
 
+/* Run IO completions from process context */
+#define IOMAP_DIO_COMP_WORK		(1 << 5)
+
 ssize_t iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 		const struct iomap_ops *ops, const struct iomap_dio_ops *dops,
 		unsigned int dio_flags, void *private, size_t done_before);
fs/iomap/direct-io.c +3 -2
index e911daedff65ae..59e6028a37d362 100644
@@ -19,7 +19,6 @@
  * iomap.h:
  */
 #define IOMAP_DIO_NO_INVALIDATE	(1U << 26)
-#define IOMAP_DIO_COMP_WORK	(1U << 27)
 #define IOMAP_DIO_WRITE_THROUGH	(1U << 28)
 #define IOMAP_DIO_NEED_SYNC	(1U << 29)
 #define IOMAP_DIO_WRITE		(1U << 30)
@@ -700,7 +699,9 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 	dio->i_size = i_size_read(inode);
 	dio->dops = dops;
 	dio->error = 0;
-	dio->flags = dio_flags & (IOMAP_DIO_FSBLOCK_ALIGNED | IOMAP_DIO_BOUNCE);
+	dio->flags = dio_flags & (IOMAP_DIO_FSBLOCK_ALIGNED |
+				  IOMAP_DIO_BOUNCE |
+				  IOMAP_DIO_COMP_WORK);
 	dio->done_before = done_before;
 
 	dio->submit.iter = iter;
Reviewed-by on v1 1/2
#20 lore raw

Re: [PATCH 1/2] iomap: allow directio callers to supply _COMP_WORK

Quoted 5 lines · Darrick J. Wong

#define IOMAP_DIO_NO_INVALIDATE (1U << 26)
-#define IOMAP_DIO_COMP_WORK (1U << 27)
#define IOMAP_DIO_WRITE_THROUGH (1U << 28)
#define IOMAP_DIO_NEED_SYNC (1U << 29)
#define IOMAP_DIO_WRITE (1U << 30)

Maybe move up IOMAP_DIO_NO_INVALIDATE to avoid unused bits?

Otherwise this looks good:

#21 lore raw

Re: [PATCH 1/2] iomap: allow directio callers to supply _COMP_WORK

Quoted 7 lines · Christoph Hellwig
Quoted 5 lines · Darrick J. Wong

#define IOMAP_DIO_NO_INVALIDATE (1U << 26)
-#define IOMAP_DIO_COMP_WORK (1U << 27)
#define IOMAP_DIO_WRITE_THROUGH (1U << 28)
#define IOMAP_DIO_NEED_SYNC (1U << 29)
#define IOMAP_DIO_WRITE (1U << 30)

Quoted 5 lines

Maybe move up IOMAP_DIO_NO_INVALIDATE to avoid unused bits?

Otherwise this looks good:

Done, and thanks for the review!

--D

#22 lore raw

PATCH 2/2 iomap: allow NULL swap info bdev when activating swapfile

In reply to 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, a subsequent patch to fuse will add iomap infrastructure so that fuse servers can be asked to provide file mappings specifically for swap files. The fuse server isn't required to set s_bdev (by mounting as fuseblk) so s_bdev might be null. For this case, we want to set sis::bdev from the first mapping.

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.

And just to be clear: fuse-iomap servers will have to respond to an explicit request for swapfile activation. It's not like fuseblk, where responding to bmap means swapfiles work even if that wasn't expected.

---
 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;
#23 lore raw

Re: [PATCH 2/2] iomap: allow NULL swap info bdev when activating swapfile

Quoted 9 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, a subsequent patch to fuse will add iomap infrastructure so that fuse servers can be asked to provide file mappings specifically for swap files.

That sounds pretty sketchy. How do you make sure that is safe vs memory reclaim deadlocks? Does someone really need this feature?

#24 lore raw

Re: [PATCH 2/2] 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 6 lines
Quoted 3 lines

However, a subsequent patch to fuse will add iomap infrastructure so that fuse servers can be asked to provide file mappings specifically for swap files.

That sounds pretty sketchy. How do you make sure that is safe vs memory reclaim deadlocks? Does someone really need this feature?

Err, which part is sketchy, specifically? This patch that adjusts stuff in fs/iomap/, or the (much later) patch to fuse-iomap?

If it's the second part (activating swapfiles via fuse-iomap) then I'll state that fuse-iomap swapfiles work mostly the same way that they do in
xfs: iomap_swapfile_activate calls ->iomap_begin, which calls the fuse server to get iomappings. Each iomap is passed to the mm, which constructs its own internal mapping of swapfile range to disk addresses. The swap code then submits bios to read/write swapfile contents directly, which means that there are no upcalls to the fuse server after the initial activation.

Obviously this means that the fuse server is granting a longterm layout lease to the kernel swapfile code, so it should reply to fuse_iomap_begin with a error code if it doesn't want to do that.

I don't know that anyone really needs this feature, but pre-iomap fuse2fs supports swapfiles, as does any other fuse server that implements bmap.

--D

#25 lore raw

Re: [PATCH 2/2] iomap: allow NULL swap info bdev when activating swapfile

Quoted 5 lines · Darrick J. Wong
Quoted 2 lines

That sounds pretty sketchy. How do you make sure that is safe vs memory reclaim deadlocks? Does someone really need this feature?

Err, which part is sketchy, specifically? This patch that adjusts stuff in fs/iomap/, or the (much later) patch to fuse-iomap?

The concept of swapping to fuse.

Quoted 7 lines

Obviously this means that the fuse server is granting a longterm layout lease to the kernel swapfile code, so it should reply to fuse_iomap_begin with a error code if it doesn't want to do that.

I don't know that anyone really needs this feature, but pre-iomap fuse2fs supports swapfiles, as does any other fuse server that implements bmap.

Eww, I didn't know people were already trying to support swap to fuse.

#26 lore raw

Re: [PATCH 2/2] iomap: allow NULL swap info bdev when activating swapfile

Quoted 13 lines · Christoph Hellwig
Quoted 5 lines · Darrick J. Wong
Quoted 2 lines

That sounds pretty sketchy. How do you make sure that is safe vs memory reclaim deadlocks? Does someone really need this feature?

Err, which part is sketchy, specifically? This patch that adjusts stuff in fs/iomap/, or the (much later) patch to fuse-iomap?

The concept of swapping to fuse.

Quoted 4 lines

Obviously this means that the fuse server is granting a longterm layout lease to the kernel swapfile code, so it should reply to fuse_iomap_begin with a error code if it doesn't want to do that.

Quoted 5 lines
Quoted 3 lines

I don't know that anyone really needs this feature, but pre-iomap fuse2fs supports swapfiles, as does any other fuse server that implements bmap.

Eww, I didn't know people were already trying to support swap to fuse.

It was merged in the kernel via commit b2d2272fae1e1d ("[PATCH] fuse:
add bmap support"), which was 2.6.20. So people have been using it for ~20 years now. At least it's the mm-managed bio swap path and we're not actually upcalling the fuse server to do swapins/swapouts.

--D

#27 lore raw

Re: [PATCH 2/2] iomap: allow NULL swap info bdev when activating swapfile

Quoted 10 lines · Darrick J. Wong
Quoted 5 lines
Quoted 3 lines

I don't know that anyone really needs this feature, but pre-iomap fuse2fs supports swapfiles, as does any other fuse server that implements bmap.

Eww, I didn't know people were already trying to support swap to fuse.

It was merged in the kernel via commit b2d2272fae1e1d ("[PATCH] fuse:
add bmap support"), which was 2.6.20. So people have been using it for ~20 years now. At least it's the mm-managed bio swap path and we're not actually upcalling the fuse server to do swapins/swapouts.

Assuming it actually gets used, but yes, it's been there forever. :(

#28 lore raw

PATCH v7 3/9 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.

With a bit of luck, this should all go splendidly. 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(-)
#29 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 77b581ecf48a16..3373252ccd1678 100644
@@ -103,10 +103,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;
@@ -981,7 +994,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
@@ -1594,10 +1607,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)
@@ -1652,6 +1667,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 ac9d7a7b3f5e68..a3d762fd4d9a86 100644
@@ -2646,7 +2646,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)))
@@ -2663,7 +2663,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 ff8b94cb02e63c..9012f4e8d68338 100644
@@ -1005,7 +1005,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);
@@ -1045,7 +1045,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,
+};
#30 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 adb4d2ebb21379..d7e074c30f46cc 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)
#31 lore raw

PATCH v7 4/9 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.

With a bit of luck, this should all go splendidly. 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: enable SYNCFS and ensure we flush everything before sending DESTROY
* fuse: clean up per-file type inode initialization
* fuse: create a per-inode flag for setting exclusive mode.
* 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: use an unrestricted backing device with iomap pagecache io
* fuse: implement large folios for iomap pagecache files
* 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 fs 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          |   73 +
 fs/fuse/fuse_iomap.h      |  109 ++
 fs/fuse/fuse_iomap_i.h    |   45 +
 fs/fuse/fuse_trace.h      |  974 ++++++++++++++++++
 include/uapi/linux/fuse.h |  235 ++++
 fs/fuse/Kconfig           |   48 +
 fs/fuse/Makefile          |    1 
 fs/fuse/backing.c         |   47 +
 fs/fuse/dev.c             |   42 +
 fs/fuse/dir.c             |  141 ++-
 fs/fuse/file.c            |  122 ++
 fs/fuse/fuse_iomap.c      | 2371 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |  180 +++
 fs/fuse/iomode.c          |    1 
 fs/fuse/trace.c           |    3 
 15 files changed, 4321 insertions(+), 71 deletions(-)
 create mode 100644 fs/fuse/fuse_iomap.h
 create mode 100644 fs/fuse/fuse_iomap_i.h
 create mode 100644 fs/fuse/fuse_iomap.c
#32 lore raw

PATCH 1/33 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          |    5 -
 fs/fuse/fuse_iomap.h      |   26 +++
 fs/fuse/fuse_iomap_i.h    |   28 +++
 include/uapi/linux/fuse.h |   91 +++++++++-
 fs/fuse/Kconfig           |   32 +++
 fs/fuse/Makefile          |    1 
 fs/fuse/fuse_iomap.c      |  430 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    9 +
 8 files changed, 620 insertions(+), 2 deletions(-)
 create mode 100644 fs/fuse/fuse_iomap.h
 create mode 100644 fs/fuse/fuse_iomap_i.h
 create mode 100644 fs/fuse/fuse_iomap.c
fs/fuse/fuse_i.h +4 -1
index 3373252ccd1678..2d62b6365fa931 100644
@@ -938,6 +938,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;
 
@@ -1059,7 +1062,7 @@ 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);
 }
fs/fuse/fuse_iomap.h new file +26 -0
new file mode 100644
index 00000000000000..6c71318365ca82
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025-2026 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#ifndef _FS_FUSE_IOMAP_H
+#define _FS_FUSE_IOMAP_H
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+enum fuse_iomap_iodir {
+	READ_MAPPING,
+	WRITE_MAPPING,
+};
+
+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 /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_H */
fs/fuse/fuse_iomap_i.h new file +28 -0
new file mode 100644
index 00000000000000..2897049637fad2
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2025-2026 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 */
+#endif /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_I_H */
include/uapi/linux/fuse.h +90 -1

125 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..2536bc6a71b898 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) += fuse_iomap.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/fuse_iomap.c new file +430 -0

430 lines not on this page · raw message

fs/fuse/inode.c +9 -0
index 9012f4e8d68338..8f01844f89b261 100644
@@ -9,6 +9,7 @@
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
 #include "dev_uring_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/dax.h>
 #include <linux/pagemap.h>
@@ -1460,6 +1461,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;
@@ -1528,6 +1535,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;
#33 lore raw

PATCH 2/33 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_iomap_i.h |    6 +
 fs/fuse/fuse_trace.h   |  295 ++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c   |   15 ++
 3 files changed, 314 insertions(+), 2 deletions(-)
fs/fuse/fuse_iomap_i.h +6 -0
index 2897049637fad2..b9ab8ce140e8e1 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/fuse_trace.h +295 -0

313 lines not on this page · raw message

fs/fuse/fuse_iomap.c +13 -2
index 8785f86941a1d2..c22c7961cc0bdc 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;
@@ -417,8 +426,10 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 			 */
 			err = 0;
 		}
-		if (err)
+		if (err) {
+			trace_fuse_iomap_end_error(inode, &inarg, err);
 			return err;
+		}
 	}
 
 	return 0;
#34 lore raw

PATCH 3/33 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_iomap_i.h |   17 ++++++++++++++---
 fs/fuse/Kconfig        |   15 +++++++++++++++
 fs/fuse/fuse_iomap.c   |   43 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 72 insertions(+), 3 deletions(-)
fs/fuse/fuse_iomap_i.h +14 -3
index b9ab8ce140e8e1..c37a7c5cfc862f 100644
@@ -8,17 +8,28 @@
 
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
-# define ASSERT(condition) do {						\
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG_BY_DEFAULT)
+DECLARE_STATIC_KEY_TRUE(fuse_iomap_debug);
+#else
+DECLARE_STATIC_KEY_FALSE(fuse_iomap_debug);
+#endif /* FUSE_IOMAP_DEBUG_BY_DEFAULT */
+
+# 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..1b8990f1c2a8f9 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 the debug_iomap
+	  module parameter.
+
 config FUSE_IO_URING
 	bool "FUSE communication over io-uring"
 	default y
fs/fuse/fuse_iomap.c +43 -0

49 lines not on this page · raw message

#35 lore raw

PATCH 4/33 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          |    7 +++
 fs/fuse/fuse_iomap.h      |    2 +
 include/uapi/linux/fuse.h |    3 +
 fs/fuse/Kconfig           |    1 
 fs/fuse/backing.c         |   47 +++++++++++++++++
 fs/fuse/fuse_iomap.c      |  126 +++++++++++++++++++++++++++++++++++++++++----
 fs/fuse/trace.c           |    1 
 7 files changed, 174 insertions(+), 13 deletions(-)
fs/fuse/fuse_i.h +7 -0
index 2d62b6365fa931..0321be384b769e 100644
@@ -104,12 +104,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;
@@ -119,6 +121,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 */
@@ -1616,6 +1619,10 @@ void fuse_backing_put(struct fuse_backing *fb);
 struct fuse_backing *fuse_backing_lookup(struct fuse_conn *fc,
 					 const struct fuse_backing_ops *ops,
 					 int backing_id);
+typedef bool (*fuse_match_backing_fn)(const struct fuse_backing *fb,
+				      const void *data);
+int fuse_backing_lookup_id(struct fuse_conn *fc, fuse_match_backing_fn match_fn,
+			   const void *data);
 #else
 
 static inline struct fuse_backing *fuse_backing_get(struct fuse_backing *fb)
fs/fuse/fuse_iomap.h +2 -0
index 6c71318365ca82..43562ef23fb325 100644
@@ -18,6 +18,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 5a58011f66f501..5ae6b05de623d7 100644
@@ -1137,7 +1137,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 1b8990f1c2a8f9..3e35611c3aac07 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 +47 -0

70 lines not on this page · raw message

fs/fuse/fuse_iomap.c +114 -12

194 lines not on this page · raw message

fs/fuse/trace.c +1 -0
index 93bd72efc98cd0..c830c1c38a833c 100644
@@ -6,6 +6,7 @@
 #include "dev_uring_i.h"
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
+#include "fuse_iomap_i.h"
 
 #include <linux/pagemap.h>
 
#36 lore raw

PATCH 5/33 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 */
#37 lore raw

PATCH 6/33 fuse: enable SYNCFS and ensure we flush everything before sending DESTROY

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 a fuse iomap server to do. 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. This is essential for fstests QA to work properly.

To make this happen, first, we need to flush queued events to userspace to give the fuse server a chance to process the events. These will all be FUSE_RELEASE events for previously opened files. Once the commands are flushed, we can send the FUSE_DESTROY request to ask the server to close the filesystem. This depends on libfuse to hold the destroy command until there are no unreleased files (instead of having the kernel enforce the ordering) because the kernel fuse developers don't like the idea of unbounded waits in unmount.

Second, to reduce the amount of metadata must be persisted to disk in the fuse server's destroy method, enable FUSE_SYNCFS so that previous sync_filesystem calls can flush dirty data before we get deeper in the unmount machinery. If a fuse command timeout is set, this reduces the likelihood that the kernel aborts the FUSE_DESTROY command whilst the server is busy flushing dirty metadata.

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     |    3 +++
 fs/fuse/fuse_iomap.h |    5 +++++
 fs/fuse/fuse_iomap.c |   32 ++++++++++++++++++++++++++++++++
 fs/fuse/inode.c      |    9 +++++++--
 4 files changed, 47 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +3 -0
index 0321be384b769e..6860913a89e65d 100644
@@ -1431,6 +1431,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);
 
fs/fuse/fuse_iomap.h +5 -0
index 43562ef23fb325..129680b056ebea 100644
@@ -20,9 +20,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 /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
fs/fuse/fuse_iomap.c +32 -0
index 0ac783dd312dc3..4b63bb32167877 100644
@@ -584,3 +584,35 @@ 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 file release commands 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.
+	 * iomap fuse servers are expected to release all exclusive access
+	 * resources before unmount completes.
+	 *
+	 * Note that multithreaded fuse servers will have to hold the destroy
+	 * command until all release requests have completed because the kernel
+	 * maintainers do not want to introduce waits in unmount.
+	 */
+	fuse_flush_requests(fc);
+	fuse_send_destroy(fm);
+}
fs/fuse/inode.c +7 -2
index 8f01844f89b261..778fdec9d81a03 100644
@@ -633,7 +633,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);
@@ -1475,6 +1475,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;
@@ -2099,7 +2102,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
#38 lore raw

PATCH 7/33 fuse: clean up per-file type inode initialization

In reply to Darrick J. Wong

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

Clean up the per-filetype inode initialization in fuse_init_inode before we start adding more functionality here. Primarily this consists of refactoring to use a switch statement and passing the file attr struct around.

---
 fs/fuse/fuse_i.h |    2 +-
 fs/fuse/file.c   |    5 +++--
 fs/fuse/inode.c  |   36 +++++++++++++++++++++++++-----------
 3 files changed, 29 insertions(+), 14 deletions(-)
fs/fuse/fuse_i.h +1 -1
index 6860913a89e65d..c6d39290a7a9cf 100644
@@ -1230,7 +1230,7 @@ int fuse_notify_poll_wakeup(struct fuse_conn *fc,
 /**
  * Initialize file operations on a regular file
  */
-void fuse_init_file_inode(struct inode *inode, unsigned int flags);
+void fuse_init_file_inode(struct inode *inode, struct fuse_attr *attr);
 
 /**
  * Initialize inode operations on regular files and special files
fs/fuse/file.c +3 -2
index b1bb7153cb785f..21a6f2cd7bfaa9 100644
@@ -3194,11 +3194,12 @@ static const struct address_space_operations fuse_file_aops  = {
 	.direct_IO	= fuse_direct_IO,
 };
 
-void fuse_init_file_inode(struct inode *inode, unsigned int flags)
+void fuse_init_file_inode(struct inode *inode, struct fuse_attr *attr)
 {
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	struct fuse_conn *fc = get_fuse_conn(inode);
 
+	fuse_init_common(inode);
 	inode->i_fop = &fuse_file_operations;
 	inode->i_data.a_ops = &fuse_file_aops;
 	if (fc->writeback_cache) {
@@ -3214,5 +3215,5 @@ void fuse_init_file_inode(struct inode *inode, unsigned int flags)
 	init_waitqueue_head(&fi->direct_io_waitq);
 
 	if (IS_ENABLED(CONFIG_FUSE_DAX))
-		fuse_dax_inode_init(inode, flags);
+		fuse_dax_inode_init(inode, attr->flags);
 }
fs/fuse/inode.c +25 -11
index 778fdec9d81a03..40450a3d32e7cb 100644
@@ -422,6 +422,12 @@ static void fuse_init_submount_lookup(struct fuse_submount_lookup *sl,
 	refcount_set(&sl->count, 1);
 }
 
+static void fuse_init_special(struct inode *inode, struct fuse_attr *attr)
+{
+	fuse_init_common(inode);
+	init_special_inode(inode, inode->i_mode, new_decode_dev(attr->rdev));
+}
+
 static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
 			    struct fuse_conn *fc)
 {
@@ -429,20 +435,28 @@ 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)) {
-		fuse_init_common(inode);
-		fuse_init_file_inode(inode, attr->flags);
-	} else if (S_ISDIR(inode->i_mode))
+
+	switch (inode->i_mode & S_IFMT) {
+	case S_IFREG:
+		fuse_init_file_inode(inode, attr);
+		break;
+	case S_IFDIR:
 		fuse_init_dir(inode);
-	else if (S_ISLNK(inode->i_mode))
+		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_init_common(inode);
-		init_special_inode(inode, inode->i_mode,
-				   new_decode_dev(attr->rdev));
-	} else
+		break;
+	case S_IFCHR:
+	case S_IFBLK:
+	case S_IFIFO:
+	case S_IFSOCK:
+		fuse_init_special(inode, attr);
+		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.
#39 lore raw

PATCH 8/33 fuse: create a per-inode flag for setting exclusive mode.

In reply to Darrick J. Wong

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

Create a per-inode flag to control whether or not this inode can use exclusive mode. This enables more aggressive use of cached file attributes for things such as ACL inheritance and transformations.

The initial user will be iomap filesystems, where we hoist the IO path into the kernel and need ACLs to work for regular files and directories in the manner that most local filesystems expect.

---
 fs/fuse/fuse_i.h          |   17 +++++++++++++++++
 include/uapi/linux/fuse.h |    4 ++++
 fs/fuse/inode.c           |    5 +++++
 3 files changed, 26 insertions(+)
fs/fuse/fuse_i.h +17 -0
index c6d39290a7a9cf..46c2c660a39484 100644
@@ -1117,6 +1117,23 @@ static inline bool fuse_is_bad(struct inode *inode)
 	return unlikely(test_bit(FUSE_I_BAD, &get_fuse_inode(inode)->state));
 }
 
+static inline void fuse_inode_set_exclusive(const struct fuse_conn *fc,
+					    struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+
+	/* This flag wasn't added until kernel API 7.99 */
+	if (fc->minor >= 99)
+		set_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
+
+static inline void fuse_inode_clear_exclusive(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+
+	clear_bit(FUSE_I_EXCLUSIVE, &fi->state);
+}
+
 static inline bool fuse_inode_is_exclusive(const struct inode *inode)
 {
 	const struct fuse_inode *fi = get_fuse_inode(inode);
include/uapi/linux/fuse.h +4 -0
index 5ae6b05de623d7..2d35dcfbf8aaf5 100644
@@ -244,6 +244,7 @@
  *  7.99
  *  - XXX magic minor revision to make experimental code really obvious
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
+ *  - add FUSE_ATTR_EXCLUSIVE to enable exclusive mode for specific inodes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -584,9 +585,12 @@ 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_EXCLUSIVE: This file can only be modified by this mount, so the
+ * kernel can use cached attributes more aggressively (e.g. ACL inheritance)
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX		(1 << 1)
+#define FUSE_ATTR_EXCLUSIVE	(1 << 2)
 
 /**
  * Open flags
fs/fuse/inode.c +5 -0
index 40450a3d32e7cb..e45b53bfce4b2d 100644
@@ -197,6 +197,8 @@ static void fuse_evict_inode(struct inode *inode)
 		WARN_ON(!list_empty(&fi->write_files));
 		WARN_ON(!list_empty(&fi->queued_writes));
 	}
+
+	fuse_inode_clear_exclusive(inode);
 }
 
 static int fuse_reconfigure(struct fs_context *fsc)
@@ -436,6 +438,9 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
 	inode_set_mtime(inode, attr->mtime, attr->mtimensec);
 	inode_set_ctime(inode, attr->ctime, attr->ctimensec);
 
+	if (attr->flags & FUSE_ATTR_EXCLUSIVE)
+		fuse_inode_set_exclusive(fc, inode);
+
 	switch (inode->i_mode & S_IFMT) {
 	case S_IFREG:
 		fuse_init_file_inode(inode, attr);
#40 lore raw

PATCH 9/33 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.

Note that more code will be added to fuse_iomap_init_inode in subsequent patches.

---
 fs/fuse/fuse_i.h          |    6 ++++--
 fs/fuse/fuse_iomap.h      |   13 ++++++++++++
 include/uapi/linux/fuse.h |    3 +++
 fs/fuse/dir.c             |   14 +++++++++++--
 fs/fuse/file.c            |    3 +++
 fs/fuse/fuse_iomap.c      |   47 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    6 ++++--
 7 files changed, 86 insertions(+), 6 deletions(-)
fs/fuse/fuse_i.h +4 -2
index 46c2c660a39484..011b252a437855 100644
@@ -264,6 +264,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;
@@ -1257,12 +1259,12 @@ void fuse_init_common(struct inode *inode);
 /**
  * Initialize inode and file operations on a directory
  */
-void fuse_init_dir(struct inode *inode);
+void fuse_init_dir(struct inode *inode, struct fuse_attr *attr);
 
 /**
  * Initialize inode operations on a symlink
  */
-void fuse_init_symlink(struct inode *inode);
+void fuse_init_symlink(struct inode *inode, struct fuse_attr *attr);
 
 /**
  * Change attributes of an inode
fs/fuse/fuse_iomap.h +13 -0
index 129680b056ebea..34f2c75416eb62 100644
@@ -23,11 +23,24 @@ 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_inode(struct inode *inode, struct fuse_attr *attr);
+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_inode(...)		((void)0)
+# define fuse_iomap_evict_inode(...)		((void)0)
+# define fuse_inode_has_iomap(...)		(false)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +3 -0
index 2d35dcfbf8aaf5..88f76f4be749a7 100644
@@ -245,6 +245,7 @@
  *  - XXX magic minor revision to make experimental code really obvious
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  *  - add FUSE_ATTR_EXCLUSIVE to enable exclusive mode for specific inodes
+ *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -587,10 +588,12 @@ struct fuse_file_lock {
  * FUSE_ATTR_DAX: Enable DAX for this file in per inode DAX mode
  * FUSE_ATTR_EXCLUSIVE: This file can only be modified by this mount, so the
  * kernel can use cached attributes more aggressively (e.g. ACL inheritance)
+ * FUSE_ATTR_IOMAP: Use iomap for this inode
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX		(1 << 1)
 #define FUSE_ATTR_EXCLUSIVE	(1 << 2)
+#define FUSE_ATTR_IOMAP		(1 << 3)
 
 /**
  * Open flags
fs/fuse/dir.c +12 -2
index 9abec6f072ac73..10db4dc046930f 100644
@@ -7,6 +7,7 @@
 */
 
 #include "fuse_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/pagemap.h>
 #include <linux/file.h>
@@ -2510,9 +2511,10 @@ void fuse_init_common(struct inode *inode)
 	inode->i_op = &fuse_common_inode_operations;
 }
 
-void fuse_init_dir(struct inode *inode)
+void fuse_init_dir(struct inode *inode, struct fuse_attr *attr)
 {
 	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_conn *fc = get_fuse_conn(inode);
 
 	inode->i_op = &fuse_dir_inode_operations;
 	inode->i_fop = &fuse_dir_operations;
@@ -2522,6 +2524,9 @@ void fuse_init_dir(struct inode *inode)
 	fi->rdc.size = 0;
 	fi->rdc.pos = 0;
 	fi->rdc.version = 0;
+
+	if (fc->iomap)
+		fuse_iomap_init_inode(inode, attr);
 }
 
 static int fuse_symlink_read_folio(struct file *null, struct folio *folio)
@@ -2540,9 +2545,14 @@ static const struct address_space_operations fuse_symlink_aops = {
 	.read_folio	= fuse_symlink_read_folio,
 };
 
-void fuse_init_symlink(struct inode *inode)
+void fuse_init_symlink(struct inode *inode, struct fuse_attr *attr)
 {
+	struct fuse_conn *fc = get_fuse_conn(inode);
+
 	inode->i_op = &fuse_symlink_inode_operations;
 	inode->i_data.a_ops = &fuse_symlink_aops;
 	inode_nohighmem(inode);
+
+	if (fc->iomap)
+		fuse_iomap_init_inode(inode, attr);
 }
fs/fuse/file.c +3 -0
index 21a6f2cd7bfaa9..4a7b0c190aa8e4 100644
@@ -7,6 +7,7 @@
 */
 
 #include "fuse_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/pagemap.h>
 #include <linux/slab.h>
@@ -3214,6 +3215,8 @@ void fuse_init_file_inode(struct inode *inode, struct fuse_attr *attr)
 	init_waitqueue_head(&fi->page_waitq);
 	init_waitqueue_head(&fi->direct_io_waitq);
 
+	if (fc->iomap)
+		fuse_iomap_init_inode(inode, attr);
 	if (IS_ENABLED(CONFIG_FUSE_DAX))
 		fuse_dax_inode_init(inode, attr->flags);
 }
fs/fuse/fuse_iomap.c +47 -0

50 lines not on this page · raw message

fs/fuse/inode.c +4 -2
index e45b53bfce4b2d..27699a6c11f66b 100644
@@ -198,6 +198,8 @@ static void fuse_evict_inode(struct inode *inode)
 		WARN_ON(!list_empty(&fi->queued_writes));
 	}
 
+	if (fuse_inode_has_iomap(inode))
+		fuse_iomap_evict_inode(inode);
 	fuse_inode_clear_exclusive(inode);
 }
 
@@ -446,10 +448,10 @@ static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
 		fuse_init_file_inode(inode, attr);
 		break;
 	case S_IFDIR:
-		fuse_init_dir(inode);
+		fuse_init_dir(inode, attr);
 		break;
 	case S_IFLNK:
-		fuse_init_symlink(inode);
+		fuse_init_symlink(inode, attr);
 		break;
 	case S_IFCHR:
 	case S_IFBLK:
#41 lore raw

PATCH 10/33 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/fuse_iomap.c |    8 +++++++-
 2 files changed, 51 insertions(+), 1 deletion(-)
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/fuse_iomap.c +7 -1
index 39c9239c64435a..dccfc9a2c9847c 100644
@@ -651,15 +651,21 @@ void fuse_iomap_init_inode(struct inode *inode, struct fuse_attr *attr)
 		return;
 	}
 
-	if (!S_ISREG(inode->i_mode))
+	if (!S_ISREG(inode->i_mode)) {
+		trace_fuse_iomap_init_inode(inode);
 		return;
+	}
 
 	fuse_inode_set_iomap(inode);
+
+	trace_fuse_iomap_init_inode(inode);
 }
 
 void fuse_iomap_evict_inode(struct inode *inode)
 {
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_evict_inode(inode);
+
 	fuse_inode_clear_iomap(inode);
 }
#42 lore raw

PATCH 11/33 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 |    3 ++-
 4 files changed, 26 insertions(+), 12 deletions(-)
fs/fuse/dir.c +9 -5
index 10db4dc046930f..138f8abbe42b4c 100644
@@ -2196,6 +2196,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;
@@ -2253,12 +2254,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;
@@ -2330,7 +2334,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);
 	}
@@ -2354,7 +2358,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 4a7b0c190aa8e4..c73536e29f1c96 100644
@@ -251,6 +251,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);
@@ -272,7 +273,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);
@@ -285,7 +286,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)
@@ -533,12 +534,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
@@ -549,7 +552,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
@@ -573,7 +577,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;
 }
@@ -2010,6 +2015,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 27699a6c11f66b..fae33371c33da6 100644
@@ -192,7 +192,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 +2 -1
index 3728933188f307..9be9ae3520003e 100644
@@ -6,6 +6,7 @@
  */
 
 #include "fuse_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/kernel.h>
 #include <linux/sched.h>
@@ -203,7 +204,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;
 
 	/*
#43 lore raw

PATCH 12/33 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_iomap.h |    8 ++++++
 fs/fuse/dir.c        |    1 +
 fs/fuse/file.c       |   13 ++++++++++
 fs/fuse/fuse_iomap.c |   68 +++++++++++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 89 insertions(+), 1 deletion(-)
fs/fuse/fuse_iomap.h +8 -0
index 34f2c75416eb62..8ba30a496545f5 100644
@@ -33,6 +33,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)
@@ -41,6 +46,9 @@ static inline bool fuse_inode_has_iomap(const struct inode *inode)
 # define fuse_iomap_init_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 /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
fs/fuse/dir.c +1 -0
index 138f8abbe42b4c..e16facbde126ef 100644
@@ -2501,6 +2501,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 c73536e29f1c96..e81571aaef15fe 100644
@@ -2588,6 +2588,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;
 
@@ -2623,6 +2629,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 != -ENOSYS)
+			return alt_pos;
+	}
+
 	if (fm->fc->no_lseek)
 		goto fallback;
 
fs/fuse/fuse_iomap.c +67 -1

83 lines not on this page · raw message

#44 lore raw

PATCH 13/33 fuse_trace: implement basic iomap reporting such as FIEMAP and SEEK_{DATA,HOLE}

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   46 ++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    4 ++++
 2 files changed, 50 insertions(+)
fs/fuse/fuse_trace.h +46 -0
index fac981e2a30df0..730ab8bce44450 100644
@@ -532,6 +532,52 @@ DEFINE_EVENT(fuse_inode_state_class, name,	\
 	TP_ARGS(inode))
 DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_init_inode);
 DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_evict_inode);
+
+TRACE_EVENT(fuse_iomap_fiemap,
+	TP_PROTO(const struct inode *inode, u64 start, u64 count,
+		unsigned int flags),
+
+	TP_ARGS(inode, start, count, flags),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(unsigned int,		flags)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	start;
+		__entry->length		=	count;
+		__entry->flags		=	flags;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT("fiemap") " flags 0x%x",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __entry->flags)
+);
+
+TRACE_EVENT(fuse_iomap_lseek,
+	TP_PROTO(const struct inode *inode, loff_t offset, int whence),
+
+	TP_ARGS(inode, offset, whence),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(loff_t,			offset)
+		__field(int,			whence)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	offset;
+		__entry->whence		=	whence;
+	),
+
+	TP_printk(FUSE_INODE_FMT " offset 0x%llx whence %d",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->offset,
+		  __entry->whence)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +4 -0
index 32ddf2fa6bdf78..be922888ae9e8a 100644
@@ -693,6 +693,8 @@ int fuse_iomap_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
 	if (!fuse_allow_current_process(fc))
 		return -EACCES;
 
+	trace_fuse_iomap_fiemap(inode, start, count, fieinfo->fi_flags);
+
 	inode_lock_shared(inode);
 	error = iomap_fiemap(inode, fieinfo, start, count, &fuse_iomap_ops);
 	inode_unlock_shared(inode);
@@ -720,6 +722,8 @@ loff_t fuse_iomap_lseek(struct file *file, loff_t offset, int whence)
 	if (!fuse_allow_current_process(fc))
 		return -EACCES;
 
+	trace_fuse_iomap_lseek(inode, offset, whence);
+
 	switch (whence) {
 	case SEEK_HOLE:
 		offset = iomap_seek_hole(inode, offset, &fuse_iomap_ops);
#45 lore raw

PATCH 14/33 fuse: implement direct IO with iomap

In reply to Darrick J. Wong

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

Start implementing the fuse-iomap file I/O paths by adding direct I/O support and all the signalling flags that come with it. Buffered I/O is much more complicated, so we leave that to a subsequent patch.

---
 fs/fuse/fuse_i.h          |   20 +++
 fs/fuse/fuse_iomap.h      |   18 ++
 include/uapi/linux/fuse.h |   27 ++++
 fs/fuse/dir.c             |   13 ++
 fs/fuse/file.c            |   29 ++++
 fs/fuse/fuse_iomap.c      |  334 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |    3 
 fs/fuse/iomode.c          |    2 
 8 files changed, 440 insertions(+), 6 deletions(-)
fs/fuse/fuse_i.h +20 -0
index 011b252a437855..d1724bf8e87b93 100644
@@ -188,6 +188,11 @@ struct fuse_inode {
 
 			/* waitq for direct-io completion */
 			wait_queue_head_t direct_io_waitq;
+
+#ifdef CONFIG_FUSE_IOMAP
+			/* file size as reported by fuse server */
+			loff_t i_disk_size;
+#endif
 		};
 
 		/* readdir cache (directory only) */
@@ -656,6 +661,16 @@ struct fuse_sync_bucket {
 	struct rcu_head rcu;
 };
 
+#ifdef CONFIG_FUSE_IOMAP
+struct fuse_iomap_conn {
+	/* fuse server doesn't implement iomap_end */
+	unsigned int no_end:1;
+
+	/* fuse server doesn't implement iomap_ioend */
+	unsigned int no_ioend:1;
+};
+#endif
+
 /**
  * A Fuse connection.
  *
@@ -1007,6 +1022,11 @@ struct fuse_conn {
 	struct idr backing_files_map;
 #endif
 
+#ifdef CONFIG_FUSE_IOMAP
+	/** iomap information */
+	struct fuse_iomap_conn iomap_conn;
+#endif
+
 #ifdef CONFIG_FUSE_IO_URING
 	/**  uring connection information*/
 	struct fuse_ring *ring;
fs/fuse/fuse_iomap.h +18 -0
index 8ba30a496545f5..476e1b869d1906 100644
@@ -38,6 +38,17 @@ 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);
+
+void fuse_iomap_open(struct inode *inode, struct file *file);
+int fuse_iomap_finish_open(const struct fuse_file *ff,
+			   const struct inode *inode);
+void fuse_iomap_open_truncate(struct inode *inode);
+
+void fuse_iomap_set_disk_size(struct fuse_inode *fi, loff_t newsize);
+int fuse_iomap_setsize_finish(struct inode *inode, loff_t newsize);
+
+ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to);
+ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -49,6 +60,13 @@ sector_t fuse_iomap_bmap(struct address_space *mapping, sector_t block);
 # define fuse_iomap_fiemap			NULL
 # define fuse_iomap_lseek(...)			(-ENOSYS)
 # define fuse_iomap_bmap(...)			(-ENOSYS)
+# define fuse_iomap_open(...)			((void)0)
+# define fuse_iomap_finish_open(...)		(-ENOSYS)
+# define fuse_iomap_open_truncate(...)		((void)0)
+# define fuse_iomap_set_disk_size(...)		((void)0)
+# define fuse_iomap_setsize_finish(...)		(-ENOSYS)
+# define fuse_iomap_read_iter(...)		(-ENOSYS)
+# define fuse_iomap_write_iter(...)		(-ENOSYS)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +27 -0
index 88f76f4be749a7..543965b2f8fb37 100644
@@ -677,6 +677,7 @@ enum fuse_opcode {
 	FUSE_STATX		= 52,
 	FUSE_COPY_FILE_RANGE_64	= 53,
 
+	FUSE_IOMAP_IOEND	= 4093,
 	FUSE_IOMAP_BEGIN	= 4094,
 	FUSE_IOMAP_END		= 4095,
 
@@ -1411,4 +1412,30 @@ struct fuse_iomap_end_in {
 	struct fuse_iomap_io	map;
 };
 
+/* out of place write extent */
+#define FUSE_IOMAP_IOEND_SHARED		(1U << 0)
+/* unwritten extent */
+#define FUSE_IOMAP_IOEND_UNWRITTEN	(1U << 1)
+/* don't merge into previous ioend */
+#define FUSE_IOMAP_IOEND_BOUNDARY	(1U << 2)
+/* is direct I/O */
+#define FUSE_IOMAP_IOEND_DIRECT		(1U << 3)
+/* is append ioend */
+#define FUSE_IOMAP_IOEND_APPEND		(1U << 4)
+
+struct fuse_iomap_ioend_in {
+	uint32_t flags;		/* FUSE_IOMAP_IOEND_* */
+	int32_t error;		/* negative errno or 0 */
+	uint64_t attr_ino;	/* matches fuse_attr:ino */
+	uint64_t pos;		/* file position, in bytes */
+	uint64_t new_addr;	/* disk offset of new mapping, in bytes */
+	uint64_t written;	/* bytes processed */
+	uint32_t dev;		/* device cookie */
+	uint32_t pad;		/* zero */
+};
+
+struct fuse_iomap_ioend_out {
+	uint64_t newsize;	/* new ondisk size */
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/dir.c +13 -0
index e16facbde126ef..dcf5ccbc57c7be 100644
@@ -907,6 +907,10 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 		goto out_acl_release;
 
 	fuse_dir_changed(dir);
+
+	if (fuse_inode_has_iomap(inode))
+		fuse_iomap_open(inode, file);
+
 	err = generic_file_open(inode, file);
 	if (!err) {
 		file->private_data = ff;
@@ -1948,6 +1952,9 @@ static int fuse_dir_open(struct inode *inode, struct file *file)
 	if (fuse_is_bad(inode))
 		return -EIO;
 
+	if (fuse_inode_has_iomap(inode))
+		fuse_iomap_open(inode, file);
+
 	err = generic_file_open(inode, file);
 	if (err)
 		return err;
@@ -2308,6 +2315,12 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		goto error;
 	}
 
+	if (is_iomap && is_truncate) {
+		err = fuse_iomap_setsize_finish(inode, outarg.attr.size);
+		if (err)
+			goto error;
+	}
+
 	spin_lock(&fi->lock);
 	/* the kernel maintains i_mtime locally */
 	if (trust_local_cmtime) {
fs/fuse/file.c +26 -3
index e81571aaef15fe..ae320026f0648f 100644
@@ -216,7 +216,10 @@ int fuse_finish_open(struct inode *inode, struct file *file)
 	struct fuse_conn *fc = get_fuse_conn(inode);
 	int err;
 
-	err = fuse_file_io_open(file, inode);
+	if (fuse_inode_has_iomap(inode))
+		err = fuse_iomap_finish_open(ff, inode);
+	else
+		err = fuse_file_io_open(file, inode);
 	if (err)
 		return err;
 
@@ -259,6 +262,9 @@ static int fuse_open(struct inode *inode, struct file *file)
 	if (fuse_is_bad(inode))
 		return -EIO;
 
+	if (is_iomap)
+		fuse_iomap_open(inode, file);
+
 	err = generic_file_open(inode, file);
 	if (err)
 		return err;
@@ -289,9 +295,11 @@ static int fuse_open(struct inode *inode, struct file *file)
 	if ((is_wb_truncate || dax_truncate) && !is_iomap)
 		fuse_release_nowrite(inode);
 	if (!err) {
-		if (is_truncate)
+		if (is_truncate) {
 			truncate_pagecache(inode, 0);
-		else if (!(ff->open_flags & FOPEN_KEEP_CACHE))
+			if (is_iomap)
+				fuse_iomap_open_truncate(inode);
+		} else if (!(ff->open_flags & FOPEN_KEEP_CACHE))
 			invalidate_inode_pages2(inode->i_mapping);
 	}
 	if (dax_truncate)
@@ -1822,6 +1830,9 @@ static ssize_t fuse_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
 	if (fuse_is_bad(inode))
 		return -EIO;
 
+	if (fuse_inode_has_iomap(inode))
+		return fuse_iomap_read_iter(iocb, to);
+
 	if (FUSE_IS_DAX(inode))
 		return fuse_dax_read_iter(iocb, to);
 
@@ -1843,6 +1854,9 @@ static ssize_t fuse_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
 	if (fuse_is_bad(inode))
 		return -EIO;
 
+	if (fuse_inode_has_iomap(inode))
+		return fuse_iomap_write_iter(iocb, from);
+
 	if (FUSE_IS_DAX(inode))
 		return fuse_dax_write_iter(iocb, from);
 
@@ -2955,7 +2969,9 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 		.length = length,
 		.mode = mode
 	};
+	loff_t newsize = 0;
 	int err;
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	bool block_faults = FUSE_IS_DAX(inode) &&
 		(!(mode & FALLOC_FL_KEEP_SIZE) ||
 		 (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE)));
@@ -2988,6 +3004,7 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 		err = inode_newsize_ok(inode, offset + length);
 		if (err)
 			goto out;
+		newsize = offset + length;
 	}
 
 	err = file_modified(file);
@@ -3012,6 +3029,12 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 
 	/* we could have extended the file */
 	if (!(mode & FALLOC_FL_KEEP_SIZE)) {
+		if (is_iomap && newsize > 0) {
+			err = fuse_iomap_setsize_finish(inode, newsize);
+			if (err)
+				goto out;
+		}
+
 		if (fuse_write_update_attr(inode, offset + length, length))
 			file_update_time(file);
 	}
fs/fuse/fuse_iomap.c +332 -2

364 lines not on this page · raw message

fs/fuse/inode.c +3 -0
index fae33371c33da6..039a780749da30 100644
@@ -303,6 +303,8 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
 	else
 		fi->cached_i_blkbits = inode->i_sb->s_blocksize_bits;
 
+	fuse_iomap_set_disk_size(fi, attr->size);
+
 	/*
 	 * Don't set the sticky bit in i_mode, unless we want the VFS
 	 * to check permissions.  This prevents failures due to the
@@ -352,6 +354,7 @@ static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr
 	 * inode.
 	 */
 	cache_mask = fuse_get_cache_mask(inode);
+	fuse_iomap_set_disk_size(fi, attr->size);
 	if (cache_mask & STATX_SIZE)
 		attr->size = i_size_read(inode);
 
fs/fuse/iomode.c +1 -1
index 9be9ae3520003e..ed666b39cf8af4 100644
@@ -204,7 +204,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_inode_has_iomap(inode) || FUSE_IS_DAX(inode) || !ff->args)
+	if (FUSE_IS_DAX(inode) || !ff->args)
 		return 0;
 
 	/*
#46 lore raw

PATCH 15/33 fuse_trace: implement direct IO with iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_iomap.h |    5 +
 fs/fuse/fuse_trace.h |  212 +++++++++++++++++++++++++++++++++++++++++++++++++-
 fs/fuse/fuse_iomap.c |   18 ++++
 fs/fuse/trace.c      |    2 
 4 files changed, 233 insertions(+), 4 deletions(-)
fs/fuse/fuse_iomap.h +5 -0
index 476e1b869d1906..07433c33535b2d 100644
@@ -45,6 +45,10 @@ int fuse_iomap_finish_open(const struct fuse_file *ff,
 void fuse_iomap_open_truncate(struct inode *inode);
 
 void fuse_iomap_set_disk_size(struct fuse_inode *fi, loff_t newsize);
+static inline loff_t fuse_iomap_get_disk_size(const struct fuse_inode *fi)
+{
+	return fuse_inode_has_iomap(&fi->inode) ? fi->i_disk_size : 0;
+}
 int fuse_iomap_setsize_finish(struct inode *inode, loff_t newsize);
 
 ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to);
@@ -64,6 +68,7 @@ ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
 # define fuse_iomap_finish_open(...)		(-ENOSYS)
 # define fuse_iomap_open_truncate(...)		((void)0)
 # define fuse_iomap_set_disk_size(...)		((void)0)
+# define fuse_iomap_get_disk_size(...)		((loff_t)0)
 # define fuse_iomap_setsize_finish(...)		(-ENOSYS)
 # define fuse_iomap_read_iter(...)		(-ENOSYS)
 # define fuse_iomap_write_iter(...)		(-ENOSYS)
fs/fuse/fuse_trace.h +208 -4

255 lines not on this page · raw message

fs/fuse/fuse_iomap.c +18 -0
index 4816e26a1ac76b..f0b5ea49b6e2ac 100644
@@ -579,6 +579,8 @@ fuse_iomap_setsize_finish(
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_setsize_finish(inode, newsize, 0);
+
 	fi->i_disk_size = newsize;
 	return 0;
 }
@@ -614,6 +616,8 @@ static int fuse_iomap_ioend(struct inode *inode, loff_t pos, size_t written,
 	if (fuse_ioend_is_append(fi, pos, written))
 		inarg.flags |= FUSE_IOMAP_IOEND_APPEND;
 
+	trace_fuse_iomap_ioend(inode, &inarg);
+
 	if (fuse_should_send_iomap_ioend(fm, &inarg)) {
 		FUSE_ARGS(args);
 		int iomap_error;
@@ -639,6 +643,9 @@ static int fuse_iomap_ioend(struct inode *inode, loff_t pos, size_t written,
 		case 0:
 			break;
 		default:
+			trace_fuse_iomap_ioend_error(inode, &inarg, &outarg,
+						     iomap_error);
+
 			/*
 			 * If the write IO failed, return the failure code to
 			 * the caller no matter what happens with the ioend.
@@ -928,6 +935,8 @@ static ssize_t fuse_iomap_direct_read(struct kiocb *iocb, struct iov_iter *to)
 	struct inode *inode = file_inode(iocb->ki_filp);
 	ssize_t ret;
 
+	trace_fuse_iomap_direct_read(iocb, to);
+
 	if (!iov_iter_count(to))
 		return 0; /* skip atime */
 
@@ -939,6 +948,7 @@ static ssize_t fuse_iomap_direct_read(struct kiocb *iocb, struct iov_iter *to)
 		file_accessed(iocb->ki_filp);
 	inode_unlock_shared(inode);
 
+	trace_fuse_iomap_direct_read_end(iocb, to, ret);
 	return ret;
 }
 
@@ -953,6 +963,9 @@ static int fuse_iomap_dio_write_end_io(struct kiocb *iocb, ssize_t written,
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_dio_write_end_io(inode, iocb->ki_pos, written, error,
+					  dioflags);
+
 	if (dioflags & IOMAP_DIO_COW)
 		ioendflags |= FUSE_IOMAP_IOEND_SHARED;
 	if (dioflags & IOMAP_DIO_UNWRITTEN)
@@ -989,6 +1002,8 @@ static ssize_t fuse_iomap_direct_write(struct kiocb *iocb,
 	unsigned int flags = IOMAP_DIO_COMP_WORK;
 	ssize_t ret;
 
+	trace_fuse_iomap_direct_write(iocb, from);
+
 	if (!count)
 		return 0;
 
@@ -1023,6 +1038,7 @@ static ssize_t fuse_iomap_direct_write(struct kiocb *iocb,
 out_unlock:
 	inode_unlock(inode);
 out_dsync:
+	trace_fuse_iomap_direct_write_end(iocb, from, ret);
 	return ret;
 }
 
@@ -1038,6 +1054,8 @@ void fuse_iomap_open_truncate(struct inode *inode)
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_open_truncate(inode);
+
 	fi->i_disk_size = 0;
 }
 
fs/fuse/trace.c +2 -0
index c830c1c38a833c..71d444ac1e5021 100644
@@ -6,9 +6,11 @@
 #include "dev_uring_i.h"
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
+#include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
 
 #include <linux/pagemap.h>
+#include <linux/iomap.h>
 
 #define CREATE_TRACE_POINTS
 #include "fuse_trace.h"
#47 lore raw

PATCH 16/33 fuse: implement buffered IO with iomap

In reply to Darrick J. Wong

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

Implement pagecache IO with iomap, complete with hooks into truncate and fallocate so that the fuse server needn't implement disk block zeroing of post-EOF and unaligned punch/zero regions.

---
 fs/fuse/fuse_i.h          |    7 
 fs/fuse/fuse_iomap.h      |   11 +
 include/uapi/linux/fuse.h |    5 
 fs/fuse/dir.c             |   23 +
 fs/fuse/file.c            |   61 +++-
 fs/fuse/fuse_iomap.c      |  696 ++++++++++++++++++++++++++++++++++++++++++++-
 6 files changed, 772 insertions(+), 31 deletions(-)
fs/fuse/fuse_i.h +7 -0
index d1724bf8e87b93..b9f41c08cc8fb0 100644
@@ -192,6 +192,11 @@ struct fuse_inode {
 #ifdef CONFIG_FUSE_IOMAP
 			/* file size as reported by fuse server */
 			loff_t i_disk_size;
+
+			/* pending io completions */
+			spinlock_t ioend_lock;
+			struct work_struct ioend_work;
+			struct list_head ioend_list;
 #endif
 		};
 
@@ -1741,4 +1746,6 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()	do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+sector_t fuse_bmap(struct address_space *mapping, sector_t block);
+
 #endif /* _FS_FUSE_I_H */
fs/fuse/fuse_iomap.h +11 -0
index 07433c33535b2d..4b12af01ff00f5 100644
@@ -53,6 +53,13 @@ int fuse_iomap_setsize_finish(struct inode *inode, loff_t newsize);
 
 ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to);
 ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
+
+int fuse_iomap_mmap(struct file *file, struct vm_area_struct *vma);
+int fuse_iomap_setsize_start(struct inode *inode, loff_t newsize);
+int fuse_iomap_fallocate(struct file *file, int mode, loff_t offset,
+			 loff_t length, loff_t new_size);
+int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
+				 loff_t endpos);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -72,6 +79,10 @@ ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
 # define fuse_iomap_setsize_finish(...)		(-ENOSYS)
 # define fuse_iomap_read_iter(...)		(-ENOSYS)
 # define fuse_iomap_write_iter(...)		(-ENOSYS)
+# define fuse_iomap_mmap(...)			(-ENOSYS)
+# define fuse_iomap_setsize_start(...)		(-ENOSYS)
+# define fuse_iomap_fallocate(...)		(-ENOSYS)
+# define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +5 -0
index 543965b2f8fb37..71b216262c84cb 100644
@@ -1373,6 +1373,9 @@ struct fuse_uring_cmd_req {
 #define FUSE_IOMAP_OP_ATOMIC		(1U << 9)
 #define FUSE_IOMAP_OP_DONTCACHE		(1U << 10)
 
+/* pagecache writeback operation */
+#define FUSE_IOMAP_OP_WRITEBACK		(1U << 31)
+
 #define FUSE_IOMAP_NULL_ADDR		(-1ULL)	/* addr is not valid */
 
 struct fuse_iomap_io {
@@ -1422,6 +1425,8 @@ struct fuse_iomap_end_in {
 #define FUSE_IOMAP_IOEND_DIRECT		(1U << 3)
 /* is append ioend */
 #define FUSE_IOMAP_IOEND_APPEND		(1U << 4)
+/* is pagecache writeback */
+#define FUSE_IOMAP_IOEND_WRITEBACK	(1U << 5)
 
 struct fuse_iomap_ioend_in {
 	uint32_t flags;		/* FUSE_IOMAP_IOEND_* */
fs/fuse/dir.c +22 -1
index dcf5ccbc57c7be..fc0751deebfd20 100644
@@ -2225,7 +2225,10 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		is_truncate = true;
 	}
 
-	if (FUSE_IS_DAX(inode) && is_truncate) {
+	if (is_iomap && is_truncate) {
+		filemap_invalidate_lock(mapping);
+		fault_blocked = true;
+	} else if (FUSE_IS_DAX(inode) && is_truncate) {
 		filemap_invalidate_lock(mapping);
 		fault_blocked = true;
 		err = fuse_dax_break_layouts(inode, 0, -1);
@@ -2240,6 +2243,18 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		WARN_ON(!(attr->ia_valid & ATTR_SIZE));
 		WARN_ON(attr->ia_size != 0);
 		if (fc->atomic_o_trunc) {
+			if (is_iomap) {
+				/*
+				 * fuse_open already set the size to zero and
+				 * truncated the pagecache, and we've since
+				 * cycled the inode locks.  Another thread
+				 * could have performed an appending write, so
+				 * we don't want to touch the file further.
+				 */
+				filemap_invalidate_unlock(mapping);
+				return 0;
+			}
+
 			/*
 			 * No need to send request to userspace, since actual
 			 * truncation has already been done by OPEN.  But still
@@ -2273,6 +2288,12 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		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;
+
+		if (is_iomap) {
+			err = fuse_iomap_setsize_start(inode, attr->ia_size);
+			if (err)
+				goto error;
+		}
 	}
 
 	memset(&inarg, 0, sizeof(inarg));
fs/fuse/file.c +45 -16

126 lines not on this page · raw message

fs/fuse/fuse_iomap.c +682 -14

753 lines not on this page · raw message

#48 lore raw

Re: [PATCH 16/33] fuse: implement buffered IO with iomap

Quoted 819 lines · Darrick J. Wong

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

Implement pagecache IO with iomap, complete with hooks into truncate and fallocate so that the fuse server needn't implement disk block zeroing of post-EOF and unaligned punch/zero regions.

---
 fs/fuse/fuse_i.h          |    7 
 fs/fuse/fuse_iomap.h      |   11 +
 include/uapi/linux/fuse.h |    5 
 fs/fuse/dir.c             |   23 +
 fs/fuse/file.c            |   61 +++-
 fs/fuse/fuse_iomap.c      |  696 ++++++++++++++++++++++++++++++++++++++++++++-
 6 files changed, 772 insertions(+), 31 deletions(-)
fs/fuse/fuse_i.h +7 -0
index d1724bf8e87b93..b9f41c08cc8fb0 100644
@@ -192,6 +192,11 @@ struct fuse_inode {
 #ifdef CONFIG_FUSE_IOMAP
 			/* file size as reported by fuse server */
 			loff_t i_disk_size;
+
+			/* pending io completions */
+			spinlock_t ioend_lock;
+			struct work_struct ioend_work;
+			struct list_head ioend_list;
 #endif
 		};
 
@@ -1741,4 +1746,6 @@ extern void fuse_sysctl_unregister(void);
 #define fuse_sysctl_unregister()	do { } while (0)
 #endif /* CONFIG_SYSCTL */
 
+sector_t fuse_bmap(struct address_space *mapping, sector_t block);
+
 #endif /* _FS_FUSE_I_H */
fs/fuse/fuse_iomap.h +11 -0
index 07433c33535b2d..4b12af01ff00f5 100644
@@ -53,6 +53,13 @@ int fuse_iomap_setsize_finish(struct inode *inode, loff_t newsize);
 
 ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to);
 ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
+
+int fuse_iomap_mmap(struct file *file, struct vm_area_struct *vma);
+int fuse_iomap_setsize_start(struct inode *inode, loff_t newsize);
+int fuse_iomap_fallocate(struct file *file, int mode, loff_t offset,
+			 loff_t length, loff_t new_size);
+int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
+				 loff_t endpos);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -72,6 +79,10 @@ ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from);
 # define fuse_iomap_setsize_finish(...)		(-ENOSYS)
 # define fuse_iomap_read_iter(...)		(-ENOSYS)
 # define fuse_iomap_write_iter(...)		(-ENOSYS)
+# define fuse_iomap_mmap(...)			(-ENOSYS)
+# define fuse_iomap_setsize_start(...)		(-ENOSYS)
+# define fuse_iomap_fallocate(...)		(-ENOSYS)
+# define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +5 -0
index 543965b2f8fb37..71b216262c84cb 100644
@@ -1373,6 +1373,9 @@ struct fuse_uring_cmd_req {
 #define FUSE_IOMAP_OP_ATOMIC		(1U << 9)
 #define FUSE_IOMAP_OP_DONTCACHE		(1U << 10)
 
+/* pagecache writeback operation */
+#define FUSE_IOMAP_OP_WRITEBACK		(1U << 31)
+
 #define FUSE_IOMAP_NULL_ADDR		(-1ULL)	/* addr is not valid */
 
 struct fuse_iomap_io {
@@ -1422,6 +1425,8 @@ struct fuse_iomap_end_in {
 #define FUSE_IOMAP_IOEND_DIRECT		(1U << 3)
 /* is append ioend */
 #define FUSE_IOMAP_IOEND_APPEND		(1U << 4)
+/* is pagecache writeback */
+#define FUSE_IOMAP_IOEND_WRITEBACK	(1U << 5)
 
 struct fuse_iomap_ioend_in {
 	uint32_t flags;		/* FUSE_IOMAP_IOEND_* */
fs/fuse/dir.c +22 -1
index dcf5ccbc57c7be..fc0751deebfd20 100644
@@ -2225,7 +2225,10 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		is_truncate = true;
 	}
 
-	if (FUSE_IS_DAX(inode) && is_truncate) {
+	if (is_iomap && is_truncate) {
+		filemap_invalidate_lock(mapping);
+		fault_blocked = true;
+	} else if (FUSE_IS_DAX(inode) && is_truncate) {
 		filemap_invalidate_lock(mapping);
 		fault_blocked = true;
 		err = fuse_dax_break_layouts(inode, 0, -1);
@@ -2240,6 +2243,18 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		WARN_ON(!(attr->ia_valid & ATTR_SIZE));
 		WARN_ON(attr->ia_size != 0);
 		if (fc->atomic_o_trunc) {
+			if (is_iomap) {
+				/*
+				 * fuse_open already set the size to zero and
+				 * truncated the pagecache, and we've since
+				 * cycled the inode locks.  Another thread
+				 * could have performed an appending write, so
+				 * we don't want to touch the file further.
+				 */
+				filemap_invalidate_unlock(mapping);
+				return 0;
+			}
+
 			/*
 			 * No need to send request to userspace, since actual
 			 * truncation has already been done by OPEN.  But still
@@ -2273,6 +2288,12 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 		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;
+
+		if (is_iomap) {
+			err = fuse_iomap_setsize_start(inode, attr->ia_size);
+			if (err)
+				goto error;
+		}
 	}
 
 	memset(&inarg, 0, sizeof(inarg));
fs/fuse/file.c +45 -16
index ae320026f0648f..0828ecb20a828c 100644
@@ -402,7 +402,7 @@ static int fuse_release(struct inode *inode, struct file *file)
 	 * Dirty pages might remain despite write_inode_now() call from
 	 * fuse_flush() due to writes racing with the close.
 	 */
-	if (fc->writeback_cache)
+	if (fc->writeback_cache || fuse_inode_has_iomap(inode))
 		write_inode_now(inode, 1);
 
 	fuse_release_common(file, false);
@@ -2395,6 +2395,9 @@ static int fuse_file_mmap(struct file *file, struct vm_area_struct *vma)
 	struct inode *inode = file_inode(file);
 	int rc;
 
+	if (fuse_inode_has_iomap(inode))
+		return fuse_iomap_mmap(file, vma);
+
 	/* DAX mmap is superior to direct_io mmap */
 	if (FUSE_IS_DAX(inode))
 		return fuse_dax_mmap(file, vma);
@@ -2593,7 +2596,7 @@ static int fuse_file_flock(struct file *file, int cmd, struct file_lock *fl)
 	return err;
 }
 
-static sector_t fuse_bmap(struct address_space *mapping, sector_t block)
+sector_t fuse_bmap(struct address_space *mapping, sector_t block)
 {
 	struct inode *inode = mapping->host;
 	struct fuse_mount *fm = get_fuse_mount(inode);
@@ -2947,8 +2950,12 @@ fuse_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
 
 static int fuse_writeback_range(struct inode *inode, loff_t start, loff_t end)
 {
-	int err = filemap_write_and_wait_range(inode->i_mapping, start, LLONG_MAX);
+	int err;
 
+	if (fuse_inode_has_iomap(inode))
+		return fuse_iomap_flush_unmap_range(inode, start, end);
+
+	err = filemap_write_and_wait_range(inode->i_mapping, start, LLONG_MAX);
 	if (!err)
 		fuse_sync_writes(inode);
 
@@ -2984,7 +2991,10 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 		return -EOPNOTSUPP;
 
 	inode_lock(inode);
-	if (block_faults) {
+	if (is_iomap) {
+		filemap_invalidate_lock(inode->i_mapping);
+		block_faults = true;
+	} else if (block_faults) {
 		filemap_invalidate_lock(inode->i_mapping);
 		err = fuse_dax_break_layouts(inode, 0, -1);
 		if (err)
@@ -2999,6 +3009,17 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 			goto out;
 	}
 
+	/*
+	 * If we are using iomap for file IO, fallocate must wait for all AIO
+	 * to complete before we continue as AIO can change the file size on
+	 * completion without holding any locks we currently hold. We must do
+	 * this first because AIO can update the in-memory inode size, and the
+	 * operations that follow require the in-memory size to be fully
+	 * up-to-date.
+	 */
+	if (is_iomap)
+		inode_dio_wait(inode);
+
 	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
 	    offset + length > i_size_read(inode)) {
 		err = inode_newsize_ok(inode, offset + length);
@@ -3027,21 +3048,23 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 	if (err)
 		goto out;
 
-	/* we could have extended the file */
-	if (!(mode & FALLOC_FL_KEEP_SIZE)) {
-		if (is_iomap && newsize > 0) {
-			err = fuse_iomap_setsize_finish(inode, newsize);
-			if (err)
-				goto out;
+	if (is_iomap) {
+		err = fuse_iomap_fallocate(file, mode, offset, length,
+					   newsize);
+		if (err)
+			goto out;
+	} else {
+		/* we could have extended the file */
+		if (!(mode & FALLOC_FL_KEEP_SIZE)) {
+			if (fuse_write_update_attr(inode, newsize, length))
+				file_update_time(file);
 		}
 
-		if (fuse_write_update_attr(inode, offset + length, length))
-			file_update_time(file);
+		if (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE))
+			truncate_pagecache_range(inode, offset,
+						 offset + length - 1);
 	}
 
-	if (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE))
-		truncate_pagecache_range(inode, offset, offset + length - 1);
-
 	fuse_invalidate_attr_mask(inode, FUSE_STATX_MODSIZE);
 
 out:
@@ -3085,6 +3108,7 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in,
 	ssize_t err;
 	/* mark unstable when write-back is not used, and file_out gets
 	 * extended */
+	const bool is_iomap = fuse_inode_has_iomap(inode_out);
 	bool is_unstable = (!fc->writeback_cache) &&
 			   ((pos_out + len) > inode_out->i_size);
 
@@ -3128,6 +3152,10 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in,
 	if (err)
 		goto out;
 
+	/* See inode_dio_wait comment in fuse_file_fallocate */
+	if (is_iomap)
+		inode_dio_wait(inode_out);
+
 	if (is_unstable)
 		set_bit(FUSE_I_SIZE_UNSTABLE, &fi_out->state);
 
@@ -3168,7 +3196,8 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in,
 		goto out;
 	}
 
-	truncate_inode_pages_range(inode_out->i_mapping,
+	if (!is_iomap)
+		truncate_inode_pages_range(inode_out->i_mapping,
 				   ALIGN_DOWN(pos_out, PAGE_SIZE),
 				   ALIGN(pos_out + bytes_copied, PAGE_SIZE) - 1);
 
fs/fuse/fuse_iomap.c +467 -11
index f0b5ea49b6e2ac..2097a83af833d5 100644
@@ -5,6 +5,8 @@
  */
 #include <linux/iomap.h>
 #include <linux/fiemap.h>
+#include <linux/pagemap.h>
+#include <linux/falloc.h>
 #include "fuse_i.h"
 #include "fuse_trace.h"
 #include "fuse_iomap.h"
@@ -204,7 +206,7 @@ static inline uint16_t fuse_iomap_flags_from_server(uint16_t fuse_f_flags)
 		ret |= FUSE_IOMAP_OP_##word
 static inline uint32_t fuse_iomap_op_to_server(unsigned iomap_op_flags)
 {
-	uint32_t ret = 0;
+	uint32_t ret = iomap_op_flags & FUSE_IOMAP_OP_WRITEBACK;
 
 	XMAP(WRITE);
 	XMAP(ZERO);
@@ -370,7 +372,8 @@ fuse_iomap_begin_validate(const struct inode *inode,
 
 static inline bool fuse_is_iomap_file_write(unsigned int opflags)
 {
-	return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE);
+	return opflags & (IOMAP_WRITE | IOMAP_ZERO | IOMAP_UNSHARE |
+			  FUSE_IOMAP_OP_WRITEBACK);
 }
 
 static inline struct fuse_backing *
@@ -747,12 +750,7 @@ void fuse_iomap_unmount(struct fuse_mount *fm)
 	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_set_iomap(struct inode *inode);
 
 static inline void fuse_inode_clear_iomap(struct inode *inode)
 {
@@ -979,17 +977,107 @@ static const struct iomap_dio_ops fuse_iomap_dio_write_ops = {
 	.end_io		= fuse_iomap_dio_write_end_io,
 };
 
+static const struct iomap_write_ops fuse_iomap_write_ops = {
+};
+
+static int
+fuse_iomap_zero_range(
+	struct inode		*inode,
+	loff_t			pos,
+	loff_t			len,
+	bool			*did_zero)
+{
+	return iomap_zero_range(inode, pos, len, did_zero, &fuse_iomap_ops,
+				&fuse_iomap_write_ops, NULL);
+}
+
+/* Take care of zeroing post-EOF blocks when they might exist. */
+static ssize_t
+fuse_iomap_write_zero_eof(
+	struct kiocb		*iocb,
+	struct iov_iter		*from,
+	bool			*drained_dio)
+{
+	struct inode *inode = file_inode(iocb->ki_filp);
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct address_space *mapping = iocb->ki_filp->f_mapping;
+	loff_t			isize;
+	int			error;
+
+	/*
+	 * We need to serialise against EOF updates that occur in IO
+	 * completions here. We want to make sure that nobody is changing the
+	 * size while we do this check until we have placed an IO barrier (i.e.
+	 * hold i_rwsem exclusively) that prevents new IO from being
+	 * dispatched.  The spinlock effectively forms a memory barrier once we
+	 * have i_rwsem exclusively so we are guaranteed to see the latest EOF
+	 * value and hence be able to correctly determine if we need to run
+	 * zeroing.
+	 */
+	spin_lock(&fi->lock);
+	isize = i_size_read(inode);
+	if (iocb->ki_pos <= isize) {
+		spin_unlock(&fi->lock);
+		return 0;
+	}
+	spin_unlock(&fi->lock);
+
+	if (iocb->ki_flags & IOCB_NOWAIT)
+		return -EAGAIN;
+
+	if (!(*drained_dio)) {
+		/*
+		 * We now have an IO submission barrier in place, but AIO can
+		 * do EOF updates during IO completion and hence we now need to
+		 * wait for all of them to drain.  Non-AIO DIO will have
+		 * drained before we are given the exclusive i_rwsem, and so
+		 * for most cases this wait is a no-op.
+		 */
+		inode_dio_wait(inode);
+		*drained_dio = true;
+		return 1;
+	}
+
+	filemap_invalidate_lock(mapping);
+	error = fuse_iomap_zero_range(inode, isize, iocb->ki_pos - isize, NULL);
+	filemap_invalidate_unlock(mapping);
+
+	return error;
+}
+
 static ssize_t
 fuse_iomap_write_checks(
 	struct kiocb		*iocb,
 	struct iov_iter		*from)
 {
+	struct inode		*inode = iocb->ki_filp->f_mapping->host;
 	ssize_t			error;
+	bool			drained_dio = false;
 
+restart:
 	error = generic_write_checks(iocb, from);
 	if (error <= 0)
 		return error;
 
+	/*
+	 * If the offset is beyond the size of the file, we need to zero all
+	 * blocks that fall between the existing EOF and the start of this
+	 * write.
+	 *
+	 * We can do an unlocked check for i_size here safely as I/O completion
+	 * can only extend EOF.  Truncate is locked out at this point, so the
+	 * EOF cannot move backwards, only forwards. Hence we only need to take
+	 * the slow path when we are at or beyond the current EOF.
+	 */
+	if (fuse_inode_has_iomap(inode) &&
+	    iocb->ki_pos > i_size_read(inode)) {
+		error = fuse_iomap_write_zero_eof(iocb, from, &drained_dio);
+		if (error == 1)
+			goto restart;
+		if (error)
+			return error;
+	}
+
 	return kiocb_modified(iocb);
 }
 
@@ -1059,6 +1147,366 @@ void fuse_iomap_open_truncate(struct inode *inode)
 	fi->i_disk_size = 0;
 }
 
+struct fuse_writepage_ctx {
+	struct iomap_writepage_ctx ctx;
+};
+
+static void fuse_iomap_end_ioend(struct iomap_ioend *ioend)
+{
+	struct inode *inode = ioend->io_inode;
+	unsigned int ioendflags = FUSE_IOMAP_IOEND_WRITEBACK;
+	unsigned int nofs_flag;
+	int error = blk_status_to_errno(ioend->io_bio.bi_status);
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	/* We still have to clean up the ioend even if the inode is dead */
+	if (!error && fuse_is_bad(inode))
+		error = -EIO;
+
+	if (ioend->io_flags & IOMAP_IOEND_SHARED)
+		ioendflags |= FUSE_IOMAP_IOEND_SHARED;
+	if (ioend->io_flags & IOMAP_IOEND_UNWRITTEN)
+		ioendflags |= FUSE_IOMAP_IOEND_UNWRITTEN;
+
+	/*
+	 * We can allocate memory here while doing writeback on behalf of
+	 * memory reclaim.  To avoid memory allocation deadlocks set the
+	 * task-wide nofs context for the following operations.
+	 */
+	nofs_flag = memalloc_nofs_save();
+	fuse_iomap_ioend(inode, ioend->io_offset, ioend->io_size, error,
+			 ioendflags, ioend->io_bio.bi_bdev, ioend->io_sector);
+	iomap_finish_ioends(ioend, error);
+	memalloc_nofs_restore(nofs_flag);
+}
+
+/*
+ * Finish all pending IO completions that require transactional modifications.
+ *
+ * We try to merge physical and logically contiguous ioends before completion to
+ * minimise the number of transactions we need to perform during IO completion.
+ * Both unwritten extent conversion and COW remapping need to iterate and modify
+ * one physical extent at a time, so we gain nothing by merging physically
+ * discontiguous extents here.
+ *
+ * The ioend chain length that we can be processing here is largely unbound in
+ * length and we may have to perform significant amounts of work on each ioend
+ * to complete it. Hence we have to be careful about holding the CPU for too
+ * long in this loop.
+ */
+static void fuse_iomap_end_io(struct work_struct *work)
+{
+	struct fuse_inode *fi =
+		container_of(work, struct fuse_inode, ioend_work);
+	struct iomap_ioend *ioend;
+	struct list_head tmp;
+	unsigned long flags;
+
+	spin_lock_irqsave(&fi->ioend_lock, flags);
+	list_replace_init(&fi->ioend_list, &tmp);
+	spin_unlock_irqrestore(&fi->ioend_lock, flags);
+
+	iomap_sort_ioends(&tmp);
+	while ((ioend = list_first_entry_or_null(&tmp, struct iomap_ioend,
+			io_list))) {
+		list_del_init(&ioend->io_list);
+		iomap_ioend_try_merge(ioend, &tmp);
+		fuse_iomap_end_ioend(ioend);
+		cond_resched();
+	}
+}
+
+static void fuse_iomap_end_bio(struct bio *bio)
+{
+	struct iomap_ioend *ioend = iomap_ioend_from_bio(bio);
+	struct inode *inode = ioend->io_inode;
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	unsigned long flags;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	spin_lock_irqsave(&fi->ioend_lock, flags);
+	if (list_empty(&fi->ioend_list))
+		WARN_ON_ONCE(!queue_work(system_unbound_wq, &fi->ioend_work));
+	list_add_tail(&ioend->io_list, &fi->ioend_list);
+	spin_unlock_irqrestore(&fi->ioend_lock, flags);
+}
+
+/*
+ * Fast revalidation of the cached writeback mapping. Return true if the current
+ * mapping is valid, false otherwise.
+ */
+static bool fuse_iomap_revalidate_writeback(struct iomap_writepage_ctx *wpc,
+					    loff_t offset)
+{
+	if (offset < wpc->iomap.offset ||
+	    offset >= wpc->iomap.offset + wpc->iomap.length)
+		return false;
+
+	/* XXX actually use revalidation cookie */
+	return true;
+}
+
+/*
+ * If the folio has delalloc blocks on it, the caller is asking us to punch them
+ * out. If we don't, we can leave a stale delalloc mapping covered by a clean
+ * page that needs to be dirtied again before the delalloc mapping can be
+ * converted. This stale delalloc mapping can trip up a later direct I/O read
+ * operation on the same region.
+ *
+ * We prevent this by truncating away the delalloc regions on the folio. Because
+ * they are delalloc, we can do this without needing a transaction. Indeed - if
+ * we get ENOSPC errors, we have to be able to do this truncation without a
+ * transaction as there is no space left for block reservation (typically why
+ * we see a ENOSPC in writeback).
+ */
+static void fuse_iomap_discard_folio(struct folio *folio, loff_t pos, int error)
+{
+	struct inode *inode = folio->mapping->host;
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	loff_t end = folio_pos(folio) + folio_size(folio);
+
+	if (fuse_is_bad(inode))
+		return;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	printk_ratelimited(KERN_ERR
+		"page discard on page %px, inode 0x%llx, pos %llu.",
+			folio, fi->orig_ino, pos);
+
+	/* Userspace may need to remove delayed allocations */
+	fuse_iomap_ioend(inode, pos, end - pos, error, 0, NULL,
+			 FUSE_IOMAP_NULL_ADDR);
+}
+
+static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
+					  struct folio *folio, u64 offset,
+					  unsigned int len, u64 end_pos)
+{
+	struct inode *inode = wpc->inode;
+	struct iomap write_iomap, dontcare;
+	ssize_t ret;
+
+	if (fuse_is_bad(inode)) {
+		ret = -EIO;
+		goto discard_folio;
+	}
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	if (!fuse_iomap_revalidate_writeback(wpc, offset)) {
+		ret = fuse_iomap_begin(inode, offset, len,
+				       FUSE_IOMAP_OP_WRITEBACK,
+				       &write_iomap, &dontcare);
+		if (ret)
+			goto discard_folio;
+
+		/*
+		 * Landed in a hole or beyond EOF?  Send that to iomap, it'll
+		 * skip writing back the file range.
+		 */
+		if (write_iomap.offset > offset) {
+			write_iomap.length = write_iomap.offset - offset;
+			write_iomap.offset = offset;
+			write_iomap.type = IOMAP_HOLE;
+		}
+
+		memcpy(&wpc->iomap, &write_iomap, sizeof(struct iomap));
+	}
+
+	ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
+	if (ret < 0)
+		goto discard_folio;
+
+	return ret;
+discard_folio:
+	fuse_iomap_discard_folio(folio, offset, ret);
+	return ret;
+}
+
+static int fuse_iomap_writeback_submit(struct iomap_writepage_ctx *wpc,
+				       int error)
+{
+	struct iomap_ioend *ioend = wpc->wb_ctx;
+
+	ASSERT(fuse_inode_has_iomap(ioend->io_inode));
+
+	/* always call our ioend function, even if we cancel the bio */
+	ioend->io_bio.bi_end_io = fuse_iomap_end_bio;
+	return iomap_ioend_writeback_submit(wpc, error);
+}
+
+static const struct iomap_writeback_ops fuse_iomap_writeback_ops = {
+	.writeback_range	= fuse_iomap_writeback_range,
+	.writeback_submit	= fuse_iomap_writeback_submit,
+};
+
+static int fuse_iomap_writepages(struct address_space *mapping,
+				 struct writeback_control *wbc)
+{
+	struct fuse_writepage_ctx wpc = {
+		.ctx = {
+			.inode = mapping->host,
+			.wbc = wbc,
+			.ops = &fuse_iomap_writeback_ops,
+		},
+	};
+
+	ASSERT(fuse_inode_has_iomap(mapping->host));
+
+	return iomap_writepages(&wpc.ctx);
+}
+
+static int fuse_iomap_read_folio(struct file *file, struct folio *folio)
+{
+	ASSERT(fuse_inode_has_iomap(file_inode(file)));
+
+	iomap_bio_read_folio(folio, &fuse_iomap_ops);
+	return 0;
+}
+
+static void fuse_iomap_readahead(struct readahead_control *rac)
+{
+	ASSERT(fuse_inode_has_iomap(file_inode(rac->file)));
+
+	iomap_bio_readahead(rac, &fuse_iomap_ops);
+}
+
+static const struct address_space_operations fuse_iomap_aops = {
+	.read_folio		= fuse_iomap_read_folio,
+	.readahead		= fuse_iomap_readahead,
+	.writepages		= fuse_iomap_writepages,
+	.dirty_folio		= iomap_dirty_folio,
+	.release_folio		= iomap_release_folio,
+	.invalidate_folio	= iomap_invalidate_folio,
+	.migrate_folio		= filemap_migrate_folio,
+	.is_partially_uptodate  = iomap_is_partially_uptodate,
+	.error_remove_folio	= generic_error_remove_folio,
+
+	/* These aren't pagecache operations per se */
+	.bmap			= fuse_bmap,
+};
+
+static inline void fuse_inode_set_iomap(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+
+	inode->i_data.a_ops = &fuse_iomap_aops;
+
+	INIT_WORK(&fi->ioend_work, fuse_iomap_end_io);
+	INIT_LIST_HEAD(&fi->ioend_list);
+	spin_lock_init(&fi->ioend_lock);
+	set_bit(FUSE_I_IOMAP, &fi->state);
+}
+
+/*
+ * Locking for serialisation of IO during page faults. This results in a lock
+ * ordering of:
+ *
+ * mmap_lock (MM)
+ *   sb_start_pagefault(vfs, freeze)
+ *     invalidate_lock (vfs - truncate serialisation)
+ *       page_lock (MM)
+ *         i_lock (FUSE - extent map serialisation)
+ */
+static vm_fault_t fuse_iomap_page_mkwrite(struct vm_fault *vmf)
+{
+	struct inode *inode = file_inode(vmf->vma->vm_file);
+	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
+	vm_fault_t ret;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	sb_start_pagefault(inode->i_sb);
+	file_update_time(vmf->vma->vm_file);
+
+	filemap_invalidate_lock_shared(mapping);
+	ret = iomap_page_mkwrite(vmf, &fuse_iomap_ops, NULL);
+	filemap_invalidate_unlock_shared(mapping);
+
+	sb_end_pagefault(inode->i_sb);
+	return ret;
+}
+
+static const struct vm_operations_struct fuse_iomap_vm_ops = {
+	.fault		= filemap_fault,
+	.map_pages	= filemap_map_pages,
+	.page_mkwrite	= fuse_iomap_page_mkwrite,
+};
+
+int fuse_iomap_mmap(struct file *file, struct vm_area_struct *vma)
+{
+	ASSERT(fuse_inode_has_iomap(file_inode(file)));
+
+	file_accessed(file);
+	vma->vm_ops = &fuse_iomap_vm_ops;
+	return 0;
+}
+
+static ssize_t fuse_iomap_buffered_read(struct kiocb *iocb, struct iov_iter *to)
+{
+	struct inode *inode = file_inode(iocb->ki_filp);
+	ssize_t ret;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	if (!iov_iter_count(to))
+		return 0; /* skip atime */
+
+	ret = fuse_iomap_ilock_iocb(iocb, SHARED);
+	if (ret)
+		return ret;
+	ret = generic_file_read_iter(iocb, to);
+	if (ret > 0)
+		file_accessed(iocb->ki_filp);
+	inode_unlock_shared(inode);
+
+	return ret;
+}
+
+static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb,
+					 struct iov_iter *from)
+{
+	struct inode *inode = file_inode(iocb->ki_filp);
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	loff_t pos = iocb->ki_pos;
+	ssize_t ret;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	if (!iov_iter_count(from))
+		return 0;
+
+	ret = fuse_iomap_ilock_iocb(iocb, EXCL);
+	if (ret)
+		return ret;
+
+	ret = fuse_iomap_write_checks(iocb, from);
+	if (ret)
+		goto out_unlock;
+
+	if (inode->i_size < pos + iov_iter_count(from))
+		set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
+
+	ret = iomap_file_buffered_write(iocb, from, &fuse_iomap_ops,
+					&fuse_iomap_write_ops, NULL);
+
+	if (ret > 0)
+		fuse_write_update_attr(inode, pos + ret, ret);
+	clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
+
+out_unlock:
+	inode_unlock(inode);
+
+	if (ret > 0) {
+		/* Handle various SYNC-type writes */
+		ret = generic_write_sync(iocb, ret);
+	}
+	return ret;
+}
+
 static inline bool fuse_iomap_force_directio(const struct kiocb *iocb)
 {
 	struct fuse_file *ff = iocb->ki_filp->private_data;
@@ -1072,9 +1520,30 @@ ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to)
 
 	ASSERT(fuse_inode_has_iomap(file_inode(iocb->ki_filp)));
 
-	if ((iocb->ki_flags & IOCB_DIRECT) || force_directio)
-		return fuse_iomap_direct_read(iocb, to);
-	return -EIO;
+	if ((iocb->ki_flags & IOCB_DIRECT) || force_directio) {
+		ssize_t ret = fuse_iomap_direct_read(iocb, to);
+
+		switch (ret) {
+		case -ENOTBLK:
+		case -ENOSYS:
+			/*
+			 * We fall back to a buffered read if:
+			 *
+			 *  - ENOTBLK means iomap told us to do it
+			 *  - ENOSYS means the fuse server wants it

fs/fuse/fuse_iomap.c ssize_t fuse_iomap_read_iter(struct kiocb *iocb, struct iov_iter *to) · line 1543

Quoted 10 lines
fs/fuse/fuse_iomap.c +10 -0
+			 *
+			 * Don't fall back if we were forced to do it.
+			 */
+			if (force_directio)
+				return -EIO;
+			break;
+		default:
+			/* errors, no progress, or partial progress */
+			return ret;
+		}

When falling back from directio read to buffered IO, we need to clear IOCB_DIRECT so that generic_file_read_iter won't fall into ->direct_IO.

Note that the directio write fallback doesn't need to clear this because it calls the iomap buffered write code directly.

--D

Quoted 218 lines
fs/fuse/fuse_iomap.c +205 -3
+	}
+
+	return fuse_iomap_buffered_read(iocb, to);
 }
 
 ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from)
@@ -1083,7 +1552,206 @@ ssize_t fuse_iomap_write_iter(struct kiocb *iocb, struct iov_iter *from)
 
 	ASSERT(fuse_inode_has_iomap(file_inode(iocb->ki_filp)));
 
-	if ((iocb->ki_flags & IOCB_DIRECT) || force_directio)
-		return fuse_iomap_direct_write(iocb, from);
-	return -EIO;
+	if ((iocb->ki_flags & IOCB_DIRECT) || force_directio) {
+		ssize_t ret = fuse_iomap_direct_write(iocb, from);
+
+		switch (ret) {
+		case -ENOTBLK:
+		case -ENOSYS:
+			/*
+			 * We fall back to a buffered write if:
+			 *
+			 *  - ENOTBLK means iomap told us to do it
+			 *  - ENOSYS means the fuse server wants it
+			 *
+			 * Either way, try the write again as a synchronous
+			 * buffered write unless we were forced to do directio.
+			 */
+			if (force_directio)
+				return -EIO;
+			iocb->ki_flags |= IOCB_SYNC;
+			break;
+		default:
+			/* errors, no progress, or partial progress */
+			return ret;
+		}
+	}
+
+	return fuse_iomap_buffered_write(iocb, from);
+}
+
+static int
+fuse_iomap_truncate_page(
+	struct inode *inode,
+	loff_t			pos,
+	bool			*did_zero)
+{
+	return iomap_truncate_page(inode, pos, did_zero, &fuse_iomap_ops,
+				   &fuse_iomap_write_ops, NULL);
+}
+/*
+ * Truncate pagecache for a file before sending the truncate request to
+ * userspace.  Must have write permission and not be a directory.
+ *
+ * Caution: The caller of this function is responsible for calling
+ * setattr_prepare() or otherwise verifying the change is fine.
+ */
+int
+fuse_iomap_setsize_start(
+	struct inode		*inode,
+	loff_t			newsize)
+{
+	loff_t			oldsize = i_size_read(inode);
+	int			error;
+	bool			did_zeroing = false;
+
+	rwsem_assert_held_write(&inode->i_rwsem);
+	rwsem_assert_held_write(&inode->i_mapping->invalidate_lock);
+	ASSERT(S_ISREG(inode->i_mode));
+
+	/*
+	 * Wait for all direct I/O to complete.
+	 */
+	inode_dio_wait(inode);
+
+	/*
+	 * File data changes must be complete and flushed to disk before we
+	 * call userspace to modify the inode.
+	 *
+	 * Start with zeroing any data beyond EOF that we may expose on file
+	 * extension, or zeroing out the rest of the block on a downward
+	 * truncate.
+	 */
+	if (newsize > oldsize)
+		error = fuse_iomap_zero_range(inode, oldsize, newsize - oldsize,
+					      &did_zeroing);
+	else
+		error = fuse_iomap_truncate_page(inode, newsize, &did_zeroing);
+	if (error)
+		return error;
+
+	/*
+	 * We've already locked out new page faults, so now we can safely
+	 * remove pages from the page cache knowing they won't get refaulted
+	 * until we drop the mapping invalidation lock after the extent
+	 * manipulations are complete. The truncate_setsize() call also cleans
+	 * folios spanning EOF on extending truncates and hence ensures
+	 * sub-page block size filesystems are correctly handled, too.
+	 *
+	 * And we update in-core i_size and truncate page cache beyond newsize
+	 * before writing back the whole file, so we're guaranteed not to write
+	 * stale data past the new EOF on truncate down.
+	 */
+	truncate_setsize(inode, newsize);
+
+	/*
+	 * Flush the entire pagecache to ensure the fuse server logs the inode
+	 * size change and all dirty data that might be associated with it.
+	 * We don't know the ondisk inode size, so we only have this clumsy
+	 * hammer.
+	 */
+	return filemap_write_and_wait(inode->i_mapping);
+}
+
+/*
+ * Prepare for a file data block remapping operation by flushing and unmapping
+ * all pagecache for the entire range.
+ */
+int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
+				 loff_t endpos)
+{
+	loff_t			start, end;
+	unsigned int		rounding;
+	int			error;
+
+	/*
+	 * Make sure we extend the flush out to extent alignment boundaries so
+	 * any extent range overlapping the start/end of the modification we
+	 * are about to do is clean and idle.
+	 */
+	rounding = max_t(unsigned int, i_blocksize(inode), PAGE_SIZE);
+	start = round_down(pos, rounding);
+	end = round_up(endpos + 1, rounding) - 1;
+
+	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
+	if (error)
+		return error;
+	truncate_pagecache_range(inode, start, end);
+	return 0;
+}
+
+static int fuse_iomap_punch_range(struct inode *inode, loff_t offset,
+				  loff_t length)
+{
+	loff_t isize = i_size_read(inode);
+	int error;
+
+	/*
+	 * Now that we've unmap all full blocks we'll have to zero out any
+	 * partial block at the beginning and/or end.  iomap_zero_range is
+	 * smart enough to skip holes and unwritten extents, including those we
+	 * just created, but we must take care not to zero beyond EOF, which
+	 * would enlarge i_size.
+	 */
+	if (offset >= isize)
+		return 0;
+	if (offset + length > isize)
+		length = isize - offset;
+	error = fuse_iomap_zero_range(inode, offset, length, NULL);
+	if (error)
+		return error;
+
+	/*
+	 * If we zeroed right up to EOF and EOF straddles a page boundary we
+	 * must make sure that the post-EOF area is also zeroed because the
+	 * page could be mmap'd and iomap_zero_range doesn't do that for us.
+	 * Writeback of the eof page will do this, albeit clumsily.
+	 */
+	if (offset + length >= isize && offset_in_page(offset + length) > 0) {
+		error = filemap_write_and_wait_range(inode->i_mapping,
+					round_down(offset + length, PAGE_SIZE),
+					LLONG_MAX);
+	}
+
+	return error;
+}
+
+int
+fuse_iomap_fallocate(
+	struct file		*file,
+	int			mode,
+	loff_t			offset,
+	loff_t			length,
+	loff_t			new_size)
+{
+	struct inode *inode = file_inode(file);
+	int error;
+
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	/*
+	 * If we unmapped blocks from the file range, then we zero the
+	 * pagecache for those regions and push them to disk rather than make
+	 * the fuse server manually zero the disk blocks.
+	 */
+	if (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE)) {
+		error = fuse_iomap_punch_range(inode, offset, length);
+		if (error)
+			return error;
+	}
+
+	/*
+	 * If this is an extending write, we need to zero the bytes beyond the
+	 * new EOF and bounce the new size out to userspace.
+	 */
+	if (new_size) {
+		error = fuse_iomap_setsize_start(inode, new_size);
+		if (error)
+			return error;
+
+		fuse_write_update_attr(inode, new_size, length);
+	}
+
+	file_update_time(file);
+	return 0;
 }
#49 lore raw

PATCH 17/33 fuse_trace: implement buffered IO with iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |  227 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/dev.c        |   10 ++
 fs/fuse/fuse_iomap.c |   40 ++++++++-
 3 files changed, 273 insertions(+), 4 deletions(-)
fs/fuse/fuse_trace.h +225 -2
index a8337f5ddcf011..c832fb9012d983 100644
@@ -227,6 +227,9 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 #endif /* CONFIG_FUSE_BACKING */
 
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
+struct iomap_writepage_ctx;
+struct iomap_ioend;
+
 /* tracepoint boilerplate so we don't have to keep doing this */
 #define FUSE_IOMAP_OPFLAGS_FIELD \
 		__field(unsigned,		opflags)
@@ -294,7 +297,8 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 	{ FUSE_IOMAP_OP_UNSHARE,		"unshare" }, \
 	{ FUSE_IOMAP_OP_DAX,			"fsdax" }, \
 	{ FUSE_IOMAP_OP_ATOMIC,			"atomic" }, \
-	{ FUSE_IOMAP_OP_DONTCACHE,		"dontcache" }
+	{ FUSE_IOMAP_OP_DONTCACHE,		"dontcache" }, \
+	{ FUSE_IOMAP_OP_WRITEBACK,		"writeback" }
 
 #define FUSE_IOMAP_TYPE_STRINGS \
 	{ FUSE_IOMAP_TYPE_PURE_OVERWRITE,	"overwrite" }, \
@@ -309,7 +313,8 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 	{ FUSE_IOMAP_IOEND_UNWRITTEN,		"unwritten" }, \
 	{ FUSE_IOMAP_IOEND_BOUNDARY,		"boundary" }, \
 	{ FUSE_IOMAP_IOEND_DIRECT,		"direct" }, \
-	{ FUSE_IOMAP_IOEND_APPEND,		"append" }
+	{ FUSE_IOMAP_IOEND_APPEND,		"append" }, \
+	{ FUSE_IOMAP_IOEND_WRITEBACK,		"writeback" }
 
 #define IOMAP_DIOEND_STRINGS \
 	{ IOMAP_DIO_UNWRITTEN,			"unwritten" }, \
@@ -334,6 +339,12 @@ TRACE_DEFINE_ENUM(FUSE_I_IOMAP);
 	{ 1 << FUSE_I_EXCLUSIVE,		"excl" }, \
 	{ 1 << FUSE_I_IOMAP,			"iomap" }
 
+#define IOMAP_IOEND_STRINGS \
+	{ IOMAP_IOEND_SHARED,			"shared" }, \
+	{ IOMAP_IOEND_UNWRITTEN,		"unwritten" }, \
+	{ IOMAP_IOEND_BOUNDARY,			"boundary" }, \
+	{ IOMAP_IOEND_DIRECT,			"direct" }
+
 DECLARE_EVENT_CLASS(fuse_iomap_check_class,
 	TP_PROTO(const char *func, int line, const char *condition),
 
@@ -683,6 +694,9 @@ DEFINE_EVENT(fuse_iomap_file_io_class, name,		\
 	TP_ARGS(iocb, iter))
 DEFINE_FUSE_IOMAP_FILE_IO_EVENT(fuse_iomap_direct_read);
 DEFINE_FUSE_IOMAP_FILE_IO_EVENT(fuse_iomap_direct_write);
+DEFINE_FUSE_IOMAP_FILE_IO_EVENT(fuse_iomap_buffered_read);
+DEFINE_FUSE_IOMAP_FILE_IO_EVENT(fuse_iomap_buffered_write);
+DEFINE_FUSE_IOMAP_FILE_IO_EVENT(fuse_iomap_write_zero_eof);
 
 DECLARE_EVENT_CLASS(fuse_iomap_file_ioend_class,
 	TP_PROTO(const struct kiocb *iocb, const struct iov_iter *iter,
@@ -709,6 +723,8 @@ DEFINE_EVENT(fuse_iomap_file_ioend_class, name,		\
 	TP_ARGS(iocb, iter, ret))
 DEFINE_FUSE_IOMAP_FILE_IOEND_EVENT(fuse_iomap_direct_read_end);
 DEFINE_FUSE_IOMAP_FILE_IOEND_EVENT(fuse_iomap_direct_write_end);
+DEFINE_FUSE_IOMAP_FILE_IOEND_EVENT(fuse_iomap_buffered_read_end);
+DEFINE_FUSE_IOMAP_FILE_IOEND_EVENT(fuse_iomap_buffered_write_end);
 
 TRACE_EVENT(fuse_iomap_dio_write_end_io,
 	TP_PROTO(const struct inode *inode, loff_t pos, ssize_t written,
@@ -781,7 +797,214 @@ DEFINE_EVENT(fuse_iomap_file_range_class, name,         \
         TP_PROTO(const struct inode *inode, loff_t offset, loff_t length), \
         TP_ARGS(inode, offset, length))
 DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_setsize_finish);
+DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_truncate_up);
+DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_truncate_down);
+DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_punch_range);
+DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_flush_unmap_range);
 
+TRACE_EVENT(fuse_iomap_end_ioend,
+	TP_PROTO(const struct iomap_ioend *ioend),
+
+	TP_ARGS(ioend),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(unsigned int,		ioendflags)
+		__field(int,			error)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(ioend->io_inode, fi, fm);
+		__entry->offset		=	ioend->io_offset;
+		__entry->length		=	ioend->io_size;
+		__entry->ioendflags	=	ioend->io_flags;
+		__entry->error		=	blk_status_to_errno(ioend->io_bio.bi_status);
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() " ioendflags (%s) error %d",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __print_flags(__entry->ioendflags, "|", IOMAP_IOEND_STRINGS),
+		  __entry->error)
+);
+
+TRACE_EVENT(fuse_iomap_writeback_range,
+	TP_PROTO(const struct inode *inode, u64 offset, unsigned int count,
+		 u64 end_pos),
+
+	TP_ARGS(inode, offset, count, end_pos),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(uint64_t,		end_pos)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	offset;
+		__entry->length		=	count;
+		__entry->end_pos	=	end_pos;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() " end_pos 0x%llx",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __entry->end_pos)
+);
+
+TRACE_EVENT(fuse_iomap_writeback_submit,
+	TP_PROTO(const struct iomap_writepage_ctx *wpc, int error),
+
+	TP_ARGS(wpc, error),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(unsigned int,		nr_folios)
+		__field(uint64_t,		addr)
+		__field(int,			error)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(wpc->inode, fi, fm);
+		__entry->nr_folios	=	wpc->nr_folios;
+		__entry->offset		=	wpc->iomap.offset;
+		__entry->length		=	wpc->iomap.length;
+		__entry->addr		=	wpc->iomap.addr << 9;
+		__entry->error		=	error;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() " addr 0x%llx nr_folios %u error %d",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __entry->addr,
+		  __entry->nr_folios,
+		  __entry->error)
+);
+
+TRACE_EVENT(fuse_iomap_discard_folio,
+	TP_PROTO(const struct inode *inode, loff_t offset, size_t count),
+
+	TP_ARGS(inode, offset, count),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	offset;
+		__entry->length		=	count;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT(),
+		  FUSE_IO_RANGE_PRINTK_ARGS())
+);
+
+TRACE_EVENT(fuse_iomap_writepages,
+	TP_PROTO(const struct inode *inode, const struct writeback_control *wbc),
+
+	TP_ARGS(inode, wbc),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(long,			nr_to_write)
+		__field(bool,			sync_all)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	wbc->range_start;
+		__entry->length		=	wbc->range_end - wbc->range_start + 1;
+		__entry->nr_to_write	=	wbc->nr_to_write;
+		__entry->sync_all	=	wbc->sync_mode == WB_SYNC_ALL;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() " nr_folios %ld sync_all? %d",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __entry->nr_to_write,
+		  __entry->sync_all)
+);
+
+TRACE_EVENT(fuse_iomap_read_folio,
+	TP_PROTO(const struct folio *folio),
+
+	TP_ARGS(folio),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(folio->mapping->host, fi, fm);
+		__entry->offset		=	folio_pos(folio);
+		__entry->length		=	folio_size(folio);
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT(),
+		  FUSE_IO_RANGE_PRINTK_ARGS())
+);
+
+TRACE_EVENT(fuse_iomap_readahead,
+	TP_PROTO(const struct readahead_control *rac),
+
+	TP_ARGS(rac),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+	),
+
+	TP_fast_assign(
+		struct readahead_control *mutrac = (struct readahead_control *)rac;
+		FUSE_INODE_ASSIGN(file_inode(rac->file), fi, fm);
+		__entry->offset		=	readahead_pos(mutrac);
+		__entry->length		=	readahead_length(mutrac);
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT(),
+		  FUSE_IO_RANGE_PRINTK_ARGS())
+);
+
+TRACE_EVENT(fuse_iomap_page_mkwrite,
+	TP_PROTO(const struct vm_fault *vmf),
+
+	TP_ARGS(vmf),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+	),
+
+	TP_fast_assign(
+		struct folio *folio = page_folio(vmf->page);
+		FUSE_INODE_ASSIGN(file_inode(vmf->vma->vm_file), fi, fm);
+		__entry->offset		=	folio_pos(folio);
+		__entry->length		=	folio_size(folio);
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT(),
+		  FUSE_IO_RANGE_PRINTK_ARGS())
+);
+
+TRACE_EVENT(fuse_iomap_fallocate,
+	TP_PROTO(const struct inode *inode, int mode, loff_t offset,
+		 loff_t length, loff_t newsize),
+	TP_ARGS(inode, mode, offset, length, newsize),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		__field(loff_t,			newsize)
+		__field(int,			mode)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	offset;
+		__entry->length		=	length;
+		__entry->mode		=	mode;
+		__entry->newsize	=	newsize;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() " mode 0x%x newsize 0x%llx",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  __entry->mode,
+		  __entry->newsize)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/dev.c +10 -0
index a3d762fd4d9a86..c5593f35dcb675 100644
@@ -9,6 +9,7 @@
 #include "dev_uring_i.h"
 #include "fuse_i.h"
 #include "fuse_dev_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/init.h>
 #include <linux/module.h>
@@ -1790,6 +1791,12 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
 	if (!inode)
 		goto out_up_killsb;
 
+	/* no backchannels for messing with the pagecache */
+	if (fuse_inode_has_iomap(inode)) {
+		err = -EOPNOTSUPP;
+		goto out_iput;
+	}
+
 	mapping = inode->i_mapping;
 	index = outarg.offset >> PAGE_SHIFT;
 	offset = outarg.offset & ~PAGE_MASK;
@@ -1874,6 +1881,9 @@ static int fuse_retrieve(struct fuse_mount *fm, struct inode *inode,
 	struct fuse_args_pages *ap;
 	struct fuse_args *args;
 
+	if (fuse_inode_has_iomap(inode))
+		return -EOPNOTSUPP;
+
 	offset = outarg->offset & ~PAGE_MASK;
 	file_size = i_size_read(inode);
 
fs/fuse/fuse_iomap.c +38 -2
index 2097a83af833d5..b7c459acd0c93b 100644
@@ -1038,6 +1038,8 @@ fuse_iomap_write_zero_eof(
 		return 1;
 	}
 
+	trace_fuse_iomap_write_zero_eof(iocb, from);
+
 	filemap_invalidate_lock(mapping);
 	error = fuse_iomap_zero_range(inode, isize, iocb->ki_pos - isize, NULL);
 	filemap_invalidate_unlock(mapping);
@@ -1164,6 +1166,8 @@ static void fuse_iomap_end_ioend(struct iomap_ioend *ioend)
 	if (!error && fuse_is_bad(inode))
 		error = -EIO;
 
+	trace_fuse_iomap_end_ioend(ioend);
+
 	if (ioend->io_flags & IOMAP_IOEND_SHARED)
 		ioendflags |= FUSE_IOMAP_IOEND_SHARED;
 	if (ioend->io_flags & IOMAP_IOEND_UNWRITTEN)
@@ -1272,6 +1276,8 @@ static void fuse_iomap_discard_folio(struct folio *folio, loff_t pos, int error)
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_discard_folio(inode, pos, folio_size(folio));
+
 	printk_ratelimited(KERN_ERR
 		"page discard on page %px, inode 0x%llx, pos %llu.",
 			folio, fi->orig_ino, pos);
@@ -1296,6 +1302,8 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_writeback_range(inode, offset, len, end_pos);
+
 	if (!fuse_iomap_revalidate_writeback(wpc, offset)) {
 		ret = fuse_iomap_begin(inode, offset, len,
 				       FUSE_IOMAP_OP_WRITEBACK,
@@ -1333,6 +1341,8 @@ static int fuse_iomap_writeback_submit(struct iomap_writepage_ctx *wpc,
 
 	ASSERT(fuse_inode_has_iomap(ioend->io_inode));
 
+	trace_fuse_iomap_writeback_submit(wpc, error);
+
 	/* always call our ioend function, even if we cancel the bio */
 	ioend->io_bio.bi_end_io = fuse_iomap_end_bio;
 	return iomap_ioend_writeback_submit(wpc, error);
@@ -1356,6 +1366,8 @@ static int fuse_iomap_writepages(struct address_space *mapping,
 
 	ASSERT(fuse_inode_has_iomap(mapping->host));
 
+	trace_fuse_iomap_writepages(mapping->host, wbc);
+
 	return iomap_writepages(&wpc.ctx);
 }
 
@@ -1363,6 +1375,8 @@ static int fuse_iomap_read_folio(struct file *file, struct folio *folio)
 {
 	ASSERT(fuse_inode_has_iomap(file_inode(file)));
 
+	trace_fuse_iomap_read_folio(folio);
+
 	iomap_bio_read_folio(folio, &fuse_iomap_ops);
 	return 0;
 }
@@ -1371,6 +1385,8 @@ static void fuse_iomap_readahead(struct readahead_control *rac)
 {
 	ASSERT(fuse_inode_has_iomap(file_inode(rac->file)));
 
+	trace_fuse_iomap_readahead(rac);
+
 	iomap_bio_readahead(rac, &fuse_iomap_ops);
 }
 
@@ -1419,6 +1435,8 @@ static vm_fault_t fuse_iomap_page_mkwrite(struct vm_fault *vmf)
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_page_mkwrite(vmf);
+
 	sb_start_pagefault(inode->i_sb);
 	file_update_time(vmf->vma->vm_file);
 
@@ -1452,6 +1470,8 @@ static ssize_t fuse_iomap_buffered_read(struct kiocb *iocb, struct iov_iter *to)
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_buffered_read(iocb, to);
+
 	if (!iov_iter_count(to))
 		return 0; /* skip atime */
 
@@ -1463,6 +1483,7 @@ static ssize_t fuse_iomap_buffered_read(struct kiocb *iocb, struct iov_iter *to)
 		file_accessed(iocb->ki_filp);
 	inode_unlock_shared(inode);
 
+	trace_fuse_iomap_buffered_read_end(iocb, to, ret);
 	return ret;
 }
 
@@ -1476,6 +1497,8 @@ static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb,
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_buffered_write(iocb, from);
+
 	if (!iov_iter_count(from))
 		return 0;
 
@@ -1504,6 +1527,7 @@ static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb,
 		/* Handle various SYNC-type writes */
 		ret = generic_write_sync(iocb, ret);
 	}
+	trace_fuse_iomap_buffered_write_end(iocb, from, ret);
 	return ret;
 }
 
@@ -1622,11 +1646,17 @@ fuse_iomap_setsize_start(
 	 * extension, or zeroing out the rest of the block on a downward
 	 * truncate.
 	 */
-	if (newsize > oldsize)
+	if (newsize > oldsize) {
+		trace_fuse_iomap_truncate_up(inode, oldsize, newsize - oldsize);
+
 		error = fuse_iomap_zero_range(inode, oldsize, newsize - oldsize,
 					      &did_zeroing);
-	else
+	} else {
+		trace_fuse_iomap_truncate_down(inode, newsize,
+					       oldsize - newsize);
+
 		error = fuse_iomap_truncate_page(inode, newsize, &did_zeroing);
+	}
 	if (error)
 		return error;
 
@@ -1673,6 +1703,8 @@ int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 	start = round_down(pos, rounding);
 	end = round_up(endpos + 1, rounding) - 1;
 
+	trace_fuse_iomap_flush_unmap_range(inode, start, end + 1 - start);
+
 	error = filemap_write_and_wait_range(inode->i_mapping, start, end);
 	if (error)
 		return error;
@@ -1686,6 +1718,8 @@ static int fuse_iomap_punch_range(struct inode *inode, loff_t offset,
 	loff_t isize = i_size_read(inode);
 	int error;
 
+	trace_fuse_iomap_punch_range(inode, offset, length);
+
 	/*
 	 * Now that we've unmap all full blocks we'll have to zero out any
 	 * partial block at the beginning and/or end.  iomap_zero_range is
@@ -1729,6 +1763,8 @@ fuse_iomap_fallocate(
 
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_fallocate(inode, mode, offset, length, new_size);
+
 	/*
 	 * If we unmapped blocks from the file range, then we zero the
 	 * pagecache for those regions and push them to disk rather than make
#50 lore raw

PATCH 18/33 fuse: use an unrestricted backing device with iomap pagecache io

In reply to Darrick J. Wong

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

With iomap support turned on for the pagecache, the kernel issues writeback to directly to block devices and we no longer have to push all those pages through the fuse device to userspace. Therefore, we don't need the tight dirty limits (~1M) that are used for regular fuse. This dramatically increases the performance of fuse's pagecache IO.

A reviewer of this patch asked why we reset s_bdi to the noop bdi and call super_setup_bdi_name a second time, instead of simply clearing STRICTLIMIT and resetting the bdi max ratio.

That's sufficient to undo the effects of fuse_bdi_init, yes. However the BDI gets created with the name "$major:$minor{-fuseblk}" and there are "management" scripts that try to tweak fuse BDIs for better performance.

I don't want some dumb script to mismanage a fuse-iomap filesystem because it can't tell the difference, so I create a new bdi with the name "$major:$minor.iomap" to make it obvious. But super_setup_bdi_name gets cranky if s_bdi isn't set to noop and we don't want to fail a mount here due to ENOMEM so ... I implemented this weird switcheroo code.

Also, userspace scripts such as udev rules can modify the bdi as soon as it appears in sysfs, so we can't run the fuse_bdi_init code in reverse and expect that will undo everything.

---
 fs/fuse/fuse_iomap.c |   21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
fs/fuse/fuse_iomap.c +21 -0
index b7c459acd0c93b..5690e5d079807b 100644
@@ -721,6 +721,27 @@ const struct fuse_backing_ops fuse_iomap_backing_ops = {
 void fuse_iomap_mount(struct fuse_mount *fm)
 {
 	struct fuse_conn *fc = fm->fc;
+	struct super_block *sb = fm->sb;
+	struct backing_dev_info *old_bdi = sb->s_bdi;
+	char *suffix = sb->s_bdev ? "-fuseblk" : "-fuse";
+	int res;
+
+	/*
+	 * sb->s_bdi points to the initial private bdi.  However, we want to
+	 * redirect it to a new private bdi with default dirty and readahead
+	 * settings because iomap writeback won't be pushing a ton of dirty
+	 * data through the fuse device.  If this fails we fall back to the
+	 * initial fuse bdi.
+	 */
+	sb->s_bdi = &noop_backing_dev_info;
+	res = super_setup_bdi_name(sb, "%u:%u%s.iomap", MAJOR(fc->dev),
+				   MINOR(fc->dev), suffix);
+	if (res) {
+		sb->s_bdi = old_bdi;
+	} else {
+		bdi_unregister(old_bdi);
+		bdi_put(old_bdi);
+	}
 
 	/*
 	 * Enable syncfs for iomap fuse servers so that we can send a final
#51 lore raw

PATCH 19/33 fuse: implement large folios for iomap pagecache files

In reply to Darrick J. Wong

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

Use large folios when we're using iomap.

---
 fs/fuse/fuse_iomap.c |    6 ++++++
 1 file changed, 6 insertions(+)
fs/fuse/fuse_iomap.c +6 -0
index 5690e5d079807b..70b6fb922fc9ec 100644
@@ -1429,12 +1429,18 @@ static const struct address_space_operations fuse_iomap_aops = {
 static inline void fuse_inode_set_iomap(struct inode *inode)
 {
 	struct fuse_inode *fi = get_fuse_inode(inode);
+	unsigned int min_order = 0;
 
 	inode->i_data.a_ops = &fuse_iomap_aops;
 
 	INIT_WORK(&fi->ioend_work, fuse_iomap_end_io);
 	INIT_LIST_HEAD(&fi->ioend_list);
 	spin_lock_init(&fi->ioend_lock);
+
+	if (inode->i_blkbits > PAGE_SHIFT)
+		min_order = inode->i_blkbits - PAGE_SHIFT;
+
+	mapping_set_folio_min_order(inode->i_mapping, min_order);
 	set_bit(FUSE_I_IOMAP, &fi->state);
 }
 
#52 lore raw

PATCH 20/33 fuse: advertise support for iomap

In reply to Darrick J. Wong

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

Advertise our new IO paths programmatically by creating an ioctl that can return the capabilities of the kernel.

---
 fs/fuse/fuse_iomap.h      |    4 ++++
 include/uapi/linux/fuse.h |    9 +++++++++
 fs/fuse/dev.c             |    3 +++
 fs/fuse/fuse_iomap.c      |   13 +++++++++++++
 4 files changed, 29 insertions(+)
fs/fuse/fuse_iomap.h +4 -0
index 4b12af01ff00f5..9a1051638a6ff4 100644
@@ -60,6 +60,9 @@ int fuse_iomap_fallocate(struct file *file, int mode, loff_t offset,
 			 loff_t length, loff_t new_size);
 int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 				 loff_t endpos);
+
+int fuse_dev_ioctl_iomap_support(struct file *file,
+				 struct fuse_iomap_support __user *argp);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -83,6 +86,7 @@ int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 # define fuse_iomap_setsize_start(...)		(-ENOSYS)
 # define fuse_iomap_fallocate(...)		(-ENOSYS)
 # define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
+# define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +9 -0
index 71b216262c84cb..de9b56e6e8d250 100644
@@ -1156,6 +1156,13 @@ struct fuse_backing_map {
 	uint64_t	padding;
 };
 
+/* basic file I/O functionality through iomap */
+#define FUSE_IOMAP_SUPPORT_FILEIO	(1ULL << 0)
+struct fuse_iomap_support {
+	uint64_t	flags;
+	uint64_t	padding;
+};
+
 /* Device ioctls: */
 #define FUSE_DEV_IOC_MAGIC		229
 #define FUSE_DEV_IOC_CLONE		_IOR(FUSE_DEV_IOC_MAGIC, 0, uint32_t)
@@ -1163,6 +1170,8 @@ struct fuse_backing_map {
 					     struct fuse_backing_map)
 #define FUSE_DEV_IOC_BACKING_CLOSE	_IOW(FUSE_DEV_IOC_MAGIC, 2, uint32_t)
 #define FUSE_DEV_IOC_SYNC_INIT		_IO(FUSE_DEV_IOC_MAGIC, 3)
+#define FUSE_DEV_IOC_IOMAP_SUPPORT	_IOR(FUSE_DEV_IOC_MAGIC, 99, \
+					     struct fuse_iomap_support)
 
 struct fuse_lseek_in {
 	uint64_t	fh;
fs/fuse/dev.c +3 -0
index c5593f35dcb675..39d3c36774de55 100644
@@ -2713,6 +2713,9 @@ static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
 	case FUSE_DEV_IOC_SYNC_INIT:
 		return fuse_dev_ioctl_sync_init(file);
 
+	case FUSE_DEV_IOC_IOMAP_SUPPORT:
+		return fuse_dev_ioctl_iomap_support(file, argp);
+
 	default:
 		return -ENOTTY;
 	}
fs/fuse/fuse_iomap.c +13 -0
index 70b6fb922fc9ec..3395b1cd907afa 100644
@@ -1818,3 +1818,16 @@ fuse_iomap_fallocate(
 	file_update_time(file);
 	return 0;
 }
+
+int fuse_dev_ioctl_iomap_support(struct file *file,
+				 struct fuse_iomap_support __user *argp)
+{
+	struct fuse_iomap_support ios = { };
+
+	if (fuse_iomap_enabled())
+		ios.flags = FUSE_IOMAP_SUPPORT_FILEIO;
+
+	if (copy_to_user(argp, &ios, sizeof(ios)))
+		return -EFAULT;
+	return 0;
+}
#53 lore raw

PATCH 21/33 fuse: query filesystem geometry when using iomap

In reply to Darrick J. Wong

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

Add a new upcall to the fuse server so that the kernel can request filesystem geometry bits when iomap mode is in use.

---
 fs/fuse/fuse_i.h          |    4 +
 fs/fuse/fuse_iomap.h      |    6 +-
 include/uapi/linux/fuse.h |   39 ++++++++++++
 fs/fuse/fuse_iomap.c      |  147 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c           |   42 ++++++++++---
 5 files changed, 227 insertions(+), 11 deletions(-)
fs/fuse/fuse_i.h +4 -0
index b9f41c08cc8fb0..153aa441a78320 100644
@@ -1037,6 +1037,9 @@ struct fuse_conn {
 	struct fuse_ring *ring;
 #endif
 
+	/** How many subsystems still need initialization? */
+	atomic_t need_init;
+
 	/** Only used if the connection opts into request timeouts */
 	struct {
 		/* Worker for checking if any requests have timed out */
@@ -1450,6 +1453,7 @@ struct fuse_dev *fuse_dev_alloc(void);
 void fuse_dev_install(struct fuse_dev *fud, struct fuse_conn *fc);
 void fuse_dev_free(struct fuse_dev *fud);
 int fuse_send_init(struct fuse_mount *fm);
+void fuse_finish_init(struct fuse_conn *fc, bool ok);
 
 /**
  * Fill in superblock and initialize fuse connection
fs/fuse/fuse_iomap.h +4 -2
index 9a1051638a6ff4..f80c1eae098af3 100644
@@ -21,7 +21,8 @@ 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);
+int fuse_iomap_mount(struct fuse_mount *fm);
+void fuse_iomap_mount_async(struct fuse_mount *fm);
 void fuse_iomap_unmount(struct fuse_mount *fm);
 
 void fuse_iomap_init_inode(struct inode *inode, struct fuse_attr *attr);
@@ -66,7 +67,8 @@ int fuse_dev_ioctl_iomap_support(struct file *file,
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
-# define fuse_iomap_mount(...)			((void)0)
+# define fuse_iomap_mount(...)			(0)
+# define fuse_iomap_mount_async(...)		((void)0)
 # define fuse_iomap_unmount(...)		((void)0)
 # define fuse_iomap_init_inode(...)		((void)0)
 # define fuse_iomap_evict_inode(...)		((void)0)
include/uapi/linux/fuse.h +39 -0
index de9b56e6e8d250..33668d66e9c4b4 100644
@@ -246,6 +246,7 @@
  *  - add FUSE_IOMAP and iomap_{begin,end,ioend} for regular file operations
  *  - add FUSE_ATTR_EXCLUSIVE to enable exclusive mode for specific inodes
  *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
+ *  - add FUSE_IOMAP_CONFIG so the fuse server can configure more fs geometry
  */
 
 #ifndef _LINUX_FUSE_H
@@ -677,6 +678,7 @@ enum fuse_opcode {
 	FUSE_STATX		= 52,
 	FUSE_COPY_FILE_RANGE_64	= 53,
 
+	FUSE_IOMAP_CONFIG	= 4092,
 	FUSE_IOMAP_IOEND	= 4093,
 	FUSE_IOMAP_BEGIN	= 4094,
 	FUSE_IOMAP_END		= 4095,
@@ -1452,4 +1454,41 @@ struct fuse_iomap_ioend_out {
 	uint64_t newsize;	/* new ondisk size */
 };
 
+struct fuse_iomap_config_in {
+	uint64_t flags;		/* supported FUSE_IOMAP_CONFIG_* flags */
+	int64_t maxbytes;	/* maximum supported file size */
+	uint64_t padding[6];	/* zero */
+};
+
+/* Which fields are set in fuse_iomap_config_out? */
+#define FUSE_IOMAP_CONFIG_SID		(1 << 0ULL)
+#define FUSE_IOMAP_CONFIG_UUID		(1 << 1ULL)
+#define FUSE_IOMAP_CONFIG_BLOCKSIZE	(1 << 2ULL)
+#define FUSE_IOMAP_CONFIG_MAX_LINKS	(1 << 3ULL)
+#define FUSE_IOMAP_CONFIG_TIME		(1 << 4ULL)
+#define FUSE_IOMAP_CONFIG_MAXBYTES	(1 << 5ULL)
+
+struct fuse_iomap_config_out {
+	uint64_t flags;		/* FUSE_IOMAP_CONFIG_* */
+
+	char s_id[32];		/* Informational name */
+	char s_uuid[16];	/* UUID */
+
+	uint8_t s_uuid_len;	/* length of s_uuid */
+
+	uint8_t s_pad[3];	/* must be zeroes */
+
+	uint32_t s_blocksize;	/* fs block size */
+	uint32_t s_max_links;	/* max hard links */
+
+	/* Granularity of c/m/atime in ns (cannot be worse than a second) */
+	uint32_t s_time_gran;
+
+	/* Time limits for c/m/atime in seconds */
+	int64_t s_time_min;
+	int64_t s_time_max;
+
+	int64_t s_maxbytes;	/* max file size */
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/fuse_iomap.c +146 -1

166 lines not on this page · raw message

fs/fuse/inode.c +34 -8

69 lines not on this page · raw message

#54 lore raw

PATCH 22/33 fuse_trace: query filesystem geometry when using iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   48 ++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    2 ++
 2 files changed, 50 insertions(+)
fs/fuse/fuse_trace.h +48 -0
index c832fb9012d983..96c4db84c7106a 100644
@@ -58,6 +58,7 @@
 	EM( FUSE_SYNCFS,		"FUSE_SYNCFS")		\
 	EM( FUSE_TMPFILE,		"FUSE_TMPFILE")		\
 	EM( FUSE_STATX,			"FUSE_STATX")		\
+	EM( FUSE_IOMAP_CONFIG,		"FUSE_IOMAP_CONFIG")	\
 	EM( FUSE_IOMAP_BEGIN,		"FUSE_IOMAP_BEGIN")	\
 	EM( FUSE_IOMAP_END,		"FUSE_IOMAP_END")	\
 	EM( FUSE_IOMAP_IOEND,		"FUSE_IOMAP_IOEND")	\
@@ -345,6 +346,14 @@ TRACE_DEFINE_ENUM(FUSE_I_IOMAP);
 	{ IOMAP_IOEND_BOUNDARY,			"boundary" }, \
 	{ IOMAP_IOEND_DIRECT,			"direct" }
 
+#define FUSE_IOMAP_CONFIG_STRINGS \
+	{ FUSE_IOMAP_CONFIG_SID,		"sid" }, \
+	{ FUSE_IOMAP_CONFIG_UUID,		"uuid" }, \
+	{ FUSE_IOMAP_CONFIG_BLOCKSIZE,		"blocksize" }, \
+	{ FUSE_IOMAP_CONFIG_MAX_LINKS,		"max_links" }, \
+	{ FUSE_IOMAP_CONFIG_TIME,		"time" }, \
+	{ FUSE_IOMAP_CONFIG_MAXBYTES,		"maxbytes" }
+
 DECLARE_EVENT_CLASS(fuse_iomap_check_class,
 	TP_PROTO(const char *func, int line, const char *condition),
 
@@ -1005,6 +1014,45 @@ TRACE_EVENT(fuse_iomap_fallocate,
 		  __entry->mode,
 		  __entry->newsize)
 );
+
+TRACE_EVENT(fuse_iomap_config,
+	TP_PROTO(const struct fuse_mount *fm,
+		 const struct fuse_iomap_config_out *outarg),
+	TP_ARGS(fm, outarg),
+
+	TP_STRUCT__entry(
+		__field(dev_t,			connection)
+
+		__field(uint64_t,		flags)
+		__field(uint32_t,		blocksize)
+		__field(uint32_t,		max_links)
+		__field(uint32_t,		time_gran)
+
+		__field(int64_t,		time_min)
+		__field(int64_t,		time_max)
+		__field(int64_t,		maxbytes)
+		__field(uint8_t,		uuid_len)
+	),
+
+	TP_fast_assign(
+		__entry->connection	=	fm->fc->dev;
+		__entry->flags		=	outarg->flags;
+		__entry->blocksize	=	outarg->s_blocksize;
+		__entry->max_links	=	outarg->s_max_links;
+		__entry->time_gran	=	outarg->s_time_gran;
+		__entry->time_min	=	outarg->s_time_min;
+		__entry->time_max	=	outarg->s_time_max;
+		__entry->maxbytes	=	outarg->s_maxbytes;
+		__entry->uuid_len	=	outarg->s_uuid_len;
+	),
+
+	TP_printk("connection %u flags (%s) blocksize 0x%x max_links %u time_gran %u time_min %lld time_max %lld maxbytes 0x%llx uuid_len %u",
+		  __entry->connection,
+		  __print_flags(__entry->flags, "|", FUSE_IOMAP_CONFIG_STRINGS),
+		  __entry->blocksize, __entry->max_links, __entry->time_gran,
+		  __entry->time_min, __entry->time_max, __entry->maxbytes,
+		  __entry->uuid_len)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +2 -0
index d9be7d47fb7acd..b7614674fae9e5 100644
@@ -745,6 +745,8 @@ static int fuse_iomap_process_config(struct fuse_mount *fm, int error,
 		return error;
 	}
 
+	trace_fuse_iomap_config(fm, outarg);
+
 	if (outarg->flags & ~FUSE_IOMAP_CONFIG_ALL)
 		return -EINVAL;
 
#55 lore raw

PATCH 23/33 fuse: implement fadvise for iomap files

In reply to Darrick J. Wong

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

If userspace asks us to perform readahead on a file, take i_rwsem so that it can't race with hole punching or writes.

---
 fs/fuse/fuse_iomap.h |    3 +++
 fs/fuse/file.c       |    1 +
 fs/fuse/fuse_iomap.c |   20 ++++++++++++++++++++
 3 files changed, 24 insertions(+)
fs/fuse/fuse_iomap.h +3 -0
index f80c1eae098af3..3e5df67db2a1fe 100644
@@ -64,6 +64,8 @@ int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 
 int fuse_dev_ioctl_iomap_support(struct file *file,
 				 struct fuse_iomap_support __user *argp);
+
+int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -89,6 +91,7 @@ int fuse_dev_ioctl_iomap_support(struct file *file,
 # define fuse_iomap_fallocate(...)		(-ENOSYS)
 # define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
+# define fuse_iomap_fadvise			NULL
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
fs/fuse/file.c +1 -0
index 0828ecb20a828c..1243d0eea22a37 100644
@@ -3252,6 +3252,7 @@ static const struct file_operations fuse_file_operations = {
 	.fallocate	= fuse_file_fallocate,
 	.copy_file_range = fuse_copy_file_range,
 	.setlease	= generic_setlease,
+	.fadvise	= fuse_iomap_fadvise,
 };
 
 static const struct address_space_operations fuse_file_aops  = {
fs/fuse/fuse_iomap.c +20 -0
index b7614674fae9e5..df92740f1e781b 100644
@@ -7,6 +7,7 @@
 #include <linux/fiemap.h>
 #include <linux/pagemap.h>
 #include <linux/falloc.h>
+#include <linux/fadvise.h>
 #include "fuse_i.h"
 #include "fuse_trace.h"
 #include "fuse_iomap.h"
@@ -1978,3 +1979,22 @@ int fuse_dev_ioctl_iomap_support(struct file *file,
 		return -EFAULT;
 	return 0;
 }
+
+int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice)
+{
+	struct inode *inode = file_inode(file);
+	bool needlock = advice == POSIX_FADV_WILLNEED &&
+			fuse_inode_has_iomap(inode);
+	int ret;
+
+	/*
+	 * Operations creating pages in page cache need protection from hole
+	 * punching and similar ops
+	 */
+	if (needlock)
+		inode_lock_shared(inode);
+	ret = generic_fadvise(file, start, end, advice);
+	if (needlock)
+		inode_unlock_shared(inode);
+	return ret;
+}
#56 lore raw

PATCH 24/33 fuse: invalidate ranges of block devices being used for iomap

In reply to Darrick J. Wong

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

Make it easier to invalidate the page cache for a block device that is being used in conjunction with iomap. This allows a fuse server to kill all cached data for a block that is being freed, so that block reuse doesn't result in file corruption. Right now, the only way to do this is with fadvise, which ignores and doesn't wait for pages undergoing writeback.

---
 fs/fuse/fuse_iomap.h      |    3 +++
 include/uapi/linux/fuse.h |   16 ++++++++++++++++
 fs/fuse/dev.c             |   27 +++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c      |   41 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 87 insertions(+)
fs/fuse/fuse_iomap.h +3 -0
index 3e5df67db2a1fe..d4a4d9f0313edf 100644
@@ -64,6 +64,8 @@ int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 
 int fuse_dev_ioctl_iomap_support(struct file *file,
 				 struct fuse_iomap_support __user *argp);
+int fuse_iomap_dev_inval(struct fuse_conn *fc,
+			 const struct fuse_iomap_dev_inval_out *arg);
 
 int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
 #else
@@ -91,6 +93,7 @@ int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
 # define fuse_iomap_fallocate(...)		(-ENOSYS)
 # define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
+# define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
 #endif /* CONFIG_FUSE_IOMAP */
 
include/uapi/linux/fuse.h +16 -0
index 33668d66e9c4b4..1ef7152306a24f 100644
@@ -247,6 +247,7 @@
  *  - add FUSE_ATTR_EXCLUSIVE to enable exclusive mode for specific inodes
  *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  *  - add FUSE_IOMAP_CONFIG so the fuse server can configure more fs geometry
+ *  - add FUSE_NOTIFY_IOMAP_DEV_INVAL to invalidate iomap bdev ranges
  */
 
 #ifndef _LINUX_FUSE_H
@@ -701,6 +702,8 @@ enum fuse_notify_code {
 	FUSE_NOTIFY_RESEND = 7,
 	FUSE_NOTIFY_INC_EPOCH = 8,
 	FUSE_NOTIFY_PRUNE = 9,
+	FUSE_NOTIFY_IOMAP_DEV_INVAL = 99,
+	FUSE_NOTIFY_CODE_MAX,
 };
 
 /* The read buffer is required to be at least 8k, but may be much larger */
@@ -1491,4 +1494,17 @@ struct fuse_iomap_config_out {
 	int64_t s_maxbytes;	/* max file size */
 };
 
+struct fuse_range {
+	uint64_t offset;
+	uint64_t length;
+};
+
+struct fuse_iomap_dev_inval_out {
+	uint32_t dev;		/* device cookie */
+	uint32_t reserved;	/* zero */
+
+	/* range of bdev pagecache to invalidate, in bytes */
+	struct fuse_range range;
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/dev.c +27 -0
index 39d3c36774de55..9a814a0d222fe6 100644
@@ -1849,6 +1849,30 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
 	return err;
 }
 
+static int fuse_notify_iomap_dev_inval(struct fuse_conn *fc, unsigned int size,
+				       struct fuse_copy_state *cs)
+{
+	struct fuse_iomap_dev_inval_out outarg;
+	int err = -EINVAL;
+
+	if (size != sizeof(outarg))
+		goto err;
+
+	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
+	if (err)
+		goto err;
+	if (outarg.reserved) {
+		err = -EINVAL;
+		goto err;
+	}
+	fuse_copy_finish(cs);
+
+	return fuse_iomap_dev_inval(fc, &outarg);
+err:
+	fuse_copy_finish(cs);
+	return err;
+}
+
 struct fuse_retrieve_args {
 	struct fuse_args_pages ap;
 	struct fuse_notify_retrieve_in inarg;
@@ -2133,6 +2157,9 @@ static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
 	case FUSE_NOTIFY_PRUNE:
 		return fuse_notify_prune(fc, size, cs);
 
+	case FUSE_NOTIFY_IOMAP_DEV_INVAL:
+		return fuse_notify_iomap_dev_inval(fc, size, cs);
+
 	default:
 		return -EINVAL;
 	}
fs/fuse/fuse_iomap.c +41 -0

44 lines not on this page · raw message

#57 lore raw

PATCH 25/33 fuse_trace: invalidate ranges of block devices being used for iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   26 ++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    2 ++
 2 files changed, 28 insertions(+)
fs/fuse/fuse_trace.h +26 -0
index 96c4db84c7106a..0e4be645802055 100644
@@ -1053,6 +1053,32 @@ TRACE_EVENT(fuse_iomap_config,
 		  __entry->time_min, __entry->time_max, __entry->maxbytes,
 		  __entry->uuid_len)
 );
+
+TRACE_EVENT(fuse_iomap_dev_inval,
+	TP_PROTO(const struct fuse_conn *fc,
+		 const struct fuse_iomap_dev_inval_out *arg),
+	TP_ARGS(fc, arg),
+
+	TP_STRUCT__entry(
+		__field(dev_t,			connection)
+		__field(int,			dev)
+		__field(unsigned long long,	offset)
+		__field(unsigned long long,	length)
+	),
+
+	TP_fast_assign(
+		__entry->connection	=	fc->dev;
+		__entry->dev		=	arg->dev;
+		__entry->offset		=	arg->range.offset;
+		__entry->length		=	arg->range.length;
+	),
+
+	TP_printk("connection %u dev %d offset 0x%llx length 0x%llx",
+		  __entry->connection,
+		  __entry->dev,
+		  __entry->offset,
+		  __entry->length)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +2 -0
index 21c286c285a59d..e8a0c1ceb409c4 100644
@@ -2007,6 +2007,8 @@ int fuse_iomap_dev_inval(struct fuse_conn *fc,
 	loff_t end;
 	int ret = 0;
 
+	trace_fuse_iomap_dev_inval(fc, arg);
+
 	if (!fc->iomap || arg->dev == FUSE_IOMAP_DEV_NULL)
 		return -EINVAL;
 
#58 lore raw

PATCH 26/33 fuse: implement inline data file IO via iomap

In reply to Darrick J. Wong

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

Implement inline data file IO by issuing FUSE_READ/FUSE_WRITE commands in response to an inline data mapping.

---
 fs/fuse/fuse_iomap.c |  205 ++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 197 insertions(+), 8 deletions(-)
fs/fuse/fuse_iomap.c +197 -8
index e8a0c1ceb409c4..1c3d99f11634d2 100644
@@ -398,6 +398,152 @@ fuse_iomap_find_dev(struct fuse_conn *fc, const struct fuse_iomap_io *map)
 	return ret;
 }
 
+static inline int fuse_iomap_inline_alloc(struct iomap *iomap)
+{
+	ASSERT(iomap->inline_data == NULL);
+	ASSERT(iomap->length > 0);
+
+	iomap->inline_data = kvzalloc(iomap->length, GFP_KERNEL);
+	return iomap->inline_data ? 0 : -ENOMEM;
+}
+
+static inline void fuse_iomap_inline_free(struct iomap *iomap)
+{
+	kvfree(iomap->inline_data);
+	iomap->inline_data = NULL;
+}
+
+/*
+ * Use the FUSE_READ command to read inline file data from the fuse server.
+ * Note that there's no file handle attached, so the fuse server must be able
+ * to reconnect to the inode via the nodeid.
+ */
+static int fuse_iomap_inline_read(struct inode *inode, loff_t pos,
+				  loff_t count, struct iomap *iomap)
+{
+	struct fuse_read_in in = {
+		.offset = pos,
+		.size = count,
+	};
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_mount *fm = get_fuse_mount(inode);
+	FUSE_ARGS(args);
+	ssize_t ret;
+
+	if (BAD_DATA(!iomap_inline_data_valid(iomap))) {
+		fuse_iomap_inline_free(iomap);
+		return -EFSCORRUPTED;
+	}
+
+	args.opcode = FUSE_READ;
+	args.nodeid = fi->nodeid;
+	args.in_numargs = 1;
+	args.in_args[0].size = sizeof(in);
+	args.in_args[0].value = &in;
+	args.out_argvar = true;
+	args.out_numargs = 1;
+	args.out_args[0].size = count;
+	args.out_args[0].value = iomap_inline_data(iomap, pos);
+
+	ret = fuse_simple_request(fm, &args);
+	if (ret < 0) {
+		fuse_iomap_inline_free(iomap);
+		return ret;
+	}
+	/* no readahead means something bad happened */
+	if (ret == 0) {
+		fuse_iomap_inline_free(iomap);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+/*
+ * Use the FUSE_WRITE command to write inline file data from the fuse server.
+ * Note that there's no file handle attached, so the fuse server must be able
+ * to reconnect to the inode via the nodeid.
+ */
+static int fuse_iomap_inline_write(struct inode *inode, loff_t pos,
+				   loff_t count, struct iomap *iomap)
+{
+	struct fuse_write_in in = {
+		.offset = pos,
+		.size = count,
+	};
+	struct fuse_write_out out = { };
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_mount *fm = get_fuse_mount(inode);
+	FUSE_ARGS(args);
+	ssize_t ret;
+
+	if (BAD_DATA(!iomap_inline_data_valid(iomap)))
+		return -EFSCORRUPTED;
+
+	args.opcode = FUSE_WRITE;
+	args.nodeid = fi->nodeid;
+	args.in_numargs = 2;
+	args.in_args[0].size = sizeof(in);
+	args.in_args[0].value = &in;
+	args.in_args[1].size = count;
+	args.in_args[1].value = iomap_inline_data(iomap, pos);
+	args.out_numargs = 1;
+	args.out_args[0].size = sizeof(out);
+	args.out_args[0].value = &out;
+
+	ret = fuse_simple_request(fm, &args);
+	if (ret < 0) {
+		fuse_iomap_inline_free(iomap);
+		return ret;
+	}
+	/* short write means something bad happened */
+	if (out.size < count) {
+		fuse_iomap_inline_free(iomap);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+/* Set up inline data buffers for iomap_begin */
+static int fuse_iomap_set_inline(struct inode *inode, unsigned opflags,
+				 loff_t pos, loff_t count,
+				 struct iomap *iomap, struct iomap *srcmap)
+{
+	int err;
+
+	if (opflags & IOMAP_REPORT)
+		return 0;
+
+	if (fuse_is_iomap_file_write(opflags)) {
+		if (iomap->type == IOMAP_INLINE) {
+			err = fuse_iomap_inline_alloc(iomap);
+			if (err)
+				return err;
+		}
+
+		if (srcmap->type == IOMAP_INLINE) {
+			err = fuse_iomap_inline_alloc(srcmap);
+			if (!err)
+				err = fuse_iomap_inline_read(inode, pos, count,
+							     srcmap);
+			if (err) {
+				fuse_iomap_inline_free(iomap);
+				return err;
+			}
+		}
+	} else if (iomap->type == IOMAP_INLINE) {
+		/* inline data read */
+		err = fuse_iomap_inline_alloc(iomap);
+		if (!err)
+			err = fuse_iomap_inline_read(inode, pos, count, iomap);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+
 static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 			    unsigned opflags, struct iomap *iomap,
 			    struct iomap *srcmap)
@@ -467,12 +613,20 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 		fuse_iomap_from_server(iomap, read_dev, &outarg.read);
 	}
 
+	if (iomap->type == IOMAP_INLINE || srcmap->type == IOMAP_INLINE) {
+		err = fuse_iomap_set_inline(inode, opflags, pos, count, iomap,
+					    srcmap);
+		if (err)
+			goto out_write_dev;
+	}
+
 	/*
 	 * 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.
 	 */
+out_write_dev:
 	fuse_backing_put(write_dev);
 out_read_dev:
 	fuse_backing_put(read_dev);
@@ -511,8 +665,28 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 {
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	struct fuse_mount *fm = get_fuse_mount(inode);
+	struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
+	struct iomap *srcmap = &iter->srcmap;
 	int err;
 
+	if (srcmap->inline_data)
+		fuse_iomap_inline_free(srcmap);
+
+	if (iomap->inline_data) {
+		if (fuse_is_iomap_file_write(opflags) && written > 0) {
+			err = fuse_iomap_inline_write(inode, pos, written,
+						      iomap);
+			fuse_iomap_inline_free(iomap);
+			if (err)
+				return err;
+		} else {
+			fuse_iomap_inline_free(iomap);
+		}
+
+		/* fuse server should already be aware of what happened */
+		return 0;
+	}
+
 	if (fuse_should_send_iomap_end(fm, iomap, opflags, count, written)) {
 		struct fuse_iomap_end_in inarg = {
 			.opflags = fuse_iomap_op_to_server(opflags),
@@ -1461,7 +1635,6 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
 					  unsigned int len, u64 end_pos)
 {
 	struct inode *inode = wpc->inode;
-	struct iomap write_iomap, dontcare;
 	ssize_t ret;
 
 	if (fuse_is_bad(inode)) {
@@ -1474,23 +1647,39 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
 	trace_fuse_iomap_writeback_range(inode, offset, len, end_pos);
 
 	if (!fuse_iomap_revalidate_writeback(wpc, offset)) {
+		struct iomap_iter fake_iter = { };
+		struct iomap *write_iomap = &fake_iter.iomap;
+
 		ret = fuse_iomap_begin(inode, offset, len,
-				       FUSE_IOMAP_OP_WRITEBACK,
-				       &write_iomap, &dontcare);
+				       FUSE_IOMAP_OP_WRITEBACK, write_iomap,
+				       &fake_iter.srcmap);
 		if (ret)
 			goto discard_folio;
 
+		if (BAD_DATA(write_iomap->type == IOMAP_INLINE)) {
+			/*
+			 * iomap assumes that inline data writes are completed
+			 * by the time ->iomap_end completes, so it should
+			 * never mark a pagecache folio dirty.
+			 */
+			fuse_iomap_end(inode, offset, len, 0,
+				       FUSE_IOMAP_OP_WRITEBACK,
+				       write_iomap);
+			ret = -EIO;
+			goto discard_folio;
+		}
+
 		/*
 		 * Landed in a hole or beyond EOF?  Send that to iomap, it'll
 		 * skip writing back the file range.
 		 */
-		if (write_iomap.offset > offset) {
-			write_iomap.length = write_iomap.offset - offset;
-			write_iomap.offset = offset;
-			write_iomap.type = IOMAP_HOLE;
+		if (write_iomap->offset > offset) {
+			write_iomap->length = write_iomap->offset - offset;
+			write_iomap->offset = offset;
+			write_iomap->type = IOMAP_HOLE;
 		}
 
-		memcpy(&wpc->iomap, &write_iomap, sizeof(struct iomap));
+		memcpy(&wpc->iomap, write_iomap, sizeof(struct iomap));
 	}
 
 	ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
#59 lore raw

Re: [PATCH 26/33] fuse: implement inline data file IO via iomap

Quoted 58 lines · Darrick J. Wong

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

Implement inline data file IO by issuing FUSE_READ/FUSE_WRITE commands in response to an inline data mapping.

---
 fs/fuse/fuse_iomap.c |  205 ++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 197 insertions(+), 8 deletions(-)
fs/fuse/fuse_iomap.c +39 -0
index e8a0c1ceb409c4..1c3d99f11634d2 100644
@@ -398,6 +398,152 @@ fuse_iomap_find_dev(struct fuse_conn *fc, const struct fuse_iomap_io *map)
 	return ret;
 }
 
+static inline int fuse_iomap_inline_alloc(struct iomap *iomap)
+{
+	ASSERT(iomap->inline_data == NULL);
+	ASSERT(iomap->length > 0);
+
+	iomap->inline_data = kvzalloc(iomap->length, GFP_KERNEL);
+	return iomap->inline_data ? 0 : -ENOMEM;
+}
+
+static inline void fuse_iomap_inline_free(struct iomap *iomap)
+{
+	kvfree(iomap->inline_data);
+	iomap->inline_data = NULL;
+}
+
+/*
+ * Use the FUSE_READ command to read inline file data from the fuse server.
+ * Note that there's no file handle attached, so the fuse server must be able
+ * to reconnect to the inode via the nodeid.
+ */
+static int fuse_iomap_inline_read(struct inode *inode, loff_t pos,
+				  loff_t count, struct iomap *iomap)
+{
+	struct fuse_read_in in = {
+		.offset = pos,
+		.size = count,
+	};
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_mount *fm = get_fuse_mount(inode);
+	FUSE_ARGS(args);
+	ssize_t ret;
+
+	if (BAD_DATA(!iomap_inline_data_valid(iomap))) {
+		fuse_iomap_inline_free(iomap);
+		return -EFSCORRUPTED;
+	}
+
+	args.opcode = FUSE_READ;
+	args.nodeid = fi->nodeid;

fs/fuse/fuse_iomap.c fuse_iomap_find_dev(struct fuse_conn *fc, const struct fuse_iomap_io *map) · line 449

Quoted 10 lines
fs/fuse/fuse_iomap.c +10 -0
+	args.in_numargs = 1;
+	args.in_args[0].size = sizeof(in);
+	args.in_args[0].value = &in;
+	args.out_argvar = true;
+	args.out_numargs = 1;
+	args.out_args[0].size = count;
+	args.out_args[0].value = iomap_inline_data(iomap, pos);
+
+	ret = fuse_simple_request(fm, &args);
+	if (ret < 0) {

For both the read and write functions, we should treat ENOSYS as a short read/write and not allow "Function not implemented" to bubble up to userspace.

--D

Quoted 207 lines
fs/fuse/fuse_iomap.c +148 -8
+		fuse_iomap_inline_free(iomap);
+		return ret;
+	}
+	/* no readahead means something bad happened */
+	if (ret == 0) {
+		fuse_iomap_inline_free(iomap);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+/*
+ * Use the FUSE_WRITE command to write inline file data from the fuse server.
+ * Note that there's no file handle attached, so the fuse server must be able
+ * to reconnect to the inode via the nodeid.
+ */
+static int fuse_iomap_inline_write(struct inode *inode, loff_t pos,
+				   loff_t count, struct iomap *iomap)
+{
+	struct fuse_write_in in = {
+		.offset = pos,
+		.size = count,
+	};
+	struct fuse_write_out out = { };
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_mount *fm = get_fuse_mount(inode);
+	FUSE_ARGS(args);
+	ssize_t ret;
+
+	if (BAD_DATA(!iomap_inline_data_valid(iomap)))
+		return -EFSCORRUPTED;
+
+	args.opcode = FUSE_WRITE;
+	args.nodeid = fi->nodeid;
+	args.in_numargs = 2;
+	args.in_args[0].size = sizeof(in);
+	args.in_args[0].value = &in;
+	args.in_args[1].size = count;
+	args.in_args[1].value = iomap_inline_data(iomap, pos);
+	args.out_numargs = 1;
+	args.out_args[0].size = sizeof(out);
+	args.out_args[0].value = &out;
+
+	ret = fuse_simple_request(fm, &args);
+	if (ret < 0) {
+		fuse_iomap_inline_free(iomap);
+		return ret;
+	}
+	/* short write means something bad happened */
+	if (out.size < count) {
+		fuse_iomap_inline_free(iomap);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+/* Set up inline data buffers for iomap_begin */
+static int fuse_iomap_set_inline(struct inode *inode, unsigned opflags,
+				 loff_t pos, loff_t count,
+				 struct iomap *iomap, struct iomap *srcmap)
+{
+	int err;
+
+	if (opflags & IOMAP_REPORT)
+		return 0;
+
+	if (fuse_is_iomap_file_write(opflags)) {
+		if (iomap->type == IOMAP_INLINE) {
+			err = fuse_iomap_inline_alloc(iomap);
+			if (err)
+				return err;
+		}
+
+		if (srcmap->type == IOMAP_INLINE) {
+			err = fuse_iomap_inline_alloc(srcmap);
+			if (!err)
+				err = fuse_iomap_inline_read(inode, pos, count,
+							     srcmap);
+			if (err) {
+				fuse_iomap_inline_free(iomap);
+				return err;
+			}
+		}
+	} else if (iomap->type == IOMAP_INLINE) {
+		/* inline data read */
+		err = fuse_iomap_inline_alloc(iomap);
+		if (!err)
+			err = fuse_iomap_inline_read(inode, pos, count, iomap);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+
 static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 			    unsigned opflags, struct iomap *iomap,
 			    struct iomap *srcmap)
@@ -467,12 +613,20 @@ static int fuse_iomap_begin(struct inode *inode, loff_t pos, loff_t count,
 		fuse_iomap_from_server(iomap, read_dev, &outarg.read);
 	}
 
+	if (iomap->type == IOMAP_INLINE || srcmap->type == IOMAP_INLINE) {
+		err = fuse_iomap_set_inline(inode, opflags, pos, count, iomap,
+					    srcmap);
+		if (err)
+			goto out_write_dev;
+	}
+
 	/*
 	 * 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.
 	 */
+out_write_dev:
 	fuse_backing_put(write_dev);
 out_read_dev:
 	fuse_backing_put(read_dev);
@@ -511,8 +665,28 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 {
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	struct fuse_mount *fm = get_fuse_mount(inode);
+	struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
+	struct iomap *srcmap = &iter->srcmap;
 	int err;
 
+	if (srcmap->inline_data)
+		fuse_iomap_inline_free(srcmap);
+
+	if (iomap->inline_data) {
+		if (fuse_is_iomap_file_write(opflags) && written > 0) {
+			err = fuse_iomap_inline_write(inode, pos, written,
+						      iomap);
+			fuse_iomap_inline_free(iomap);
+			if (err)
+				return err;
+		} else {
+			fuse_iomap_inline_free(iomap);
+		}
+
+		/* fuse server should already be aware of what happened */
+		return 0;
+	}
+
 	if (fuse_should_send_iomap_end(fm, iomap, opflags, count, written)) {
 		struct fuse_iomap_end_in inarg = {
 			.opflags = fuse_iomap_op_to_server(opflags),
@@ -1461,7 +1635,6 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
 					  unsigned int len, u64 end_pos)
 {
 	struct inode *inode = wpc->inode;
-	struct iomap write_iomap, dontcare;
 	ssize_t ret;
 
 	if (fuse_is_bad(inode)) {
@@ -1474,23 +1647,39 @@ static ssize_t fuse_iomap_writeback_range(struct iomap_writepage_ctx *wpc,
 	trace_fuse_iomap_writeback_range(inode, offset, len, end_pos);
 
 	if (!fuse_iomap_revalidate_writeback(wpc, offset)) {
+		struct iomap_iter fake_iter = { };
+		struct iomap *write_iomap = &fake_iter.iomap;
+
 		ret = fuse_iomap_begin(inode, offset, len,
-				       FUSE_IOMAP_OP_WRITEBACK,
-				       &write_iomap, &dontcare);
+				       FUSE_IOMAP_OP_WRITEBACK, write_iomap,
+				       &fake_iter.srcmap);
 		if (ret)
 			goto discard_folio;
 
+		if (BAD_DATA(write_iomap->type == IOMAP_INLINE)) {
+			/*
+			 * iomap assumes that inline data writes are completed
+			 * by the time ->iomap_end completes, so it should
+			 * never mark a pagecache folio dirty.
+			 */
+			fuse_iomap_end(inode, offset, len, 0,
+				       FUSE_IOMAP_OP_WRITEBACK,
+				       write_iomap);
+			ret = -EIO;
+			goto discard_folio;
+		}
+
 		/*
 		 * Landed in a hole or beyond EOF?  Send that to iomap, it'll
 		 * skip writing back the file range.
 		 */
-		if (write_iomap.offset > offset) {
-			write_iomap.length = write_iomap.offset - offset;
-			write_iomap.offset = offset;
-			write_iomap.type = IOMAP_HOLE;
+		if (write_iomap->offset > offset) {
+			write_iomap->length = write_iomap->offset - offset;
+			write_iomap->offset = offset;
+			write_iomap->type = IOMAP_HOLE;
 		}
 
-		memcpy(&wpc->iomap, &write_iomap, sizeof(struct iomap));
+		memcpy(&wpc->iomap, write_iomap, sizeof(struct iomap));
 	}
 
 	ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
#60 lore raw

PATCH 27/33 fuse_trace: implement inline data file IO via iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   45 +++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    7 +++++++
 2 files changed, 52 insertions(+)
fs/fuse/fuse_trace.h +45 -0
index 0e4be645802055..d3352e75fa6bdf 100644
@@ -230,6 +230,7 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 #if IS_ENABLED(CONFIG_FUSE_IOMAP)
 struct iomap_writepage_ctx;
 struct iomap_ioend;
+struct iomap;
 
 /* tracepoint boilerplate so we don't have to keep doing this */
 #define FUSE_IOMAP_OPFLAGS_FIELD \
@@ -1079,6 +1080,50 @@ TRACE_EVENT(fuse_iomap_dev_inval,
 		  __entry->offset,
 		  __entry->length)
 );
+
+DECLARE_EVENT_CLASS(fuse_iomap_inline_class,
+	TP_PROTO(const struct inode *inode, loff_t pos, uint64_t count,
+		 const struct iomap *map),
+	TP_ARGS(inode, pos, count, map),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		FUSE_IOMAP_MAP_FIELDS(map)
+		__field(bool,			has_buf)
+		__field(uint64_t,		validity_cookie)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	pos;
+		__entry->length		=	count;
+
+		__entry->mapdev		=	FUSE_IOMAP_DEV_NULL;
+		__entry->mapaddr	=	map->addr;
+		__entry->mapoffset	=	map->offset;
+		__entry->maplength	=	map->length;
+		__entry->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+
+		__entry->has_buf	=	map->inline_data != NULL;
+		__entry->validity_cookie=	map->validity_cookie;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() FUSE_IOMAP_MAP_FMT() " has_buf? %d cookie 0x%llx",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map),
+		  __entry->has_buf,
+		  __entry->validity_cookie)
+);
+#define DEFINE_FUSE_IOMAP_INLINE_EVENT(name)	\
+DEFINE_EVENT(fuse_iomap_inline_class, name,	\
+	TP_PROTO(const struct inode *inode, loff_t pos, uint64_t count, \
+		 const struct iomap *map), \
+	TP_ARGS(inode, pos, count, map))
+DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_inline_read);
+DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_inline_write);
+DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_iomap);
+DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_srcmap);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +7 -0
index 1c3d99f11634d2..6230819d0962a2 100644
@@ -435,6 +435,8 @@ static int fuse_iomap_inline_read(struct inode *inode, loff_t pos,
 		return -EFSCORRUPTED;
 	}
 
+	trace_fuse_iomap_inline_read(inode, pos, count, iomap);
+
 	args.opcode = FUSE_READ;
 	args.nodeid = fi->nodeid;
 	args.in_numargs = 1;
@@ -480,6 +482,8 @@ static int fuse_iomap_inline_write(struct inode *inode, loff_t pos,
 	if (BAD_DATA(!iomap_inline_data_valid(iomap)))
 		return -EFSCORRUPTED;
 
+	trace_fuse_iomap_inline_write(inode, pos, count, iomap);
+
 	args.opcode = FUSE_WRITE;
 	args.nodeid = fi->nodeid;
 	args.in_numargs = 2;
@@ -541,6 +545,9 @@ static int fuse_iomap_set_inline(struct inode *inode, unsigned opflags,
 			return err;
 	}
 
+	trace_fuse_iomap_set_inline_iomap(inode, pos, count, iomap);
+	trace_fuse_iomap_set_inline_srcmap(inode, pos, count, srcmap);
+
 	return 0;
 }
 
#61 lore raw

PATCH 28/33 fuse: allow more statx fields

In reply to Darrick J. Wong

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

Allow the fuse server to supply us with the more recently added fields of struct statx.

---
 include/uapi/linux/fuse.h |   15 ++++++++-
 fs/fuse/dir.c             |   76 ++++++++++++++++++++++++++++++++++++++-------
 2 files changed, 79 insertions(+), 12 deletions(-)
include/uapi/linux/fuse.h +14 -1
index 1ef7152306a24f..aa96b4cbdfa255 100644
@@ -341,7 +341,20 @@ struct fuse_statx {
 	uint32_t	rdev_minor;
 	uint32_t	dev_major;
 	uint32_t	dev_minor;
-	uint64_t	__spare2[14];
+
+	uint64_t	mnt_id;
+	uint32_t	dio_mem_align;
+	uint32_t	dio_offset_align;
+	uint64_t	subvol;
+
+	uint32_t	atomic_write_unit_min;
+	uint32_t	atomic_write_unit_max;
+	uint32_t	atomic_write_segments_max;
+	uint32_t	dio_read_offset_align;
+	uint32_t	atomic_write_unit_max_opt;
+	uint32_t	__spare2[1];
+
+	uint64_t	__spare3[8];
 };
 
 struct fuse_kstatfs {
fs/fuse/dir.c +65 -11

112 lines not on this page · raw message

#62 lore raw

PATCH 29/33 fuse: support atomic writes with iomap

In reply to Darrick J. Wong

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

Enable untorn writes of up to a single fsblock, if iomap is enabled.

---
 fs/fuse/fuse_i.h          |    2 ++
 fs/fuse/fuse_iomap.h      |    7 +++++++
 include/uapi/linux/fuse.h |    5 +++++
 fs/fuse/fuse_iomap.c      |   45 ++++++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 58 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +2 -0
index 153aa441a78320..f96c69c755bd9b 100644
@@ -276,6 +276,8 @@ enum {
 	FUSE_I_EXCLUSIVE,
 	/* Use iomap for this inode */
 	FUSE_I_IOMAP,
+	/* Enable untorn writes */
+	FUSE_I_ATOMIC,
 };
 
 struct fuse_conn;
fs/fuse/fuse_iomap.h +7 -0
index d4a4d9f0313edf..1d9d39383ca9b2 100644
@@ -35,6 +35,13 @@ static inline bool fuse_inode_has_iomap(const struct inode *inode)
 	return test_bit(FUSE_I_IOMAP, &fi->state);
 }
 
+static inline bool fuse_inode_has_atomic(const struct inode *inode)
+{
+	const struct fuse_inode *fi = get_fuse_inode(inode);
+
+	return test_bit(FUSE_I_ATOMIC, &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);
include/uapi/linux/fuse.h +5 -0
index aa96b4cbdfa255..c454cea83083d3 100644
@@ -248,6 +248,7 @@
  *  - add FUSE_ATTR_IOMAP to enable iomap for specific inodes
  *  - add FUSE_IOMAP_CONFIG so the fuse server can configure more fs geometry
  *  - add FUSE_NOTIFY_IOMAP_DEV_INVAL to invalidate iomap bdev ranges
+ *  - add FUSE_ATTR_ATOMIC for single-fsblock atomic write support
  */
 
 #ifndef _LINUX_FUSE_H
@@ -604,11 +605,13 @@ struct fuse_file_lock {
  * FUSE_ATTR_EXCLUSIVE: This file can only be modified by this mount, so the
  * kernel can use cached attributes more aggressively (e.g. ACL inheritance)
  * FUSE_ATTR_IOMAP: Use iomap for this inode
+ * FUSE_ATTR_ATOMIC: Enable untorn writes
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX		(1 << 1)
 #define FUSE_ATTR_EXCLUSIVE	(1 << 2)
 #define FUSE_ATTR_IOMAP		(1 << 3)
+#define FUSE_ATTR_ATOMIC	(1 << 4)
 
 /**
  * Open flags
@@ -1176,6 +1179,8 @@ struct fuse_backing_map {
 
 /* basic file I/O functionality through iomap */
 #define FUSE_IOMAP_SUPPORT_FILEIO	(1ULL << 0)
+/* untorn writes through iomap */
+#define FUSE_IOMAP_SUPPORT_ATOMIC	(1ULL << 1)
 struct fuse_iomap_support {
 	uint64_t	flags;
 	uint64_t	padding;
fs/fuse/fuse_iomap.c +44 -1

93 lines not on this page · raw message

#63 lore raw

Re: [PATCH 29/33] fuse: support atomic writes with iomap

Quoted 6 lines
fs/fuse/fuse_iomap.c +2 -0
+	}
+
 	/*
 	 * Unaligned direct writes require zeroing of unwritten head and tail
 	 * blocks.  Extending writes require zeroing of post-EOF tail blocks.

fs/fuse/fuse_iomap.c static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb, · line 1917

Quoted 9 lines
fs/fuse/fuse_iomap.c +6 -0
@@ -1873,6 +1909,12 @@ static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb,
 	if (!iov_iter_count(from))
 		return 0;
 
+	if (iocb->ki_flags & IOCB_ATOMIC) {
+		ret = fuse_iomap_atomic_write_valid(iocb, from);
+		if (ret)
+			return ret;
+	}
+

I still haven't gone through the whole patch blizzard but I had a general question here: we don't give ATOMIC guarantees to buffered IO, so I am wondering how we give that here. For example, we might mix atomic and non atomic buffered IO during writeback. Am I missing some implementation detail that makes it possible here? I don't think we should enable this for buffered IO.

Signature · 1 line
Pankaj
#64 lore raw

Re: [PATCH 29/33] fuse: support atomic writes with iomap

Quoted 9 lines · Pankaj Raghav (Samsung)
Quoted 9 lines
fs/fuse/fuse_iomap.c +2 -0
+	}
+
 	/*
 	 * Unaligned direct writes require zeroing of unwritten head and tail
 	 * blocks.  Extending writes require zeroing of post-EOF tail blocks.
@@ -1873,6 +1909,12 @@ static ssize_t fuse_iomap_buffered_write(struct kiocb *iocb,
 	if (!iov_iter_count(from))
 		return 0;
 
Quoted 10 lines

fs/fuse/fuse_iomap.c static ssize_t fuse_iomap_direct_write(struct kiocb *iocb, · line 1485

Quoted 6 lines
fs/fuse/fuse_iomap.c +6 -0
+	if (iocb->ki_flags & IOCB_ATOMIC) {
+		ret = fuse_iomap_atomic_write_valid(iocb, from);
+		if (ret)
+			return ret;
+	}
+

I still haven't gone through the whole patch blizzard but I had a general question here: we don't give ATOMIC guarantees to buffered IO, so I am wondering how we give that here.

Oh, we don't. generic_atomic_write_valid rejects !IOCB_DIRECT iocbs.

Quoted 4 lines

For example, we might mix
atomic and non atomic buffered IO during writeback. Am I missing some implementation detail that makes it possible here? I don't think we should enable this for buffered IO.

<nod> Now that y'all have an lsf thread on this, I agree that not supporting buffered writes in fuse-iomap should be more explicit.

	if (iocb->ki_flags & IOCB_ATOMIC)
		return -EOPNOTSUPP;

--D

Quoted 3 lines
Signature · 1 line
Pankaj
#65 lore raw

Re: [PATCH 29/33] fuse: support atomic writes with iomap

Quoted 6 lines
Quoted 4 lines

I still haven't gone through the whole patch blizzard but I had a general question here: we don't give ATOMIC guarantees to buffered IO, so I am wondering how we give that here.

Oh, we don't. generic_atomic_write_valid rejects !IOCB_DIRECT iocbs.

Ah, that is true. I was secretly hoping you added support for buffered IO atomics ;)

Quoted 6 lines
Quoted 5 lines

For example, we might mix
atomic and non atomic buffered IO during writeback. Am I missing some implementation detail that makes it possible here? I don't think we should enable this for buffered IO.

Quoted 6 lines

<nod> Now that y'all have an lsf thread on this, I agree that not supporting buffered writes in fuse-iomap should be more explicit.

	if (iocb->ki_flags & IOCB_ATOMIC)
		return -EOPNOTSUPP;

Yeah. This looks more explicit. Of course this change does not warrant a new series as it is not changing anything functionally. If you plan to send a new series anyway, then this could be folded in.

Signature · 1 line
Pankaj
#66 lore raw

PATCH 30/33 fuse_trace: support atomic writes with iomap

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/fuse/fuse_trace.h +3 -1
index d3352e75fa6bdf..de7d483d4b0f34 100644
@@ -330,6 +330,7 @@ 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);
+TRACE_DEFINE_ENUM(FUSE_I_ATOMIC);
 
 #define FUSE_IFLAG_STRINGS \
 	{ 1 << FUSE_I_ADVISE_RDPLUS,		"advise_rdplus" }, \
@@ -339,7 +340,8 @@ TRACE_DEFINE_ENUM(FUSE_I_IOMAP);
 	{ 1 << FUSE_I_BTIME,			"btime" }, \
 	{ 1 << FUSE_I_CACHE_IO_MODE,		"cacheio" }, \
 	{ 1 << FUSE_I_EXCLUSIVE,		"excl" }, \
-	{ 1 << FUSE_I_IOMAP,			"iomap" }
+	{ 1 << FUSE_I_IOMAP,			"iomap" }, \
+	{ 1 << FUSE_I_ATOMIC,			"atomic" }
 
 #define IOMAP_IOEND_STRINGS \
 	{ IOMAP_IOEND_SHARED,			"shared" }, \
#67 lore raw

PATCH 31/33 fuse: disable direct fs reclaim for any fuse server that uses iomap

In reply to Darrick J. Wong

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

Any fuse server that uses iomap can create a substantial amount of dirty pages in the pagecache because we don't write dirty stuff until reclaim or fsync. Therefore, memory reclaim on any fuse iomap server musn't ever recurse back into the same filesystem. We must also never throttle the fuse server writes to a bdi because that will just slow down metadata operations.

Add a new ioctl that the fuse server can call on the fuse device to set PF_MEMALLOC_NOFS and PF_LOCAL_THROTTLE. Either the fuse connection must have already enabled iomap, or the caller must have CAP_SYS_RESOURCE.

---
 fs/fuse/fuse_iomap.h      |    2 ++
 include/uapi/linux/fuse.h |    1 +
 fs/fuse/dev.c             |    2 ++
 fs/fuse/fuse_iomap.c      |   37 +++++++++++++++++++++++++++++++++++++
 4 files changed, 42 insertions(+)
fs/fuse/fuse_iomap.h +2 -0
index 1d9d39383ca9b2..bf6640c36465e1 100644
@@ -75,6 +75,7 @@ int fuse_iomap_dev_inval(struct fuse_conn *fc,
 			 const struct fuse_iomap_dev_inval_out *arg);
 
 int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
+int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -102,6 +103,7 @@ int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
 # define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
+# define fuse_dev_ioctl_iomap_set_nofs(...)	(-EOPNOTSUPP)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +1 -0
index c454cea83083d3..9e59fba64f48d9 100644
@@ -1195,6 +1195,7 @@ struct fuse_iomap_support {
 #define FUSE_DEV_IOC_SYNC_INIT		_IO(FUSE_DEV_IOC_MAGIC, 3)
 #define FUSE_DEV_IOC_IOMAP_SUPPORT	_IOR(FUSE_DEV_IOC_MAGIC, 99, \
 					     struct fuse_iomap_support)
+#define FUSE_DEV_IOC_SET_NOFS		_IOW(FUSE_DEV_IOC_MAGIC, 100, uint32_t)
 
 struct fuse_lseek_in {
 	uint64_t	fh;
fs/fuse/dev.c +2 -0
index 9a814a0d222fe6..896706c911cf24 100644
@@ -2742,6 +2742,8 @@ static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
 
 	case FUSE_DEV_IOC_IOMAP_SUPPORT:
 		return fuse_dev_ioctl_iomap_support(file, argp);
+	case FUSE_DEV_IOC_SET_NOFS:
+		return fuse_dev_ioctl_iomap_set_nofs(file, argp);
 
 	default:
 		return -ENOTTY;
fs/fuse/fuse_iomap.c +37 -0
index 84bc8bbd2eeb85..561b0105e6dadc 100644
@@ -12,6 +12,7 @@
 #include "fuse_trace.h"
 #include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
+#include "fuse_dev_i.h"
 
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
@@ -2280,3 +2281,39 @@ int fuse_iomap_dev_inval(struct fuse_conn *fc,
 	up_read(&fc->killsb);
 	return ret;
 }
+
+static inline bool can_set_nofs(struct fuse_dev *fud)
+{
+	if (fud && fud->fc && fud->fc->iomap)
+	       return true;
+
+	return capable(CAP_SYS_RESOURCE);
+}
+
+int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp)
+{
+	struct fuse_dev *fud = fuse_get_dev(file);
+	uint32_t flags;
+
+	if (!can_set_nofs(fud))
+		return -EPERM;
+
+	if (copy_from_user(&flags, argp, sizeof(flags)))
+		return -EFAULT;
+
+	/*
+	 * The fuse server could be asked to perform a substantial amount of
+	 * writeback, so prohibit reclaim from recursing into fuse or the
+	 * kernel from throttling any bdis that the fuse server might write to.
+	 */
+	switch (flags) {
+	case 1:
+		current->flags |= PF_MEMALLOC_NOFS | PF_LOCAL_THROTTLE;
+		return 0;
+	case 0:
+		current->flags &= ~(PF_MEMALLOC_NOFS | PF_LOCAL_THROTTLE);
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
#68 lore raw

PATCH 32/33 fuse: enable swapfile activation on iomap

In reply to Darrick J. Wong

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

It turns out that fuse supports swapfile activation, so let's enable that.

---
 fs/fuse/fuse_trace.h      |    1 +
 include/uapi/linux/fuse.h |    5 ++++
 fs/fuse/fuse_iomap.c      |   54 ++++++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 59 insertions(+), 1 deletion(-)
fs/fuse/fuse_trace.h +1 -0
index de7d483d4b0f34..63cc1496ee5ca1 100644
@@ -300,6 +300,7 @@ struct iomap;
 	{ FUSE_IOMAP_OP_DAX,			"fsdax" }, \
 	{ FUSE_IOMAP_OP_ATOMIC,			"atomic" }, \
 	{ FUSE_IOMAP_OP_DONTCACHE,		"dontcache" }, \
+	{ FUSE_IOMAP_OP_SWAPFILE,		"swapfile" }, \
 	{ FUSE_IOMAP_OP_WRITEBACK,		"writeback" }
 
 #define FUSE_IOMAP_TYPE_STRINGS \
include/uapi/linux/fuse.h +5 -0
index 9e59fba64f48d9..5f3724f36f764a 100644
@@ -1406,6 +1406,9 @@ struct fuse_uring_cmd_req {
 #define FUSE_IOMAP_OP_ATOMIC		(1U << 9)
 #define FUSE_IOMAP_OP_DONTCACHE		(1U << 10)
 
+/* swapfile config operation */
+#define FUSE_IOMAP_OP_SWAPFILE		(1U << 30)
+
 /* pagecache writeback operation */
 #define FUSE_IOMAP_OP_WRITEBACK		(1U << 31)
 
@@ -1460,6 +1463,8 @@ struct fuse_iomap_end_in {
 #define FUSE_IOMAP_IOEND_APPEND		(1U << 4)
 /* is pagecache writeback */
 #define FUSE_IOMAP_IOEND_WRITEBACK	(1U << 5)
+/* swapfile deactivation */
+#define FUSE_IOMAP_IOEND_SWAPOFF	(1U << 6)
 
 struct fuse_iomap_ioend_in {
 	uint32_t flags;		/* FUSE_IOMAP_IOEND_* */
fs/fuse/fuse_iomap.c +53 -1

90 lines not on this page · raw message

#69 lore raw

PATCH 33/33 fuse: implement freeze and shutdowns for iomap filesystems

In reply to Darrick J. Wong

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

Implement filesystem freezing and block device shutdown notifications for iomap-based servers

---
 include/uapi/linux/fuse.h |   12 +++++++
 fs/fuse/inode.c           |   73 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 85 insertions(+)
include/uapi/linux/fuse.h +12 -0
index 5f3724f36f764a..b6fa828776b82f 100644
@@ -695,6 +695,10 @@ enum fuse_opcode {
 	FUSE_STATX		= 52,
 	FUSE_COPY_FILE_RANGE_64	= 53,
 
+	FUSE_FREEZE_FS		= 4089,
+	FUSE_UNFREEZE_FS	= 4090,
+	FUSE_SHUTDOWN_FS	= 4091,
+
 	FUSE_IOMAP_CONFIG	= 4092,
 	FUSE_IOMAP_IOEND	= 4093,
 	FUSE_IOMAP_BEGIN	= 4094,
@@ -1257,6 +1261,14 @@ struct fuse_syncfs_in {
 	uint64_t	padding;
 };
 
+struct fuse_freezefs_in {
+	uint64_t	unlinked;
+};
+
+struct fuse_shutdownfs_in {
+	uint64_t	flags;
+};
+
 /*
  * For each security context, send fuse_secctx with size of security context
  * fuse_secctx will be followed by security context name and this in turn
fs/fuse/inode.c +73 -0

85 lines not on this page · raw message

#70 lore raw

PATCH v7 5/9 fuse: allow servers to specify root node id

In reply to Darrick J. Wong

Hi all,

This series grants fuse servers full control over the entire node id address space by allowing them to specify the nodeid of the root directory. With this new feature, fuse4fs will not have to translate node ids.

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

With a bit of luck, this should all go splendidly. 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-root-nodeid
---
Commits in this patchset:
* fuse: make the root nodeid dynamic
* fuse_trace: make the root nodeid dynamic
* fuse: allow setting of root nodeid

---
 fs/fuse/fuse_i.h     |    9 +++++++--
 fs/fuse/fuse_trace.h |    6 ++++--
 fs/fuse/dir.c        |   10 ++++++----
 fs/fuse/inode.c      |   22 ++++++++++++++++++----
 fs/fuse/readdir.c    |   10 +++++-----
 5 files changed, 40 insertions(+), 17 deletions(-)
#71 lore raw

PATCH 1/3 fuse: make the root nodeid dynamic

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

Change this from a hardcoded constant to a dynamic field so that fuse servers don't need to translate.

---
 fs/fuse/fuse_i.h  |    7 +++++--
 fs/fuse/dir.c     |   10 ++++++----
 fs/fuse/inode.c   |   11 +++++++----
 fs/fuse/readdir.c |   10 +++++-----
 4 files changed, 23 insertions(+), 15 deletions(-)
fs/fuse/fuse_i.h +5 -2
index f96c69c755bd9b..fc0e352e2e8f9b 100644
@@ -702,6 +702,9 @@ struct fuse_conn {
 
 	struct rcu_head rcu;
 
+	/* node id of the root directory */
+	u64 root_nodeid;
+
 	/** The user id for this mount */
 	kuid_t user_id;
 
@@ -1117,9 +1120,9 @@ static inline u64 get_node_id(struct inode *inode)
 	return get_fuse_inode(inode)->nodeid;
 }
 
-static inline int invalid_nodeid(u64 nodeid)
+static inline int invalid_nodeid(const struct fuse_conn *fc, u64 nodeid)
 {
-	return !nodeid || nodeid == FUSE_ROOT_ID;
+	return !nodeid || nodeid == fc->root_nodeid;
 }
 
 static inline u64 fuse_get_attr_version(struct fuse_conn *fc)
fs/fuse/dir.c +6 -4
index 0492619e397f56..ff678f26e9cd79 100644
@@ -580,7 +580,7 @@ int fuse_lookup_name(struct super_block *sb, u64 nodeid, const struct qstr *name
 	err = -EIO;
 	if (fuse_invalid_attr(&outarg->attr))
 		goto out_put_forget;
-	if (outarg->nodeid == FUSE_ROOT_ID && outarg->generation != 0) {
+	if (outarg->nodeid == fm->fc->root_nodeid && outarg->generation != 0) {
 		pr_warn_once("root generation should be zero\n");
 		outarg->generation = 0;
 	}
@@ -630,7 +630,7 @@ static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry,
 		goto out_err;
 
 	err = -EIO;
-	if (inode && get_node_id(inode) == FUSE_ROOT_ID)
+	if (inode && get_node_id(inode) == fc->root_nodeid)
 		goto out_iput;
 
 	newent = d_splice_alias(inode, entry);
@@ -881,7 +881,8 @@ static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
 		goto out_free_ff;
 
 	err = -EIO;
-	if (!S_ISREG(outentry.attr.mode) || invalid_nodeid(outentry.nodeid) ||
+	if (!S_ISREG(outentry.attr.mode) ||
+	    invalid_nodeid(fm->fc, outentry.nodeid) ||
 	    fuse_invalid_attr(&outentry.attr))
 		goto out_free_ff;
 
@@ -1028,7 +1029,8 @@ static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_moun
 		goto out_put_forget_req;
 
 	err = -EIO;
-	if (invalid_nodeid(outarg.nodeid) || fuse_invalid_attr(&outarg.attr))
+	if (invalid_nodeid(fm->fc, outarg.nodeid) ||
+	    fuse_invalid_attr(&outarg.attr))
 		goto out_put_forget_req;
 
 	if ((outarg.attr.mode ^ mode) & S_IFMT)
fs/fuse/inode.c +7 -4
index f3afa63bfe7f61..2a679bce3b178c 100644
@@ -1030,6 +1030,7 @@ void fuse_conn_init(struct fuse_conn *fc, struct fuse_mount *fm,
 	fc->max_pages_limit = fuse_max_pages_limit;
 	fc->name_max = FUSE_NAME_LOW_MAX;
 	fc->timeout.req_timeout = 0;
+	fc->root_nodeid = FUSE_ROOT_ID;
 
 	if (IS_ENABLED(CONFIG_FUSE_BACKING))
 		fuse_backing_files_init(fc);
@@ -1087,12 +1088,14 @@ EXPORT_SYMBOL_GPL(fuse_conn_get);
 static struct inode *fuse_get_root_inode(struct super_block *sb, unsigned int mode)
 {
 	struct fuse_attr attr;
+	struct fuse_conn *fc = get_fuse_conn_super(sb);
+
 	memset(&attr, 0, sizeof(attr));
 
 	attr.mode = mode;
-	attr.ino = FUSE_ROOT_ID;
+	attr.ino = fc->root_nodeid;
 	attr.nlink = 1;
-	return fuse_iget(sb, FUSE_ROOT_ID, 0, &attr, 0, 0, 0);
+	return fuse_iget(sb, fc->root_nodeid, 0, &attr, 0, 0, 0);
 }
 
 struct fuse_inode_handle {
@@ -1136,7 +1139,7 @@ static struct dentry *fuse_get_dentry(struct super_block *sb,
 		goto out_iput;
 
 	entry = d_obtain_alias(inode);
-	if (!IS_ERR(entry) && get_node_id(inode) != FUSE_ROOT_ID)
+	if (!IS_ERR(entry) && get_node_id(inode) != fc->root_nodeid)
 		fuse_invalidate_entry_cache(entry);
 
 	return entry;
@@ -1229,7 +1232,7 @@ static struct dentry *fuse_get_parent(struct dentry *child)
 	}
 
 	parent = d_obtain_alias(inode);
-	if (!IS_ERR(parent) && get_node_id(inode) != FUSE_ROOT_ID)
+	if (!IS_ERR(parent) && get_node_id(inode) != fc->root_nodeid)
 		fuse_invalidate_entry_cache(parent);
 
 	return parent;
fs/fuse/readdir.c +5 -5
index c2aae2eef0868b..45dd932eb03a5e 100644
@@ -185,12 +185,12 @@ static int fuse_direntplus_link(struct file *file,
 			return 0;
 	}
 
-	if (invalid_nodeid(o->nodeid))
-		return -EIO;
-	if (fuse_invalid_attr(&o->attr))
-		return -EIO;
-
 	fc = get_fuse_conn(dir);
+	if (invalid_nodeid(fc, o->nodeid))
+		return -EIO;
+	if (fuse_invalid_attr(&o->attr))
+		return -EIO;
+
 	epoch = atomic_read(&fc->epoch);
 
 	name.hash = full_name_hash(parent, name.name, name.len);
#72 lore raw

PATCH 2/3 fuse_trace: make the root nodeid dynamic

In reply to Darrick J. Wong

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

Enhance the iomap config tracepoint to report the node id of the root directory.

---
 fs/fuse/fuse_trace.h |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/fuse/fuse_trace.h +4 -2
index 63cc1496ee5ca1..0016242ff34f62 100644
@@ -1026,6 +1026,7 @@ TRACE_EVENT(fuse_iomap_config,
 
 	TP_STRUCT__entry(
 		__field(dev_t,			connection)
+		__field(uint64_t,		root_nodeid)
 
 		__field(uint64_t,		flags)
 		__field(uint32_t,		blocksize)
@@ -1040,6 +1041,7 @@ TRACE_EVENT(fuse_iomap_config,
 
 	TP_fast_assign(
 		__entry->connection	=	fm->fc->dev;
+		__entry->root_nodeid	=	fm->fc->root_nodeid;
 		__entry->flags		=	outarg->flags;
 		__entry->blocksize	=	outarg->s_blocksize;
 		__entry->max_links	=	outarg->s_max_links;
@@ -1050,8 +1052,8 @@ TRACE_EVENT(fuse_iomap_config,
 		__entry->uuid_len	=	outarg->s_uuid_len;
 	),
 
-	TP_printk("connection %u flags (%s) blocksize 0x%x max_links %u time_gran %u time_min %lld time_max %lld maxbytes 0x%llx uuid_len %u",
-		  __entry->connection,
+	TP_printk("connection %u root_ino 0x%llx flags (%s) blocksize 0x%x max_links %u time_gran %u time_min %lld time_max %lld maxbytes 0x%llx uuid_len %u",
+		  __entry->connection, __entry->root_nodeid,
 		  __print_flags(__entry->flags, "|", FUSE_IOMAP_CONFIG_STRINGS),
 		  __entry->blocksize, __entry->max_links, __entry->time_gran,
 		  __entry->time_min, __entry->time_max, __entry->maxbytes,
#73 lore raw

PATCH 3/3 fuse: allow setting of root nodeid

In reply to Darrick J. Wong

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

Provide a new mount option so that fuse servers can actually set the root nodeid.

---
 fs/fuse/fuse_i.h |    2 ++
 fs/fuse/inode.c  |   11 +++++++++++
 2 files changed, 13 insertions(+)
fs/fuse/fuse_i.h +2 -0
index fc0e352e2e8f9b..884f29533d0206 100644
@@ -636,6 +636,7 @@ struct fuse_fs_context {
 	int fd;
 	struct file *file;
 	unsigned int rootmode;
+	u64 root_nodeid;
 	kuid_t user_id;
 	kgid_t group_id;
 	bool is_bdev:1;
@@ -649,6 +650,7 @@ struct fuse_fs_context {
 	bool no_control:1;
 	bool no_force_umount:1;
 	bool legacy_opts_show:1;
+	bool root_nodeid_present:1;
 	enum fuse_dax_mode dax_mode;
 	unsigned int max_read;
 	unsigned int blksize;
fs/fuse/inode.c +11 -0
index 2a679bce3b178c..9185b3b922559a 100644
@@ -813,6 +813,7 @@ enum {
 	OPT_ALLOW_OTHER,
 	OPT_MAX_READ,
 	OPT_BLKSIZE,
+	OPT_ROOT_NODEID,
 	OPT_ERR
 };
 
@@ -827,6 +828,7 @@ static const struct fs_parameter_spec fuse_fs_parameters[] = {
 	fsparam_u32	("max_read",		OPT_MAX_READ),
 	fsparam_u32	("blksize",		OPT_BLKSIZE),
 	fsparam_string	("subtype",		OPT_SUBTYPE),
+	fsparam_u64	("root_nodeid",		OPT_ROOT_NODEID),
 	{}
 };
 
@@ -922,6 +924,11 @@ static int fuse_parse_param(struct fs_context *fsc, struct fs_parameter *param)
 		ctx->blksize = result.uint_32;
 		break;
 
+	case OPT_ROOT_NODEID:
+		ctx->root_nodeid = result.uint_64;
+		ctx->root_nodeid_present = true;
+		break;
+
 	default:
 		return -EINVAL;
 	}
@@ -957,6 +964,8 @@ static int fuse_show_options(struct seq_file *m, struct dentry *root)
 			seq_printf(m, ",max_read=%u", fc->max_read);
 		if (sb->s_bdev && sb->s_blocksize != FUSE_DEFAULT_BLKSIZE)
 			seq_printf(m, ",blksize=%lu", sb->s_blocksize);
+		if (fc->root_nodeid && fc->root_nodeid != FUSE_ROOT_ID)
+			seq_printf(m, ",root_nodeid=%llu", fc->root_nodeid);
 	}
 #ifdef CONFIG_FUSE_DAX
 	if (fc->dax_mode == FUSE_DAX_ALWAYS)
@@ -2005,6 +2014,8 @@ int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx)
 	sb->s_flags |= SB_POSIXACL;
 
 	fc->default_permissions = ctx->default_permissions;
+	if (ctx->root_nodeid_present)
+		fc->root_nodeid = ctx->root_nodeid;
 	fc->allow_other = ctx->allow_other;
 	fc->user_id = ctx->user_id;
 	fc->group_id = ctx->group_id;
#74 lore raw

PATCH v7 6/9 fuse: handle timestamps and ACLs correctly when iomap is enabled

In reply to Darrick J. Wong

Hi all,

When iomap is enabled for a fuse file, we try to keep as much of the file IO path in the kernel as we possibly can. That means no calling out to the fuse server in the IO path when we can avoid it. However, the existing FUSE architecture defers all file attributes to the fuse server -- [cm]time updates, ACL metadata management, set[ug]id removal, and permissions checking thereof, etc.

We'd really rather do all these attribute updates in the kernel, and only push them to the fuse server when it's actually necessary (e.g. fsync). Furthermore, the POSIX ACL code has the weird behavior that if the access ACL can be represented entirely by i_mode bits, it will change the mode and delete the ACL, which fuse servers generally don't seem to implement.

IOWs, we want consistent and correct (as defined by fstests) behavior of file attributes in iomap mode. Let's make the kernel manage all that and push the results to userspace as needed. This improves performance even further, since it's sort of like writeback_cache mode but more aggressive.

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

With a bit of luck, this should all go splendidly. 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-attrs
---
Commits in this patchset:
* fuse: enable caching of timestamps
* fuse: force a ctime update after a fileattr_set call when in iomap mode
* fuse: allow local filesystems to set some VFS iflags
* fuse_trace: allow local filesystems to set some VFS iflags
* fuse: cache atime when in iomap mode
* fuse: let the kernel handle KILL_SUID/KILL_SGID for iomap filesystems
* fuse_trace: let the kernel handle KILL_SUID/KILL_SGID for iomap filesystems
* fuse: update ctime when updating acls on an iomap inode
* fuse: always cache ACLs when using iomap

---
 fs/fuse/fuse_i.h          |    1 +
 fs/fuse/fuse_trace.h      |   87 +++++++++++++++++++++++++++++++++++++++++++++
 include/uapi/linux/fuse.h |    8 ++++
 fs/fuse/acl.c             |   30 +++++++++++++---
 fs/fuse/dir.c             |   38 ++++++++++++++++----
 fs/fuse/file.c            |   18 ++++++---
 fs/fuse/fuse_iomap.c      |   12 ++++++
 fs/fuse/inode.c           |   19 +++++++---
 fs/fuse/ioctl.c           |   68 +++++++++++++++++++++++++++++++++++
 fs/fuse/readdir.c         |    5 ++-
 10 files changed, 262 insertions(+), 24 deletions(-)
#75 lore raw

PATCH 1/9 fuse: enable caching of timestamps

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

Cache the timestamps in the kernel so that the kernel sends FUSE_SETATTR calls to the fuse server after writes, because the iomap infrastructure won't do that for us.

---
 fs/fuse/dir.c        |    5 ++++-
 fs/fuse/file.c       |   18 ++++++++++++------
 fs/fuse/fuse_iomap.c |    6 ++++++
 fs/fuse/inode.c      |   13 +++++++------
 4 files changed, 29 insertions(+), 13 deletions(-)
fs/fuse/dir.c +4 -1
index ff678f26e9cd79..5ae6c5639f6d2c 100644
@@ -2261,7 +2261,8 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	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);
+	bool is_wb = (is_iomap || fc->writeback_cache) &&
+		     S_ISREG(inode->i_mode);
 	loff_t oldsize;
 	int err;
 	bool trust_local_cmtime = is_wb;
@@ -2401,6 +2402,8 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	spin_lock(&fi->lock);
 	/* the kernel maintains i_mtime locally */
 	if (trust_local_cmtime) {
+		if ((attr->ia_valid & ATTR_ATIME) && is_iomap)
+			inode_set_atime_to_ts(inode, attr->ia_atime);
 		if (attr->ia_valid & ATTR_MTIME)
 			inode_set_mtime_to_ts(inode, attr->ia_mtime);
 		if (attr->ia_valid & ATTR_CTIME)
fs/fuse/file.c +12 -6
index 1243d0eea22a37..0b21fcdefffeb7 100644
@@ -256,7 +256,7 @@ static int fuse_open(struct inode *inode, struct file *file)
 	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 is_wb_truncate = is_truncate && (is_iomap || fc->writeback_cache);
 	bool dax_truncate = is_truncate && FUSE_IS_DAX(inode);
 
 	if (fuse_is_bad(inode))
@@ -471,12 +471,14 @@ static int fuse_flush(struct file *file, fl_owner_t id)
 	struct fuse_file *ff = file->private_data;
 	struct fuse_flush_in inarg;
 	FUSE_ARGS(args);
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	int err;
 
 	if (fuse_is_bad(inode))
 		return -EIO;
 
-	if (ff->open_flags & FOPEN_NOFLUSH && !fm->fc->writeback_cache)
+	if ((ff->open_flags & FOPEN_NOFLUSH) &&
+	    !fm->fc->writeback_cache && !is_iomap)
 		return 0;
 
 	err = write_inode_now(inode, 1);
@@ -512,7 +514,7 @@ static int fuse_flush(struct file *file, fl_owner_t id)
 	 * In memory i_blocks is not maintained by fuse, if writeback cache is
 	 * enabled, i_blocks from cached attr may not be accurate.
 	 */
-	if (!err && fm->fc->writeback_cache)
+	if (!err && (is_iomap || fm->fc->writeback_cache))
 		fuse_invalidate_attr_mask(inode, STATX_BLOCKS);
 	return err;
 }
@@ -814,8 +816,10 @@ static void fuse_short_read(struct inode *inode, u64 attr_ver, size_t num_read,
 	 * If writeback_cache is enabled, a short read means there's a hole in
 	 * the file.  Some data after the hole is in page cache, but has not
 	 * reached the client fs yet.  So the hole is not present there.
+	 * If iomap is enabled, a short read means we hit EOF so there's
+	 * nothing to adjust.
 	 */
-	if (!fc->writeback_cache) {
+	if (!fc->writeback_cache && !fuse_inode_has_iomap(inode)) {
 		loff_t pos = folio_pos(ap->folios[0]) + num_read;
 		fuse_read_update_size(inode, pos, attr_ver);
 	}
@@ -864,6 +868,8 @@ static int fuse_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
 			    unsigned int flags, struct iomap *iomap,
 			    struct iomap *srcmap)
 {
+	WARN_ON(fuse_inode_has_iomap(inode));
+
 	iomap->type = IOMAP_MAPPED;
 	iomap->length = length;
 	iomap->offset = offset;
@@ -2016,7 +2022,7 @@ static void fuse_writepage_end(struct fuse_mount *fm, struct fuse_args *args,
 	 * Do this only if writeback_cache is not enabled.  If writeback_cache
 	 * is enabled, we trust local ctime/mtime.
 	 */
-	if (!fc->writeback_cache)
+	if (!fc->writeback_cache && !fuse_inode_has_iomap(inode))
 		fuse_invalidate_attr_mask(inode, FUSE_STATX_MODIFY);
 	spin_lock(&fi->lock);
 	fi->writectr--;
@@ -3109,7 +3115,7 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in,
 	/* mark unstable when write-back is not used, and file_out gets
 	 * extended */
 	const bool is_iomap = fuse_inode_has_iomap(inode_out);
-	bool is_unstable = (!fc->writeback_cache) &&
+	bool is_unstable = (!fc->writeback_cache && !is_iomap) &&
 			   ((pos_out + len) > inode_out->i_size);
 
 	if (fc->no_copy_file_range)
fs/fuse/fuse_iomap.c +6 -0
index 9a3703b2d65bbd..65c8e06fdd653a 100644
@@ -1864,6 +1864,12 @@ static inline void fuse_inode_set_iomap(struct inode *inode)
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	unsigned int min_order = 0;
 
+	/*
+	 * Manage timestamps ourselves, don't make the fuse server do it.  This
+	 * is critical for mtime updates to work correctly with page_mkwrite.
+	 */
+	inode->i_flags &= ~S_NOCMTIME;
+	inode->i_flags &= ~S_NOATIME;
 	inode->i_data.a_ops = &fuse_iomap_aops;
 
 	INIT_WORK(&fi->ioend_work, fuse_iomap_end_io);
fs/fuse/inode.c +7 -6
index 9185b3b922559a..94355977904068 100644
@@ -331,10 +331,11 @@ u32 fuse_get_cache_mask(struct inode *inode)
 {
 	struct fuse_conn *fc = get_fuse_conn(inode);
 
-	if (!fc->writeback_cache || !S_ISREG(inode->i_mode))
-		return 0;
+	if (S_ISREG(inode->i_mode) &&
+	    (fuse_inode_has_iomap(inode) || fc->writeback_cache))
+		return STATX_MTIME | STATX_CTIME | STATX_SIZE;
 
-	return STATX_MTIME | STATX_CTIME | STATX_SIZE;
+	return 0;
 }
 
 static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr,
@@ -349,9 +350,9 @@ static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr
 
 	spin_lock(&fi->lock);
 	/*
-	 * In case of writeback_cache enabled, writes update mtime, ctime and
-	 * may update i_size.  In these cases trust the cached value in the
-	 * inode.
+	 * In case of writeback_cache or iomap enabled, writes update mtime,
+	 * ctime and may update i_size.  In these cases trust the cached value
+	 * in the inode.
 	 */
 	cache_mask = fuse_get_cache_mask(inode);
 	fuse_iomap_set_disk_size(fi, attr->size);
#76 lore raw

PATCH 2/9 fuse: force a ctime update after a fileattr_set call when in iomap mode

In reply to Darrick J. Wong

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

In iomap mode, the kernel is in charge of driving ctime updates to the fuse server and ignores updates coming from the fuse server. Therefore, when someone calls fileattr_set to change file attributes, we must force a ctime update.

Found by generic/277.

---
 fs/fuse/ioctl.c |   11 +++++++++++
 1 file changed, 11 insertions(+)
fs/fuse/ioctl.c +11 -0
index fdc175e93f7474..07529db21fb781 100644
@@ -546,8 +546,13 @@ int fuse_fileattr_set(struct mnt_idmap *idmap,
 	struct fuse_file *ff;
 	unsigned int flags = fa->flags;
 	struct fsxattr xfa;
+	struct file_kattr old_ma = { };
+	bool is_wb = (fuse_get_cache_mask(inode) & STATX_CTIME);
 	int err;
 
+	if (is_wb)
+		vfs_fileattr_get(dentry, &old_ma);
+
 	ff = fuse_priv_ioctl_prepare(inode);
 	if (IS_ERR(ff))
 		return PTR_ERR(ff);
@@ -571,6 +576,12 @@ int fuse_fileattr_set(struct mnt_idmap *idmap,
 
 cleanup:
 	fuse_priv_ioctl_cleanup(inode, ff);
+	/*
+	 * If we cache ctime updates and the fileattr changed, then force a
+	 * ctime update.
+	 */
+	if (is_wb && memcmp(&old_ma, fa, sizeof(old_ma)))
+		fuse_update_ctime(inode);
 
 	return err;
 }
#77 lore raw

PATCH 3/9 fuse: allow local filesystems to set some VFS iflags

In reply to Darrick J. Wong

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

There are three inode flags (immutable, append, sync) that are enforced by the VFS. Whenever we go around setting iflags, let's update the VFS state so that they actually work. Make it so that the fuse server can set these three inode flags at load time and have the kernel advertise and enforce them.

---
 fs/fuse/fuse_i.h          |    1 +
 include/uapi/linux/fuse.h |    8 +++++++
 fs/fuse/dir.c             |    1 +
 fs/fuse/inode.c           |    1 +
 fs/fuse/ioctl.c           |   50 +++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 61 insertions(+)
fs/fuse/fuse_i.h +1 -0
index 884f29533d0206..b4da866187ba2c 100644
@@ -1654,6 +1654,7 @@ long fuse_file_compat_ioctl(struct file *file, unsigned int cmd,
 int fuse_fileattr_get(struct dentry *dentry, struct file_kattr *fa);
 int fuse_fileattr_set(struct mnt_idmap *idmap,
 		      struct dentry *dentry, struct file_kattr *fa);
+void fuse_fileattr_init(struct inode *inode, const struct fuse_attr *attr);
 
 /* iomode.c */
 int fuse_file_cached_io_open(struct inode *inode, struct fuse_file *ff);
include/uapi/linux/fuse.h +8 -0
index b6fa828776b82f..bf8514a5ee27af 100644
@@ -249,6 +249,8 @@
  *  - add FUSE_IOMAP_CONFIG so the fuse server can configure more fs geometry
  *  - add FUSE_NOTIFY_IOMAP_DEV_INVAL to invalidate iomap bdev ranges
  *  - add FUSE_ATTR_ATOMIC for single-fsblock atomic write support
+ *  - add FUSE_ATTR_{SYNC,IMMUTABLE,APPEND} for VFS enforcement of file
+ *    attributes
  */
 
 #ifndef _LINUX_FUSE_H
@@ -606,12 +608,18 @@ struct fuse_file_lock {
  * kernel can use cached attributes more aggressively (e.g. ACL inheritance)
  * FUSE_ATTR_IOMAP: Use iomap for this inode
  * FUSE_ATTR_ATOMIC: Enable untorn writes
+ * FUSE_ATTR_SYNC: File writes are synchronous
+ * FUSE_ATTR_IMMUTABLE: File is immutable
+ * FUSE_ATTR_APPEND: File is append-only
  */
 #define FUSE_ATTR_SUBMOUNT      (1 << 0)
 #define FUSE_ATTR_DAX		(1 << 1)
 #define FUSE_ATTR_EXCLUSIVE	(1 << 2)
 #define FUSE_ATTR_IOMAP		(1 << 3)
 #define FUSE_ATTR_ATOMIC	(1 << 4)
+#define FUSE_ATTR_SYNC		(1 << 5)
+#define FUSE_ATTR_IMMUTABLE	(1 << 6)
+#define FUSE_ATTR_APPEND	(1 << 7)
 
 /**
  * Open flags
fs/fuse/dir.c +1 -0
index 5ae6c5639f6d2c..10543873f1a611 100644
@@ -1446,6 +1446,7 @@ static void fuse_fillattr(struct mnt_idmap *idmap, struct inode *inode,
 		blkbits = inode->i_sb->s_blocksize_bits;
 
 	stat->blksize = 1 << blkbits;
+	generic_fill_statx_attr(inode, stat);
 }
 
 static void fuse_statx_to_attr(struct fuse_statx *sx, struct fuse_attr *attr)
fs/fuse/inode.c +1 -0
index 94355977904068..7fcadbfe87a593 100644
@@ -542,6 +542,7 @@ struct inode *fuse_iget(struct super_block *sb, u64 nodeid,
 			inode->i_flags |= S_NOCMTIME;
 		inode->i_generation = generation;
 		fuse_init_inode(inode, attr, fc);
+		fuse_fileattr_init(inode, attr);
 		unlock_new_inode(inode);
 	} else if (fuse_stale_inode(inode, generation, attr)) {
 		/* nodeid was reused, any I/O on the old inode should fail */
fs/fuse/ioctl.c +50 -0

63 lines not on this page · raw message

#78 lore raw

PATCH 4/9 fuse_trace: allow local filesystems to set some VFS iflags

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   29 +++++++++++++++++++++++++++++
 fs/fuse/ioctl.c      |    7 +++++++
 2 files changed, 36 insertions(+)
fs/fuse/fuse_trace.h +29 -0
index 0016242ff34f62..7136ecf25e1f2b 100644
@@ -179,6 +179,35 @@ TRACE_EVENT(fuse_request_end,
 		  __entry->unique, __entry->len, __entry->error)
 );
 
+DECLARE_EVENT_CLASS(fuse_fileattr_class,
+	TP_PROTO(const struct inode *inode, unsigned int old_iflags),
+
+	TP_ARGS(inode, old_iflags),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(unsigned int,		old_iflags)
+		__field(unsigned int,		new_iflags)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->old_iflags	=	old_iflags;
+		__entry->new_iflags	=	inode->i_flags;
+	),
+
+	TP_printk(FUSE_INODE_FMT " old_iflags 0x%x iflags 0x%x",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->old_iflags,
+		  __entry->new_iflags)
+);
+#define DEFINE_FUSE_FILEATTR_EVENT(name)	\
+DEFINE_EVENT(fuse_fileattr_class, name,		\
+	TP_PROTO(const struct inode *inode, unsigned int old_iflags), \
+	TP_ARGS(inode, old_iflags))
+DEFINE_FUSE_FILEATTR_EVENT(fuse_fileattr_update_inode);
+DEFINE_FUSE_FILEATTR_EVENT(fuse_fileattr_init);
+
 #ifdef CONFIG_FUSE_BACKING
 #define FUSE_BACKING_FLAG_STRINGS \
 	{ FUSE_BACKING_TYPE_PASSTHROUGH,	"pass" }, \
fs/fuse/ioctl.c +7 -0
index bd2caf191ce2e0..5180066678e8c1 100644
@@ -4,6 +4,7 @@
  */
 
 #include "fuse_i.h"
+#include "fuse_trace.h"
 
 #include <linux/uio.h>
 #include <linux/compat.h>
@@ -530,12 +531,16 @@ static void fuse_fileattr_update_inode(struct inode *inode,
 		update_iflag(inode, S_APPEND, fa->fsx_xflags & FS_XFLAG_APPEND);
 	}
 
+	trace_fuse_fileattr_update_inode(inode, old_iflags);
+
 	if (old_iflags != inode->i_flags)
 		fuse_invalidate_attr(inode);
 }
 
 void fuse_fileattr_init(struct inode *inode, const struct fuse_attr *attr)
 {
+	unsigned int old_iflags = inode->i_flags;
+
 	if (!fuse_inode_is_exclusive(inode))
 		return;
 
@@ -547,6 +552,8 @@ void fuse_fileattr_init(struct inode *inode, const struct fuse_attr *attr)
 
 	if (attr->flags & FUSE_ATTR_APPEND)
 		inode->i_flags |= S_APPEND;
+
+	trace_fuse_fileattr_init(inode, old_iflags);
 }
 
 int fuse_fileattr_get(struct dentry *dentry, struct file_kattr *fa)
#79 lore raw

PATCH 5/9 fuse: cache atime when in iomap mode

In reply to Darrick J. Wong

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

When we're running in iomap mode, allow the kernel to cache the access timestamp to further reduce the number of roundtrips to the fuse server.

---
 fs/fuse/dir.c        |    5 +++++
 fs/fuse/fuse_iomap.c |    6 ++++++
 fs/fuse/inode.c      |   11 ++++++++---
 3 files changed, 19 insertions(+), 3 deletions(-)
fs/fuse/dir.c +5 -0
index 10543873f1a611..6c05321e32f136 100644
@@ -2232,6 +2232,11 @@ int fuse_flush_times(struct inode *inode, struct fuse_file *ff)
 		inarg.ctime = inode_get_ctime_sec(inode);
 		inarg.ctimensec = inode_get_ctime_nsec(inode);
 	}
+	if (fuse_inode_has_iomap(inode)) {
+		inarg.valid |= FATTR_ATIME;
+		inarg.atime = inode_get_atime_sec(inode);
+		inarg.atimensec = inode_get_atime_nsec(inode);
+	}
 	if (ff) {
 		inarg.valid |= FATTR_FH;
 		inarg.fh = ff->fh;
fs/fuse/fuse_iomap.c +6 -0
index 65c8e06fdd653a..9599efcf1c2593 100644
@@ -1164,6 +1164,12 @@ void fuse_iomap_init_inode(struct inode *inode, struct fuse_attr *attr)
 	if (attr->flags & FUSE_ATTR_ATOMIC)
 		fuse_inode_set_atomic(inode);
 
+	/*
+	 * iomap caches atime too, so we must load it from the fuse server
+	 * at instantiation time.
+	 */
+	inode_set_atime(inode, attr->atime, attr->atimensec);
+
 	trace_fuse_iomap_init_inode(inode);
 }
 
fs/fuse/inode.c +8 -3
index 7fcadbfe87a593..1fedfb57a22514 100644
@@ -266,7 +266,8 @@ void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
 	attr->mtimensec = min_t(u32, attr->mtimensec, NSEC_PER_SEC - 1);
 	attr->ctimensec = min_t(u32, attr->ctimensec, NSEC_PER_SEC - 1);
 
-	inode_set_atime(inode, attr->atime, attr->atimensec);
+	if (!(cache_mask & STATX_ATIME))
+		inode_set_atime(inode, attr->atime, attr->atimensec);
 	/* mtime from server may be stale due to local buffered write */
 	if (!(cache_mask & STATX_MTIME)) {
 		inode_set_mtime(inode, attr->mtime, attr->mtimensec);
@@ -331,8 +332,12 @@ u32 fuse_get_cache_mask(struct inode *inode)
 {
 	struct fuse_conn *fc = get_fuse_conn(inode);
 
-	if (S_ISREG(inode->i_mode) &&
-	    (fuse_inode_has_iomap(inode) || fc->writeback_cache))
+	if (!S_ISREG(inode->i_mode))
+		return 0;
+
+	if (fuse_inode_has_iomap(inode))
+		return STATX_MTIME | STATX_CTIME | STATX_ATIME | STATX_SIZE;
+	if (fc->writeback_cache)
 		return STATX_MTIME | STATX_CTIME | STATX_SIZE;
 
 	return 0;
#80 lore raw

PATCH 6/9 fuse: let the kernel handle KILL_SUID/KILL_SGID for iomap filesystems

In reply to Darrick J. Wong

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

Let the kernel handle killing the suid/sgid bits because the write/falloc/truncate/chown code already does this, and we don't have to worry about external modifications that are only visible to the fuse server (i.e. we're not a cluster fs).

---
 fs/fuse/dir.c |   11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
fs/fuse/dir.c +8 -3
index 6c05321e32f136..069afade99d44f 100644
@@ -2473,6 +2473,7 @@ static int fuse_setattr(struct mnt_idmap *idmap, struct dentry *entry,
 	struct inode *inode = d_inode(entry);
 	struct fuse_conn *fc = get_fuse_conn(inode);
 	struct file *file = (attr->ia_valid & ATTR_FILE) ? attr->ia_file : NULL;
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	int ret;
 
 	if (fuse_is_bad(inode))
@@ -2481,15 +2482,19 @@ static int fuse_setattr(struct mnt_idmap *idmap, struct dentry *entry,
 	if (!fuse_allow_current_process(get_fuse_conn(inode)))
 		return -EACCES;
 
-	if (attr->ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID)) {
+	if (!is_iomap &&
+	    (attr->ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID))) {
 		attr->ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID |
 				    ATTR_MODE);
 
 		/*
 		 * The only sane way to reliably kill suid/sgid is to do it in
-		 * the userspace filesystem
+		 * the userspace filesystem if this isn't an iomap file.  For
+		 * iomap filesystems we let the kernel kill the setuid/setgid
+		 * bits.
 		 *
-		 * This should be done on write(), truncate() and chown().
+		 * This should be done on write(), truncate(), chown(), and
+		 * fallocate().
 		 */
 		if (!fc->handle_killpriv && !fc->handle_killpriv_v2) {
 			/*
#81 lore raw

PATCH 7/9 fuse_trace: let the kernel handle KILL_SUID/KILL_SGID for iomap filesystems

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   58 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/dir.c        |    5 ++++
 2 files changed, 63 insertions(+)
fs/fuse/fuse_trace.h +58 -0
index 7136ecf25e1f2b..a6374d64a62357 100644
@@ -208,6 +208,64 @@ DEFINE_EVENT(fuse_fileattr_class, name,		\
 DEFINE_FUSE_FILEATTR_EVENT(fuse_fileattr_update_inode);
 DEFINE_FUSE_FILEATTR_EVENT(fuse_fileattr_init);
 
+TRACE_EVENT(fuse_setattr_fill,
+	TP_PROTO(const struct inode *inode,
+		 const struct fuse_setattr_in *inarg),
+	TP_ARGS(inode, inarg),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(umode_t,		mode)
+		__field(uint32_t,		valid)
+		__field(umode_t,		new_mode)
+		__field(uint64_t,		new_size)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->mode		=	inode->i_mode;
+		__entry->valid		=	inarg->valid;
+		__entry->new_mode	=	inarg->mode;
+		__entry->new_size	=	inarg->size;
+	),
+
+	TP_printk(FUSE_INODE_FMT " mode 0%o valid 0x%x new_mode 0%o new_size 0x%llx",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->mode,
+		  __entry->valid,
+		  __entry->new_mode,
+		  __entry->new_size)
+);
+
+TRACE_EVENT(fuse_setattr,
+	TP_PROTO(const struct inode *inode,
+		 const struct iattr *inarg),
+	TP_ARGS(inode, inarg),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(umode_t,		mode)
+		__field(uint32_t,		valid)
+		__field(umode_t,		new_mode)
+		__field(uint64_t,		new_size)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->mode		=	inode->i_mode;
+		__entry->valid		=	inarg->ia_valid;
+		__entry->new_mode	=	inarg->ia_mode;
+		__entry->new_size	=	inarg->ia_size;
+	),
+
+	TP_printk(FUSE_INODE_FMT " mode 0%o valid 0x%x new_mode 0%o new_size 0x%llx",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->mode,
+		  __entry->valid,
+		  __entry->new_mode,
+		  __entry->new_size)
+);
+
 #ifdef CONFIG_FUSE_BACKING
 #define FUSE_BACKING_FLAG_STRINGS \
 	{ FUSE_BACKING_TYPE_PASSTHROUGH,	"pass" }, \
fs/fuse/dir.c +5 -0
index 069afade99d44f..4729137fddab30 100644
@@ -8,6 +8,7 @@
 
 #include "fuse_i.h"
 #include "fuse_iomap.h"
+#include "fuse_trace.h"
 
 #include <linux/pagemap.h>
 #include <linux/file.h>
@@ -2201,6 +2202,8 @@ static void fuse_setattr_fill(struct fuse_conn *fc, struct fuse_args *args,
 			      struct fuse_setattr_in *inarg_p,
 			      struct fuse_attr_out *outarg_p)
 {
+	trace_fuse_setattr_fill(inode, inarg_p);
+
 	args->opcode = FUSE_SETATTR;
 	args->nodeid = get_node_id(inode);
 	args->in_numargs = 1;
@@ -2482,6 +2485,8 @@ static int fuse_setattr(struct mnt_idmap *idmap, struct dentry *entry,
 	if (!fuse_allow_current_process(get_fuse_conn(inode)))
 		return -EACCES;
 
+	trace_fuse_setattr(inode, attr);
+
 	if (!is_iomap &&
 	    (attr->ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID))) {
 		attr->ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID |
#82 lore raw

PATCH 8/9 fuse: update ctime when updating acls on an iomap inode

In reply to Darrick J. Wong

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

In iomap mode, the fuse kernel driver is in charge of updating file attributes, so we need to update ctime after an ACL change.

---
 fs/fuse/acl.c |   18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
fs/fuse/acl.c +17 -1
index 483ddf195d40a6..b1e6520ae237cc 100644
@@ -7,6 +7,7 @@
  */
 
 #include "fuse_i.h"
+#include "fuse_iomap.h"
 
 #include <linux/posix_acl.h>
 #include <linux/posix_acl_xattr.h>
@@ -112,6 +113,7 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
 	struct fuse_conn *fc = get_fuse_conn(inode);
 	const char *name;
 	umode_t mode = inode->i_mode;
+	const bool is_iomap = fuse_inode_has_iomap(inode);
 	int ret;
 
 	if (fuse_is_bad(inode))
@@ -179,10 +181,24 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
 			ret = 0;
 	}
 
-	/* If we scheduled a mode update above, push that to userspace now. */
 	if (!ret) {
 		struct iattr attr = { };
 
+		/*
+		 * When we're running in iomap mode, we need to update mode and
+		 * ctime ourselves instead of letting the fuse server figure
+		 * that out.
+		 */
+		if (is_iomap) {
+			attr.ia_valid |= ATTR_CTIME;
+			inode_set_ctime_current(inode);
+			attr.ia_ctime = inode_get_ctime(inode);
+		}
+
+		/*
+		 * If we scheduled a mode update above, push that to userspace
+		 * now.
+		 */
 		if (mode != inode->i_mode) {
 			attr.ia_valid |= ATTR_MODE;
 			attr.ia_mode = mode;
#83 lore raw

PATCH 9/9 fuse: always cache ACLs when using iomap

In reply to Darrick J. Wong

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

Keep ACLs cached in memory when we're using iomap, so that we don't have to make a round trip to the fuse server. This might want to become a FUSE_ATTR_ flag.

---
 fs/fuse/acl.c     |   12 +++++++++---
 fs/fuse/dir.c     |   11 ++++++++---
 fs/fuse/readdir.c |    5 ++++-
 3 files changed, 21 insertions(+), 7 deletions(-)
fs/fuse/acl.c +9 -3
index b1e6520ae237cc..146d80552072bd 100644
@@ -211,10 +211,16 @@ int fuse_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
 	if (fc->posix_acl) {
 		/*
 		 * Fuse daemons without FUSE_POSIX_ACL never cached POSIX ACLs
-		 * and didn't invalidate attributes. Retain that behavior.
+		 * and didn't invalidate attributes. Retain that behavior
+		 * except for iomap, where we assume that only the source of
+		 * ACL changes is userspace.
 		 */
-		forget_all_cached_acls(inode);
-		fuse_invalidate_attr(inode);
+		if (!ret && is_iomap) {
+			set_cached_acl(inode, type, acl);
+		} else {
+			forget_all_cached_acls(inode);
+			fuse_invalidate_attr(inode);
+		}
 	}
 
 	return ret;
fs/fuse/dir.c +8 -3
index 4729137fddab30..7be5185d9506d9 100644
@@ -448,7 +448,8 @@ static int fuse_dentry_revalidate(struct inode *dir, const struct qstr *name,
 		    fuse_stale_inode(inode, outarg.generation, &outarg.attr))
 			goto invalid;
 
-		forget_all_cached_acls(inode);
+		if (!fuse_inode_has_iomap(inode))
+			forget_all_cached_acls(inode);
 		fuse_change_attributes(inode, &outarg.attr, NULL,
 				       ATTR_TIMEOUT(&outarg),
 				       attr_version);
@@ -1663,7 +1664,8 @@ static int fuse_update_get_attr(struct mnt_idmap *idmap, struct inode *inode,
 		sync = time_before64(fi->i_time, get_jiffies_64());
 
 	if (sync) {
-		forget_all_cached_acls(inode);
+		if (!fuse_inode_has_iomap(inode))
+			forget_all_cached_acls(inode);
 		/* Try statx if a field not covered by regular stat is wanted */
 		if (!fc->no_statx && (request_mask & ~STATX_BASIC_STATS)) {
 			err = fuse_do_statx(idmap, inode, file, stat);
@@ -1847,6 +1849,9 @@ static int fuse_access(struct inode *inode, int mask)
 
 static int fuse_perm_getattr(struct inode *inode, int mask)
 {
+	if (fuse_inode_has_iomap(inode))
+		return 0;
+
 	if (mask & MAY_NOT_BLOCK)
 		return -ECHILD;
 
@@ -2530,7 +2535,7 @@ static int fuse_setattr(struct mnt_idmap *idmap, struct dentry *entry,
 		 * If filesystem supports acls it may have updated acl xattrs in
 		 * the filesystem, so forget cached acls for the inode.
 		 */
-		if (fc->posix_acl)
+		if (fc->posix_acl && !is_iomap)
 			forget_all_cached_acls(inode);
 
 		/* Directory mode changed, may need to revalidate access */
fs/fuse/readdir.c +4 -1
index 45dd932eb03a5e..7ecc55049eefc6 100644
@@ -8,6 +8,8 @@
 
 
 #include "fuse_i.h"
+#include "fuse_iomap.h"
+
 #include <linux/iversion.h>
 #include <linux/posix_acl.h>
 #include <linux/pagemap.h>
@@ -224,7 +226,8 @@ static int fuse_direntplus_link(struct file *file,
 		fi->nlookup++;
 		spin_unlock(&fi->lock);
 
-		forget_all_cached_acls(inode);
+		if (!fuse_inode_has_iomap(inode))
+			forget_all_cached_acls(inode);
 		fuse_change_attributes(inode, &o->attr, NULL,
 				       ATTR_TIMEOUT(o),
 				       attr_version);
#84 lore raw

PATCH v7 7/9 fuse: cache iomap mappings for even better file IO performance

In reply to Darrick J. Wong

Hi all,

This series improves the performance (and correctness for some filesystems) by adding the ability to cache iomap mappings in the kernel. For filesystems that can change mapping states during pagecache writeback (e.g. unwritten extent conversion) this is absolutely necessary to deal with races with writes to the pagecache because writeback does not take i_rwsem. For everyone else, it simply eliminates roundtrips to userspace.

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

With a bit of luck, this should all go splendidly. 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-cache
---
Commits in this patchset:
* fuse: cache iomaps
* fuse_trace: cache iomaps
* fuse: use the iomap cache for iomap_begin
* fuse_trace: use the iomap cache for iomap_begin
* fuse: invalidate iomap cache after file updates
* fuse_trace: invalidate iomap cache after file updates
* fuse: enable iomap cache management
* fuse_trace: enable iomap cache management
* fuse: overlay iomap inode info in struct fuse_inode
* fuse: constrain iomap mapping cache size
* fuse_trace: constrain iomap mapping cache size
* fuse: enable iomap

---
 fs/fuse/fuse_i.h           |   11 
 fs/fuse/fuse_iomap.h       |   10 
 fs/fuse/fuse_iomap_cache.h |  121 +++
 fs/fuse/fuse_trace.h       |  445 +++++++++++
 include/uapi/linux/fuse.h  |   41 +
 fs/fuse/Makefile           |    2 
 fs/fuse/dev.c              |   46 +
 fs/fuse/file.c             |   18 
 fs/fuse/fuse_iomap.c       |  533 +++++++++++++
 fs/fuse/fuse_iomap_cache.c | 1797 ++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/trace.c            |    1 
 11 files changed, 3002 insertions(+), 23 deletions(-)
 create mode 100644 fs/fuse/fuse_iomap_cache.h
 create mode 100644 fs/fuse/fuse_iomap_cache.c
#85 lore raw

PATCH 1/12 fuse: cache iomaps

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

Cache iomaps to a file so that we don't have to upcall the server.

---
 fs/fuse/fuse_i.h           |    3 
 fs/fuse/fuse_iomap_cache.h |   99 +++
 include/uapi/linux/fuse.h  |    5 
 fs/fuse/Makefile           |    2 
 fs/fuse/fuse_iomap.c       |    5 
 fs/fuse/fuse_iomap_cache.c | 1701 ++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/trace.c            |    1 
 7 files changed, 1815 insertions(+), 1 deletion(-)
 create mode 100644 fs/fuse/fuse_iomap_cache.h
 create mode 100644 fs/fuse/fuse_iomap_cache.c
fs/fuse/fuse_i.h +3 -0
index b4da866187ba2c..1ba95d1f430c3e 100644
@@ -197,6 +197,9 @@ struct fuse_inode {
 			spinlock_t ioend_lock;
 			struct work_struct ioend_work;
 			struct list_head ioend_list;
+
+			/* cached iomap mappings */
+			struct fuse_iomap_cache *cache;
 #endif
 		};
 
fs/fuse/fuse_iomap_cache.h new file +99 -0

99 lines not on this page · raw message

include/uapi/linux/fuse.h +5 -0
index bf8514a5ee27af..a273838bc20f2f 100644
@@ -1394,6 +1394,8 @@ struct fuse_uring_cmd_req {
 
 /* fuse-specific mapping type indicating that writes use the read mapping */
 #define FUSE_IOMAP_TYPE_PURE_OVERWRITE	(255)
+/* fuse-specific mapping type saying the server has populated the cache */
+#define FUSE_IOMAP_TYPE_RETRY_CACHE	(254)
 
 #define FUSE_IOMAP_DEV_NULL		(0U)	/* null device cookie */
 
@@ -1551,4 +1553,7 @@ struct fuse_iomap_dev_inval_out {
 	struct fuse_range range;
 };
 
+/* invalidate all cached iomap mappings up to EOF */
+#define FUSE_IOMAP_INVAL_TO_EOF		(~0ULL)
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/Makefile +1 -1
index 2536bc6a71b898..c672503da7bcbd 100644
@@ -18,6 +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) += fuse_iomap.o
+fuse-$(CONFIG_FUSE_IOMAP) += fuse_iomap.o fuse_iomap_cache.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/fuse_iomap.c +5 -0
index 9599efcf1c2593..849ce1626c35fd 100644
@@ -14,6 +14,7 @@
 #include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
 #include "fuse_dev_i.h"
+#include "fuse_iomap_cache.h"
 
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
@@ -1179,6 +1180,8 @@ void fuse_iomap_evict_inode(struct inode *inode)
 
 	trace_fuse_iomap_evict_inode(inode);
 
+	if (fuse_inode_caches_iomaps(inode))
+		fuse_iomap_cache_free(inode);
 	fuse_inode_clear_atomic(inode);
 	fuse_inode_clear_iomap(inode);
 }
@@ -1886,6 +1889,8 @@ static inline void fuse_inode_set_iomap(struct inode *inode)
 		min_order = inode->i_blkbits - PAGE_SHIFT;
 
 	mapping_set_folio_min_order(inode->i_mapping, min_order);
+
+	fuse_iomap_cache_init(fi);
 	set_bit(FUSE_I_IOMAP, &fi->state);
 }
 
fs/fuse/fuse_iomap_cache.c new file +1701 -0

1,701 lines not on this page · raw message

fs/fuse/trace.c +1 -0
index 71d444ac1e5021..69310d6f773ffa 100644
@@ -8,6 +8,7 @@
 #include "fuse_dev_i.h"
 #include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
+#include "fuse_iomap_cache.h"
 
 #include <linux/pagemap.h>
 #include <linux/iomap.h>
#86 lore raw

Re: [PATCH 01/12] fuse: cache iomaps

Quoted 1,832 lines · Darrick J. Wong

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

Cache iomaps to a file so that we don't have to upcall the server.

---
 fs/fuse/fuse_i.h           |    3 
 fs/fuse/fuse_iomap_cache.h |   99 +++
 include/uapi/linux/fuse.h  |    5 
 fs/fuse/Makefile           |    2 
 fs/fuse/fuse_iomap.c       |    5 
 fs/fuse/fuse_iomap_cache.c | 1701 ++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/trace.c            |    1 
 7 files changed, 1815 insertions(+), 1 deletion(-)
 create mode 100644 fs/fuse/fuse_iomap_cache.h
 create mode 100644 fs/fuse/fuse_iomap_cache.c
fs/fuse/fuse_i.h +3 -0
index b4da866187ba2c..1ba95d1f430c3e 100644
@@ -197,6 +197,9 @@ struct fuse_inode {
 			spinlock_t ioend_lock;
 			struct work_struct ioend_work;
 			struct list_head ioend_list;
+
+			/* cached iomap mappings */
+			struct fuse_iomap_cache *cache;
 #endif
 		};
 
fs/fuse/fuse_iomap_cache.h new file +99 -0
new file mode 100644
index 00000000000000..922ca182357aa7
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * The fuse_iext code comes from xfs_iext_tree.[ch] and is:
+ * Copyright (c) 2017 Christoph Hellwig.
+ *
+ * Everything else is:
+ * Copyright (C) 2025-2026 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#ifndef _FS_FUSE_IOMAP_CACHE_H
+#define _FS_FUSE_IOMAP_CACHE_H
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP)
+/*
+ * File incore extent information, present for read and write mappings.
+ */
+struct fuse_iext_root {
+	/* bytes in ir_data, or -1 if it has never been used */
+	int64_t			ir_bytes;
+	void			*ir_data;	/* extent tree root */
+	unsigned int		ir_height;	/* height of the extent tree */
+};
+
+struct fuse_iomap_cache {
+	struct fuse_iext_root	ic_read;
+	struct fuse_iext_root	ic_write;
+	uint64_t		ic_seq;		/* validity counter */
+	struct rw_semaphore	ic_lock;	/* mapping lock */
+	struct inode		*ic_inode;
+};
+
+void fuse_iomap_cache_lock(struct inode *inode);
+void fuse_iomap_cache_unlock(struct inode *inode);
+void fuse_iomap_cache_lock_shared(struct inode *inode);
+void fuse_iomap_cache_unlock_shared(struct inode *inode);
+
+struct fuse_iext_leaf;
+
+struct fuse_iext_cursor {
+	struct fuse_iext_leaf	*leaf;
+	int			pos;
+};
+
+#define FUSE_IEXT_LEFT_CONTIG	(1u << 0)
+#define FUSE_IEXT_RIGHT_CONTIG	(1u << 1)
+#define FUSE_IEXT_LEFT_FILLING	(1u << 2)
+#define FUSE_IEXT_RIGHT_FILLING	(1u << 3)
+#define FUSE_IEXT_LEFT_VALID	(1u << 4)
+#define FUSE_IEXT_RIGHT_VALID	(1u << 5)
+#define FUSE_IEXT_WRITE_MAPPING	(1u << 6)
+
+bool fuse_iext_get_extent(const struct fuse_iext_root *ir,
+			  const struct fuse_iext_cursor *cur,
+			  struct fuse_iomap_io *gotp);
+
+static inline uint64_t fuse_iext_read_seq(struct fuse_iomap_cache *ic)
+{
+	return (uint64_t)READ_ONCE(ic->ic_seq);
+}
+
+static inline void fuse_iomap_cache_init(struct fuse_inode *fi)
+{
+	fi->cache = NULL;
+}
+
+static inline bool fuse_inode_caches_iomaps(const struct inode *inode)
+{
+	const struct fuse_inode *fi = get_fuse_inode(inode);
+
+	return fi->cache != NULL;
+}
+
+int fuse_iomap_cache_alloc(struct inode *inode);
+void fuse_iomap_cache_free(struct inode *inode);
+
+int fuse_iomap_cache_remove(struct inode *inode, enum fuse_iomap_iodir iodir,
+			    loff_t off, uint64_t len);
+
+int fuse_iomap_cache_upsert(struct inode *inode, enum fuse_iomap_iodir iodir,
+			    const struct fuse_iomap_io *map);
+
+enum fuse_iomap_lookup_result {
+	LOOKUP_HIT,
+	LOOKUP_MISS,
+	LOOKUP_NOFORK,
+};
+
+struct fuse_iomap_lookup {
+	struct fuse_iomap_io	map;		 /* cached mapping */
+	uint64_t		validity_cookie; /* used with .iomap_valid() */
+};
+
+enum fuse_iomap_lookup_result
+fuse_iomap_cache_lookup(struct inode *inode, enum fuse_iomap_iodir iodir,
+			loff_t off, uint64_t len,
+			struct fuse_iomap_lookup *mval);
+#endif /* CONFIG_FUSE_IOMAP */
+
+#endif /* _FS_FUSE_IOMAP_CACHE_H */
include/uapi/linux/fuse.h +5 -0
index bf8514a5ee27af..a273838bc20f2f 100644
@@ -1394,6 +1394,8 @@ struct fuse_uring_cmd_req {
 
 /* fuse-specific mapping type indicating that writes use the read mapping */
 #define FUSE_IOMAP_TYPE_PURE_OVERWRITE	(255)
+/* fuse-specific mapping type saying the server has populated the cache */
+#define FUSE_IOMAP_TYPE_RETRY_CACHE	(254)
 
 #define FUSE_IOMAP_DEV_NULL		(0U)	/* null device cookie */
 
@@ -1551,4 +1553,7 @@ struct fuse_iomap_dev_inval_out {
 	struct fuse_range range;
 };
 
+/* invalidate all cached iomap mappings up to EOF */
+#define FUSE_IOMAP_INVAL_TO_EOF		(~0ULL)
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/Makefile +1 -1
index 2536bc6a71b898..c672503da7bcbd 100644
@@ -18,6 +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) += fuse_iomap.o
+fuse-$(CONFIG_FUSE_IOMAP) += fuse_iomap.o fuse_iomap_cache.o
 
 virtiofs-y := virtio_fs.o
fs/fuse/fuse_iomap.c +5 -0
index 9599efcf1c2593..849ce1626c35fd 100644
@@ -14,6 +14,7 @@
 #include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
 #include "fuse_dev_i.h"
+#include "fuse_iomap_cache.h"
 
 static bool __read_mostly enable_iomap =
 #if IS_ENABLED(CONFIG_FUSE_IOMAP_BY_DEFAULT)
@@ -1179,6 +1180,8 @@ void fuse_iomap_evict_inode(struct inode *inode)
 
 	trace_fuse_iomap_evict_inode(inode);
 
+	if (fuse_inode_caches_iomaps(inode))
+		fuse_iomap_cache_free(inode);
 	fuse_inode_clear_atomic(inode);
 	fuse_inode_clear_iomap(inode);
 }
@@ -1886,6 +1889,8 @@ static inline void fuse_inode_set_iomap(struct inode *inode)
 		min_order = inode->i_blkbits - PAGE_SHIFT;
 
 	mapping_set_folio_min_order(inode->i_mapping, min_order);
+
+	fuse_iomap_cache_init(fi);
 	set_bit(FUSE_I_IOMAP, &fi->state);
 }
 
fs/fuse/fuse_iomap_cache.c new file +1626 -0
new file mode 100644
index 00000000000000..e32de8a5e3c325
@@ -0,0 +1,1701 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * fuse_iext* code adapted from xfs_iext_tree.c:
+ * Copyright (c) 2017 Christoph Hellwig.
+ *
+ * fuse_iomap_cache*lock* code adapted from xfs_inode.c:
+ * Copyright (c) 2000-2006 Silicon Graphics, Inc.
+ * All Rights Reserved.
+ *
+ * Copyright (C) 2025-2026 Oracle.  All Rights Reserved.
+ * Author: Darrick J. Wong <[email protected]>
+ */
+#include "fuse_i.h"
+#include "fuse_trace.h"
+#include "fuse_iomap_i.h"
+#include "fuse_iomap.h"
+#include "fuse_iomap_cache.h"
+#include <linux/iomap.h>
+
+void fuse_iomap_cache_lock_shared(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *ic = fi->cache;
+
+	down_read(&ic->ic_lock);
+}
+
+void fuse_iomap_cache_unlock_shared(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *ic = fi->cache;
+
+	up_read(&ic->ic_lock);
+}
+
+void fuse_iomap_cache_lock(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *ic = fi->cache;
+
+	down_write(&ic->ic_lock);
+}
+
+void fuse_iomap_cache_unlock(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *ic = fi->cache;
+
+	up_write(&ic->ic_lock);
+}
+
+static inline void assert_cache_locked_shared(struct fuse_iomap_cache *ic)
+{
+	rwsem_assert_held(&ic->ic_lock);
+}
+
+static inline void assert_cache_locked(struct fuse_iomap_cache *ic)
+{
+	rwsem_assert_held_write_nolockdep(&ic->ic_lock);
+}
+
+/*
+ * In-core extent btree block layout:
+ *
+ * There are two types of blocks in the btree: leaf and inner (non-leaf) blocks.
+ *
+ * The leaf blocks are made up by %KEYS_PER_NODE extent records, which each
+ * contain the startoffset, blockcount, startblock and unwritten extent flag.
+ * See above for the exact format, followed by pointers to the previous and next
+ * leaf blocks (if there are any).
+ *
+ * The inner (non-leaf) blocks first contain KEYS_PER_NODE lookup keys, followed
+ * by an equal number of pointers to the btree blocks at the next lower level.
+ *
+ *		+-------+-------+-------+-------+-------+----------+----------+
+ * Leaf:	| rec 1 | rec 2 | rec 3 | rec 4 | rec N | prev-ptr | next-ptr |
+ *		+-------+-------+-------+-------+-------+----------+----------+
+ *
+ *		+-------+-------+-------+-------+-------+-------+------+-------+
+ * Inner:	| key 1 | key 2 | key 3 | key N | ptr 1 | ptr 2 | ptr3 | ptr N |
+ *		+-------+-------+-------+-------+-------+-------+------+-------+
+ */
+typedef uint64_t fuse_iext_key_t;
+#define FUSE_IEXT_KEY_INVALID	(1ULL << 63)
+
+enum {
+	NODE_SIZE	= 256,
+	KEYS_PER_NODE	= NODE_SIZE / (sizeof(fuse_iext_key_t) + sizeof(void *)),
+	RECS_PER_LEAF	= (NODE_SIZE - (2 * sizeof(struct fuse_iext_leaf *))) /
+				sizeof(struct fuse_iomap_io),
+};
+
+/* maximum length of a mapping that we're willing to cache */
+#define FUSE_IOMAP_MAX_LEN	((loff_t)(1ULL << 63))
+
+struct fuse_iext_node {
+	fuse_iext_key_t		keys[KEYS_PER_NODE];
+	void			*ptrs[KEYS_PER_NODE];
+};
+
+struct fuse_iext_leaf {
+	struct fuse_iomap_io	recs[RECS_PER_LEAF];
+	struct fuse_iext_leaf	*prev;
+	struct fuse_iext_leaf	*next;
+};
+
+static uint32_t
+fuse_iomap_fork_to_state(const struct fuse_iomap_cache *ic,
+			 const struct fuse_iext_root *ir)
+{
+	ASSERT(ir == &ic->ic_write || ir == &ic->ic_read);
+
+	if (ir == &ic->ic_write)
+		return FUSE_IEXT_WRITE_MAPPING;
+	return 0;
+}
+
+/* Convert bmap state flags to an inode fork. */
+static struct fuse_iext_root *
+fuse_iext_state_to_fork(
+	struct fuse_iomap_cache	*ic,
+	uint32_t		state)
+{
+	if (state & FUSE_IEXT_WRITE_MAPPING)
+		return &ic->ic_write;
+	return &ic->ic_read;
+}
+
+/* The internal iext tree record is a struct fuse_iomap_io */
+
+static inline bool fuse_iext_rec_is_empty(const struct fuse_iomap_io *rec)
+{
+	return rec->length == 0;
+}
+
+static inline void fuse_iext_rec_clear(struct fuse_iomap_io *rec)
+{
+	memset(rec, 0, sizeof(*rec));
+}
+
+static inline void
+fuse_iext_set(
+	struct fuse_iomap_io		*rec,
+	const struct fuse_iomap_io	*irec)
+{
+	ASSERT(irec->length > 0);
+
+	*rec = *irec;
+}
+
+static inline void
+fuse_iext_get(
+	struct fuse_iomap_io		*irec,
+	const struct fuse_iomap_io	*rec)
+{
+	*irec = *rec;
+}
+
+static inline uint64_t fuse_iext_count(const struct fuse_iext_root *ir)
+{
+	return ir->ir_bytes / sizeof(struct fuse_iomap_io);
+}
+
+static inline int fuse_iext_max_recs(const struct fuse_iext_root *ir)
+{
+	if (ir->ir_height == 1)
+		return fuse_iext_count(ir);
+	return RECS_PER_LEAF;
+}
+
+static inline struct fuse_iomap_io *cur_rec(const struct fuse_iext_cursor *cur)
+{
+	return &cur->leaf->recs[cur->pos];
+}
+
+static bool fuse_iext_valid(const struct fuse_iext_root *ir,
+				   const struct fuse_iext_cursor *cur)
+{
+	if (!cur->leaf)
+		return false;
+	if (cur->pos < 0 || cur->pos >= fuse_iext_max_recs(ir))
+		return false;
+	if (fuse_iext_rec_is_empty(cur_rec(cur)))
+		return false;
+	return true;
+}
+
+static void *
+fuse_iext_find_first_leaf(
+	struct fuse_iext_root	*ir)
+{
+	struct fuse_iext_node	*node = ir->ir_data;
+	int			height;
+
+	if (!ir->ir_height)
+		return NULL;
+
+	for (height = ir->ir_height; height > 1; height--) {
+		node = node->ptrs[0];
+		ASSERT(node);
+	}
+
+	return node;
+}
+
+static void *
+fuse_iext_find_last_leaf(
+	struct fuse_iext_root	*ir)
+{
+	struct fuse_iext_node	*node = ir->ir_data;
+	int			height, i;
+
+	if (!ir->ir_height)
+		return NULL;
+
+	for (height = ir->ir_height; height > 1; height--) {
+		for (i = 1; i < KEYS_PER_NODE; i++)
+			if (!node->ptrs[i])
+				break;
+		node = node->ptrs[i - 1];
+		ASSERT(node);
+	}
+
+	return node;
+}
+
+static void
+fuse_iext_first(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	cur->pos = 0;
+	cur->leaf = fuse_iext_find_first_leaf(ir);
+}
+
+static void
+fuse_iext_last(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	int			i;
+
+	cur->leaf = fuse_iext_find_last_leaf(ir);
+	if (!cur->leaf) {
+		cur->pos = 0;
+		return;
+	}
+
+	for (i = 1; i < fuse_iext_max_recs(ir); i++) {
+		if (fuse_iext_rec_is_empty(&cur->leaf->recs[i]))
+			break;
+	}
+	cur->pos = i - 1;
+}
+
+static void
+fuse_iext_next(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	if (!cur->leaf) {
+		ASSERT(cur->pos <= 0 || cur->pos >= RECS_PER_LEAF);
+		fuse_iext_first(ir, cur);
+		return;
+	}
+
+	ASSERT(cur->pos >= 0);
+	ASSERT(cur->pos < fuse_iext_max_recs(ir));
+
+	cur->pos++;
+	if (ir->ir_height > 1 && !fuse_iext_valid(ir, cur) &&
+	    cur->leaf->next) {
+		cur->leaf = cur->leaf->next;
+		cur->pos = 0;
+	}
+}
+
+static void
+fuse_iext_prev(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	if (!cur->leaf) {
+		ASSERT(cur->pos <= 0 || cur->pos >= RECS_PER_LEAF);
+		fuse_iext_last(ir, cur);
+		return;
+	}
+
+	ASSERT(cur->pos >= 0);
+	ASSERT(cur->pos <= RECS_PER_LEAF);
+
+recurse:
+	do {
+		cur->pos--;
+		if (fuse_iext_valid(ir, cur))
+			return;
+	} while (cur->pos > 0);
+
+	if (ir->ir_height > 1 && cur->leaf->prev) {
+		cur->leaf = cur->leaf->prev;
+		cur->pos = RECS_PER_LEAF;
+		goto recurse;
+	}
+}
+
+/*
+ * Return true if the cursor points at an extent and return the extent structure
+ * in gotp.  Else return false.
+ */
+bool
+fuse_iext_get_extent(
+	const struct fuse_iext_root	*ir,
+	const struct fuse_iext_cursor	*cur,
+	struct fuse_iomap_io		*gotp)
+{
+	if (!fuse_iext_valid(ir, cur))
+		return false;
+	fuse_iext_get(gotp, cur_rec(cur));
+	return true;
+}
+
+static inline bool fuse_iext_next_extent(struct fuse_iext_root *ir,
+		struct fuse_iext_cursor *cur, struct fuse_iomap_io *gotp)
+{
+	fuse_iext_next(ir, cur);
+	return fuse_iext_get_extent(ir, cur, gotp);
+}
+
+static inline bool fuse_iext_prev_extent(struct fuse_iext_root *ir,
+		struct fuse_iext_cursor *cur, struct fuse_iomap_io *gotp)
+{
+	fuse_iext_prev(ir, cur);
+	return fuse_iext_get_extent(ir, cur, gotp);
+}
+
+/*
+ * Return the extent after cur in gotp without updating the cursor.
+ */
+static inline bool fuse_iext_peek_next_extent(struct fuse_iext_root *ir,
+		struct fuse_iext_cursor *cur, struct fuse_iomap_io *gotp)
+{
+	struct fuse_iext_cursor ncur = *cur;
+
+	fuse_iext_next(ir, &ncur);
+	return fuse_iext_get_extent(ir, &ncur, gotp);
+}
+
+/*
+ * Return the extent before cur in gotp without updating the cursor.
+ */
+static inline bool fuse_iext_peek_prev_extent(struct fuse_iext_root *ir,
+		struct fuse_iext_cursor *cur, struct fuse_iomap_io *gotp)
+{
+	struct fuse_iext_cursor ncur = *cur;
+
+	fuse_iext_prev(ir, &ncur);
+	return fuse_iext_get_extent(ir, &ncur, gotp);
+}
+
+static inline int
+fuse_iext_key_cmp(
+	struct fuse_iext_node	*node,
+	int			n,
+	loff_t			offset)
+{
+	if (node->keys[n] > offset)
+		return 1;
+	if (node->keys[n] < offset)
+		return -1;
+	return 0;
+}
+
+static inline int
+fuse_iext_rec_cmp(
+	struct fuse_iomap_io	*rec,
+	loff_t			offset)
+{
+	if (rec->offset > offset)
+		return 1;
+	if (rec->offset + rec->length <= offset)
+		return -1;
+	return 0;
+}
+
+static void *
+fuse_iext_find_level(
+	struct fuse_iext_root	*ir,
+	loff_t			offset,
+	int			level)
+{
+	struct fuse_iext_node	*node = ir->ir_data;
+	int			height, i;
+
+	if (!ir->ir_height)
+		return NULL;
+
+	for (height = ir->ir_height; height > level; height--) {
+		for (i = 1; i < KEYS_PER_NODE; i++)
+			if (fuse_iext_key_cmp(node, i, offset) > 0)
+				break;
+
+		node = node->ptrs[i - 1];
+		if (!node)
+			break;
+	}
+
+	return node;
+}
+
+static int
+fuse_iext_node_pos(
+	struct fuse_iext_node	*node,
+	loff_t			offset)
+{
+	int			i;
+
+	for (i = 1; i < KEYS_PER_NODE; i++) {
+		if (fuse_iext_key_cmp(node, i, offset) > 0)
+			break;
+	}
+
+	return i - 1;
+}
+
+static int
+fuse_iext_node_insert_pos(
+	struct fuse_iext_node	*node,
+	loff_t			offset)
+{
+	int			i;
+
+	for (i = 0; i < KEYS_PER_NODE; i++) {
+		if (fuse_iext_key_cmp(node, i, offset) > 0)
+			return i;
+	}
+
+	return KEYS_PER_NODE;
+}
+
+static int
+fuse_iext_node_nr_entries(
+	struct fuse_iext_node	*node,
+	int			start)
+{
+	int			i;
+
+	for (i = start; i < KEYS_PER_NODE; i++) {
+		if (node->keys[i] == FUSE_IEXT_KEY_INVALID)
+			break;
+	}
+
+	return i;
+}
+
+static int
+fuse_iext_leaf_nr_entries(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_leaf	*leaf,
+	int			start)
+{
+	int			i;
+
+	for (i = start; i < fuse_iext_max_recs(ir); i++) {
+		if (fuse_iext_rec_is_empty(&leaf->recs[i]))
+			break;
+	}
+
+	return i;
+}
+
+static inline fuse_iext_key_t
+fuse_iext_leaf_key(
+	struct fuse_iext_leaf	*leaf,
+	int			n)
+{
+	return leaf->recs[n].offset;
+}
+
+static inline void *
+fuse_iext_alloc_node(
+	int	size)
+{
+	return kzalloc(size, GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
+}
+
+static void
+fuse_iext_grow(
+	struct fuse_iext_root	*ir)
+{
+	struct fuse_iext_node	*node = fuse_iext_alloc_node(NODE_SIZE);
+	int			i;
+
+	if (ir->ir_height == 1) {
+		struct fuse_iext_leaf *prev = ir->ir_data;
+
+		node->keys[0] = fuse_iext_leaf_key(prev, 0);
+		node->ptrs[0] = prev;
+	} else  {
+		struct fuse_iext_node *prev = ir->ir_data;
+
+		ASSERT(ir->ir_height > 1);
+
+		node->keys[0] = prev->keys[0];
+		node->ptrs[0] = prev;
+	}
+
+	for (i = 1; i < KEYS_PER_NODE; i++)
+		node->keys[i] = FUSE_IEXT_KEY_INVALID;
+
+	ir->ir_data = node;
+	ir->ir_height++;
+}
+
+static void
+fuse_iext_update_node(
+	struct fuse_iext_root	*ir,
+	loff_t			old_offset,
+	loff_t			new_offset,
+	int			level,
+	void			*ptr)
+{
+	struct fuse_iext_node	*node = ir->ir_data;
+	int			height, i;
+
+	for (height = ir->ir_height; height > level; height--) {
+		for (i = 0; i < KEYS_PER_NODE; i++) {
+			if (i > 0 && fuse_iext_key_cmp(node, i, old_offset) > 0)
+				break;
+			if (node->keys[i] == old_offset)
+				node->keys[i] = new_offset;
+		}
+		node = node->ptrs[i - 1];
+		ASSERT(node);
+	}
+
+	ASSERT(node == ptr);
+}
+
+static struct fuse_iext_node *
+fuse_iext_split_node(
+	struct fuse_iext_node	**nodep,
+	int			*pos,
+	int			*nr_entries)
+{
+	struct fuse_iext_node	*node = *nodep;
+	struct fuse_iext_node	*new = fuse_iext_alloc_node(NODE_SIZE);
+	const int		nr_move = KEYS_PER_NODE / 2;
+	int			nr_keep = nr_move + (KEYS_PER_NODE & 1);
+	int			i = 0;
+
+	/* for sequential append operations just spill over into the new node */
+	if (*pos == KEYS_PER_NODE) {
+		*nodep = new;
+		*pos = 0;
+		*nr_entries = 0;
+		goto done;
+	}
+
+
+	for (i = 0; i < nr_move; i++) {
+		new->keys[i] = node->keys[nr_keep + i];
+		new->ptrs[i] = node->ptrs[nr_keep + i];
+
+		node->keys[nr_keep + i] = FUSE_IEXT_KEY_INVALID;
+		node->ptrs[nr_keep + i] = NULL;
+	}
+
+	if (*pos >= nr_keep) {
+		*nodep = new;
+		*pos -= nr_keep;
+		*nr_entries = nr_move;
+	} else {
+		*nr_entries = nr_keep;
+	}
+done:
+	for (; i < KEYS_PER_NODE; i++)
+		new->keys[i] = FUSE_IEXT_KEY_INVALID;
+	return new;
+}
+
+static void
+fuse_iext_insert_node(
+	struct fuse_iext_root	*ir,
+	fuse_iext_key_t		offset,
+	void			*ptr,
+	int			level)
+{
+	struct fuse_iext_node	*node, *new;
+	int			i, pos, nr_entries;
+
+again:
+	if (ir->ir_height < level)
+		fuse_iext_grow(ir);
+
+	new = NULL;
+	node = fuse_iext_find_level(ir, offset, level);
+	pos = fuse_iext_node_insert_pos(node, offset);
+	nr_entries = fuse_iext_node_nr_entries(node, pos);
+
+	ASSERT(pos >= nr_entries || fuse_iext_key_cmp(node, pos, offset) != 0);
+	ASSERT(nr_entries <= KEYS_PER_NODE);
+
+	if (nr_entries == KEYS_PER_NODE)
+		new = fuse_iext_split_node(&node, &pos, &nr_entries);
+
+	/*
+	 * Update the pointers in higher levels if the first entry changes
+	 * in an existing node.
+	 */
+	if (node != new && pos == 0 && nr_entries > 0)
+		fuse_iext_update_node(ir, node->keys[0], offset, level, node);
+
+	for (i = nr_entries; i > pos; i--) {
+		node->keys[i] = node->keys[i - 1];
+		node->ptrs[i] = node->ptrs[i - 1];
+	}
+	node->keys[pos] = offset;
+	node->ptrs[pos] = ptr;
+
+	if (new) {
+		offset = new->keys[0];
+		ptr = new;
+		level++;
+		goto again;
+	}
+}
+
+static struct fuse_iext_leaf *
+fuse_iext_split_leaf(
+	struct fuse_iext_cursor	*cur,
+	int			*nr_entries)
+{
+	struct fuse_iext_leaf	*leaf = cur->leaf;
+	struct fuse_iext_leaf	*new = fuse_iext_alloc_node(NODE_SIZE);
+	const int		nr_move = RECS_PER_LEAF / 2;
+	int			nr_keep = nr_move + (RECS_PER_LEAF & 1);
+	int			i;
+
+	/* for sequential append operations just spill over into the new node */
+	if (cur->pos == RECS_PER_LEAF) {
+		cur->leaf = new;
+		cur->pos = 0;
+		*nr_entries = 0;
+		goto done;
+	}
+
+	for (i = 0; i < nr_move; i++) {
+		new->recs[i] = leaf->recs[nr_keep + i];
+		fuse_iext_rec_clear(&leaf->recs[nr_keep + i]);
+	}
+
+	if (cur->pos >= nr_keep) {
+		cur->leaf = new;
+		cur->pos -= nr_keep;
+		*nr_entries = nr_move;
+	} else {
+		*nr_entries = nr_keep;
+	}
+done:
+	if (leaf->next)
+		leaf->next->prev = new;
+	new->next = leaf->next;
+	new->prev = leaf;
+	leaf->next = new;
+	return new;
+}
+
+static void
+fuse_iext_alloc_root(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	ASSERT(ir->ir_bytes == 0);
+
+	ir->ir_data = fuse_iext_alloc_node(sizeof(struct fuse_iomap_io));
+	ir->ir_height = 1;
+
+	/* now that we have a node step into it */
+	cur->leaf = ir->ir_data;
+	cur->pos = 0;
+}
+
+static void
+fuse_iext_realloc_root(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur)
+{
+	int64_t new_size = ir->ir_bytes + sizeof(struct fuse_iomap_io);
+	void *new;
+
+	/* account for the prev/next pointers */
+	if (new_size / sizeof(struct fuse_iomap_io) == RECS_PER_LEAF)
+		new_size = NODE_SIZE;
+
+	new = krealloc(ir->ir_data, new_size,
+			GFP_KERNEL | __GFP_NOLOCKDEP | __GFP_NOFAIL);
+	memset(new + ir->ir_bytes, 0, new_size - ir->ir_bytes);
+	ir->ir_data = new;
+	cur->leaf = new;
+}
+
+/*
+ * Increment the sequence counter on extent tree changes. We use WRITE_ONCE
+ * here to ensure the update to the sequence counter is seen before the
+ * modifications to the extent tree itself take effect.
+ */
+static inline void fuse_iext_inc_seq(struct fuse_iomap_cache *ic)
+{
+	WRITE_ONCE(ic->ic_seq, READ_ONCE(ic->ic_seq) + 1);
+}
+
+static void
+fuse_iext_insert_raw(
+	struct fuse_iomap_cache		*ic,
+	struct fuse_iext_root		*ir,
+	struct fuse_iext_cursor		*cur,
+	const struct fuse_iomap_io	*irec)
+{
+	loff_t				offset = irec->offset;
+	struct fuse_iext_leaf		*new = NULL;
+	int				nr_entries, i;
+
+	fuse_iext_inc_seq(ic);
+
+	if (ir->ir_height == 0)
+		fuse_iext_alloc_root(ir, cur);
+	else if (ir->ir_height == 1)
+		fuse_iext_realloc_root(ir, cur);
+
+	nr_entries = fuse_iext_leaf_nr_entries(ir, cur->leaf, cur->pos);
+	ASSERT(nr_entries <= RECS_PER_LEAF);
+	ASSERT(cur->pos >= nr_entries ||
+	       fuse_iext_rec_cmp(cur_rec(cur), irec->offset) != 0);
+
+	if (nr_entries == RECS_PER_LEAF)
+		new = fuse_iext_split_leaf(cur, &nr_entries);
+
+	/*
+	 * Update the pointers in higher levels if the first entry changes
+	 * in an existing node.
+	 */
+	if (cur->leaf != new && cur->pos == 0 && nr_entries > 0) {
+		fuse_iext_update_node(ir, fuse_iext_leaf_key(cur->leaf, 0),
+				offset, 1, cur->leaf);
+	}
+
+	for (i = nr_entries; i > cur->pos; i--)
+		cur->leaf->recs[i] = cur->leaf->recs[i - 1];
+	fuse_iext_set(cur_rec(cur), irec);
+	ir->ir_bytes += sizeof(struct fuse_iomap_io);
+
+	if (new)
+		fuse_iext_insert_node(ir, fuse_iext_leaf_key(new, 0), new, 2);
+}
+
+static void
+fuse_iext_insert(
+	struct fuse_iomap_cache		*ic,
+	struct fuse_iext_cursor		*cur,
+	const struct fuse_iomap_io	*irec,
+	uint32_t			state)
+{
+	struct fuse_iext_root		*ir = fuse_iext_state_to_fork(ic, state);
+
+	fuse_iext_insert_raw(ic, ir, cur, irec);
+}
+
+static struct fuse_iext_node *
+fuse_iext_rebalance_node(
+	struct fuse_iext_node	*parent,
+	int			*pos,
+	struct fuse_iext_node	*node,
+	int			nr_entries)
+{
+	/*
+	 * If the neighbouring nodes are completely full, or have different
+	 * parents, we might never be able to merge our node, and will only
+	 * delete it once the number of entries hits zero.
+	 */
+	if (nr_entries == 0)
+		return node;
+
+	if (*pos > 0) {
+		struct fuse_iext_node *prev = parent->ptrs[*pos - 1];
+		int nr_prev = fuse_iext_node_nr_entries(prev, 0), i;
+
+		if (nr_prev + nr_entries <= KEYS_PER_NODE) {
+			for (i = 0; i < nr_entries; i++) {
+				prev->keys[nr_prev + i] = node->keys[i];
+				prev->ptrs[nr_prev + i] = node->ptrs[i];
+			}
+			return node;
+		}
+	}
+
+	if (*pos + 1 < fuse_iext_node_nr_entries(parent, *pos)) {
+		struct fuse_iext_node *next = parent->ptrs[*pos + 1];
+		int nr_next = fuse_iext_node_nr_entries(next, 0), i;
+
+		if (nr_entries + nr_next <= KEYS_PER_NODE) {
+			/*
+			 * Merge the next node into this node so that we don't
+			 * have to do an additional update of the keys in the
+			 * higher levels.
+			 */
+			for (i = 0; i < nr_next; i++) {
+				node->keys[nr_entries + i] = next->keys[i];
+				node->ptrs[nr_entries + i] = next->ptrs[i];
+			}
+
+			++*pos;
+			return next;
+		}
+	}
+
+	return NULL;
+}
+
+static void
+fuse_iext_remove_node(
+	struct fuse_iext_root	*ir,
+	loff_t			offset,
+	void			*victim)
+{
+	struct fuse_iext_node	*node, *parent;
+	int			level = 2, pos, nr_entries, i;
+
+	ASSERT(level <= ir->ir_height);
+	node = fuse_iext_find_level(ir, offset, level);
+	pos = fuse_iext_node_pos(node, offset);
+again:
+	ASSERT(node->ptrs[pos]);
+	ASSERT(node->ptrs[pos] == victim);
+	kfree(victim);
+
+	nr_entries = fuse_iext_node_nr_entries(node, pos) - 1;
+	offset = node->keys[0];
+	for (i = pos; i < nr_entries; i++) {
+		node->keys[i] = node->keys[i + 1];
+		node->ptrs[i] = node->ptrs[i + 1];
+	}
+	node->keys[nr_entries] = FUSE_IEXT_KEY_INVALID;
+	node->ptrs[nr_entries] = NULL;
+
+	if (pos == 0 && nr_entries > 0) {
+		fuse_iext_update_node(ir, offset, node->keys[0], level, node);
+		offset = node->keys[0];
+	}
+
+	if (nr_entries >= KEYS_PER_NODE / 2)
+		return;
+
+	if (level < ir->ir_height) {
+		/*
+		 * If we aren't at the root yet try to find a neighbour node to
+		 * merge with (or delete the node if it is empty), and then
+		 * recurse up to the next level.
+		 */
+		level++;
+		parent = fuse_iext_find_level(ir, offset, level);
+		pos = fuse_iext_node_pos(parent, offset);
+
+		ASSERT(pos != KEYS_PER_NODE);
+		ASSERT(parent->ptrs[pos] == node);
+
+		node = fuse_iext_rebalance_node(parent, &pos, node, nr_entries);
+		if (node) {
+			victim = node;
+			node = parent;
+			goto again;
+		}
+	} else if (nr_entries == 1) {
+		/*
+		 * If we are at the root and only one entry is left we can just
+		 * free this node and update the root pointer.
+		 */
+		ASSERT(node == ir->ir_data);
+		ir->ir_data = node->ptrs[0];
+		ir->ir_height--;
+		kfree(node);
+	}
+}
+
+static void
+fuse_iext_rebalance_leaf(
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*cur,
+	struct fuse_iext_leaf	*leaf,
+	loff_t			offset,
+	int			nr_entries)
+{
+	/*
+	 * If the neighbouring nodes are completely full we might never be able
+	 * to merge our node, and will only delete it once the number of
+	 * entries hits zero.
+	 */
+	if (nr_entries == 0)
+		goto remove_node;
+
+	if (leaf->prev) {
+		int nr_prev = fuse_iext_leaf_nr_entries(ir, leaf->prev, 0), i;
+
+		if (nr_prev + nr_entries <= RECS_PER_LEAF) {
+			for (i = 0; i < nr_entries; i++)
+				leaf->prev->recs[nr_prev + i] = leaf->recs[i];
+
+			if (cur->leaf == leaf) {
+				cur->leaf = leaf->prev;
+				cur->pos += nr_prev;
+			}
+			goto remove_node;
+		}
+	}
+
+	if (leaf->next) {
+		int nr_next = fuse_iext_leaf_nr_entries(ir, leaf->next, 0), i;
+
+		if (nr_entries + nr_next <= RECS_PER_LEAF) {
+			/*
+			 * Merge the next node into this node so that we don't
+			 * have to do an additional update of the keys in the
+			 * higher levels.
+			 */
+			for (i = 0; i < nr_next; i++) {
+				leaf->recs[nr_entries + i] =
+					leaf->next->recs[i];
+			}
+
+			if (cur->leaf == leaf->next) {
+				cur->leaf = leaf;
+				cur->pos += nr_entries;
+			}
+
+			offset = fuse_iext_leaf_key(leaf->next, 0);
+			leaf = leaf->next;
+			goto remove_node;
+		}
+	}
+
+	return;
+remove_node:
+	if (leaf->prev)
+		leaf->prev->next = leaf->next;
+	if (leaf->next)
+		leaf->next->prev = leaf->prev;
+	fuse_iext_remove_node(ir, offset, leaf);
+}
+
+static void
+fuse_iext_free_last_leaf(
+	struct fuse_iext_root	*ir)
+{
+	ir->ir_height--;
+	kfree(ir->ir_data);
+	ir->ir_data = NULL;
+}
+
+static void
+fuse_iext_remove(
+	struct fuse_iomap_cache	*ic,
+	struct fuse_iext_cursor	*cur,
+	uint32_t		state)
+{
+	struct fuse_iext_root	*ir = fuse_iext_state_to_fork(ic, state);
+	struct fuse_iext_leaf	*leaf = cur->leaf;
+	loff_t			offset = fuse_iext_leaf_key(leaf, 0);
+	int			i, nr_entries;
+
+	ASSERT(ir->ir_height > 0);
+	ASSERT(ir->ir_data != NULL);
+	ASSERT(fuse_iext_valid(ir, cur));
+
+	fuse_iext_inc_seq(ic);
+
+	nr_entries = fuse_iext_leaf_nr_entries(ir, leaf, cur->pos) - 1;
+	for (i = cur->pos; i < nr_entries; i++)
+		leaf->recs[i] = leaf->recs[i + 1];
+	fuse_iext_rec_clear(&leaf->recs[nr_entries]);
+	ir->ir_bytes -= sizeof(struct fuse_iomap_io);
+
+	if (cur->pos == 0 && nr_entries > 0) {
+		fuse_iext_update_node(ir, offset, fuse_iext_leaf_key(leaf, 0), 1,
+				leaf);
+		offset = fuse_iext_leaf_key(leaf, 0);
+	} else if (cur->pos == nr_entries) {
+		if (ir->ir_height > 1 && leaf->next)
+			cur->leaf = leaf->next;
+		else
+			cur->leaf = NULL;
+		cur->pos = 0;
+	}
+
+	if (nr_entries >= RECS_PER_LEAF / 2)
+		return;
+
+	if (ir->ir_height > 1)
+		fuse_iext_rebalance_leaf(ir, cur, leaf, offset, nr_entries);
+	else if (nr_entries == 0)
+		fuse_iext_free_last_leaf(ir);
+}
+
+/*
+ * Lookup the extent covering offset.
+ *
+ * If there is an extent covering offset return the extent index, and store the
+ * expanded extent structure in *gotp, and the extent cursor in *cur.
+ * If there is no extent covering offset, but there is an extent after it (e.g.
+ * it lies in a hole) return that extent in *gotp and its cursor in *cur
+ * instead.
+ * If offset is beyond the last extent return false, and return an invalid
+ * cursor value.
+ */
+static bool
+fuse_iext_lookup_extent(
+	struct fuse_iomap_cache	*ic,
+	struct fuse_iext_root	*ir,
+	loff_t			offset,
+	struct fuse_iext_cursor	*cur,
+	struct fuse_iomap_io	*gotp)
+{
+	cur->leaf = fuse_iext_find_level(ir, offset, 1);
+	if (!cur->leaf) {
+		cur->pos = 0;
+		return false;
+	}
+
+	for (cur->pos = 0; cur->pos < fuse_iext_max_recs(ir); cur->pos++) {
+		struct fuse_iomap_io *rec = cur_rec(cur);
+
+		if (fuse_iext_rec_is_empty(rec))
+			break;
+		if (fuse_iext_rec_cmp(rec, offset) >= 0)
+			goto found;
+	}
+
+	/* Try looking in the next node for an entry > offset */
+	if (ir->ir_height == 1 || !cur->leaf->next)
+		return false;
+	cur->leaf = cur->leaf->next;
+	cur->pos = 0;
+	if (!fuse_iext_valid(ir, cur))
+		return false;
+found:
+	fuse_iext_get(gotp, cur_rec(cur));
+	return true;
+}
+
+/*
+ * Returns the last extent before end, and if this extent doesn't cover
+ * end, update end to the end of the extent.
+ */
+static bool
+fuse_iext_lookup_extent_before(
+	struct fuse_iomap_cache	*ic,
+	struct fuse_iext_root	*ir,
+	loff_t			*end,
+	struct fuse_iext_cursor	*cur,
+	struct fuse_iomap_io	*gotp)
+{
+	/* could be optimized to not even look up the next on a match.. */
+	if (fuse_iext_lookup_extent(ic, ir, *end - 1, cur, gotp) &&
+	    gotp->offset <= *end - 1)
+		return true;
+	if (!fuse_iext_prev_extent(ir, cur, gotp))
+		return false;
+	*end = gotp->offset + gotp->length;
+	return true;
+}
+
+static void
+fuse_iext_update_extent(
+	struct fuse_iomap_cache	*ic,
+	uint32_t		state,
+	struct fuse_iext_cursor	*cur,
+	struct fuse_iomap_io	*new)
+{
+	struct fuse_iext_root	*ir = fuse_iext_state_to_fork(ic, state);
+
+	fuse_iext_inc_seq(ic);
+
+	if (cur->pos == 0) {
+		struct fuse_iomap_io	old;
+
+		fuse_iext_get(&old, cur_rec(cur));
+		if (new->offset != old.offset) {
+			fuse_iext_update_node(ir, old.offset,
+					new->offset, 1, cur->leaf);
+		}
+	}
+
+	fuse_iext_set(cur_rec(cur), new);
+}
+
+/*
+ * This is a recursive function, because of that we need to be extremely
+ * careful with stack usage.
+ */
+static void
+fuse_iext_destroy_node(
+	struct fuse_iext_node	*node,
+	int			level)
+{
+	int			i;
+
+	if (level > 1) {
+		for (i = 0; i < KEYS_PER_NODE; i++) {
+			if (node->keys[i] == FUSE_IEXT_KEY_INVALID)
+				break;
+			fuse_iext_destroy_node(node->ptrs[i], level - 1);
+		}
+	}
+
+	kfree(node);
+}
+
+static void
+fuse_iext_destroy(
+	struct fuse_iext_root	*ir)
+{
+	fuse_iext_destroy_node(ir->ir_data, ir->ir_height);
+
+	ir->ir_bytes = 0;
+	ir->ir_height = 0;
+	ir->ir_data = NULL;
+}
+
+static inline struct fuse_iext_root *
+fuse_iext_root_ptr(
+	struct fuse_iomap_cache	*ic,
+	enum fuse_iomap_iodir	iodir)
+{
+	switch (iodir) {
+	case READ_MAPPING:
+		return &ic->ic_read;
+	case WRITE_MAPPING:
+		return &ic->ic_write;
+	default:
+		ASSERT(0);
+		return NULL;
+	}
+}
+
+static inline bool fuse_iomap_addrs_adjacent(const struct fuse_iomap_io *left,
+					     const struct fuse_iomap_io *right)
+{
+	switch (left->type) {
+	case FUSE_IOMAP_TYPE_MAPPED:
+	case FUSE_IOMAP_TYPE_UNWRITTEN:
+		return left->addr + left->length == right->addr;
+	default:
+		return left->addr  == FUSE_IOMAP_NULL_ADDR &&
+		       right->addr == FUSE_IOMAP_NULL_ADDR;
+	}
+}
+
+static inline bool fuse_iomap_can_merge(const struct fuse_iomap_io *left,
+					const struct fuse_iomap_io *right)
+{
+	return (left->dev == right->dev &&
+		left->offset + left->length == right->offset &&
+		left->type  == right->type &&
+		fuse_iomap_addrs_adjacent(left, right) &&
+		left->flags == right->flags &&
+		left->length + right->length <= FUSE_IOMAP_MAX_LEN);
+}
+
+static inline bool fuse_iomap_can_merge3(const struct fuse_iomap_io *left,
+					 const struct fuse_iomap_io *new,
+					 const struct fuse_iomap_io *right)
+{
+	return left->length + new->length + right->length <= FUSE_IOMAP_MAX_LEN;
+}
+
+#if IS_ENABLED(CONFIG_FUSE_IOMAP_DEBUG)
+static void fuse_iext_check_mappings(struct fuse_iomap_cache *ic,
+				     struct fuse_iext_root *ir)
+{
+	struct fuse_iext_cursor	icur;
+	struct fuse_iomap_io	prev, got;
+	struct inode		*inode = ic->ic_inode;
+	struct fuse_inode	*fi = get_fuse_inode(inode);
+	unsigned long long	nr = 0;
+
+	if (ir->ir_bytes < 0 || !static_branch_unlikely(&fuse_iomap_debug))
+		return;
+
+	fuse_iext_first(ir, &icur);
+	if (!fuse_iext_get_extent(ir, &icur, &prev))
+		return;
+	nr++;
+
+	fuse_iext_next(ir, &icur);
+	while (fuse_iext_get_extent(ir, &icur, &got)) {
+		if (got.length == 0 ||
+		    got.offset < prev.offset + prev.length ||
+		    fuse_iomap_can_merge(&prev, &got)) {
+			printk(KERN_ERR "FUSE IOMAP CORRUPTION ino=%llu nr=%llu",
+			       fi->orig_ino, nr);
+			printk(KERN_ERR "prev: offset=%llu length=%llu type=%u flags=0x%x dev=%u addr=%llu\n",
+			       prev.offset, prev.length, prev.type, prev.flags,
+			       prev.dev, prev.addr);
+			printk(KERN_ERR "curr: offset=%llu length=%llu type=%u flags=0x%x dev=%u addr=%llu\n",
+			       got.offset, got.length, got.type, got.flags,
+			       got.dev, got.addr);
+		}
+
+		prev = got;
+		nr++;
+		fuse_iext_next(ir, &icur);
+	}
+}
+#else
+# define fuse_iext_check_mappings(...)	((void)0)
+#endif
+
+static void
+fuse_iext_del_mapping(
+	struct fuse_iomap_cache	*ic,
+	struct fuse_iext_root	*ir,
+	struct fuse_iext_cursor	*icur,
+	struct fuse_iomap_io	*got,	/* current extent entry */
+	struct fuse_iomap_io	*del)	/* data to remove from extents */
+{
+	struct fuse_iomap_io	new;	/* new record to be inserted */
+	/* first addr (fsblock aligned) past del */
+	fuse_iext_key_t		del_endaddr;
+	/* first offset (fsblock aligned) past del */
+	fuse_iext_key_t		del_endoff = del->offset + del->length;
+	/* first offset (fsblock aligned) past got */
+	fuse_iext_key_t		got_endoff = got->offset + got->length;
+	uint32_t		state = fuse_iomap_fork_to_state(ic, ir);
+
+	ASSERT(del->length > 0);
+	ASSERT(got->offset <= del->offset);
+	ASSERT(got_endoff >= del_endoff);
+
+	switch (del->type) {
+	case FUSE_IOMAP_TYPE_MAPPED:
+	case FUSE_IOMAP_TYPE_UNWRITTEN:
+		del_endaddr = del->addr + del->length;
+		break;
+	default:
+		del_endaddr = FUSE_IOMAP_NULL_ADDR;
+		break;
+	}
+
+	if (got->offset == del->offset)
+		state |= FUSE_IEXT_LEFT_FILLING;
+	if (got_endoff == del_endoff)
+		state |= FUSE_IEXT_RIGHT_FILLING;
+
+	switch (state & (FUSE_IEXT_LEFT_FILLING | FUSE_IEXT_RIGHT_FILLING)) {
+	case FUSE_IEXT_LEFT_FILLING | FUSE_IEXT_RIGHT_FILLING:
+		/*
+		 * Matches the whole extent.  Delete the entry.
+		 */
+		fuse_iext_remove(ic, icur, state);
+		fuse_iext_prev(ir, icur);
+		break;
+	case FUSE_IEXT_LEFT_FILLING:
+		/*
+		 * Deleting the first part of the extent.
+		 */
+		got->offset = del_endoff;
+		got->addr = del_endaddr;
+		got->length -= del->length;
+		fuse_iext_update_extent(ic, state, icur, got);
+		break;
+	case FUSE_IEXT_RIGHT_FILLING:
+		/*
+		 * Deleting the last part of the extent.
+		 */
+		got->length -= del->length;
+		fuse_iext_update_extent(ic, state, icur, got);
+		break;
+	case 0:
+		/*
+		 * Deleting the middle of the extent.
+		 */
+		got->length = del->offset - got->offset;
+		fuse_iext_update_extent(ic, state, icur, got);
+
+		new.offset = del_endoff;
+		new.length = got_endoff - del_endoff;
+		new.type = got->type;
+		new.flags = got->flags;
+		new.addr = del_endaddr;
+		new.dev = got->dev;
+
+		fuse_iext_next(ir, icur);
+		fuse_iext_insert(ic, icur, &new, state);
+		break;
+	}
+}
+
+int
+fuse_iomap_cache_remove(
+	struct inode		*inode,
+	enum fuse_iomap_iodir	iodir,
+	loff_t			start,		/* first file offset deleted */
+	uint64_t		len)		/* length to unmap */
+{
+	struct fuse_iext_cursor	icur;
+	struct fuse_iomap_io	got;		/* current extent record */
+	struct fuse_iomap_io	del;		/* extent being deleted */
+	loff_t			end;
+	struct fuse_inode	*fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache	*ic = fi->cache;
+	struct fuse_iext_root	*ir = fuse_iext_root_ptr(ic, iodir);
+	bool			wasreal;
+	bool			done = false;
+	int			ret = 0;
+
+	assert_cache_locked(ic);
+
+	/* Fork is not active or has zero mappings */
+	if (ir->ir_bytes < 0 || fuse_iext_count(ir) == 0)
+		return 0;
+
+	/* Fast shortcut if the caller wants to erase everything */
+	if (start == 0 && len >= inode->i_sb->s_maxbytes) {
+		fuse_iext_destroy(ir);
+		return 0;
+	}
+
+	if (!len)
+		goto out;
+
+	/*
+	 * If the caller wants us to remove everything to EOF, we set the end
+	 * of the removal range to the maximum file offset.  We don't support
+	 * unsigned file offsets.
+	 */
+	if (len == FUSE_IOMAP_INVAL_TO_EOF) {
+		const unsigned int blocksize = i_blocksize(&fi->inode);
+
+		len = round_up(inode->i_sb->s_maxbytes, blocksize) - start;
+	}
+
+	/*
+	 * Now that we've settled len, look up the extent before the end of the
+	 * range.
+	 */
+	end = start + len;
+	if (!fuse_iext_lookup_extent_before(ic, ir, &end, &icur, &got))
+		goto out;
+	end--;
+
+	while (end != -1 && end >= start) {
+		/*
+		 * Is the found extent after a hole in which end lives?
+		 * Just back up to the previous extent, if so.
+		 */
+		if (got.offset > end &&
+		    !fuse_iext_prev_extent(ir, &icur, &got)) {
+			done = true;
+			break;
+		}
+		/*
+		 * Is the last block of this extent before the range
+		 * we're supposed to delete?  If so, we're done.
+		 */
+		end = min_t(loff_t, end, got.offset + got.length - 1);
+		if (end < start)
+			break;
+		/*
+		 * Then deal with the (possibly delayed) allocated space
+		 * we found.
+		 */
+		del = got;
+		switch (del.type) {
+		case FUSE_IOMAP_TYPE_DELALLOC:
+		case FUSE_IOMAP_TYPE_HOLE:
+		case FUSE_IOMAP_TYPE_INLINE:
+		case FUSE_IOMAP_TYPE_PURE_OVERWRITE:
+			wasreal = false;
+			break;
+		case FUSE_IOMAP_TYPE_MAPPED:
+		case FUSE_IOMAP_TYPE_UNWRITTEN:
+			wasreal = true;
+			break;
+		default:
+			ASSERT(0);
+			ret = -EFSCORRUPTED;
+			goto out;
+		}
+
+		if (got.offset < start) {
+			del.offset = start;
+			del.length -= start - got.offset;
+			if (wasreal)
+				del.addr += start - got.offset;
+		}
+		if (del.offset + del.length > end + 1)
+			del.length = end + 1 - del.offset;
+
+		fuse_iext_del_mapping(ic, ir, &icur, &got, &del);
+		end = del.offset - 1;
+
+		/*
+		 * If not done go on to the next (previous) record.
+		 */
+		if (end != -1 && end >= start) {
+			if (!fuse_iext_get_extent(ir, &icur, &got) ||
+			    (got.offset > end &&
+			     !fuse_iext_prev_extent(ir, &icur, &got))) {
+				done = true;
+				break;
+			}
+		}
+	}
+
+	/* Should have removed everything */
+	if (len == 0 || done || end == (loff_t)-1 || end < start)
+		ret = 0;
+	else
+		ret = -EFSCORRUPTED;
+
+out:
+	fuse_iext_check_mappings(ic, ir);
+	return ret;
+}
+
+static void
+fuse_iext_add_mapping(
+	struct fuse_iomap_cache		*ic,
+	struct fuse_iext_root		*ir,
+	struct fuse_iext_cursor		*icur,
+	const struct fuse_iomap_io	*new)	/* new extent entry */
+{
+	struct fuse_iomap_io		left;	/* left neighbor extent entry */
+	struct fuse_iomap_io		right;	/* right neighbor extent entry */
+	uint32_t			state = fuse_iomap_fork_to_state(ic, ir);
+
+	/*
+	 * Check and set flags if this segment has a left neighbor.
+	 */
+	if (fuse_iext_peek_prev_extent(ir, icur, &left))
+		state |= FUSE_IEXT_LEFT_VALID;
+
+	/*
+	 * Check and set flags if this segment has a current value.
+	 * Not true if we're inserting into the "hole" at eof.
+	 */
+	if (fuse_iext_get_extent(ir, icur, &right))
+		state |= FUSE_IEXT_RIGHT_VALID;
+
+	/*
+	 * We're inserting a real allocation between "left" and "right".
+	 * Set the contiguity flags.  Don't let extents get too large.
+	 */
+	if ((state & FUSE_IEXT_LEFT_VALID) && fuse_iomap_can_merge(&left, new))
+		state |= FUSE_IEXT_LEFT_CONTIG;
+
+	if ((state & FUSE_IEXT_RIGHT_VALID) &&
+	    fuse_iomap_can_merge(new, &right) &&
+	    (!(state & FUSE_IEXT_LEFT_CONTIG) ||
+	     fuse_iomap_can_merge3(&left, new, &right)))
+		state |= FUSE_IEXT_RIGHT_CONTIG;
+
+	/*
+	 * Select which case we're in here, and implement it.
+	 */
+	switch (state & (FUSE_IEXT_LEFT_CONTIG | FUSE_IEXT_RIGHT_CONTIG)) {
+	case FUSE_IEXT_LEFT_CONTIG | FUSE_IEXT_RIGHT_CONTIG:
+		/*
+		 * New allocation is contiguous with real allocations on the
+		 * left and on the right.
+		 * Merge all three into a single extent record.
+		 */
+		left.length += new->length + right.length;
+
+		fuse_iext_remove(ic, icur, state);
+		fuse_iext_prev(ir, icur);
+		fuse_iext_update_extent(ic, state, icur, &left);
+		break;
+
+	case FUSE_IEXT_LEFT_CONTIG:
+		/*
+		 * New allocation is contiguous with a real allocation
+		 * on the left.
+		 * Merge the new allocation with the left neighbor.
+		 */
+		left.length += new->length;
+
+		fuse_iext_prev(ir, icur);
+		fuse_iext_update_extent(ic, state, icur, &left);
+		break;
+
+	case FUSE_IEXT_RIGHT_CONTIG:
+		/*
+		 * New allocation is contiguous with a real allocation
+		 * on the right.
+		 * Merge the new allocation with the right neighbor.
+		 */
+		right.offset = new->offset;
+		right.addr = new->addr;
+		right.length += new->length;
+		fuse_iext_update_extent(ic, state, icur, &right);
+		break;
+
+	case 0:
+		/*
+		 * New allocation is not contiguous with another
+		 * real allocation.
+		 * Insert a new entry.
+		 */
+		fuse_iext_insert(ic, icur, new, state);
+		break;
+	}
+}
+
+static int
+fuse_iomap_cache_add(
+	struct inode			*inode,
+	enum fuse_iomap_iodir		iodir,
+	const struct fuse_iomap_io	*new)
+{
+	struct fuse_iext_cursor		icur;
+	struct fuse_iomap_io		got;
+	struct fuse_inode		*fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache		*ic = fi->cache;
+	struct fuse_iext_root		*ir = fuse_iext_root_ptr(ic, iodir);
+
+	assert_cache_locked(ic);
+	ASSERT(new->length > 0);
+	ASSERT(new->offset < inode->i_sb->s_maxbytes);
+
+	/* Mark this fork as being in use */
+	if (ir->ir_bytes < 0)
+		ir->ir_bytes = 0;
+
+	if (fuse_iext_lookup_extent(ic, ir, new->offset, &icur, &got)) {
+		/* make sure we only add into a hole. */
+		ASSERT(got.offset > new->offset);
+		ASSERT(got.offset - new->offset >= new->length);
+
+		if (got.offset <= new->offset ||
+		    got.offset - new->offset < new->length)
+			return -EFSCORRUPTED;
+	}
+
+	fuse_iext_add_mapping(ic, ir, &icur, new);
+	fuse_iext_check_mappings(ic, ir);
+	return 0;
+}
+
+int fuse_iomap_cache_alloc(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *old = NULL;
+	struct fuse_iomap_cache *ic;
+
+	ic = kzalloc_obj(struct fuse_iomap_cache);
+	if (!ic)
+		return -ENOMEM;
+
+	/* Only the write mapping cache can return NOFORK */
+	ic->ic_write.ir_bytes = -1;
+	ic->ic_inode = inode;
+	init_rwsem(&ic->ic_lock);
+
+	if (!try_cmpxchg(&fi->cache, &old, ic)) {
+		/* Someone created mapping cache before us? Free ours... */
+		kfree(ic);
+	}
+
+	return 0;
+}
+
+static void fuse_iomap_cache_purge(struct fuse_iomap_cache *ic)
+{
+	fuse_iext_destroy(&ic->ic_read);
+	fuse_iext_destroy(&ic->ic_write);
+}
+
+void fuse_iomap_cache_free(struct inode *inode)
+{
+	struct fuse_inode *fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache *ic = fi->cache;
+
+	/*
+	 * This is only called from eviction, so we cannot be racing to set or
+	 * clear the pointer.
+	 */
+	fi->cache = NULL;
+
+	fuse_iomap_cache_purge(ic);
+	kfree(ic);
+}
+
+int
+fuse_iomap_cache_upsert(
+	struct inode			*inode,
+	enum fuse_iomap_iodir		iodir,
+	const struct fuse_iomap_io	*map)
+{
+	struct fuse_inode		*fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache		*ic = fi->cache;
+	int				err;
+
+	ASSERT(fuse_inode_caches_iomaps(inode));
+
+	/*
+	 * We interpret no write fork to mean that all writes are pure
+	 * overwrites.  Avoid wasting memory if we're trying to upsert a
+	 * pure overwrite.
+	 */
+	if (iodir == WRITE_MAPPING &&
+	    map->type == FUSE_IOMAP_TYPE_PURE_OVERWRITE &&
+	    ic->ic_write.ir_bytes < 0)
+		return 0;
+
+	err = fuse_iomap_cache_remove(inode, iodir, map->offset, map->length);
+	if (err)
+		return err;
+
+	return fuse_iomap_cache_add(inode, iodir, map);
+}
+
+/*
+ * Trim the returned map to the required bounds
+ */
+static void
+fuse_iomap_trim(
+	struct fuse_inode		*fi,

fs/fuse/fuse_iomap_cache.c line 1636

Quoted 10 lines
fs/fuse/fuse_iomap_cache.c new file +10 -0
+	struct fuse_iomap_lookup	*mval,
+	const struct fuse_iomap_io	*got,
+	loff_t				off,
+	loff_t				len)
+{
+	struct fuse_iomap_cache		*ic = fi->cache;
+	const unsigned int blocksize = i_blocksize(&fi->inode);
+	const loff_t aligned_off = round_down(off, blocksize);
+	const loff_t aligned_end = round_up(off + len, blocksize);
+	const loff_t aligned_len = aligned_end - aligned_off;

This realignment logic is no longer necessary because now we require that all cached mappings are aligned to the blocksize...

Quoted 5 lines
fs/fuse/fuse_iomap_cache.c new file +5 -0
+
+	ASSERT(aligned_off >= got->offset);
+
+	switch (got->type) {
+	case FUSE_IOMAP_TYPE_MAPPED:

fs/fuse/fuse_iomap_cache.c line 1651

Quoted 10 lines
fs/fuse/fuse_iomap_cache.c new file +10 -0
+	case FUSE_IOMAP_TYPE_UNWRITTEN:
+		mval->map.addr = got->addr + (aligned_off - got->offset);
+		break;
+	default:
+		mval->map.addr = FUSE_IOMAP_NULL_ADDR;
+		break;
+	}
+	mval->map.offset = aligned_off;
+	mval->map.length = min_t(loff_t, aligned_len,
+				 got->length - (aligned_off - got->offset));

...and this logic here has a bug where we can accidentally extend mappings if off+len is far beyond the end of @got. In the end we can more or less copy got to mval->map, set addr appropriately for the iomap type, and sample the validity cookie.

--D

Quoted 64 lines
fs/fuse/fuse_iomap_cache.c new file +50 -0
+	mval->map.type = got->type;
+	mval->map.flags = got->flags;
+	mval->map.dev = got->dev;
+	mval->validity_cookie = fuse_iext_read_seq(ic);
+}
+
+enum fuse_iomap_lookup_result
+fuse_iomap_cache_lookup(
+	struct inode			*inode,
+	enum fuse_iomap_iodir		iodir,
+	loff_t				off,
+	uint64_t			len,
+	struct fuse_iomap_lookup	*mval)
+{
+	struct fuse_iomap_io		got;
+	struct fuse_iext_cursor		icur;
+	struct fuse_inode		*fi = get_fuse_inode(inode);
+	struct fuse_iomap_cache		*ic = fi->cache;
+	struct fuse_iext_root		*ir = fuse_iext_root_ptr(ic, iodir);
+
+	assert_cache_locked_shared(ic);
+
+	if (ir->ir_bytes < 0) {
+		/*
+		 * No write fork at all means this filesystem doesn't do out of
+		 * place writes.
+		 */
+		return LOOKUP_NOFORK;
+	}
+
+	if (!fuse_iext_lookup_extent(ic, ir, off, &icur, &got)) {
+		/*
+		 * Does not contain a mapping at or beyond off, which is a
+		 * cache miss.
+		 */
+		return LOOKUP_MISS;
+	}
+
+	if (got.offset > off) {
+		/*
+		 * Found a mapping, but it doesn't cover the start of the
+		 * range, which is effectively a miss.
+		 */
+		return LOOKUP_MISS;
+	}
+
+	/* Found a mapping in the cache, return it */
+	fuse_iomap_trim(fi, mval, &got, off, len);
+	return LOOKUP_HIT;
+}
fs/fuse/trace.c +1 -0
index 71d444ac1e5021..69310d6f773ffa 100644
@@ -8,6 +8,7 @@
 #include "fuse_dev_i.h"
 #include "fuse_iomap.h"
 #include "fuse_iomap_i.h"
+#include "fuse_iomap_cache.h"
 
 #include <linux/pagemap.h>
 #include <linux/iomap.h>
#87 lore raw

PATCH 2/12 fuse_trace: cache iomaps

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h       |  293 ++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap_cache.c |   36 +++++
 2 files changed, 329 insertions(+)
fs/fuse/fuse_trace.h +293 -0
index a6374d64a62357..697289c82d0dad 100644
@@ -318,6 +318,8 @@ DEFINE_FUSE_BACKING_EVENT(fuse_backing_close);
 struct iomap_writepage_ctx;
 struct iomap_ioend;
 struct iomap;
+struct fuse_iext_cursor;
+struct fuse_iomap_lookup;
 
 /* tracepoint boilerplate so we don't have to keep doing this */
 #define FUSE_IOMAP_OPFLAGS_FIELD \
@@ -348,6 +350,16 @@ struct iomap;
 		__entry->prefix##addr, \
 		__print_flags(__entry->prefix##flags, "|", FUSE_IOMAP_F_STRINGS)
 
+#define FUSE_IOMAP_IODIR_FIELD \
+		__field(unsigned int,	iodir)
+
+#define FUSE_IOMAP_IODIR_FMT \
+		 " iodir %s"
+
+#define FUSE_IOMAP_IODIR_PRINTK_ARGS \
+		  __print_symbolic(__entry->iodir, FUSE_IOMAP_FORK_STRINGS)
+
+
 /* combinations of boilerplate to reduce typing further */
 #define FUSE_IOMAP_OP_FIELDS(prefix) \
 		FUSE_INODE_FIELDS \
@@ -445,6 +457,22 @@ TRACE_DEFINE_ENUM(FUSE_I_ATOMIC);
 	{ FUSE_IOMAP_CONFIG_TIME,		"time" }, \
 	{ FUSE_IOMAP_CONFIG_MAXBYTES,		"maxbytes" }
 
+TRACE_DEFINE_ENUM(READ_MAPPING);
+TRACE_DEFINE_ENUM(WRITE_MAPPING);
+
+#define FUSE_IOMAP_FORK_STRINGS \
+	{ READ_MAPPING,				"read" }, \
+	{ WRITE_MAPPING,			"write" }
+
+#define FUSE_IEXT_STATE_STRINGS \
+	{ FUSE_IEXT_LEFT_CONTIG,		"l_cont" }, \
+	{ FUSE_IEXT_RIGHT_CONTIG,		"r_cont" }, \
+	{ FUSE_IEXT_LEFT_FILLING,		"l_fill" }, \
+	{ FUSE_IEXT_RIGHT_FILLING,		"r_fill" }, \
+	{ FUSE_IEXT_LEFT_VALID,			"l_valid" }, \
+	{ FUSE_IEXT_RIGHT_VALID,		"r_valid" }, \
+	{ FUSE_IEXT_WRITE_MAPPING,		"write" }
+
 DECLARE_EVENT_CLASS(fuse_iomap_check_class,
 	TP_PROTO(const char *func, int line, const char *condition),
 
@@ -727,6 +755,8 @@ DEFINE_EVENT(fuse_inode_state_class, name,	\
 	TP_ARGS(inode))
 DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_init_inode);
 DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_evict_inode);
+DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_cache_alloc);
+DEFINE_FUSE_INODE_STATE_EVENT(fuse_iomap_cache_free);
 
 TRACE_EVENT(fuse_iomap_fiemap,
 	TP_PROTO(const struct inode *inode, u64 start, u64 count,
@@ -1216,6 +1246,269 @@ DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_inline_read);
 DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_inline_write);
 DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_iomap);
 DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_srcmap);
+
+DECLARE_EVENT_CLASS(fuse_iext_class,
+	TP_PROTO(const struct inode *inode, const struct fuse_iext_cursor *cur,
+		 int state, unsigned long caller_ip),
+
+	TP_ARGS(inode, cur, state, caller_ip),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		FUSE_IOMAP_MAP_FIELDS(map)
+		__field(void *,			leaf)
+		__field(int,			pos)
+		__field(int,			iext_state)
+		__field(unsigned long,		caller_ip)
+	),
+	TP_fast_assign(
+		const struct fuse_iext_root *ir;
+		struct fuse_iomap_io r = { };
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+
+		if (state & FUSE_IEXT_WRITE_MAPPING)
+			ir = &fi->cache->ic_write;
+		else
+			ir = &fi->cache->ic_read;
+		if (ir)
+			fuse_iext_get_extent(ir, cur, &r);
+
+		__entry->mapoffset	=	r.offset;
+		__entry->mapaddr	=	r.addr;
+		__entry->maplength	=	r.length;
+		__entry->mapdev		=	r.dev;
+		__entry->maptype	=	r.type;
+		__entry->mapflags	=	r.flags;
+
+		__entry->leaf		=	cur->leaf;
+		__entry->pos		=	cur->pos;
+
+		__entry->iext_state	=	state;
+		__entry->caller_ip	=	caller_ip;
+	),
+	TP_printk(FUSE_INODE_FMT " state (%s) cur %p/%d " FUSE_IOMAP_MAP_FMT() " caller %pS",
+		  FUSE_INODE_PRINTK_ARGS,
+		  __print_flags(__entry->iext_state, "|", FUSE_IEXT_STATE_STRINGS),
+		  __entry->leaf,
+		  __entry->pos,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map),
+		  (void *)__entry->caller_ip)
+)
+
+#define DEFINE_IEXT_EVENT(name) \
+DEFINE_EVENT(fuse_iext_class, name, \
+	TP_PROTO(const struct inode *inode, const struct fuse_iext_cursor *cur, \
+		 int state, unsigned long caller_ip), \
+	TP_ARGS(inode, cur, state, caller_ip))
+DEFINE_IEXT_EVENT(fuse_iext_insert);
+DEFINE_IEXT_EVENT(fuse_iext_remove);
+DEFINE_IEXT_EVENT(fuse_iext_pre_update);
+DEFINE_IEXT_EVENT(fuse_iext_post_update);
+
+TRACE_EVENT(fuse_iext_update_class,
+	TP_PROTO(const struct inode *inode, uint32_t iext_state,
+		 const struct fuse_iomap_io *map),
+	TP_ARGS(inode, iext_state, map),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		FUSE_IOMAP_MAP_FIELDS(map)
+		__field(uint32_t,		iext_state)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->mapoffset	=	map->offset;
+		__entry->maplength	=	map->length;
+		__entry->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+		__entry->mapdev		=	map->dev;
+		__entry->mapaddr	=	map->addr;
+
+		__entry->iext_state	=	iext_state;
+	),
+
+	TP_printk(FUSE_INODE_FMT " state (%s)" FUSE_IOMAP_MAP_FMT(),
+		  FUSE_INODE_PRINTK_ARGS,
+		  __print_flags(__entry->iext_state, "|", FUSE_IEXT_STATE_STRINGS),
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map))
+);
+#define DEFINE_IEXT_UPDATE_EVENT(name) \
+DEFINE_EVENT(fuse_iext_update_class, name, \
+	TP_PROTO(const struct inode *inode, uint32_t iext_state, \
+		 const struct fuse_iomap_io *map), \
+	TP_ARGS(inode, iext_state, map))
+DEFINE_IEXT_UPDATE_EVENT(fuse_iext_del_mapping);
+DEFINE_IEXT_UPDATE_EVENT(fuse_iext_add_mapping);
+
+TRACE_EVENT(fuse_iext_alt_update_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->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+		__entry->mapdev		=	map->dev;
+		__entry->mapaddr	=	map->addr;
+	),
+
+	TP_printk(FUSE_INODE_FMT FUSE_IOMAP_MAP_FMT(),
+		  FUSE_INODE_PRINTK_ARGS,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map))
+);
+#define DEFINE_IEXT_ALT_UPDATE_EVENT(name) \
+DEFINE_EVENT(fuse_iext_alt_update_class, name, \
+	TP_PROTO(const struct inode *inode, const struct fuse_iomap_io *map), \
+	TP_ARGS(inode, map))
+DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_del_mapping_got);
+DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_add_mapping_left);
+DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_add_mapping_right);
+
+TRACE_EVENT(fuse_iomap_cache_remove,
+	TP_PROTO(const struct inode *inode, unsigned int iodir,
+		 loff_t offset, uint64_t length, unsigned long caller_ip),
+	TP_ARGS(inode, iodir, offset, length, caller_ip),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		FUSE_IOMAP_IODIR_FIELD
+		__field(unsigned long,		caller_ip)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->iodir		=	iodir;
+		__entry->offset		=	offset;
+		__entry->length		=	length;
+		__entry->caller_ip	=	caller_ip;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() FUSE_IOMAP_IODIR_FMT " caller %pS",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  FUSE_IOMAP_IODIR_PRINTK_ARGS,
+		  (void *)__entry->caller_ip)
+);
+
+TRACE_EVENT(fuse_iomap_cached_mapping_class,
+	TP_PROTO(const struct inode *inode, unsigned int iodir,
+		 const struct fuse_iomap_io *map, unsigned long caller_ip),
+	TP_ARGS(inode, iodir, map, caller_ip),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		FUSE_IOMAP_IODIR_FIELD
+		FUSE_IOMAP_MAP_FIELDS(map)
+		__field(unsigned long,		caller_ip)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->iodir		=	iodir;
+
+		__entry->mapoffset	=	map->offset;
+		__entry->maplength	=	map->length;
+		__entry->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+		__entry->mapdev		=	map->dev;
+		__entry->mapaddr	=	map->addr;
+
+		__entry->caller_ip	=	caller_ip;
+	),
+
+	TP_printk(FUSE_INODE_FMT FUSE_IOMAP_IODIR_FMT FUSE_IOMAP_MAP_FMT() " caller %pS",
+		  FUSE_INODE_PRINTK_ARGS,
+		  FUSE_IOMAP_IODIR_PRINTK_ARGS,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map),
+		  (void *)__entry->caller_ip)
+);
+#define DEFINE_FUSE_IOMAP_CACHED_MAPPING_EVENT(name) \
+DEFINE_EVENT(fuse_iomap_cached_mapping_class, name, \
+	TP_PROTO(const struct inode *inode, unsigned int iodir, \
+		 const struct fuse_iomap_io *map, unsigned long caller_ip), \
+	TP_ARGS(inode, iodir, map, caller_ip))
+DEFINE_FUSE_IOMAP_CACHED_MAPPING_EVENT(fuse_iomap_cache_add);
+DEFINE_FUSE_IOMAP_CACHED_MAPPING_EVENT(fuse_iext_check_mapping);
+
+TRACE_EVENT(fuse_iomap_cache_lookup,
+	TP_PROTO(const struct inode *inode, unsigned int iodir,
+		 loff_t pos, uint64_t count, unsigned long caller_ip),
+	TP_ARGS(inode, iodir, pos, count, caller_ip),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		FUSE_IOMAP_IODIR_FIELD
+		__field(unsigned long,		caller_ip)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->iodir		=	iodir;
+		__entry->offset		=	pos;
+		__entry->length		=	count;
+		__entry->caller_ip	=	caller_ip;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() FUSE_IOMAP_IODIR_FMT " caller %pS",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  FUSE_IOMAP_IODIR_PRINTK_ARGS,
+		  (void *)__entry->caller_ip)
+);
+
+TRACE_EVENT(fuse_iomap_cache_lookup_result,
+	TP_PROTO(const struct inode *inode, unsigned int iodir,
+		 loff_t pos, uint64_t count, const struct fuse_iomap_io *got,
+		 const struct fuse_iomap_lookup *map),
+	TP_ARGS(inode, iodir, pos, count, got, map),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+
+		FUSE_IOMAP_MAP_FIELDS(got)
+		FUSE_IOMAP_MAP_FIELDS(map)
+
+		FUSE_IOMAP_IODIR_FIELD
+		__field(uint64_t,		validity_cookie)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->iodir		=	iodir;
+		__entry->offset		=	pos;
+		__entry->length		=	count;
+
+		__entry->gotoffset	=	got->offset;
+		__entry->gotlength	=	got->length;
+		__entry->gottype	=	got->type;
+		__entry->gotflags	=	got->flags;
+		__entry->gotdev		=	got->dev;
+		__entry->gotaddr	=	got->addr;
+
+		__entry->mapoffset	=	map->map.offset;
+		__entry->maplength	=	map->map.length;
+		__entry->maptype	=	map->map.type;
+		__entry->mapflags	=	map->map.flags;
+		__entry->mapdev		=	map->map.dev;
+		__entry->mapaddr	=	map->map.addr;
+
+		__entry->validity_cookie=	map->validity_cookie;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() FUSE_IOMAP_IODIR_FMT FUSE_IOMAP_MAP_FMT("map") FUSE_IOMAP_MAP_FMT("got") " cookie 0x%llx",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  FUSE_IOMAP_IODIR_PRINTK_ARGS,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map),
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(got),
+		  __entry->validity_cookie)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap_cache.c +36 -0
index e32de8a5e3c325..a047d7bf95257a 100644
@@ -763,6 +763,7 @@ fuse_iext_insert(
 	struct fuse_iext_root		*ir = fuse_iext_state_to_fork(ic, state);
 
 	fuse_iext_insert_raw(ic, ir, cur, irec);
+	trace_fuse_iext_insert(ic->ic_inode, cur, state, _RET_IP_);
 }
 
 static struct fuse_iext_node *
@@ -970,6 +971,8 @@ fuse_iext_remove(
 	ASSERT(ir->ir_data != NULL);
 	ASSERT(fuse_iext_valid(ir, cur));
 
+	trace_fuse_iext_remove(ic->ic_inode, cur, state, _RET_IP_);
+
 	fuse_iext_inc_seq(ic);
 
 	nr_entries = fuse_iext_leaf_nr_entries(ir, leaf, cur->pos) - 1;
@@ -1088,7 +1091,9 @@ fuse_iext_update_extent(
 		}
 	}
 
+	trace_fuse_iext_pre_update(ic->ic_inode, cur, state, _RET_IP_);
 	fuse_iext_set(cur_rec(cur), new);
+	trace_fuse_iext_post_update(ic->ic_inode, cur, state, _RET_IP_);
 }
 
 /*
@@ -1180,17 +1185,26 @@ static void fuse_iext_check_mappings(struct fuse_iomap_cache *ic,
 	struct inode		*inode = ic->ic_inode;
 	struct fuse_inode	*fi = get_fuse_inode(inode);
 	unsigned long long	nr = 0;
+	enum fuse_iomap_iodir	iodir;
 
 	if (ir->ir_bytes < 0 || !static_branch_unlikely(&fuse_iomap_debug))
 		return;
 
+	if (ir == &ic->ic_write)
+		iodir = WRITE_MAPPING;
+	else
+		iodir = READ_MAPPING;
+
 	fuse_iext_first(ir, &icur);
 	if (!fuse_iext_get_extent(ir, &icur, &prev))
 		return;
+	trace_fuse_iext_check_mapping(ic->ic_inode, iodir, &prev, _RET_IP_);
 	nr++;
 
 	fuse_iext_next(ir, &icur);
 	while (fuse_iext_get_extent(ir, &icur, &got)) {
+		trace_fuse_iext_check_mapping(ic->ic_inode, iodir, &got,
+					      _RET_IP_);
 		if (got.length == 0 ||
 		    got.offset < prev.offset + prev.length ||
 		    fuse_iomap_can_merge(&prev, &got)) {
@@ -1249,6 +1263,9 @@ fuse_iext_del_mapping(
 	if (got_endoff == del_endoff)
 		state |= FUSE_IEXT_RIGHT_FILLING;
 
+	trace_fuse_iext_del_mapping(ic->ic_inode, state, del);
+	trace_fuse_iext_del_mapping_got(ic->ic_inode, got);
+
 	switch (state & (FUSE_IEXT_LEFT_FILLING | FUSE_IEXT_RIGHT_FILLING)) {
 	case FUSE_IEXT_LEFT_FILLING | FUSE_IEXT_RIGHT_FILLING:
 		/*
@@ -1313,6 +1330,8 @@ fuse_iomap_cache_remove(
 
 	assert_cache_locked(ic);
 
+	trace_fuse_iomap_cache_remove(&fi->inode, iodir, start, len, _RET_IP_);
+
 	/* Fork is not active or has zero mappings */
 	if (ir->ir_bytes < 0 || fuse_iext_count(ir) == 0)
 		return 0;
@@ -1458,6 +1477,12 @@ fuse_iext_add_mapping(
 	     fuse_iomap_can_merge3(&left, new, &right)))
 		state |= FUSE_IEXT_RIGHT_CONTIG;
 
+	trace_fuse_iext_add_mapping(ic->ic_inode, state, new);
+	if (state & FUSE_IEXT_LEFT_VALID)
+		trace_fuse_iext_add_mapping_left(ic->ic_inode, &left);
+	if (state & FUSE_IEXT_RIGHT_VALID)
+		trace_fuse_iext_add_mapping_right(ic->ic_inode, &right);
+
 	/*
 	 * Select which case we're in here, and implement it.
 	 */
@@ -1526,6 +1551,8 @@ fuse_iomap_cache_add(
 	ASSERT(new->length > 0);
 	ASSERT(new->offset < inode->i_sb->s_maxbytes);
 
+	trace_fuse_iomap_cache_add(&fi->inode, iodir, new, _RET_IP_);
+
 	/* Mark this fork as being in use */
 	if (ir->ir_bytes < 0)
 		ir->ir_bytes = 0;
@@ -1563,8 +1590,10 @@ int fuse_iomap_cache_alloc(struct inode *inode)
 	if (!try_cmpxchg(&fi->cache, &old, ic)) {
 		/* Someone created mapping cache before us? Free ours... */
 		kfree(ic);
+		return 0;
 	}
 
+	trace_fuse_iomap_cache_alloc(inode);
 	return 0;
 }
 
@@ -1579,6 +1608,8 @@ void fuse_iomap_cache_free(struct inode *inode)
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	struct fuse_iomap_cache *ic = fi->cache;
 
+	trace_fuse_iomap_cache_free(inode);
+
 	/*
 	 * This is only called from eviction, so we cannot be racing to set or
 	 * clear the pointer.
@@ -1671,6 +1702,8 @@ fuse_iomap_cache_lookup(
 
 	assert_cache_locked_shared(ic);
 
+	trace_fuse_iomap_cache_lookup(ic->ic_inode, iodir, off, len, _RET_IP_);
+
 	if (ir->ir_bytes < 0) {
 		/*
 		 * No write fork at all means this filesystem doesn't do out of
@@ -1697,5 +1730,8 @@ fuse_iomap_cache_lookup(
 
 	/* Found a mapping in the cache, return it */
 	fuse_iomap_trim(fi, mval, &got, off, len);
+
+	trace_fuse_iomap_cache_lookup_result(inode, iodir, off, len, &got,
+					     mval);
 	return LOOKUP_HIT;
 }
#88 lore raw

PATCH 3/12 fuse: use the iomap cache for iomap_begin

In reply to Darrick J. Wong

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

Look inside the iomap cache to try to satisfy iomap_begin.

---
 fs/fuse/fuse_iomap_cache.h |    5 +
 fs/fuse/fuse_iomap.c       |  221 +++++++++++++++++++++++++++++++++++++++++++-
 fs/fuse/fuse_iomap_cache.c |    7 +
 3 files changed, 228 insertions(+), 5 deletions(-)
fs/fuse/fuse_iomap_cache.h +5 -0
index 922ca182357aa7..dcd52c183f22ab 100644
@@ -53,6 +53,11 @@ bool fuse_iext_get_extent(const struct fuse_iext_root *ir,
 			  const struct fuse_iext_cursor *cur,
 			  struct fuse_iomap_io *gotp);
 
+/* iomaps that come direct from the fuse server are presumed to be valid */
+#define FUSE_IOMAP_ALWAYS_VALID	((uint64_t)0)
+/* set initial iomap cookie value to avoid ALWAYS_VALID */
+#define FUSE_IOMAP_INIT_COOKIE	((uint64_t)1)
+
 static inline uint64_t fuse_iext_read_seq(struct fuse_iomap_cache *ic)
 {
 	return (uint64_t)READ_ONCE(ic->ic_seq);
fs/fuse/fuse_iomap.c +217 -4

290 lines not on this page · raw message

fs/fuse/fuse_iomap_cache.c +6 -1
index a047d7bf95257a..7fb5dd1198819f 100644
@@ -706,7 +706,11 @@ fuse_iext_realloc_root(
  */
 static inline void fuse_iext_inc_seq(struct fuse_iomap_cache *ic)
 {
-	WRITE_ONCE(ic->ic_seq, READ_ONCE(ic->ic_seq) + 1);
+	uint64_t new_val = READ_ONCE(ic->ic_seq) + 1;
+
+	if (new_val == FUSE_IOMAP_ALWAYS_VALID)
+		new_val++;
+	WRITE_ONCE(ic->ic_seq, new_val);
 }
 
 static void
@@ -1584,6 +1588,7 @@ int fuse_iomap_cache_alloc(struct inode *inode)
 
 	/* Only the write mapping cache can return NOFORK */
 	ic->ic_write.ir_bytes = -1;
+	ic->ic_seq = FUSE_IOMAP_INIT_COOKIE;
 	ic->ic_inode = inode;
 	init_rwsem(&ic->ic_lock);
 
#89 lore raw

PATCH 4/12 fuse_trace: use the iomap cache for iomap_begin

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   34 ++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    7 ++++++-
 2 files changed, 40 insertions(+), 1 deletion(-)
fs/fuse/fuse_trace.h +34 -0
index 697289c82d0dad..bf47008e50920a 100644
@@ -404,6 +404,7 @@ struct fuse_iomap_lookup;
 
 #define FUSE_IOMAP_TYPE_STRINGS \
 	{ FUSE_IOMAP_TYPE_PURE_OVERWRITE,	"overwrite" }, \
+	{ FUSE_IOMAP_TYPE_RETRY_CACHE,		"retry" }, \
 	{ FUSE_IOMAP_TYPE_HOLE,			"hole" }, \
 	{ FUSE_IOMAP_TYPE_DELALLOC,		"delalloc" }, \
 	{ FUSE_IOMAP_TYPE_MAPPED,		"mapped" }, \
@@ -1509,6 +1510,39 @@ TRACE_EVENT(fuse_iomap_cache_lookup_result,
 		  FUSE_IOMAP_MAP_PRINTK_ARGS(got),
 		  __entry->validity_cookie)
 );
+
+TRACE_EVENT(fuse_iomap_invalid,
+	TP_PROTO(const struct inode *inode, const struct iomap *map,
+		 uint64_t validity_cookie),
+	TP_ARGS(inode, map, validity_cookie),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		FUSE_IOMAP_MAP_FIELDS(map)
+		__field(uint64_t,		old_validity_cookie)
+		__field(uint64_t,		validity_cookie)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+
+		__entry->mapoffset	=	map->offset;
+		__entry->maplength	=	map->length;
+		__entry->maptype	=	map->type;
+		__entry->mapflags	=	map->flags;
+		__entry->mapaddr	=	map->addr;
+		__entry->mapdev		=	FUSE_IOMAP_DEV_NULL;
+
+		__entry->old_validity_cookie=	map->validity_cookie;
+		__entry->validity_cookie=	validity_cookie;
+	),
+
+	TP_printk(FUSE_INODE_FMT FUSE_IOMAP_MAP_FMT() " old_cookie 0x%llx new_cookie 0x%llx",
+		  FUSE_INODE_PRINTK_ARGS,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(map),
+		  __entry->old_validity_cookie,
+		  __entry->validity_cookie)
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +6 -1
index b87ccc63ac81ed..59a2481f89626d 100644
@@ -1576,7 +1576,12 @@ static bool fuse_iomap_revalidate(struct inode *inode,
 		return true;
 
 	validity_cookie = fuse_iext_read_seq(fi->cache);
-	return iomap->validity_cookie == validity_cookie;
+	if (unlikely(iomap->validity_cookie != validity_cookie)) {
+		trace_fuse_iomap_invalid(inode, iomap, validity_cookie);
+		return false;
+	}
+
+	return true;
 }
 
 static const struct iomap_write_ops fuse_iomap_write_ops = {
#90 lore raw

PATCH 5/12 fuse: invalidate iomap cache after file updates

In reply to Darrick J. Wong

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

The kernel doesn't know what the fuse server might have done in response to truncate, fallocate, or ioend events. Therefore, it must invalidate the mapping cache after those operations to ensure cache coherency.

---
 fs/fuse/fuse_iomap.h       |    3 +++
 fs/fuse/fuse_iomap_cache.h |    9 +++++++++
 fs/fuse/file.c             |   18 ++++++++++--------
 fs/fuse/fuse_iomap.c       |   26 ++++++++++++++++++++++++--
 fs/fuse/fuse_iomap_cache.c |   27 +++++++++++++++++++++++++++
 5 files changed, 73 insertions(+), 10 deletions(-)
fs/fuse/fuse_iomap.h +3 -0
index bf6640c36465e1..efc8adbc4f31dc 100644
@@ -68,6 +68,8 @@ int fuse_iomap_fallocate(struct file *file, int mode, loff_t offset,
 			 loff_t length, loff_t new_size);
 int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 				 loff_t endpos);
+void fuse_iomap_copied_file_range(struct inode *inode, loff_t offset,
+				  u64 written);
 
 int fuse_dev_ioctl_iomap_support(struct file *file,
 				 struct fuse_iomap_support __user *argp);
@@ -100,6 +102,7 @@ int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp);
 # define fuse_iomap_setsize_start(...)		(-ENOSYS)
 # define fuse_iomap_fallocate(...)		(-ENOSYS)
 # define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
+# define fuse_iomap_copied_file_range(...)	((void)0)
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
 # define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
fs/fuse/fuse_iomap_cache.h +9 -0
index dcd52c183f22ab..eba90d9519b8c3 100644
@@ -99,6 +99,15 @@ enum fuse_iomap_lookup_result
 fuse_iomap_cache_lookup(struct inode *inode, enum fuse_iomap_iodir iodir,
 			loff_t off, uint64_t len,
 			struct fuse_iomap_lookup *mval);
+
+int fuse_iomap_cache_invalidate_range(struct inode *inode, loff_t offset,
+				      uint64_t length);
+static inline int fuse_iomap_cache_invalidate(struct inode *inode,
+					      loff_t offset)
+{
+	return fuse_iomap_cache_invalidate_range(inode, offset,
+						 FUSE_IOMAP_INVAL_TO_EOF);
+}
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_CACHE_H */
fs/fuse/file.c +10 -8
index 0b21fcdefffeb7..771885adf8a5e1 100644
@@ -101,7 +101,7 @@ static void fuse_release_end(struct fuse_mount *fm, struct fuse_args *args,
 	kfree(ra);
 }
 
-static void fuse_file_put(struct fuse_file *ff, bool sync)
+static void fuse_file_put(struct fuse_file *ff, struct inode *inode, bool sync)
 {
 	if (refcount_dec_and_test(&ff->count)) {
 		struct fuse_release_args *ra = &ff->args->release_args;
@@ -385,7 +385,7 @@ void fuse_file_release(struct inode *inode, struct fuse_file *ff,
 	 * own ref to the file, the IO completion has to drop the ref, which is
 	 * how the fuse server can end up closing its clients' files.
 	 */
-	fuse_file_put(ff, false);
+	fuse_file_put(ff, inode, false);
 }
 
 void fuse_release_common(struct file *file, bool isdir)
@@ -416,7 +416,7 @@ void fuse_sync_release(struct fuse_inode *fi, struct fuse_file *ff,
 {
 	WARN_ON(refcount_read(&ff->count) > 1);
 	fuse_prepare_release(fi, ff, flags, FUSE_RELEASE, true);
-	fuse_file_put(ff, true);
+	fuse_file_put(ff, fi ? &fi->inode : NULL, true);
 }
 EXPORT_SYMBOL_GPL(fuse_sync_release);
 
@@ -1043,7 +1043,7 @@ static void fuse_readpages_end(struct fuse_mount *fm, struct fuse_args *args,
 		folio_put(ap->folios[i]);
 	}
 	if (ia->ff)
-		fuse_file_put(ia->ff, false);
+		fuse_file_put(ia->ff, inode, false);
 
 	fuse_io_free(ia);
 }
@@ -1907,7 +1907,7 @@ static void fuse_writepage_free(struct fuse_writepage_args *wpa)
 	if (wpa->bucket)
 		fuse_sync_bucket_dec(wpa->bucket);
 
-	fuse_file_put(wpa->ia.ff, false);
+	fuse_file_put(wpa->ia.ff, wpa->inode, false);
 
 	kfree(ap->folios);
 	kfree(wpa);
@@ -2064,7 +2064,7 @@ int fuse_write_inode(struct inode *inode, struct writeback_control *wbc)
 	ff = __fuse_write_file_get(fi);
 	err = fuse_flush_times(inode, ff);
 	if (ff)
-		fuse_file_put(ff, false);
+		fuse_file_put(ff, inode, false);
 
 	return err;
 }
@@ -2290,7 +2290,7 @@ static int fuse_iomap_writeback_submit(struct iomap_writepage_ctx *wpc,
 	}
 
 	if (data->ff)
-		fuse_file_put(data->ff, false);
+		fuse_file_put(data->ff, wpc->inode, false);
 
 	return error;
 }
@@ -3202,7 +3202,9 @@ static ssize_t __fuse_copy_file_range(struct file *file_in, loff_t pos_in,
 		goto out;
 	}
 
-	if (!is_iomap)
+	if (is_iomap)
+		fuse_iomap_copied_file_range(inode_out, pos_out, bytes_copied);
+	else
 		truncate_inode_pages_range(inode_out->i_mapping,
 				   ALIGN_DOWN(pos_out, PAGE_SIZE),
 				   ALIGN(pos_out + bytes_copied, PAGE_SIZE) - 1);
fs/fuse/fuse_iomap.c +24 -2
index 59a2481f89626d..98e6db197a01d3 100644
@@ -891,6 +891,7 @@ static int fuse_iomap_end(struct inode *inode, loff_t pos, loff_t count,
 			fuse_iomap_inline_free(iomap);
 			if (err)
 				return err;
+			fuse_iomap_cache_invalidate_range(inode, pos, written);
 		} else {
 			fuse_iomap_inline_free(iomap);
 		}
@@ -979,7 +980,7 @@ fuse_iomap_setsize_finish(
 	trace_fuse_iomap_setsize_finish(inode, newsize, 0);
 
 	fi->i_disk_size = newsize;
-	return 0;
+	return fuse_iomap_cache_invalidate(inode, newsize);
 }
 
 /*
@@ -1064,10 +1065,12 @@ static int fuse_iomap_ioend(struct inode *inode, loff_t pos, size_t written,
 
 	/*
 	 * If there weren't any ioend errors, update the incore isize, which
-	 * confusingly takes the new i_size as "pos".
+	 * confusingly takes the new i_size as "pos".  Invalidate cached
+	 * mappings for the file range that we just completed.
 	 */
 	fi->i_disk_size = outarg.newsize;
 	fuse_write_update_attr(inode, pos + written, written);
+	fuse_iomap_cache_invalidate_range(inode, pos, written);
 	return 0;
 }
 
@@ -1772,6 +1775,7 @@ void fuse_iomap_open_truncate(struct inode *inode)
 	trace_fuse_iomap_open_truncate(inode);
 
 	fi->i_disk_size = 0;
+	fuse_iomap_cache_invalidate(inode, 0);
 }
 
 struct fuse_writepage_ctx {
@@ -2466,6 +2470,14 @@ fuse_iomap_fallocate(
 
 	trace_fuse_iomap_fallocate(inode, mode, offset, length, new_size);
 
+	if (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE))
+		error = fuse_iomap_cache_invalidate(inode, offset);
+	else
+		error = fuse_iomap_cache_invalidate_range(inode, offset,
+							  length);
+	if (error)
+		return error;
+
 	/*
 	 * If we unmapped blocks from the file range, then we zero the
 	 * pagecache for those regions and push them to disk rather than make
@@ -2483,6 +2495,8 @@ fuse_iomap_fallocate(
 	 */
 	if (new_size) {
 		error = fuse_iomap_setsize_start(inode, new_size);
+		if (!error)
+			error = fuse_iomap_setsize_finish(inode, new_size);
 		if (error)
 			return error;
 
@@ -2604,3 +2618,11 @@ int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp)
 		return -EINVAL;
 	}
 }
+
+void fuse_iomap_copied_file_range(struct inode *inode, loff_t offset,
+				  u64 written)
+{
+	ASSERT(fuse_inode_has_iomap(inode));
+
+	fuse_iomap_cache_invalidate_range(inode, offset, written);
+}
fs/fuse/fuse_iomap_cache.c +27 -0
index 7fb5dd1198819f..4f30a27360b029 100644
@@ -1444,6 +1444,33 @@ fuse_iomap_cache_remove(
 	return ret;
 }
 
+int fuse_iomap_cache_invalidate_range(struct inode *inode, loff_t offset,
+				      uint64_t length)
+{
+	loff_t aligned_offset;
+	const unsigned int blocksize = i_blocksize(inode);
+	int ret, ret2;
+
+	if (!fuse_inode_caches_iomaps(inode))
+		return 0;
+
+	aligned_offset = round_down(offset, blocksize);
+	if (length != FUSE_IOMAP_INVAL_TO_EOF) {
+		length += offset - aligned_offset;
+		length = round_up(length, blocksize);
+	}
+
+	fuse_iomap_cache_lock(inode);
+	ret = fuse_iomap_cache_remove(inode, READ_MAPPING,
+				      aligned_offset, length);
+	ret2 = fuse_iomap_cache_remove(inode, WRITE_MAPPING,
+				       aligned_offset, length);
+	fuse_iomap_cache_unlock(inode);
+	if (ret)
+		return ret;
+	return ret2;
+}
+
 static void
 fuse_iext_add_mapping(
 	struct fuse_iomap_cache		*ic,
#91 lore raw

PATCH 6/12 fuse_trace: invalidate iomap cache after file updates

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h       |   20 ++++++++++++++++++++
 fs/fuse/fuse_iomap.c       |    2 ++
 fs/fuse/fuse_iomap_cache.c |    2 ++
 3 files changed, 24 insertions(+)
fs/fuse/fuse_trace.h +20 -0
index bf47008e50920a..ddcbefd33a4024 100644
@@ -932,6 +932,7 @@ DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_truncate_up);
 DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_truncate_down);
 DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_punch_range);
 DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_flush_unmap_range);
+DEFINE_FUSE_IOMAP_FILE_RANGE_EVENT(fuse_iomap_cache_invalidate_range);
 
 TRACE_EVENT(fuse_iomap_end_ioend,
 	TP_PROTO(const struct iomap_ioend *ioend),
@@ -1248,6 +1249,25 @@ DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_inline_write);
 DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_iomap);
 DEFINE_FUSE_IOMAP_INLINE_EVENT(fuse_iomap_set_inline_srcmap);
 
+TRACE_EVENT(fuse_iomap_copied_file_range,
+	TP_PROTO(const struct inode *inode, loff_t offset,
+		 size_t written),
+	TP_ARGS(inode, offset, written),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->offset		=	offset;
+		__entry->length		=	written;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT(),
+		  FUSE_IO_RANGE_PRINTK_ARGS())
+);
+
 DECLARE_EVENT_CLASS(fuse_iext_class,
 	TP_PROTO(const struct inode *inode, const struct fuse_iext_cursor *cur,
 		 int state, unsigned long caller_ip),
fs/fuse/fuse_iomap.c +2 -0
index 98e6db197a01d3..4bc2322a4ba796 100644
@@ -2624,5 +2624,7 @@ void fuse_iomap_copied_file_range(struct inode *inode, loff_t offset,
 {
 	ASSERT(fuse_inode_has_iomap(inode));
 
+	trace_fuse_iomap_copied_file_range(inode, offset, written);
+
 	fuse_iomap_cache_invalidate_range(inode, offset, written);
 }
fs/fuse/fuse_iomap_cache.c +2 -0
index 4f30a27360b029..277311c7c0c4ea 100644
@@ -1454,6 +1454,8 @@ int fuse_iomap_cache_invalidate_range(struct inode *inode, loff_t offset,
 	if (!fuse_inode_caches_iomaps(inode))
 		return 0;
 
+	trace_fuse_iomap_cache_invalidate_range(inode, offset, length);
+
 	aligned_offset = round_down(offset, blocksize);
 	if (length != FUSE_IOMAP_INVAL_TO_EOF) {
 		length += offset - aligned_offset;
#92 lore raw

PATCH 7/12 fuse: enable iomap cache management

In reply to Darrick J. Wong

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

Provide a means for the fuse server to upload iomappings to the kernel and invalidate them. This is how we enable iomap caching for better performance. This is also required for correct synchronization between pagecache writes and writeback.

---
 fs/fuse/fuse_iomap.h      |    7 +
 include/uapi/linux/fuse.h |   29 +++++
 fs/fuse/dev.c             |   46 ++++++++
 fs/fuse/fuse_iomap.c      |  264 ++++++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 343 insertions(+), 3 deletions(-)
fs/fuse/fuse_iomap.h +7 -0
index efc8adbc4f31dc..b13d305ee0508b 100644
@@ -78,6 +78,11 @@ int fuse_iomap_dev_inval(struct fuse_conn *fc,
 
 int fuse_iomap_fadvise(struct file *file, loff_t start, loff_t end, int advice);
 int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp);
+
+int fuse_iomap_upsert_mappings(struct fuse_conn *fc,
+		      const struct fuse_iomap_upsert_mappings_out *outarg);
+int fuse_iomap_inval_mappings(struct fuse_conn *fc,
+		     const struct fuse_iomap_inval_mappings_out *outarg);
 #else
 # define fuse_iomap_enabled(...)		(false)
 # define fuse_has_iomap(...)			(false)
@@ -107,6 +112,8 @@ int fuse_dev_ioctl_iomap_set_nofs(struct file *file, uint32_t __user *argp);
 # define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
 # define fuse_dev_ioctl_iomap_set_nofs(...)	(-EOPNOTSUPP)
+# define fuse_iomap_upsert_mappings(...)	(-ENOSYS)
+# define fuse_iomap_inval_mappings(...)		(-ENOSYS)
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_H */
include/uapi/linux/fuse.h +29 -0
index a273838bc20f2f..8c5e67731b21b8 100644
@@ -251,6 +251,8 @@
  *  - add FUSE_ATTR_ATOMIC for single-fsblock atomic write support
  *  - add FUSE_ATTR_{SYNC,IMMUTABLE,APPEND} for VFS enforcement of file
  *    attributes
+ *  - add FUSE_NOTIFY_IOMAP_{UPSERT,INVAL}_MAPPINGS so fuse servers can cache
+ *    file range mappings in the kernel for iomap
  */
 
 #ifndef _LINUX_FUSE_H
@@ -731,6 +733,8 @@ enum fuse_notify_code {
 	FUSE_NOTIFY_INC_EPOCH = 8,
 	FUSE_NOTIFY_PRUNE = 9,
 	FUSE_NOTIFY_IOMAP_DEV_INVAL = 99,
+	FUSE_NOTIFY_IOMAP_UPSERT_MAPPINGS = 100,
+	FUSE_NOTIFY_IOMAP_INVAL_MAPPINGS = 101,
 	FUSE_NOTIFY_CODE_MAX,
 };
 
@@ -1396,6 +1400,8 @@ struct fuse_uring_cmd_req {
 #define FUSE_IOMAP_TYPE_PURE_OVERWRITE	(255)
 /* fuse-specific mapping type saying the server has populated the cache */
 #define FUSE_IOMAP_TYPE_RETRY_CACHE	(254)
+/* do not upsert this mapping */
+#define FUSE_IOMAP_TYPE_NOCACHE		(253)
 
 #define FUSE_IOMAP_DEV_NULL		(0U)	/* null device cookie */
 
@@ -1556,4 +1562,27 @@ struct fuse_iomap_dev_inval_out {
 /* invalidate all cached iomap mappings up to EOF */
 #define FUSE_IOMAP_INVAL_TO_EOF		(~0ULL)
 
+struct fuse_iomap_inval_mappings_out {
+	uint64_t nodeid;	/* Inode ID */
+	uint64_t attr_ino;	/* matches fuse_attr:ino */
+
+	/*
+	 * Range of read and mappings to invalidate.  Zero length means ignore
+	 * the range; and FUSE_IOMAP_INVAL_TO_EOF can be used for length.
+	 */
+	struct fuse_range read;
+	struct fuse_range write;
+};
+
+struct fuse_iomap_upsert_mappings_out {
+	uint64_t nodeid;	/* Inode ID */
+	uint64_t attr_ino;	/* matches fuse_attr:ino */
+
+	/* read file data from here */
+	struct fuse_iomap_io	read;
+
+	/* write file data to here, if applicable */
+	struct fuse_iomap_io	write;
+};
+
 #endif /* _LINUX_FUSE_H */
fs/fuse/dev.c +46 -0

58 lines not on this page · raw message

fs/fuse/fuse_iomap.c +261 -3

305 lines not on this page · raw message

#93 lore raw

PATCH 8/12 fuse_trace: enable iomap cache management

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h |   67 ++++++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/fuse_iomap.c |    4 +++
 2 files changed, 71 insertions(+)
fs/fuse/fuse_trace.h +67 -0
index ddcbefd33a4024..09da9bce61b98c 100644
@@ -405,6 +405,7 @@ struct fuse_iomap_lookup;
 #define FUSE_IOMAP_TYPE_STRINGS \
 	{ FUSE_IOMAP_TYPE_PURE_OVERWRITE,	"overwrite" }, \
 	{ FUSE_IOMAP_TYPE_RETRY_CACHE,		"retry" }, \
+	{ FUSE_IOMAP_TYPE_NOCACHE,		"nocache" }, \
 	{ FUSE_IOMAP_TYPE_HOLE,			"hole" }, \
 	{ FUSE_IOMAP_TYPE_DELALLOC,		"delalloc" }, \
 	{ FUSE_IOMAP_TYPE_MAPPED,		"mapped" }, \
@@ -1563,6 +1564,72 @@ TRACE_EVENT(fuse_iomap_invalid,
 		  __entry->old_validity_cookie,
 		  __entry->validity_cookie)
 );
+
+TRACE_EVENT(fuse_iomap_upsert_mappings,
+	TP_PROTO(const struct inode *inode,
+		 const struct fuse_iomap_upsert_mappings_out *outarg),
+	TP_ARGS(inode, outarg),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(uint64_t,		attr_ino)
+
+		FUSE_IOMAP_MAP_FIELDS(read)
+		FUSE_IOMAP_MAP_FIELDS(write)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->attr_ino	=	outarg->attr_ino;
+		__entry->readoffset	=	outarg->read.offset;
+		__entry->readlength	=	outarg->read.length;
+		__entry->readaddr	=	outarg->read.addr;
+		__entry->readtype	=	outarg->read.type;
+		__entry->readflags	=	outarg->read.flags;
+		__entry->readdev	=	outarg->read.dev;
+		__entry->writeoffset	=	outarg->write.offset;
+		__entry->writelength	=	outarg->write.length;
+		__entry->writeaddr	=	outarg->write.addr;
+		__entry->writetype	=	outarg->write.type;
+		__entry->writeflags	=	outarg->write.flags;
+		__entry->writedev	=	outarg->write.dev;
+	),
+
+	TP_printk(FUSE_INODE_FMT " attr_ino 0x%llx" FUSE_IOMAP_MAP_FMT("read") FUSE_IOMAP_MAP_FMT("write"),
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->attr_ino,
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(read),
+		  FUSE_IOMAP_MAP_PRINTK_ARGS(write))
+);
+
+TRACE_EVENT(fuse_iomap_inval_mappings,
+	TP_PROTO(const struct inode *inode,
+		 const struct fuse_iomap_inval_mappings_out *outarg),
+	TP_ARGS(inode, outarg),
+
+	TP_STRUCT__entry(
+		FUSE_INODE_FIELDS
+		__field(uint64_t,		attr_ino)
+
+		FUSE_FILE_RANGE_FIELDS(read)
+		FUSE_FILE_RANGE_FIELDS(write)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->attr_ino	=	outarg->attr_ino;
+		__entry->readoffset	=	outarg->read.offset;
+		__entry->readlength	=	outarg->read.length;
+		__entry->writeoffset	=	outarg->write.offset;
+		__entry->writelength	=	outarg->write.length;
+	),
+
+	TP_printk(FUSE_INODE_FMT " attr_ino 0x%llx" FUSE_FILE_RANGE_FMT("read") FUSE_FILE_RANGE_FMT("write"),
+		  FUSE_INODE_PRINTK_ARGS,
+		  __entry->attr_ino,
+		  FUSE_FILE_RANGE_PRINTK_ARGS(read),
+		  FUSE_FILE_RANGE_PRINTK_ARGS(write))
+);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _TRACE_FUSE_H */
fs/fuse/fuse_iomap.c +4 -0
index 478c11b90ad4aa..2e428b6e6b0ce6 100644
@@ -2781,6 +2781,8 @@ int fuse_iomap_upsert_mappings(struct fuse_conn *fc,
 		goto out_sb;
 	}
 
+	trace_fuse_iomap_upsert_mappings(inode, outarg);
+
 	fi = get_fuse_inode(inode);
 	if (BAD_DATA(fi->orig_ino != outarg->attr_ino)) {
 		ret = -EINVAL;
@@ -2868,6 +2870,8 @@ int fuse_iomap_inval_mappings(struct fuse_conn *fc,
 		goto out_sb;
 	}
 
+	trace_fuse_iomap_inval_mappings(inode, outarg);
+
 	fi = get_fuse_inode(inode);
 	if (BAD_DATA(fi->orig_ino != outarg->attr_ino)) {
 		ret = -EINVAL;
#94 lore raw

PATCH 9/12 fuse: overlay iomap inode info in struct fuse_inode

In reply to Darrick J. Wong

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

It's not possible for a regular file to use iomap mode and writeback caching at the same time, so we can save some memory in struct fuse_inode by overlaying them in the union. This is a separate patch because C unions are rather unsafe and I prefer any errors to be bisectable to this patch.

---
 fs/fuse/fuse_i.h |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/fuse/fuse_i.h +4 -1
index 1ba95d1f430c3e..f6725d699b3e26 100644
@@ -188,8 +188,11 @@ struct fuse_inode {
 
 			/* waitq for direct-io completion */
 			wait_queue_head_t direct_io_waitq;
+		};
 
 #ifdef CONFIG_FUSE_IOMAP
+		/* regular file iomap mode */
+		struct {
 			/* file size as reported by fuse server */
 			loff_t i_disk_size;
 
@@ -200,8 +203,8 @@ struct fuse_inode {
 
 			/* cached iomap mappings */
 			struct fuse_iomap_cache *cache;
-#endif
 		};
+#endif
 
 		/* readdir cache (directory only) */
 		struct {
#95 lore raw

PATCH 10/12 fuse: constrain iomap mapping cache size

In reply to Darrick J. Wong

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

Provide a means to constrain the size of each iomap mapping cache. Most files (at least on XFS) don't have more than 1000 extents, so we'll set the absolute maximum to 10000 and let the fuse server set a lower limit if it so desires.

---
 fs/fuse/fuse_i.h           |    3 +++
 fs/fuse/fuse_iomap_cache.h |    8 ++++++++
 include/uapi/linux/fuse.h  |    7 ++++++-
 fs/fuse/fuse_iomap.c       |    9 ++++++++-
 fs/fuse/fuse_iomap_cache.c |   24 ++++++++++++++++++++++++
 5 files changed, 49 insertions(+), 2 deletions(-)
fs/fuse/fuse_i.h +3 -0
index f6725d699b3e26..5c10be0d02538e 100644
@@ -683,6 +683,9 @@ struct fuse_iomap_conn {
 
 	/* fuse server doesn't implement iomap_ioend */
 	unsigned int no_ioend:1;
+
+	/* maximum mapping cache size */
+	unsigned int cache_maxbytes;
 };
 #endif
 
fs/fuse/fuse_iomap_cache.h +8 -0
index eba90d9519b8c3..cb312b0720d6b7 100644
@@ -108,6 +108,14 @@ static inline int fuse_iomap_cache_invalidate(struct inode *inode,
 	return fuse_iomap_cache_invalidate_range(inode, offset,
 						 FUSE_IOMAP_INVAL_TO_EOF);
 }
+
+/* absolute maximum memory consumption per iomap mapping cache */
+#define FUSE_IOMAP_CACHE_MAX_MAXBYTES		(SZ_2M)
+
+/* default maximum memory consumption per iomap mapping cache */
+#define FUSE_IOMAP_CACHE_DEFAULT_MAXBYTES	(SZ_256K)
+
+void fuse_iomap_cache_set_maxbytes(struct fuse_conn *fc, unsigned int maxbytes);
 #endif /* CONFIG_FUSE_IOMAP */
 
 #endif /* _FS_FUSE_IOMAP_CACHE_H */
include/uapi/linux/fuse.h +6 -1
index 8c5e67731b21b8..035e1a59ce50d3 100644
@@ -1512,7 +1512,9 @@ struct fuse_iomap_ioend_out {
 struct fuse_iomap_config_in {
 	uint64_t flags;		/* supported FUSE_IOMAP_CONFIG_* flags */
 	int64_t maxbytes;	/* maximum supported file size */
-	uint64_t padding[6];	/* zero */
+	uint32_t cache_maxbytes; /* mapping cache maxbytes */
+	uint32_t zero;		/* zero */
+	uint64_t padding[5];	/* zero */
 };
 
 /* Which fields are set in fuse_iomap_config_out? */
@@ -1522,6 +1524,7 @@ struct fuse_iomap_config_in {
 #define FUSE_IOMAP_CONFIG_MAX_LINKS	(1 << 3ULL)
 #define FUSE_IOMAP_CONFIG_TIME		(1 << 4ULL)
 #define FUSE_IOMAP_CONFIG_MAXBYTES	(1 << 5ULL)
+#define FUSE_IOMAP_CONFIG_CACHE_MAXBYTES (1 << 6ULL)
 
 struct fuse_iomap_config_out {
 	uint64_t flags;		/* FUSE_IOMAP_CONFIG_* */
@@ -1544,6 +1547,8 @@ struct fuse_iomap_config_out {
 	int64_t s_time_max;
 
 	int64_t s_maxbytes;	/* max file size */
+
+	uint32_t cache_maxbytes; /* mapping cache maximum size */
 };
 
 struct fuse_range {
fs/fuse/fuse_iomap.c +8 -1
index 2e428b6e6b0ce6..8fad9278293bff 100644
@@ -1141,7 +1141,8 @@ struct fuse_iomap_config_args {
 			       FUSE_IOMAP_CONFIG_BLOCKSIZE | \
 			       FUSE_IOMAP_CONFIG_MAX_LINKS | \
 			       FUSE_IOMAP_CONFIG_TIME | \
-			       FUSE_IOMAP_CONFIG_MAXBYTES)
+			       FUSE_IOMAP_CONFIG_MAXBYTES | \
+			       FUSE_IOMAP_CONFIG_CACHE_MAXBYTES)
 
 static int fuse_iomap_process_config(struct fuse_mount *fm, int error,
 				     const struct fuse_iomap_config_out *outarg)
@@ -1206,6 +1207,9 @@ static int fuse_iomap_process_config(struct fuse_mount *fm, int error,
 	if (outarg->flags & FUSE_IOMAP_CONFIG_MAXBYTES)
 		sb->s_maxbytes = outarg->s_maxbytes;
 
+	if (outarg->flags & FUSE_IOMAP_CONFIG_CACHE_MAXBYTES)
+		fuse_iomap_cache_set_maxbytes(fm->fc, outarg->cache_maxbytes);
+
 	return 0;
 }
 
@@ -1267,6 +1271,9 @@ fuse_iomap_new_mount(struct fuse_mount *fm)
 	ia->inarg.maxbytes = MAX_LFS_FILESIZE;
 	ia->inarg.flags = FUSE_IOMAP_CONFIG_ALL;
 
+	fm->fc->iomap_conn.cache_maxbytes = FUSE_IOMAP_CACHE_DEFAULT_MAXBYTES;
+	ia->inarg.cache_maxbytes = fm->fc->iomap_conn.cache_maxbytes;
+
 	ia->args.opcode = FUSE_IOMAP_CONFIG;
 	ia->args.nodeid = 0;
 	ia->args.in_numargs = 1;
fs/fuse/fuse_iomap_cache.c +24 -0
index 277311c7c0c4ea..b9e6083a18ce63 100644
@@ -1654,6 +1654,28 @@ void fuse_iomap_cache_free(struct inode *inode)
 	kfree(ic);
 }
 
+void fuse_iomap_cache_set_maxbytes(struct fuse_conn *fc, unsigned int maxbytes)
+{
+	if (!maxbytes)
+		return;
+
+	fc->iomap_conn.cache_maxbytes = clamp(maxbytes, NODE_SIZE,
+					      FUSE_IOMAP_CACHE_MAX_MAXBYTES);
+}
+
+static void
+fuse_iomap_cache_cleanup(
+	struct inode		*inode,
+	enum fuse_iomap_iodir	iodir)
+{
+	struct fuse_inode	*fi = get_fuse_inode(inode);
+	struct fuse_mount	*fm = get_fuse_mount(inode);
+	struct fuse_iext_root	*ir = fuse_iext_root_ptr(fi->cache, iodir);
+
+	if (ir && ir->ir_bytes > fm->fc->iomap_conn.cache_maxbytes)
+		fuse_iext_destroy(ir);
+}
+
 int
 fuse_iomap_cache_upsert(
 	struct inode			*inode,
@@ -1680,6 +1702,8 @@ fuse_iomap_cache_upsert(
 	if (err)
 		return err;
 
+	fuse_iomap_cache_cleanup(inode, iodir);
+
 	return fuse_iomap_cache_add(inode, iodir, map);
 }
 
#96 lore raw

PATCH 11/12 fuse_trace: constrain iomap mapping cache size

In reply to Darrick J. Wong

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

Add tracepoints for the previous patch.

---
 fs/fuse/fuse_trace.h       |   31 +++++++++++++++++++++++++++++--
 fs/fuse/fuse_iomap_cache.c |    4 +++-
 2 files changed, 32 insertions(+), 3 deletions(-)
fs/fuse/fuse_trace.h +29 -2
index 09da9bce61b98c..aa2d5ca88c9d40 100644
@@ -320,6 +320,7 @@ struct iomap_ioend;
 struct iomap;
 struct fuse_iext_cursor;
 struct fuse_iomap_lookup;
+struct fuse_iext_root;
 
 /* tracepoint boilerplate so we don't have to keep doing this */
 #define FUSE_IOMAP_OPFLAGS_FIELD \
@@ -1157,6 +1158,8 @@ TRACE_EVENT(fuse_iomap_config,
 		__field(int64_t,		time_max)
 		__field(int64_t,		maxbytes)
 		__field(uint8_t,		uuid_len)
+
+		__field(uint32_t,		cache_maxbytes)
 	),
 
 	TP_fast_assign(
@@ -1170,14 +1173,15 @@ TRACE_EVENT(fuse_iomap_config,
 		__entry->time_max	=	outarg->s_time_max;
 		__entry->maxbytes	=	outarg->s_maxbytes;
 		__entry->uuid_len	=	outarg->s_uuid_len;
+		__entry->cache_maxbytes	=	outarg->cache_maxbytes;
 	),
 
-	TP_printk("connection %u root_ino 0x%llx flags (%s) blocksize 0x%x max_links %u time_gran %u time_min %lld time_max %lld maxbytes 0x%llx uuid_len %u",
+	TP_printk("connection %u root_ino 0x%llx flags (%s) blocksize 0x%x max_links %u time_gran %u time_min %lld time_max %lld maxbytes 0x%llx uuid_len %u cache_maxbytes %u",
 		  __entry->connection, __entry->root_nodeid,
 		  __print_flags(__entry->flags, "|", FUSE_IOMAP_CONFIG_STRINGS),
 		  __entry->blocksize, __entry->max_links, __entry->time_gran,
 		  __entry->time_min, __entry->time_max, __entry->maxbytes,
-		  __entry->uuid_len)
+		  __entry->uuid_len, __entry->cache_maxbytes)
 );
 
 TRACE_EVENT(fuse_iomap_dev_inval,
@@ -1395,6 +1399,29 @@ DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_del_mapping_got);
 DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_add_mapping_left);
 DEFINE_IEXT_ALT_UPDATE_EVENT(fuse_iext_add_mapping_right);
 
+TRACE_EVENT(fuse_iomap_cache_cleanup,
+	TP_PROTO(const struct inode *inode, unsigned int iodir,
+		 struct fuse_iext_root *ir),
+	TP_ARGS(inode, iodir, ir),
+
+	TP_STRUCT__entry(
+		FUSE_IO_RANGE_FIELDS()
+		FUSE_IOMAP_IODIR_FIELD
+		__field(unsigned long long,	bytes)
+	),
+
+	TP_fast_assign(
+		FUSE_INODE_ASSIGN(inode, fi, fm);
+		__entry->iodir		=	iodir;
+		__entry->bytes		=	ir->ir_bytes;
+	),
+
+	TP_printk(FUSE_IO_RANGE_FMT() FUSE_IOMAP_IODIR_FMT " bytes 0x%llx",
+		  FUSE_IO_RANGE_PRINTK_ARGS(),
+		  FUSE_IOMAP_IODIR_PRINTK_ARGS,
+		  __entry->bytes)
+);
+
 TRACE_EVENT(fuse_iomap_cache_remove,
 	TP_PROTO(const struct inode *inode, unsigned int iodir,
 		 loff_t offset, uint64_t length, unsigned long caller_ip),
fs/fuse/fuse_iomap_cache.c +3 -1
index b9e6083a18ce63..7f79ea4197e676 100644
@@ -1672,8 +1672,10 @@ fuse_iomap_cache_cleanup(
 	struct fuse_mount	*fm = get_fuse_mount(inode);
 	struct fuse_iext_root	*ir = fuse_iext_root_ptr(fi->cache, iodir);
 
-	if (ir && ir->ir_bytes > fm->fc->iomap_conn.cache_maxbytes)
+	if (ir && ir->ir_bytes > fm->fc->iomap_conn.cache_maxbytes) {
+		trace_fuse_iomap_cache_cleanup(inode, iodir, ir);
 		fuse_iext_destroy(ir);
+	}
 }
 
 int
#97 lore raw

PATCH 12/12 fuse: enable iomap

In reply to Darrick J. Wong

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

Remove the guard that we used to avoid bisection problems.

---
 fs/fuse/fuse_iomap.c |    3 ---
 1 file changed, 3 deletions(-)
fs/fuse/fuse_iomap.c +0 -3
index 8fad9278293bff..74bd18bb4009c6 100644
@@ -70,9 +70,6 @@ MODULE_PARM_DESC(debug_iomap, "Enable debugging of fuse 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
#98 lore raw

PATCH v7 8/9 fuse: run fuse servers as a contained service

In reply to Darrick J. Wong

Hi all,

This patchset defines the necessary communication protocols and library code so that users can mount fuse servers that run in unprivileged systemd service containers. That in turn allows unprivileged untrusted mounts, because the worst that can happen is that a malicious image crashes the fuse server and the mount dies, instead of corrupting the kernel. As part of the delegation, add a new ioctl allowing any process with an open fusedev fd to ask for permission for anyone with that fusedev fd to use iomap.

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

With a bit of luck, this should all go splendidly. 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-service-container
---
Commits in this patchset:
* fuse: allow privileged mount helpers to pre-approve iomap usage
* fuse: set iomap backing device block size

---
 fs/fuse/fuse_dev_i.h      |   32 ++++++++++++++++++--
 fs/fuse/fuse_i.h          |    7 ++++
 fs/fuse/fuse_iomap.h      |    5 +++
 include/uapi/linux/fuse.h |    8 +++++
 fs/fuse/dev.c             |   13 ++++----
 fs/fuse/fuse_iomap.c      |   72 ++++++++++++++++++++++++++++++++++++++++++++-
 fs/fuse/inode.c           |   18 ++++++++---
 7 files changed, 138 insertions(+), 17 deletions(-)
#99 lore raw

PATCH 1/2 fuse: allow privileged mount helpers to pre-approve iomap usage

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

For the upcoming safemount functionality in libfuse, we will create a privileged "mount.safe" helper that starts the fuse server in a completely unprivileged systemd container. The mount helper will pass the mount options and fds for /dev/fuse and any other files requested by the fuse server into the container via a Unix socket.

Currently, the ability to turn on iomap for fuse depends on a module parameter and the process that calls mount() having the CAP_SYS_RAWIO capability. However, the unprivilged fuse server might want to query the /dev/fuse fd for iomap capabilities before mount or FUSE_INIT so that it can get ready.

Similar to FUSE_DEV_SYNC_INIT, add a new bit for iomap that can be squirreled away in file->private_data and an ioctl to set that bit. That way the privileged mount helper can pass its iomap privilege to the contained fuse server without the fuse server needing to have CAP_SYS_RAWIO.

---
 fs/fuse/fuse_dev_i.h      |   32 +++++++++++++++++++++++++++++---
 fs/fuse/fuse_i.h          |    7 +++++++
 fs/fuse/fuse_iomap.h      |    2 ++
 include/uapi/linux/fuse.h |    1 +
 fs/fuse/dev.c             |   11 +++++------
 fs/fuse/fuse_iomap.c      |   45 +++++++++++++++++++++++++++++++++++++++++++--
 fs/fuse/inode.c           |   18 ++++++++++++------
 7 files changed, 99 insertions(+), 17 deletions(-)
fs/fuse/fuse_dev_i.h +29 -3
index 134bf44aff0d39..900c0ce2ffa96e 100644
@@ -39,8 +39,10 @@ struct fuse_copy_state {
 	} ring;
 };
 
-#define FUSE_DEV_SYNC_INIT ((struct fuse_dev *) 1)
-#define FUSE_DEV_PTR_MASK (~1UL)
+#define FUSE_DEV_SYNC_INIT	(1UL << 0)
+#define FUSE_DEV_INHERIT_IOMAP	(1UL << 1)
+#define FUSE_DEV_FLAGS_MASK	(FUSE_DEV_SYNC_INIT | FUSE_DEV_INHERIT_IOMAP)
+#define FUSE_DEV_PTR_MASK	(~FUSE_DEV_FLAGS_MASK)
 
 static inline struct fuse_dev *__fuse_get_dev(struct file *file)
 {
@@ -50,7 +52,31 @@ static inline struct fuse_dev *__fuse_get_dev(struct file *file)
 	 */
 	struct fuse_dev *fud = READ_ONCE(file->private_data);
 
-	return (typeof(fud)) ((unsigned long) fud & FUSE_DEV_PTR_MASK);
+	return (typeof(fud)) ((uintptr_t)fud & FUSE_DEV_PTR_MASK);
+}
+
+static inline struct fuse_dev *__fuse_get_dev_and_flags(struct file *file,
+							uintptr_t *flagsp)
+{
+	/*
+	 * Lockless access is OK, because file->private data is set
+	 * once during mount and is valid until the file is released.
+	 */
+	struct fuse_dev *fud = READ_ONCE(file->private_data);
+
+	*flagsp = ((uintptr_t)fud) & FUSE_DEV_FLAGS_MASK;
+	return (typeof(fud)) ((uintptr_t) fud & FUSE_DEV_PTR_MASK);
+}
+
+static inline int __fuse_set_dev_flags(struct file *file, uintptr_t flag)
+{
+	uintptr_t old_flags = 0;
+
+	if (__fuse_get_dev_and_flags(file, &old_flags))
+		return -EINVAL;
+
+	WRITE_ONCE(file->private_data, (struct fuse_dev *)(old_flags | flag));
+	return 0;
 }
 
 struct fuse_dev *fuse_get_dev(struct file *file);
fs/fuse/fuse_i.h +7 -0
index 5c10be0d02538e..5f2e7755e3e4e4 100644
@@ -982,6 +982,13 @@ struct fuse_conn {
 	/* Enable fs/iomap for file operations */
 	unsigned int iomap:1;
 
+	/*
+	 * Are filesystems using this connection allowed to use iomap?  This is
+	 * determined by the privilege level of the process that initiated the
+	 * mount() call.
+	 */
+	unsigned int may_iomap:1;
+
 	/* Use io_uring for communication */
 	unsigned int io_uring;
 
fs/fuse/fuse_iomap.h +2 -0
index b13d305ee0508b..6afc916e31a4fa 100644
@@ -71,6 +71,7 @@ int fuse_iomap_flush_unmap_range(struct inode *inode, loff_t pos,
 void fuse_iomap_copied_file_range(struct inode *inode, loff_t offset,
 				  u64 written);
 
+int fuse_dev_ioctl_add_iomap(struct file *file);
 int fuse_dev_ioctl_iomap_support(struct file *file,
 				 struct fuse_iomap_support __user *argp);
 int fuse_iomap_dev_inval(struct fuse_conn *fc,
@@ -108,6 +109,7 @@ int fuse_iomap_inval_mappings(struct fuse_conn *fc,
 # define fuse_iomap_fallocate(...)		(-ENOSYS)
 # define fuse_iomap_flush_unmap_range(...)	(-ENOSYS)
 # define fuse_iomap_copied_file_range(...)	((void)0)
+# define fuse_dev_ioctl_add_iomap(...)		(-EOPNOTSUPP)
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
 # define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
include/uapi/linux/fuse.h +1 -0
index 035e1a59ce50d3..1132493c66d266 100644
@@ -1212,6 +1212,7 @@ struct fuse_iomap_support {
 #define FUSE_DEV_IOC_IOMAP_SUPPORT	_IOR(FUSE_DEV_IOC_MAGIC, 99, \
 					     struct fuse_iomap_support)
 #define FUSE_DEV_IOC_SET_NOFS		_IOW(FUSE_DEV_IOC_MAGIC, 100, uint32_t)
+#define FUSE_DEV_IOC_ADD_IOMAP		_IO(FUSE_DEV_IOC_MAGIC, 101)
 
 struct fuse_lseek_in {
 	uint64_t	fh;
fs/fuse/dev.c +5 -6
index b2433dec8cc5e5..f4ca408653cf61 100644
@@ -1559,7 +1559,7 @@ struct fuse_dev *fuse_get_dev(struct file *file)
 		return fud;
 
 	err = wait_event_interruptible(fuse_dev_waitq,
-				       READ_ONCE(file->private_data) != FUSE_DEV_SYNC_INIT);
+				       __fuse_get_dev(file) != NULL);
 	if (err)
 		return ERR_PTR(err);
 
@@ -2757,13 +2757,10 @@ static long fuse_dev_ioctl_backing_close(struct file *file, __u32 __user *argp)
 
 static long fuse_dev_ioctl_sync_init(struct file *file)
 {
-	int err = -EINVAL;
+	int err;
 
 	mutex_lock(&fuse_mutex);
-	if (!__fuse_get_dev(file)) {
-		WRITE_ONCE(file->private_data, FUSE_DEV_SYNC_INIT);
-		err = 0;
-	}
+	err = __fuse_set_dev_flags(file, FUSE_DEV_SYNC_INIT);
 	mutex_unlock(&fuse_mutex);
 	return err;
 }
@@ -2790,6 +2787,8 @@ static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
 		return fuse_dev_ioctl_iomap_support(file, argp);
 	case FUSE_DEV_IOC_SET_NOFS:
 		return fuse_dev_ioctl_iomap_set_nofs(file, argp);
+	case FUSE_DEV_IOC_ADD_IOMAP:
+		return fuse_dev_ioctl_add_iomap(file);
 
 	default:
 		return -ENOTTY;
fs/fuse/fuse_iomap.c +43 -2

74 lines not on this page · raw message

fs/fuse/inode.c +12 -6
index 1fedfb57a22514..0f2b12aa1ac4bb 100644
@@ -1047,6 +1047,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;
 	fc->root_nodeid = FUSE_ROOT_ID;
+	fc->may_iomap = fuse_iomap_enabled();
 
 	if (IS_ENABLED(CONFIG_FUSE_BACKING))
 		fuse_backing_files_init(fc);
@@ -1581,7 +1582,7 @@ 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()) {
+			if ((flags & FUSE_IOMAP) && fc->may_iomap) {
 				fc->iomap = 1;
 				pr_warn(
  "EXPERIMENTAL iomap feature enabled.  Use at your own risk!");
@@ -1668,7 +1669,7 @@ 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())
+	if (fm->fc->may_iomap)
 		flags |= FUSE_IOMAP;
 
 	ia->in.flags = flags;
@@ -2041,11 +2042,16 @@ int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx)
 
 	mutex_lock(&fuse_mutex);
 	err = -EINVAL;
-	if (ctx->fudptr && *ctx->fudptr) {
-		if (*ctx->fudptr == FUSE_DEV_SYNC_INIT)
-			fc->sync_init = 1;
-		else
+	if (ctx->fudptr) {
+		uintptr_t raw = (uintptr_t)(*ctx->fudptr);
+		uintptr_t flags = raw & FUSE_DEV_FLAGS_MASK;
+
+		if (raw & FUSE_DEV_PTR_MASK)
 			goto err_unlock;
+		if (flags & FUSE_DEV_SYNC_INIT)
+			fc->sync_init = 1;
+		if (flags & FUSE_DEV_INHERIT_IOMAP)
+			fc->may_iomap = 1;
 	}
 
 	err = fuse_ctl_add_conn(fc);
#100 lore raw

PATCH 2/2 fuse: set iomap backing device block size

In reply to Darrick J. Wong

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

Add a new ioctl so that an unprivileged fuse server can set the block size of a bdev that's opened for iomap usage.

---
 fs/fuse/fuse_iomap.h      |    3 +++
 include/uapi/linux/fuse.h |    7 +++++++
 fs/fuse/dev.c             |    2 ++
 fs/fuse/fuse_iomap.c      |   27 +++++++++++++++++++++++++++
 4 files changed, 39 insertions(+)
fs/fuse/fuse_iomap.h +3 -0
index 6afc916e31a4fa..f61e99941e94cb 100644
@@ -74,6 +74,8 @@ void fuse_iomap_copied_file_range(struct inode *inode, loff_t offset,
 int fuse_dev_ioctl_add_iomap(struct file *file);
 int fuse_dev_ioctl_iomap_support(struct file *file,
 				 struct fuse_iomap_support __user *argp);
+int fuse_dev_ioctl_iomap_set_blocksize(struct file *file,
+				struct fuse_iomap_backing_info __user *argp);
 int fuse_iomap_dev_inval(struct fuse_conn *fc,
 			 const struct fuse_iomap_dev_inval_out *arg);
 
@@ -111,6 +113,7 @@ int fuse_iomap_inval_mappings(struct fuse_conn *fc,
 # define fuse_iomap_copied_file_range(...)	((void)0)
 # define fuse_dev_ioctl_add_iomap(...)		(-EOPNOTSUPP)
 # define fuse_dev_ioctl_iomap_support(...)	(-EOPNOTSUPP)
+# define fuse_dev_ioctl_iomap_set_blocksize(...) (-EOPNOTSUPP)
 # define fuse_iomap_dev_inval(...)		(-ENOSYS)
 # define fuse_iomap_fadvise			NULL
 # define fuse_dev_ioctl_iomap_set_nofs(...)	(-EOPNOTSUPP)
include/uapi/linux/fuse.h +7 -0
index 1132493c66d266..94e99a01af5da7 100644
@@ -1202,6 +1202,11 @@ struct fuse_iomap_support {
 	uint64_t	padding;
 };
 
+struct fuse_iomap_backing_info {
+	uint32_t	backing_id;
+	uint32_t	blocksize;
+};
+
 /* Device ioctls: */
 #define FUSE_DEV_IOC_MAGIC		229
 #define FUSE_DEV_IOC_CLONE		_IOR(FUSE_DEV_IOC_MAGIC, 0, uint32_t)
@@ -1213,6 +1218,8 @@ struct fuse_iomap_support {
 					     struct fuse_iomap_support)
 #define FUSE_DEV_IOC_SET_NOFS		_IOW(FUSE_DEV_IOC_MAGIC, 100, uint32_t)
 #define FUSE_DEV_IOC_ADD_IOMAP		_IO(FUSE_DEV_IOC_MAGIC, 101)
+#define FUSE_DEV_IOC_IOMAP_SET_BLOCKSIZE _IOW(FUSE_DEV_IOC_MAGIC, 102, \
+					      struct fuse_iomap_backing_info)
 
 struct fuse_lseek_in {
 	uint64_t	fh;
fs/fuse/dev.c +2 -0
index f4ca408653cf61..60327b5609fe74 100644
@@ -2789,6 +2789,8 @@ static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
 		return fuse_dev_ioctl_iomap_set_nofs(file, argp);
 	case FUSE_DEV_IOC_ADD_IOMAP:
 		return fuse_dev_ioctl_add_iomap(file);
+	case FUSE_DEV_IOC_IOMAP_SET_BLOCKSIZE:
+		return fuse_dev_ioctl_iomap_set_blocksize(file, argp);
 
 	default:
 		return -ENOTTY;
fs/fuse/fuse_iomap.c +27 -0
index ca37eb93d71a43..7bc938cd859fae 100644
@@ -2935,3 +2935,30 @@ int fuse_iomap_inval_mappings(struct fuse_conn *fc,
 	up_read(&fc->killsb);
 	return ret;
 }
+
+int fuse_dev_ioctl_iomap_set_blocksize(struct file *file,
+				struct fuse_iomap_backing_info __user *argp)
+{
+	struct fuse_iomap_backing_info fbi;
+	struct fuse_dev *fud = fuse_get_dev(file);
+	struct fuse_backing *fb;
+	int ret;
+
+	if (IS_ERR(fud))
+		return PTR_ERR(fud);
+
+	if (!fud->fc->iomap)
+		return -EOPNOTSUPP;
+
+	if (copy_from_user(&fbi, argp, sizeof(fbi)))
+		return -EFAULT;
+
+	fb = fuse_backing_lookup(fud->fc, &fuse_iomap_backing_ops,
+				 fbi.backing_id);
+	if (!fb)
+		return -ENOENT;
+
+	ret = set_blocksize(fb->file, fbi.blocksize);
+	fuse_backing_put(fb);
+	return ret;
+}
#101 lore raw

RFC PATCH 9/9 fuse: allow fuse servers to upload iomap BPF programs

In reply to Darrick J. Wong

Hi all,

There are certain fuse servers that might benefit from the ability to upload a BPF program into the kernel to respond to ->iomap_begin requests instead of upcalling the fuse server itself.

For example, consider a fuse server that abstracts a large amount of storage for use as intermediate storage by programs. If the storage is striped across hardware devices (e.g. RAID0 or interleaved memory controllers) then the iomapping pattern will be completely regular but the mappings themselves might be very small.

Performance for large IOs will suck if it is necessary to upcall the fuse server every time we cross a mapping boundary. The fuse server can try to mitigate that hit by upserting mappings ahead of time, but there's a better solution for this usecase: BPF programs.

In this case, the fuse server can compile a BPF program that will compute the mapping data for a given request and upload the program. This avoids the overhead of cache lookups and server upcalls. Note that the BPF verifier still imposes instruction count and complexity limits on the uploaded programs.

Note that I embraced and extended some code from Joanne, but at this point I've modified it so heavily that it's not really the original anymore. But she still gets credit for coming up with the idea and engaging me in flinging prototypes around.

Now with kfuncs to manage the cache, and some ability to restrict memory access from within the BPF program.

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

With a bit of luck, this should all go splendidly. 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-bpf
---
Commits in this patchset:
* fuse: enable fuse servers to upload BPF programs to handle iomap requests
* fuse_trace: enable fuse servers to upload BPF programs to handle iomap requests
* fuse: prevent iomap bpf programs from writing to most of the system
* fuse: add kfuncs for iomap bpf programs to manage the cache
* fuse: make fuse_inode opaque to iomap bpf programs

---
 fs/fuse/fuse_i.h         |    5 
 fs/fuse/fuse_iomap_bpf.h |  123 ++++++++++++
 fs/fuse/fuse_iomap_i.h   |    6 +
 fs/fuse/fuse_trace.h     |   53 +++++
 fs/fuse/Makefile         |    4 
 fs/fuse/fuse_iomap.c     |   17 +-
 fs/fuse/fuse_iomap_bpf.c |  464 ++++++++++++++++++++++++++++++++++++++++++++++
 fs/fuse/inode.c          |    7 +
 fs/fuse/trace.c          |    1 
 kernel/bpf/btf.c         |    1 
 10 files changed, 676 insertions(+), 5 deletions(-)
 create mode 100644 fs/fuse/fuse_iomap_bpf.h
 create mode 100644 fs/fuse/fuse_iomap_bpf.c