Skip to contentSkip to conversation

fuse: add io-uring buffer pools and zero-copy

PATCH Superseded Joanne Koong 3 participants 37 messages Jul 16 – Aug 14

Subsystems (4)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Joanne Koong

author maintainer
#0 lore raw

v6 cover fuse: add io-uring buffer pools and zero-copy

This series adds fuse io-uring buffer pools and zero-copy.

Prior to this series, ents and buffers are tightly coupled where each entry has its own dedicated payload buffer, requiring N buffers for N entries where each buffer must be large enough to accomodate the maximum payload size. This is suboptimal as most request types require vastly less bytes than the maximum payload size and some requests do not require payload buffers at all.

This series allows servers to pass in a buffer pool (a contiguous chunk of memory) that the kernel will use as it wishes for servicing ents/requests. This decoupling reduces the memory usage requirements needed to use fuse-io-uring and lets the kernel do any optimizations for assigning payload memory to requests.

This series additionally adds zero copy to fuse io-uring. The server can directly access client pages or page cache folios without copying data through an intermediary buffer. This requires CAP_SYS_ADMIN privileges and using buffer pools. The zero copy patch has a dependency on io-uring registered bvec changes in [1].

This series is on top of commit 7d87a5a284bb and on top of the io-uring bvec changes and the changes from the series in [2] applied.

The throughput improvements from registered buffers and zero-copy depends on how much of the server's per-request latency is spent on data copying vs backing I/O. When backing I/O dominates, the saved memcpy is a negligible fraction of overall latency. Please also note that for the server to read/write into the zero-copied pages, the read/write must go through io-uring as an IORING_OP_READ_FIXED / IORING_OP_WRITE_FIXED operation.

The throughput improvement from zero-copy depends on how much of the per-request latency is spent on data copying vs backing I/O. The gain comes from eliminating the payload-buffer memcpy, but accessing the zero-copied pages requires the server to issue the read/write as an IORING_OP_READ/WRITE_FIXED operation. The benefit is largest when the mempcy is a meaningful fraction of per-request latency while backing i/o is still noticable enough that the extra io-uring op's overhead doesn't dominate.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

baseline registered-buf zero-copy (zc vs base)

direct read     ~5.1 GB/s  ~5.4 GB/s        ~8.9 GB/s   (+75%)
direct write    ~3.4 GB/s  ~4.8 GB/s        ~5.1 GB/s   (+50%)

On a device-bound NVMe (~2 GB/s reads) the read gain shrinks to ~10-16% (no measurable gains for writes), as backing I/O rather than the eliminated copy dominates latency. The benefit overall scales with how much of the per-request latency is the data copy versus backing I/O.

The benchmark script and results can be found in [3]. The libfuse changes can be found in [4]. To test the server, run:
sudo ~/libfuse/build/example/passthrough_hp ~/src ~/mounts/tmp --nopassthrough -o io_uring_zero_copy -o io_uring_q_depth=8
Once this series is merged, the libfuse changes will be tidied up and submitted upstream.

Thanks,
Joanne

[1] https://lore.kernel.org/io-uring/[email protected]/T/#t
[2] https://lore.kernel.org/fuse-devel/[email protected]/
[3] https://github.com/joannekoong/linux/commits/fuse_zero_copy_benchmarks/
[4] https://github.com/joannekoong/libfuse/commits/zero_copy_v5

Changelog
---------
v5: https://lore.kernel.org/fuse-devel/[email protected]/
v5 -> v6:
* Remove WARN_ON tag, add missing barrier (Sashiko)
* Bring back some documentation from v4, rename uapi doc (Amir)

v4: https://lore.kernel.org/fuse-devel/[email protected]/
v4 -> v5:
* Address Miklos's feedback (separate uring cmd for adding bufpool, pass only bufpool addr and len, pass back bufpool offset instead of buf id, etc)
* Make zero-copy opt-in on file open
* Do any zeroing for short zero-copy reads instead of accidentally skipping that
* Drop Baokun and Jeff's reviewed-bys since the commits had modifications
* Run more rigorous benchmarks, on bare-metal machine

v3: https://lore.kernel.org/fuse-devel/[email protected]/
v3 -> v4:
* Add reviewed-bys
* Fix documentation typo, add paragraph about aborts to zero-copy commit message, undo unnecessary padding[6] change, add FUSE_HAS_URING_BUFPOOL advertisement

v2: https://lore.kernel.org/linux-fsdevel/[email protected]/
v2 -> v3:
* Rework the uapis to be more ergonomic. Use io-uring registered buffers infrastructure instead of doing pinning logic in fuse. Get rid of header pinning as that makes no real perf difference
* Rename from "buffer ring" to buffer pool. Logic is the same, just different naming

v1: https://lore.kernel.org/linux-fsdevel/[email protected]/
v1 -> v2:
* Drop kernel managed buffers from io-uring infrastructure and move it to fuse
* Add visual diagrams and more documentatoin to commit messages and documentation patch

Joanne Koong (6):
fuse: decouple fuse_ring creation from ent registration
fuse: add FUSE_IO_URING_CMD_ADD_QUEUE
fuse: add io-uring buffer pools
fuse: support registered buffer pools in io-uring
fuse: add zero-copy over io-uring
docs: fuse: document io-uring buffer pool and zero-copy uapi

 .../filesystems/fuse/fuse-io-uring.rst        |  36 +-
 Documentation/filesystems/fuse/index.rst      |   1 +
 .../fuse/uapi/fuse-uapi-io-uring.rst          | 129 ++++
 fs/fuse/args.h                                |   2 +
 fs/fuse/dev.c                                 |  27 +-
 fs/fuse/dev.h                                 |   2 +-
 fs/fuse/dev_uring.c                           | 577 +++++++++++++++---
 fs/fuse/dev_uring_i.h                         |  56 +-
 fs/fuse/file.c                                |   2 +
 fs/fuse/fuse_dev_i.h                          |   1 +
 fs/fuse/inode.c                               |   6 +-
 include/uapi/linux/fuse.h                     |  66 +-
 12 files changed, 821 insertions(+), 84 deletions(-)
 create mode 100644 Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst
Signature · 1 line
2.52.0
author maintainer
#1 lore raw

PATCH v6 1/6 fuse: decouple fuse_ring creation from ent registration

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

---
 fs/fuse/dev.c         |  8 +++-----
 fs/fuse/dev.h         |  2 +-
 fs/fuse/dev_uring.c   | 26 ++++++++++----------------
 fs/fuse/dev_uring_i.h |  5 +++++
 fs/fuse/inode.c       |  4 +++-
 5 files changed, 22 insertions(+), 23 deletions(-)
fs/fuse/dev.c +3 -5
index 8b68b24af9d7..d50792162d8b 100644
@@ -75,6 +75,9 @@ void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *pa
 		fch->minor = param->minor;
 		fch->max_write = param->max_write;
 		fch->max_pages = param->max_pages;
+
+		if (param->io_uring_enabled)
+			fuse_uring_conn_init(fch);
 	}
 
 	/* Pairs with smp_load_acquire() readers of fch->initialized */
@@ -411,11 +414,6 @@ void fuse_chan_set_fc(struct fuse_chan *fch, struct fuse_conn *fc)
 	fch->conn = fc;
 }
 
-void fuse_chan_io_uring_enable(struct fuse_chan *fch)
-{
-	fch->io_uring = 1;
-}
-
 void fuse_pqueue_init(struct fuse_pqueue *fpq)
 {
 	spin_lock_init(&fpq->lock);
fs/fuse/dev.h +1 -1
index aed69fd14c41..8d25378c0918 100644
@@ -22,6 +22,7 @@ struct fuse_chan_param {
 	unsigned int minor;
 	unsigned int max_write;
 	unsigned int max_pages;
+	bool io_uring_enabled;
 };
 
 struct fuse_chan *fuse_chan_new(void);
@@ -34,7 +35,6 @@ void fuse_chan_max_background_set(struct fuse_chan *fch, unsigned int val);
 unsigned int fuse_chan_num_waiting(struct fuse_chan *fch);
 void fuse_chan_set_fc(struct fuse_chan *fch, struct fuse_conn *fc);
 void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *param);
-void fuse_chan_io_uring_enable(struct fuse_chan *fch);
 ssize_t fuse_chan_send(struct fuse_chan *fch, struct fuse_args *args);
 int fuse_chan_send_bg(struct fuse_chan *fch, struct fuse_args *args, gfp_t gfp_flags);
 int fuse_chan_send_notify_reply(struct fuse_chan *fch, struct fuse_args *args, u64 unique);
fs/fuse/dev_uring.c +10 -16
index bf9d51f2a508..b7c6100c4176 100644
@@ -238,7 +238,6 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 {
 	struct fuse_ring *ring;
 	size_t nr_queues = num_possible_cpus();
-	struct fuse_ring *res = NULL;
 	size_t max_payload_size;
 
 	ring = kzalloc_obj(*ring, GFP_KERNEL_ACCOUNT);
@@ -258,12 +257,6 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 		spin_unlock(&fch->lock);
 		goto out_err;
 	}
-	if (fch->ring) {
-		/* race, another thread created the ring in the meantime */
-		spin_unlock(&fch->lock);
-		res = fch->ring;
-		goto out_err;
-	}
 
 	init_waitqueue_head(&ring->stop_waitq);
 
@@ -278,7 +271,13 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 out_err:
 	kfree(ring->queues);
 	kfree(ring);
-	return res;
+	return NULL;
+}
+
+void fuse_uring_conn_init(struct fuse_chan *fch)
+{
+	if (fuse_uring_create(fch))
+		fch->io_uring = 1;
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
@@ -1178,15 +1177,10 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
 	struct fuse_ring_queue *queue;
 	struct fuse_ring_ent *ent;
-	int err;
 	unsigned int qid = READ_ONCE(cmd_req->qid);
 
-	err = -ENOMEM;
-	if (!ring) {
-		ring = fuse_uring_create(fch);
-		if (!ring)
-			return err;
-	}
+	if (!ring)
+		return -EINVAL;
 
 	if (qid >= ring->nr_queues) {
 		pr_info_ratelimited("fuse: Invalid ring qid %u\n", qid);
@@ -1197,7 +1191,7 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	if (!queue) {
 		queue = fuse_uring_create_queue(ring, qid);
 		if (!queue)
-			return err;
+			return -ENOMEM;
 	}
 
 	/*
fs/fuse/dev_uring_i.h +5 -0
index 55f8d04e4b0b..d721a4fc0215 100644
@@ -135,6 +135,7 @@ struct fuse_ring {
 	bool ready;
 };
 
+void fuse_uring_conn_init(struct fuse_chan *fch);
 void fuse_uring_stop_queues(struct fuse_ring *ring);
 void fuse_uring_abort_end_requests(struct fuse_ring *ring);
 int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags);
@@ -174,6 +175,10 @@ static inline bool fuse_uring_ready(struct fuse_chan *fch)
 
 #else /* CONFIG_FUSE_IO_URING */
 
+static inline void fuse_uring_conn_init(struct fuse_chan *fch)
+{
+}
+
 static inline void fuse_uring_abort(struct fuse_chan *fch)
 {
 }
fs/fuse/inode.c +3 -1
index d975073c6029..ce4891a04a37 100644
@@ -1272,6 +1272,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 	struct fuse_mount *fm = ia->fm;
 	struct fuse_conn *fc = fm->fc;
 	struct fuse_init_out *arg = &ia->out;
+	bool io_uring_enabled = false;
 	bool ok = true;
 
 	if (error || arg->major != FUSE_KERNEL_VERSION)
@@ -1402,7 +1403,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 					ok = false;
 			}
 			if (flags & FUSE_OVER_IO_URING && fuse_uring_enabled())
-				fuse_chan_io_uring_enable(fc->chan);
+				io_uring_enabled = true;
 
 			if (flags & FUSE_REQUEST_TIMEOUT)
 				timeout = arg->request_timeout;
@@ -1432,6 +1433,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 			.minor = fc->minor,
 			.max_write = fc->max_write,
 			.max_pages = fc->max_pages,
+			.io_uring_enabled = io_uring_enabled,
 		};
 		fuse_chan_set_initialized(fc->chan, &cp);
 	}
Signature · 1 line
2.52.0
maintainer
#2 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 8 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Quoted 5 lines

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

What about if the fuse ring is not yet set up? Should fuse_uring_register() wait in that case?

Thanks,
Miklos

author maintainer
#3 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 10 lines · Miklos Szeredi
Quoted 8 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Quoted 8 lines
Quoted 5 lines

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

What about if the fuse ring is not yet set up? Should fuse_uring_register() wait in that case?

The fuse ring is set up when the kernel processes the FUSE_INIT reply. If userspace races ahead and issues a REGISTER before the FUSE_INIT reply is processed, they get back -EAGAIN and will need to retry, which is the same as the pre-existing behavior. The ring gets published before fch->initialized gets set.

Not sure if this answers your question or if I'm misreading what you're asking.

Thanks,
Joanne

Quoted 3 lines

Thanks,
Miklos

maintainer
#4 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 21 lines · Joanne Koong
Quoted 10 lines · Miklos Szeredi
Quoted 8 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Quoted 8 lines
Quoted 5 lines

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

What about if the fuse ring is not yet set up? Should fuse_uring_register() wait in that case?

Quoted 7 lines

The fuse ring is set up when the kernel processes the FUSE_INIT reply. If userspace races ahead and issues a REGISTER before the FUSE_INIT reply is processed, they get back -EAGAIN and will need to retry, which is the same as the pre-existing behavior. The ring gets published before fch->initialized gets set.

Not sure if this answers your question or if I'm misreading what you're asking.

That was my question, yes.

Retrying in a loop doesn't sound like good behavior.

I was thinking that with sync INIT the completing the write() with the INIT reply does not mean that the connection gets initialized.

Shouldn't the REGISTER op block until initialization is complete?

Thanks,
Miklos

author maintainer
#5 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 31 lines · Miklos Szeredi
Quoted 21 lines · Joanne Koong
Quoted 10 lines · Miklos Szeredi
Quoted 8 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Quoted 8 lines
Quoted 5 lines

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

What about if the fuse ring is not yet set up? Should fuse_uring_register() wait in that case?

Quoted 7 lines

The fuse ring is set up when the kernel processes the FUSE_INIT reply. If userspace races ahead and issues a REGISTER before the FUSE_INIT reply is processed, they get back -EAGAIN and will need to retry, which is the same as the pre-existing behavior. The ring gets published before fch->initialized gets set.

Not sure if this answers your question or if I'm misreading what you're asking.

Quoted 8 lines

That was my question, yes.

Retrying in a loop doesn't sound like good behavior.

I was thinking that with sync INIT the completing the write() with the INIT reply does not mean that the connection gets initialized.

Shouldn't the REGISTER op block until initialization is complete?

Yes, this would be more ideal for the sync case. libfuse currently works around this with the retry loop.

This is a pre-existing issue that's not introduced by this series though, so I'll send a patch out for this separately.

Thanks,
Joanne

author maintainer
#6 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 40 lines · Joanne Koong
Quoted 38 lines · Miklos Szeredi
Quoted 21 lines · Joanne Koong
Quoted 10 lines · Miklos Szeredi
Quoted 8 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Quoted 8 lines
Quoted 5 lines

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

What about if the fuse ring is not yet set up? Should fuse_uring_register() wait in that case?

Quoted 7 lines

The fuse ring is set up when the kernel processes the FUSE_INIT reply. If userspace races ahead and issues a REGISTER before the FUSE_INIT reply is processed, they get back -EAGAIN and will need to retry, which is the same as the pre-existing behavior. The ring gets published before fch->initialized gets set.

Not sure if this answers your question or if I'm misreading what you're asking.

That was my question, yes.

Retrying in a loop doesn't sound like good behavior.

I was thinking that with sync INIT the completing the write() with the INIT reply does not mean that the connection gets initialized.

Quoted 7 lines
Quoted 1 line

Shouldn't the REGISTER op block until initialization is complete?

Yes, this would be more ideal for the sync case. libfuse currently works around this with the retry loop.

This is a pre-existing issue that's not introduced by this series though, so I'll send a patch out for this separately.

We can fix up libfuse [1] to no longer send REGISTER before the connection is initialized, so I don't think a kernel fix is strictly needed here, but if you still prefer kernel code to coordinate this, I can send that out.

Thanks,
Joanne

[1] https://github.com/libfuse/libfuse/pull/1561

maintainer
#7 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 4 lines · Joanne Koong

We can fix up libfuse [1] to no longer send REGISTER before the connection is initialized, so I don't think a kernel fix is strictly needed here, but if you still prefer kernel code to coordinate this, I can send that out.

With async INIT this is possible by waiting until the write(2) syscall for the INIT reply returns. This is because the initialization is performed within the context of the write call.

For sync INIT the initialization is performed in the context of the mount/FSCONFIG_CMD_CREATE, libfuse can wait until the respective syscall returns.

So yes, it's possible to ensure this from userspace, no kernel change is need.

Thanks,
Miklos

maintainer
#8 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

Quoted 11 lines · Miklos Szeredi
Quoted 4 lines · Joanne Koong

We can fix up libfuse [1] to no longer send REGISTER before the connection is initialized, so I don't think a kernel fix is strictly needed here, but if you still prefer kernel code to coordinate this, I can send that out.

With async INIT this is possible by waiting until the write(2) syscall for the INIT reply returns. This is because the initialization is performed within the context of the write call.

Quoted 5 lines

For sync INIT the initialization is performed in the context of the mount/FSCONFIG_CMD_CREATE, libfuse can wait until the respective syscall returns.

So yes, it's possible to ensure this from userspace, no kernel change is need.

The patch here from Joanne needs a slight update:
https://github.com/libfuse/libfuse/pull/1561

I can amend myself next week (once I'm through with review here).

As I wrote there, I had run last into -EAGAIN last year and had added an -EAGAIN handler. Pity that I didn't record in the commit message the exact reason :/

Thanks,
Bernd

maintainer Reviewed-by on v6 1/6
#9 lore raw

Re: [PATCH v6 1/6] fuse: decouple fuse_ring creation from ent registration

In reply to Joanne Koong
Quoted 180 lines · Joanne Koong

Currently, the connection's fuse_ring is created lazily on the first FUSE_IO_URING_CMD_REGISTER command. A server registers entries from one thread per queue (one per CPU) and those threads issue their first REGISTER command concurrently. They then race to create the single per-connection fuse_ring, which required open-coded handling in fuse_uring_create() to detect and protect against concurrent creations.

Decouple fuse_ring creation from ent registration and move it to FUSE_INIT reply processing after a server has negotiated and set FUSE_OVER_IO_URING. The ring is published before the connection is marked initialized. fuse_uring_register() no longer creates the ring and it instead uses the ring set up at init time.

---
 fs/fuse/dev.c         |  8 +++-----
 fs/fuse/dev.h         |  2 +-
 fs/fuse/dev_uring.c   | 26 ++++++++++----------------
 fs/fuse/dev_uring_i.h |  5 +++++
 fs/fuse/inode.c       |  4 +++-
 5 files changed, 22 insertions(+), 23 deletions(-)
fs/fuse/dev.c +3 -5
index 8b68b24af9d7..d50792162d8b 100644
@@ -75,6 +75,9 @@ void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *pa
 		fch->minor = param->minor;
 		fch->max_write = param->max_write;
 		fch->max_pages = param->max_pages;
+
+		if (param->io_uring_enabled)
+			fuse_uring_conn_init(fch);
 	}
 
 	/* Pairs with smp_load_acquire() readers of fch->initialized */
@@ -411,11 +414,6 @@ void fuse_chan_set_fc(struct fuse_chan *fch, struct fuse_conn *fc)
 	fch->conn = fc;
 }
 
-void fuse_chan_io_uring_enable(struct fuse_chan *fch)
-{
-	fch->io_uring = 1;
-}
-
 void fuse_pqueue_init(struct fuse_pqueue *fpq)
 {
 	spin_lock_init(&fpq->lock);
fs/fuse/dev.h +1 -1
index aed69fd14c41..8d25378c0918 100644
@@ -22,6 +22,7 @@ struct fuse_chan_param {
 	unsigned int minor;
 	unsigned int max_write;
 	unsigned int max_pages;
+	bool io_uring_enabled;
 };
 
 struct fuse_chan *fuse_chan_new(void);
@@ -34,7 +35,6 @@ void fuse_chan_max_background_set(struct fuse_chan *fch, unsigned int val);
 unsigned int fuse_chan_num_waiting(struct fuse_chan *fch);
 void fuse_chan_set_fc(struct fuse_chan *fch, struct fuse_conn *fc);
 void fuse_chan_set_initialized(struct fuse_chan *fch, struct fuse_chan_param *param);
-void fuse_chan_io_uring_enable(struct fuse_chan *fch);
 ssize_t fuse_chan_send(struct fuse_chan *fch, struct fuse_args *args);
 int fuse_chan_send_bg(struct fuse_chan *fch, struct fuse_args *args, gfp_t gfp_flags);
 int fuse_chan_send_notify_reply(struct fuse_chan *fch, struct fuse_args *args, u64 unique);
fs/fuse/dev_uring.c +10 -16
index bf9d51f2a508..b7c6100c4176 100644
@@ -238,7 +238,6 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 {
 	struct fuse_ring *ring;
 	size_t nr_queues = num_possible_cpus();
-	struct fuse_ring *res = NULL;
 	size_t max_payload_size;
 
 	ring = kzalloc_obj(*ring, GFP_KERNEL_ACCOUNT);
@@ -258,12 +257,6 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 		spin_unlock(&fch->lock);
 		goto out_err;
 	}
-	if (fch->ring) {
-		/* race, another thread created the ring in the meantime */
-		spin_unlock(&fch->lock);
-		res = fch->ring;
-		goto out_err;
-	}
 
 	init_waitqueue_head(&ring->stop_waitq);
 
@@ -278,7 +271,13 @@ static struct fuse_ring *fuse_uring_create(struct fuse_chan *fch)
 out_err:
 	kfree(ring->queues);
 	kfree(ring);
-	return res;
+	return NULL;
+}
+
+void fuse_uring_conn_init(struct fuse_chan *fch)
+{
+	if (fuse_uring_create(fch))
+		fch->io_uring = 1;
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
@@ -1178,15 +1177,10 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
 	struct fuse_ring_queue *queue;
 	struct fuse_ring_ent *ent;
-	int err;
 	unsigned int qid = READ_ONCE(cmd_req->qid);
 
-	err = -ENOMEM;
-	if (!ring) {
-		ring = fuse_uring_create(fch);
-		if (!ring)
-			return err;
-	}
+	if (!ring)
+		return -EINVAL;
 
 	if (qid >= ring->nr_queues) {
 		pr_info_ratelimited("fuse: Invalid ring qid %u\n", qid);
@@ -1197,7 +1191,7 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	if (!queue) {
 		queue = fuse_uring_create_queue(ring, qid);
 		if (!queue)
-			return err;
+			return -ENOMEM;
 	}
 
 	/*
fs/fuse/dev_uring_i.h +5 -0
index 55f8d04e4b0b..d721a4fc0215 100644
@@ -135,6 +135,7 @@ struct fuse_ring {
 	bool ready;
 };
 
+void fuse_uring_conn_init(struct fuse_chan *fch);
 void fuse_uring_stop_queues(struct fuse_ring *ring);
 void fuse_uring_abort_end_requests(struct fuse_ring *ring);
 int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags);
@@ -174,6 +175,10 @@ static inline bool fuse_uring_ready(struct fuse_chan *fch)
 
 #else /* CONFIG_FUSE_IO_URING */
 
+static inline void fuse_uring_conn_init(struct fuse_chan *fch)
+{
+}
+
 static inline void fuse_uring_abort(struct fuse_chan *fch)
 {
 }
fs/fuse/inode.c +2 -1
index d975073c6029..ce4891a04a37 100644
@@ -1272,6 +1272,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 	struct fuse_mount *fm = ia->fm;
 	struct fuse_conn *fc = fm->fc;
 	struct fuse_init_out *arg = &ia->out;
+	bool io_uring_enabled = false;
 	bool ok = true;
 
 	if (error || arg->major != FUSE_KERNEL_VERSION)
@@ -1402,7 +1403,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 					ok = false;
 			}
 			if (flags & FUSE_OVER_IO_URING && fuse_uring_enabled())
-				fuse_chan_io_uring_enable(fc->chan);
+				io_uring_enabled = true;
 
 			if (flags & FUSE_REQUEST_TIMEOUT)
 				timeout = arg->request_timeout;

fs/fuse/inode.c static void process_init_reply(struct fuse_args *args, int error) · line 1439

Quoted 7 lines
fs/fuse/inode.c +1 -0
@@ -1432,6 +1433,7 @@ static void process_init_reply(struct fuse_args *args, int error)
 			.minor = fc->minor,
 			.max_write = fc->max_write,
 			.max_pages = fc->max_pages,
+			.io_uring_enabled = io_uring_enabled,
 		};
 		fuse_chan_set_initialized(fc->chan, &cp);
 	}

Thanks, I should have done that from the beginning!

author maintainer
#10 lore raw

PATCH v6 2/6 fuse: add FUSE_IO_URING_CMD_ADD_QUEUE

In reply to Joanne Koong

fuse-over-io-uring queues are currently created lazily, as a side effect of the first FUSE_IO_URING_CMD_REGISTER command for a given qid. This ties queue creation to entry registration.

Add a FUSE_IO_URING_CMD_ADD_QUEUE command so a server can create a queue explicitly, decoupling queue setup from entry registration. This is additionally a prerequisite for FUSE_IO_URING_CMD_ADD_BUFPOOL, which attaches a buffer pool to an existing queue and therefore needs the queue to have been created first.

---
 fs/fuse/dev_uring.c       | 45 +++++++++++++++++++++++++++++++++------
 include/uapi/linux/fuse.h |  8 ++++++-
 2 files changed, 45 insertions(+), 8 deletions(-)
fs/fuse/dev_uring.c +38 -7
index b7c6100c4176..fdf1058e582c 100644
@@ -281,7 +281,8 @@ void fuse_uring_conn_init(struct fuse_chan *fch)
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
-						       int qid)
+						       int qid,
+						       bool fail_if_exists)
 {
 	struct fuse_chan *fch = ring->chan;
 	struct fuse_ring_queue *queue;
@@ -289,11 +290,11 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 
 	queue = kzalloc_obj(*queue, GFP_KERNEL_ACCOUNT);
 	if (!queue)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	pq = fuse_pqueue_alloc();
 	if (!pq) {
 		kfree(queue);
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	}
 
 	queue->qid = qid;
@@ -316,7 +317,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 		spin_unlock(&fch->lock);
 		kfree(queue->fpq.processing);
 		kfree(queue);
-		return ring->queues[qid];
+		return fail_if_exists ? ERR_PTR(-EEXIST) : ring->queues[qid];
 	}
 
 	/*
@@ -1189,9 +1190,9 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 
 	queue = READ_ONCE(ring->queues[qid]);
 	if (!queue) {
-		queue = fuse_uring_create_queue(ring, qid);
-		if (!queue)
-			return -ENOMEM;
+		queue = fuse_uring_create_queue(ring, qid, false);
+		if (IS_ERR(queue))
+			return PTR_ERR(queue);
 	}
 
 	/*
@@ -1206,6 +1207,30 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	return fuse_uring_do_register(ent, cmd, issue_flags);
 }
 
+static int fuse_uring_add_queue(struct io_uring_cmd *cmd, struct fuse_chan *fch)
+{
+	const struct fuse_uring_cmd_req *cmd_req =
+		io_uring_sqe128_cmd(cmd->sqe, struct fuse_uring_cmd_req);
+	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
+	unsigned int qid = READ_ONCE(cmd_req->qid);
+	uint64_t flags = READ_ONCE(cmd_req->flags);
+	struct fuse_ring_queue *queue;
+
+	if (!ring || flags)
+		return -EINVAL;
+
+	if (qid >= ring->nr_queues) {
+		pr_info_ratelimited("fuse: Invalid ring qid %u\n", qid);
+		return -EINVAL;
+	}
+
+	queue = fuse_uring_create_queue(ring, qid, true);
+	if (IS_ERR(queue))
+		return PTR_ERR(queue);
+
+	return 0;
+}
+
 /*
  * Entry function from io_uring to handle the given passthrough command
  * (op code IORING_OP_URING_CMD)
@@ -1272,6 +1297,12 @@ int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
 			return err;
 		}
 		break;
+	case FUSE_IO_URING_CMD_ADD_QUEUE:
+		err = fuse_uring_add_queue(cmd, fch);
+		if (err)
+			pr_info_once("FUSE_IO_URING_CMD_ADD_QUEUE failed err=%d\n",
+				     err);
+		return err;
 	default:
 		return -EINVAL;
 	}
include/uapi/linux/fuse.h +7 -1
index c13e1f9a2f12..cfb055c0c764 100644
@@ -240,6 +240,9 @@
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.46
+ *  - add FUSE_IO_URING_CMD_ADD_QUEUE
  */
 
 #ifndef _LINUX_FUSE_H
@@ -275,7 +278,7 @@
 #define FUSE_KERNEL_VERSION 7
 
 /** Minor version number of this interface */
-#define FUSE_KERNEL_MINOR_VERSION 45
+#define FUSE_KERNEL_MINOR_VERSION 46
 
 /** The node ID of the root inode */
 #define FUSE_ROOT_ID 1
