Skip to contentSkip to conversation

io_uring: support sqe group and provide group kbuf

PATCH Superseded Ming Lei 2 participants 20 messages Jul 6, 2024 – Aug 7, 2024

Subsystems (3)

v4 of 8 Superseded Latest is v8 →

lore
Share & tools
lore

Ming Lei

author
#0 lore raw

v4 cover io_uring: support sqe group and provide group kbuf

Hello,

The 1st 3 patches are cleanup, and prepare for adding sqe group.

The 4th patch supports generic sqe group which is like link chain, but allows each sqe in group to be issued in parallel and the group shares same IO_LINK & IO_DRAIN boundary, so N:M dependency can be supported with sqe group & io link together. sqe group changes nothing on IOSQE_IO_LINK.

The 5th patch supports one variant of sqe group: allow members to depend on group leader, so that kernel resource lifetime can be aligned with group leader or group, then any kernel resource can be shared in this sqe group, and can be used in generic device zero copy.

The 6th & 7th patches supports providing sqe group buffer via the sqe group variant.

The 8th patch supports ublk zero copy based on io_uring providing sqe group buffer.

Tests:

1) pass liburing test
- make runtests

2) write/pass two sqe group test cases:

https://github.com/axboe/liburing/compare/master...ming1:liburing:sqe_group_v2

- covers related sqe flags combination and linking groups, both nop and one multi-destination file copy.

- cover failure handling test: fail leader IO or member IO in both single group and linked groups, which is done in each sqe flags combination test

3) ublksrv zero copy:

ublksrv userspace implements zero copy by sqe group & provide group kbuf:

	git clone https://github.com/ublk-org/ublksrv.git -b group-provide-buf_v2
	make test T=loop/009:nbd/061	#ublk zc tests

When running 64KB/512KB block size test on ublk-loop('ublk add -t loop --buffered_io -f $backing'), it is observed that perf is doubled.

Any comments are welcome!

V4:
- address most comments from Pavel
- fix request double free
- don't use io_req_commit_cqe() in io_req_complete_defer()
- make members' REQ_F_INFLIGHT discoverable
- use common assembling check in submission code path
- drop patch 3 and don't move REQ_F_CQE_SKIP out of io_free_req()
- don't set .accept_group_kbuf for net send zc, in which members need to be queued after buffer notification is got, and can be enabled in future
- add .grp_leader field via union, and share storage with .grp_link
- move .grp_refs into one hole of io_kiocb, so that one extra cacheline isn't needed for io_kiocb
- cleanup & document improvement

V3:
- add IORING_FEAT_SQE_GROUP
- simplify group completion, and minimize change on io_req_complete_defer()
- simplify & cleanup io_queue_group_members()
- fix many failure handling issues
- cover failure handling code in added liburing tests
- remove RFC

V2:
- add generic sqe group, suggested by Kevin Wolf
- add REQ_F_SQE_GROUP_DEP which is based on IOSQE_SQE_GROUP, for sharing kernel resource in group wide, suggested by Kevin Wolf
- remove sqe ext flag, and use the last bit for IOSQE_SQE_GROUP(Pavel), in future we still can extend sqe flags with one uring context flag
- initialize group requests via submit state pattern, suggested by Pavel
- all kinds of cleanup & bug fixes

Ming Lei (8):
io_uring: add io_link_req() helper
io_uring: add io_submit_fail_link() helper
io_uring: add helper of io_req_commit_cqe()
io_uring: support SQE group
io_uring: support sqe group with members depending on leader
io_uring: support providing sqe group buffer io_uring/uring_cmd: support provide group kernel buffer
ublk: support provide io buffer

 drivers/block/ublk_drv.c       | 158 ++++++++++++-
 include/linux/io_uring/cmd.h   |   7 +
 include/linux/io_uring_types.h |  54 +++++
 include/uapi/linux/io_uring.h  |  11 +-
 include/uapi/linux/ublk_cmd.h  |   7 +-
 io_uring/io_uring.c            | 392 +++++++++++++++++++++++++++++----
 io_uring/io_uring.h            |  24 ++
 io_uring/kbuf.c                |  60 +++++
 io_uring/kbuf.h                |  13 ++
 io_uring/net.c                 |  23 +-
 io_uring/opdef.c               |   4 +
 io_uring/opdef.h               |   2 +
 io_uring/rw.c                  |  20 +-
 io_uring/timeout.c             |   2 +
 io_uring/uring_cmd.c           |  28 +++
 15 files changed, 752 insertions(+), 53 deletions(-)
Signature · 1 line
2.42.0
author
#1 lore raw

PATCH v4 1/8 io_uring: add io_link_req() helper

Add io_link_req() helper, so that io_submit_sqe() becomes more readable.

---
 io_uring/io_uring.c | 41 +++++++++++++++++++++++++++--------------
 1 file changed, 27 insertions(+), 14 deletions(-)
io_uring/io_uring.c +27 -14
index 42139bb85fff..617ee97bb3f2 100644
@@ -2132,19 +2132,11 @@ static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
 	return 0;
 }
 
-static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
-			 const struct io_uring_sqe *sqe)
-	__must_hold(&ctx->uring_lock)
+/*
+ * Return NULL if nothing to be queued, otherwise return request for queueing */
+static struct io_kiocb *io_link_sqe(struct io_submit_link *link,
+				    struct io_kiocb *req)
 {
-	struct io_submit_link *link = &ctx->submit_state.link;
-	int ret;
-
-	ret = io_init_req(ctx, req, sqe);
-	if (unlikely(ret))
-		return io_submit_fail_init(sqe, req, ret);
-
-	trace_io_uring_submit_req(req);
-
 	/*
 	 * If we already have a head request, queue this one for async
 	 * submittal once the head completes. If we don't have a head but
@@ -2158,7 +2150,7 @@ static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
 		link->last = req;
 
 		if (req->flags & IO_REQ_LINK_FLAGS)
-			return 0;
+			return NULL;
 		/* last request of the link, flush it */
 		req = link->head;
 		link->head = NULL;
@@ -2174,9 +2166,30 @@ static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
 fallback:
 			io_queue_sqe_fallback(req);
 		}
-		return 0;
+		return NULL;
 	}
+	return req;
+}
+
+static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
+			 const struct io_uring_sqe *sqe)
+	__must_hold(&ctx->uring_lock)
+{
+	struct io_submit_link *link = &ctx->submit_state.link;
+	int ret;
 
+	ret = io_init_req(ctx, req, sqe);
+	if (unlikely(ret))
+		return io_submit_fail_init(sqe, req, ret);
+
+	trace_io_uring_submit_req(req);
+
+	if (unlikely(link->head || (req->flags & (IO_REQ_LINK_FLAGS |
+				    REQ_F_FORCE_ASYNC | REQ_F_FAIL)))) {
+		req = io_link_sqe(link, req);
+		if (!req)
+			return 0;
+	}
 	io_queue_sqe(req);
 	return 0;
 }
Signature · 1 line
2.42.0
author
#2 lore raw

PATCH v4 2/8 io_uring: add io_submit_fail_link() helper

In reply to Ming Lei

Add io_submit_fail_link() helper and put linking fail logic into this helper.

This way simplifies io_submit_fail_init(), and becomes easier to add sqe group failing logic.

---
 io_uring/io_uring.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
io_uring/io_uring.c +16 -6
index 617ee97bb3f2..5d69851b5131 100644
@@ -2095,22 +2095,17 @@ static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
 	return def->prep(req, sqe);
 }
 
-static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
+static __cold int io_submit_fail_link(struct io_submit_link *link,
 				      struct io_kiocb *req, int ret)
 {
-	struct io_ring_ctx *ctx = req->ctx;
-	struct io_submit_link *link = &ctx->submit_state.link;
 	struct io_kiocb *head = link->head;
 
-	trace_io_uring_req_failed(sqe, req, ret);
-
 	/*
 	 * Avoid breaking links in the middle as it renders links with SQPOLL
 	 * unusable. Instead of failing eagerly, continue assembling the link if
 	 * applicable and mark the head with REQ_F_FAIL. The link flushing code
 	 * should find the flag and handle the rest.
 	 */
-	req_fail_link_node(req, ret);
 	if (head && !(head->flags & REQ_F_FAIL))
 		req_fail_link_node(head, -ECANCELED);
 
@@ -2129,9 +2124,24 @@ static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
 	else
 		link->head = req;
 	link->last = req;
+
 	return 0;
 }
 
+static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
+				      struct io_kiocb *req, int ret)
+{
+	struct io_ring_ctx *ctx = req->ctx;
+	struct io_submit_link *link = &ctx->submit_state.link;
+
+	trace_io_uring_req_failed(sqe, req, ret);
+
+	req_fail_link_node(req, ret);
+
+	/* cover both linked and non-linked request */
+	return io_submit_fail_link(link, req, ret);
+}
+
 /*
  * Return NULL if nothing to be queued, otherwise return request for queueing */
 static struct io_kiocb *io_link_sqe(struct io_submit_link *link,
Signature · 1 line
2.42.0
author
#3 lore raw

PATCH v4 3/8 io_uring: add helper of io_req_commit_cqe()

In reply to Ming Lei

Add helper of io_req_commit_cqe() for simplifying
__io_submit_flush_completions() a bit.

No functional change, and the added helper will be reused in sqe group code with same lock rule.

---
 io_uring/io_uring.c | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)
io_uring/io_uring.c +16 -10
index 5d69851b5131..7597344a6440 100644
@@ -861,6 +861,20 @@ bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
 	return posted;
 }
 
+static __always_inline void io_req_commit_cqe(struct io_ring_ctx *ctx,
+		struct io_kiocb *req)
+{
+	if (unlikely(!io_fill_cqe_req(ctx, req))) {
+		if (ctx->lockless_cq) {
+			spin_lock(&ctx->completion_lock);
+			io_req_cqe_overflow(req);
+			spin_unlock(&ctx->completion_lock);
+		} else {
+			io_req_cqe_overflow(req);
+		}
+	}
+}
+
 static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
 {
 	struct io_ring_ctx *ctx = req->ctx;
@@ -1413,16 +1427,8 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
 		struct io_kiocb *req = container_of(node, struct io_kiocb,
 					    comp_list);
 
-		if (!(req->flags & REQ_F_CQE_SKIP) &&
-		    unlikely(!io_fill_cqe_req(ctx, req))) {
-			if (ctx->lockless_cq) {
-				spin_lock(&ctx->completion_lock);
-				io_req_cqe_overflow(req);
-				spin_unlock(&ctx->completion_lock);
-			} else {
-				io_req_cqe_overflow(req);
-			}
-		}
+		if (!(req->flags & REQ_F_CQE_SKIP))
+			io_req_commit_cqe(ctx, req);
 	}
 	__io_cq_unlock_post(ctx);
 
Signature · 1 line
2.42.0
author
#4 lore raw

PATCH v4 4/8 io_uring: support SQE group

In reply to Ming Lei

SQE group is defined as one chain of SQEs starting with the first SQE that has IOSQE_SQE_GROUP set, and ending with the first subsequent SQE that doesn't have it set, and it is similar with chain of linked SQEs.

Not like linked SQEs, each sqe is issued after the previous one is completed. All SQEs in one group are submitted in parallel, so there isn't any dependency among SQEs in one group.

The 1st SQE is group leader, and the other SQEs are group member. The whole group share single IOSQE_IO_LINK and IOSQE_IO_DRAIN from group leader, and the two flags are ignored for group members.

When the group is in one link chain, this group isn't submitted until the previous SQE or group is completed. And the following SQE or group can't be started if this group isn't completed. Failure from any group member will fail the group leader, then the link chain can be terminated.

When IOSQE_IO_DRAIN is set for group leader, all requests in this group and previous requests submitted are drained. Given IOSQE_IO_DRAIN can be set for group leader only, we respect IO_DRAIN by always completing group leader as the last one in the group.

Working together with IOSQE_IO_LINK, SQE group provides flexible way to support N:M dependency, such as:

- group A is chained with group B together
- group A has N SQEs
- group B has M SQEs

then M SQEs in group B depend on N SQEs in group A.

N:M dependency can support some interesting use cases in efficient way:

1) read from multiple files, then write the read data into single file

2) read from single file, and write the read data into multiple files

3) write same data into multiple files, and read data from multiple files and compare if correct data is written

Also IOSQE_SQE_GROUP takes the last bit in sqe->flags, but we still can extend sqe->flags with one uring context flag, such as use __pad3 for non-uring_cmd OPs and part of uring_cmd_flags for uring_cmd OP.

One simple sqe group based copy example[1] shows that:
1) buffered copy:
- perf is improved by 5%

2) direct IO mode
- perf is improved by 27%

3) sqe group copy, which keeps QD not changed, just re-organize IOs in the following ways:

- each group have 4 READ IOs, linked by one single write IO for writing the read data in sqe group to destination file

- the 1st 12 groups have (4 + 1) IOs, and the last group have (3 + 1) IOs

- test code:
https://github.com/ming1/liburing/commits/sqe_group_v2/

---
 include/linux/io_uring_types.h |  18 ++
 include/uapi/linux/io_uring.h  |   4 +
 io_uring/io_uring.c            | 304 ++++++++++++++++++++++++++++++---
 io_uring/io_uring.h            |  16 ++
 io_uring/timeout.c             |   2 +
 5 files changed, 324 insertions(+), 20 deletions(-)