@@ -1292,6 +1295,9 @@ enum fuse_uring_cmd {
 
 	/* commit fuse request result and fetch next request */
 	FUSE_IO_URING_CMD_COMMIT_AND_FETCH = 2,
+
+	/* add a queue */
+	FUSE_IO_URING_CMD_ADD_QUEUE = 3,
 };
 
 /**
Signature · 1 line
2.52.0
maintainer Reviewed-by on v6 2/6
#11 lore raw

Re: [PATCH v6 2/6] fuse: add FUSE_IO_URING_CMD_ADD_QUEUE

Quoted 134 lines · Joanne Koong

fuse-over-io-uring queues are currently created lazily, as a side effect of the first FUSE_IO_URING_CMD_REGISTER command for a given qid. This ties queue creation to entry registration.

Add a FUSE_IO_URING_CMD_ADD_QUEUE command so a server can create a queue explicitly, decoupling queue setup from entry registration. This is additionally a prerequisite for FUSE_IO_URING_CMD_ADD_BUFPOOL, which attaches a buffer pool to an existing queue and therefore needs the queue to have been created first.

---
 fs/fuse/dev_uring.c       | 45 +++++++++++++++++++++++++++++++++------
 include/uapi/linux/fuse.h |  8 ++++++-
 2 files changed, 45 insertions(+), 8 deletions(-)
fs/fuse/dev_uring.c +38 -7
index b7c6100c4176..fdf1058e582c 100644
@@ -281,7 +281,8 @@ void fuse_uring_conn_init(struct fuse_chan *fch)
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
-						       int qid)
+						       int qid,
+						       bool fail_if_exists)
 {
 	struct fuse_chan *fch = ring->chan;
 	struct fuse_ring_queue *queue;
@@ -289,11 +290,11 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 
 	queue = kzalloc_obj(*queue, GFP_KERNEL_ACCOUNT);
 	if (!queue)
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	pq = fuse_pqueue_alloc();
 	if (!pq) {
 		kfree(queue);
-		return NULL;
+		return ERR_PTR(-ENOMEM);
 	}
 
 	queue->qid = qid;
@@ -316,7 +317,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 		spin_unlock(&fch->lock);
 		kfree(queue->fpq.processing);
 		kfree(queue);
-		return ring->queues[qid];
+		return fail_if_exists ? ERR_PTR(-EEXIST) : ring->queues[qid];
 	}
 
 	/*
@@ -1189,9 +1190,9 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 
 	queue = READ_ONCE(ring->queues[qid]);
 	if (!queue) {
-		queue = fuse_uring_create_queue(ring, qid);
-		if (!queue)
-			return -ENOMEM;
+		queue = fuse_uring_create_queue(ring, qid, false);
+		if (IS_ERR(queue))
+			return PTR_ERR(queue);
 	}
 
 	/*
@@ -1206,6 +1207,30 @@ static int fuse_uring_register(struct io_uring_cmd *cmd,
 	return fuse_uring_do_register(ent, cmd, issue_flags);
 }
 
+static int fuse_uring_add_queue(struct io_uring_cmd *cmd, struct fuse_chan *fch)
+{
+	const struct fuse_uring_cmd_req *cmd_req =
+		io_uring_sqe128_cmd(cmd->sqe, struct fuse_uring_cmd_req);
+	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
+	unsigned int qid = READ_ONCE(cmd_req->qid);
+	uint64_t flags = READ_ONCE(cmd_req->flags);
+	struct fuse_ring_queue *queue;
+
+	if (!ring || flags)
+		return -EINVAL;
+
+	if (qid >= ring->nr_queues) {
+		pr_info_ratelimited("fuse: Invalid ring qid %u\n", qid);
+		return -EINVAL;
+	}
+
+	queue = fuse_uring_create_queue(ring, qid, true);
+	if (IS_ERR(queue))
+		return PTR_ERR(queue);
+
+	return 0;
+}
+
 /*
  * Entry function from io_uring to handle the given passthrough command
  * (op code IORING_OP_URING_CMD)
@@ -1272,6 +1297,12 @@ int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
 			return err;
 		}
 		break;
+	case FUSE_IO_URING_CMD_ADD_QUEUE:
+		err = fuse_uring_add_queue(cmd, fch);
+		if (err)
+			pr_info_once("FUSE_IO_URING_CMD_ADD_QUEUE failed err=%d\n",
+				     err);
+		return err;
 	default:
 		return -EINVAL;
 	}
include/uapi/linux/fuse.h +4 -1
index c13e1f9a2f12..cfb055c0c764 100644
@@ -240,6 +240,9 @@
  *  - add FUSE_COPY_FILE_RANGE_64
  *  - add struct fuse_copy_file_range_out
  *  - add FUSE_NOTIFY_PRUNE
+ *
+ *  7.46
+ *  - add FUSE_IO_URING_CMD_ADD_QUEUE
  */
 
 #ifndef _LINUX_FUSE_H
@@ -275,7 +278,7 @@
 #define FUSE_KERNEL_VERSION 7
 
 /** Minor version number of this interface */
-#define FUSE_KERNEL_MINOR_VERSION 45
+#define FUSE_KERNEL_MINOR_VERSION 46
 
 /** The node ID of the root inode */
 #define FUSE_ROOT_ID 1

include/uapi/linux/fuse.h enum fuse_uring_cmd { · line 1303

Quoted 9 lines
include/uapi/linux/fuse.h +3 -0
@@ -1292,6 +1295,9 @@ enum fuse_uring_cmd {
 
 	/* commit fuse request result and fetch next request */
 	FUSE_IO_URING_CMD_COMMIT_AND_FETCH = 2,
+
+	/* add a queue */
+	FUSE_IO_URING_CMD_ADD_QUEUE = 3,
 };
 
 /**
author maintainer
#12 lore raw

PATCH v6 3/6 fuse: add io-uring buffer pools

In reply to Joanne Koong

Right now, ents and buffers are tightly coupled in fuse io-uring where each entry has its own dedicated payload buffer, requiring N buffers for N entries where each buffer must be large enough to accomodate the maximum payload size. This is suboptimal as most request types (lookup, open, release, getattr, etc) require vastly less bytes than the maximum payload size and some requests (unlink, rmdir, fsync, flush, etc) do not require payload buffers at all.

Instead of requiring a 1:1 coupling between ents and payload buffers, allow the server to pass in a buffer pool (a contiguous chunk of memory) that the kernel will use as it wishes for servicing ents/requests. Entries only reserve a "buffer" from the pool while actively processing a request that requires a payload buffer. This decoupling and letting the kernel delegate memory from the pool for requests allows the kernel to optimize memory usage and reduces the memory usage requirements needed to use fuse-over-io-uring.

A pool is registered per queue with the new FUSE_IO_URING_CMD_ADD_BUFPOOL command. The server passes the pool's base address and length in fuse_uring_cmd_req.bufpool.{uaddr,len}.

Internally, the kernel splits the region into buffers of ring->max_payload_sz bytes each (nr_bufs = pool len / max_payload_sz). A queue commits to a payload mode on first use: registering an entry that carries its own payload selects the legacy per-entry mode, while ADD_BUFPOOL selects pool mode. The two are mutually exclusive, so ADD_BUFPOOL must be issued before any payload-carrying entries are registered on that queue. The queue must have been created before the bufpool is added, through the FUSE_IO_URING_CMD_ADD_QUEUE command.

The kernel tracks free buffers with a bitmap (a set bit marks a free buffer). On dispatch, a request that needs a payload claims a free buffer (find_first_bit + clear). A request that needs none claims nothing. The buffer's byte offset within the pool is reported to the server in the new fuse_uring_ent_in_out.offset field so that the server can locate the payload. On completion the buffer is returned to the pool or reused directly if the next request on that entry also has a payload.

The FUSE_HAS_IO_URING_BUFPOOL flag advertises kernel support to the server for bufpools.

Buffer pool request flow
~~~~~~~~~~~~~~~~~~~~~~~~

|  Kernel                                  |  FUSE daemon
|                                          |
|  [request arrives]                       |
|    [claim a free pool buffer]            |
|    >fuse_uring_select_buffer()           |
|    [copy headers to ring]                |
|    [copy payload to buffer]              |
|    [report buffer offset in ent_in_out]  |
|    >io_uring_cmd_done()                  |
|                                          |  [read headers]
|                                          |  [read/write payload at offset]
|                                          |  [process request]
|                                          |  >io_uring_submit()
|                                          |   COMMIT_AND_FETCH
|  >fuse_uring_commit_fetch()              |
|    [copy reply from ring]                |
|    [return buffer to the pool]           |
|    >fuse_uring_recycle_buffer()          |
---
 fs/fuse/dev_uring.c       | 237 +++++++++++++++++++++++++++++++++-----
 fs/fuse/dev_uring_i.h     |  37 +++++-
 fs/fuse/inode.c           |   2 +-
 include/uapi/linux/fuse.h |  20 +++-
 4 files changed, 266 insertions(+), 30 deletions(-)
fs/fuse/dev_uring.c +210 -27
index fdf1058e582c..e9da92b46090 100644
@@ -9,6 +9,7 @@
 #include "dev_uring_i.h"
 #include "fuse_trace.h"
 
+#include <linux/bitmap.h>
 #include <linux/fs.h>
 #include <linux/io_uring/cmd.h>
 
@@ -41,6 +42,11 @@ enum fuse_uring_header_type {
 	FUSE_URING_HEADER_RING_ENT,
 };
 
+static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
+{
+	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -222,6 +228,7 @@ void fuse_uring_destruct(struct fuse_chan *fch)
 		}
 
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		ring->queues[qid] = NULL;
 	}
@@ -316,6 +323,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 	if (ring->queues[qid]) {
 		spin_unlock(&fch->lock);
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		return fail_if_exists ? ERR_PTR(-EEXIST) : ring->queues[qid];
 	}
@@ -646,13 +654,14 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 }
 
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
-				 struct fuse_ring *ring, struct fuse_req *req,
+				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
 				 struct iov_iter *iter)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+			  iter);
 	if (err) {
 		pr_info_ratelimited("fuse: Import of user buffer failed\n");
 		return err;
@@ -666,8 +675,7 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 	return 0;
 }
 
-static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
-				     struct fuse_req *req,
+static int fuse_uring_copy_from_ring(struct fuse_req *req,
 				     struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -681,7 +689,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
 	if (err)
 		return err;
 
@@ -693,7 +701,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 /*
  * Copy data from the req to the ring buffer
  */
-static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
+static int fuse_uring_args_to_ring(struct fuse_req *req,
 				   struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -707,7 +715,7 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
 	if (err)
 		return err;
 
@@ -737,6 +745,10 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 	}
 
 	ent_in_out.payload_sz = cs.ring.copied_sz;
+	if (bufpool_enabled(ent->queue) && ent->payload.iov_base)
+		ent_in_out.offset =
+			(uintptr_t)ent->payload.iov_base - ent->queue->bufpool->base_uaddr;
+
 	return copy_header_to_ring(ent, FUSE_URING_HEADER_RING_ENT,
 				   &ent_in_out, sizeof(ent_in_out));
 }
@@ -745,7 +757,6 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
 	struct fuse_ring_queue *queue = ent->queue;
-	struct fuse_ring *ring = queue->ring;
 	int err;
 
 	err = -EIO;
@@ -760,7 +771,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(ring, req, ent);
+	err = fuse_uring_args_to_ring(req, ent);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -771,6 +782,91 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   sizeof(req->in.h));
 }
 
+static bool fuse_uring_req_has_payload(struct fuse_req *req)
+{
+	struct fuse_args *args = req->args;
+
+	return args->in_numargs > 1 || args->out_numargs;
+}
+
+static int fuse_uring_select_buffer(struct fuse_ring_ent *ent)
+{
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool = queue->bufpool;
+	unsigned int id;
+
+	lockdep_assert_held(&queue->lock);
+
+	id = find_first_bit(pool->free_map, pool->nr_bufs);
+	if (id >= pool->nr_bufs)
+		return -ENOBUFS;
+
+	WARN_ON_ONCE(ent->payload.iov_base);
+	__clear_bit(id, pool->free_map);
+
+	ent->buf_id = id;
+	ent->payload.iov_base =
+		(void __user *)(pool->base_uaddr + id * pool->buf_size);
+	ent->payload.iov_len = pool->buf_size;
+
+	return 0;
+}
+
+static void fuse_uring_recycle_buffer(struct fuse_ring_ent *ent)
+{
+	struct iovec *ent_payload = &ent->payload;
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool;
+
+	lockdep_assert_held(&queue->lock);
+
+	if (!bufpool_enabled(queue) || !ent_payload->iov_base)
+		return;
+
+	pool = queue->bufpool;
+
+	/* a buffer should never be recycled twice */
+	WARN_ON_ONCE(test_bit(ent->buf_id, pool->free_map));
+	__set_bit(ent->buf_id, pool->free_map);
+
+	memset(ent_payload, 0, sizeof(*ent_payload));
+	ent->buf_id = 0;
+}
+
+static int fuse_uring_next_req_update_buffer(struct fuse_ring_ent *ent,
+					     struct fuse_req *req)
+{
+	bool buffer_selected;
+	bool has_payload;
+
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	buffer_selected = !!ent->payload.iov_base;
+	has_payload = fuse_uring_req_has_payload(req);
+
+	if (has_payload && !buffer_selected)
+		return fuse_uring_select_buffer(ent);
+
+	if (!has_payload && buffer_selected)
+		fuse_uring_recycle_buffer(ent);
+
+	return 0;
+}
+
+static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
+				  struct fuse_req *req)
+{
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	/* no payload to copy, can skip selecting a buffer */
+	if (!fuse_uring_req_has_payload(req))
+		return 0;
+
+	return fuse_uring_select_buffer(ent);
+}
+
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
@@ -858,10 +954,13 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 
 	/* get and assign the next entry while it is still holding the lock */
 	req = list_first_entry_or_null(req_queue, struct fuse_req, list);
-	if (req)
+	if (req && !fuse_uring_next_req_update_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
+		return req;
+	}
 
-	return req;
+	fuse_uring_recycle_buffer(ent);
+	return NULL;
 }
 
 /*
@@ -872,7 +971,6 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 			      unsigned int issue_flags)
 {
-	struct fuse_ring *ring = ent->queue->ring;
 	ssize_t err = -EFAULT;
 
 	if (copy_header_from_ring(ent, FUSE_URING_HEADER_IN_OUT, &req->out.h,
@@ -885,7 +983,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(ring, req, ent);
+	err = fuse_uring_copy_from_ring(req, ent);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -1004,6 +1102,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	if (err != 0) {
 		pr_info_ratelimited("qid=%d commit_id %llu state %d",
 				    queue->qid, commit_id, ent->state);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 		fuse_uring_req_end(ent, req, err);
 		return err;
@@ -1021,6 +1120,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * fuse requests would otherwise not get processed - committing
 	 * and fetching is done in one step vs legacy fuse, which has separated
 	 * read (fetch request) and write (commit result).
+	 *
+	 * If there is no next request or if all buffers are busy (if using a
+	 * bufpool), the cmd is not returned to userspace. The entry is left
+	 * available and the cmd only returns to userspace when there's a
+	 * next request and an available buffer.
 	 */
 	if (fuse_uring_get_next_fuse_req(ent, queue))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
@@ -1145,11 +1249,23 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 	}
 
 	payload = &iov[FUSE_URING_IOV_PAYLOAD];
-	if (payload->iov_len < ring->max_payload_sz) {
-		pr_info_ratelimited("Invalid req payload len %zu\n",
-				    payload->iov_len);
-		return ERR_PTR(err);
+
+	spin_lock(&queue->lock);
+	if (bufpool_enabled(queue)) {
+		if (payload->iov_base || payload->iov_len) {
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+	} else {
+		if (payload->iov_len < ring->max_payload_sz) {
+			pr_info_ratelimited("Invalid req payload len %zu\n",
+					    payload->iov_len);
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+		queue->payload_mode = FUSE_PAYLOAD_PER_ENT;
 	}
+	spin_unlock(&queue->lock);
 
 	err = -ENOMEM;
 	ent = kzalloc_obj(*ent, GFP_KERNEL_ACCOUNT);
@@ -1160,7 +1276,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	ent->queue = queue;
 	ent->headers = headers->iov_base;
-	ent->payload = payload->iov_base;
+	if (queue->payload_mode == FUSE_PAYLOAD_PER_ENT)
+		ent->payload = *payload;
 
 	atomic_inc(&ring->queue_refs);
 	return ent;
@@ -1231,6 +1348,63 @@ static int fuse_uring_add_queue(struct io_uring_cmd *cmd, struct fuse_chan *fch)
 	return 0;
 }
 
+static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
+				  struct fuse_chan *fch)
+{
+	const struct fuse_uring_cmd_req *cmd_req =
+		io_uring_sqe128_cmd(cmd->sqe, struct fuse_uring_cmd_req);
+	unsigned int qid = READ_ONCE(cmd_req->qid);
+	uint64_t flags = READ_ONCE(cmd_req->flags);
+	/* paired with the smp_store_release() in fuse_uring_create */
+	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
+	struct fuse_ring_queue *queue;
+	struct fuse_bufpool *pool;
+	uintptr_t pool_uaddr;
+	unsigned int pool_len, nr_bufs;
+	size_t pool_size, buf_size;
+
+	if (!ring || qid >= ring->nr_queues || flags)
+		return -EINVAL;
+
+	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
+	queue = smp_load_acquire(&ring->queues[qid]);
+	if (!queue)
+		return -EINVAL;
+
+	pool_uaddr = READ_ONCE(cmd_req->bufpool.uaddr);
+	pool_len = READ_ONCE(cmd_req->bufpool.len);
+
+	/* each buffer holds the max payload size */
+	buf_size = queue->ring->max_payload_sz;
+
+	nr_bufs = pool_len / buf_size;
+	if (!nr_bufs)
+		return -EINVAL;
+
+	pool_size = struct_size(pool, free_map, BITS_TO_LONGS(nr_bufs));
+	pool = kzalloc(pool_size, GFP_KERNEL_ACCOUNT);
+	if (!pool)
+		return -ENOMEM;
+
+	pool->base_uaddr = pool_uaddr;
+	pool->buf_size = buf_size;
+	pool->nr_bufs = nr_bufs;
+	/* all buffers are free */
+	bitmap_set(pool->free_map, 0, nr_bufs);
+
+	spin_lock(&queue->lock);
+	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
+		spin_unlock(&queue->lock);
+		kfree(pool);
+		return -EINVAL;
+	}
+	queue->bufpool = pool;
+	queue->payload_mode = FUSE_PAYLOAD_BUFPOOL;
+	spin_unlock(&queue->lock);
+
+	return 0;
+}
+
 /*
  * Entry function from io_uring to handle the given passthrough command
  * (op code IORING_OP_URING_CMD)
@@ -1303,6 +1477,12 @@ int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
 			pr_info_once("FUSE_IO_URING_CMD_ADD_QUEUE failed err=%d\n",
 				     err);
 		return err;
+	case FUSE_IO_URING_CMD_ADD_BUFPOOL:
+		err = fuse_uring_add_bufpool(cmd, fch);
+		if (err)
+			pr_info_once("FUSE_IO_URING_ADD_BUFPOOL failed err=%d\n",
+				     err);
+		return err;
 	default:
 		return -EINVAL;
 	}
@@ -1336,6 +1516,7 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 
 		spin_lock(&queue->lock);
 		list_del_init(&ent->list);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 
 		io_uring_cmd_done(cmd, err, issue_flags);
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
 	req->ring_queue = queue;
 	ent = list_first_entry_or_null(&queue->ent_avail_queue,
 				       struct fuse_ring_ent, list);
-	if (ent)
-		fuse_uring_add_req_to_ring_ent(ent, req);
-	else
-		list_add_tail(&req->list, &queue->fuse_req_queue);
-	spin_unlock(&queue->lock);
+	if (ent) {
+		if (!fuse_uring_prep_buffer(ent, req)) {
+			fuse_uring_add_req_to_ring_ent(ent, req);
+			spin_unlock(&queue->lock);
+			fuse_uring_dispatch_ent(ent);
+			return;
+		}
+	}
 
-	if (ent)
-		fuse_uring_dispatch_ent(ent);
+	list_add_tail(&req->list, &queue->fuse_req_queue);
+	spin_unlock(&queue->lock);
 
 	return;
 
@@ -1453,10 +1637,9 @@ bool fuse_uring_queue_bq_req(struct fuse_req *req)
 	 */
 	req = list_first_entry_or_null(&queue->fuse_req_queue, struct fuse_req,
 				       list);
-	if (ent && req) {
+	if (ent && req && !fuse_uring_prep_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
 		spin_unlock(&queue->lock);
-
 		fuse_uring_dispatch_ent(ent);
 	} else {
 		spin_unlock(&queue->lock);
fs/fuse/dev_uring_i.h +36 -1
index d721a4fc0215..cdf56f8b38b5 100644
@@ -7,6 +7,8 @@
 #ifndef _FS_FUSE_DEV_URING_I_H
 #define _FS_FUSE_DEV_URING_I_H
 
+#include <linux/uio.h>
+
 #include "fuse_dev_i.h"
 
 #ifdef CONFIG_FUSE_IO_URING
@@ -36,11 +38,38 @@ enum fuse_ring_req_state {
 	FRRS_RELEASED,
 };
 
+/* how a queue's payload buffers are provided */
+enum fuse_queue_payload_mode {
+	/* not yet committed (a bufpool may still be added) */
+	FUSE_PAYLOAD_UNSET = 0,
+	/* each entry registers its own payload buffer */
+	FUSE_PAYLOAD_PER_ENT,
+	/* each entry's payload buffer is assigned from a bufpool */
+	FUSE_PAYLOAD_BUFPOOL,
+};
+
+struct fuse_bufpool {
+	/* starting uaddr of the bufpool */
+	uintptr_t base_uaddr;
+
+	/* size of each buffer in the pool */
+	size_t buf_size;
+
+	/* total number of buffers in the pool */
+	unsigned int nr_bufs;
+
+	/* bitmap tracking which buffers are free */
+	unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
 	/* userspace buffer */
 	struct fuse_uring_req_header __user *headers;
-	void __user *payload;
+	struct iovec payload;
+
+	/* buffer id in the pool, if bufpools are used. ignored otherwise */
+	unsigned int buf_id;
 
 	/* the ring queue that owns the request */
 	struct fuse_ring_queue *queue;
@@ -99,6 +128,12 @@ struct fuse_ring_queue {
 	unsigned int active_background;
 
 	bool stopped;
+
+	/* how this queue's payload buffers are provided */
+	enum fuse_queue_payload_mode payload_mode;
+
+	/* only allocated when payload_mode == FUSE_PAYLOAD_BUFPOOL */
+	struct fuse_bufpool *bufpool;
 };
 
 /*
fs/fuse/inode.c +1 -1
index ce4891a04a37..929ddbea0eb0 100644
@@ -1481,7 +1481,7 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
 	 * the reply - server is either sending IORING_OP_URING_CMD or not.
 	 */
 	if (fuse_uring_enabled())
-		flags |= FUSE_OVER_IO_URING;
+		flags |= FUSE_OVER_IO_URING | FUSE_HAS_IO_URING_BUFPOOL;
 
 	ia->in.flags = flags;
 	ia->in.flags2 = flags >> 32;
include/uapi/linux/fuse.h +19 -1
index cfb055c0c764..f7173b5d4321 100644
@@ -243,6 +243,9 @@
  *
  *  7.46
  *  - add FUSE_IO_URING_CMD_ADD_QUEUE
+ *  - add FUSE_HAS_IO_URING_BUFPOOL
+ *  - add fuse_uring_cmd_req bufpool struct
+ *  - add bufpool offset field to fuse_uring_ent_in_out struct
  */
 
 #ifndef _LINUX_FUSE_H
@@ -451,6 +454,7 @@ struct fuse_file_lock {
  * FUSE_OVER_IO_URING: Indicate that client supports io-uring
  * FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
  *			 init_out.request_timeout contains the timeout (in secs)
+ * FUSE_HAS_IO_URING_BUFPOOL: kernel supports io-uring buffer pools
  */
 #define FUSE_ASYNC_READ		(1 << 0)
 #define FUSE_POSIX_LOCKS	(1 << 1)
@@ -498,6 +502,7 @@ struct fuse_file_lock {
 #define FUSE_ALLOW_IDMAP	(1ULL << 40)
 #define FUSE_OVER_IO_URING	(1ULL << 41)
 #define FUSE_REQUEST_TIMEOUT	(1ULL << 42)
+#define FUSE_HAS_IO_URING_BUFPOOL (1ULL << 43)
 
 /**
  * CUSE INIT request/reply flags
@@ -1266,7 +1271,9 @@ struct fuse_uring_ent_in_out {
 
 	/* size of user payload buffer */
 	uint32_t payload_sz;
-	uint32_t padding;
+
+	/* Offset into the bufpool, if bufpools are used */
+	uint32_t offset;
 
 	uint64_t reserved;
 };
@@ -1298,6 +1305,9 @@ enum fuse_uring_cmd {
 
 	/* add a queue */
 	FUSE_IO_URING_CMD_ADD_QUEUE = 3,
+
+	/* add a bufpool to a queue */
+	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
 	/* queue the command is for (queue index) */
 	uint16_t qid;
 	uint8_t padding[6];
+
+	union {
+		struct {
+			/* base address of bufpool */
+			uint64_t uaddr;
+			uint32_t len;
+		} bufpool;
+	};
 };
 
 #endif /* _LINUX_FUSE_H */
Signature · 1 line
2.52.0
maintainer
#13 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

Quoted 467 lines · Joanne Koong

Right now, ents and buffers are tightly coupled in fuse io-uring where each entry has its own dedicated payload buffer, requiring N buffers for N entries where each buffer must be large enough to accomodate the maximum payload size. This is suboptimal as most request types (lookup, open, release, getattr, etc) require vastly less bytes than the maximum payload size and some requests (unlink, rmdir, fsync, flush, etc) do not require payload buffers at all.

Instead of requiring a 1:1 coupling between ents and payload buffers, allow the server to pass in a buffer pool (a contiguous chunk of memory) that the kernel will use as it wishes for servicing ents/requests. Entries only reserve a "buffer" from the pool while actively processing a request that requires a payload buffer. This decoupling and letting the kernel delegate memory from the pool for requests allows the kernel to optimize memory usage and reduces the memory usage requirements needed to use fuse-over-io-uring.

A pool is registered per queue with the new FUSE_IO_URING_CMD_ADD_BUFPOOL command. The server passes the pool's base address and length in fuse_uring_cmd_req.bufpool.{uaddr,len}.

Internally, the kernel splits the region into buffers of ring->max_payload_sz bytes each (nr_bufs = pool len / max_payload_sz). A queue commits to a payload mode on first use: registering an entry that carries its own payload selects the legacy per-entry mode, while ADD_BUFPOOL selects pool mode. The two are mutually exclusive, so ADD_BUFPOOL must be issued before any payload-carrying entries are registered on that queue. The queue must have been created before the bufpool is added, through the FUSE_IO_URING_CMD_ADD_QUEUE command.

The kernel tracks free buffers with a bitmap (a set bit marks a free buffer). On dispatch, a request that needs a payload claims a free buffer (find_first_bit + clear). A request that needs none claims nothing. The buffer's byte offset within the pool is reported to the server in the new fuse_uring_ent_in_out.offset field so that the server can locate the payload. On completion the buffer is returned to the pool or reused directly if the next request on that entry also has a payload.

The FUSE_HAS_IO_URING_BUFPOOL flag advertises kernel support to the server for bufpools.

Buffer pool request flow
~~~~~~~~~~~~~~~~~~~~~~~~

|  Kernel                                  |  FUSE daemon
|                                          |
|  [request arrives]                       |
|    [claim a free pool buffer]            |
|    >fuse_uring_select_buffer()           |
|    [copy headers to ring]                |
|    [copy payload to buffer]              |
|    [report buffer offset in ent_in_out]  |
|    >io_uring_cmd_done()                  |
|                                          |  [read headers]
|                                          |  [read/write payload at offset]
|                                          |  [process request]
|                                          |  >io_uring_submit()
|                                          |   COMMIT_AND_FETCH
|  >fuse_uring_commit_fetch()              |
|    [copy reply from ring]                |
|    [return buffer to the pool]           |
|    >fuse_uring_recycle_buffer()          |
---
 fs/fuse/dev_uring.c       | 237 +++++++++++++++++++++++++++++++++-----
 fs/fuse/dev_uring_i.h     |  37 +++++-
 fs/fuse/inode.c           |   2 +-
 include/uapi/linux/fuse.h |  20 +++-
 4 files changed, 266 insertions(+), 30 deletions(-)
fs/fuse/dev_uring.c +199 -21
index fdf1058e582c..e9da92b46090 100644
@@ -9,6 +9,7 @@
 #include "dev_uring_i.h"
 #include "fuse_trace.h"
 
+#include <linux/bitmap.h>
 #include <linux/fs.h>
 #include <linux/io_uring/cmd.h>
 
@@ -41,6 +42,11 @@ enum fuse_uring_header_type {
 	FUSE_URING_HEADER_RING_ENT,
 };
 
+static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
+{
+	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -222,6 +228,7 @@ void fuse_uring_destruct(struct fuse_chan *fch)
 		}
 
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		ring->queues[qid] = NULL;
 	}
@@ -316,6 +323,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 	if (ring->queues[qid]) {
 		spin_unlock(&fch->lock);
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		return fail_if_exists ? ERR_PTR(-EEXIST) : ring->queues[qid];
 	}
@@ -646,13 +654,14 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 }
 
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
-				 struct fuse_ring *ring, struct fuse_req *req,
+				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
 				 struct iov_iter *iter)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+			  iter);
 	if (err) {
 		pr_info_ratelimited("fuse: Import of user buffer failed\n");
 		return err;
@@ -666,8 +675,7 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 	return 0;
 }
 
-static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
-				     struct fuse_req *req,
+static int fuse_uring_copy_from_ring(struct fuse_req *req,
 				     struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -681,7 +689,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
 	if (err)
 		return err;
 
@@ -693,7 +701,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 /*
  * Copy data from the req to the ring buffer
  */
-static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
+static int fuse_uring_args_to_ring(struct fuse_req *req,
 				   struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -707,7 +715,7 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
 	if (err)
 		return err;
 
@@ -737,6 +745,10 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 	}
 
 	ent_in_out.payload_sz = cs.ring.copied_sz;
+	if (bufpool_enabled(ent->queue) && ent->payload.iov_base)
+		ent_in_out.offset =
+			(uintptr_t)ent->payload.iov_base - ent->queue->bufpool->base_uaddr;
+
 	return copy_header_to_ring(ent, FUSE_URING_HEADER_RING_ENT,
 				   &ent_in_out, sizeof(ent_in_out));
 }
@@ -745,7 +757,6 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
 	struct fuse_ring_queue *queue = ent->queue;
-	struct fuse_ring *ring = queue->ring;
 	int err;
 
 	err = -EIO;
@@ -760,7 +771,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(ring, req, ent);
+	err = fuse_uring_args_to_ring(req, ent);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -771,6 +782,91 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   sizeof(req->in.h));
 }
 
+static bool fuse_uring_req_has_payload(struct fuse_req *req)
+{
+	struct fuse_args *args = req->args;
+
+	return args->in_numargs > 1 || args->out_numargs;
+}
+
+static int fuse_uring_select_buffer(struct fuse_ring_ent *ent)
+{
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool = queue->bufpool;
+	unsigned int id;
+
+	lockdep_assert_held(&queue->lock);
+
+	id = find_first_bit(pool->free_map, pool->nr_bufs);
+	if (id >= pool->nr_bufs)
+		return -ENOBUFS;
+
+	WARN_ON_ONCE(ent->payload.iov_base);
+	__clear_bit(id, pool->free_map);
+
+	ent->buf_id = id;
+	ent->payload.iov_base =
+		(void __user *)(pool->base_uaddr + id * pool->buf_size);
+	ent->payload.iov_len = pool->buf_size;
+
+	return 0;
+}
+
+static void fuse_uring_recycle_buffer(struct fuse_ring_ent *ent)
+{
+	struct iovec *ent_payload = &ent->payload;
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool;
+
+	lockdep_assert_held(&queue->lock);
+
+	if (!bufpool_enabled(queue) || !ent_payload->iov_base)
+		return;
+
+	pool = queue->bufpool;
+
+	/* a buffer should never be recycled twice */
+	WARN_ON_ONCE(test_bit(ent->buf_id, pool->free_map));
+	__set_bit(ent->buf_id, pool->free_map);
+
+	memset(ent_payload, 0, sizeof(*ent_payload));
+	ent->buf_id = 0;
+}
+
+static int fuse_uring_next_req_update_buffer(struct fuse_ring_ent *ent,
+					     struct fuse_req *req)
+{
+	bool buffer_selected;
+	bool has_payload;
+
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	buffer_selected = !!ent->payload.iov_base;
+	has_payload = fuse_uring_req_has_payload(req);
+
+	if (has_payload && !buffer_selected)
+		return fuse_uring_select_buffer(ent);
+
+	if (!has_payload && buffer_selected)
+		fuse_uring_recycle_buffer(ent);
+
+	return 0;
+}
+
+static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
+				  struct fuse_req *req)
+{
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	/* no payload to copy, can skip selecting a buffer */
+	if (!fuse_uring_req_has_payload(req))
+		return 0;
+
+	return fuse_uring_select_buffer(ent);
+}
+
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
@@ -858,10 +954,13 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 
 	/* get and assign the next entry while it is still holding the lock */
 	req = list_first_entry_or_null(req_queue, struct fuse_req, list);
-	if (req)
+	if (req && !fuse_uring_next_req_update_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
+		return req;
+	}
 
-	return req;
+	fuse_uring_recycle_buffer(ent);
+	return NULL;
 }
 
 /*
@@ -872,7 +971,6 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 			      unsigned int issue_flags)
 {
-	struct fuse_ring *ring = ent->queue->ring;
 	ssize_t err = -EFAULT;
 
 	if (copy_header_from_ring(ent, FUSE_URING_HEADER_IN_OUT, &req->out.h,
@@ -885,7 +983,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(ring, req, ent);
+	err = fuse_uring_copy_from_ring(req, ent);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -1004,6 +1102,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	if (err != 0) {
 		pr_info_ratelimited("qid=%d commit_id %llu state %d",
 				    queue->qid, commit_id, ent->state);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 		fuse_uring_req_end(ent, req, err);
 		return err;
@@ -1021,6 +1120,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * fuse requests would otherwise not get processed - committing
 	 * and fetching is done in one step vs legacy fuse, which has separated
 	 * read (fetch request) and write (commit result).
+	 *
+	 * If there is no next request or if all buffers are busy (if using a
+	 * bufpool), the cmd is not returned to userspace. The entry is left
+	 * available and the cmd only returns to userspace when there's a
+	 * next request and an available buffer.
 	 */
 	if (fuse_uring_get_next_fuse_req(ent, queue))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
@@ -1145,11 +1249,23 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 	}
 
 	payload = &iov[FUSE_URING_IOV_PAYLOAD];
-	if (payload->iov_len < ring->max_payload_sz) {
-		pr_info_ratelimited("Invalid req payload len %zu\n",
-				    payload->iov_len);
-		return ERR_PTR(err);
+
+	spin_lock(&queue->lock);
+	if (bufpool_enabled(queue)) {
+		if (payload->iov_base || payload->iov_len) {
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+	} else {
+		if (payload->iov_len < ring->max_payload_sz) {
+			pr_info_ratelimited("Invalid req payload len %zu\n",
+					    payload->iov_len);
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+		queue->payload_mode = FUSE_PAYLOAD_PER_ENT;
 	}
+	spin_unlock(&queue->lock);
 
 	err = -ENOMEM;
 	ent = kzalloc_obj(*ent, GFP_KERNEL_ACCOUNT);
@@ -1160,7 +1276,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	ent->queue = queue;
 	ent->headers = headers->iov_base;
-	ent->payload = payload->iov_base;
+	if (queue->payload_mode == FUSE_PAYLOAD_PER_ENT)
+		ent->payload = *payload;
 
 	atomic_inc(&ring->queue_refs);
 	return ent;
@@ -1231,6 +1348,63 @@ static int fuse_uring_add_queue(struct io_uring_cmd *cmd, struct fuse_chan *fch)
 	return 0;
 }
 
+static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
+				  struct fuse_chan *fch)
+{
+	const struct fuse_uring_cmd_req *cmd_req =
+		io_uring_sqe128_cmd(cmd->sqe, struct fuse_uring_cmd_req);
+	unsigned int qid = READ_ONCE(cmd_req->qid);
+	uint64_t flags = READ_ONCE(cmd_req->flags);
+	/* paired with the smp_store_release() in fuse_uring_create */
+	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
+	struct fuse_ring_queue *queue;
+	struct fuse_bufpool *pool;
+	uintptr_t pool_uaddr;
+	unsigned int pool_len, nr_bufs;
+	size_t pool_size, buf_size;
+
+	if (!ring || qid >= ring->nr_queues || flags)
+		return -EINVAL;
+
+	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
+	queue = smp_load_acquire(&ring->queues[qid]);
+	if (!queue)
+		return -EINVAL;
+
+	pool_uaddr = READ_ONCE(cmd_req->bufpool.uaddr);
+	pool_len = READ_ONCE(cmd_req->bufpool.len);
+
+	/* each buffer holds the max payload size */
+	buf_size = queue->ring->max_payload_sz;
+
+	nr_bufs = pool_len / buf_size;
+	if (!nr_bufs)
+		return -EINVAL;
+
+	pool_size = struct_size(pool, free_map, BITS_TO_LONGS(nr_bufs));
+	pool = kzalloc(pool_size, GFP_KERNEL_ACCOUNT);
+	if (!pool)
+		return -ENOMEM;
+
+	pool->base_uaddr = pool_uaddr;
+	pool->buf_size = buf_size;
+	pool->nr_bufs = nr_bufs;
+	/* all buffers are free */
+	bitmap_set(pool->free_map, 0, nr_bufs);
+
+	spin_lock(&queue->lock);
+	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
+		spin_unlock(&queue->lock);
+		kfree(pool);
+		return -EINVAL;
+	}
+	queue->bufpool = pool;
+	queue->payload_mode = FUSE_PAYLOAD_BUFPOOL;
+	spin_unlock(&queue->lock);
+
+	return 0;
+}
+
 /*
  * Entry function from io_uring to handle the given passthrough command
  * (op code IORING_OP_URING_CMD)
@@ -1303,6 +1477,12 @@ int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
 			pr_info_once("FUSE_IO_URING_CMD_ADD_QUEUE failed err=%d\n",
 				     err);
 		return err;
+	case FUSE_IO_URING_CMD_ADD_BUFPOOL:
+		err = fuse_uring_add_bufpool(cmd, fch);
+		if (err)
+			pr_info_once("FUSE_IO_URING_ADD_BUFPOOL failed err=%d\n",
+				     err);
+		return err;
 	default:
 		return -EINVAL;
 	}
@@ -1336,6 +1516,7 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 
 		spin_lock(&queue->lock);
 		list_del_init(&ent->list);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 
 		io_uring_cmd_done(cmd, err, issue_flags);
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
 	req->ring_queue = queue;
 	ent = list_first_entry_or_null(&queue->ent_avail_queue,
 				       struct fuse_ring_ent, list);
-	if (ent)
-		fuse_uring_add_req_to_ring_ent(ent, req);
-	else

fs/fuse/dev_uring.c void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req) · line 1588

Quoted 10 lines
fs/fuse/dev_uring.c +8 -2
-		list_add_tail(&req->list, &queue->fuse_req_queue);
-	spin_unlock(&queue->lock);
+	if (ent) {
+		if (!fuse_uring_prep_buffer(ent, req)) {
+			fuse_uring_add_req_to_ring_ent(ent, req);
+			spin_unlock(&queue->lock);
+			fuse_uring_dispatch_ent(ent);
+			return;
+		}
+	}

Pure style, somehow "if (!fuse_uring_prep_buffer(ent, req))" reads like an error case, *maybe*

        ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                       struct fuse_ring_ent, list);
        /* no idle entry, or no free pool buffer for this req */
        if (!ent || fuse_uring_prep_buffer(ent, req)) {
                list_add_tail(&req->list, &queue->fuse_req_queue);
                spin_unlock(&queue->lock);
                return;                
        }
        
        fuse_uring_add_req_to_ring_ent(ent, req);
        spin_unlock(&queue->lock);
        fuse_uring_dispatch_ent(ent);
        return; 

err_unlock:
...

and similar in fuse_uring_ent_assign_req()

        req = list_first_entry_or_null(req_queue, struct fuse_req, list);
        if (!req || fuse_uring_next_req_update_buffer(ent, req)) {
                fuse_uring_recycle_buffer(ent);
                return NULL;
        }
        
        fuse_uring_add_req_to_ring_ent(ent, req);
        return req;

Just a pure style suggestion, though.

Quoted 57 lines
fs/fuse/dev_uring.c +3 -4
-	if (ent)
-		fuse_uring_dispatch_ent(ent);
+	list_add_tail(&req->list, &queue->fuse_req_queue);
+	spin_unlock(&queue->lock);
 
 	return;
 
@@ -1453,10 +1637,9 @@ bool fuse_uring_queue_bq_req(struct fuse_req *req)
 	 */
 	req = list_first_entry_or_null(&queue->fuse_req_queue, struct fuse_req,
 				       list);