include/linux/io_uring_types.h +18 -0
index ede42dce1506..b5cc3dee8fa2 100644
@@ -202,6 +202,8 @@ struct io_submit_state {
 	/* batch completion logic */
 	struct io_wq_work_list	compl_reqs;
 	struct io_submit_link	link;
+	/* points to current group */
+	struct io_submit_link	group;
 
 	bool			plug_started;
 	bool			need_plug;
@@ -436,6 +438,7 @@ enum {
 	REQ_F_FORCE_ASYNC_BIT	= IOSQE_ASYNC_BIT,
 	REQ_F_BUFFER_SELECT_BIT	= IOSQE_BUFFER_SELECT_BIT,
 	REQ_F_CQE_SKIP_BIT	= IOSQE_CQE_SKIP_SUCCESS_BIT,
+	REQ_F_SQE_GROUP_BIT	= IOSQE_SQE_GROUP_BIT,
 
 	/* first byte is taken by user flags, shift it to not overlap */
 	REQ_F_FAIL_BIT		= 8,
@@ -467,6 +470,7 @@ enum {
 	REQ_F_BL_EMPTY_BIT,
 	REQ_F_BL_NO_RECYCLE_BIT,
 	REQ_F_BUFFERS_COMMIT_BIT,
+	REQ_F_SQE_GROUP_LEADER_BIT,
 
 	/* not a real bit, just to check we're not overflowing the space */
 	__REQ_F_LAST_BIT,
@@ -490,6 +494,8 @@ enum {
 	REQ_F_BUFFER_SELECT	= IO_REQ_FLAG(REQ_F_BUFFER_SELECT_BIT),
 	/* IOSQE_CQE_SKIP_SUCCESS */
 	REQ_F_CQE_SKIP		= IO_REQ_FLAG(REQ_F_CQE_SKIP_BIT),
+	/* IOSQE_SQE_GROUP */
+	REQ_F_SQE_GROUP		= IO_REQ_FLAG(REQ_F_SQE_GROUP_BIT),
 
 	/* fail rest of links */
 	REQ_F_FAIL		= IO_REQ_FLAG(REQ_F_FAIL_BIT),
@@ -547,6 +553,8 @@ enum {
 	REQ_F_BL_NO_RECYCLE	= IO_REQ_FLAG(REQ_F_BL_NO_RECYCLE_BIT),
 	/* buffer ring head needs incrementing on put */
 	REQ_F_BUFFERS_COMMIT	= IO_REQ_FLAG(REQ_F_BUFFERS_COMMIT_BIT),
+	/* sqe group lead */
+	REQ_F_SQE_GROUP_LEADER	= IO_REQ_FLAG(REQ_F_SQE_GROUP_LEADER_BIT),
 };
 
 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, struct io_tw_state *ts);
@@ -652,6 +660,8 @@ struct io_kiocb {
 	void				*async_data;
 	/* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
 	atomic_t			poll_refs;
+	/* reference for group leader requests */
+	int				grp_refs;
 	struct io_kiocb			*link;
 	/* custom credentials, valid IFF REQ_F_CREDS is set */
 	const struct cred		*creds;
@@ -661,6 +671,14 @@ struct io_kiocb {
 		u64			extra1;
 		u64			extra2;
 	} big_cqe;
+
+	union {
+		/* links all group members for leader */
+		struct io_kiocb			*grp_link;
+
+		/* points to group leader for member */
+		struct io_kiocb			*grp_leader;
+	};
 };
 
 struct io_overflow_cqe {
include/uapi/linux/io_uring.h +4 -0
index 2aaf7ee256ac..e6d321b3add7 100644
@@ -124,6 +124,7 @@ enum io_uring_sqe_flags_bit {
 	IOSQE_ASYNC_BIT,
 	IOSQE_BUFFER_SELECT_BIT,
 	IOSQE_CQE_SKIP_SUCCESS_BIT,
+	IOSQE_SQE_GROUP_BIT,
 };
 
 /*
@@ -143,6 +144,8 @@ enum io_uring_sqe_flags_bit {
 #define IOSQE_BUFFER_SELECT	(1U << IOSQE_BUFFER_SELECT_BIT)
 /* don't post CQE if request succeeded */
 #define IOSQE_CQE_SKIP_SUCCESS	(1U << IOSQE_CQE_SKIP_SUCCESS_BIT)
+/* defines sqe group */
+#define IOSQE_SQE_GROUP		(1U << IOSQE_SQE_GROUP_BIT)
 
 /*
  * io_uring_setup() flags
@@ -542,6 +545,7 @@ struct io_uring_params {
 #define IORING_FEAT_LINKED_FILE		(1U << 12)
 #define IORING_FEAT_REG_REG_RING	(1U << 13)
 #define IORING_FEAT_RECVSEND_BUNDLE	(1U << 14)
+#define IORING_FEAT_SQE_GROUP		(1U << 15)
 
 /*
  * io_uring_register(2) opcodes and arguments
io_uring/io_uring.c +284 -20

448 lines not on this page · raw message

io_uring/io_uring.h +16 -0
index e1ce908f0679..8cc347959f7e 100644
@@ -68,6 +68,8 @@ bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags
 void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags);
 bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags);
 void __io_commit_cqring_flush(struct io_ring_ctx *ctx);
+void io_queue_group_members(struct io_kiocb *req, bool async);
+void io_cancel_group_members(struct io_kiocb *req, bool ignore_cqes);
 
 struct file *io_file_get_normal(struct io_kiocb *req, int fd);
 struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
@@ -339,6 +341,16 @@ static inline void io_tw_lock(struct io_ring_ctx *ctx, struct io_tw_state *ts)
 	lockdep_assert_held(&ctx->uring_lock);
 }
 
+static inline bool req_is_group_leader(struct io_kiocb *req)
+{
+	return req->flags & REQ_F_SQE_GROUP_LEADER;
+}
+
+static inline bool req_is_group_member(struct io_kiocb *req)
+{
+	return !req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP);
+}
+
 /*
  * Don't complete immediately but use deferred completion infrastructure.
  * Protected by ->uring_lock and can only be used either with
@@ -352,6 +364,10 @@ static inline void io_req_complete_defer(struct io_kiocb *req)
 	lockdep_assert_held(&req->ctx->uring_lock);
 
 	wq_list_add_tail(&req->comp_list, &state->compl_reqs);
+
+	/* members may not be issued when leader is completed */
+	if (unlikely(req_is_group_leader(req) && req->grp_link))
+		io_queue_group_members(req, false);
 }
 
 static inline void io_commit_cqring_flush(struct io_ring_ctx *ctx)
io_uring/timeout.c +2 -0
index 1c9bf07499b1..4e5eaf4054c3 100644
@@ -168,6 +168,8 @@ static void io_fail_links(struct io_kiocb *req)
 			link->flags |= REQ_F_CQE_SKIP;
 		else
 			link->flags &= ~REQ_F_CQE_SKIP;
+		if (req_is_group_leader(link))
+			io_cancel_group_members(link, ignore_cqes);
 		trace_io_uring_fail_link(req, link);
 		link = link->link;
 	}
Signature · 1 line
2.42.0
#5 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 37 lines · Ming Lei

SQE group is defined as one chain of SQEs starting with the first SQE that has IOSQE_SQE_GROUP set, and ending with the first subsequent SQE that doesn't have it set, and it is similar with chain of linked SQEs.

Not like linked SQEs, each sqe is issued after the previous one is completed. All SQEs in one group are submitted in parallel, so there isn't any dependency among SQEs in one group.

The 1st SQE is group leader, and the other SQEs are group member. The whole group share single IOSQE_IO_LINK and IOSQE_IO_DRAIN from group leader, and the two flags are ignored for group members.

When the group is in one link chain, this group isn't submitted until the previous SQE or group is completed. And the following SQE or group can't be started if this group isn't completed. Failure from any group member will fail the group leader, then the link chain can be terminated.

When IOSQE_IO_DRAIN is set for group leader, all requests in this group and previous requests submitted are drained. Given IOSQE_IO_DRAIN can be set for group leader only, we respect IO_DRAIN by always completing group leader as the last one in the group.

Working together with IOSQE_IO_LINK, SQE group provides flexible way to support N:M dependency, such as:

- group A is chained with group B together
- group A has N SQEs
- group B has M SQEs

then M SQEs in group B depend on N SQEs in group A.

N:M dependency can support some interesting use cases in efficient way:

1) read from multiple files, then write the read data into single file

2) read from single file, and write the read data into multiple files

Quoted 8 lines

3) write same data into multiple files, and read data from multiple files and compare if correct data is written

Also IOSQE_SQE_GROUP takes the last bit in sqe->flags, but we still can extend sqe->flags with one uring context flag, such as use __pad3 for non-uring_cmd OPs and part of uring_cmd_flags for uring_cmd OP.

One simple sqe group based copy example[1] shows that:

Sorry to say, but it's a flawed misleading example. We just can't coalesce 4 writes into 1 and say it's a win of this feature. It'd be a different thing if you compare perfectly optimised version without vs with groups. Note, I'm not asking you to do that, the use case here is zerocopy ublk.

Quoted 25 lines

1) buffered copy:
- perf is improved by 5%

2) direct IO mode
- perf is improved by 27%

3) sqe group copy, which keeps QD not changed, just re-organize IOs in the following ways:

- each group have 4 READ IOs, linked by one single write IO for writing the read data in sqe group to destination file

- the 1st 12 groups have (4 + 1) IOs, and the last group have (3 + 1) IOs

- test code:
https://github.com/ming1/liburing/commits/sqe_group_v2/

---

io_uring/io_uring.c +0 -0
index 7597344a6440..b5415f0774e5 100644

...

io_uring/io_uring.c static inline void io_req_track_inflight(struct io_kiocb *req) · line 428

Quoted 9 lines
io_uring/io_uring.c +4 -0
@@ -421,6 +422,10 @@ static inline void io_req_track_inflight(struct io_kiocb *req)
  	if (!(req->flags & REQ_F_INFLIGHT)) {
  		req->flags |= REQ_F_INFLIGHT;
  		atomic_inc(&req->task->io_uring->inflight_tracked);
+
+		/* make members' REQ_F_INFLIGHT discoverable via leader's */
+		if (req_is_group_member(req))
+			io_req_track_inflight(req->grp_leader);

Requests in a group can be run in parallel with the leader (i.e. io_issue_sqe()), right? In which case it'd race setting req->flags. We'd need to think how make it sane.

Quoted 2 lines
io_uring/io_uring.c +0 -0
  	}
  }

...

Quoted 4 lines
io_uring/io_uring.c +4 -0
+void io_queue_group_members(struct io_kiocb *req, bool async)
+{
+	struct io_kiocb *member = req->grp_link;
+

io_uring/io_uring.c static __always_inline void io_req_commit_cqe(struct io_ring_ctx *ctx, · line 929

Quoted 10 lines
io_uring/io_uring.c +10 -0
+	if (!member)
+		return;
+
+	req->grp_link = NULL;
+	while (member) {
+		struct io_kiocb *next = member->grp_link;
+
+		member->grp_leader = req;
+		if (async)
+			member->flags |= REQ_F_FORCE_ASYNC;

It doesn't need REQ_F_FORCE_ASYNC. That forces io-wq -> task_work -> io-wq for no reason when the user didn't ask for that.

Quoted 79 lines
io_uring/io_uring.c +65 -1
+
+		if (unlikely(member->flags & REQ_F_FAIL)) {
+			io_req_task_queue_fail(member, member->cqe.res);
+		} else if (member->flags & REQ_F_FORCE_ASYNC) {
+			io_req_task_queue(member);
+		} else {
+			io_queue_sqe(member);
+		}
+		member = next;
+	}
+}
+
+static inline bool __io_complete_group_req(struct io_kiocb *req,
+			     struct io_kiocb *lead)
+{
+	WARN_ON_ONCE(!(req->flags & REQ_F_SQE_GROUP));
+
+	if (WARN_ON_ONCE(lead->grp_refs <= 0))
+		return false;
+
+	/*
+	 * Set linked leader as failed if any member is failed, so
+	 * the remained link chain can be terminated
+	 */
+	if (unlikely((req->flags & REQ_F_FAIL) &&
+		     ((lead->flags & IO_REQ_LINK_FLAGS) && lead->link)))
+		req_set_fail(lead);
+	return !--lead->grp_refs;
+}
+
+/* Complete group request and collect completed leader for freeing */
+static void io_complete_group_req(struct io_kiocb *req,
+		struct io_wq_work_list *grp_list)
+{
+	struct io_kiocb *lead = get_group_leader(req);
+
+	if (__io_complete_group_req(req, lead)) {
+		req->flags &= ~REQ_F_SQE_GROUP;
+		lead->flags &= ~REQ_F_SQE_GROUP_LEADER;
+
+		if (!(lead->flags & REQ_F_CQE_SKIP))
+			io_req_commit_cqe(lead->ctx, lead);
+
+		if (req != lead) {
+			/*
+			 * Add leader to free list if it isn't there
+			 * otherwise clearing group flag for freeing it
+			 * in current batch
+			 */
+			if (!(lead->flags & REQ_F_SQE_GROUP))
+				wq_list_add_tail(&lead->comp_list, grp_list);
+			else
+				lead->flags &= ~REQ_F_SQE_GROUP;
+		}
+	} else if (req != lead) {
+		req->flags &= ~REQ_F_SQE_GROUP;
+	} else {
+		/*
+		 * Leader's group flag clearing is delayed until it is
+		 * removed from free list
+		 */
+	}
+}
+
  static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  {
  	struct io_ring_ctx *ctx = req->ctx;
@@ -897,7 +1013,7 @@ static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  	}
 
  	io_cq_lock(ctx);
-	if (!(req->flags & REQ_F_CQE_SKIP)) {
+	if (!(req->flags & REQ_F_CQE_SKIP) && !req_is_group_leader(req)) {
  		if (!io_fill_cqe_req(ctx, req))
  			io_req_cqe_overflow(req);
  	}
@@ -974,16 +1090,22 @@ __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
  	return true;
  }

...

Quoted 34 lines
  static void __io_req_find_next_prep(struct io_kiocb *req)
  {
  	struct io_ring_ctx *ctx = req->ctx;
io_uring/io_uring.c +12 -1
@@ -1388,6 +1510,17 @@ static void io_free_batch_list(struct io_ring_ctx *ctx,
  						    comp_list);
 
  		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
+			/*
+			 * Group leader may be removed twice, don't free it
+			 * if group flag isn't cleared, when some members
+			 * aren't completed yet
+			 */
+			if (req->flags & REQ_F_SQE_GROUP) {
+				node = req->comp_list.next;
+				req->flags &= ~REQ_F_SQE_GROUP;
+				continue;
+			}
+
  			if (req->flags & REQ_F_REFCOUNT) {
  				node = req->comp_list.next;
  				if (!req_ref_put_and_test(req))
@@ -1420,6 +1553,7 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  	__must_hold(&ctx->uring_lock)
  {
  	struct io_submit_state *state = &ctx->submit_state;
+	struct io_wq_work_list grp_list = {NULL};
  	struct io_wq_work_node *node;
 
  	__io_cq_lock(ctx);
@@ -1427,11 +1561,22 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  		struct io_kiocb *req = container_of(node, struct io_kiocb,
  					    comp_list);
 
-		if (!(req->flags & REQ_F_CQE_SKIP))

io_uring/io_uring.c void __io_submit_flush_completions(struct io_ring_ctx *ctx) · line 1573

Quoted 10 lines
io_uring/io_uring.c +9 -0
+		/*
+		 * For group leader, cqe has to be committed after all
+		 * members are committed, when the group leader flag is
+		 * cleared
+		 */
+		if (!(req->flags & REQ_F_CQE_SKIP) &&
+				likely(!req_is_group_leader(req)))
  			io_req_commit_cqe(ctx, req);
+		if (req->flags & REQ_F_SQE_GROUP)
+			io_complete_group_req(req, &grp_list);

if (unlikely(flags & (SKIP_CQE|GROUP))) {
<sqe group code>
if (/* needs to skip CQE posting */)
continue;
<more sqe group code>
}

io_req_commit_cqe();

Please. And, what's the point of reversing the CQE order and posting the "leader" completion last? It breaks the natural order of how IO complete, that is first the "leader" completes what it has need to do including IO, and then "members" follow doing their stuff. And besides, you can even post a CQE for the "leader" when its IO is done and let the user possibly continue executing. And the user can count when the entire group complete, if that's necessary to know.

Quoted 9 lines
io_uring/io_uring.c +3 -0
  	}
  	__io_cq_unlock_post(ctx);
 
+	if (!wq_list_empty(&grp_list))
+		__wq_list_splice(&grp_list, state->compl_reqs.first);
+
  	if (!wq_list_empty(&state->compl_reqs)) {
  		io_free_batch_list(ctx, state->compl_reqs.first);
  		INIT_WQ_LIST(&state->compl_reqs);

...

Quoted 9 lines
io_uring/io_uring.c +1 -3
@@ -1754,9 +1903,18 @@ struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
  	struct io_kiocb *nxt = NULL;
 
  	if (req_ref_put_and_test(req)) {
-		if (req->flags & IO_REQ_LINK_FLAGS)
-			nxt = io_req_find_next(req);
-		io_free_req(req);
+		/*

io_uring/io_uring.c struct io_wq_work *io_wq_free_work(struct io_wq_work *work) · line 1916

Quoted 10 lines
io_uring/io_uring.c +10 -0
+		 * CQEs have been posted in io_req_complete_post() except
+		 * for group leader, and we can't advance the link for
+		 * group leader until its CQE is posted.
+		 */
+		if (!req_is_group_leader(req)) {
+			if (req->flags & IO_REQ_LINK_FLAGS)
+				nxt = io_req_find_next(req);
+			io_free_req(req);
+		} else {
+			__io_free_req(req, false);

Something fishy is going on here. io-wq only holds a ref that the request is not killed, but it's owned by someone else. And the owner is responsible for CQE posting and logical flow of the request.

Now, the owner put the request down but for some reason didn't finish with the request like posting a CQE, but it's delayed to iowq dropping the ref?

I assume the refcounting hierarchy, first grp_refs go down, and when it hits zero it does whatever it needs, posting a CQE at that point of prior, and then puts the request reference down.

Quoted 18 lines
io_uring/io_uring.c +4 -0
+		}
  	}
  	return nxt ? &nxt->work : NULL;
  }
@@ -1821,6 +1979,8 @@ void io_wq_submit_work(struct io_wq_work *work)
  		}
  	}
 
+	if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, true);
  	do {
  		ret = io_issue_sqe(req, issue_flags);
  		if (ret != -EAGAIN)
@@ -1932,9 +2092,17 @@ static inline void io_queue_sqe(struct io_kiocb *req)
  	/*
  	 * We async punt it if the file wasn't marked NOWAIT, or if the file
  	 * doesn't support non-blocking read/write attempts
+	 *

io_uring/io_uring.c static inline void io_queue_sqe(struct io_kiocb *req) · line 2105

Quoted 10 lines
io_uring/io_uring.c +7 -0
+	 * Request is always freed after returning from io_queue_sqe(), so
+	 * it is fine to check its flags after it is issued
+	 *
+	 * For group leader, members holds leader references, so it is safe
+	 * to touch the leader after leader is issued
  	 */
  	if (unlikely(ret))
  		io_queue_async(req, ret);
+	else if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, false);

It absolutely cannot be here. There is no relation between this place in code and lifetime of the request. It could've been failed or completed, it can also be flying around in a completely arbitrary context being executed. We're not introducing weird special lifetime rules for group links. It complicates the code, and no way it can be sanely supported.
For example, it's not forbidden for issue_sqe callbacks to queue requests to io-wq and return 0 (IOU_ISSUE_SKIP_COMPLETE which would be turned into 0), and then we have two racing io_queue_group_members() calls.

You mentioned before there are 2 cases, w/ and w/o deps. That gives me a very _very_ bad feeling that you're taking two separate features, and trying to hammer them together into one. And the current dependencies thing looks terrible as a user api, when you have requests run in parallel, unless there is a special request ahead which provides buffers but doesn't advertise that in a good way. I don't know what to do about it. Either we need to find a better api or just implement one. Maybe, always delaying until leader executes like with dependencies is good enough, and then you set a nop as a leader to emulate the dependency-less mode.