-	if (ent && req) {
+	if (ent && req && !fuse_uring_prep_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
 		spin_unlock(&queue->lock);
-
 		fuse_uring_dispatch_ent(ent);
 	} else {
 		spin_unlock(&queue->lock);
fs/fuse/dev_uring_i.h +22 -0
index d721a4fc0215..cdf56f8b38b5 100644
@@ -7,6 +7,8 @@
 #ifndef _FS_FUSE_DEV_URING_I_H
 #define _FS_FUSE_DEV_URING_I_H
 
+#include <linux/uio.h>
+
 #include "fuse_dev_i.h"
 
 #ifdef CONFIG_FUSE_IO_URING
@@ -36,11 +38,38 @@ enum fuse_ring_req_state {
 	FRRS_RELEASED,
 };
 
+/* how a queue's payload buffers are provided */
+enum fuse_queue_payload_mode {
+	/* not yet committed (a bufpool may still be added) */
+	FUSE_PAYLOAD_UNSET = 0,
+	/* each entry registers its own payload buffer */
+	FUSE_PAYLOAD_PER_ENT,
+	/* each entry's payload buffer is assigned from a bufpool */
+	FUSE_PAYLOAD_BUFPOOL,
+};
+
+struct fuse_bufpool {
+	/* starting uaddr of the bufpool */
+	uintptr_t base_uaddr;
+
+	/* size of each buffer in the pool */
+	size_t buf_size;
+
+	/* total number of buffers in the pool */
+	unsigned int nr_bufs;
+

fs/fuse/dev_uring_i.h enum fuse_ring_req_state { · line 69

Quoted 10 lines
fs/fuse/dev_uring_i.h +5 -1
+	/* bitmap tracking which buffers are free */
+	unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
 	/* userspace buffer */
 	struct fuse_uring_req_header __user *headers;
-	void __user *payload;
+	struct iovec payload;

Here I have a real concern. What is if fuse server sets up really really large buffers, to thrash the CPUs?

setup_fuse_copy_state() is now changed to

- err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+ err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+ iter);

And the iov is taken as it from the SQE. Is there actually a really good reason to have the payload as iov, at least in this series? I could imagine it might make sense to have it as iov once we make the buf pools more dynamically usable.

Could we restrict setup_fuse_copy_state() to ring->max_payload_sz?

Quoted 84 lines
fs/fuse/dev_uring_i.h +9 -0
+
+	/* buffer id in the pool, if bufpools are used. ignored otherwise */
+	unsigned int buf_id;
 
 	/* the ring queue that owns the request */
 	struct fuse_ring_queue *queue;
@@ -99,6 +128,12 @@ struct fuse_ring_queue {
 	unsigned int active_background;
 
 	bool stopped;
+
+	/* how this queue's payload buffers are provided */
+	enum fuse_queue_payload_mode payload_mode;
+
+	/* only allocated when payload_mode == FUSE_PAYLOAD_BUFPOOL */
+	struct fuse_bufpool *bufpool;
 };
 
 /*
fs/fuse/inode.c +1 -1
index ce4891a04a37..929ddbea0eb0 100644
@@ -1481,7 +1481,7 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
 	 * the reply - server is either sending IORING_OP_URING_CMD or not.
 	 */
 	if (fuse_uring_enabled())
-		flags |= FUSE_OVER_IO_URING;
+		flags |= FUSE_OVER_IO_URING | FUSE_HAS_IO_URING_BUFPOOL;
 
 	ia->in.flags = flags;
 	ia->in.flags2 = flags >> 32;
include/uapi/linux/fuse.h +11 -1
index cfb055c0c764..f7173b5d4321 100644
@@ -243,6 +243,9 @@
  *
  *  7.46
  *  - add FUSE_IO_URING_CMD_ADD_QUEUE
+ *  - add FUSE_HAS_IO_URING_BUFPOOL
+ *  - add fuse_uring_cmd_req bufpool struct
+ *  - add bufpool offset field to fuse_uring_ent_in_out struct
  */
 
 #ifndef _LINUX_FUSE_H
@@ -451,6 +454,7 @@ struct fuse_file_lock {
  * FUSE_OVER_IO_URING: Indicate that client supports io-uring
  * FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
  *			 init_out.request_timeout contains the timeout (in secs)
+ * FUSE_HAS_IO_URING_BUFPOOL: kernel supports io-uring buffer pools
  */
 #define FUSE_ASYNC_READ		(1 << 0)
 #define FUSE_POSIX_LOCKS	(1 << 1)
@@ -498,6 +502,7 @@ struct fuse_file_lock {
 #define FUSE_ALLOW_IDMAP	(1ULL << 40)
 #define FUSE_OVER_IO_URING	(1ULL << 41)
 #define FUSE_REQUEST_TIMEOUT	(1ULL << 42)
+#define FUSE_HAS_IO_URING_BUFPOOL (1ULL << 43)
 
 /**
  * CUSE INIT request/reply flags
@@ -1266,7 +1271,9 @@ struct fuse_uring_ent_in_out {
 
 	/* size of user payload buffer */
 	uint32_t payload_sz;
-	uint32_t padding;
+
+	/* Offset into the bufpool, if bufpools are used */
+	uint32_t offset;
 
 	uint64_t reserved;
 };
@@ -1298,6 +1305,9 @@ enum fuse_uring_cmd {
 
 	/* add a queue */
 	FUSE_IO_URING_CMD_ADD_QUEUE = 3,
+
+	/* add a bufpool to a queue */
+	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
 /**

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1331

Quoted 10 lines
include/uapi/linux/fuse.h +7 -0
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
 	/* queue the command is for (queue index) */
 	uint16_t qid;
 	uint8_t padding[6];
+
+	union {
+		struct {
+			/* base address of bufpool */
+			uint64_t uaddr;
+			uint32_t len;
+		} bufpool;

Ok, if we ever want to add a new bufpool, I guess we could invent "struct { } bufpool2;". Personally I would have preferred to have an index in here, currently always set to 0, but not a strict requirement.

(Sorry, have to stop reviewing for today and can earliest continue on Satturday night).

Thanks,
Bernd

author maintainer
#14 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

Quoted 53 lines · Bernd Schubert
Quoted 10 lines · Joanne Koong
fs/fuse/dev_uring.c +0 -3
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
      req->ring_queue = queue;
      ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                     struct fuse_ring_ent, list);
-     if (ent)
-             fuse_uring_add_req_to_ring_ent(ent, req);
-     else

fs/fuse/dev_uring.c void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req) · line 1588

Quoted 10 lines
fs/fuse/dev_uring.c +8 -2
-             list_add_tail(&req->list, &queue->fuse_req_queue);
-     spin_unlock(&queue->lock);
+     if (ent) {
+             if (!fuse_uring_prep_buffer(ent, req)) {
+                     fuse_uring_add_req_to_ring_ent(ent, req);
+                     spin_unlock(&queue->lock);
+                     fuse_uring_dispatch_ent(ent);
+                     return;
+             }
+     }

Pure style, somehow "if (!fuse_uring_prep_buffer(ent, req))" reads like an error case, *maybe*

        ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                       struct fuse_ring_ent, list);
        /* no idle entry, or no free pool buffer for this req */
        if (!ent || fuse_uring_prep_buffer(ent, req)) {
                list_add_tail(&req->list, &queue->fuse_req_queue);
                spin_unlock(&queue->lock);
                return;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        spin_unlock(&queue->lock);
        fuse_uring_dispatch_ent(ent);
        return;

err_unlock:
...

and similar in fuse_uring_ent_assign_req()

        req = list_first_entry_or_null(req_queue, struct fuse_req, list);
        if (!req || fuse_uring_next_req_update_buffer(ent, req)) {
                fuse_uring_recycle_buffer(ent);
                return NULL;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        return req;
Quoted 2 lines

Just a pure style suggestion, though.

Happy to make this change. Thanks for reviewing the patches. I'll wait until you have finished reviewing the other patches in this series before sending this.

Quoted 38 lines
Quoted 18 lines
fs/fuse/dev_uring_i.h +12 -2
-     if (ent)
-             fuse_uring_dispatch_ent(ent);
+     list_add_tail(&req->list, &queue->fuse_req_queue);
+     spin_unlock(&queue->lock);
 
      return;
 
+struct fuse_bufpool {
+     /* starting uaddr of the bufpool */
+     uintptr_t base_uaddr;
+
+     /* size of each buffer in the pool */
+     size_t buf_size;
+
+     /* total number of buffers in the pool */
+     unsigned int nr_bufs;
+

fs/fuse/dev_uring_i.h enum fuse_ring_req_state { · line 69

Quoted 10 lines
fs/fuse/dev_uring_i.h +5 -1
+     /* bitmap tracking which buffers are free */
+     unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
      /* userspace buffer */
      struct fuse_uring_req_header __user *headers;
-     void __user *payload;
+     struct iovec payload;

Here I have a real concern. What is if fuse server sets up really really large buffers, to thrash the CPUs?

setup_fuse_copy_state() is now changed to

fs/fuse/dev_uring.c +2 -1
-       err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+       err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+                         iter);
Quoted 6 lines

And the iov is taken as it from the SQE. Is there actually a really good reason to have the payload as iov, at least in this series? I could imagine it might make sense to have it as iov once we make the buf pools more dynamically usable.

Could we restrict setup_fuse_copy_state() to ring->max_payload_sz?

The payload.iov fields are not taken directly from the bufpool sqe. It is assigned in fuse_uring_select_buffer() to reflect one buffer within the pool. ent->payload.iov_len is set to pool->buf_size, which in fuse_uring_add_bufpool(), we set pool->buf_size to be ring->max_payload_sz. Looking at import_ubuf() though, even if we did pass in the entire buffer pool size here, it is harmless, as the bytes copied are already limited/determined by the request (eg on the send-side, copies are bound by in-arg sizes and on the reply side, fuse_copy_out_args() rejects any payload_sz exceeding sum of the out args before doing any copying). Right now pools hand out buffers of the same size so iov_len tracking isn't needed, but pools will be handing out differently-sized buffers.

Quoted 19 lines
Quoted 19 lines
fs/fuse/dev_uring_i.h +3 -0
+
+     /* buffer id in the pool, if bufpools are used. ignored otherwise */
+     unsigned int buf_id;
include/uapi/linux/fuse.h +5 -0
index cfb055c0c764..f7173b5d4321 100644
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
      /* queue the command is for (queue index) */
      uint16_t qid;
      uint8_t padding[6];
+
+     union {
+             struct {
+                     /* base address of bufpool */
+                     uint64_t uaddr;
Quoted 9 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1331

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+                     uint32_t len;
+             } bufpool;

Ok, if we ever want to add a new bufpool, I guess we could invent "struct { } bufpool2;". Personally I would have preferred to have an index in here, currently always set to 0, but not a strict requirement.

If we ever want to add a new bufpool, I think it'd be cleaner for the kernel to assign the bufpool id and pass it back in the cqe to the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd rather than the server assigning it. With server-supplied indexes, we would have to also track / prevent collisions, gaps, out-of-range values, etc.

Thanks,
Joanne

maintainer
#15 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

Quoted 106 lines · Joanne Koong
Quoted 53 lines · Bernd Schubert
Quoted 10 lines · Joanne Koong
fs/fuse/dev_uring.c +0 -3
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
      req->ring_queue = queue;
      ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                     struct fuse_ring_ent, list);
-     if (ent)
-             fuse_uring_add_req_to_ring_ent(ent, req);
-     else

fs/fuse/dev_uring.c void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req) · line 1588

Quoted 10 lines
fs/fuse/dev_uring.c +8 -2
-             list_add_tail(&req->list, &queue->fuse_req_queue);
-     spin_unlock(&queue->lock);
+     if (ent) {
+             if (!fuse_uring_prep_buffer(ent, req)) {
+                     fuse_uring_add_req_to_ring_ent(ent, req);
+                     spin_unlock(&queue->lock);
+                     fuse_uring_dispatch_ent(ent);
+                     return;
+             }
+     }

Pure style, somehow "if (!fuse_uring_prep_buffer(ent, req))" reads like an error case, *maybe*

        ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                       struct fuse_ring_ent, list);
        /* no idle entry, or no free pool buffer for this req */
        if (!ent || fuse_uring_prep_buffer(ent, req)) {
                list_add_tail(&req->list, &queue->fuse_req_queue);
                spin_unlock(&queue->lock);
                return;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        spin_unlock(&queue->lock);
        fuse_uring_dispatch_ent(ent);
        return;

err_unlock:
...

and similar in fuse_uring_ent_assign_req()

        req = list_first_entry_or_null(req_queue, struct fuse_req, list);
        if (!req || fuse_uring_next_req_update_buffer(ent, req)) {
                fuse_uring_recycle_buffer(ent);
                return NULL;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        return req;
Quoted 2 lines

Just a pure style suggestion, though.

Happy to make this change. Thanks for reviewing the patches. I'll wait until you have finished reviewing the other patches in this series before sending this.

Quoted 38 lines
Quoted 18 lines
fs/fuse/dev_uring_i.h +12 -2
-     if (ent)
-             fuse_uring_dispatch_ent(ent);
+     list_add_tail(&req->list, &queue->fuse_req_queue);
+     spin_unlock(&queue->lock);
 
      return;
 
+struct fuse_bufpool {
+     /* starting uaddr of the bufpool */
+     uintptr_t base_uaddr;
+
+     /* size of each buffer in the pool */
+     size_t buf_size;
+
+     /* total number of buffers in the pool */
+     unsigned int nr_bufs;
+

fs/fuse/dev_uring_i.h enum fuse_ring_req_state { · line 69

Quoted 10 lines
fs/fuse/dev_uring_i.h +5 -1
+     /* bitmap tracking which buffers are free */
+     unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
      /* userspace buffer */
      struct fuse_uring_req_header __user *headers;
-     void __user *payload;
+     struct iovec payload;

Here I have a real concern. What is if fuse server sets up really really large buffers, to thrash the CPUs?

setup_fuse_copy_state() is now changed to

fs/fuse/dev_uring.c +2 -1
-       err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+       err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+                         iter);
Quoted 6 lines

And the iov is taken as it from the SQE. Is there actually a really good reason to have the payload as iov, at least in this series? I could imagine it might make sense to have it as iov once we make the buf pools more dynamically usable.

Could we restrict setup_fuse_copy_state() to ring->max_payload_sz?

Quoted 12 lines

The payload.iov fields are not taken directly from the bufpool sqe. It is assigned in fuse_uring_select_buffer() to reflect one buffer within the pool. ent->payload.iov_len is set to pool->buf_size, which in fuse_uring_add_bufpool(), we set pool->buf_size to be ring->max_payload_sz. Looking at import_ubuf() though, even if we did pass in the entire buffer pool size here, it is harmless, as the bytes copied are already limited/determined by the request (eg on the send-side, copies are bound by in-arg sizes and on the reply side, fuse_copy_out_args() rejects any payload_sz exceeding sum of the out args before doing any copying). Right now pools hand out buffers of the same size so iov_len tracking isn't needed, but pools will be handing out differently-sized buffers.

Yeah, I noticed later that it is actually not an issue, but had already disassembled my equipment and didn't manage to reply before now.

Quoted 30 lines
Quoted 20 lines
Quoted 20 lines
fs/fuse/dev_uring_i.h +3 -0
+
+     /* buffer id in the pool, if bufpools are used. ignored otherwise */
+     unsigned int buf_id;
include/uapi/linux/fuse.h +5 -0
index cfb055c0c764..f7173b5d4321 100644
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
      /* queue the command is for (queue index) */
      uint16_t qid;
      uint8_t padding[6];
+
+     union {
+             struct {
+                     /* base address of bufpool */
+                     uint64_t uaddr;
Quoted 9 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1331

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+                     uint32_t len;
+             } bufpool;

Ok, if we ever want to add a new bufpool, I guess we could invent "struct { } bufpool2;". Personally I would have preferred to have an index in here, currently always set to 0, but not a strict requirement.

Quoted 5 lines

If we ever want to add a new bufpool, I think it'd be cleaner for the kernel to assign the bufpool id and pass it back in the cqe to the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd rather than the server assigning it. With server-supplied indexes, we would have to also track / prevent collisions, gaps, out-of-range values, etc.

Dunno what your plans with that are, but I would take that number as opaque user-space identifier and not something to be used by fuse kernel. In my mind without coding, I would put the bufpools into a list without an index that fuse kernel would use. IMHO it only needs to check if any pool in the list has free bufs.
Anyway, while I would prefer to have the userspace identifier in the struct, that is not a blocker and we can add it in bufpool2 when we have actual usage. Or userspace needs to use the identfier from io-uring and we use that, as you suggest.

Thanks,
Bernd

author maintainer
#16 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

Quoted 161 lines · Bernd Schubert
Quoted 106 lines · Joanne Koong
Quoted 53 lines · Bernd Schubert
Quoted 10 lines · Joanne Koong
fs/fuse/dev_uring.c +0 -3
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
      req->ring_queue = queue;
      ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                     struct fuse_ring_ent, list);
-     if (ent)
-             fuse_uring_add_req_to_ring_ent(ent, req);
-     else

fs/fuse/dev_uring.c void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req) · line 1588

Quoted 10 lines
fs/fuse/dev_uring.c +8 -2
-             list_add_tail(&req->list, &queue->fuse_req_queue);
-     spin_unlock(&queue->lock);
+     if (ent) {
+             if (!fuse_uring_prep_buffer(ent, req)) {
+                     fuse_uring_add_req_to_ring_ent(ent, req);
+                     spin_unlock(&queue->lock);
+                     fuse_uring_dispatch_ent(ent);
+                     return;
+             }
+     }

Pure style, somehow "if (!fuse_uring_prep_buffer(ent, req))" reads like an error case, *maybe*

        ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                       struct fuse_ring_ent, list);
        /* no idle entry, or no free pool buffer for this req */
        if (!ent || fuse_uring_prep_buffer(ent, req)) {
                list_add_tail(&req->list, &queue->fuse_req_queue);
                spin_unlock(&queue->lock);
                return;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        spin_unlock(&queue->lock);
        fuse_uring_dispatch_ent(ent);
        return;

err_unlock:
...

and similar in fuse_uring_ent_assign_req()

        req = list_first_entry_or_null(req_queue, struct fuse_req, list);
        if (!req || fuse_uring_next_req_update_buffer(ent, req)) {
                fuse_uring_recycle_buffer(ent);
                return NULL;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        return req;
Quoted 2 lines

Just a pure style suggestion, though.

Happy to make this change. Thanks for reviewing the patches. I'll wait until you have finished reviewing the other patches in this series before sending this.

Quoted 38 lines
Quoted 18 lines
fs/fuse/dev_uring_i.h +12 -2
-     if (ent)
-             fuse_uring_dispatch_ent(ent);
+     list_add_tail(&req->list, &queue->fuse_req_queue);
+     spin_unlock(&queue->lock);
 
      return;
 
+struct fuse_bufpool {
+     /* starting uaddr of the bufpool */
+     uintptr_t base_uaddr;
+
+     /* size of each buffer in the pool */
+     size_t buf_size;
+
+     /* total number of buffers in the pool */
+     unsigned int nr_bufs;
+

fs/fuse/dev_uring_i.h enum fuse_ring_req_state { · line 69

Quoted 10 lines
fs/fuse/dev_uring_i.h +5 -1
+     /* bitmap tracking which buffers are free */
+     unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
      /* userspace buffer */
      struct fuse_uring_req_header __user *headers;
-     void __user *payload;
+     struct iovec payload;

Here I have a real concern. What is if fuse server sets up really really large buffers, to thrash the CPUs?

setup_fuse_copy_state() is now changed to

fs/fuse/dev_uring.c +2 -1
-       err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+       err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+                         iter);
Quoted 6 lines

And the iov is taken as it from the SQE. Is there actually a really good reason to have the payload as iov, at least in this series? I could imagine it might make sense to have it as iov once we make the buf pools more dynamically usable.

Could we restrict setup_fuse_copy_state() to ring->max_payload_sz?

Quoted 12 lines

The payload.iov fields are not taken directly from the bufpool sqe. It is assigned in fuse_uring_select_buffer() to reflect one buffer within the pool. ent->payload.iov_len is set to pool->buf_size, which in fuse_uring_add_bufpool(), we set pool->buf_size to be ring->max_payload_sz. Looking at import_ubuf() though, even if we did pass in the entire buffer pool size here, it is harmless, as the bytes copied are already limited/determined by the request (eg on the send-side, copies are bound by in-arg sizes and on the reply side, fuse_copy_out_args() rejects any payload_sz exceeding sum of the out args before doing any copying). Right now pools hand out buffers of the same size so iov_len tracking isn't needed, but pools will be handing out differently-sized buffers.

Yeah, I noticed later that it is actually not an issue, but had already disassembled my equipment and didn't manage to reply before now.

Quoted 30 lines
Quoted 20 lines
Quoted 20 lines
fs/fuse/dev_uring_i.h +3 -0
+
+     /* buffer id in the pool, if bufpools are used. ignored otherwise */
+     unsigned int buf_id;
include/uapi/linux/fuse.h +5 -0
index cfb055c0c764..f7173b5d4321 100644
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
      /* queue the command is for (queue index) */
      uint16_t qid;
      uint8_t padding[6];
+
+     union {
+             struct {
+                     /* base address of bufpool */
+                     uint64_t uaddr;
Quoted 9 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1331

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+                     uint32_t len;
+             } bufpool;

Ok, if we ever want to add a new bufpool, I guess we could invent "struct { } bufpool2;". Personally I would have preferred to have an index in here, currently always set to 0, but not a strict requirement.

Quoted 5 lines

If we ever want to add a new bufpool, I think it'd be cleaner for the kernel to assign the bufpool id and pass it back in the cqe to the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd rather than the server assigning it. With server-supplied indexes, we would have to also track / prevent collisions, gaps, out-of-range values, etc.

Quoted 9 lines

Dunno what your plans with that are, but I would take that number as opaque user-space identifier and not something to be used by fuse kernel. In my mind without coding, I would put the bufpools into a list without an index that fuse kernel would use. IMHO it only needs to check if any pool in the list has free bufs.
Anyway, while I would prefer to have the userspace identifier in the struct, that is not a blocker and we can add it in bufpool2 when we have actual usage. Or userspace needs to use the identfier from io-uring and we use that, as you suggest.

I don't really have a preference here. I can add a zero-enforced "uint32_t reserved" field in to keep this choice open-ended for now, that could be repurposed to hold an id in the future, if that becomes necessary. Even without this though, I don't think we would need a separate bufpool2 - I think we could just use "flags" to indicate multi-bufpool, and have an "id" field added to the struct.

Thanks,
Joanne

maintainer
#17 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

Quoted 172 lines · Joanne Koong
Quoted 161 lines · Bernd Schubert
Quoted 106 lines · Joanne Koong
Quoted 53 lines · Bernd Schubert
Quoted 10 lines · Joanne Koong
fs/fuse/dev_uring.c +0 -3
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
      req->ring_queue = queue;
      ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                     struct fuse_ring_ent, list);
-     if (ent)
-             fuse_uring_add_req_to_ring_ent(ent, req);
-     else

fs/fuse/dev_uring.c void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req) · line 1588

Quoted 10 lines
fs/fuse/dev_uring.c +8 -2
-             list_add_tail(&req->list, &queue->fuse_req_queue);
-     spin_unlock(&queue->lock);
+     if (ent) {
+             if (!fuse_uring_prep_buffer(ent, req)) {
+                     fuse_uring_add_req_to_ring_ent(ent, req);
+                     spin_unlock(&queue->lock);
+                     fuse_uring_dispatch_ent(ent);
+                     return;
+             }
+     }

Pure style, somehow "if (!fuse_uring_prep_buffer(ent, req))" reads like an error case, *maybe*

        ent = list_first_entry_or_null(&queue->ent_avail_queue,
                                       struct fuse_ring_ent, list);
        /* no idle entry, or no free pool buffer for this req */
        if (!ent || fuse_uring_prep_buffer(ent, req)) {
                list_add_tail(&req->list, &queue->fuse_req_queue);
                spin_unlock(&queue->lock);
                return;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        spin_unlock(&queue->lock);
        fuse_uring_dispatch_ent(ent);
        return;

err_unlock:
...

and similar in fuse_uring_ent_assign_req()

        req = list_first_entry_or_null(req_queue, struct fuse_req, list);
        if (!req || fuse_uring_next_req_update_buffer(ent, req)) {
                fuse_uring_recycle_buffer(ent);
                return NULL;
        }

        fuse_uring_add_req_to_ring_ent(ent, req);
        return req;
Quoted 2 lines

Just a pure style suggestion, though.

Happy to make this change. Thanks for reviewing the patches. I'll wait until you have finished reviewing the other patches in this series before sending this.

Quoted 38 lines
Quoted 18 lines
fs/fuse/dev_uring_i.h +12 -2
-     if (ent)
-             fuse_uring_dispatch_ent(ent);
+     list_add_tail(&req->list, &queue->fuse_req_queue);
+     spin_unlock(&queue->lock);
 
      return;
 
+struct fuse_bufpool {
+     /* starting uaddr of the bufpool */
+     uintptr_t base_uaddr;
+
+     /* size of each buffer in the pool */
+     size_t buf_size;
+
+     /* total number of buffers in the pool */
+     unsigned int nr_bufs;
+

fs/fuse/dev_uring_i.h enum fuse_ring_req_state { · line 69

Quoted 10 lines
fs/fuse/dev_uring_i.h +5 -1
+     /* bitmap tracking which buffers are free */
+     unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
      /* userspace buffer */
      struct fuse_uring_req_header __user *headers;
-     void __user *payload;
+     struct iovec payload;

Here I have a real concern. What is if fuse server sets up really really large buffers, to thrash the CPUs?

setup_fuse_copy_state() is now changed to

fs/fuse/dev_uring.c +2 -1
-       err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+       err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+                         iter);
Quoted 6 lines

And the iov is taken as it from the SQE. Is there actually a really good reason to have the payload as iov, at least in this series? I could imagine it might make sense to have it as iov once we make the buf pools more dynamically usable.

Could we restrict setup_fuse_copy_state() to ring->max_payload_sz?

Quoted 12 lines

The payload.iov fields are not taken directly from the bufpool sqe. It is assigned in fuse_uring_select_buffer() to reflect one buffer within the pool. ent->payload.iov_len is set to pool->buf_size, which in fuse_uring_add_bufpool(), we set pool->buf_size to be ring->max_payload_sz. Looking at import_ubuf() though, even if we did pass in the entire buffer pool size here, it is harmless, as the bytes copied are already limited/determined by the request (eg on the send-side, copies are bound by in-arg sizes and on the reply side, fuse_copy_out_args() rejects any payload_sz exceeding sum of the out args before doing any copying). Right now pools hand out buffers of the same size so iov_len tracking isn't needed, but pools will be handing out differently-sized buffers.

Yeah, I noticed later that it is actually not an issue, but had already disassembled my equipment and didn't manage to reply before now.

Quoted 30 lines
Quoted 20 lines
Quoted 20 lines
fs/fuse/dev_uring_i.h +3 -0
+
+     /* buffer id in the pool, if bufpools are used. ignored otherwise */
+     unsigned int buf_id;
include/uapi/linux/fuse.h +5 -0
index cfb055c0c764..f7173b5d4321 100644
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
      /* queue the command is for (queue index) */
      uint16_t qid;
      uint8_t padding[6];
+
+     union {
+             struct {
+                     /* base address of bufpool */
+                     uint64_t uaddr;
Quoted 9 lines

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1331

Quoted 2 lines
include/uapi/linux/fuse.h +2 -0
+                     uint32_t len;
+             } bufpool;

Ok, if we ever want to add a new bufpool, I guess we could invent "struct { } bufpool2;". Personally I would have preferred to have an index in here, currently always set to 0, but not a strict requirement.

Quoted 5 lines

If we ever want to add a new bufpool, I think it'd be cleaner for the kernel to assign the bufpool id and pass it back in the cqe to the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd rather than the server assigning it. With server-supplied indexes, we would have to also track / prevent collisions, gaps, out-of-range values, etc.

Quoted 9 lines

Dunno what your plans with that are, but I would take that number as opaque user-space identifier and not something to be used by fuse kernel. In my mind without coding, I would put the bufpools into a list without an index that fuse kernel would use. IMHO it only needs to check if any pool in the list has free bufs.
Anyway, while I would prefer to have the userspace identifier in the struct, that is not a blocker and we can add it in bufpool2 when we have actual usage. Or userspace needs to use the identfier from io-uring and we use that, as you suggest.

Quoted 6 lines

I don't really have a preference here. I can add a zero-enforced "uint32_t reserved" field in to keep this choice open-ended for now, that could be repurposed to hold an id in the future, if that becomes necessary. Even without this though, I don't think we would need a separate bufpool2 - I think we could just use "flags" to indicate multi-bufpool, and have an "id" field added to the struct.

I'm also ok with just a flag, we both just need to be make sure that nothing else gets added below the union for ABI compat. On 64 bit systems there should be padding, but 32 bit arch is not excluded. The alternative would be a something like

		 * created with FUSE_URING_ZERO_COPY. On a non-zero-copy queue
		 * this must be 0
		 */
		uint16_t ent_zero_copy_buf_index;

		/* To enforce a specific size for the union on all CPU archs */
		uin64_t for_union_size[2];
	};

Thanks,
Bernd

maintainer Reviewed-by on v6 3/6
#18 lore raw

Re: [PATCH v6 3/6] fuse: add io-uring buffer pools

In reply to Joanne Koong
Quoted 632 lines · Joanne Koong

Right now, ents and buffers are tightly coupled in fuse io-uring where each entry has its own dedicated payload buffer, requiring N buffers for N entries where each buffer must be large enough to accomodate the maximum payload size. This is suboptimal as most request types (lookup, open, release, getattr, etc) require vastly less bytes than the maximum payload size and some requests (unlink, rmdir, fsync, flush, etc) do not require payload buffers at all.

Instead of requiring a 1:1 coupling between ents and payload buffers, allow the server to pass in a buffer pool (a contiguous chunk of memory) that the kernel will use as it wishes for servicing ents/requests. Entries only reserve a "buffer" from the pool while actively processing a request that requires a payload buffer. This decoupling and letting the kernel delegate memory from the pool for requests allows the kernel to optimize memory usage and reduces the memory usage requirements needed to use fuse-over-io-uring.

A pool is registered per queue with the new FUSE_IO_URING_CMD_ADD_BUFPOOL command. The server passes the pool's base address and length in fuse_uring_cmd_req.bufpool.{uaddr,len}.

Internally, the kernel splits the region into buffers of ring->max_payload_sz bytes each (nr_bufs = pool len / max_payload_sz). A queue commits to a payload mode on first use: registering an entry that carries its own payload selects the legacy per-entry mode, while ADD_BUFPOOL selects pool mode. The two are mutually exclusive, so ADD_BUFPOOL must be issued before any payload-carrying entries are registered on that queue. The queue must have been created before the bufpool is added, through the FUSE_IO_URING_CMD_ADD_QUEUE command.

The kernel tracks free buffers with a bitmap (a set bit marks a free buffer). On dispatch, a request that needs a payload claims a free buffer (find_first_bit + clear). A request that needs none claims nothing. The buffer's byte offset within the pool is reported to the server in the new fuse_uring_ent_in_out.offset field so that the server can locate the payload. On completion the buffer is returned to the pool or reused directly if the next request on that entry also has a payload.

The FUSE_HAS_IO_URING_BUFPOOL flag advertises kernel support to the server for bufpools.

Buffer pool request flow
~~~~~~~~~~~~~~~~~~~~~~~~

|  Kernel                                  |  FUSE daemon
|                                          |
|  [request arrives]                       |
|    [claim a free pool buffer]            |
|    >fuse_uring_select_buffer()           |
|    [copy headers to ring]                |
|    [copy payload to buffer]              |
|    [report buffer offset in ent_in_out]  |
|    >io_uring_cmd_done()                  |
|                                          |  [read headers]
|                                          |  [read/write payload at offset]
|                                          |  [process request]
|                                          |  >io_uring_submit()
|                                          |   COMMIT_AND_FETCH
|  >fuse_uring_commit_fetch()              |
|    [copy reply from ring]                |
|    [return buffer to the pool]           |
|    >fuse_uring_recycle_buffer()          |
---
 fs/fuse/dev_uring.c       | 237 +++++++++++++++++++++++++++++++++-----
 fs/fuse/dev_uring_i.h     |  37 +++++-
 fs/fuse/inode.c           |   2 +-
 include/uapi/linux/fuse.h |  20 +++-
 4 files changed, 266 insertions(+), 30 deletions(-)
fs/fuse/dev_uring.c +210 -27
index fdf1058e582c..e9da92b46090 100644
@@ -9,6 +9,7 @@
 #include "dev_uring_i.h"
 #include "fuse_trace.h"
 
+#include <linux/bitmap.h>
 #include <linux/fs.h>
 #include <linux/io_uring/cmd.h>
 
@@ -41,6 +42,11 @@ enum fuse_uring_header_type {
 	FUSE_URING_HEADER_RING_ENT,
 };
 
+static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
+{
+	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -222,6 +228,7 @@ void fuse_uring_destruct(struct fuse_chan *fch)
 		}
 
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		ring->queues[qid] = NULL;
 	}
@@ -316,6 +323,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 	if (ring->queues[qid]) {
 		spin_unlock(&fch->lock);
 		kfree(queue->fpq.processing);
+		kfree(queue->bufpool);
 		kfree(queue);
 		return fail_if_exists ? ERR_PTR(-EEXIST) : ring->queues[qid];
 	}
@@ -646,13 +654,14 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 }
 
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
-				 struct fuse_ring *ring, struct fuse_req *req,
+				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
 				 struct iov_iter *iter)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload, ring->max_payload_sz, iter);
+	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
+			  iter);
 	if (err) {
 		pr_info_ratelimited("fuse: Import of user buffer failed\n");
 		return err;
@@ -666,8 +675,7 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 	return 0;
 }
 
-static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
-				     struct fuse_req *req,
+static int fuse_uring_copy_from_ring(struct fuse_req *req,
 				     struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -681,7 +689,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
 	if (err)
 		return err;
 
@@ -693,7 +701,7 @@ static int fuse_uring_copy_from_ring(struct fuse_ring *ring,
 /*
  * Copy data from the req to the ring buffer
  */
-static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
+static int fuse_uring_args_to_ring(struct fuse_req *req,
 				   struct fuse_ring_ent *ent)
 {
 	struct fuse_copy_state cs;
@@ -707,7 +715,7 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, ring, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
 	if (err)
 		return err;
 
@@ -737,6 +745,10 @@ static int fuse_uring_args_to_ring(struct fuse_ring *ring, struct fuse_req *req,
 	}
 
 	ent_in_out.payload_sz = cs.ring.copied_sz;
+	if (bufpool_enabled(ent->queue) && ent->payload.iov_base)
+		ent_in_out.offset =
+			(uintptr_t)ent->payload.iov_base - ent->queue->bufpool->base_uaddr;
+
 	return copy_header_to_ring(ent, FUSE_URING_HEADER_RING_ENT,
 				   &ent_in_out, sizeof(ent_in_out));
 }
@@ -745,7 +757,6 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
 	struct fuse_ring_queue *queue = ent->queue;
-	struct fuse_ring *ring = queue->ring;
 	int err;
 
 	err = -EIO;
@@ -760,7 +771,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(ring, req, ent);
+	err = fuse_uring_args_to_ring(req, ent);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -771,6 +782,91 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 				   sizeof(req->in.h));
 }
 
+static bool fuse_uring_req_has_payload(struct fuse_req *req)
+{
+	struct fuse_args *args = req->args;
+
+	return args->in_numargs > 1 || args->out_numargs;
+}
+
+static int fuse_uring_select_buffer(struct fuse_ring_ent *ent)
+{
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool = queue->bufpool;
+	unsigned int id;
+
+	lockdep_assert_held(&queue->lock);
+
+	id = find_first_bit(pool->free_map, pool->nr_bufs);
+	if (id >= pool->nr_bufs)
+		return -ENOBUFS;
+
+	WARN_ON_ONCE(ent->payload.iov_base);
+	__clear_bit(id, pool->free_map);
+
+	ent->buf_id = id;
+	ent->payload.iov_base =
+		(void __user *)(pool->base_uaddr + id * pool->buf_size);
+	ent->payload.iov_len = pool->buf_size;
+
+	return 0;
+}
+
+static void fuse_uring_recycle_buffer(struct fuse_ring_ent *ent)
+{
+	struct iovec *ent_payload = &ent->payload;
+	struct fuse_ring_queue *queue = ent->queue;
+	struct fuse_bufpool *pool;
+
+	lockdep_assert_held(&queue->lock);
+
+	if (!bufpool_enabled(queue) || !ent_payload->iov_base)
+		return;
+
+	pool = queue->bufpool;
+
+	/* a buffer should never be recycled twice */
+	WARN_ON_ONCE(test_bit(ent->buf_id, pool->free_map));
+	__set_bit(ent->buf_id, pool->free_map);
+
+	memset(ent_payload, 0, sizeof(*ent_payload));
+	ent->buf_id = 0;
+}
+
+static int fuse_uring_next_req_update_buffer(struct fuse_ring_ent *ent,
+					     struct fuse_req *req)
+{
+	bool buffer_selected;
+	bool has_payload;
+
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	buffer_selected = !!ent->payload.iov_base;
+	has_payload = fuse_uring_req_has_payload(req);
+
+	if (has_payload && !buffer_selected)
+		return fuse_uring_select_buffer(ent);
+
+	if (!has_payload && buffer_selected)
+		fuse_uring_recycle_buffer(ent);
+
+	return 0;
+}
+
+static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
+				  struct fuse_req *req)
+{
+	if (!bufpool_enabled(ent->queue))
+		return 0;
+
+	/* no payload to copy, can skip selecting a buffer */
+	if (!fuse_uring_req_has_payload(req))
+		return 0;
+
+	return fuse_uring_select_buffer(ent);
+}
+
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
 				   struct fuse_req *req)
 {
@@ -858,10 +954,13 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 
 	/* get and assign the next entry while it is still holding the lock */
 	req = list_first_entry_or_null(req_queue, struct fuse_req, list);
-	if (req)
+	if (req && !fuse_uring_next_req_update_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
+		return req;
+	}
 
-	return req;
+	fuse_uring_recycle_buffer(ent);
+	return NULL;
 }
 
 /*
@@ -872,7 +971,6 @@ static struct fuse_req *fuse_uring_ent_assign_req(struct fuse_ring_ent *ent)
 static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 			      unsigned int issue_flags)
 {
-	struct fuse_ring *ring = ent->queue->ring;
 	ssize_t err = -EFAULT;
 
 	if (copy_header_from_ring(ent, FUSE_URING_HEADER_IN_OUT, &req->out.h,
@@ -885,7 +983,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(ring, req, ent);
+	err = fuse_uring_copy_from_ring(req, ent);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -1004,6 +1102,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	if (err != 0) {
 		pr_info_ratelimited("qid=%d commit_id %llu state %d",
 				    queue->qid, commit_id, ent->state);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 		fuse_uring_req_end(ent, req, err);
 		return err;
@@ -1021,6 +1120,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * fuse requests would otherwise not get processed - committing
 	 * and fetching is done in one step vs legacy fuse, which has separated
 	 * read (fetch request) and write (commit result).
+	 *
+	 * If there is no next request or if all buffers are busy (if using a
+	 * bufpool), the cmd is not returned to userspace. The entry is left
+	 * available and the cmd only returns to userspace when there's a
+	 * next request and an available buffer.
 	 */
 	if (fuse_uring_get_next_fuse_req(ent, queue))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
@@ -1145,11 +1249,23 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 	}
 
 	payload = &iov[FUSE_URING_IOV_PAYLOAD];
-	if (payload->iov_len < ring->max_payload_sz) {
-		pr_info_ratelimited("Invalid req payload len %zu\n",
-				    payload->iov_len);
-		return ERR_PTR(err);
+
+	spin_lock(&queue->lock);
+	if (bufpool_enabled(queue)) {
+		if (payload->iov_base || payload->iov_len) {
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+	} else {
+		if (payload->iov_len < ring->max_payload_sz) {
+			pr_info_ratelimited("Invalid req payload len %zu\n",
+					    payload->iov_len);
+			spin_unlock(&queue->lock);
+			return ERR_PTR(err);
+		}
+		queue->payload_mode = FUSE_PAYLOAD_PER_ENT;
 	}
+	spin_unlock(&queue->lock);
 
 	err = -ENOMEM;
 	ent = kzalloc_obj(*ent, GFP_KERNEL_ACCOUNT);
@@ -1160,7 +1276,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	ent->queue = queue;
 	ent->headers = headers->iov_base;
-	ent->payload = payload->iov_base;
+	if (queue->payload_mode == FUSE_PAYLOAD_PER_ENT)
+		ent->payload = *payload;
 
 	atomic_inc(&ring->queue_refs);
 	return ent;
@@ -1231,6 +1348,63 @@ static int fuse_uring_add_queue(struct io_uring_cmd *cmd, struct fuse_chan *fch)
 	return 0;
 }
 
+static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
+				  struct fuse_chan *fch)
+{
+	const struct fuse_uring_cmd_req *cmd_req =
+		io_uring_sqe128_cmd(cmd->sqe, struct fuse_uring_cmd_req);
+	unsigned int qid = READ_ONCE(cmd_req->qid);
+	uint64_t flags = READ_ONCE(cmd_req->flags);
+	/* paired with the smp_store_release() in fuse_uring_create */
+	struct fuse_ring *ring = smp_load_acquire(&fch->ring);
+	struct fuse_ring_queue *queue;
+	struct fuse_bufpool *pool;
+	uintptr_t pool_uaddr;
+	unsigned int pool_len, nr_bufs;
+	size_t pool_size, buf_size;
+
+	if (!ring || qid >= ring->nr_queues || flags)
+		return -EINVAL;
+
+	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
+	queue = smp_load_acquire(&ring->queues[qid]);
+	if (!queue)
+		return -EINVAL;
+
+	pool_uaddr = READ_ONCE(cmd_req->bufpool.uaddr);
+	pool_len = READ_ONCE(cmd_req->bufpool.len);
+
+	/* each buffer holds the max payload size */
+	buf_size = queue->ring->max_payload_sz;
+
+	nr_bufs = pool_len / buf_size;
+	if (!nr_bufs)
+		return -EINVAL;
+
+	pool_size = struct_size(pool, free_map, BITS_TO_LONGS(nr_bufs));
+	pool = kzalloc(pool_size, GFP_KERNEL_ACCOUNT);
+	if (!pool)
+		return -ENOMEM;
+
+	pool->base_uaddr = pool_uaddr;
+	pool->buf_size = buf_size;
+	pool->nr_bufs = nr_bufs;
+	/* all buffers are free */
+	bitmap_set(pool->free_map, 0, nr_bufs);
+
+	spin_lock(&queue->lock);
+	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
+		spin_unlock(&queue->lock);
+		kfree(pool);
+		return -EINVAL;
+	}
+	queue->bufpool = pool;
+	queue->payload_mode = FUSE_PAYLOAD_BUFPOOL;
+	spin_unlock(&queue->lock);
+
+	return 0;
+}
+
 /*
  * Entry function from io_uring to handle the given passthrough command
  * (op code IORING_OP_URING_CMD)
@@ -1303,6 +1477,12 @@ int fuse_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)
 			pr_info_once("FUSE_IO_URING_CMD_ADD_QUEUE failed err=%d\n",
 				     err);
 		return err;
+	case FUSE_IO_URING_CMD_ADD_BUFPOOL:
+		err = fuse_uring_add_bufpool(cmd, fch);
+		if (err)
+			pr_info_once("FUSE_IO_URING_ADD_BUFPOOL failed err=%d\n",
+				     err);
+		return err;
 	default:
 		return -EINVAL;
 	}
@@ -1336,6 +1516,7 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 
 		spin_lock(&queue->lock);
 		list_del_init(&ent->list);
+		fuse_uring_recycle_buffer(ent);
 		spin_unlock(&queue->lock);
 
 		io_uring_cmd_done(cmd, err, issue_flags);
@@ -1397,14 +1578,17 @@ void fuse_uring_queue_fuse_req(struct fuse_iqueue *fiq, struct fuse_req *req)
 	req->ring_queue = queue;
 	ent = list_first_entry_or_null(&queue->ent_avail_queue,
 				       struct fuse_ring_ent, list);
-	if (ent)
-		fuse_uring_add_req_to_ring_ent(ent, req);
-	else
-		list_add_tail(&req->list, &queue->fuse_req_queue);
-	spin_unlock(&queue->lock);
+	if (ent) {
+		if (!fuse_uring_prep_buffer(ent, req)) {
+			fuse_uring_add_req_to_ring_ent(ent, req);
+			spin_unlock(&queue->lock);
+			fuse_uring_dispatch_ent(ent);
+			return;
+		}
+	}
 
-	if (ent)
-		fuse_uring_dispatch_ent(ent);
+	list_add_tail(&req->list, &queue->fuse_req_queue);
+	spin_unlock(&queue->lock);
 
 	return;
 
@@ -1453,10 +1637,9 @@ bool fuse_uring_queue_bq_req(struct fuse_req *req)
 	 */
 	req = list_first_entry_or_null(&queue->fuse_req_queue, struct fuse_req,
 				       list);
-	if (ent && req) {
+	if (ent && req && !fuse_uring_prep_buffer(ent, req)) {
 		fuse_uring_add_req_to_ring_ent(ent, req);
 		spin_unlock(&queue->lock);
-
 		fuse_uring_dispatch_ent(ent);
 	} else {
 		spin_unlock(&queue->lock);
fs/fuse/dev_uring_i.h +36 -1
index d721a4fc0215..cdf56f8b38b5 100644
@@ -7,6 +7,8 @@
 #ifndef _FS_FUSE_DEV_URING_I_H
 #define _FS_FUSE_DEV_URING_I_H
 
+#include <linux/uio.h>
+
 #include "fuse_dev_i.h"
 
 #ifdef CONFIG_FUSE_IO_URING
@@ -36,11 +38,38 @@ enum fuse_ring_req_state {
 	FRRS_RELEASED,
 };
 
+/* how a queue's payload buffers are provided */
+enum fuse_queue_payload_mode {
+	/* not yet committed (a bufpool may still be added) */
+	FUSE_PAYLOAD_UNSET = 0,
+	/* each entry registers its own payload buffer */
+	FUSE_PAYLOAD_PER_ENT,
+	/* each entry's payload buffer is assigned from a bufpool */
+	FUSE_PAYLOAD_BUFPOOL,
+};
+
+struct fuse_bufpool {
+	/* starting uaddr of the bufpool */
+	uintptr_t base_uaddr;
+
+	/* size of each buffer in the pool */
+	size_t buf_size;
+
+	/* total number of buffers in the pool */
+	unsigned int nr_bufs;
+
+	/* bitmap tracking which buffers are free */
+	unsigned long free_map[];
+};
+
 /** A fuse ring entry, part of the ring queue */
 struct fuse_ring_ent {
 	/* userspace buffer */
 	struct fuse_uring_req_header __user *headers;
-	void __user *payload;
+	struct iovec payload;
+
+	/* buffer id in the pool, if bufpools are used. ignored otherwise */
+	unsigned int buf_id;
 
 	/* the ring queue that owns the request */
 	struct fuse_ring_queue *queue;
@@ -99,6 +128,12 @@ struct fuse_ring_queue {
 	unsigned int active_background;
 
 	bool stopped;
+
+	/* how this queue's payload buffers are provided */
+	enum fuse_queue_payload_mode payload_mode;
+
+	/* only allocated when payload_mode == FUSE_PAYLOAD_BUFPOOL */
+	struct fuse_bufpool *bufpool;
 };
 
 /*
fs/fuse/inode.c +1 -1
index ce4891a04a37..929ddbea0eb0 100644
@@ -1481,7 +1481,7 @@ static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
 	 * the reply - server is either sending IORING_OP_URING_CMD or not.
 	 */
 	if (fuse_uring_enabled())
-		flags |= FUSE_OVER_IO_URING;
+		flags |= FUSE_OVER_IO_URING | FUSE_HAS_IO_URING_BUFPOOL;
 
 	ia->in.flags = flags;
 	ia->in.flags2 = flags >> 32;
include/uapi/linux/fuse.h +12 -1
index cfb055c0c764..f7173b5d4321 100644
@@ -243,6 +243,9 @@
  *
  *  7.46
  *  - add FUSE_IO_URING_CMD_ADD_QUEUE
+ *  - add FUSE_HAS_IO_URING_BUFPOOL
+ *  - add fuse_uring_cmd_req bufpool struct
+ *  - add bufpool offset field to fuse_uring_ent_in_out struct
  */
 
 #ifndef _LINUX_FUSE_H
@@ -451,6 +454,7 @@ struct fuse_file_lock {
  * FUSE_OVER_IO_URING: Indicate that client supports io-uring
  * FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
  *			 init_out.request_timeout contains the timeout (in secs)
+ * FUSE_HAS_IO_URING_BUFPOOL: kernel supports io-uring buffer pools
  */
 #define FUSE_ASYNC_READ		(1 << 0)
 #define FUSE_POSIX_LOCKS	(1 << 1)
@@ -498,6 +502,7 @@ struct fuse_file_lock {
 #define FUSE_ALLOW_IDMAP	(1ULL << 40)
 #define FUSE_OVER_IO_URING	(1ULL << 41)
 #define FUSE_REQUEST_TIMEOUT	(1ULL << 42)
+#define FUSE_HAS_IO_URING_BUFPOOL (1ULL << 43)
 
 /**
  * CUSE INIT request/reply flags
@@ -1266,7 +1271,9 @@ struct fuse_uring_ent_in_out {
 
 	/* size of user payload buffer */
 	uint32_t payload_sz;
-	uint32_t padding;
+
+	/* Offset into the bufpool, if bufpools are used */
+	uint32_t offset;
 
 	uint64_t reserved;
 };
@@ -1298,6 +1305,9 @@ enum fuse_uring_cmd {
 
 	/* add a queue */
 	FUSE_IO_URING_CMD_ADD_QUEUE = 3,
+
+	/* add a bufpool to a queue */
+	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
 /**
@@ -1312,6 +1322,14 @@ struct fuse_uring_cmd_req {
 	/* queue the command is for (queue index) */
 	uint16_t qid;
 	uint8_t padding[6];
+

include/uapi/linux/fuse.h struct fuse_uring_cmd_req { · line 1335

Quoted 10 lines
include/uapi/linux/fuse.h +7 -0
+	union {
+		struct {
+			/* base address of bufpool */
+			uint64_t uaddr;
+			uint32_t len;
+		} bufpool;
+	};
 };
 
 #endif /* _LINUX_FUSE_H */
author maintainer
#19 lore raw

PATCH v6 4/6 fuse: support registered buffer pools in io-uring

In reply to Joanne Koong

Allow servers to use a buffer pool that is also registered through io-uring. When the server registers a buffer pool with io-uring, the pages backing the pool are pinned upfront. This eliminates the overhead of pinning/unpinning user pages and translating virtual addresses per i/o request. This also allows servers to use the same registered memory for subsequent backing store I/O (eg read_fixed/write_fixed), keeping data in the same pinned pages without additional pinning or mapping overhead required.

To use this, the server needs to set the FUSE_URING_REGISTERED_BUFPOOL flag when adding a bufpool through the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd. For every sqe submitted (including the one for adding the bufpool), it should set sqe->uring_cmd_flags to include IORING_URING_CMD_FIXED, and pass in the index where the registered bufpool resides to sqe->buf_index.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

		    baseline      registered buffers
  direct read       ~5.1 GB/s     ~5.4 GB/s   (+~5%)
  direct write      ~3.4 GB/s     ~4.8 GB/s   (+~45%)

Registered buffers bring up the write path speed up closer to speed of reads. There isn't much improvement for reads because it is already fast enough where it's at the copy-bound ceiling (surpassing that requires doing zero-copy). On a device-bound NVMe though, the differences are within noise, as backing I/O dominates per-request latency.

---
 fs/fuse/dev_uring.c       | 122 +++++++++++++++++++++++++++++++-------
 fs/fuse/dev_uring_i.h     |   8 +++
 include/uapi/linux/fuse.h |   4 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
fs/fuse/dev_uring.c +100 -22
index e9da92b46090..ed7e783bd68d 100644
@@ -22,6 +22,8 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_HEADERS 0
 #define FUSE_URING_IOV_PAYLOAD 1
 
+#define FUSE_URING_ADD_BUFPOOL_FLAGS	(FUSE_URING_REGISTERED_BUFPOOL)
+
 bool fuse_uring_enabled(void)
 {
 	return enable_uring;
@@ -47,6 +49,27 @@ static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
 	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
 }
 
+static inline bool bufpool_registered(struct fuse_ring_queue *queue)
+{
+	return queue->bufpool && queue->bufpool->registered;
+}
+
+/*
+ * For a registered bufpool, every sqe that drives a payload import (REGISTER,
+ * COMMIT_AND_FETCH) must carry the registered buffer index of the pool.
+ * This also must be called from the command's issue handler, where cmd->sqe is
+ * still valid
+ */
+static inline bool fuse_uring_cmd_index_ok(struct io_uring_cmd *cmd,
+					   struct fuse_ring_queue *queue)
+{
+	if (!bufpool_registered(queue))
+		return true;
+
+	return (cmd->flags & IORING_URING_CMD_FIXED) &&
+	       READ_ONCE(cmd->sqe->buf_index) == queue->bufpool->registered_index;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -653,19 +676,42 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 	return 0;
 }
 
+static int fuse_uring_import_payload(struct fuse_ring_ent *ent, int dir,
+				     struct iov_iter *iter,
+				     unsigned int issue_flags)
+{
+	void __user *base = ent->payload.iov_base;
+	size_t len = ent->payload.iov_len;
+	int err = 0;
+
+	if (!base) {
+		memset(iter, 0, sizeof(*iter));
+		return 0;
+	}
+
+	if (bufpool_registered(ent->queue))
+		err = io_uring_cmd_import_fixed((u64)(uintptr_t)base, len, dir,
+						iter, ent->cmd, issue_flags);
+	else
+		err = import_ubuf(dir, base, len, iter);
+
+	if (err)
+		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+
+	return err;
+}
+
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
-				 struct iov_iter *iter)
+				 struct iov_iter *iter,
+				 unsigned int issue_flags)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
-			  iter);
-	if (err) {
-		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+	err = fuse_uring_import_payload(ent, dir, iter, issue_flags);
+	if (err)
 		return err;
-	}
 
 	fuse_copy_init(cs, dir == ITER_DEST, iter);
 
@@ -676,7 +722,8 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 }
 
 static int fuse_uring_copy_from_ring(struct fuse_req *req,
-				     struct fuse_ring_ent *ent)
+				     struct fuse_ring_ent *ent,
+				     unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -689,7 +736,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -702,7 +750,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
  * Copy data from the req to the ring buffer
  */
 static int fuse_uring_args_to_ring(struct fuse_req *req,
-				   struct fuse_ring_ent *ent)
+				   struct fuse_ring_ent *ent,
+				   unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -715,7 +764,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -754,7 +804,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 }
 
 static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	struct fuse_ring_queue *queue = ent->queue;
 	int err;
@@ -771,7 +822,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(req, ent);
+	err = fuse_uring_args_to_ring(req, ent, issue_flags);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -868,11 +919,12 @@ static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
 }
 
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	int err;
 
-	err = fuse_uring_copy_to_ring(ent, req);
+	err = fuse_uring_copy_to_ring(ent, req, issue_flags);
 	if (!err) {
 		set_bit(FR_SENT, &req->flags);
 		trace_fuse_request_sent(req);
@@ -983,7 +1035,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(req, ent);
+	err = fuse_uring_copy_from_ring(req, ent, issue_flags);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -995,7 +1047,8 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
  * Else, there is no next fuse request and this returns false.
  */
 static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
-					 struct fuse_ring_queue *queue)
+					 struct fuse_ring_queue *queue,
+					 unsigned int issue_flags)
 {
 	int err;
 	struct fuse_req *req;
@@ -1007,7 +1060,7 @@ static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
 	spin_unlock(&queue->lock);
 
 	if (req) {
-		err = fuse_uring_prepare_send(ent, req);
+		err = fuse_uring_prepare_send(ent, req, issue_flags);
 		if (err)
 			goto retry;
 	}
@@ -1081,6 +1134,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 		return err;
 	}
 
+	if (!fuse_uring_cmd_index_ok(cmd, queue)) {
+		spin_unlock(&queue->lock);
+		return -EINVAL;
+	}
+
 	/* Find a request based on the unique ID of the fuse request
 	 * This should get revised, as it needs a hash calculation and list
 	 * search. And full struct fuse_pqueue is needed (memory overhead).
@@ -1126,7 +1184,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * available and the cmd only returns to userspace when there's a
 	 * next request and an available buffer.
 	 */
-	if (fuse_uring_get_next_fuse_req(ent, queue))
+	if (fuse_uring_get_next_fuse_req(ent, queue, issue_flags))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
 	return 0;
 }
@@ -1252,7 +1310,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	spin_lock(&queue->lock);
 	if (bufpool_enabled(queue)) {
-		if (payload->iov_base || payload->iov_len) {
+		if (payload->iov_base || payload->iov_len ||
+		    !fuse_uring_cmd_index_ok(cmd, queue)) {
 			spin_unlock(&queue->lock);
 			return ERR_PTR(err);
 		}
@@ -1362,8 +1421,21 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	uintptr_t pool_uaddr;
 	unsigned int pool_len, nr_bufs;
 	size_t pool_size, buf_size;
+	bool registered = flags & FUSE_URING_REGISTERED_BUFPOOL;
+
+	if (!ring || qid >= ring->nr_queues)
+		return -EINVAL;
 
-	if (!ring || qid >= ring->nr_queues || flags)
+	if (flags & ~FUSE_URING_ADD_BUFPOOL_FLAGS)
+		return -EINVAL;
+
+	/*
+	 * A registered bufpool is reached through an io_uring fixed buffer, so
+	 * this command must be submitted with IORING_URING_CMD_FIXED and the
+	 * registered buffer index in sqe->buf_index. That index is recorded
+	 * below and enforced on every REGISTER / COMMIT_AND_FETCH sqe.
+	 */
+	if (registered && !(cmd->flags & IORING_URING_CMD_FIXED))
 		return -EINVAL;
 
 	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
@@ -1392,6 +1464,11 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	/* all buffers are free */
 	bitmap_set(pool->free_map, 0, nr_bufs);
 
+	if (registered) {
+		pool->registered = true;
+		pool->registered_index = READ_ONCE(cmd->sqe->buf_index);
+	}
+
 	spin_lock(&queue->lock);
 	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
 		spin_unlock(&queue->lock);
@@ -1504,9 +1581,10 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 	int err;
 
 	if (!tw.cancel) {
-		err = fuse_uring_prepare_send(ent, ent->fuse_req);
+		err = fuse_uring_prepare_send(ent, ent->fuse_req, issue_flags);
 		if (err) {
-			if (!fuse_uring_get_next_fuse_req(ent, queue))
+			if (!fuse_uring_get_next_fuse_req(ent, queue,
+							  issue_flags))
 				return;
 			err = 0;
 		}
fs/fuse/dev_uring_i.h +8 -0
index cdf56f8b38b5..e142cae43022 100644
@@ -49,6 +49,14 @@ enum fuse_queue_payload_mode {
 };
 
 struct fuse_bufpool {
+	bool registered;
+
+	/*
+	 * io_uring registered buffer table index for this pool, bound at
+	 * ADD_BUFPOOL time. Only valid if the bufpool is registered
+	 */
+	u16 registered_index;
+
 	/* starting uaddr of the bufpool */
 	uintptr_t base_uaddr;
 
include/uapi/linux/fuse.h +4 -0
index f7173b5d4321..07d12f1c55bb 100644
@@ -246,6 +246,7 @@
  *  - add FUSE_HAS_IO_URING_BUFPOOL
  *  - add fuse_uring_cmd_req bufpool struct
  *  - add bufpool offset field to fuse_uring_ent_in_out struct
+ *  - add FUSE_URING_REGISTERED_BUFPOOL flag
  */
 
 #ifndef _LINUX_FUSE_H
@@ -1310,6 +1311,9 @@ enum fuse_uring_cmd {
 	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
+/* fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_BUFPOOL */
+#define FUSE_URING_REGISTERED_BUFPOOL	(1 << 0)
+
 /**
  * In the 80B command area of the SQE.
  */
Signature · 1 line
2.52.0
maintainer
#20 lore raw

Re: [PATCH v6 4/6] fuse: support registered buffer pools in io-uring

Quoted 92 lines · Joanne Koong

Allow servers to use a buffer pool that is also registered through io-uring. When the server registers a buffer pool with io-uring, the pages backing the pool are pinned upfront. This eliminates the overhead of pinning/unpinning user pages and translating virtual addresses per i/o request. This also allows servers to use the same registered memory for subsequent backing store I/O (eg read_fixed/write_fixed), keeping data in the same pinned pages without additional pinning or mapping overhead required.

To use this, the server needs to set the FUSE_URING_REGISTERED_BUFPOOL flag when adding a bufpool through the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd. For every sqe submitted (including the one for adding the bufpool), it should set sqe->uring_cmd_flags to include IORING_URING_CMD_FIXED, and pass in the index where the registered bufpool resides to sqe->buf_index.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

		    baseline      registered buffers
  direct read       ~5.1 GB/s     ~5.4 GB/s   (+~5%)
  direct write      ~3.4 GB/s     ~4.8 GB/s   (+~45%)

Registered buffers bring up the write path speed up closer to speed of reads. There isn't much improvement for reads because it is already fast enough where it's at the copy-bound ceiling (surpassing that requires doing zero-copy). On a device-bound NVMe though, the differences are within noise, as backing I/O dominates per-request latency.

---
 fs/fuse/dev_uring.c       | 122 +++++++++++++++++++++++++++++++-------
 fs/fuse/dev_uring_i.h     |   8 +++
 include/uapi/linux/fuse.h |   4 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
fs/fuse/dev_uring.c +31 -0
index e9da92b46090..ed7e783bd68d 100644
@@ -22,6 +22,8 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_HEADERS 0
 #define FUSE_URING_IOV_PAYLOAD 1
 
+#define FUSE_URING_ADD_BUFPOOL_FLAGS	(FUSE_URING_REGISTERED_BUFPOOL)
+
 bool fuse_uring_enabled(void)
 {
 	return enable_uring;
@@ -47,6 +49,27 @@ static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
 	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
 }
 
+static inline bool bufpool_registered(struct fuse_ring_queue *queue)
+{
+	return queue->bufpool && queue->bufpool->registered;
+}
+
+/*
+ * For a registered bufpool, every sqe that drives a payload import (REGISTER,
+ * COMMIT_AND_FETCH) must carry the registered buffer index of the pool.
+ * This also must be called from the command's issue handler, where cmd->sqe is
+ * still valid
+ */
+static inline bool fuse_uring_cmd_index_ok(struct io_uring_cmd *cmd,
+					   struct fuse_ring_queue *queue)
+{
+	if (!bufpool_registered(queue))
+		return true;
+
+	return (cmd->flags & IORING_URING_CMD_FIXED) &&
+	       READ_ONCE(cmd->sqe->buf_index) == queue->bufpool->registered_index;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -653,19 +676,42 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 	return 0;
 }
 
+static int fuse_uring_import_payload(struct fuse_ring_ent *ent, int dir,
+				     struct iov_iter *iter,
+				     unsigned int issue_flags)
+{
+	void __user *base = ent->payload.iov_base;
+	size_t len = ent->payload.iov_len;
+	int err = 0;
+

fs/fuse/dev_uring.c static int copy_header_from_ring(struct fuse_ring_ent *ent, · line 696

Quoted 10 lines
fs/fuse/dev_uring.c +10 -0
+	if (!base) {
+		memset(iter, 0, sizeof(*iter));
+		return 0;
+	}
+
+	if (bufpool_registered(ent->queue))
+		err = io_uring_cmd_import_fixed((u64)(uintptr_t)base, len, dir,
+						iter, ent->cmd, issue_flags);
+	else
+		err = import_ubuf(dir, base, len, iter);

Hmm ok, just an annotation, I have to admit that I don't like issue_flags too much. Especially for the optimization that DDN has by avoiding io_uring_cmd_complete_in_task(), IO_URING_F_UNLOCKED is rather painful. Additionaly with that optimization the lock might get contended. The new addition here doesn't introduce it, but also doesn't make it any better.

Quoted 171 lines
fs/fuse/dev_uring.c +42 -20
+
+	if (err)
+		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+
+	return err;
+}
+
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
-				 struct iov_iter *iter)
+				 struct iov_iter *iter,
+				 unsigned int issue_flags)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
-			  iter);
-	if (err) {
-		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+	err = fuse_uring_import_payload(ent, dir, iter, issue_flags);
+	if (err)
 		return err;
-	}
 
 	fuse_copy_init(cs, dir == ITER_DEST, iter);
 
@@ -676,7 +722,8 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 }
 
 static int fuse_uring_copy_from_ring(struct fuse_req *req,
-				     struct fuse_ring_ent *ent)
+				     struct fuse_ring_ent *ent,
+				     unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -689,7 +736,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -702,7 +750,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
  * Copy data from the req to the ring buffer
  */
 static int fuse_uring_args_to_ring(struct fuse_req *req,
-				   struct fuse_ring_ent *ent)
+				   struct fuse_ring_ent *ent,
+				   unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -715,7 +764,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -754,7 +804,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 }
 
 static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	struct fuse_ring_queue *queue = ent->queue;
 	int err;
@@ -771,7 +822,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(req, ent);
+	err = fuse_uring_args_to_ring(req, ent, issue_flags);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -868,11 +919,12 @@ static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
 }
 
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	int err;
 
-	err = fuse_uring_copy_to_ring(ent, req);
+	err = fuse_uring_copy_to_ring(ent, req, issue_flags);
 	if (!err) {
 		set_bit(FR_SENT, &req->flags);
 		trace_fuse_request_sent(req);
@@ -983,7 +1035,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(req, ent);
+	err = fuse_uring_copy_from_ring(req, ent, issue_flags);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -995,7 +1047,8 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
  * Else, there is no next fuse request and this returns false.
  */
 static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
-					 struct fuse_ring_queue *queue)
+					 struct fuse_ring_queue *queue,
+					 unsigned int issue_flags)
 {
 	int err;
 	struct fuse_req *req;
@@ -1007,7 +1060,7 @@ static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
 	spin_unlock(&queue->lock);
 
 	if (req) {
-		err = fuse_uring_prepare_send(ent, req);
+		err = fuse_uring_prepare_send(ent, req, issue_flags);
 		if (err)
 			goto retry;
 	}
@@ -1081,6 +1134,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 		return err;
 	}
 
+	if (!fuse_uring_cmd_index_ok(cmd, queue)) {
+		spin_unlock(&queue->lock);
+		return -EINVAL;
+	}
+
 	/* Find a request based on the unique ID of the fuse request
 	 * This should get revised, as it needs a hash calculation and list
 	 * search. And full struct fuse_pqueue is needed (memory overhead).
@@ -1126,7 +1184,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * available and the cmd only returns to userspace when there's a
 	 * next request and an available buffer.
 	 */
-	if (fuse_uring_get_next_fuse_req(ent, queue))
+	if (fuse_uring_get_next_fuse_req(ent, queue, issue_flags))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
 	return 0;
 }