Taking uapi aside, the two mode dichotomy tells the story how io_queue_group_members() placing should look like. If there are dependencies, the leader should be executed, completed, and quueue members in a good place denoting completion, like io_free_batch_list. In case of no deps it need to queue everyone when you'd queue up a linked request (or issue the head).

Quoted 9 lines
io_uring/io_uring.c +2 -0
  }
 
  static void io_queue_sqe_fallback(struct io_kiocb *req)
@@ -2101,6 +2269,56 @@ static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
  	return def->prep(req, sqe);
  }
 
+static struct io_kiocb *io_group_sqe(struct io_submit_link *group,
+				     struct io_kiocb *req)

io_uring/io_uring.c static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req, · line 2283

Quoted 10 lines
io_uring/io_uring.c +10 -0
+{
+	/*
+	 * Group chain is similar with link chain: starts with 1st sqe with
+	 * REQ_F_SQE_GROUP, and ends with the 1st sqe without REQ_F_SQE_GROUP
+	 */
+	if (group->head) {
+		struct io_kiocb *lead = group->head;
+
+		/* members can't be in link chain, can't be drained */
+		req->flags &= ~(IO_REQ_LINK_FLAGS | REQ_F_IO_DRAIN);

needs to fail instead seeing these flags

Quoted 22 lines
io_uring/io_uring.c +22 -0
+		lead->grp_refs += 1;
+		group->last->grp_link = req;
+		group->last = req;
+
+		if (req->flags & REQ_F_SQE_GROUP)
+			return NULL;
+
+		req->grp_link = NULL;
+		req->flags |= REQ_F_SQE_GROUP;
+		group->head = NULL;
+		return lead;
+	} else if (req->flags & REQ_F_SQE_GROUP) {
+		group->head = req;
+		group->last = req;
+		req->grp_refs = 1;
+		req->flags |= REQ_F_SQE_GROUP_LEADER;
+		return NULL;
+	} else {
+		return req;
+	}
+}
+

...

Quoted 31 lines
io_uring/io_uring.h +12 -0
index e1ce908f0679..8cc347959f7e 100644
@@ -68,6 +68,8 @@ bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags
  void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags);
  bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags);
  void __io_commit_cqring_flush(struct io_ring_ctx *ctx);
+void io_queue_group_members(struct io_kiocb *req, bool async);
+void io_cancel_group_members(struct io_kiocb *req, bool ignore_cqes);
 
  struct file *io_file_get_normal(struct io_kiocb *req, int fd);
  struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
@@ -339,6 +341,16 @@ static inline void io_tw_lock(struct io_ring_ctx *ctx, struct io_tw_state *ts)
  	lockdep_assert_held(&ctx->uring_lock);
  }
 
+static inline bool req_is_group_leader(struct io_kiocb *req)
+{
+	return req->flags & REQ_F_SQE_GROUP_LEADER;
+}
+
+static inline bool req_is_group_member(struct io_kiocb *req)
+{
+	return !req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP);
+}
+
  /*
   * Don't complete immediately but use deferred completion infrastructure.
   * Protected by ->uring_lock and can only be used either with

io_uring/io_uring.h static inline void io_req_complete_defer(struct io_kiocb *req) · line 371

Quoted 8 lines
io_uring/io_uring.h +4 -0
@@ -352,6 +364,10 @@ static inline void io_req_complete_defer(struct io_kiocb *req)
  	lockdep_assert_held(&req->ctx->uring_lock);
 
  	wq_list_add_tail(&req->comp_list, &state->compl_reqs);
+
+	/* members may not be issued when leader is completed */
+	if (unlikely(req_is_group_leader(req) && req->grp_link))
+		io_queue_group_members(req, false);
  }

Here should be no processing, it's not a place where it can be

Signature · 1 line
Pavel Begunkov
author
#6 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Hi Pavel,

Thanks for the review!

Quoted 45 lines · Pavel Begunkov
Quoted 44 lines · Ming Lei

SQE group is defined as one chain of SQEs starting with the first SQE that has IOSQE_SQE_GROUP set, and ending with the first subsequent SQE that doesn't have it set, and it is similar with chain of linked SQEs.

Not like linked SQEs, each sqe is issued after the previous one is completed. All SQEs in one group are submitted in parallel, so there isn't any dependency among SQEs in one group.

The 1st SQE is group leader, and the other SQEs are group member. The whole group share single IOSQE_IO_LINK and IOSQE_IO_DRAIN from group leader, and the two flags are ignored for group members.

When the group is in one link chain, this group isn't submitted until the previous SQE or group is completed. And the following SQE or group can't be started if this group isn't completed. Failure from any group member will fail the group leader, then the link chain can be terminated.

When IOSQE_IO_DRAIN is set for group leader, all requests in this group and previous requests submitted are drained. Given IOSQE_IO_DRAIN can be set for group leader only, we respect IO_DRAIN by always completing group leader as the last one in the group.

Working together with IOSQE_IO_LINK, SQE group provides flexible way to support N:M dependency, such as:

- group A is chained with group B together
- group A has N SQEs
- group B has M SQEs

then M SQEs in group B depend on N SQEs in group A.

N:M dependency can support some interesting use cases in efficient way:

1) read from multiple files, then write the read data into single file

2) read from single file, and write the read data into multiple files

3) write same data into multiple files, and read data from multiple files and compare if correct data is written

Also IOSQE_SQE_GROUP takes the last bit in sqe->flags, but we still can extend sqe->flags with one uring context flag, such as use __pad3 for non-uring_cmd OPs and part of uring_cmd_flags for uring_cmd OP.

Quoted 7 lines
Quoted 1 line

One simple sqe group based copy example[1] shows that:

Sorry to say, but it's a flawed misleading example. We just can't coalesce 4 writes into 1 and say it's a win of this feature. It'd be a different thing if you compare perfectly optimised version without vs with groups. Note, I'm not asking you to do that, the use case here is zerocopy ublk.

OK, group provides one easy way to do that.

Quoted 28 lines
Quoted 27 lines

1) buffered copy:
- perf is improved by 5%

2) direct IO mode
- perf is improved by 27%

3) sqe group copy, which keeps QD not changed, just re-organize IOs in the following ways:

- each group have 4 READ IOs, linked by one single write IO for writing the read data in sqe group to destination file

- the 1st 12 groups have (4 + 1) IOs, and the last group have (3 + 1) IOs

- test code:
https://github.com/ming1/liburing/commits/sqe_group_v2/

---

io_uring/io_uring.c +0 -0
index 7597344a6440..b5415f0774e5 100644

...

Quoted 12 lines

io_uring/io_uring.c static inline void io_req_track_inflight(struct io_kiocb *req) · line 428

Quoted 8 lines
io_uring/io_uring.c +4 -0
@@ -421,6 +422,10 @@ static inline void io_req_track_inflight(struct io_kiocb *req)
  	if (!(req->flags & REQ_F_INFLIGHT)) {
  		req->flags |= REQ_F_INFLIGHT;
  		atomic_inc(&req->task->io_uring->inflight_tracked);
+
+		/* make members' REQ_F_INFLIGHT discoverable via leader's */
+		if (req_is_group_member(req))
+			io_req_track_inflight(req->grp_leader);

Requests in a group can be run in parallel with the leader (i.e. io_issue_sqe()), right? In which case it'd race setting req->flags. We'd need to think how make it sane.

Yeah, another easier way could be to always mark leader as INFLIGHT.

Quoted 14 lines
Quoted 3 lines
io_uring/io_uring.c +0 -0
  	}
  }

...

Quoted 10 lines
io_uring/io_uring.c +10 -0
+void io_queue_group_members(struct io_kiocb *req, bool async)
+{
+	struct io_kiocb *member = req->grp_link;
+
+	if (!member)
+		return;
+
+	req->grp_link = NULL;
+	while (member) {
+		struct io_kiocb *next = member->grp_link;
Quoted 8 lines

io_uring/io_uring.c static __always_inline void io_req_commit_cqe(struct io_ring_ctx *ctx, · line 929

Quoted 4 lines
io_uring/io_uring.c +4 -0
+
+		member->grp_leader = req;
+		if (async)
+			member->flags |= REQ_F_FORCE_ASYNC;

It doesn't need REQ_F_FORCE_ASYNC. That forces io-wq -> task_work -> io-wq for no reason when the user didn't ask for that.

OK.

Quoted 120 lines
Quoted 79 lines
io_uring/io_uring.c +65 -1
+
+		if (unlikely(member->flags & REQ_F_FAIL)) {
+			io_req_task_queue_fail(member, member->cqe.res);
+		} else if (member->flags & REQ_F_FORCE_ASYNC) {
+			io_req_task_queue(member);
+		} else {
+			io_queue_sqe(member);
+		}
+		member = next;
+	}
+}
+
+static inline bool __io_complete_group_req(struct io_kiocb *req,
+			     struct io_kiocb *lead)
+{
+	WARN_ON_ONCE(!(req->flags & REQ_F_SQE_GROUP));
+
+	if (WARN_ON_ONCE(lead->grp_refs <= 0))
+		return false;
+
+	/*
+	 * Set linked leader as failed if any member is failed, so
+	 * the remained link chain can be terminated
+	 */
+	if (unlikely((req->flags & REQ_F_FAIL) &&
+		     ((lead->flags & IO_REQ_LINK_FLAGS) && lead->link)))
+		req_set_fail(lead);
+	return !--lead->grp_refs;
+}
+
+/* Complete group request and collect completed leader for freeing */
+static void io_complete_group_req(struct io_kiocb *req,
+		struct io_wq_work_list *grp_list)
+{
+	struct io_kiocb *lead = get_group_leader(req);
+
+	if (__io_complete_group_req(req, lead)) {
+		req->flags &= ~REQ_F_SQE_GROUP;
+		lead->flags &= ~REQ_F_SQE_GROUP_LEADER;
+
+		if (!(lead->flags & REQ_F_CQE_SKIP))
+			io_req_commit_cqe(lead->ctx, lead);
+
+		if (req != lead) {
+			/*
+			 * Add leader to free list if it isn't there
+			 * otherwise clearing group flag for freeing it
+			 * in current batch
+			 */
+			if (!(lead->flags & REQ_F_SQE_GROUP))
+				wq_list_add_tail(&lead->comp_list, grp_list);
+			else
+				lead->flags &= ~REQ_F_SQE_GROUP;
+		}
+	} else if (req != lead) {
+		req->flags &= ~REQ_F_SQE_GROUP;
+	} else {
+		/*
+		 * Leader's group flag clearing is delayed until it is
+		 * removed from free list
+		 */
+	}
+}
+
  static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  {
  	struct io_ring_ctx *ctx = req->ctx;
@@ -897,7 +1013,7 @@ static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  	}
  	io_cq_lock(ctx);
-	if (!(req->flags & REQ_F_CQE_SKIP)) {
+	if (!(req->flags & REQ_F_CQE_SKIP) && !req_is_group_leader(req)) {
  		if (!io_fill_cqe_req(ctx, req))
  			io_req_cqe_overflow(req);
  	}
@@ -974,16 +1090,22 @@ __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
  	return true;
  }

...

Quoted 39 lines
  static void __io_req_find_next_prep(struct io_kiocb *req)
  {
  	struct io_ring_ctx *ctx = req->ctx;
io_uring/io_uring.c +19 -1
@@ -1388,6 +1510,17 @@ static void io_free_batch_list(struct io_ring_ctx *ctx,
  						    comp_list);
  		if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
+			/*
+			 * Group leader may be removed twice, don't free it
+			 * if group flag isn't cleared, when some members
+			 * aren't completed yet
+			 */
+			if (req->flags & REQ_F_SQE_GROUP) {
+				node = req->comp_list.next;
+				req->flags &= ~REQ_F_SQE_GROUP;
+				continue;
+			}
+
  			if (req->flags & REQ_F_REFCOUNT) {
  				node = req->comp_list.next;
  				if (!req_ref_put_and_test(req))
@@ -1420,6 +1553,7 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  	__must_hold(&ctx->uring_lock)
  {
  	struct io_submit_state *state = &ctx->submit_state;
+	struct io_wq_work_list grp_list = {NULL};
  	struct io_wq_work_node *node;
  	__io_cq_lock(ctx);
@@ -1427,11 +1561,22 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  		struct io_kiocb *req = container_of(node, struct io_kiocb,
  					    comp_list);
-		if (!(req->flags & REQ_F_CQE_SKIP))
+		/*
+		 * For group leader, cqe has to be committed after all
+		 * members are committed, when the group leader flag is
+		 * cleared
+		 */
+		if (!(req->flags & REQ_F_CQE_SKIP) &&
+				likely(!req_is_group_leader(req)))
  			io_req_commit_cqe(ctx, req);
Quoted 8 lines

io_uring/io_uring.c void __io_submit_flush_completions(struct io_ring_ctx *ctx) · line 1573

Quoted 2 lines
io_uring/io_uring.c +2 -0
+		if (req->flags & REQ_F_SQE_GROUP)
+			io_complete_group_req(req, &grp_list);

if (unlikely(flags & (SKIP_CQE|GROUP))) {
<sqe group code>
if (/* needs to skip CQE posting */)
continue;

io_complete_group_req() needs to be called too in case of CQE_SKIP because the current request may belong to group.

Quoted 6 lines

<more sqe group code>
}

io_req_commit_cqe();

Quoted 8 lines

Please. And, what's the point of reversing the CQE order and posting the "leader" completion last? It breaks the natural order of how IO complete, that is first the "leader" completes what it has need to do including IO, and then "members" follow doing their stuff. And besides, you can even post a CQE for the "leader" when its IO is done and let the user possibly continue executing. And the user can count when the entire group complete, if that's necessary to know.

There are several reasons for posting leader completion last:

1) only the leader is visible in link chain, IO drain has to wait the whole group by draining the leader

2) when members depend on leader, leader holds group-wide resource, so it has to be completed after all members are done

Quoted 24 lines
Quoted 9 lines
io_uring/io_uring.c +3 -0
  	}
  	__io_cq_unlock_post(ctx);
+	if (!wq_list_empty(&grp_list))
+		__wq_list_splice(&grp_list, state->compl_reqs.first);
+
  	if (!wq_list_empty(&state->compl_reqs)) {
  		io_free_batch_list(ctx, state->compl_reqs.first);
  		INIT_WQ_LIST(&state->compl_reqs);

...

Quoted 14 lines
io_uring/io_uring.c +8 -3
@@ -1754,9 +1903,18 @@ struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
  	struct io_kiocb *nxt = NULL;
  	if (req_ref_put_and_test(req)) {
-		if (req->flags & IO_REQ_LINK_FLAGS)
-			nxt = io_req_find_next(req);
-		io_free_req(req);
+		/*
+		 * CQEs have been posted in io_req_complete_post() except
+		 * for group leader, and we can't advance the link for
+		 * group leader until its CQE is posted.
+		 */
+		if (!req_is_group_leader(req)) {
+			if (req->flags & IO_REQ_LINK_FLAGS)
+				nxt = io_req_find_next(req);
Quoted 8 lines

io_uring/io_uring.c struct io_wq_work *io_wq_free_work(struct io_wq_work *work) · line 1916

Quoted 3 lines
io_uring/io_uring.c +3 -0
+			io_free_req(req);
+		} else {
+			__io_free_req(req, false);

Something fishy is going on here. io-wq only holds a ref that the request is not killed, but it's owned by someone else. And the owner is responsible for CQE posting and logical flow of the request.

io_req_complete_post() is always called in io-wq for CQE posting before io-wq drops ref.

The ref held by io-wq prevents the owner from calling io_free_req(), so the owner actually can't run CQE post.

Quoted 9 lines

Now, the owner put the request down but for some reason didn't finish with the request like posting a CQE, but it's delayed to iowq dropping the ref?

I assume the refcounting hierarchy, first grp_refs go down, and when it hits zero it does whatever it needs, posting a CQE at that point of prior, and then puts the request reference down.

Yes, that is why the patch doesn't mark CQE_SKIP for leader in io_wq_free_work(), meantime leader->link has to be issued after leader's CQE is posted in case of io-wq.

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Quoted 30 lines
Quoted 18 lines
io_uring/io_uring.c +4 -0
+		}
  	}
  	return nxt ? &nxt->work : NULL;
  }
@@ -1821,6 +1979,8 @@ void io_wq_submit_work(struct io_wq_work *work)
  		}
  	}