@@ -1252,7 +1310,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	spin_lock(&queue->lock);
 	if (bufpool_enabled(queue)) {
-		if (payload->iov_base || payload->iov_len) {
+		if (payload->iov_base || payload->iov_len ||
+		    !fuse_uring_cmd_index_ok(cmd, queue)) {
 			spin_unlock(&queue->lock);
 			return ERR_PTR(err);
 		}
@@ -1362,8 +1421,21 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	uintptr_t pool_uaddr;
 	unsigned int pool_len, nr_bufs;
 	size_t pool_size, buf_size;
+	bool registered = flags & FUSE_URING_REGISTERED_BUFPOOL;
+
+	if (!ring || qid >= ring->nr_queues)
+		return -EINVAL;
 
-	if (!ring || qid >= ring->nr_queues || flags)
+	if (flags & ~FUSE_URING_ADD_BUFPOOL_FLAGS)

fs/fuse/dev_uring.c static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd, · line 1439

Quoted 10 lines
fs/fuse/dev_uring.c +9 -0
+		return -EINVAL;
+
+	/*
+	 * A registered bufpool is reached through an io_uring fixed buffer, so
+	 * this command must be submitted with IORING_URING_CMD_FIXED and the
+	 * registered buffer index in sqe->buf_index. That index is recorded
+	 * below and enforced on every REGISTER / COMMIT_AND_FETCH sqe.
+	 */
+	if (registered && !(cmd->flags & IORING_URING_CMD_FIXED))
 		return -EINVAL;

Hmm, why do we actually need FUSE_URING_REGISTERED_BUFPOOL if the decision can be made by IORING_URING_CMD_FIXED?

Quoted 32 lines
fs/fuse/dev_uring.c +8 -2
 	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
@@ -1392,6 +1464,11 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	/* all buffers are free */
 	bitmap_set(pool->free_map, 0, nr_bufs);
 
+	if (registered) {
+		pool->registered = true;
+		pool->registered_index = READ_ONCE(cmd->sqe->buf_index);
+	}
+
 	spin_lock(&queue->lock);
 	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
 		spin_unlock(&queue->lock);
@@ -1504,9 +1581,10 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 	int err;
 
 	if (!tw.cancel) {
-		err = fuse_uring_prepare_send(ent, ent->fuse_req);
+		err = fuse_uring_prepare_send(ent, ent->fuse_req, issue_flags);
 		if (err) {
-			if (!fuse_uring_get_next_fuse_req(ent, queue))
+			if (!fuse_uring_get_next_fuse_req(ent, queue,
+							  issue_flags))
 				return;
 			err = 0;
 		}
fs/fuse/dev_uring_i.h +0 -0
index cdf56f8b38b5..e142cae43022 100644

fs/fuse/dev_uring_i.h enum fuse_queue_payload_mode { · line 58

Quoted 10 lines
fs/fuse/dev_uring_i.h +7 -0
@@ -49,6 +49,14 @@ enum fuse_queue_payload_mode {
 };
 
 struct fuse_bufpool {
+	bool registered;
+
+	/*
+	 * io_uring registered buffer table index for this pool, bound at
+	 * ADD_BUFPOOL time. Only valid if the bufpool is registered
+	 */
+	u16 registered_index;

Dunno, could this go into the previous commit or be reserved in the previous commit? This addition make bisect hard due to ABI change?

Quoted 17 lines
fs/fuse/dev_uring_i.h +1 -0
+
 	/* starting uaddr of the bufpool */
 	uintptr_t base_uaddr;
 
include/uapi/linux/fuse.h +1 -0
index f7173b5d4321..07d12f1c55bb 100644
@@ -246,6 +246,7 @@
  *  - add FUSE_HAS_IO_URING_BUFPOOL
  *  - add fuse_uring_cmd_req bufpool struct
  *  - add bufpool offset field to fuse_uring_ent_in_out struct
+ *  - add FUSE_URING_REGISTERED_BUFPOOL flag
  */
 
 #ifndef _LINUX_FUSE_H

include/uapi/linux/fuse.h enum fuse_uring_cmd { · line 1319

Quoted 9 lines
include/uapi/linux/fuse.h +3 -0
@@ -1310,6 +1311,9 @@ enum fuse_uring_cmd {
 	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
+/* fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_BUFPOOL */
+#define FUSE_URING_REGISTERED_BUFPOOL	(1 << 0)
+
 /**
  * In the 80B command area of the SQE.
  */

Thanks,
Bernd

author maintainer
#21 lore raw

Re: [PATCH v6 4/6] fuse: support registered buffer pools in io-uring

Quoted 105 lines · Bernd Schubert
Quoted 101 lines · Joanne Koong

Allow servers to use a buffer pool that is also registered through io-uring. When the server registers a buffer pool with io-uring, the pages backing the pool are pinned upfront. This eliminates the overhead of pinning/unpinning user pages and translating virtual addresses per i/o request. This also allows servers to use the same registered memory for subsequent backing store I/O (eg read_fixed/write_fixed), keeping data in the same pinned pages without additional pinning or mapping overhead required.

To use this, the server needs to set the FUSE_URING_REGISTERED_BUFPOOL flag when adding a bufpool through the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd. For every sqe submitted (including the one for adding the bufpool), it should set sqe->uring_cmd_flags to include IORING_URING_CMD_FIXED, and pass in the index where the registered bufpool resides to sqe->buf_index.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

baseline registered buffers

  direct read       ~5.1 GB/s     ~5.4 GB/s   (+~5%)
  direct write      ~3.4 GB/s     ~4.8 GB/s   (+~45%)

Registered buffers bring up the write path speed up closer to speed of reads. There isn't much improvement for reads because it is already fast enough where it's at the copy-bound ceiling (surpassing that requires doing zero-copy). On a device-bound NVMe though, the differences are within noise, as backing I/O dominates per-request latency.

---
 fs/fuse/dev_uring.c       | 122 +++++++++++++++++++++++++++++++-------
 fs/fuse/dev_uring_i.h     |   8 +++
 include/uapi/linux/fuse.h |   4 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
fs/fuse/dev_uring.c +40 -0
index e9da92b46090..ed7e783bd68d 100644
@@ -22,6 +22,8 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_HEADERS 0
 #define FUSE_URING_IOV_PAYLOAD 1
 
+#define FUSE_URING_ADD_BUFPOOL_FLAGS (FUSE_URING_REGISTERED_BUFPOOL)
+
 bool fuse_uring_enabled(void)
 {
      return enable_uring;
@@ -47,6 +49,27 @@ static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
      return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
 }
 
+static inline bool bufpool_registered(struct fuse_ring_queue *queue)
+{
+     return queue->bufpool && queue->bufpool->registered;
+}
+
+/*
+ * For a registered bufpool, every sqe that drives a payload import (REGISTER,
+ * COMMIT_AND_FETCH) must carry the registered buffer index of the pool.
+ * This also must be called from the command's issue handler, where cmd->sqe is
+ * still valid
+ */
+static inline bool fuse_uring_cmd_index_ok(struct io_uring_cmd *cmd,
+                                        struct fuse_ring_queue *queue)
+{
+     if (!bufpool_registered(queue))
+             return true;
+
+     return (cmd->flags & IORING_URING_CMD_FIXED) &&
+            READ_ONCE(cmd->sqe->buf_index) == queue->bufpool->registered_index;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
                                 struct fuse_ring_ent *ring_ent)
 {
@@ -653,19 +676,42 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
      return 0;
 }
 
+static int fuse_uring_import_payload(struct fuse_ring_ent *ent, int dir,
+                                  struct iov_iter *iter,
+                                  unsigned int issue_flags)
+{
+     void __user *base = ent->payload.iov_base;
+     size_t len = ent->payload.iov_len;
+     int err = 0;
+
+     if (!base) {
+             memset(iter, 0, sizeof(*iter));
+             return 0;
+     }
+
+     if (bufpool_registered(ent->queue))
+             err = io_uring_cmd_import_fixed((u64)(uintptr_t)base, len, dir,
+                                             iter, ent->cmd, issue_flags);
+     else
Quoted 8 lines

fs/fuse/dev_uring.c static int copy_header_from_ring(struct fuse_ring_ent *ent, · line 696

Quoted 1 line
fs/fuse/dev_uring.c +1 -0
+             err = import_ubuf(dir, base, len, iter);

Hmm ok, just an annotation, I have to admit that I don't like issue_flags too much. Especially for the optimization that DDN has by avoiding io_uring_cmd_complete_in_task(), IO_URING_F_UNLOCKED is rather painful. Additionaly with that optimization the lock might get contended. The new addition here doesn't introduce it, but also doesn't make it any better.

For what it's worth, the locks aren't taken on these paths (eg sends go through fuse_uring_dispatch_ent() -> io_uring_cmd_complete_in_task() and task work runs with ctx->uring_lock held, and commits run in the command's issue handler, where the lock is likewise held).

Threading the issue_flags through gets a bit annoying, but I personally don't see a better way for core io-uring infrastructure to determine whether a given call path already holds the lock or not.

Quoted 17 lines
Quoted 17 lines
fs/fuse/dev_uring.c +11 -0
+
+     if (err)
+             pr_info_ratelimited("fuse: Import of user buffer failed\n");
+
+     return err;
+}
+
@@ -1362,8 +1421,21 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
      uintptr_t pool_uaddr;
      unsigned int pool_len, nr_bufs;
      size_t pool_size, buf_size;
+     bool registered = flags & FUSE_URING_REGISTERED_BUFPOOL;
+
+     if (!ring || qid >= ring->nr_queues)
+             return -EINVAL;
 
Quoted 15 lines

fs/fuse/dev_uring.c static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd, · line 1439

Quoted 12 lines
fs/fuse/dev_uring.c +10 -1
-     if (!ring || qid >= ring->nr_queues || flags)
+     if (flags & ~FUSE_URING_ADD_BUFPOOL_FLAGS)
+             return -EINVAL;
+
+     /*
+      * A registered bufpool is reached through an io_uring fixed buffer, so
+      * this command must be submitted with IORING_URING_CMD_FIXED and the
+      * registered buffer index in sqe->buf_index. That index is recorded
+      * below and enforced on every REGISTER / COMMIT_AND_FETCH sqe.
+      */
+     if (registered && !(cmd->flags & IORING_URING_CMD_FIXED))
              return -EINVAL;

Hmm, why do we actually need FUSE_URING_REGISTERED_BUFPOOL if the decision can be made by IORING_URING_CMD_FIXED?

It's not strictly needed, but imo it makes uapi more explicit and the contract more clear. I don't feel strongly about this though, I'm fine with either approach.

Quoted 9 lines
Quoted 9 lines
fs/fuse/dev_uring_i.h +0 -0
index cdf56f8b38b5..e142cae43022 100644
@@ -49,6 +49,14 @@ enum fuse_queue_payload_mode {
 };
 
Quoted 11 lines

fs/fuse/dev_uring_i.h enum fuse_queue_payload_mode { · line 58

Quoted 8 lines
fs/fuse/dev_uring_i.h +7 -0
 struct fuse_bufpool {
+     bool registered;
+
+     /*
+      * io_uring registered buffer table index for this pool, bound at
+      * ADD_BUFPOOL time. Only valid if the bufpool is registered
+      */
+     u16 registered_index;

Dunno, could this go into the previous commit or be reserved in the previous commit? This addition make bisect hard due to ABI change?

This is an addition to a kernel-internal struct, not an uapi-defined one, so I don't think this affects ABI. The previous commit doesn't have any notion of registered buffers, so I think moving these definitions to the previous commit would be confusing.

Thanks,
Joanne

maintainer
#22 lore raw

Re: [PATCH v6 4/6] fuse: support registered buffer pools in io-uring

Quoted 115 lines · Joanne Koong
Quoted 105 lines · Bernd Schubert
Quoted 101 lines · Joanne Koong

Allow servers to use a buffer pool that is also registered through io-uring. When the server registers a buffer pool with io-uring, the pages backing the pool are pinned upfront. This eliminates the overhead of pinning/unpinning user pages and translating virtual addresses per i/o request. This also allows servers to use the same registered memory for subsequent backing store I/O (eg read_fixed/write_fixed), keeping data in the same pinned pages without additional pinning or mapping overhead required.

To use this, the server needs to set the FUSE_URING_REGISTERED_BUFPOOL flag when adding a bufpool through the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd. For every sqe submitted (including the one for adding the bufpool), it should set sqe->uring_cmd_flags to include IORING_URING_CMD_FIXED, and pass in the index where the registered bufpool resides to sqe->buf_index.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

baseline registered buffers

  direct read       ~5.1 GB/s     ~5.4 GB/s   (+~5%)
  direct write      ~3.4 GB/s     ~4.8 GB/s   (+~45%)

Registered buffers bring up the write path speed up closer to speed of reads. There isn't much improvement for reads because it is already fast enough where it's at the copy-bound ceiling (surpassing that requires doing zero-copy). On a device-bound NVMe though, the differences are within noise, as backing I/O dominates per-request latency.

---
 fs/fuse/dev_uring.c       | 122 +++++++++++++++++++++++++++++++-------
 fs/fuse/dev_uring_i.h     |   8 +++
 include/uapi/linux/fuse.h |   4 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
fs/fuse/dev_uring.c +40 -0
index e9da92b46090..ed7e783bd68d 100644
@@ -22,6 +22,8 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_HEADERS 0
 #define FUSE_URING_IOV_PAYLOAD 1
 
+#define FUSE_URING_ADD_BUFPOOL_FLAGS (FUSE_URING_REGISTERED_BUFPOOL)
+
 bool fuse_uring_enabled(void)
 {
      return enable_uring;
@@ -47,6 +49,27 @@ static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
      return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
 }
 
+static inline bool bufpool_registered(struct fuse_ring_queue *queue)
+{
+     return queue->bufpool && queue->bufpool->registered;
+}
+
+/*
+ * For a registered bufpool, every sqe that drives a payload import (REGISTER,
+ * COMMIT_AND_FETCH) must carry the registered buffer index of the pool.
+ * This also must be called from the command's issue handler, where cmd->sqe is
+ * still valid
+ */
+static inline bool fuse_uring_cmd_index_ok(struct io_uring_cmd *cmd,
+                                        struct fuse_ring_queue *queue)
+{
+     if (!bufpool_registered(queue))
+             return true;
+
+     return (cmd->flags & IORING_URING_CMD_FIXED) &&
+            READ_ONCE(cmd->sqe->buf_index) == queue->bufpool->registered_index;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
                                 struct fuse_ring_ent *ring_ent)
 {
@@ -653,19 +676,42 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
      return 0;
 }
 
+static int fuse_uring_import_payload(struct fuse_ring_ent *ent, int dir,
+                                  struct iov_iter *iter,
+                                  unsigned int issue_flags)
+{
+     void __user *base = ent->payload.iov_base;
+     size_t len = ent->payload.iov_len;
+     int err = 0;
+
+     if (!base) {
+             memset(iter, 0, sizeof(*iter));
+             return 0;
+     }
+
+     if (bufpool_registered(ent->queue))
+             err = io_uring_cmd_import_fixed((u64)(uintptr_t)base, len, dir,
+                                             iter, ent->cmd, issue_flags);
+     else
Quoted 8 lines

fs/fuse/dev_uring.c static int copy_header_from_ring(struct fuse_ring_ent *ent, · line 696

Quoted 1 line
fs/fuse/dev_uring.c +1 -0
+             err = import_ubuf(dir, base, len, iter);

Hmm ok, just an annotation, I have to admit that I don't like issue_flags too much. Especially for the optimization that DDN has by avoiding io_uring_cmd_complete_in_task(), IO_URING_F_UNLOCKED is rather painful. Additionaly with that optimization the lock might get contended. The new addition here doesn't introduce it, but also doesn't make it any better.

Quoted 5 lines

For what it's worth, the locks aren't taken on these paths (eg sends go through fuse_uring_dispatch_ent() -> io_uring_cmd_complete_in_task() and task work runs with ctx->uring_lock held, and commits run in the command's issue handler, where the lock is likewise held).

Yeah, except for the optimization that avoids io_uring_cmd_complete_in_task/fuse_uring_send_in_task and submits the request directly from the caller. Anyway, it was just an annotation, as this lock is not new.

Quoted 5 lines

Threading the issue_flags through gets a bit annoying, but I personally don't see a better way for core io-uring infrastructure to determine whether a given call path already holds the lock or not.

The flag doesn't work that well with the optimization when the caller is in io-uring context, we need to figure out that with Jens/Pavel later on.

Quoted 33 lines
Quoted 17 lines
Quoted 17 lines
fs/fuse/dev_uring.c +11 -0
+
+     if (err)
+             pr_info_ratelimited("fuse: Import of user buffer failed\n");
+
+     return err;
+}
+
@@ -1362,8 +1421,21 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
      uintptr_t pool_uaddr;
      unsigned int pool_len, nr_bufs;
      size_t pool_size, buf_size;
+     bool registered = flags & FUSE_URING_REGISTERED_BUFPOOL;
+
+     if (!ring || qid >= ring->nr_queues)
+             return -EINVAL;
 
Quoted 15 lines

fs/fuse/dev_uring.c static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd, · line 1439

Quoted 12 lines
fs/fuse/dev_uring.c +10 -1
-     if (!ring || qid >= ring->nr_queues || flags)
+     if (flags & ~FUSE_URING_ADD_BUFPOOL_FLAGS)
+             return -EINVAL;
+
+     /*
+      * A registered bufpool is reached through an io_uring fixed buffer, so
+      * this command must be submitted with IORING_URING_CMD_FIXED and the
+      * registered buffer index in sqe->buf_index. That index is recorded
+      * below and enforced on every REGISTER / COMMIT_AND_FETCH sqe.
+      */
+     if (registered && !(cmd->flags & IORING_URING_CMD_FIXED))
              return -EINVAL;

Hmm, why do we actually need FUSE_URING_REGISTERED_BUFPOOL if the decision can be made by IORING_URING_CMD_FIXED?

Quoted 3 lines

It's not strictly needed, but imo it makes uapi more explicit and the contract more clear. I don't feel strongly about this though, I'm fine with either approach.

I don't have a strong opinion, it just looks a bit weird to have a flag that could be used and then to introduce another one and give userspace even more choices and possible failure points.
Would there ever be a reason to register a buffer, but not to use that in fuse?

Quoted 22 lines
Quoted 10 lines
Quoted 10 lines
fs/fuse/dev_uring_i.h +0 -0
index cdf56f8b38b5..e142cae43022 100644
@@ -49,6 +49,14 @@ enum fuse_queue_payload_mode {
 };
 
Quoted 11 lines

fs/fuse/dev_uring_i.h enum fuse_queue_payload_mode { · line 58

Quoted 8 lines
fs/fuse/dev_uring_i.h +7 -0
 struct fuse_bufpool {
+     bool registered;
+
+     /*
+      * io_uring registered buffer table index for this pool, bound at
+      * ADD_BUFPOOL time. Only valid if the bufpool is registered
+      */
+     u16 registered_index;

Dunno, could this go into the previous commit or be reserved in the previous commit? This addition make bisect hard due to ABI change?

Quoted 4 lines

This is an addition to a kernel-internal struct, not an uapi-defined one, so I don't think this affects ABI. The previous commit doesn't have any notion of registered buffers, so I think moving these definitions to the previous commit would be confusing.

Ah yes sorry, my fault, I shouldn't do reviews past midnight. Sorry again.

Thanks,
Bernd

maintainer Reviewed-by on v6 4/6
#23 lore raw

Re: [PATCH v6 4/6] fuse: support registered buffer pools in io-uring

In reply to Joanne Koong
Quoted 342 lines · Joanne Koong

Allow servers to use a buffer pool that is also registered through io-uring. When the server registers a buffer pool with io-uring, the pages backing the pool are pinned upfront. This eliminates the overhead of pinning/unpinning user pages and translating virtual addresses per i/o request. This also allows servers to use the same registered memory for subsequent backing store I/O (eg read_fixed/write_fixed), keeping data in the same pinned pages without additional pinning or mapping overhead required.

To use this, the server needs to set the FUSE_URING_REGISTERED_BUFPOOL flag when adding a bufpool through the FUSE_IO_URING_CMD_ADD_BUFPOOL cmd. For every sqe submitted (including the one for adding the bufpool), it should set sqe->uring_cmd_flags to include IORING_URING_CMD_FIXED, and pass in the index where the registered bufpool resides to sqe->buf_index.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

		    baseline      registered buffers
  direct read       ~5.1 GB/s     ~5.4 GB/s   (+~5%)
  direct write      ~3.4 GB/s     ~4.8 GB/s   (+~45%)

Registered buffers bring up the write path speed up closer to speed of reads. There isn't much improvement for reads because it is already fast enough where it's at the copy-bound ceiling (surpassing that requires doing zero-copy). On a device-bound NVMe though, the differences are within noise, as backing I/O dominates per-request latency.

---
 fs/fuse/dev_uring.c       | 122 +++++++++++++++++++++++++++++++-------
 fs/fuse/dev_uring_i.h     |   8 +++
 include/uapi/linux/fuse.h |   4 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
fs/fuse/dev_uring.c +100 -22
index e9da92b46090..ed7e783bd68d 100644
@@ -22,6 +22,8 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_HEADERS 0
 #define FUSE_URING_IOV_PAYLOAD 1
 
+#define FUSE_URING_ADD_BUFPOOL_FLAGS	(FUSE_URING_REGISTERED_BUFPOOL)
+
 bool fuse_uring_enabled(void)
 {
 	return enable_uring;
@@ -47,6 +49,27 @@ static inline bool bufpool_enabled(struct fuse_ring_queue *queue)
 	return queue->payload_mode == FUSE_PAYLOAD_BUFPOOL;
 }
 
+static inline bool bufpool_registered(struct fuse_ring_queue *queue)
+{
+	return queue->bufpool && queue->bufpool->registered;
+}
+
+/*
+ * For a registered bufpool, every sqe that drives a payload import (REGISTER,
+ * COMMIT_AND_FETCH) must carry the registered buffer index of the pool.
+ * This also must be called from the command's issue handler, where cmd->sqe is
+ * still valid
+ */
+static inline bool fuse_uring_cmd_index_ok(struct io_uring_cmd *cmd,
+					   struct fuse_ring_queue *queue)
+{
+	if (!bufpool_registered(queue))
+		return true;
+
+	return (cmd->flags & IORING_URING_CMD_FIXED) &&
+	       READ_ONCE(cmd->sqe->buf_index) == queue->bufpool->registered_index;
+}
+
 static void uring_cmd_set_ring_ent(struct io_uring_cmd *cmd,
 				   struct fuse_ring_ent *ring_ent)
 {
@@ -653,19 +676,42 @@ static int copy_header_from_ring(struct fuse_ring_ent *ent,
 	return 0;
 }
 
+static int fuse_uring_import_payload(struct fuse_ring_ent *ent, int dir,
+				     struct iov_iter *iter,
+				     unsigned int issue_flags)
+{
+	void __user *base = ent->payload.iov_base;
+	size_t len = ent->payload.iov_len;
+	int err = 0;
+
+	if (!base) {
+		memset(iter, 0, sizeof(*iter));
+		return 0;
+	}
+
+	if (bufpool_registered(ent->queue))
+		err = io_uring_cmd_import_fixed((u64)(uintptr_t)base, len, dir,
+						iter, ent->cmd, issue_flags);
+	else
+		err = import_ubuf(dir, base, len, iter);
+
+	if (err)
+		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+
+	return err;
+}
+
 static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 				 struct fuse_req *req,
 				 struct fuse_ring_ent *ent, int dir,
-				 struct iov_iter *iter)
+				 struct iov_iter *iter,
+				 unsigned int issue_flags)
 {
 	int err;
 
-	err = import_ubuf(dir, ent->payload.iov_base, ent->payload.iov_len,
-			  iter);
-	if (err) {
-		pr_info_ratelimited("fuse: Import of user buffer failed\n");
+	err = fuse_uring_import_payload(ent, dir, iter, issue_flags);
+	if (err)
 		return err;
-	}
 
 	fuse_copy_init(cs, dir == ITER_DEST, iter);
 
@@ -676,7 +722,8 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 }
 
 static int fuse_uring_copy_from_ring(struct fuse_req *req,
-				     struct fuse_ring_ent *ent)
+				     struct fuse_ring_ent *ent,
+				     unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -689,7 +736,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
 	if (err)
 		return err;
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_SOURCE, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -702,7 +750,8 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
  * Copy data from the req to the ring buffer
  */
 static int fuse_uring_args_to_ring(struct fuse_req *req,
-				   struct fuse_ring_ent *ent)
+				   struct fuse_ring_ent *ent,
+				   unsigned int issue_flags)
 {
 	struct fuse_copy_state cs;
 	struct fuse_args *args = req->args;
@@ -715,7 +764,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 		.commit_id = req->in.h.unique,
 	};
 
-	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter);
+	err = setup_fuse_copy_state(&cs, req, ent, ITER_DEST, &iter,
+				    issue_flags);
 	if (err)
 		return err;
 
@@ -754,7 +804,8 @@ static int fuse_uring_args_to_ring(struct fuse_req *req,
 }
 
 static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	struct fuse_ring_queue *queue = ent->queue;
 	int err;
@@ -771,7 +822,7 @@ static int fuse_uring_copy_to_ring(struct fuse_ring_ent *ent,
 		return err;
 
 	/* copy the request */
-	err = fuse_uring_args_to_ring(req, ent);
+	err = fuse_uring_args_to_ring(req, ent, issue_flags);
 	if (unlikely(err)) {
 		pr_info_ratelimited("Copy to ring failed: %d\n", err);
 		return err;
@@ -868,11 +919,12 @@ static int fuse_uring_prep_buffer(struct fuse_ring_ent *ent,
 }
 
 static int fuse_uring_prepare_send(struct fuse_ring_ent *ent,
-				   struct fuse_req *req)
+				   struct fuse_req *req,
+				   unsigned int issue_flags)
 {
 	int err;
 
-	err = fuse_uring_copy_to_ring(ent, req);
+	err = fuse_uring_copy_to_ring(ent, req, issue_flags);
 	if (!err) {
 		set_bit(FR_SENT, &req->flags);
 		trace_fuse_request_sent(req);
@@ -983,7 +1035,7 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
 		goto out;
 	}
 
-	err = fuse_uring_copy_from_ring(req, ent);
+	err = fuse_uring_copy_from_ring(req, ent, issue_flags);
 out:
 	fuse_uring_req_end(ent, req, err);
 }
@@ -995,7 +1047,8 @@ static void fuse_uring_commit(struct fuse_ring_ent *ent, struct fuse_req *req,
  * Else, there is no next fuse request and this returns false.
  */
 static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
-					 struct fuse_ring_queue *queue)
+					 struct fuse_ring_queue *queue,
+					 unsigned int issue_flags)
 {
 	int err;
 	struct fuse_req *req;
@@ -1007,7 +1060,7 @@ static bool fuse_uring_get_next_fuse_req(struct fuse_ring_ent *ent,
 	spin_unlock(&queue->lock);
 
 	if (req) {
-		err = fuse_uring_prepare_send(ent, req);
+		err = fuse_uring_prepare_send(ent, req, issue_flags);
 		if (err)
 			goto retry;
 	}
@@ -1081,6 +1134,11 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 		return err;
 	}
 
+	if (!fuse_uring_cmd_index_ok(cmd, queue)) {
+		spin_unlock(&queue->lock);
+		return -EINVAL;
+	}
+
 	/* Find a request based on the unique ID of the fuse request
 	 * This should get revised, as it needs a hash calculation and list
 	 * search. And full struct fuse_pqueue is needed (memory overhead).
@@ -1126,7 +1184,7 @@ static int fuse_uring_commit_fetch(struct io_uring_cmd *cmd, int issue_flags,
 	 * available and the cmd only returns to userspace when there's a
 	 * next request and an available buffer.
 	 */
-	if (fuse_uring_get_next_fuse_req(ent, queue))
+	if (fuse_uring_get_next_fuse_req(ent, queue, issue_flags))
 		fuse_uring_send(ent, cmd, 0, issue_flags);
 	return 0;
 }
@@ -1252,7 +1310,8 @@ fuse_uring_create_ring_ent(struct io_uring_cmd *cmd,
 
 	spin_lock(&queue->lock);
 	if (bufpool_enabled(queue)) {
-		if (payload->iov_base || payload->iov_len) {
+		if (payload->iov_base || payload->iov_len ||
+		    !fuse_uring_cmd_index_ok(cmd, queue)) {
 			spin_unlock(&queue->lock);
 			return ERR_PTR(err);
 		}
@@ -1362,8 +1421,21 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	uintptr_t pool_uaddr;
 	unsigned int pool_len, nr_bufs;
 	size_t pool_size, buf_size;
+	bool registered = flags & FUSE_URING_REGISTERED_BUFPOOL;
+
+	if (!ring || qid >= ring->nr_queues)
+		return -EINVAL;
 
-	if (!ring || qid >= ring->nr_queues || flags)
+	if (flags & ~FUSE_URING_ADD_BUFPOOL_FLAGS)
+		return -EINVAL;
+
+	/*
+	 * A registered bufpool is reached through an io_uring fixed buffer, so
+	 * this command must be submitted with IORING_URING_CMD_FIXED and the
+	 * registered buffer index in sqe->buf_index. That index is recorded
+	 * below and enforced on every REGISTER / COMMIT_AND_FETCH sqe.
+	 */
+	if (registered && !(cmd->flags & IORING_URING_CMD_FIXED))
 		return -EINVAL;
 
 	/* Pairs with smp_store_release() in fuse_uring_create_queue() */
@@ -1392,6 +1464,11 @@ static int fuse_uring_add_bufpool(struct io_uring_cmd *cmd,
 	/* all buffers are free */
 	bitmap_set(pool->free_map, 0, nr_bufs);
 
+	if (registered) {
+		pool->registered = true;
+		pool->registered_index = READ_ONCE(cmd->sqe->buf_index);
+	}
+
 	spin_lock(&queue->lock);
 	if (queue->payload_mode != FUSE_PAYLOAD_UNSET) {
 		spin_unlock(&queue->lock);
@@ -1504,9 +1581,10 @@ static void fuse_uring_send_in_task(struct io_tw_req tw_req, io_tw_token_t tw)
 	int err;
 
 	if (!tw.cancel) {
-		err = fuse_uring_prepare_send(ent, ent->fuse_req);
+		err = fuse_uring_prepare_send(ent, ent->fuse_req, issue_flags);
 		if (err) {
-			if (!fuse_uring_get_next_fuse_req(ent, queue))
+			if (!fuse_uring_get_next_fuse_req(ent, queue,
+							  issue_flags))
 				return;
 			err = 0;
 		}
fs/fuse/dev_uring_i.h +8 -0
index cdf56f8b38b5..e142cae43022 100644
@@ -49,6 +49,14 @@ enum fuse_queue_payload_mode {
 };
 
 struct fuse_bufpool {
+	bool registered;
+
+	/*
+	 * io_uring registered buffer table index for this pool, bound at
+	 * ADD_BUFPOOL time. Only valid if the bufpool is registered
+	 */
+	u16 registered_index;
+
 	/* starting uaddr of the bufpool */
 	uintptr_t base_uaddr;
 
include/uapi/linux/fuse.h +1 -0
index f7173b5d4321..07d12f1c55bb 100644
@@ -246,6 +246,7 @@
  *  - add FUSE_HAS_IO_URING_BUFPOOL
  *  - add fuse_uring_cmd_req bufpool struct
  *  - add bufpool offset field to fuse_uring_ent_in_out struct
+ *  - add FUSE_URING_REGISTERED_BUFPOOL flag
  */
 
 #ifndef _LINUX_FUSE_H

include/uapi/linux/fuse.h enum fuse_uring_cmd { · line 1319

Quoted 9 lines
include/uapi/linux/fuse.h +3 -0
@@ -1310,6 +1311,9 @@ enum fuse_uring_cmd {
 	FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
+/* fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_BUFPOOL */
+#define FUSE_URING_REGISTERED_BUFPOOL	(1 << 0)
+
 /**
  * In the 80B command area of the SQE.
  */

I would personally prefer to avoid FUSE_URING_ADD_BUFPOOL_FLAGS and to use IORING_URING_CMD_FIXED, unless there is a really compelling reason to have a 2nd flag, but I don't have a strong opinion about it.

author maintainer
#24 lore raw

Re: [PATCH v6 4/6] fuse: support registered buffer pools in io-uring

Quoted 29 lines · Bernd Schubert
Quoted 14 lines
include/uapi/linux/fuse.h +1 -0
index f7173b5d4321..07d12f1c55bb 100644
@@ -246,6 +246,7 @@
  *  - add FUSE_HAS_IO_URING_BUFPOOL
  *  - add fuse_uring_cmd_req bufpool struct
  *  - add bufpool offset field to fuse_uring_ent_in_out struct
+ *  - add FUSE_URING_REGISTERED_BUFPOOL flag
  */
 
 #ifndef _LINUX_FUSE_H

include/uapi/linux/fuse.h enum fuse_uring_cmd { · line 1319

Quoted 9 lines
include/uapi/linux/fuse.h +3 -0
@@ -1310,6 +1311,9 @@ enum fuse_uring_cmd {
      FUSE_IO_URING_CMD_ADD_BUFPOOL = 4,
 };
 
+/* fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_BUFPOOL */
+#define FUSE_URING_REGISTERED_BUFPOOL        (1 << 0)
+
 /**
  * In the 80B command area of the SQE.
  */

I would personally prefer to avoid FUSE_URING_ADD_BUFPOOL_FLAGS and to use IORING_URING_CMD_FIXED, unless there is a really compelling reason to have a 2nd flag, but I don't have a strong opinion about it.

Quoted 1 line

Happy to remove the flag then for v7. Thanks for reviewing the patches.

Thanks,
Joanne

author maintainer
#25 lore raw

PATCH v6 5/6 fuse: add zero-copy over io-uring

In reply to Joanne Koong

Implement zero-copy in fuse io-uring to eliminate memory copies between the application, kernel, and server for read/write operations. The server can directly access client pages or page cache folios without copying data through an intermediary buffer. When a fuse request arrives, the kernel registers the relevant pages into a sparse slot in the server's io_uring registered buffer table. The server can then operate on these pages directly using io-uring fixed buffer operations (eg read_fixed/write_fixed) and the kernel unregisters these pages when the request completes. Non-page-backed args (eg op out headers) will go through the payload buffer as normal. The server can specify which open files should have their reads/writes go through zero-copy, by setting the FOPEN_IO_URING_ZERO_COPY flag when servicing opens.

This requires CAP_SYS_ADMIN and bufpools. This is gated behind CAP_SYS_ADMIN because zero-copy allows the server direct access to the client's underlying pages, rather than operating on an intermediary buffer that the contents of the client's pages were copied into or on page cache folios.

The request flow for the zero-copy direct-io write path (client writes data, server reads it) is as follows:
=======================================================================

|  Kernel                                   |  FUSE server
|                                           |
|  "write(fd, buf, 1MB)"                    |
|                                           |
|  >sys_write()                             |
|    >fuse_file_write_iter()                |
|      >fuse_send_one()                     |
|        [req->args->in_pages = true]       |
|        [folios hold client write data]    |
|                                           |
|  >fuse_uring_copy_to_ring()               |
|    >copy_header_to_ring(IN_OUT)           |
|      [memcpy fuse_in_header]              |
|    >copy_header_to_ring(OP)               |
|      [memcpy write_in header]             |
|                                           |
|    >fuse_uring_args_to_ring()             |
|      >setup_fuse_copy_state()             |
|        [skip_folio_copy = true]           |
|                                           |
|      >fuse_uring_set_up_zero_copy()       |
|        [folio_get for each client folio]  |
|        [build bio_vec array from folios]  |
|        >io_buffer_register_bvec()         |
|          [register pages at
                 ent->zero_copy_index]      |
|        [ent->zero_copied = true]          |
|                                           |
|      >fuse_copy_args()                    |
|        [skip_folio_copy => return 0       |
|         for page arg, skip data copy]     |
|                                           |
|    >copy_header_to_ring(RING_ENT)         |
|      [memcpy ent_in_out]                  |
|    >io_uring_cmd_done()                   |
|                                           |
|                                           | [CQE received]
|                                           |
|                                           | [issue io_uring READ at
|                                           |  ent->zero_copy_index]
|                                           | [reads directly from
|                                           |client's pages (ZERO_COPY)]
|                                           |
|                                           | [write data to backing
|                                           | store]
|                                           |  [submit COMMIT AND FETCH]
|                                           |
|  >fuse_uring_commit_fetch()               |
|    >fuse_uring_commit()                   |
|      >fuse_uring_copy_from_ring()         |
|    >fuse_uring_req_end()                  |
|      >io_buffer_unregister(ent->zero_copy_index) |
|        [unregister pages from index]      |
|      >fuse_zero_copy_release()            |
|        [folio_put for each folio]         |
|      [ent->zero_copied = false]           |
|      >fuse_request_end()                  |
|        [wake up client]                   |

The zero-copy read path is analogous.

Some requests may have both page-backed args and non-page-backed args. For these requests, the page-backed args are zero-copied while the non-page-backed args are copied to the buffer selected from the buffer pool:
zero-copy: pages registered via io_buffer_register_bvec()
non-page-backed: copied to payload buffer via fuse_copy_args()

For a request whose payload is zero-copied, the
registration/unregistration path looks like:

    register:  fuse_uring_set_up_zero_copy()
                 folio_get() for each folio
                 io_buffer_register_bvec(ent->zero_copy_index)

    unregister: fuse_uring_req_end()
                  io_buffer_unregister(ent->zero_copy_index)
                  -> fuse_zero_copy_release() callback
                     folio_put() for each folio

Please note that on abort for in-flight zero-copied requests that have been sent to userspace, the registered bvec slot remains occupied and its folios remain pinned until the io-uring ring is destroyed, at which point io-uring unregisters all buffers and the fuse_zero_copy_release() callback drops the folio references. Unregistering at teardown would require operating on the ring context directly, whose validity is hard to ascertain; this is deemed not worth the complexity for the abort race, since everything is freed when the ring is torn down.

The throughput improvement from zero-copy depends on how much of the per-request latency is spent on data copying vs backing I/O. The gain comes from eliminating the payload-buffer memcpy, but accessing the zero-copied pages requires the server to issue the read/write as an IORING_OP_READ/WRITE_FIXED operation. The benefit is largest when the mempcy is a meaningful fraction of per-request latency while backing i/o is still noticable enough that the extra io-uring op's overhead doesn't dominate.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

baseline registered-buf zero-copy (zc vs base)

direct read     ~5.1 GB/s  ~5.4 GB/s        ~8.9 GB/s   (+75%)
direct write    ~3.4 GB/s  ~4.8 GB/s        ~5.1 GB/s   (+50%)

Reads end up higher than writes because the backing store reads faster than it writes (the baseline shows the same read>write gap, and the raw device does too). On a device-bound NVMe (~2 GB/s reads) the read gain shrinks to ~10-16% (and no measurable gains for writes), as backing I/O rather than the eliminated copy dominates latency.

The benefit overall scales with how much of the per-request latency is the data copy versus backing I/O.

---
 fs/fuse/args.h            |   2 +
 fs/fuse/dev.c             |  19 +++-
 fs/fuse/dev_uring.c       | 181 +++++++++++++++++++++++++++++++++++---
 fs/fuse/dev_uring_i.h     |   6 ++
 fs/fuse/file.c            |   2 +
 fs/fuse/fuse_dev_i.h      |   1 +
 include/uapi/linux/fuse.h |  34 +++++++
 7 files changed, 229 insertions(+), 16 deletions(-)
fs/fuse/args.h +2 -0
index ecfe51a192af..5173264a1261 100644
@@ -42,6 +42,8 @@ struct fuse_args {
 	bool is_pinned:1;
 	bool invalidate_vmap:1;
 	bool abort_on_kill:1;
+	/* server requested io-uring zero-copy for this op */
+	bool zero_copy:1;
 	struct fuse_in_arg in_args[4];
 	struct fuse_arg out_args[2];
 	void (*end)(struct fuse_args *args, int error);
fs/fuse/dev.c +16 -3
index d50792162d8b..3d1910a9db52 100644
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
 	if (folio) {
 		size = folio_size(folio);
-		if (zeroing && count < size)
-			folio_zero_range(folio, 0, size);
+		if (zeroing && count < size) {
+			if (cs->skip_folio_copy) {
+				if (offset)
+					folio_zero_range(folio, 0, offset);
+				if (offset + count < size)
+					folio_zero_range(folio, offset + count,
+							 size - offset - count);
+			} else {
+				folio_zero_range(folio, 0, size);
+			}
+		}
 	}
 
-	while (count) {
+	while (!cs->skip_folio_copy && count) {
 		if (cs->write && cs->pipebufs && folio) {
 			/*
 			 * Can't control lifetime of pipe buffers, so always
@@ -1344,6 +1353,10 @@ int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
 	for (i = 0; !err && i < numargs; i++)  {
 		struct fuse_arg *arg = &args[i];
 		if (i == numargs - 1 && argpages)
+			/*
+			 * if cs->skip_folio_copy is set, this just does any
+			 * needed zeroing. No copying is involved.
+			 */
 			err = fuse_copy_folios(cs, arg->size, zeroing);
 		else
 			err = fuse_copy_one(cs, arg->value, arg->size);
fs/fuse/dev_uring.c +168 -13

337 lines not on this page · raw message

fs/fuse/dev_uring_i.h +6 -0
index e142cae43022..263d0f8b9714 100644
@@ -79,6 +79,10 @@ struct fuse_ring_ent {
 	/* buffer id in the pool, if bufpools are used. ignored otherwise */
 	unsigned int buf_id;
 
+	/* true if the request's pages are being zero-copied */
+	bool zero_copied;
+	unsigned int zero_copy_index;
+
 	/* the ring queue that owns the request */
 	struct fuse_ring_queue *queue;
 
@@ -142,6 +146,8 @@ struct fuse_ring_queue {
 
 	/* only allocated when payload_mode == FUSE_PAYLOAD_BUFPOOL */
 	struct fuse_bufpool *bufpool;
+
+	bool zero_copy;
 };
 
 /*
fs/fuse/file.c +2 -0
index cb8da4c06d17..791564f11398 100644
@@ -605,6 +605,7 @@ void fuse_read_args_fill(struct fuse_io_args *ia, struct file *file, loff_t pos,
 	args->out_argvar = true;
 	args->out_numargs = 1;
 	args->out_args[0].size = count;
+	args->zero_copy = ff->open_flags & FOPEN_IO_URING_ZERO_COPY;
 }
 
 static void fuse_release_user_pages(struct fuse_args_pages *ap, ssize_t nres,
@@ -1159,6 +1160,7 @@ static void fuse_write_args_fill(struct fuse_io_args *ia, struct fuse_file *ff,
 	args->out_numargs = 1;
 	args->out_args[0].size = sizeof(ia->write.out);
 	args->out_args[0].value = &ia->write.out;
+	args->zero_copy = ff->open_flags & FOPEN_IO_URING_ZERO_COPY;
 }
 
 static unsigned int fuse_write_flags(struct kiocb *iocb)
fs/fuse/fuse_dev_i.h +1 -0
index 668c8391d61c..00722fee572e 100644
@@ -325,6 +325,7 @@ struct fuse_copy_state {
 	bool write:1;
 	bool move_folios:1;
 	bool is_uring:1;
+	bool skip_folio_copy:1;
 	struct {
 		unsigned int copied_sz; /* copied size into the user buffer */
 	} ring;
include/uapi/linux/fuse.h +34 -0
index 07d12f1c55bb..7b842c3f303d 100644
@@ -247,6 +247,8 @@
  *  - add fuse_uring_cmd_req bufpool struct
  *  - add bufpool offset field to fuse_uring_ent_in_out struct
  *  - add FUSE_URING_REGISTERED_BUFPOOL flag
+ *  - add FUSE_URING_ZERO_COPY, FUSE_URING_ENT_ZERO_COPY, and
+ *    FOPEN_IO_URING_ZERO_COPY flag
  */
 
 #ifndef _LINUX_FUSE_H
@@ -390,6 +392,12 @@ struct fuse_file_lock {
  * FOPEN_NOFLUSH: don't flush data cache on close (unless FUSE_WRITEBACK_CACHE)
  * FOPEN_PARALLEL_DIRECT_WRITES: Allow concurrent direct writes on the same inode
  * FOPEN_PASSTHROUGH: passthrough read/write io for this open file
+ * FOPEN_IO_URING_ZERO_COPY: use io-uring zero-copy for reads/writes on this
+ *                           open file. Honored only when the serving io-uring
+ *                           queue was set up for zero-copy
+ *                           (FUSE_URING_ZERO_COPY) and the request carries page
+ *                           payload. Otherwise reads/writes fall back to
+ *                           copying.
  */
 #define FOPEN_DIRECT_IO		(1 << 0)
 #define FOPEN_KEEP_CACHE	(1 << 1)
@@ -399,6 +407,7 @@ struct fuse_file_lock {
 #define FOPEN_NOFLUSH		(1 << 5)
 #define FOPEN_PARALLEL_DIRECT_WRITES	(1 << 6)
 #define FOPEN_PASSTHROUGH	(1 << 7)
+#define FOPEN_IO_URING_ZERO_COPY (1 << 8)
 
 /**
  * INIT request/reply flags
@@ -1260,6 +1269,13 @@ struct fuse_supp_groups {
 #define FUSE_URING_IN_OUT_HEADER_SZ 128
 #define FUSE_URING_OP_IN_OUT_SZ 128
 
+/**
+ * fuse_uring_ent_in_out flags
+ *
+ * FUSE_URING_ENT_ZERO_COPY: Set if the ent's payload is zero-copied
+ */
+#define FUSE_URING_ENT_ZERO_COPY	(1 << 0)
+
 /* Used as part of the fuse_uring_req_header */
 struct fuse_uring_ent_in_out {
 	uint64_t flags;
@@ -1314,6 +1330,14 @@ enum fuse_uring_cmd {
 /* fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_BUFPOOL */
 #define FUSE_URING_REGISTERED_BUFPOOL	(1 << 0)
 
+/*
+ * fuse_uring_cmd_req flags for FUSE_IO_URING_CMD_ADD_QUEUE
+ *
+ * FUSE_URING_ZERO_COPY is only supported for queues with bufpools on privileged
+ * servers
+ */
+#define FUSE_URING_ZERO_COPY		(1 << 0)
+
 /**
  * In the 80B command area of the SQE.
  */
@@ -1333,6 +1357,16 @@ struct fuse_uring_cmd_req {
 			uint64_t uaddr;
 			uint32_t len;
 		} bufpool;
+
+		/*
+		 * Index of this entry's slot in the server's io_uring
+		 * registered buffer table, where the kernel registers the
+		 * request's pages for zero-copy. Set for
+		 * FUSE_IO_URING_CMD_REGISTER cmds only, and only on queues
+		 * created with FUSE_URING_ZERO_COPY. On a non-zero-copy queue
+		 * this must be 0
+		 */
+		uint16_t ent_zero_copy_buf_index;
 	};
 };
 
Signature · 1 line
2.52.0
maintainer
#26 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 168 lines · Joanne Koong

Implement zero-copy in fuse io-uring to eliminate memory copies between the application, kernel, and server for read/write operations. The server can directly access client pages or page cache folios without copying data through an intermediary buffer. When a fuse request arrives, the kernel registers the relevant pages into a sparse slot in the server's io_uring registered buffer table. The server can then operate on these pages directly using io-uring fixed buffer operations (eg read_fixed/write_fixed) and the kernel unregisters these pages when the request completes. Non-page-backed args (eg op out headers) will go through the payload buffer as normal. The server can specify which open files should have their reads/writes go through zero-copy, by setting the FOPEN_IO_URING_ZERO_COPY flag when servicing opens.

This requires CAP_SYS_ADMIN and bufpools. This is gated behind CAP_SYS_ADMIN because zero-copy allows the server direct access to the client's underlying pages, rather than operating on an intermediary buffer that the contents of the client's pages were copied into or on page cache folios.

The request flow for the zero-copy direct-io write path (client writes data, server reads it) is as follows:
=======================================================================

|  Kernel                                   |  FUSE server
|                                           |
|  "write(fd, buf, 1MB)"                    |
|                                           |
|  >sys_write()                             |
|    >fuse_file_write_iter()                |
|      >fuse_send_one()                     |
|        [req->args->in_pages = true]       |
|        [folios hold client write data]    |
|                                           |
|  >fuse_uring_copy_to_ring()               |
|    >copy_header_to_ring(IN_OUT)           |
|      [memcpy fuse_in_header]              |
|    >copy_header_to_ring(OP)               |
|      [memcpy write_in header]             |
|                                           |
|    >fuse_uring_args_to_ring()             |
|      >setup_fuse_copy_state()             |
|        [skip_folio_copy = true]           |
|                                           |
|      >fuse_uring_set_up_zero_copy()       |
|        [folio_get for each client folio]  |
|        [build bio_vec array from folios]  |
|        >io_buffer_register_bvec()         |
|          [register pages at
                 ent->zero_copy_index]      |
|        [ent->zero_copied = true]          |
|                                           |
|      >fuse_copy_args()                    |
|        [skip_folio_copy => return 0       |
|         for page arg, skip data copy]     |
|                                           |
|    >copy_header_to_ring(RING_ENT)         |
|      [memcpy ent_in_out]                  |
|    >io_uring_cmd_done()                   |
|                                           |
|                                           | [CQE received]
|                                           |
|                                           | [issue io_uring READ at
|                                           |  ent->zero_copy_index]
|                                           | [reads directly from
|                                           |client's pages (ZERO_COPY)]
|                                           |
|                                           | [write data to backing
|                                           | store]
|                                           |  [submit COMMIT AND FETCH]
|                                           |
|  >fuse_uring_commit_fetch()               |
|    >fuse_uring_commit()                   |
|      >fuse_uring_copy_from_ring()         |
|    >fuse_uring_req_end()                  |
|      >io_buffer_unregister(ent->zero_copy_index) |
|        [unregister pages from index]      |
|      >fuse_zero_copy_release()            |
|        [folio_put for each folio]         |
|      [ent->zero_copied = false]           |
|      >fuse_request_end()                  |
|        [wake up client]                   |

The zero-copy read path is analogous.

Some requests may have both page-backed args and non-page-backed args. For these requests, the page-backed args are zero-copied while the non-page-backed args are copied to the buffer selected from the buffer pool:
zero-copy: pages registered via io_buffer_register_bvec()
non-page-backed: copied to payload buffer via fuse_copy_args()

For a request whose payload is zero-copied, the
registration/unregistration path looks like:

    register:  fuse_uring_set_up_zero_copy()
                 folio_get() for each folio
                 io_buffer_register_bvec(ent->zero_copy_index)

    unregister: fuse_uring_req_end()
                  io_buffer_unregister(ent->zero_copy_index)
                  -> fuse_zero_copy_release() callback
                     folio_put() for each folio

Please note that on abort for in-flight zero-copied requests that have been sent to userspace, the registered bvec slot remains occupied and its folios remain pinned until the io-uring ring is destroyed, at which point io-uring unregisters all buffers and the fuse_zero_copy_release() callback drops the folio references. Unregistering at teardown would require operating on the ring context directly, whose validity is hard to ascertain; this is deemed not worth the complexity for the abort race, since everything is freed when the ring is torn down.

The throughput improvement from zero-copy depends on how much of the per-request latency is spent on data copying vs backing I/O. The gain comes from eliminating the payload-buffer memcpy, but accessing the zero-copied pages requires the server to issue the read/write as an IORING_OP_READ/WRITE_FIXED operation. The benefit is largest when the mempcy is a meaningful fraction of per-request latency while backing i/o is still noticable enough that the extra io-uring op's overhead doesn't dominate.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

baseline registered-buf zero-copy (zc vs base)

direct read     ~5.1 GB/s  ~5.4 GB/s        ~8.9 GB/s   (+75%)
direct write    ~3.4 GB/s  ~4.8 GB/s        ~5.1 GB/s   (+50%)

Reads end up higher than writes because the backing store reads faster than it writes (the baseline shows the same read>write gap, and the raw device does too). On a device-bound NVMe (~2 GB/s reads) the read gain shrinks to ~10-16% (and no measurable gains for writes), as backing I/O rather than the eliminated copy dominates latency.

The benefit overall scales with how much of the per-request latency is the data copy versus backing I/O.

---
 fs/fuse/args.h            |   2 +
 fs/fuse/dev.c             |  19 +++-
 fs/fuse/dev_uring.c       | 181 +++++++++++++++++++++++++++++++++++---
 fs/fuse/dev_uring_i.h     |   6 ++
 fs/fuse/file.c            |   2 +
 fs/fuse/fuse_dev_i.h      |   1 +
 include/uapi/linux/fuse.h |  34 +++++++
 7 files changed, 229 insertions(+), 16 deletions(-)
fs/fuse/args.h +2 -0
index ecfe51a192af..5173264a1261 100644
@@ -42,6 +42,8 @@ struct fuse_args {
 	bool is_pinned:1;
 	bool invalidate_vmap:1;
 	bool abort_on_kill:1;
+	/* server requested io-uring zero-copy for this op */
+	bool zero_copy:1;
 	struct fuse_in_arg in_args[4];
 	struct fuse_arg out_args[2];
 	void (*end)(struct fuse_args *args, int error);
fs/fuse/dev.c +0 -0
index d50792162d8b..3d1910a9db52 100644

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1250

Quoted 6 lines
fs/fuse/dev.c +1 -2
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
 	if (folio) {
 		size = folio_size(folio);
-		if (zeroing && count < size)
-			folio_zero_range(folio, 0, size);
+		if (zeroing && count < size) {

This function is quite complex and long, maybe a comment here

/* io-uring zery-copy */

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1256

Quoted 6 lines
fs/fuse/dev.c +6 -0
+			if (cs->skip_folio_copy) {
+				if (offset)
+					folio_zero_range(folio, 0, offset);
+				if (offset + count < size)
+					folio_zero_range(folio, offset + count,
+							 size - offset - count);

Maybe
folio_zero_segments(folio, 0, offset, offset + count, size);

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1263

Quoted 8 lines
fs/fuse/dev.c +5 -1
+			} else {
+				folio_zero_range(folio, 0, size);
+			}
+		}
 	}
 
-	while (count) {
+	while (!cs->skip_folio_copy && count) {

For readibility and also to let the compiler know that cs->skip_folio_copy never changes, maybe at the top of the function

const bool uring_zero_copy = cs->skip_folio_copy;

and then

while (!uring_zero_copy && count) {

Also would avoid the comment I asked for above.

Quoted 115 lines
fs/fuse/dev.c +4 -0
 		if (cs->write && cs->pipebufs && folio) {
 			/*
 			 * Can't control lifetime of pipe buffers, so always
@@ -1344,6 +1353,10 @@ int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
 	for (i = 0; !err && i < numargs; i++)  {
 		struct fuse_arg *arg = &args[i];
 		if (i == numargs - 1 && argpages)
+			/*
+			 * if cs->skip_folio_copy is set, this just does any
+			 * needed zeroing. No copying is involved.
+			 */
 			err = fuse_copy_folios(cs, arg->size, zeroing);
 		else
 			err = fuse_copy_one(cs, arg->value, arg->size);
fs/fuse/dev_uring.c +42 -2
index ed7e783bd68d..d7d517497a1e 100644
@@ -23,6 +23,7 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_PAYLOAD 1
 
 #define FUSE_URING_ADD_BUFPOOL_FLAGS	(FUSE_URING_REGISTERED_BUFPOOL)
+#define FUSE_URING_ADD_QUEUE_FLAGS	(FUSE_URING_ZERO_COPY)
 
 bool fuse_uring_enabled(void)
 {
@@ -33,6 +34,11 @@ struct fuse_uring_pdu {
 	struct fuse_ring_ent *ent;
 };
 
+struct fuse_zero_copy_bvs {
+	unsigned int nr_bvs;
+	struct bio_vec bvs[];
+};
+
 static const struct fuse_iqueue_ops fuse_io_uring_ops;
 
 enum fuse_uring_header_type {
@@ -115,8 +121,36 @@ static void fuse_uring_flush_bg(struct fuse_ring_queue *queue)
 	}
 }
 
+static bool can_zero_copy_req(struct fuse_ring_ent *ent, struct fuse_req *req)
+{
+	struct fuse_args *args = req->args;
+
+	if (!ent->queue->zero_copy || !args->zero_copy)
+		return false;
+
+	if (args->opcode != FUSE_READ && args->opcode != FUSE_WRITE)
+		return false;
+
+	return args->in_pages || args->out_pages;
+}
+
+static void zero_copy_unregister(struct io_uring_cmd *cmd,
+				 struct fuse_ring_ent *ent,
+				 unsigned int issue_flags)
+{
+	if (ent->zero_copied) {
+		int err = io_buffer_unregister(cmd, ent->zero_copy_index,
+					       issue_flags);
+
+		if (err)
+			pr_warn_ratelimited("qid=%d zero-copy unregister failed: %d\n",
+					    ent->queue->qid, err);
+		ent->zero_copied = false;
+	}
+}
+
 static void fuse_uring_req_end(struct fuse_ring_ent *ent, struct fuse_req *req,
-			       int error)
+			       int error, unsigned int issue_flags)
 {
 	struct fuse_ring_queue *queue = ent->queue;
 	struct fuse_ring *ring = queue->ring;
@@ -136,6 +170,8 @@ static void fuse_uring_req_end(struct fuse_ring_ent *ent, struct fuse_req *req,
 
 	spin_unlock(&queue->lock);
 
+	zero_copy_unregister(ent->cmd, ent, issue_flags);
+
 	if (error)
 		req->out.h.error = error;
 
@@ -311,7 +347,7 @@ void fuse_uring_conn_init(struct fuse_chan *fch)
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
-						       int qid,
+						       int qid, bool zero_copy,
 						       bool fail_if_exists)
 {
 	struct fuse_chan *fch = ring->chan;
@@ -330,6 +366,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
 	queue->qid = qid;
 	queue->ring = ring;
 	spin_lock_init(&queue->lock);
+	queue->zero_copy = zero_copy;
 
 	INIT_LIST_HEAD(&queue->ent_avail_queue);
 	INIT_LIST_HEAD(&queue->ent_commit_queue);
@@ -715,6 +752,9 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 
 	fuse_copy_init(cs, dir == ITER_DEST, iter);
 
+	if (ent->zero_copied)
+		cs->skip_folio_copy = true;
+
 	cs->is_uring = true;
 	cs->req = req;
 
@@ -746,6 +786,62 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
 	return err;
 }

fs/fuse/dev_uring.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 797

Quoted 10 lines
fs/fuse/dev_uring.c +9 -0
 
+static void fuse_zero_copy_release(void *priv)
+{
+	struct fuse_zero_copy_bvs *zc_bvs = priv;
+	unsigned int i;
+
+	for (i = 0; i < zc_bvs->nr_bvs; i++)
+		folio_put(page_folio(zc_bvs->bvs[i].bv_page));
+
+	kfree(zc_bvs);

kvfree (see below)?

Quoted 11 lines
fs/fuse/dev_uring.c +11 -0
+}
+
+static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
+				       struct fuse_req *req,
+				       unsigned int issue_flags)
+{
+	struct fuse_args_pages *ap;
+	int err, i, ddir = 0;
+	struct fuse_zero_copy_bvs *zc_bvs;
+	struct bio_vec *bvs;
+

fs/fuse/dev_uring.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 818

Quoted 10 lines
fs/fuse/dev_uring.c +10 -0
+	/* out_pages indicates a read, in_pages indicates a write */
+	if (req->args->out_pages)
+		ddir |= IO_BUF_DEST;
+	if (req->args->in_pages)
+		ddir |= IO_BUF_SOURCE;
+
+	ap = container_of(req->args, typeof(*ap), args);
+
+	zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
+			 GFP_KERNEL_ACCOUNT);

Assuming one folio per page and 1MB max_nr_pages:

struct_size(zc_bvs, bvs, n) == 8 + 16 * 256 = 4104

Shouldn't this be kvmalloc()?

(otherwise looks good, will do another review in the morning, though).

Thanks,
Bernd

author maintainer
#27 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 24 lines · Bernd Schubert

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1250

Quoted 12 lines
fs/fuse/dev.c +1 -2
index d50792162d8b..3d1910a9db52 100644
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
      if (folio) {
              size = folio_size(folio);
-             if (zeroing && count < size)
-                     folio_zero_range(folio, 0, size);
+             if (zeroing && count < size) {

This function is quite complex and long, maybe a comment here

/* io-uring zery-copy */

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1256

Quoted 6 lines
fs/fuse/dev.c +6 -0
+                     if (cs->skip_folio_copy) {
+                             if (offset)
+                                     folio_zero_range(folio, 0, offset);
+                             if (offset + count < size)
+                                     folio_zero_range(folio, offset + count,
+                                                      size - offset - count);
Quoted 2 lines

Maybe
folio_zero_segments(folio, 0, offset, offset + count, size);

Nice, didn't realize folio_zero_segments existed. I'll use this API.

Quoted 13 lines

fs/fuse/dev.c int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, · line 1263

Quoted 9 lines
fs/fuse/dev.c +5 -1
+                     } else {
+                             folio_zero_range(folio, 0, size);
+                     }
+             }
      }
 
-     while (count) {
+     while (!cs->skip_folio_copy && count) {

For readibility and also to let the compiler know that cs->skip_folio_copy never changes, maybe at the top of the function

Quoted 8 lines

const bool uring_zero_copy = cs->skip_folio_copy;

and then

while (!uring_zero_copy && count) {

Also would avoid the comment I asked for above.

Sounds good, will do.

Quoted 153 lines
Quoted 116 lines
fs/fuse/dev.c +4 -0
              if (cs->write && cs->pipebufs && folio) {
                      /*
                       * Can't control lifetime of pipe buffers, so always
@@ -1344,6 +1353,10 @@ int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
      for (i = 0; !err && i < numargs; i++)  {
              struct fuse_arg *arg = &args[i];
              if (i == numargs - 1 && argpages)
+                     /*
+                      * if cs->skip_folio_copy is set, this just does any
+                      * needed zeroing. No copying is involved.
+                      */
                      err = fuse_copy_folios(cs, arg->size, zeroing);
              else
                      err = fuse_copy_one(cs, arg->value, arg->size);
fs/fuse/dev_uring.c +42 -2
index ed7e783bd68d..d7d517497a1e 100644
@@ -23,6 +23,7 @@ MODULE_PARM_DESC(enable_uring,
 #define FUSE_URING_IOV_PAYLOAD 1
 
 #define FUSE_URING_ADD_BUFPOOL_FLAGS (FUSE_URING_REGISTERED_BUFPOOL)
+#define FUSE_URING_ADD_QUEUE_FLAGS   (FUSE_URING_ZERO_COPY)
 
 bool fuse_uring_enabled(void)
 {
@@ -33,6 +34,11 @@ struct fuse_uring_pdu {
      struct fuse_ring_ent *ent;
 };
 
+struct fuse_zero_copy_bvs {
+     unsigned int nr_bvs;
+     struct bio_vec bvs[];
+};
+
 static const struct fuse_iqueue_ops fuse_io_uring_ops;
 
 enum fuse_uring_header_type {
@@ -115,8 +121,36 @@ static void fuse_uring_flush_bg(struct fuse_ring_queue *queue)
      }
 }
 
+static bool can_zero_copy_req(struct fuse_ring_ent *ent, struct fuse_req *req)
+{
+     struct fuse_args *args = req->args;
+
+     if (!ent->queue->zero_copy || !args->zero_copy)
+             return false;
+
+     if (args->opcode != FUSE_READ && args->opcode != FUSE_WRITE)
+             return false;
+
+     return args->in_pages || args->out_pages;
+}
+
+static void zero_copy_unregister(struct io_uring_cmd *cmd,
+                              struct fuse_ring_ent *ent,
+                              unsigned int issue_flags)
+{
+     if (ent->zero_copied) {
+             int err = io_buffer_unregister(cmd, ent->zero_copy_index,
+                                            issue_flags);
+
+             if (err)
+                     pr_warn_ratelimited("qid=%d zero-copy unregister failed: %d\n",
+                                         ent->queue->qid, err);
+             ent->zero_copied = false;
+     }
+}
+
 static void fuse_uring_req_end(struct fuse_ring_ent *ent, struct fuse_req *req,
-                            int error)
+                            int error, unsigned int issue_flags)
 {
      struct fuse_ring_queue *queue = ent->queue;
      struct fuse_ring *ring = queue->ring;
@@ -136,6 +170,8 @@ static void fuse_uring_req_end(struct fuse_ring_ent *ent, struct fuse_req *req,
 
      spin_unlock(&queue->lock);
 
+     zero_copy_unregister(ent->cmd, ent, issue_flags);
+
      if (error)
              req->out.h.error = error;
 
@@ -311,7 +347,7 @@ void fuse_uring_conn_init(struct fuse_chan *fch)
 }
 
 static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
-                                                    int qid,
+                                                    int qid, bool zero_copy,
                                                     bool fail_if_exists)
 {
      struct fuse_chan *fch = ring->chan;
@@ -330,6 +366,7 @@ static struct fuse_ring_queue *fuse_uring_create_queue(struct fuse_ring *ring,
      queue->qid = qid;
      queue->ring = ring;
      spin_lock_init(&queue->lock);
+     queue->zero_copy = zero_copy;
 
      INIT_LIST_HEAD(&queue->ent_avail_queue);
      INIT_LIST_HEAD(&queue->ent_commit_queue);
@@ -715,6 +752,9 @@ static int setup_fuse_copy_state(struct fuse_copy_state *cs,
 
      fuse_copy_init(cs, dir == ITER_DEST, iter);
 
+     if (ent->zero_copied)
+             cs->skip_folio_copy = true;
+
      cs->is_uring = true;
      cs->req = req;
 
@@ -746,6 +786,62 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
      return err;
 }

fs/fuse/dev_uring.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 797

Quoted 10 lines
fs/fuse/dev_uring.c +9 -0
 
+static void fuse_zero_copy_release(void *priv)
+{
+     struct fuse_zero_copy_bvs *zc_bvs = priv;
+     unsigned int i;
+
+     for (i = 0; i < zc_bvs->nr_bvs; i++)
+             folio_put(page_folio(zc_bvs->bvs[i].bv_page));
+
+     kfree(zc_bvs);

kvfree (see below)?

Quoted 11 lines
fs/fuse/dev_uring.c +11 -0
+}
+
+static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
+                                    struct fuse_req *req,
+                                    unsigned int issue_flags)
+{
+     struct fuse_args_pages *ap;
+     int err, i, ddir = 0;
+     struct fuse_zero_copy_bvs *zc_bvs;
+     struct bio_vec *bvs;
+

fs/fuse/dev_uring.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 818

Quoted 10 lines
fs/fuse/dev_uring.c +10 -0
+     /* out_pages indicates a read, in_pages indicates a write */
+     if (req->args->out_pages)
+             ddir |= IO_BUF_DEST;
+     if (req->args->in_pages)
+             ddir |= IO_BUF_SOURCE;
+
+     ap = container_of(req->args, typeof(*ap), args);
+
+     zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
+                      GFP_KERNEL_ACCOUNT);

Assuming one folio per page and 1MB max_nr_pages:

Quoted 3 lines

struct_size(zc_bvs, bvs, n) == 8 + 16 * 256 = 4104

Shouldn't this be kvmalloc()?

I'm not sure what the upper limit is for a kmalloc, but I'll change this to kvmalloc().

Quoted 3 lines

(otherwise looks good, will do another review in the morning, though).

Thanks for reviewing the patches!

Thanks,
Joanne

maintainer
#28 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 48 lines · Joanne Koong
Quoted 47 lines · Bernd Schubert
Quoted 10 lines
fs/fuse/dev.c +0 -0
index d50792162d8b..3d1910a9db52 100644
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
@@ -746,6 +786,62 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
      return err;
 }

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 797

Quoted 10 lines
fs/fuse/dev.c +9 -0
 
+static void fuse_zero_copy_release(void *priv)
+{
+     struct fuse_zero_copy_bvs *zc_bvs = priv;
+     unsigned int i;
+
+     for (i = 0; i < zc_bvs->nr_bvs; i++)
+             folio_put(page_folio(zc_bvs->bvs[i].bv_page));
+
+     kfree(zc_bvs);

kvfree (see below)?

Quoted 11 lines
fs/fuse/dev.c +11 -0
+}
+
+static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
+                                    struct fuse_req *req,
+                                    unsigned int issue_flags)
+{
+     struct fuse_args_pages *ap;
+     int err, i, ddir = 0;
+     struct fuse_zero_copy_bvs *zc_bvs;
+     struct bio_vec *bvs;
+

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 818

Quoted 10 lines
fs/fuse/dev.c +10 -0
+     /* out_pages indicates a read, in_pages indicates a write */
+     if (req->args->out_pages)
+             ddir |= IO_BUF_DEST;
+     if (req->args->in_pages)
+             ddir |= IO_BUF_SOURCE;
+
+     ap = container_of(req->args, typeof(*ap), args);
+
+     zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
+                      GFP_KERNEL_ACCOUNT);

Assuming one folio per page and 1MB max_nr_pages:

Quoted 6 lines
Quoted 3 lines

struct_size(zc_bvs, bvs, n) == 8 + 16 * 256 = 4104

Shouldn't this be kvmalloc()?

I'm not sure what the upper limit is for a kmalloc, but I'll change this to kvmalloc().

As far as I know kmalloc will allocate continuos pages and might fail under fragmentation if more than a page is needed. I'm not entirely sure if kvmalloc for such a small allocation will actually do the job. How about the attached patch? And with that maybe we should limit max_nr_pages to 256 for ZC?

Thanks,
Bernd

fs/fuse/dev_uring.c +9 -27
index d7d517497a1e..e1b55f7c0c09 100644
@@ -34,11 +34,6 @@ struct fuse_uring_pdu {
 	struct fuse_ring_ent *ent;
 };
 
-struct fuse_zero_copy_bvs {
-	unsigned int nr_bvs;
-	struct bio_vec bvs[];
-};
-
 static const struct fuse_iqueue_ops fuse_io_uring_ops;
 
 enum fuse_uring_header_type {
@@ -786,24 +781,12 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
 	return err;
 }
 
-static void fuse_zero_copy_release(void *priv)
-{
-	struct fuse_zero_copy_bvs *zc_bvs = priv;
-	unsigned int i;
-
-	for (i = 0; i < zc_bvs->nr_bvs; i++)
-		folio_put(page_folio(zc_bvs->bvs[i].bv_page));
-
-	kfree(zc_bvs);
-}
-
 static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
 				       struct fuse_req *req,
 				       unsigned int issue_flags)
 {
 	struct fuse_args_pages *ap;
 	int err, i, ddir = 0;
-	struct fuse_zero_copy_bvs *zc_bvs;
 	struct bio_vec *bvs;
 
 	/* out_pages indicates a read, in_pages indicates a write */
@@ -814,13 +797,11 @@ static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
 
 	ap = container_of(req->args, typeof(*ap), args);
 
-	zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
-			 GFP_KERNEL_ACCOUNT);
-	if (!zc_bvs)
+	/* only needed until registration copies it into the ring */
+	bvs = kmalloc_array(ap->num_folios, sizeof(*bvs), GFP_KERNEL_ACCOUNT);
+	if (!bvs)
 		return -ENOMEM;
 
-	zc_bvs->nr_bvs = ap->num_folios;
-	bvs = zc_bvs->bvs;
 	for (i = 0; i < ap->num_folios; i++) {
 		bvs[i].bv_page = folio_page(ap->folios[i], 0);
 		bvs[i].bv_offset = ap->descs[i].offset;
@@ -828,12 +809,13 @@ static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
 		folio_get(ap->folios[i]);
 	}
 
-	err = io_buffer_register_bvec(ent->cmd, bvs, ap->num_folios,
-				      fuse_zero_copy_release, zc_bvs,
-				      ddir, ent->zero_copy_index,
-				      issue_flags);
+	err = io_buffer_register_bvec(ent->cmd, bvs, ap->num_folios, NULL, NULL,
+				      ddir, IO_BUF_F_PUT_FOLIOS,
+				      ent->zero_copy_index, issue_flags);
+	kfree(bvs);
 	if (err) {
-		fuse_zero_copy_release(zc_bvs);
+		for (i = 0; i < ap->num_folios; i++)
+			folio_put(ap->folios[i]);
 		return err;
 	}
 
include/linux/io_uring/cmd.h +13 -3
index 42801f0b6456..980948c86c62 100644
@@ -41,6 +41,15 @@ static inline void io_uring_cmd_private_sz_check(size_t cmd_sz)
 	((pdu_type *)&(cmd)->pdu) \
 )
 
+/* Flags for io_buffer_register_bvec() */
+enum io_buffer_register_flags {
+	/*
+	 * The caller holds a folio reference per bvec, to be dropped when the
+	 * buffer is released. Registers without release/priv.
+	 */
+	IO_BUF_F_PUT_FOLIOS	= (1u << 0),
+};
+
 #if defined(CONFIG_IO_URING)
 int io_uring_cmd_import_fixed(u64 ubuf, unsigned long len, int rw,
 			      struct iov_iter *iter,
@@ -96,8 +105,8 @@ int io_buffer_register_request(struct io_uring_cmd *cmd, struct request *rq,
 			       unsigned int issue_flags);
 int io_buffer_register_bvec(struct io_uring_cmd *cmd, const struct bio_vec *bvs,
 			    unsigned int nr_bvecs, void (*release)(void *),
-			    void *priv, u8 dir, unsigned int index,
-			    unsigned int issue_flags);
+			    void *priv, u8 dir, unsigned int flags,
+			    unsigned int index, unsigned int issue_flags);
 int io_buffer_unregister(struct io_uring_cmd *cmd, unsigned int index,
 			 unsigned int issue_flags);
 #else
@@ -154,7 +163,8 @@ static inline int io_buffer_register_bvec(struct io_uring_cmd *cmd,
 					  const struct bio_vec *bvs,
 					  unsigned int nr_bvecs,
 					  void (*release)(void *), void *priv,
-					  u8 dir, unsigned int index,
+					  u8 dir, unsigned int flags,
+					  unsigned int index,
 					  unsigned int issue_flags)
 {
 	return -EOPNOTSUPP;
io_uring/rsrc.c +17 -2
index f3f01e0c8102..bd73a7ee98cc 100644
@@ -158,6 +158,15 @@ static void io_release_ubuf(void *priv)
 	}
 }
 
+static void io_release_kbuf_folios(void *priv)
+{
+	struct io_mapped_ubuf *imu = priv;
+	unsigned int i;
+
+	for (i = 0; i < imu->nr_bvecs; i++)
+		folio_put(bvec_folio(&imu->bvec[i]));
+}
+
 static struct io_mapped_ubuf *io_alloc_imu(struct io_ring_ctx *ctx,
 					   int nr_bvecs)
 {
@@ -1101,8 +1110,8 @@ EXPORT_SYMBOL_GPL(io_buffer_register_request);
  */
 int io_buffer_register_bvec(struct io_uring_cmd *cmd, const struct bio_vec *bvs,
 			    unsigned int nr_bvecs, void (*release)(void *),
-			    void *priv, u8 dir, unsigned int index,
-			    unsigned int issue_flags)
+			    void *priv, u8 dir, unsigned int flags,
+			    unsigned int index, unsigned int issue_flags)
 {
 	struct io_ring_ctx *ctx = cmd_to_io_kiocb(cmd)->ctx;
 	struct io_mapped_ubuf *imu;
@@ -1125,6 +1134,12 @@ int io_buffer_register_bvec(struct io_uring_cmd *cmd, const struct bio_vec *bvs,
 	for (i = 0; i < nr_bvecs; i++)
 		bvec[i] = bvs[i];
 
+	/* imu is only known here, and needs the bvecs in place */
+	if (flags & IO_BUF_F_PUT_FOLIOS) {
+		imu->release = io_release_kbuf_folios;
+		imu->priv = imu;
+	}
+
 unlock:
 	io_ring_submit_unlock(ctx, issue_flags);
 	return ret;
author maintainer
#29 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 60 lines · Bernd Schubert
Quoted 48 lines · Joanne Koong
Quoted 47 lines · Bernd Schubert
Quoted 10 lines
fs/fuse/dev.c +0 -0
index d50792162d8b..3d1910a9db52 100644
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
@@ -746,6 +786,62 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
      return err;
 }

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 797

Quoted 10 lines
fs/fuse/dev.c +9 -0
 
+static void fuse_zero_copy_release(void *priv)
+{
+     struct fuse_zero_copy_bvs *zc_bvs = priv;
+     unsigned int i;
+
+     for (i = 0; i < zc_bvs->nr_bvs; i++)
+             folio_put(page_folio(zc_bvs->bvs[i].bv_page));
+
+     kfree(zc_bvs);

kvfree (see below)?

Quoted 11 lines
fs/fuse/dev.c +11 -0
+}
+
+static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
+                                    struct fuse_req *req,
+                                    unsigned int issue_flags)
+{
+     struct fuse_args_pages *ap;
+     int err, i, ddir = 0;
+     struct fuse_zero_copy_bvs *zc_bvs;
+     struct bio_vec *bvs;
+

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 818

Quoted 10 lines
fs/fuse/dev.c +10 -0
+     /* out_pages indicates a read, in_pages indicates a write */
+     if (req->args->out_pages)
+             ddir |= IO_BUF_DEST;
+     if (req->args->in_pages)
+             ddir |= IO_BUF_SOURCE;
+
+     ap = container_of(req->args, typeof(*ap), args);
+
+     zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
+                      GFP_KERNEL_ACCOUNT);

Assuming one folio per page and 1MB max_nr_pages:

Quoted 6 lines
Quoted 3 lines

struct_size(zc_bvs, bvs, n) == 8 + 16 * 256 = 4104

Shouldn't this be kvmalloc()?

I'm not sure what the upper limit is for a kmalloc, but I'll change this to kvmalloc().

Quoted 5 lines

As far as I know kmalloc will allocate continuos pages and might fail under fragmentation if more than a page is needed. I'm not entirely sure if kvmalloc for such a small allocation will actually do the job. How about the attached patch? And with that maybe we should limit max_nr_pages to 256 for ZC?

I think kvmalloc should be fine. For size > PAGE_SIZE it tries kmalloc first and has a fallback to vmalloc. For small allocations, kvmalloc is just plain kmalloc.

Thanks,
Joanne

maintainer
#30 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 67 lines · Joanne Koong
Quoted 60 lines · Bernd Schubert
Quoted 48 lines · Joanne Koong
Quoted 47 lines · Bernd Schubert
Quoted 10 lines
fs/fuse/dev.c +0 -0
index d50792162d8b..3d1910a9db52 100644
@@ -1247,11 +1247,20 @@ int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop,
 
@@ -746,6 +786,62 @@ static int fuse_uring_copy_from_ring(struct fuse_req *req,
      return err;
 }

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 797

Quoted 10 lines
fs/fuse/dev.c +9 -0
 
+static void fuse_zero_copy_release(void *priv)
+{
+     struct fuse_zero_copy_bvs *zc_bvs = priv;
+     unsigned int i;
+
+     for (i = 0; i < zc_bvs->nr_bvs; i++)
+             folio_put(page_folio(zc_bvs->bvs[i].bv_page));
+
+     kfree(zc_bvs);

kvfree (see below)?

Quoted 11 lines
fs/fuse/dev.c +11 -0
+}
+
+static int fuse_uring_set_up_zero_copy(struct fuse_ring_ent *ent,
+                                    struct fuse_req *req,
+                                    unsigned int issue_flags)
+{
+     struct fuse_args_pages *ap;
+     int err, i, ddir = 0;
+     struct fuse_zero_copy_bvs *zc_bvs;
+     struct bio_vec *bvs;
+

fs/fuse/dev.c static int fuse_uring_copy_from_ring(struct fuse_req *req, · line 818

Quoted 10 lines
fs/fuse/dev.c +10 -0
+     /* out_pages indicates a read, in_pages indicates a write */
+     if (req->args->out_pages)
+             ddir |= IO_BUF_DEST;
+     if (req->args->in_pages)
+             ddir |= IO_BUF_SOURCE;
+
+     ap = container_of(req->args, typeof(*ap), args);
+
+     zc_bvs = kmalloc(struct_size(zc_bvs, bvs, ap->num_folios),
+                      GFP_KERNEL_ACCOUNT);

Assuming one folio per page and 1MB max_nr_pages:

Quoted 6 lines
Quoted 3 lines

struct_size(zc_bvs, bvs, n) == 8 + 16 * 256 = 4104

Shouldn't this be kvmalloc()?

I'm not sure what the upper limit is for a kmalloc, but I'll change this to kvmalloc().

Quoted 5 lines

As far as I know kmalloc will allocate continuos pages and might fail under fragmentation if more than a page is needed. I'm not entirely sure if kvmalloc for such a small allocation will actually do the job. How about the attached patch? And with that maybe we should limit max_nr_pages to 256 for ZC?

Quoted 3 lines

I think kvmalloc should be fine. For size > PAGE_SIZE it tries kmalloc first and has a fallback to vmalloc. For small allocations, kvmalloc is just plain kmalloc.

I think the patch I had attached is more elegant, but we can do that any time later. I just found kvmalloc_flex, I guess that would be most suitable.

Thanks,
Bernd

author maintainer
#31 lore raw

Re: [PATCH v6 5/6] fuse: add zero-copy over io-uring

Quoted 8 lines · Bernd Schubert
Quoted 8 lines
Quoted 7 lines

As far as I know kmalloc will allocate continuos pages and might fail under fragmentation if more than a page is needed. I'm not entirely sure if kvmalloc for such a small allocation will actually do the job. How about the attached patch? And with that maybe we should limit max_nr_pages to 256 for ZC?

Quoted 7 lines
Quoted 3 lines

I think kvmalloc should be fine. For size > PAGE_SIZE it tries kmalloc first and has a fallback to vmalloc. For small allocations, kvmalloc is just plain kmalloc.

I think the patch I had attached is more elegant, but we can do that any time later. I just found kvmalloc_flex, I guess that would be most suitable.

I'll change this to use kvmalloc_flex.

Thanks,
Joanne

author maintainer
#32 lore raw

PATCH v6 6/6 docs: fuse: document io-uring buffer pool and zero-copy uapi

In reply to Joanne Koong

Add documentation for fuse over io-uring usage of buffer pools and zero-copy.

---
 .../filesystems/fuse/fuse-io-uring.rst        |  36 ++++-
 Documentation/filesystems/fuse/index.rst      |   1 +
 .../fuse/uapi/fuse-uapi-io-uring.rst          | 129 ++++++++++++++++++
 3 files changed, 164 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst
Documentation/filesystems/fuse/fuse-io-uring.rst +34 -2
index d73dd0dbd238..29f98057500d 100644
@@ -11,6 +11,9 @@ and works. For generic details about FUSE see fuse.rst.
 This document also covers the current interface, which is
 still in development and might change.
 
+For the userspace protocol, see
+Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst.
+
 Limitations
 ===========
 As of now not all requests types are supported through io-uring, userspace
@@ -95,5 +98,34 @@ Sending requests with CQEs
  |    <fuse_unlink()                         |
  |  <sys_unlink()                            |
 
-
-
+Buffer pools
+============
+
+Without a buffer pool, every entry needs to pass a dedicated payload buffer
+large enough for the maximum payload size. A buffer pool decouples entries
+from payload buffers. The server hands the kernel one contiguous buffer pool
+of memory and when the kernel sends the server a request, it indicates the
+offset into the pool for that request's payload. Internally, the kernel is
+able to manage/optimize the buffer pool memory however it likes.
+
+A server may also register the pool region with io_uring as a fixed buffer.
+The backing pages are then pinned once, avoiding per-request pinning and
+address translation. This also allows servers to use the same registered
+buffers for subsequent backing store I/O through io-uring, keeping data
+in the same pinned pages without additional pinning / mapping overhead.
+
+Zero-copy
+=========
+
+Zero-copy lets the server read from / write to the client's pages (pinned
+user pages for direct I/O, or page-cache folios for buffered I/O) without an
+intermediary payload copy. This requires CAP_SYS_ADMIN privileges.
+
+When a fuse request arrives for a file that opted into zero-copy, the kernel
+registers the relevant pages (pinned user pages for direct i/o or underlying
+page cache folios for buffered i/o) into a sparse slot in the server's
+io_uring registered buffer table. The server can then operate on these pages
+directly using io-uring fixed buffer operations (eg read_fixed / write_fixed)
+and the kernel unregisters these pages when the request completes.
+Non-page-backed args (eg op out headers) will go through the payload buffer as
+normal.
Documentation/filesystems/fuse/index.rst +1 -0
index 393a845214da..3dada6c4057a 100644
@@ -12,3 +12,4 @@ FUSE (Filesystem in Userspace) Technical Documentation
    fuse-io
    fuse-io-uring
    fuse-passthrough
+   uapi/fuse-uapi-io-uring
Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst new file +129 -0

129 lines not on this page · raw message

Signature · 1 line
2.52.0
maintainer Reviewed-by on v6 6/6
#33 lore raw

Re: [PATCH v6 6/6] docs: fuse: document io-uring buffer pool and zero-copy uapi

Quoted 196 lines · Joanne Koong

Add documentation for fuse over io-uring usage of buffer pools and zero-copy.

---
 .../filesystems/fuse/fuse-io-uring.rst        |  36 ++++-
 Documentation/filesystems/fuse/index.rst      |   1 +
 .../fuse/uapi/fuse-uapi-io-uring.rst          | 129 ++++++++++++++++++
 3 files changed, 164 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst
Documentation/filesystems/fuse/fuse-io-uring.rst +34 -2
index d73dd0dbd238..29f98057500d 100644
@@ -11,6 +11,9 @@ and works. For generic details about FUSE see fuse.rst.
 This document also covers the current interface, which is
 still in development and might change.
 
+For the userspace protocol, see
+Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst.
+
 Limitations
 ===========
 As of now not all requests types are supported through io-uring, userspace
@@ -95,5 +98,34 @@ Sending requests with CQEs
  |    <fuse_unlink()                         |
  |  <sys_unlink()                            |
 
-
-
+Buffer pools
+============
+
+Without a buffer pool, every entry needs to pass a dedicated payload buffer
+large enough for the maximum payload size. A buffer pool decouples entries
+from payload buffers. The server hands the kernel one contiguous buffer pool
+of memory and when the kernel sends the server a request, it indicates the
+offset into the pool for that request's payload. Internally, the kernel is
+able to manage/optimize the buffer pool memory however it likes.
+
+A server may also register the pool region with io_uring as a fixed buffer.
+The backing pages are then pinned once, avoiding per-request pinning and
+address translation. This also allows servers to use the same registered
+buffers for subsequent backing store I/O through io-uring, keeping data
+in the same pinned pages without additional pinning / mapping overhead.
+
+Zero-copy
+=========
+
+Zero-copy lets the server read from / write to the client's pages (pinned
+user pages for direct I/O, or page-cache folios for buffered I/O) without an
+intermediary payload copy. This requires CAP_SYS_ADMIN privileges.
+
+When a fuse request arrives for a file that opted into zero-copy, the kernel
+registers the relevant pages (pinned user pages for direct i/o or underlying
+page cache folios for buffered i/o) into a sparse slot in the server's
+io_uring registered buffer table. The server can then operate on these pages
+directly using io-uring fixed buffer operations (eg read_fixed / write_fixed)
+and the kernel unregisters these pages when the request completes.
+Non-page-backed args (eg op out headers) will go through the payload buffer as
+normal.
Documentation/filesystems/fuse/index.rst +1 -0
index 393a845214da..3dada6c4057a 100644
@@ -12,3 +12,4 @@ FUSE (Filesystem in Userspace) Technical Documentation
    fuse-io
    fuse-io-uring
    fuse-passthrough
+   uapi/fuse-uapi-io-uring
Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst new file +119 -0
new file mode 100644
index 000000000000..66b0fcbcde24
@@ -0,0 +1,129 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=====================================
+FUSE-over-io-uring uapi documentation
+=====================================
+
+Commands
+========
+
+``enum fuse_uring_cmd``:
+
+``FUSE_IO_URING_CMD_ADD_QUEUE``
+  Create a queue identified by ``fuse_uring_cmd_req.qid``. Queue-wide
+  options are passed in ``fuse_uring_cmd_req.flags``:
+
+  ``FUSE_URING_ZERO_COPY``
+    Enable zero-copy on this queue. Requires ``CAP_SYS_ADMIN`` and a buffer
+    pool, which is added separately via ``ADD_BUFPOOL`` before registering
+    entries (see `Zero-copy`_).
+
+``FUSE_IO_URING_CMD_ADD_BUFPOOL``
+  Register the payload buffer pool for an existing queue. The server provides
+  a single contiguous region in ``fuse_uring_cmd_req.bufpool.uaddr`` /
+  ``.len``. This command must be issued after ``ADD_QUEUE`` and before
+  registering any payload-carrying entries on that queue. Flags:
+
+  ``FUSE_URING_REGISTERED_BUFPOOL``
+    The pool region is registered ahead of time with io_uring to avoid per i/o
+    pinning/unpinning and mapping overhead.
+
+``FUSE_IO_URING_CMD_REGISTER``
+  Register a ring entry (a long-lived SQE that carries the request header
+  iovec). For a zero-copy queue, ``fuse_uring_cmd_req.ent_zero_copy_buf_index``
+  indicates the reserved registered buffer table slot this entry uses for
+  zero-copy (see `Zero-copy`_).
+
+``FUSE_IO_URING_CMD_COMMIT_AND_FETCH``
+  Commit the reply for a completed request and fetch the next one. The
+  request is identified by ``fuse_uring_cmd_req.commit_id`` (the value the
+  kernel reported in ``fuse_uring_ent_in_out.commit_id``).
+
+Structures
+==========
+
+``struct fuse_uring_cmd_req`` (80-byte SQE command area):
+
+============================  ==================================================
+Field                         Meaning
+============================  ==================================================
+``flags``                     Command-specific flags (see each command).
+``commit_id``                 Request id, for ``COMMIT_AND_FETCH``.
+``qid``                       Queue index.
+``bufpool.uaddr``             Pool base address, for ``ADD_BUFPOOL``.
+``bufpool.len``               Pool length in bytes, for ``ADD_BUFPOOL``.
+``ent_zero_copy_buf_index``   Per-entry zero-copy slot, for ``REGISTER``.
+============================  ==================================================
+
+``struct fuse_uring_ent_in_out`` (reported by the kernel per request):
+
+============================  ==================================================
+Field                         Meaning
+============================  ==================================================
+``flags``                     ``FUSE_URING_ENT_ZERO_COPY`` if zero-copied.
+``commit_id``                 Id to echo back in ``COMMIT_AND_FETCH``.
+``payload_sz``                Total payload size in bytes (see `Zero-copy`_).
+``offset``                    Payload buffer offset within the pool.
+============================  ==================================================
+
+Buffer pools
+============
+Setup:
+
+* Issue ``ADD_QUEUE`` for the qid.
+* Issue ``ADD_BUFPOOL`` with ``bufpool.uaddr`` and ``bufpool.len`` pointing
+  at the region.
+* Register entries with ``REGISTER``.
+
+For every request that has a payload, the kernel reports where the payload
+lives in ``struct fuse_uring_ent_in_out`` (part of
+``struct fuse_uring_req_header``):
+
+``offset``
+  Byte offset, within the pool region, for this request's payload buffer.
+  The server adds this to the pool base address to locate the payload.
+
+``payload_sz``
+  Number of payload bytes for this request.
+
+To use registered buffers, the server should pass ``FUSE_URING_REGISTERED_BUFPOOL``
+as a flag to ``ADD_BUFPOOL`` and set ``IORING_URING_CMD_FIXED`` in
+``sqe->uring_cmd_flags`` and put the index of the registered bufpool in
+``sqe->buf_index``. The same registered buffer can be reused for the server's
+backing-store I/O as well (e.g. ``IORING_OP_READ_FIXED`` /
+``IORING_OP_WRITE_FIXED``).
+
+When using registered bufpools, every SQE the server submits must follow the
+standard fixed-buffer protocol: set ``IORING_URING_CMD_FIXED`` in
+``sqe->uring_cmd_flags`` and put the index of the registered bufpool in
+``sqe->buf_index``.
+
+Zero-copy
+=========
+Requirements:
+
+* The server must be privileged (``CAP_SYS_ADMIN``).
+* A zero-copy queue: ``ADD_QUEUE`` with the ``FUSE_URING_ZERO_COPY`` flag set.
+* A buffer pool: ``ADD_BUFPOOL``.
+* For each entry, ``REGISTER`` with ``ent_zero_copy_buf_index`` set to the
+  index this entry uses in the server's io_uring registered-buffer table.
+  This is where the kernel registers the request's pages for the server to
+  access (it is separate from the payload pool). On a non-zero-copy queue this
+  field must be 0.
+
+Zero-copy is selected per open file. The server sets the open-file flag in
+the ``FUSE_OPEN`` / ``FUSE_CREATE`` reply:
+
+``FOPEN_IO_URING_ZERO_COPY``
+  Reads/writes on this open file should use zero-copy.
+

Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst line 129

Quoted 10 lines
Documentation/filesystems/fuse/uapi/fuse-uapi-io-uring.rst new file +10 -0
+For a request that is zero-copied, the kernel sets ``FUSE_URING_ENT_ZERO_COPY``
+in ``fuse_uring_ent_in_out.flags`` and places the request's pages at the
+entry's ``ent_zero_copy_buf_index``. The server then issues
+``IORING_OP_READ_FIXED`` / ``IORING_OP_WRITE_FIXED`` against that index to
+transfer the data directly to/from the client's pages.
+
+For such a request, ``payload_sz`` includes the zero-copied page bytes
+(transferred via the registered buffer at ``ent_zero_copy_buf_index``). Any
+non-page-backed args (e.g. op headers) are still copied through the pool
+payload buffer at ``offset``.

Thank you for the additional documentation!

maintainer
#34 lore raw
In reply to Joanne Koong
Quoted 46 lines · Joanne Koong

This series adds fuse io-uring buffer pools and zero-copy.

Prior to this series, ents and buffers are tightly coupled where each entry has its own dedicated payload buffer, requiring N buffers for N entries where each buffer must be large enough to accomodate the maximum payload size. This is suboptimal as most request types require vastly less bytes than the maximum payload size and some requests do not require payload buffers at all.

This series allows servers to pass in a buffer pool (a contiguous chunk of memory) that the kernel will use as it wishes for servicing ents/requests. This decoupling reduces the memory usage requirements needed to use fuse-io-uring and lets the kernel do any optimizations for assigning payload memory to requests.

This series additionally adds zero copy to fuse io-uring. The server can directly access client pages or page cache folios without copying data through an intermediary buffer. This requires CAP_SYS_ADMIN privileges and using buffer pools. The zero copy patch has a dependency on io-uring registered bvec changes in [1].

This series is on top of commit 7d87a5a284bb and on top of the io-uring bvec changes and the changes from the series in [2] applied.

The throughput improvements from registered buffers and zero-copy depends on how much of the server's per-request latency is spent on data copying vs backing I/O. When backing I/O dominates, the saved memcpy is a negligible fraction of overall latency. Please also note that for the server to read/write into the zero-copied pages, the read/write must go through io-uring as an IORING_OP_READ_FIXED / IORING_OP_WRITE_FIXED operation.

The throughput improvement from zero-copy depends on how much of the per-request latency is spent on data copying vs backing I/O. The gain comes from eliminating the payload-buffer memcpy, but accessing the zero-copied pages requires the server to issue the read/write as an IORING_OP_READ/WRITE_FIXED operation. The benefit is largest when the mempcy is a meaningful fraction of per-request latency while backing i/o is still noticable enough that the extra io-uring op's overhead doesn't dominate.

Benchmarked with passthrough_hp (--nopassthrough, q_depth=8) on a 2-socket Intel Xeon Gold 6138 (40 cores / 80 threads), using fio (sync engine, bs=1M, O_DIRECT, numjobs=2, 30s run + 10s ramp, 3 runs) where direct-I/O throughput is against a RAM-backed (tmpfs) source (backing I/O is not the bottleneck):

Quoted 3 lines
                baseline   registered-buf   zero-copy   (zc vs base)
direct read     ~5.1 GB/s  ~5.4 GB/s        ~8.9 GB/s   (+75%)
direct write    ~3.4 GB/s  ~4.8 GB/s        ~5.1 GB/s   (+50%)

The interface changes make sense and the benchmark results look impressive.

I think if the synchronization between INIT is sorted out then this is good to go. Sashiko can't apply the series, I guess because of the
non-standard base. Not sure if we can help that.

Also because Bernd and you are co-maintainers of fuse-uring, I'd hope for an ack from Bernd (when he returns from vacation).

Thanks,
Miklos

author maintainer
#35 lore raw
Quoted 2 lines · Miklos Szeredi

I think if the synchronization between INIT is sorted out then this is

I'll submit a patch for the INIT synchronization separately to avoid respinning a v7, since it's a pre-existing issue not introduced by this series.

Quoted 5 lines

good to go. Sashiko can't apply the series, I guess because of the
non-standard base. Not sure if we can help that.

Also because Bernd and you are co-maintainers of fuse-uring, I'd hope for an ack from Bernd (when he returns from vacation).

Bernd, this is targeting the 7.3 merge window, which opens August 16th. Because it involves cross-coordination with Jens's tree, I'd prefer to get this in at the start of the window. Can you please look at this series and make it a priority before then?

Thanks,
Joanne

maintainer
#36 lore raw
Quoted 11 lines · Joanne Koong
Quoted 2 lines · Miklos Szeredi

I think if the synchronization between INIT is sorted out then this is

I'll submit a patch for the INIT synchronization separately to avoid respinning a v7, since it's a pre-existing issue not introduced by this series.

Quoted 3 lines

good to go. Sashiko can't apply the series, I guess because of the
non-standard base. Not sure if we can help that.

Quoted 7 lines
Quoted 2 lines

Also because Bernd and you are co-maintainers of fuse-uring, I'd hope for an ack from Bernd (when he returns from vacation).

Bernd, this is targeting the 7.3 merge window, which opens August 16th. Because it involves cross-coordination with Jens's tree, I'd prefer to get this in at the start of the window. Can you please look at this series and make it a priority before then?

I will hopefully get it reviewed till next Sunday, didn't manage last weekend (was kind of working all weekend on the new libfuse test suite, because pytest does not hand out when something hangs). And from tomorrow on traveling again. Exactly that hang and uncooperative pytest caused extra work in the nights when I was on vacation and I then didn't manage the review this series :(

Sorry about the delays,
Bernd