+	if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, true);
  	do {
  		ret = io_issue_sqe(req, issue_flags);
  		if (ret != -EAGAIN)
@@ -1932,9 +2092,17 @@ static inline void io_queue_sqe(struct io_kiocb *req)
  	/*
  	 * We async punt it if the file wasn't marked NOWAIT, or if the file
  	 * doesn't support non-blocking read/write attempts
+	 *

io_uring/io_uring.c static inline void io_queue_sqe(struct io_kiocb *req) · line 2105

Quoted 10 lines
io_uring/io_uring.c +7 -0
+	 * Request is always freed after returning from io_queue_sqe(), so
+	 * it is fine to check its flags after it is issued
+	 *
+	 * For group leader, members holds leader references, so it is safe
+	 * to touch the leader after leader is issued
  	 */
  	if (unlikely(ret))
  		io_queue_async(req, ret);
+	else if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, false);

It absolutely cannot be here. There is no relation between this place

Quoted 8 lines

in code and lifetime of the request. It could've been failed or completed, it can also be flying around in a completely arbitrary context being executed. We're not introducing weird special lifetime rules for group links. It complicates the code, and no way it can be sanely supported.
For example, it's not forbidden for issue_sqe callbacks to queue requests to io-wq and return 0 (IOU_ISSUE_SKIP_COMPLETE which would be turned into 0), and then we have two racing io_queue_group_members() calls.

It can by handled by adding io_queue_sqe_group() in which:

- req->grp_link is moved to one local variable, and make every member's grp_leader point to req

- call io_queue_sqe() for leader

- then call io_queue_group_members() for all members, and make sure not touch leader in io_queue_group_members()

What do you think of this way?

Quoted 4 lines

You mentioned before there are 2 cases, w/ and w/o deps. That gives me a very _very_ bad feeling that you're taking two separate features, and trying to hammer them together into one. And the current

Yes, because w/ deps reuses most of code of w/ deps.

Quoted 7 lines

dependencies thing looks terrible as a user api, when you have requests run in parallel, unless there is a special request ahead which provides buffers but doesn't advertise that in a good way. I don't know what to do about it. Either we need to find a better api or just implement one. Maybe, always delaying until leader executes like with dependencies is good enough, and then you set a nop as a leader to emulate the dependency-less mode.

Another ways is to start with w/ deps mode only, which is exactly what ublk zero copy is needed, and w/o deps is just for making the feature more generic, suggested by Kevin.

Quoted 20 lines

Taking uapi aside, the two mode dichotomy tells the story how io_queue_group_members() placing should look like. If there are dependencies, the leader should be executed, completed, and quueue members in a good place denoting completion, like io_free_batch_list. In case of no deps it need to queue everyone when you'd queue up a linked request (or issue the head).

Quoted 11 lines
io_uring/io_uring.c +6 -0
  }
  static void io_queue_sqe_fallback(struct io_kiocb *req)
@@ -2101,6 +2269,56 @@ static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
  	return def->prep(req, sqe);
  }
+static struct io_kiocb *io_group_sqe(struct io_submit_link *group,
+				     struct io_kiocb *req)
+{
+	/*
+	 * Group chain is similar with link chain: starts with 1st sqe with
+	 * REQ_F_SQE_GROUP, and ends with the 1st sqe without REQ_F_SQE_GROUP
Quoted 8 lines

io_uring/io_uring.c static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req, · line 2283

Quoted 6 lines
io_uring/io_uring.c +6 -0
+	 */
+	if (group->head) {
+		struct io_kiocb *lead = group->head;
+
+		/* members can't be in link chain, can't be drained */
+		req->flags &= ~(IO_REQ_LINK_FLAGS | REQ_F_IO_DRAIN);

needs to fail instead seeing these flags

OK.

Quoted 54 lines
Quoted 23 lines
io_uring/io_uring.c +22 -0
+		lead->grp_refs += 1;
+		group->last->grp_link = req;
+		group->last = req;
+
+		if (req->flags & REQ_F_SQE_GROUP)
+			return NULL;
+
+		req->grp_link = NULL;
+		req->flags |= REQ_F_SQE_GROUP;
+		group->head = NULL;
+		return lead;
+	} else if (req->flags & REQ_F_SQE_GROUP) {
+		group->head = req;
+		group->last = req;
+		req->grp_refs = 1;
+		req->flags |= REQ_F_SQE_GROUP_LEADER;
+		return NULL;
+	} else {
+		return req;
+	}
+}
+

...

Quoted 30 lines
io_uring/io_uring.h +12 -0
index e1ce908f0679..8cc347959f7e 100644
@@ -68,6 +68,8 @@ bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags
  void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags);
  bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags);
  void __io_commit_cqring_flush(struct io_ring_ctx *ctx);
+void io_queue_group_members(struct io_kiocb *req, bool async);
+void io_cancel_group_members(struct io_kiocb *req, bool ignore_cqes);
  struct file *io_file_get_normal(struct io_kiocb *req, int fd);
  struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
@@ -339,6 +341,16 @@ static inline void io_tw_lock(struct io_ring_ctx *ctx, struct io_tw_state *ts)
  	lockdep_assert_held(&ctx->uring_lock);
  }
+static inline bool req_is_group_leader(struct io_kiocb *req)
+{
+	return req->flags & REQ_F_SQE_GROUP_LEADER;
+}
+
+static inline bool req_is_group_member(struct io_kiocb *req)
+{
+	return !req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP);
+}
+
  /*
   * Don't complete immediately but use deferred completion infrastructure.
   * Protected by ->uring_lock and can only be used either with
@@ -352,6 +364,10 @@ static inline void io_req_complete_defer(struct io_kiocb *req)
  	lockdep_assert_held(&req->ctx->uring_lock);
Quoted 8 lines

io_uring/io_uring.h static inline void io_req_complete_defer(struct io_kiocb *req) · line 371

Quoted 6 lines
io_uring/io_uring.h +4 -0
  	wq_list_add_tail(&req->comp_list, &state->compl_reqs);
+
+	/* members may not be issued when leader is completed */
+	if (unlikely(req_is_group_leader(req) && req->grp_link))
+		io_queue_group_members(req, false);
  }

Here should be no processing, it's not a place where it can be

OK.

Thanks,
Ming

#7 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 10 lines · Ming Lei

Hi Pavel,

Thanks for the review!

Quoted 5 lines · Pavel Begunkov
Quoted 4 lines · Ming Lei

SQE group is defined as one chain of SQEs starting with the first SQE that has IOSQE_SQE_GROUP set, and ending with the first subsequent SQE that doesn't have it set, and it is similar with chain of linked SQEs.

...

Quoted 19 lines
Quoted 6 lines
Quoted 5 lines

---

io_uring/io_uring.c +0 -0
index 7597344a6440..b5415f0774e5 100644

...

Quoted 12 lines

io_uring/io_uring.c static inline void io_req_track_inflight(struct io_kiocb *req) · line 428

Quoted 8 lines
io_uring/io_uring.c +4 -0
@@ -421,6 +422,10 @@ static inline void io_req_track_inflight(struct io_kiocb *req)
   	if (!(req->flags & REQ_F_INFLIGHT)) {
   		req->flags |= REQ_F_INFLIGHT;
   		atomic_inc(&req->task->io_uring->inflight_tracked);
+
+		/* make members' REQ_F_INFLIGHT discoverable via leader's */
+		if (req_is_group_member(req))
+			io_req_track_inflight(req->grp_leader);

Requests in a group can be run in parallel with the leader (i.e. io_issue_sqe()), right? In which case it'd race setting req->flags. We'd need to think how make it sane.

Quoted 1 line

Yeah, another easier way could be to always mark leader as INFLIGHT.

I've been thinking a bit more about it, there should be an easier way out since we now have lazy file assignment. I sent a patch closing a gap, I need to double check if that's enough, but let's forget about additional REQ_F_INFLIGHT handling here.

...

Quoted 28 lines
Quoted 19 lines
Quoted 19 lines
io_uring/io_uring.c +8 -1
@@ -1420,6 +1553,7 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
   	__must_hold(&ctx->uring_lock)
   {
   	struct io_submit_state *state = &ctx->submit_state;
+	struct io_wq_work_list grp_list = {NULL};
   	struct io_wq_work_node *node;
   	__io_cq_lock(ctx);
@@ -1427,11 +1561,22 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
   		struct io_kiocb *req = container_of(node, struct io_kiocb,
   					    comp_list);
-		if (!(req->flags & REQ_F_CQE_SKIP))
+		/*
+		 * For group leader, cqe has to be committed after all
+		 * members are committed, when the group leader flag is
+		 * cleared
+		 */
+		if (!(req->flags & REQ_F_CQE_SKIP) &&
+				likely(!req_is_group_leader(req)))
   			io_req_commit_cqe(ctx, req);
Quoted 8 lines

io_uring/io_uring.c void __io_submit_flush_completions(struct io_ring_ctx *ctx) · line 1572

Quoted 2 lines
io_uring/io_uring.c +2 -0
+		if (req->flags & REQ_F_SQE_GROUP)
+			io_complete_group_req(req, &grp_list);

if (unlikely(flags & (SKIP_CQE|GROUP))) {
<sqe group code>
if (/* needs to skip CQE posting */)
continue;

Quoted 2 lines

io_complete_group_req() needs to be called too in case of CQE_SKIP because the current request may belong to group.

What's the problem? You can even do

if (flags & GROUP) {
	// do all group specific stuff
	// handle CQE_SKIP if needed
} else if (flags & CQE_SKIP) {
	continue;
}

And call io_complete_group_req() and other group stuff at any place there.

Quoted 15 lines
Quoted 6 lines

<more sqe group code>
}

io_req_commit_cqe();

Quoted 8 lines

Please. And, what's the point of reversing the CQE order and posting the "leader" completion last? It breaks the natural order of how IO complete, that is first the "leader" completes what it has need to do including IO, and then "members" follow doing their stuff. And besides, you can even post a CQE for the "leader" when its IO is done and let the user possibly continue executing. And the user can count when the entire group complete, if that's necessary to know.

Quoted 4 lines

There are several reasons for posting leader completion last:

1) only the leader is visible in link chain, IO drain has to wait the whole group by draining the leader

Let's forget about IO drain. It's a feature I'd love to see killed (if only we can), it's a slow path, for same reasons I'll discourage anyone using it.

For correctness we can just copy the link trick, i.e. mark the next request outside of the current group/link as drained like below or just fail the group.

io_uring/io_uring.c +1 -1
index 7ed1e009aaec..aa0b93765406 100644
@@ -1975,7 +1975,7 @@ static void io_init_req_drain(struct io_kiocb *req)
 	struct io_kiocb *head = ctx->submit_state.link.head;
 
 	ctx->drain_active = true;
-	if (head) {
+	if (head || ctx->submit_state.group.head) {
 		/*
 		 * If we need to drain a request in the middle of a link, drain
 		 * the head request and the next request/link after the current
Quoted 2 lines

2) when members depend on leader, leader holds group-wide resource, so it has to be completed after all members are done

I'm talking about posting a CQE but not destroying the request (and associated resources).

Quoted 43 lines
Quoted 23 lines
Quoted 8 lines
io_uring/io_uring.c +3 -0
   	}
   	__io_cq_unlock_post(ctx);
+	if (!wq_list_empty(&grp_list))
+		__wq_list_splice(&grp_list, state->compl_reqs.first);
+
   	if (!wq_list_empty(&state->compl_reqs)) {
   		io_free_batch_list(ctx, state->compl_reqs.first);
   		INIT_WQ_LIST(&state->compl_reqs);

...

Quoted 14 lines
io_uring/io_uring.c +8 -3
@@ -1754,9 +1903,18 @@ struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
   	struct io_kiocb *nxt = NULL;
   	if (req_ref_put_and_test(req)) {
-		if (req->flags & IO_REQ_LINK_FLAGS)
-			nxt = io_req_find_next(req);
-		io_free_req(req);
+		/*
+		 * CQEs have been posted in io_req_complete_post() except
+		 * for group leader, and we can't advance the link for
+		 * group leader until its CQE is posted.
+		 */
+		if (!req_is_group_leader(req)) {
+			if (req->flags & IO_REQ_LINK_FLAGS)
+				nxt = io_req_find_next(req);
Quoted 8 lines

io_uring/io_uring.c struct io_wq_work *io_wq_free_work(struct io_wq_work *work) · line 1915

Quoted 3 lines
io_uring/io_uring.c +3 -0
+			io_free_req(req);
+		} else {
+			__io_free_req(req, false);

Something fishy is going on here. io-wq only holds a ref that the request is not killed, but it's owned by someone else. And the owner is responsible for CQE posting and logical flow of the request.

io_req_complete_post() is always called in io-wq for CQE posting before io-wq drops ref.

The ref held by io-wq prevents the owner from calling io_free_req(), so the owner actually can't run CQE post.

Quoted 5 lines

Now, the owner put the request down but for some reason didn't finish with the request like posting a CQE, but it's delayed to iowq dropping the ref?

Quoted 8 lines
Quoted 4 lines

I assume the refcounting hierarchy, first grp_refs go down, and when it hits zero it does whatever it needs, posting a CQE at that point of prior, and then puts the request reference down.

Yes, that is why the patch doesn't mark CQE_SKIP for leader in io_wq_free_work(), meantime leader->link has to be issued after leader's CQE is posted in case of io-wq.

The point is that io_wq_free_work() doesn't need to know anything about groups and can just continue setting the skip cqe flag as before if it's done differently

Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}

You can do it this way, nobody would ever care, and it shouldn't affect performance. Otherwise everything down below can probably be extended to io_req_complete_post().

To avoid confusion in terminology, what I call a member below doesn't include a leader. IOW, a group leader request is not a member.

At the init we have:
grp_refs = nr_members; /* doesn't include the leader */

Let's also say that the group leader can and always goes through io_submit_flush_completions() twice, just how it's with your patches.

1) The first time we see the leader in io_submit_flush_completions() is when it's done with resource preparation. For example, it was doing some IO into a buffer, and now is ready to give that buffer with data to group members. At this point it should queue up all group members. And we also drop 1 grp_ref. There will also be no io_issue_sqe() for it anymore.

2) Members are executed and completed, in io_submit_flush_completions() they drop 1 grp_leader->grp_ref reference each.

3) When all members complete, leader's grp_ref becomes 0. Here the leader is queued for io_submit_flush_completions() a second time, at which point it drops ublk buffers and such and gets destroyed.

You can post a CQE in 1) and then set CQE_SKIP. Can also be fitted into 3). A pseudo code for when we post it in step 1)

io_free_batch_list() {
	if (req->flags & GROUP) {
		if (req_is_member(req)) {
			req->grp_leader->grp_refs--;
			if (req->grp_leader->grp_refs == 0) {
				req->io_task_work.func = io_req_task_complete;
				io_req_task_work_add(req->grp_leader);
				// can be done better....
			}
			goto free_req;
		}
		WARN_ON_ONCE(!req_is_leader());

		if (!(req->flags & SEEN_FIRST_TIME)) {
			// already posted it just before coming here
			req->flags |= SKIP_CQE;
			// we'll see it again when grp_refs hit 0
			req->flags |= SEEN_FIRST_TIME;

			// Don't free the req, we're leaving it alive for now.
			// req->ref/REQ_F_REFCOUNT will be put next time we get here.
			return; // or continue
		}

		clean_up_request_resources(); // calls back into ublk
		// and now free the leader
	}

free_req:

	// the rest of io_free_batch_list()
	if (flags & REQ_F_REFCOUNT) {
		req_drop_ref();
		....
	}
	...
}

This way
1) There are relatively easy request lifetime rules.
2) No special ownership/lifetime rules for the group link field.
3) You don't need to touch io_req_complete_defer()
4) io-wq doesn't know anything about grp_refs and doesn't play tricks with SKIP_CQE.
5) All handling is in one place, doesn't need multiple checks in common hot path. You might need some extra, but at least it's contained.

Quoted 43 lines
Quoted 29 lines
Quoted 17 lines
io_uring/io_uring.c +4 -0
+		}
   	}
   	return nxt ? &nxt->work : NULL;
   }
@@ -1821,6 +1979,8 @@ void io_wq_submit_work(struct io_wq_work *work)
   		}
   	}
+	if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, true);
   	do {
   		ret = io_issue_sqe(req, issue_flags);
   		if (ret != -EAGAIN)
@@ -1932,9 +2092,17 @@ static inline void io_queue_sqe(struct io_kiocb *req)
   	/*
   	 * We async punt it if the file wasn't marked NOWAIT, or if the file
   	 * doesn't support non-blocking read/write attempts
+	 *

io_uring/io_uring.c static inline void io_queue_sqe(struct io_kiocb *req) · line 2105

Quoted 10 lines
io_uring/io_uring.c +7 -0
+	 * Request is always freed after returning from io_queue_sqe(), so
+	 * it is fine to check its flags after it is issued
+	 *
+	 * For group leader, members holds leader references, so it is safe
+	 * to touch the leader after leader is issued
   	 */
   	if (unlikely(ret))
   		io_queue_async(req, ret);
+	else if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, false);

It absolutely cannot be here. There is no relation between this place

Quoted 8 lines

in code and lifetime of the request. It could've been failed or completed, it can also be flying around in a completely arbitrary context being executed. We're not introducing weird special lifetime rules for group links. It complicates the code, and no way it can be sanely supported.
For example, it's not forbidden for issue_sqe callbacks to queue requests to io-wq and return 0 (IOU_ISSUE_SKIP_COMPLETE which would be turned into 0), and then we have two racing io_queue_group_members() calls.

It can by handled by adding io_queue_sqe_group() in which:

- req->grp_link is moved to one local variable, and make every member's grp_leader point to req

Quoted 6 lines

- call io_queue_sqe() for leader

- then call io_queue_group_members() for all members, and make sure not touch leader in io_queue_group_members()

What do you think of this way?

By the end of the day, io_queue_sqe is just not the right place for it. Take a look at the scheme above, I believe it should work

Signature · 1 line
Pavel Begunkov
#8 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

On 7/24/24 14:41, Pavel Begunkov wrote:
...> io_free_batch_list() {

Quoted 12 lines

    if (req->flags & GROUP) {
        if (req_is_member(req)) { req->grp_leader->grp_refs--;
            if (req->grp_leader->grp_refs == 0) { req->io_task_work.func = io_req_task_complete; io_req_task_work_add(req->grp_leader); // can be done better....
            }
            goto free_req;
        }
        WARN_ON_ONCE(!req_is_leader());

Quoted 5 lines

        if (!(req->flags & SEEN_FIRST_TIME)) { // already posted it just before coming here req->flags |= SKIP_CQE;
            // we'll see it again when grp_refs hit 0 req->flags |= SEEN_FIRST_TIME;

Forgot queue_group_members() here

Quoted 17 lines

            // Don't free the req, we're leaving it alive for now. // req->ref/REQ_F_REFCOUNT will be put next time we get here. return; // or continue
        }

        clean_up_request_resources(); // calls back into ublk // and now free the leader
    }

free_req:
    // the rest of io_free_batch_list()
    if (flags & REQ_F_REFCOUNT) {
        req_drop_ref();
        ....
    }
    ...
}

Signature · 1 line
Pavel Begunkov
author
#9 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

In reply to Pavel Begunkov
Quoted 31 lines · Pavel Begunkov
Quoted 10 lines · Ming Lei

Hi Pavel,

Thanks for the review!

Quoted 5 lines · Pavel Begunkov
Quoted 4 lines · Ming Lei

SQE group is defined as one chain of SQEs starting with the first SQE that has IOSQE_SQE_GROUP set, and ending with the first subsequent SQE that doesn't have it set, and it is similar with chain of linked SQEs.

...

Quoted 19 lines
Quoted 18 lines
Quoted 5 lines

---

io_uring/io_uring.c +0 -0
index 7597344a6440..b5415f0774e5 100644

...

io_uring/io_uring.c static inline void io_req_track_inflight(struct io_kiocb *req) · line 428

Quoted 8 lines
io_uring/io_uring.c +4 -0
@@ -421,6 +422,10 @@ static inline void io_req_track_inflight(struct io_kiocb *req)
   	if (!(req->flags & REQ_F_INFLIGHT)) {
   		req->flags |= REQ_F_INFLIGHT;
   		atomic_inc(&req->task->io_uring->inflight_tracked);
+
+		/* make members' REQ_F_INFLIGHT discoverable via leader's */
+		if (req_is_group_member(req))
+			io_req_track_inflight(req->grp_leader);

Requests in a group can be run in parallel with the leader (i.e. io_issue_sqe()), right? In which case it'd race setting req->flags. We'd need to think how make it sane.

Quoted 6 lines
Quoted 1 line

Yeah, another easier way could be to always mark leader as INFLIGHT.

I've been thinking a bit more about it, there should be an easier way out since we now have lazy file assignment. I sent a patch closing a gap, I need to double check if that's enough, but let's forget about additional REQ_F_INFLIGHT handling here.

Great, thanks!

Quoted 42 lines

...

Quoted 28 lines
Quoted 19 lines
Quoted 19 lines
io_uring/io_uring.c +8 -1
@@ -1420,6 +1553,7 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
   	__must_hold(&ctx->uring_lock)
   {
   	struct io_submit_state *state = &ctx->submit_state;
+	struct io_wq_work_list grp_list = {NULL};
   	struct io_wq_work_node *node;
   	__io_cq_lock(ctx);
@@ -1427,11 +1561,22 @@ void __io_submit_flush_completions(struct io_ring_ctx *ctx)
   		struct io_kiocb *req = container_of(node, struct io_kiocb,
   					    comp_list);
-		if (!(req->flags & REQ_F_CQE_SKIP))
+		/*
+		 * For group leader, cqe has to be committed after all
+		 * members are committed, when the group leader flag is
+		 * cleared
+		 */
+		if (!(req->flags & REQ_F_CQE_SKIP) &&
+				likely(!req_is_group_leader(req)))
   			io_req_commit_cqe(ctx, req);
Quoted 8 lines

io_uring/io_uring.c void __io_submit_flush_completions(struct io_ring_ctx *ctx) · line 1572

Quoted 2 lines
io_uring/io_uring.c +2 -0
+		if (req->flags & REQ_F_SQE_GROUP)
+			io_complete_group_req(req, &grp_list);

if (unlikely(flags & (SKIP_CQE|GROUP))) {
<sqe group code>
if (/* needs to skip CQE posting */)
continue;

Quoted 2 lines

io_complete_group_req() needs to be called too in case of CQE_SKIP because the current request may belong to group.

What's the problem? You can even do

if (flags & GROUP) {
	// do all group specific stuff
	// handle CQE_SKIP if needed
} else if (flags & CQE_SKIP) {
	continue;
}
Quoted 2 lines

And call io_complete_group_req() and other group stuff at any place there.

It depends on if leader CQE posting need to be the last one posted.

Quoted 16 lines
Quoted 16 lines
Quoted 15 lines

<more sqe group code>
}

io_req_commit_cqe();

Please. And, what's the point of reversing the CQE order and posting the "leader" completion last? It breaks the natural order of how IO complete, that is first the "leader" completes what it has need to do including IO, and then "members" follow doing their stuff. And besides, you can even post a CQE for the "leader" when its IO is done and let the user possibly continue executing. And the user can count when the entire group complete, if that's necessary to know.

Quoted 8 lines
Quoted 4 lines

There are several reasons for posting leader completion last:

1) only the leader is visible in link chain, IO drain has to wait the whole group by draining the leader

Let's forget about IO drain. It's a feature I'd love to see killed (if only we can), it's a slow path, for same reasons I'll discourage anyone using it.

Then we have to fail io group in case of IO_DRAIN, otherwise, it may fail liburing test.

I am fine with this way, at least ublk doesn't use IO_DRAIN at all.

Quoted 20 lines

For correctness we can just copy the link trick, i.e. mark the next request outside of the current group/link as drained like below or just fail the group.

io_uring/io_uring.c +1 -1
index 7ed1e009aaec..aa0b93765406 100644
@@ -1975,7 +1975,7 @@ static void io_init_req_drain(struct io_kiocb *req)
 	struct io_kiocb *head = ctx->submit_state.link.head;
 	ctx->drain_active = true;
-	if (head) {
+	if (head || ctx->submit_state.group.head) {
 		/*
 		 * If we need to drain a request in the middle of a link, drain
 		 * the head request and the next request/link after the current
 
Quoted 5 lines
Quoted 2 lines

2) when members depend on leader, leader holds group-wide resource, so it has to be completed after all members are done

I'm talking about posting a CQE but not destroying the request (and associated resources).

Such as, in ublk, the group leader is one uring command for providing buffer, if its cqe is observed before member consumers's CQE, this way may confuse application, cause consumer is supposed to be consuming the provided buffer/resource, and it shouldn't have been completed before all consumers.

Quoted 66 lines
Quoted 44 lines
Quoted 24 lines
Quoted 9 lines
io_uring/io_uring.c +3 -0
   	}
   	__io_cq_unlock_post(ctx);
+	if (!wq_list_empty(&grp_list))
+		__wq_list_splice(&grp_list, state->compl_reqs.first);
+
   	if (!wq_list_empty(&state->compl_reqs)) {
   		io_free_batch_list(ctx, state->compl_reqs.first);
   		INIT_WQ_LIST(&state->compl_reqs);

...

Quoted 14 lines
io_uring/io_uring.c +8 -3
@@ -1754,9 +1903,18 @@ struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
   	struct io_kiocb *nxt = NULL;
   	if (req_ref_put_and_test(req)) {
-		if (req->flags & IO_REQ_LINK_FLAGS)
-			nxt = io_req_find_next(req);
-		io_free_req(req);
+		/*
+		 * CQEs have been posted in io_req_complete_post() except
+		 * for group leader, and we can't advance the link for
+		 * group leader until its CQE is posted.
+		 */
+		if (!req_is_group_leader(req)) {
+			if (req->flags & IO_REQ_LINK_FLAGS)
+				nxt = io_req_find_next(req);
Quoted 8 lines

io_uring/io_uring.c struct io_wq_work *io_wq_free_work(struct io_wq_work *work) · line 1915

Quoted 3 lines
io_uring/io_uring.c +3 -0
+			io_free_req(req);
+		} else {
+			__io_free_req(req, false);

Something fishy is going on here. io-wq only holds a ref that the request is not killed, but it's owned by someone else. And the owner is responsible for CQE posting and logical flow of the request.

io_req_complete_post() is always called in io-wq for CQE posting before io-wq drops ref.

The ref held by io-wq prevents the owner from calling io_free_req(), so the owner actually can't run CQE post.

Quoted 5 lines

Now, the owner put the request down but for some reason didn't finish with the request like posting a CQE, but it's delayed to iowq dropping the ref?

Quoted 8 lines
Quoted 4 lines

I assume the refcounting hierarchy, first grp_refs go down, and when it hits zero it does whatever it needs, posting a CQE at that point of prior, and then puts the request reference down.

Yes, that is why the patch doesn't mark CQE_SKIP for leader in io_wq_free_work(), meantime leader->link has to be issued after leader's CQE is posted in case of io-wq.

The point is that io_wq_free_work() doesn't need to know anything about groups and can just continue setting the skip cqe flag as before if it's done differently

Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

Quoted 8 lines
io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}

OK.

io_wq_free_work() still need to change to not deal with next link & ignoring skip_cqe, because group handling( cqe posting, link advance) is completely moved into io_submit_flush_completions().

Quoted 15 lines

You can do it this way, nobody would ever care, and it shouldn't affect performance. Otherwise everything down below can probably be extended to io_req_complete_post().

To avoid confusion in terminology, what I call a member below doesn't include a leader. IOW, a group leader request is not a member.

At the init we have:
grp_refs = nr_members; /* doesn't include the leader */

Let's also say that the group leader can and always goes through io_submit_flush_completions() twice, just how it's with your patches.

Quoted 6 lines

1) The first time we see the leader in io_submit_flush_completions() is when it's done with resource preparation. For example, it was doing some IO into a buffer, and now is ready to give that buffer with data to group members. At this point it should queue up all group members. And we also drop 1 grp_ref. There will also be no io_issue_sqe() for it anymore.

Ok, then it is just the case with dependency.

Quoted 10 lines

2) Members are executed and completed, in io_submit_flush_completions() they drop 1 grp_leader->grp_ref reference each.

3) When all members complete, leader's grp_ref becomes 0. Here the leader is queued for io_submit_flush_completions() a second time, at which point it drops ublk buffers and such and gets destroyed.

You can post a CQE in 1) and then set CQE_SKIP. Can also be fitted into 3). A pseudo code for when we post it in step 1)

This way should work, but it confuses application because the leader is completed before all members:

- leader usually provide resources in group wide
- member consumes this resource
- leader is supposed to be completed after all consumer(member) are done.

Given it is UAPI, we have to be careful with CQE posting order.

Quoted 39 lines
io_free_batch_list() {
	if (req->flags & GROUP) {
		if (req_is_member(req)) {
			req->grp_leader->grp_refs--;
			if (req->grp_leader->grp_refs == 0) {
				req->io_task_work.func = io_req_task_complete;
				io_req_task_work_add(req->grp_leader);
				// can be done better....
			}
			goto free_req;
		}
		WARN_ON_ONCE(!req_is_leader());

		if (!(req->flags & SEEN_FIRST_TIME)) {
			// already posted it just before coming here
			req->flags |= SKIP_CQE;
			// we'll see it again when grp_refs hit 0
			req->flags |= SEEN_FIRST_TIME;

			// Don't free the req, we're leaving it alive for now.
			// req->ref/REQ_F_REFCOUNT will be put next time we get here.
			return; // or continue
		}

		clean_up_request_resources(); // calls back into ublk
		// and now free the leader
	}

free_req:

	// the rest of io_free_batch_list()
	if (flags & REQ_F_REFCOUNT) {
		req_drop_ref();
		....
	}
	...
}
Quoted 6 lines

This way
1) There are relatively easy request lifetime rules.
2) No special ownership/lifetime rules for the group link field.
3) You don't need to touch io_req_complete_defer()
4) io-wq doesn't know anything about grp_refs and doesn't play tricks with SKIP_CQE.

io_wq_free_work() still need to change for not setting SKIP_CQE and not advancing the link.

Quoted 49 lines

5) All handling is in one place, doesn't need multiple checks in common hot path. You might need some extra, but at least it's contained.

Quoted 45 lines
Quoted 29 lines
Quoted 17 lines
io_uring/io_uring.c +4 -0
+		}
   	}
   	return nxt ? &nxt->work : NULL;
   }
@@ -1821,6 +1979,8 @@ void io_wq_submit_work(struct io_wq_work *work)
   		}
   	}
+	if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, true);
   	do {
   		ret = io_issue_sqe(req, issue_flags);
   		if (ret != -EAGAIN)
@@ -1932,9 +2092,17 @@ static inline void io_queue_sqe(struct io_kiocb *req)
   	/*
   	 * We async punt it if the file wasn't marked NOWAIT, or if the file
   	 * doesn't support non-blocking read/write attempts
+	 *

io_uring/io_uring.c static inline void io_queue_sqe(struct io_kiocb *req) · line 2105

Quoted 10 lines
io_uring/io_uring.c +7 -0
+	 * Request is always freed after returning from io_queue_sqe(), so
+	 * it is fine to check its flags after it is issued
+	 *
+	 * For group leader, members holds leader references, so it is safe
+	 * to touch the leader after leader is issued
   	 */
   	if (unlikely(ret))
   		io_queue_async(req, ret);
+	else if (need_queue_group_members(req->flags))
+		io_queue_group_members(req, false);

It absolutely cannot be here. There is no relation between this place

Quoted 8 lines

in code and lifetime of the request. It could've been failed or completed, it can also be flying around in a completely arbitrary context being executed. We're not introducing weird special lifetime rules for group links. It complicates the code, and no way it can be sanely supported.
For example, it's not forbidden for issue_sqe callbacks to queue requests to io-wq and return 0 (IOU_ISSUE_SKIP_COMPLETE which would be turned into 0), and then we have two racing io_queue_group_members() calls.

It can by handled by adding io_queue_sqe_group() in which:

- req->grp_link is moved to one local variable, and make every member's grp_leader point to req

- call io_queue_sqe() for leader

Quoted 7 lines
Quoted 4 lines

- then call io_queue_group_members() for all members, and make sure not touch leader in io_queue_group_members()

What do you think of this way?

By the end of the day, io_queue_sqe is just not the right place for it. Take a look at the scheme above, I believe it should work

OK, thanks again for the review!

Thanks,
Ming

#10 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 2 lines · Ming Lei
Quoted 1 line · Pavel Begunkov

On 7/23/24 15:34, Ming Lei wrote:

...

Quoted 18 lines
Quoted 9 lines
Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

Quoted 8 lines
io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}
Quoted 4 lines

OK.

io_wq_free_work() still need to change to not deal with next link & ignoring skip_cqe, because group handling(

No, it doesn't need to know about all that.

Quoted 2 lines

cqe posting, link advance) is completely moved into io_submit_flush_completions().

It has never been guaranteed that io_req_complete_post() will be the one completing the request, io_submit_flush_completions() can always happen.

struct io_wq_work *io_wq_free_work(struct io_wq_work *work)

{
	...
	if (req_ref_put_and_test(req)) {
		nxt = io_req_find_next(req);
		io_free_req();
	}
}

We queue linked requests only when all refs are dropped, and the group handling in my snippet is done before we drop the owner's reference.

IOW, you won't hit io_free_req() in io_wq_free_work() for a leader unless all members in its group got completed and the leader already went through the code dropping those shared ublk buffers.

Quoted 37 lines
Quoted 14 lines

You can do it this way, nobody would ever care, and it shouldn't affect performance. Otherwise everything down below can probably be extended to io_req_complete_post().

To avoid confusion in terminology, what I call a member below doesn't include a leader. IOW, a group leader request is not a member.

At the init we have:
grp_refs = nr_members; /* doesn't include the leader */

Let's also say that the group leader can and always goes through io_submit_flush_completions() twice, just how it's with your patches.

Quoted 6 lines

1) The first time we see the leader in io_submit_flush_completions() is when it's done with resource preparation. For example, it was doing some IO into a buffer, and now is ready to give that buffer with data to group members. At this point it should queue up all group members. And we also drop 1 grp_ref. There will also be no io_issue_sqe() for it anymore.

Ok, then it is just the case with dependency.

Quoted 10 lines

2) Members are executed and completed, in io_submit_flush_completions() they drop 1 grp_leader->grp_ref reference each.

3) When all members complete, leader's grp_ref becomes 0. Here the leader is queued for io_submit_flush_completions() a second time, at which point it drops ublk buffers and such and gets destroyed.

You can post a CQE in 1) and then set CQE_SKIP. Can also be fitted into 3). A pseudo code for when we post it in step 1)

This way should work, but it confuses application because the leader is completed before all members:

Quoted 6 lines

- leader usually provide resources in group wide
- member consumes this resource
- leader is supposed to be completed after all consumer(member) are done.

Given it is UAPI, we have to be careful with CQE posting order.

That's exactly what I was telling about the uapi previously, I don't believe we want to inverse the natural CQE order.

Regardless, the order can be inversed like this:

__io_flush_completions() {
	...
	if (req->flags & (SKIP_CQE|GROUP)) {
		if (req->flags & SKIP_CQE)
			continue;
		// post a CQE only when we see it for a 2nd time in io_flush_completion();
		if (is_leader() && !(req->flags & ALREADY_SEEN))
			continue;
	}
	post_cqe();
}
Quoted 36 lines
Quoted 36 lines
io_free_batch_list() {
	if (req->flags & GROUP) {
		if (req_is_member(req)) {
			req->grp_leader->grp_refs--;
			if (req->grp_leader->grp_refs == 0) {
				req->io_task_work.func = io_req_task_complete;
				io_req_task_work_add(req->grp_leader);
				// can be done better....
			}
			goto free_req;
		}
		WARN_ON_ONCE(!req_is_leader());

		if (!(req->flags & SEEN_FIRST_TIME)) {
			// already posted it just before coming here
			req->flags |= SKIP_CQE;
			// we'll see it again when grp_refs hit 0
			req->flags |= SEEN_FIRST_TIME;

			// Don't free the req, we're leaving it alive for now.
			// req->ref/REQ_F_REFCOUNT will be put next time we get here.
			return; // or continue
		}

		clean_up_request_resources(); // calls back into ublk
		// and now free the leader
	}

free_req:

	// the rest of io_free_batch_list()
	if (flags & REQ_F_REFCOUNT) {
		req_drop_ref();
		....
	}
	...
}
Signature · 1 line
Pavel Begunkov
author
#11 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 46 lines · Pavel Begunkov
Quoted 2 lines · Ming Lei
Quoted 1 line · Pavel Begunkov

On 7/23/24 15:34, Ming Lei wrote:

...

Quoted 18 lines
Quoted 9 lines
Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

Quoted 8 lines
io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}
Quoted 4 lines

OK.

io_wq_free_work() still need to change to not deal with next link & ignoring skip_cqe, because group handling(

No, it doesn't need to know about all that.

Quoted 2 lines

cqe posting, link advance) is completely moved into io_submit_flush_completions().

It has never been guaranteed that io_req_complete_post() will be the one completing the request, io_submit_flush_completions() can always happen.

struct io_wq_work *io_wq_free_work(struct io_wq_work *work)

{
	...
	if (req_ref_put_and_test(req)) {
		nxt = io_req_find_next(req);
		io_free_req();
	}
}
Quoted 8 lines

We queue linked requests only when all refs are dropped, and the group handling in my snippet is done before we drop the owner's reference.

IOW, you won't hit io_free_req() in io_wq_free_work() for a leader unless all members in its group got completed and the leader already went through the code dropping those shared ublk buffers.

If io_free_req() won't be called for leader, leader won't be added to ->compl_reqs, and it has to be generated when all members are completed in __io_submit_flush_completions().

For !io_wq, we can align to this way by not completing leader in io_req_complete_defer().

The above implementation looks simpler, and more readable.

Quoted 51 lines
Quoted 39 lines
Quoted 16 lines

You can do it this way, nobody would ever care, and it shouldn't affect performance. Otherwise everything down below can probably be extended to io_req_complete_post().

To avoid confusion in terminology, what I call a member below doesn't include a leader. IOW, a group leader request is not a member.

At the init we have:
grp_refs = nr_members; /* doesn't include the leader */

Let's also say that the group leader can and always goes through io_submit_flush_completions() twice, just how it's with your patches.

Quoted 6 lines

1) The first time we see the leader in io_submit_flush_completions() is when it's done with resource preparation. For example, it was doing some IO into a buffer, and now is ready to give that buffer with data to group members. At this point it should queue up all group members. And we also drop 1 grp_ref. There will also be no io_issue_sqe() for it anymore.

Ok, then it is just the case with dependency.

Quoted 10 lines

2) Members are executed and completed, in io_submit_flush_completions() they drop 1 grp_leader->grp_ref reference each.

3) When all members complete, leader's grp_ref becomes 0. Here the leader is queued for io_submit_flush_completions() a second time, at which point it drops ublk buffers and such and gets destroyed.

You can post a CQE in 1) and then set CQE_SKIP. Can also be fitted into 3). A pseudo code for when we post it in step 1)

This way should work, but it confuses application because the leader is completed before all members:

Quoted 6 lines

- leader usually provide resources in group wide
- member consumes this resource
- leader is supposed to be completed after all consumer(member) are done.

Given it is UAPI, we have to be careful with CQE posting order.

That's exactly what I was telling about the uapi previously, I don't believe we want to inverse the natural CQE order.

Regardless, the order can be inversed like this:

Quoted 8 lines
__io_flush_completions() {
	...
	if (req->flags & (SKIP_CQE|GROUP)) {
		if (req->flags & SKIP_CQE)
			continue;
		// post a CQE only when we see it for a 2nd time in io_flush_completion();
		if (is_leader() && !(req->flags & ALREADY_SEEN))
			continue;

I am afraid that ALREADY_SEEN can't work, since leader can only be added to ->compl_reqs once.

Thanks,
Ming

author
#12 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 56 lines · Ming Lei
Quoted 46 lines · Pavel Begunkov
Quoted 2 lines · Ming Lei
Quoted 1 line · Pavel Begunkov

On 7/23/24 15:34, Ming Lei wrote:

...

Quoted 18 lines
Quoted 9 lines
Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

Quoted 8 lines
io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}
Quoted 4 lines

OK.

io_wq_free_work() still need to change to not deal with next link & ignoring skip_cqe, because group handling(

No, it doesn't need to know about all that.

Quoted 2 lines

cqe posting, link advance) is completely moved into io_submit_flush_completions().

It has never been guaranteed that io_req_complete_post() will be the one completing the request, io_submit_flush_completions() can always happen.

struct io_wq_work *io_wq_free_work(struct io_wq_work *work)

{
	...
	if (req_ref_put_and_test(req)) {
		nxt = io_req_find_next(req);
		io_free_req();
	}
}
Quoted 8 lines

We queue linked requests only when all refs are dropped, and the group handling in my snippet is done before we drop the owner's reference.

IOW, you won't hit io_free_req() in io_wq_free_work() for a leader unless all members in its group got completed and the leader already went through the code dropping those shared ublk buffers.

Quoted 8 lines

If io_free_req() won't be called for leader, leader won't be added to ->compl_reqs, and it has to be generated when all members are completed in __io_submit_flush_completions().

For !io_wq, we can align to this way by not completing leader in io_req_complete_defer().

The above implementation looks simpler, and more readable.

Thinking of this issue further, looks the above is still not doable:

1) for avoiding to hit io_free_req(), extra req->refs has to be grabbed, then the leader's completion may not be notified.

2) 1) may be avoided by holding one leader's refcount for each member, and call req_ref_put_and_test(leader) when leader or member is completed, and post leader's CQE when leader's refs drops to zero. But there are other issues:

- other req_ref_inc_not_zero() or req_ref_get() may cause leader's CQE post missed

- the req_ref_put_and_test() in io_free_batch_list() can be called on group leader unexpectedly.

both 1) and 2) need to touch io_req_complete_defer() for completing group leader

Thanks,
Ming

author
#13 lore raw

Re: [PATCH V4 4/8] io_uring: support SQE group

Quoted 76 lines · Ming Lei
Quoted 56 lines · Ming Lei
Quoted 46 lines · Pavel Begunkov
Quoted 2 lines · Ming Lei
Quoted 1 line · Pavel Begunkov

On 7/23/24 15:34, Ming Lei wrote:

...

Quoted 18 lines
Quoted 9 lines
Quoted 4 lines

But grp_refs is dropped after io-wq request reference drops to zero, then both io-wq and nor-io-wq code path can be unified wrt. dealing with grp_refs, meantime it needn't to be updated in extra(io-wq) context.

Let's try to describe how it can work. First, I'm only describing the dep mode for simplicity. And for the argument's sake we can say that all CQEs are posted via io_submit_flush_completions.

Quoted 8 lines
io_req_complete_post() {
	if (flags & GROUP) {
		req->io_task_work.func = io_req_task_complete;
		io_req_task_work_add(req);
		return;
	}
	...
}
Quoted 4 lines

OK.

io_wq_free_work() still need to change to not deal with next link & ignoring skip_cqe, because group handling(

No, it doesn't need to know about all that.

Quoted 2 lines

cqe posting, link advance) is completely moved into io_submit_flush_completions().

It has never been guaranteed that io_req_complete_post() will be the one completing the request, io_submit_flush_completions() can always happen.

struct io_wq_work *io_wq_free_work(struct io_wq_work *work)

{
	...
	if (req_ref_put_and_test(req)) {
		nxt = io_req_find_next(req);
		io_free_req();
	}
}
Quoted 8 lines

We queue linked requests only when all refs are dropped, and the group handling in my snippet is done before we drop the owner's reference.

IOW, you won't hit io_free_req() in io_wq_free_work() for a leader unless all members in its group got completed and the leader already went through the code dropping those shared ublk buffers.

Quoted 8 lines

If io_free_req() won't be called for leader, leader won't be added to ->compl_reqs, and it has to be generated when all members are completed in __io_submit_flush_completions().

For !io_wq, we can align to this way by not completing leader in io_req_complete_defer().

The above implementation looks simpler, and more readable.

Thinking of this issue further, looks the above is still not doable:

1) for avoiding to hit io_free_req(), extra req->refs has to be grabbed, then the leader's completion may not be notified.

2) 1) may be avoided by holding one leader's refcount for each member, and call req_ref_put_and_test(leader) when leader or member is completed, and post leader's CQE when leader's refs drops to zero. But there are other issues:

Quoted 8 lines

- other req_ref_inc_not_zero() or req_ref_get() may cause leader's CQE post missed

- the req_ref_put_and_test() in io_free_batch_list() can be called on group leader unexpectedly.

both 1) and 2) need to touch io_req_complete_defer() for completing group leader

oops, looks I missed the point of completing request from io_req_complete_post() directly in the following link:

https://lore.kernel.org/linux-block/[email protected]/

Please ignore yesterday's replies, and now I should get the whole picture of your point.

Thanks,
Ming

author
#14 lore raw

PATCH v4 5/8 io_uring: support sqe group with members depending on leader

In reply to Ming Lei

Generic sqe group provides flexible way for supporting N:M dependency between groups.

However, some resource can't cross OPs, such as kernel buffer, otherwise the buffer may be leaked easily in case that any OP failure or application panic.

Add flag REQ_F_SQE_GROUP_DEP for allowing members to depend on group leader, so that group members won't be queued until the leader request is completed, and we still commit leader's CQE after all members CQE are posted. With this way, the kernel resource lifetime can be aligned with group leader or group, one typical use case is to support zero copy for device internal buffer.

This use case may not be generic enough, so set it only for specific OP which can serve as group leader, meantime we have run out of sqe flags.

---
 include/linux/io_uring_types.h |  3 +++
 io_uring/io_uring.c            | 15 ++++++++++++++-
 io_uring/io_uring.h            |  5 ++++-
 3 files changed, 21 insertions(+), 2 deletions(-)
include/linux/io_uring_types.h +3 -0
index b5cc3dee8fa2..f56f37833239 100644
@@ -471,6 +471,7 @@ enum {
 	REQ_F_BL_NO_RECYCLE_BIT,
 	REQ_F_BUFFERS_COMMIT_BIT,
 	REQ_F_SQE_GROUP_LEADER_BIT,
+	REQ_F_SQE_GROUP_DEP_BIT,
 
 	/* not a real bit, just to check we're not overflowing the space */
 	__REQ_F_LAST_BIT,
@@ -555,6 +556,8 @@ enum {
 	REQ_F_BUFFERS_COMMIT	= IO_REQ_FLAG(REQ_F_BUFFERS_COMMIT_BIT),
 	/* sqe group lead */
 	REQ_F_SQE_GROUP_LEADER	= IO_REQ_FLAG(REQ_F_SQE_GROUP_LEADER_BIT),
+	/* sqe group with members depending on leader */
+	REQ_F_SQE_GROUP_DEP	= IO_REQ_FLAG(REQ_F_SQE_GROUP_DEP_BIT),
 };
 
 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, struct io_tw_state *ts);
io_uring/io_uring.c +14 -1
index b5415f0774e5..986048bdc546 100644
@@ -882,7 +882,13 @@ static __always_inline void io_req_commit_cqe(struct io_ring_ctx *ctx,
 
 static inline bool need_queue_group_members(io_req_flags_t flags)
 {
-	return flags & REQ_F_SQE_GROUP_LEADER;
+	if (likely(!(flags & REQ_F_SQE_GROUP)))
+		return false;
+
+	if (!(flags & REQ_F_SQE_GROUP_LEADER) ||
+			(flags & REQ_F_SQE_GROUP_DEP))
+		return false;
+	return true;
 }
 
 /* Can only be called after this request is issued */
@@ -930,6 +936,9 @@ void io_queue_group_members(struct io_kiocb *req, bool async)
 
 		if (unlikely(member->flags & REQ_F_FAIL)) {
 			io_req_task_queue_fail(member, member->cqe.res);
+		} else if (unlikely((req->flags & REQ_F_FAIL) &&
+			     (req->flags & REQ_F_SQE_GROUP_DEP))) {
+			io_req_task_queue_fail(member, -ECANCELED);
 		} else if (member->flags & REQ_F_FORCE_ASYNC) {
 			io_req_task_queue(member);
 		} else {
@@ -1012,6 +1021,10 @@ static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
 		return;
 	}
 
+	/* queue members which may depend on leader */
+	if (req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP_DEP))
+		io_queue_group_members(req, true);
+
 	io_cq_lock(ctx);
 	if (!(req->flags & REQ_F_CQE_SKIP) && !req_is_group_leader(req)) {
 		if (!io_fill_cqe_req(ctx, req))
io_uring/io_uring.h +4 -1
index 8cc347959f7e..72cbbf883a46 100644
@@ -365,7 +365,10 @@ static inline void io_req_complete_defer(struct io_kiocb *req)
 
 	wq_list_add_tail(&req->comp_list, &state->compl_reqs);
 
-	/* members may not be issued when leader is completed */
+	/*
+	 * Members may not be issued when leader is completed, or members
+	 * depend on leader in case of REQ_F_SQE_GROUP_DEP
+	 */
 	if (unlikely(req_is_group_leader(req) && req->grp_link))
 		io_queue_group_members(req, false);
 }
Signature · 1 line
2.42.0
author
#15 lore raw

PATCH v4 6/8 io_uring: support providing sqe group buffer

In reply to Ming Lei

SQE group with REQ_F_SQE_GROUP_DEP introduces one new mechanism to share resource among one group of requests, and all member requests can consume the resource provided by group lead efficiently in parallel.

This patch uses the added sqe group feature REQ_F_SQE_GROUP_DEP to share kernel buffer in sqe group:

- the group lead provides kernel buffer to member requests

- member requests use the provided buffer to do FS or network IO, or more operations in future

- this kernel buffer is returned back after member requests use it up

This way looks a bit similar with kernel's pipe/splice, but there are some important differences:

- splice is for transferring data between two FDs via pipe, and fd_out can only read data from pipe; this feature can borrow buffer from group lead to members, so member request can write data to this buffer if the provided buffer is allowed to write to.

- splice implements data transfer by moving pages between subsystem and pipe, that means page ownership is transferred, and this way is one of the most complicated thing of splice; this patch supports scenarios in which the buffer can't be transferred, and buffer is only borrowed to member requests, and is returned back after member requests consume the provided buffer, so buffer lifetime is simplified a lot. Especially the buffer is guaranteed to be returned back.

- splice can't run in async way basically

It can help to implement generic zero copy between device and related operations, such as ublk, fuse, vdpa, even network receive or whatever.

---
 include/linux/io_uring_types.h | 33 +++++++++++++++++++
 io_uring/io_uring.c            | 10 +++++-
 io_uring/io_uring.h            |  5 +++
 io_uring/kbuf.c                | 60 ++++++++++++++++++++++++++++++++++
 io_uring/kbuf.h                | 13 ++++++++
 io_uring/net.c                 | 23 ++++++++++++-
 io_uring/opdef.c               |  4 +++
 io_uring/opdef.h               |  2 ++
 io_uring/rw.c                  | 20 +++++++++++-
 9 files changed, 167 insertions(+), 3 deletions(-)
include/linux/io_uring_types.h +33 -0
index f56f37833239..918b5ae8a00e 100644
@@ -6,6 +6,7 @@
 #include <linux/task_work.h>
 #include <linux/bitmap.h>
 #include <linux/llist.h>
+#include <linux/bvec.h>
 #include <uapi/linux/io_uring.h>
 
 enum {
@@ -39,6 +40,26 @@ enum io_uring_cmd_flags {
 	IO_URING_F_COMPAT		= (1 << 12),
 };
 
+struct io_uring_kernel_buf;
+typedef void (io_uring_buf_giveback_t) (const struct io_uring_kernel_buf *);
+
+/* buffer provided from kernel */
+struct io_uring_kernel_buf {
+	unsigned long		len;
+	unsigned short		nr_bvecs;
+	unsigned char		dir;	/* ITER_SOURCE or ITER_DEST */
+
+	/* offset in the 1st bvec */
+	unsigned int		offset;
+	const struct bio_vec	*bvec;
+
+	/* called when we are done with this buffer */
+	io_uring_buf_giveback_t	*grp_kbuf_ack;
+
+	/* private field, user don't touch it */
+	struct bio_vec		__bvec[];
+};
+
 struct io_wq_work_node {
 	struct io_wq_work_node *next;
 };
@@ -472,6 +493,7 @@ enum {
 	REQ_F_BUFFERS_COMMIT_BIT,
 	REQ_F_SQE_GROUP_LEADER_BIT,
 	REQ_F_SQE_GROUP_DEP_BIT,
+	REQ_F_GROUP_KBUF_BIT,
 
 	/* not a real bit, just to check we're not overflowing the space */
 	__REQ_F_LAST_BIT,
@@ -558,6 +580,8 @@ enum {
 	REQ_F_SQE_GROUP_LEADER	= IO_REQ_FLAG(REQ_F_SQE_GROUP_LEADER_BIT),
 	/* sqe group with members depending on leader */
 	REQ_F_SQE_GROUP_DEP	= IO_REQ_FLAG(REQ_F_SQE_GROUP_DEP_BIT),
+	/* group lead provides kbuf for members, set for both lead and member */
+	REQ_F_GROUP_KBUF	= IO_REQ_FLAG(REQ_F_GROUP_KBUF_BIT),
 };
 
 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, struct io_tw_state *ts);
@@ -641,6 +665,15 @@ struct io_kiocb {
 		 * REQ_F_BUFFER_RING is set.
 		 */
 		struct io_buffer_list	*buf_list;
+
+		/*
+		 * store kernel buffer provided by sqe group lead, valid
+		 * IFF REQ_F_GROUP_KBUF
+		 *
+		 * The buffer meta is immutable since it is shared by
+		 * all member requests
+		 */
+		const struct io_uring_kernel_buf *grp_kbuf;
 	};
 
 	union {
io_uring/io_uring.c +9 -1
index 986048bdc546..ae113fcce992 100644
@@ -116,7 +116,7 @@
 
 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
 				REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
-				REQ_F_ASYNC_DATA)
+				REQ_F_ASYNC_DATA | REQ_F_GROUP_KBUF)
 
 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
 				 REQ_F_SQE_GROUP | IO_REQ_CLEAN_FLAGS)
@@ -386,6 +386,11 @@ static bool req_need_defer(struct io_kiocb *req, u32 seq)
 
 static void io_clean_op(struct io_kiocb *req)
 {
+	/* GROUP_KBUF is only available for REQ_F_SQE_GROUP_DEP */
+	if ((req->flags & (REQ_F_GROUP_KBUF | REQ_F_SQE_GROUP_DEP)) ==
+			(REQ_F_GROUP_KBUF | REQ_F_SQE_GROUP_DEP))
+		io_group_kbuf_drop(req);
+
 	if (req->flags & REQ_F_BUFFER_SELECTED) {
 		spin_lock(&req->ctx->completion_lock);
 		io_kbuf_drop(req);
@@ -928,9 +933,12 @@ void io_queue_group_members(struct io_kiocb *req, bool async)
 
 	req->grp_link = NULL;
 	while (member) {
+		const struct io_issue_def *def = &io_issue_defs[member->opcode];
 		struct io_kiocb *next = member->grp_link;
 
 		member->grp_leader = req;
+		if ((req->flags & REQ_F_GROUP_KBUF) && def->accept_group_kbuf)
+			member->flags |= REQ_F_GROUP_KBUF;
 		if (async)
 			member->flags |= REQ_F_FORCE_ASYNC;
 
io_uring/io_uring.h +5 -0
index 72cbbf883a46..f48b6dc6d6aa 100644
@@ -351,6 +351,11 @@ static inline bool req_is_group_member(struct io_kiocb *req)
 	return !req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP);
 }
 
+static inline bool req_support_group_dep(struct io_kiocb *req)
+{
+	return req_is_group_leader(req) && (req->flags & REQ_F_SQE_GROUP_DEP);
+}
+
 /*
  * Don't complete immediately but use deferred completion infrastructure.
  * Protected by ->uring_lock and can only be used either with
io_uring/kbuf.c +60 -0

63 lines not on this page · raw message

io_uring/kbuf.h +13 -0
index b90aca3a57fa..2e1b7f91efb6 100644
@@ -82,6 +82,11 @@ struct io_buffer_list *io_pbuf_get_bl(struct io_ring_ctx *ctx,
 				      unsigned long bgid);
 int io_pbuf_mmap(struct file *file, struct vm_area_struct *vma);
 
+int io_provide_group_kbuf(struct io_kiocb *req,
+		const struct io_uring_kernel_buf *grp_kbuf);
+int io_import_group_kbuf(struct io_kiocb *req, unsigned long buf_off,
+		unsigned int len, int dir, struct iov_iter *iter);
+
 static inline bool io_kbuf_recycle_ring(struct io_kiocb *req)
 {
 	/*
@@ -180,4 +185,12 @@ static inline unsigned int io_put_kbufs(struct io_kiocb *req, int nbufs,
 {
 	return __io_put_kbufs(req, nbufs, issue_flags);
 }
+
+static inline void io_group_kbuf_drop(struct io_kiocb *req)
+{
+	const struct io_uring_kernel_buf *gbuf = req->grp_kbuf;
+
+	if (gbuf && gbuf->grp_kbuf_ack)
+		gbuf->grp_kbuf_ack(gbuf);
+}
 #endif
io_uring/net.c +22 -1
index 25223e11958f..9b08ccccd9b0 100644
@@ -89,6 +89,13 @@ struct io_sr_msg {
  */
 #define MULTISHOT_MAX_RETRY	32
 
+#define user_ptr_to_u64(x) (		\
+{					\
+	typecheck(void __user *, (x));	\
+	(u64)(unsigned long)(x);	\
+}					\
+)
+
 int io_shutdown_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 {
 	struct io_shutdown *shutdown = io_kiocb_to_cmd(req, struct io_shutdown);
@@ -375,7 +382,7 @@ static int io_send_setup(struct io_kiocb *req)
 		kmsg->msg.msg_name = &kmsg->addr;
 		kmsg->msg.msg_namelen = sr->addr_len;
 	}
-	if (!io_do_buffer_select(req)) {
+	if (!io_do_buffer_select(req) && !(req->flags & REQ_F_GROUP_KBUF)) {
 		ret = import_ubuf(ITER_SOURCE, sr->buf, sr->len,
 				  &kmsg->msg.msg_iter);
 		if (unlikely(ret < 0))
@@ -595,6 +602,15 @@ int io_send(struct io_kiocb *req, unsigned int issue_flags)
 	if (issue_flags & IO_URING_F_NONBLOCK)
 		flags |= MSG_DONTWAIT;
 
+	if (req->flags & REQ_F_GROUP_KBUF) {
+		ret = io_import_group_kbuf(req,
+					user_ptr_to_u64(sr->buf),
+					sr->len, ITER_SOURCE,
+					&kmsg->msg.msg_iter);
+		if (unlikely(ret))
+			return ret;
+	}
+
 retry_bundle:
 	if (io_do_buffer_select(req)) {
 		struct buf_sel_arg arg = {
@@ -1145,6 +1161,11 @@ int io_recv(struct io_kiocb *req, unsigned int issue_flags)
 		if (unlikely(ret))
 			goto out_free;
 		sr->buf = NULL;
+	} else if (req->flags & REQ_F_GROUP_KBUF) {
+		ret = io_import_group_kbuf(req, user_ptr_to_u64(sr->buf),
+				sr->len, ITER_DEST, &kmsg->msg.msg_iter);
+		if (unlikely(ret))
+			goto out_free;
 	}
 
 	if (flags & MSG_WAITALL)
io_uring/opdef.c +4 -0
index a2be3bbca5ff..c12f57619a33 100644
@@ -246,6 +246,7 @@ const struct io_issue_def io_issue_defs[] = {
 		.ioprio			= 1,
 		.iopoll			= 1,
 		.iopoll_queue		= 1,
+		.accept_group_kbuf	= 1,
 		.async_size		= sizeof(struct io_async_rw),
 		.prep			= io_prep_read,
 		.issue			= io_read,
@@ -260,6 +261,7 @@ const struct io_issue_def io_issue_defs[] = {
 		.ioprio			= 1,
 		.iopoll			= 1,
 		.iopoll_queue		= 1,
+		.accept_group_kbuf	= 1,
 		.async_size		= sizeof(struct io_async_rw),
 		.prep			= io_prep_write,
 		.issue			= io_write,
@@ -282,6 +284,7 @@ const struct io_issue_def io_issue_defs[] = {
 		.audit_skip		= 1,
 		.ioprio			= 1,
 		.buffer_select		= 1,
+		.accept_group_kbuf	= 1,
 #if defined(CONFIG_NET)
 		.async_size		= sizeof(struct io_async_msghdr),
 		.prep			= io_sendmsg_prep,
@@ -297,6 +300,7 @@ const struct io_issue_def io_issue_defs[] = {
 		.buffer_select		= 1,
 		.audit_skip		= 1,
 		.ioprio			= 1,
+		.accept_group_kbuf	= 1,
 #if defined(CONFIG_NET)
 		.async_size		= sizeof(struct io_async_msghdr),
 		.prep			= io_recvmsg_prep,
io_uring/opdef.h +2 -0
index 14456436ff74..328c8a3c4fa7 100644
@@ -27,6 +27,8 @@ struct io_issue_def {
 	unsigned		iopoll_queue : 1;
 	/* vectored opcode, set if 1) vectored, and 2) handler needs to know */
 	unsigned		vectored : 1;
+	/* opcodes which accept provided group kbuf */
+	unsigned		accept_group_kbuf : 1;
 
 	/* size of async data needed, if any */
 	unsigned short		async_size;
io_uring/rw.c +19 -1
index 1a2128459cb4..e19ed05cc3e2 100644
@@ -235,7 +235,8 @@ static int io_prep_rw_setup(struct io_kiocb *req, int ddir, bool do_import)
 	if (io_rw_alloc_async(req))
 		return -ENOMEM;
 
-	if (!do_import || io_do_buffer_select(req))
+	if (!do_import || io_do_buffer_select(req) ||
+	    (req->flags & REQ_F_GROUP_KBUF))
 		return 0;
 
 	rw = req->async_data;
@@ -620,11 +621,16 @@ static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
  */
 static ssize_t loop_rw_iter(int ddir, struct io_rw *rw, struct iov_iter *iter)
 {
+	struct io_kiocb *req = cmd_to_io_kiocb(rw);
 	struct kiocb *kiocb = &rw->kiocb;
 	struct file *file = kiocb->ki_filp;
 	ssize_t ret = 0;
 	loff_t *ppos;
 
+	/* group buffer is kernel buffer and doesn't have userspace addr */
+	if (req->flags & REQ_F_GROUP_KBUF)
+		return -EOPNOTSUPP;
+
 	/*
 	 * Don't support polled IO through this interface, and we can't
 	 * support non-blocking either. For the latter, this just causes
@@ -831,6 +837,11 @@ static int __io_read(struct io_kiocb *req, unsigned int issue_flags)
 		ret = io_import_iovec(ITER_DEST, req, io, issue_flags);
 		if (unlikely(ret < 0))
 			return ret;
+	} else if (req->flags & REQ_F_GROUP_KBUF) {
+		ret = io_import_group_kbuf(req, rw->addr, rw->len, ITER_DEST,
+				&io->iter);
+		if (unlikely(ret))
+			return ret;
 	}
 
 	ret = io_rw_init_file(req, FMODE_READ);
@@ -1013,6 +1024,13 @@ int io_write(struct io_kiocb *req, unsigned int issue_flags)
 	ssize_t ret, ret2;
 	loff_t *ppos;
 
+	if (req->flags & REQ_F_GROUP_KBUF) {
+		ret = io_import_group_kbuf(req, rw->addr, rw->len, ITER_SOURCE,
+				&io->iter);
+		if (unlikely(ret))
+			return ret;
+	}
+
 	ret = io_rw_init_file(req, FMODE_WRITE);
 	if (unlikely(ret))
 		return ret;
Signature · 1 line
2.42.0
author
#16 lore raw

PATCH v4 7/8 io_uring/uring_cmd: support provide group kernel buffer

In reply to Ming Lei

Allow uring command to be group leader for providing kernel buffer, and this way can support generic device zero copy over device buffer.

The following patch will use the way to support zero copy for ublk.

---
 include/linux/io_uring/cmd.h  |  7 +++++++
 include/uapi/linux/io_uring.h |  7 ++++++-
 io_uring/uring_cmd.c          | 28 ++++++++++++++++++++++++++++
 3 files changed, 41 insertions(+), 1 deletion(-)
include/linux/io_uring/cmd.h +7 -0
index 447fbfd32215..fde3a2ec7d9a 100644
@@ -48,6 +48,8 @@ void __io_uring_cmd_do_in_task(struct io_uring_cmd *ioucmd,
 void io_uring_cmd_mark_cancelable(struct io_uring_cmd *cmd,
 		unsigned int issue_flags);
 
+int io_uring_cmd_provide_kbuf(struct io_uring_cmd *ioucmd,
+		const struct io_uring_kernel_buf *grp_kbuf);
 #else
 static inline int io_uring_cmd_import_fixed(u64 ubuf, unsigned long len, int rw,
 			      struct iov_iter *iter, void *ioucmd)
@@ -67,6 +69,11 @@ static inline void io_uring_cmd_mark_cancelable(struct io_uring_cmd *cmd,
 		unsigned int issue_flags)
 {
 }
+static inline int io_uring_cmd_provide_kbuf(struct io_uring_cmd *ioucmd,
+		const struct io_uring_kernel_buf *grp_kbuf)
+{
+	return -EOPNOTSUPP;
+}
 #endif
 
 /*
include/uapi/linux/io_uring.h +6 -1
index e6d321b3add7..2e1f33aeea2e 100644
@@ -271,9 +271,14 @@ enum io_uring_op {
  * sqe->uring_cmd_flags		top 8bits aren't available for userspace
  * IORING_URING_CMD_FIXED	use registered buffer; pass this flag
  *				along with setting sqe->buf_index.
+ * IORING_PROVIDE_GROUP_KBUF	this command provides group kernel buffer
+ *				for member requests which can retrieve
+ *				any sub-buffer with offset(sqe->addr) and
+ *				len(sqe->len)
  */
 #define IORING_URING_CMD_FIXED	(1U << 0)
-#define IORING_URING_CMD_MASK	IORING_URING_CMD_FIXED
+#define IORING_PROVIDE_GROUP_KBUF	(1U << 1)
+#define IORING_URING_CMD_MASK	(IORING_URING_CMD_FIXED | IORING_PROVIDE_GROUP_KBUF)
 
 
 /*
io_uring/uring_cmd.c +28 -0
index 21ac5fb2d5f0..14744eac9158 100644
@@ -15,6 +15,7 @@
 #include "alloc_cache.h"
 #include "rsrc.h"
 #include "uring_cmd.h"
+#include "kbuf.h"
 
 static struct uring_cache *io_uring_async_get(struct io_kiocb *req)
 {
@@ -175,6 +176,26 @@ void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2,
 }
 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
 
+/*
+ * Provide kernel buffer for sqe group members to consume, and the caller
+ * has to guarantee that the provided buffer and the callback are valid
+ * until the callback is called.
+ */
+int io_uring_cmd_provide_kbuf(struct io_uring_cmd *ioucmd,
+		const struct io_uring_kernel_buf *grp_kbuf)
+{
+	struct io_kiocb *req = cmd_to_io_kiocb(ioucmd);
+
+	if (unlikely(!(ioucmd->flags & IORING_PROVIDE_GROUP_KBUF)))
+		return -EINVAL;
+
+	if (unlikely(!req_support_group_dep(req)))
+		return -EINVAL;
+
+	return io_provide_group_kbuf(req, grp_kbuf);
+}
+EXPORT_SYMBOL_GPL(io_uring_cmd_provide_kbuf);
+
 static int io_uring_cmd_prep_setup(struct io_kiocb *req,
 				   const struct io_uring_sqe *sqe)
 {
@@ -207,6 +228,13 @@ int io_uring_cmd_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 	if (ioucmd->flags & ~IORING_URING_CMD_MASK)
 		return -EINVAL;
 
+	if (ioucmd->flags & IORING_PROVIDE_GROUP_KBUF) {
+		/* LEADER flag isn't set yet, so check GROUP only */
+		if (!(req->flags & REQ_F_SQE_GROUP))
+			return -EINVAL;
+		req->flags |= REQ_F_SQE_GROUP_DEP;
+	}
+
 	if (ioucmd->flags & IORING_URING_CMD_FIXED) {
 		struct io_ring_ctx *ctx = req->ctx;
 		u16 index;
Signature · 1 line
2.42.0
author
#17 lore raw

PATCH v4 8/8 ublk: support provide io buffer

In reply to Ming Lei

Implement uring command's IORING_PROVIDE_GROUP_KBUF, and provide io buffer for userpace to run io_uring operations(FS, network IO), then ublk zero copy can be supported.

userspace code:

https://github.com/ublk-org/ublksrv/tree/group-provide-buf.v2
git clone https://github.com/ublk-org/ublksrv.git -b group-provide-buf.v2

And both loop and nbd zero copy(io_uring send and send zc) are covered.

Performance improvement is quite obvious in big block size test, such as 'loop --buffered_io' perf is doubled in 64KB block test("loop/007 vs loop/009").

---
 drivers/block/ublk_drv.c      | 158 ++++++++++++++++++++++++++++++++--
 include/uapi/linux/ublk_cmd.h |   7 +-
 2 files changed, 154 insertions(+), 11 deletions(-)
drivers/block/ublk_drv.c +151 -7
index 4e159948c912..7f09e32f104e 100644
@@ -71,6 +71,8 @@ struct ublk_rq_data {
 	__u64 sector;
 	__u32 operation;
 	__u32 nr_zones;
+	bool allocated_bvec;
+	struct io_uring_kernel_buf buf[0];
 };
 
 struct ublk_uring_cmd_pdu {
@@ -189,11 +191,15 @@ struct ublk_params_header {
 	__u32	types;
 };
 
+static inline struct request *__ublk_check_and_get_req(struct ublk_device *ub,
+		struct ublk_queue *ubq, int tag, size_t offset);
 static bool ublk_abort_requests(struct ublk_device *ub, struct ublk_queue *ubq);
 
 static inline unsigned int ublk_req_build_flags(struct request *req);
 static inline struct ublksrv_io_desc *ublk_get_iod(struct ublk_queue *ubq,
 						   int tag);
+static void ublk_io_buf_giveback_cb(const struct io_uring_kernel_buf *buf);
+
 static inline bool ublk_dev_is_user_copy(const struct ublk_device *ub)
 {
 	return ub->dev_info.flags & UBLK_F_USER_COPY;
@@ -565,6 +571,11 @@ static inline bool ublk_need_req_ref(const struct ublk_queue *ubq)
 	return ublk_support_user_copy(ubq);
 }
 
+static inline bool ublk_support_zc(const struct ublk_queue *ubq)
+{
+	return ubq->flags & UBLK_F_SUPPORT_ZERO_COPY;
+}
+
 static inline void ublk_init_req_ref(const struct ublk_queue *ubq,
 		struct request *req)
 {
@@ -828,6 +839,71 @@ static size_t ublk_copy_user_pages(const struct request *req,
 	return done;
 }
 
+/*
+ * The built command buffer is immutable, so it is fine to feed it to
+ * concurrent io_uring provide buf commands
+ */
+static int ublk_init_zero_copy_buffer(struct request *req)
+{
+	struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
+	struct io_uring_kernel_buf *imu = data->buf;
+	struct req_iterator rq_iter;
+	unsigned int nr_bvecs = 0;
+	struct bio_vec *bvec;
+	unsigned int offset;
+	struct bio_vec bv;
+
+	if (!ublk_rq_has_data(req))
+		goto exit;
+
+	rq_for_each_bvec(bv, req, rq_iter)
+		nr_bvecs++;
+
+	if (!nr_bvecs)
+		goto exit;
+
+	if (req->bio != req->biotail) {
+		int idx = 0;
+
+		bvec = kvmalloc_array(nr_bvecs, sizeof(struct bio_vec),
+				GFP_NOIO);
+		if (!bvec)
+			return -ENOMEM;
+
+		offset = 0;
+		rq_for_each_bvec(bv, req, rq_iter)
+			bvec[idx++] = bv;
+		data->allocated_bvec = true;
+	} else {
+		struct bio *bio = req->bio;
+
+		offset = bio->bi_iter.bi_bvec_done;
+		bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
+	}
+	imu->bvec = bvec;
+	imu->nr_bvecs = nr_bvecs;
+	imu->offset = offset;
+	imu->len = blk_rq_bytes(req);
+	imu->dir = req_op(req) == REQ_OP_READ ? ITER_DEST : ITER_SOURCE;
+	imu->grp_kbuf_ack = ublk_io_buf_giveback_cb;
+
+	return 0;
+exit:
+	imu->bvec = NULL;
+	return 0;
+}
+
+static void ublk_deinit_zero_copy_buffer(struct request *req)
+{
+	struct ublk_rq_data *data = blk_mq_rq_to_pdu(req);
+	struct io_uring_kernel_buf *imu = data->buf;
+
+	if (data->allocated_bvec) {
+		kvfree(imu->bvec);
+		data->allocated_bvec = false;
+	}
+}
+
 static inline bool ublk_need_map_req(const struct request *req)
 {
 	return ublk_rq_has_data(req) && req_op(req) == REQ_OP_WRITE;
@@ -839,13 +915,25 @@ static inline bool ublk_need_unmap_req(const struct request *req)
 	       (req_op(req) == REQ_OP_READ || req_op(req) == REQ_OP_DRV_IN);
 }
 
-static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
+static int ublk_map_io(const struct ublk_queue *ubq, struct request *req,
 		struct ublk_io *io)
 {
 	const unsigned int rq_bytes = blk_rq_bytes(req);
 
-	if (ublk_support_user_copy(ubq))
+	if (ublk_support_user_copy(ubq)) {
+		if (ublk_support_zc(ubq)) {
+			int ret = ublk_init_zero_copy_buffer(req);
+
+			/*
+			 * The only failure is -ENOMEM for allocating providing
+			 * buffer command, return zero so that we can requeue
+			 * this req.
+			 */
+			if (unlikely(ret))
+				return 0;
+		}
 		return rq_bytes;
+	}
 
 	/*
 	 * no zero copy, we delay copy WRITE request data into ublksrv
@@ -863,13 +951,16 @@ static int ublk_map_io(const struct ublk_queue *ubq, const struct request *req,
 }
 
 static int ublk_unmap_io(const struct ublk_queue *ubq,
-		const struct request *req,
+		struct request *req,
 		struct ublk_io *io)
 {
 	const unsigned int rq_bytes = blk_rq_bytes(req);
 
-	if (ublk_support_user_copy(ubq))
+	if (ublk_support_user_copy(ubq)) {
+		if (ublk_support_zc(ubq))
+			ublk_deinit_zero_copy_buffer(req);
 		return rq_bytes;
+	}
 
 	if (ublk_need_unmap_req(req)) {
 		struct iov_iter iter;
@@ -1015,6 +1106,7 @@ static inline void __ublk_complete_rq(struct request *req)
 
 	return;
 exit:
+	ublk_deinit_zero_copy_buffer(req);
 	blk_mq_end_request(req, res);
 }
 
@@ -1657,6 +1749,45 @@ static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
 }
 
+static void ublk_io_buf_giveback_cb(const struct io_uring_kernel_buf *buf)
+{
+	struct ublk_rq_data *data = container_of(buf, struct ublk_rq_data, buf[0]);
+	struct request *req = blk_mq_rq_from_pdu(data);
+	struct ublk_queue *ubq = req->mq_hctx->driver_data;
+
+	ublk_put_req_ref(ubq, req);
+}
+
+static int ublk_provide_io_buf(struct io_uring_cmd *cmd,
+		struct ublk_queue *ubq, int tag)
+{
+	struct ublk_device *ub = cmd->file->private_data;
+	struct ublk_rq_data *data;
+	struct request *req;
+
+	if (!ub)
+		return -EPERM;
+
+	req = __ublk_check_and_get_req(ub, ubq, tag, 0);
+	if (!req)
+		return -EINVAL;
+
+	pr_devel("%s: qid %d tag %u request bytes %u\n",
+			__func__, tag, ubq->q_id, blk_rq_bytes(req));
+
+	data = blk_mq_rq_to_pdu(req);
+
+	/*
+	 * io_uring guarantees that the callback will be called after
+	 * the provided buffer is consumed, and it is automatic removal
+	 * before this uring command is freed.
+	 *
+	 * This request won't be completed unless the callback is called,
+	 * so ublk module won't be unloaded too.
+	 */
+	return io_uring_cmd_provide_kbuf(cmd, data->buf);
+}
+
 static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
 			       unsigned int issue_flags,
 			       const struct ublksrv_io_cmd *ub_cmd)
@@ -1673,6 +1804,10 @@ static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
 			__func__, cmd->cmd_op, ub_cmd->q_id, tag,
 			ub_cmd->result);
 
+	if ((cmd->flags & IORING_PROVIDE_GROUP_KBUF) &&
+			cmd_op != UBLK_U_IO_PROVIDE_IO_BUF)
+		return -EOPNOTSUPP;
+
 	if (ub_cmd->q_id >= ub->dev_info.nr_hw_queues)
 		goto out;
 
@@ -1708,6 +1843,8 @@ static int __ublk_ch_uring_cmd(struct io_uring_cmd *cmd,
 
 	ret = -EINVAL;
 	switch (_IOC_NR(cmd_op)) {
+	case _IOC_NR(UBLK_U_IO_PROVIDE_IO_BUF):
+		return ublk_provide_io_buf(cmd, ubq, tag);
 	case UBLK_IO_FETCH_REQ:
 		/* UBLK_IO_FETCH_REQ is only allowed before queue is setup */
 		if (ublk_queue_ready(ubq)) {
@@ -2127,11 +2264,14 @@ static void ublk_align_max_io_size(struct ublk_device *ub)
 
 static int ublk_add_tag_set(struct ublk_device *ub)
 {
+	int zc = !!(ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY);
+	struct ublk_rq_data *data;
+
 	ub->tag_set.ops = &ublk_mq_ops;
 	ub->tag_set.nr_hw_queues = ub->dev_info.nr_hw_queues;
 	ub->tag_set.queue_depth = ub->dev_info.queue_depth;
 	ub->tag_set.numa_node = NUMA_NO_NODE;
-	ub->tag_set.cmd_size = sizeof(struct ublk_rq_data);
+	ub->tag_set.cmd_size = struct_size(data, buf, zc);
 	ub->tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
 	ub->tag_set.driver_data = ub;
 	return blk_mq_alloc_tag_set(&ub->tag_set);
@@ -2418,8 +2558,12 @@ static int ublk_ctrl_add_dev(struct io_uring_cmd *cmd)
 		goto out_free_dev_number;
 	}
 
-	/* We are not ready to support zero copy */
-	ub->dev_info.flags &= ~UBLK_F_SUPPORT_ZERO_COPY;
+	/* zero copy depends on user copy */
+	if ((ub->dev_info.flags & UBLK_F_SUPPORT_ZERO_COPY) &&
+			!ublk_dev_is_user_copy(ub)) {
+		ret = -EINVAL;
+		goto out_free_dev_number;
+	}
 
 	ub->dev_info.nr_hw_queues = min_t(unsigned int,
 			ub->dev_info.nr_hw_queues, nr_cpu_ids);
include/uapi/linux/ublk_cmd.h +3 -4
index c8dc5f8ea699..897ace0794c2 100644
@@ -94,6 +94,8 @@
 	_IOWR('u', UBLK_IO_COMMIT_AND_FETCH_REQ, struct ublksrv_io_cmd)
 #define	UBLK_U_IO_NEED_GET_DATA		\
 	_IOWR('u', UBLK_IO_NEED_GET_DATA, struct ublksrv_io_cmd)
+#define	UBLK_U_IO_PROVIDE_IO_BUF	\
+	_IOWR('u', 0x23, struct ublksrv_io_cmd)
 
 /* only ABORT means that no re-fetch */
 #define UBLK_IO_RES_OK			0
@@ -126,10 +128,7 @@
 #define UBLKSRV_IO_BUF_TOTAL_BITS	(UBLK_QID_OFF + UBLK_QID_BITS)
 #define UBLKSRV_IO_BUF_TOTAL_SIZE	(1ULL << UBLKSRV_IO_BUF_TOTAL_BITS)
 
-/*
- * zero copy requires 4k block size, and can remap ublk driver's io
- * request into ublksrv's vm space
- */
+/* io_uring provide kbuf command based zero copy */
 #define UBLK_F_SUPPORT_ZERO_COPY	(1ULL << 0)
 
 /*
Signature · 1 line
2.42.0
author
#18 lore raw
In reply to Ming Lei
Quoted 50 lines · Ming Lei

Hello,

The 1st 3 patches are cleanup, and prepare for adding sqe group.

The 4th patch supports generic sqe group which is like link chain, but allows each sqe in group to be issued in parallel and the group shares same IO_LINK & IO_DRAIN boundary, so N:M dependency can be supported with sqe group & io link together. sqe group changes nothing on IOSQE_IO_LINK.

The 5th patch supports one variant of sqe group: allow members to depend on group leader, so that kernel resource lifetime can be aligned with group leader or group, then any kernel resource can be shared in this sqe group, and can be used in generic device zero copy.

The 6th & 7th patches supports providing sqe group buffer via the sqe group variant.

The 8th patch supports ublk zero copy based on io_uring providing sqe group buffer.

Tests:

1) pass liburing test
- make runtests

2) write/pass two sqe group test cases:

https://github.com/axboe/liburing/compare/master...ming1:liburing:sqe_group_v2

- covers related sqe flags combination and linking groups, both nop and one multi-destination file copy.

- cover failure handling test: fail leader IO or member IO in both single group and linked groups, which is done in each sqe flags combination test

3) ublksrv zero copy:

ublksrv userspace implements zero copy by sqe group & provide group kbuf:

	git clone https://github.com/ublk-org/ublksrv.git -b group-provide-buf_v2
	make test T=loop/009:nbd/061	#ublk zc tests

When running 64KB/512KB block size test on ublk-loop('ublk add -t loop --buffered_io -f $backing'), it is observed that perf is doubled.

Any comments are welcome!

Quoted 14 lines

V4:
- address most comments from Pavel
- fix request double free
- don't use io_req_commit_cqe() in io_req_complete_defer()
- make members' REQ_F_INFLIGHT discoverable
- use common assembling check in submission code path
- drop patch 3 and don't move REQ_F_CQE_SKIP out of io_free_req()
- don't set .accept_group_kbuf for net send zc, in which members need to be queued after buffer notification is got, and can be enabled in future
- add .grp_leader field via union, and share storage with .grp_link
- move .grp_refs into one hole of io_kiocb, so that one extra cacheline isn't needed for io_kiocb
- cleanup & document improvement

Hello Pavel, Jens and Guys,

Gentle ping...

thanks,
Ming

#19 lore raw
Quoted 7 lines · Ming Lei
Quoted 2 lines · Ming Lei

Hello,
...

Hello Pavel, Jens and Guys,

Gentle ping...

Hi Ming,

I'm currently away, will give it a look when I'm back next week.

Signature · 1 line
Pavel Begunkov