Skip to contentSkip to conversation

io_uring: opaque TCP payload objects

RFC PATCH New Alex Markuze 2 participants 18 messages Nov 10 – Nov 11

Subsystems (7)
Networking Network drivers BPF TCP +3 more subsystems
lore
Share & tools
lore
#0 lore raw

cover io_uring: opaque TCP payload objects

A proxy, cache or key-value store often does not read the payload. It parses a header, decides, and forwards the body or keeps it to serve again. The body should stay in the kernel. The application needs a handle, not a mapping.

Sharing pages with the application does not give it that. MSG_ZEROCOPY and SEND_ZC pin the application's buffer. TCP_ZEROCOPY_RECEIVE and io_uring zcrx map receive pages into the application, and zcrx also wants a header/data split and a queue steered to one ring. splice() and sendfile() ask nothing of the NIC, but a pipe only carries bytes in order, and a file holds them only after a copy into the page cache. There is nothing to retain and send again.

This series keeps the payload in the kernel and names it. Nothing is mapped. Capture uses the socket's receive queue through tcp_read_sock(), after the stack, on whatever pages the driver used. A fragment nothing else shares is kept by reference. The rest is copied into pages the store owns. The NIC is not asked for a split, a provider, a queue or flow steering. The same path runs on any driver that delivers TCP to the socket.

A send takes page references through MSG_SPLICE_PAGES. There is no pin per send, no registered buffer, and no range the application must leave unchanged until a completion. The object is the received data, so the body is not copied into an application buffer before it is forwarded, retained or served to another client.

The net change
==============

recv(), splice() and tcp_zerocopy_receive() are the reader. They consume the sequence as they go. They never hand the application a stable offset over a queue that some other reader can still drain, so TCP had nothing to protect.

The collector does. RECV_OBJECT and DISCARD name ranges counted from the first unread byte at attach. If recv() or splice() takes bytes in the meantime, those offsets no longer point at the same data, and the application keeps or drops the wrong range. Patch 1 puts one receive owner on the socket. While the collector holds it, the other readers return -EBUSY.

The option is hidden and selected by this feature. With it off, struct sock and those paths are unchanged. Patch 1 has no other user.

Interface
=========

IORING_REGISTER_OPAQUE_STORE creates a store with a memory budget. Rings share it through a descriptor. IORING_OP_OPAQUE_COLLECT attaches a connected TCP socket. Bytes the application has not decided about stop the collector, so TCP flow control applies. Between passes the collector waits on io_uring's own multishot poll. There is no second polling mechanism and no new poll event for userspace.

IORING_OP_OPAQUE_OBJ carries the object operations. INSPECT copies out the header bytes the application has to parse. RECV_OBJECT turns a range of the stream into an object and returns its handle. DISCARD drops a range. READ_OBJECT copies bytes out when they are needed after all, and FREE releases the handle. CREATE copies application memory into an object, for a value that is served many times rather than received.

IORING_OP_OPAQUE_OBJ_SEND sends one range, or a vector of up to 1024, with a prefix and a suffix from application memory. An object can be sent any number of times and on any socket. SEND_LAST gives it up with the send. Sends through one store to one socket are ordered by enqueue under the store's TX lock at first issue, not by SQE submission across rings.

Backing is bounded per store, accounted like registered buffers and charged to the memory cgroup of the task that created the store.

Measurements
============

These numbers are from development kernels (7.3-rc6 based), not from the patches as posted. This series is a first-interface cut of that work and has not been benchmarked itself. Those kernels also carried an earlier skb_splice_from_iter() change, which made object sends 24% cheaper at 64 KiB and 14% at 256 KiB. This series applies and works without it.

The runs used virtio-net VMs with 32 vCPUs, one TCP flow and NIC interrupts pinned. That is where the numbers were taken, not a limit of the interface. CPU is the whole host's, total minus idle, per GB delivered. Full speed is unpaced: from 4 KiB every sender, and every receiver, moves what the path allows, so the comparison is CPU.

At full speed with 64 KiB writes, capturing the stream as objects costs the receiving host 31% less CPU than recv(), and DISCARD 57% less. In the runs where the path gave the flow 16 Gbit/s instead of 22, those figures were 15% and 53%. Paced, capture and recv() are within 21% of each other, in either direction. Receive at full speed was measured at 64 KiB only.

On send, from 16 KiB an object costs what SEND_ZC costs without its pin. Sender CPU at full speed, one object or one buffer per request. Objects against SEND_ZC that pins on every send:

   4 KiB   -15%
  16 KiB   -22%
  64 KiB   -24%
 256 KiB   -22%
   1 MiB   -27%

The pin itself, SEND_ZC pinning per send against SEND_ZC with a registered buffer:

   4 KiB   +90%
  16 KiB   +25%
  64 KiB   +22%
 256 KiB   +17%
   1 MiB   +33%

The pin costs SEND_ZC 49-106 ns per 4 KiB page from 16 KiB to 1 MiB, so it grows with the buffer, and 0.70 microseconds per send at 4 KiB. Against a registered buffer, which is pinned once, objects are level from 16 KiB (-21% to +4%, eight ranges per request on both sides). Small sends are where a registered buffer stays ahead: by 6-12% at 1 and 4 KiB with eight ranges per request, and by more at 4 KiB with one. Objects cost 40-57% less than copying send() from 16 KiB, and 12-48% less than MSG_ZEROCOPY from 1 KiB to 1 MiB.

The SEND_ZC senders resend one page-aligned buffer and set MSG_EOR every 1 MiB to bound their notification chains.

The series
==========

Patch 1 is the receive claim above. Patches 2-6 add the store, its accounting and sharing between rings. Patch 7 adds the send and patch 8 its vectored form: at full speed, eight ranges per request make 1 KiB sends 3.6 times cheaper. Patch 9 adds the collector, 10 CREATE, and 11 compaction, which copies an object out of sparsely used receive pages into dense backing under the same handle. Patch 12 adds two KUnit cases for budget admission and version release.

Registering a store needs DEFER_TASKRUN and CQE32 or CQE_MIXED. Userspace helpers are not in this posting. A mapped mode, for applications that do read the payload, is not in this RFC. Neither is the later send-path work that takes one reference per folio instead of one per fragment. The separate skb_splice_from_iter() series, which builds one fragment per folio for every MSG_SPLICE_PAGES user, makes sendfile() from 64 KiB folios 11% cheaper. This series does not depend on it.

Testing
=======

Two KUnit cases passed on UML, with no skips. They check budget admission and release of a page-backed version. A loopback program against this kernel captured one payload, sent the handle twice with framing, checked SEND_LAST, and left the store empty. The kernel build used W=1 and WERROR=y.

This is smoke coverage, not a pressure or scheduling-race campaign. io-wq fallback, native SMP callback lifetimes and runtime memcg isolation are not covered. The numbers above are not a benchmark of this series.

Known limits
============

- Receive authorization is checked when the collector attaches and covers its lifetime; later policy changes do not revoke it.
- If poll setup fails for lack of memory, collection ends and the undecided data is dropped.
- Table sizes (objects, streams, extents) are fixed at registration.
- An object holds the receive pages its bytes arrived in, which can be much more memory than its payload until it is compacted.
- A large CREATE copies under the ring lock.

Feedback wanted
===============

- The receive claim: is an owner in struct sock the right way to make a socket's receive side exclusive to one consumer?
- One opcode with the operation in sqe->ioprio (OPAQUE_OBJ), against an opcode per operation.
- Reporting the transfer of ownership in the extended CQE (CONSUMED).
- Whether this is the right first scope.

Thanks,
Alex Markuze

Alex Markuze (12):
net: add an exclusive TCP receive claim io_uring/opaque: add data structures and the UAPI header io_uring/opaque: add backing accounting and immutable versions io_uring/opaque: add owned-page helpers for dense copies io_uring/opaque: add store registration and IORING_OP_OPAQUE_OBJ io_uring/opaque: allow rings to share a store io_uring/opaque: add IORING_OP_OPAQUE_OBJ_SEND io_uring/opaque: add vectored IORING_OP_OPAQUE_OBJ_SEND io_uring/opaque: add IORING_OP_OPAQUE_COLLECT io_uring/opaque: add IORING_OPAQUE_CREATE io_uring/opaque: add manual and automatic compaction io_uring/opaque: add basic KUnit tests

 include/linux/io_uring_types.h       |   10 +
 include/linux/net.h                  |    8 +
 include/linux/poll.h                 |    3 +
 include/net/sock.h                   |   46 +
 include/uapi/linux/io_uring.h        |   10 +
 include/uapi/linux/io_uring/opaque.h |  145 ++
 io_uring/Kconfig                     |   21 +
 io_uring/Makefile                    |    2 +
 io_uring/cancel.c                    |    5 +
 io_uring/io_uring.c                  |    9 +
 io_uring/opaque.c                    | 3926 ++++++++++++++++++++++++++++++++++
 io_uring/opaque.h                    |  167 ++
 io_uring/opaque_compact.c            |  425 ++++
 io_uring/opaque_internal.h           |  295 +++
 io_uring/opaque_register.c           |  152 ++
 io_uring/opaque_test.c               |  128 ++
 io_uring/opdef.c                     |   55 +
 io_uring/poll.c                      |   58 +-
 io_uring/register.c                  |    7 +
 net/Kconfig                          |    7 +
 net/core/skmsg.c                     |    4 +
 net/core/sock.c                      |    6 +-
 net/ipv4/af_inet.c                   |    2 +
 net/ipv4/tcp.c                       |   22 +-
 net/ipv4/tcp_input.c                 |    1 +
 net/ipv4/tcp_ulp.c                   |    2 +
 26 files changed, 5512 insertions(+), 4 deletions(-)

base-commit: 4dd16e31135ea8437a720222df34e8745f385d6d

#1 lore raw

RFC PATCH 1/12 net: add an exclusive TCP receive claim

The io_uring opaque object collector, added later in this series, consumes the receive queue of a TCP socket through tcp_read_sock() with its own actor. It reports stream offsets that count from the first byte that was unread when it attached. If another reader consumes bytes while the collector is attached, those offsets no longer match the data, and the application selects the wrong ranges.

Add a receive owner to struct sock: a pointer to a struct sock_rx_owner that names a tcp_read_sock() actor and its data. The owner is published and cleared under the socket lock and sk_callback_lock. While an owner is set:

- tcp_read_sock() and tcp_read_sock_noack() return -EBUSY unless the caller passes the owning actor and data. This also stops splice().
- tcp_recvmsg_locked(), tcp_zerocopy_receive() and tcp_read_skb() return -EBUSY.
- sk_wait_data() also returns when an owner appears. A reader that sleeps in tcp_recvmsg_locked() then stops with the bytes that it copied, or with -EBUSY. The claimant wakes sleeping readers after it publishes the owner.
- tcp_disconnect(), connect(AF_UNSPEC), tcp_set_ulp(), sk_psock_init() and TCP_REPAIR return -EBUSY, because each of them resets or takes over the receive sequence. TCP_REPAIR checks the owner before its permission check, so a caller without the permission also gets -EBUSY.
- sk_clone() starts the child socket without an owner.

CONFIG_SOCK_RX_OWNER is a hidden option that the io_uring feature selects. Without it, struct sock does not change and the checks compile away. With it, struct sock grows by one pointer. Each affected receive path reads the pointer once with READ_ONCE(), and tcp_recvmsg_locked() reads it once per loop iteration.

An optional data_ready callback notifies the owner independently of ordinary TCP low-water readiness. TCP invokes it under the read side of sk_callback_lock, which pins the owner and its data; the callback must not sleep. With receive ownership disabled, the helper is empty.

This patch adds no user of the claim or callback.

---
 include/linux/net.h  |  8 ++++++++
 include/net/sock.h   | 46 ++++++++++++++++++++++++++++++++++++++++++++
 net/Kconfig          |  7 +++++++
 net/core/skmsg.c     |  4 ++++
 net/core/sock.c      |  6 +++++-
 net/ipv4/af_inet.c   |  2 ++
 net/ipv4/tcp.c       | 22 ++++++++++++++++++++-
 net/ipv4/tcp_input.c |  1 +
 net/ipv4/tcp_ulp.c   |  2 ++
 9 files changed, 96 insertions(+), 2 deletions(-)
include/linux/net.h +8 -0
index e2a866fbcfa5..d8fe1812e02b 100644
@@ -230,6 +230,14 @@ struct sk_buff;
 struct proto_accept_arg;
 typedef int (*sk_read_actor_t)(read_descriptor_t *, struct sk_buff *,
 			       unsigned int, size_t);
+
+/* Published under socket and callback locks; controls the receive sequence. */
+struct sock_rx_owner {
+	sk_read_actor_t actor;
+	void *data;
+	/* TCP receive context, under sk_callback_lock: must not sleep. */
+	void (*data_ready)(struct sock *sk, void *data);
+};
 typedef int (*skb_read_actor_t)(struct sock *, struct sk_buff *);
 
 
include/net/sock.h +46 -0

64 lines not on this page · raw message

net/Kconfig +7 -0
index 76ab44aa439a..6ece51ab26ba 100644
@@ -26,6 +26,13 @@ menuconfig NET
 
 if NET
 
+config SOCK_RX_OWNER
+	bool
+	depends on INET
+	help
+	  Allow a TCP stream actor to claim exclusive receive sequence access.
+	  Receive paths reject competing readers while the claim is held.
+
 config WANT_COMPAT_NETLINK_MESSAGES
 	bool
 	help
net/core/skmsg.c +4 -0
index df385a5a961e..5c753bcb808c 100644
@@ -754,6 +754,10 @@ struct sk_psock *sk_psock_init(struct sock *sk, int node)
 
 	write_lock_bh(&sk->sk_callback_lock);
 
+	if (sock_rx_owned(sk)) {
+		psock = ERR_PTR(-EBUSY);
+		goto out;
+	}
 	if (sk_is_inet(sk) && inet_csk_has_ulp(sk)) {
 		psock = ERR_PTR(-EINVAL);
 		goto out;
net/core/sock.c +5 -1
index e7405be8941f..3fcdc56e624e 100644
@@ -2614,6 +2614,9 @@ struct sock *sk_clone(const struct sock *sk, const gfp_t priority,
 	 */
 	if (sk_user_data_is_nocopy(newsk))
 		newsk->sk_user_data = NULL;
+#ifdef CONFIG_SOCK_RX_OWNER
+	newsk->sk_rx_owner = NULL;
+#endif
 
 	newsk->sk_err	   = 0;
 	newsk->sk_err_soft = 0;
@@ -3389,7 +3392,8 @@ int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
 
 	add_wait_queue(sk_sleep(sk), &wait);
 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
-	rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
+	rc = sk_wait_event(sk, timeo, sock_rx_owned(sk) ||
+			   skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
 	remove_wait_queue(sk_sleep(sk), &wait);
 	return rc;
net/ipv4/af_inet.c +2 -0
index 7677b0343abd..54c30a59bbce 100644
@@ -649,6 +649,8 @@ int __inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr,
 			return -EINVAL;
 
 		if (uaddr->sa_family == AF_UNSPEC) {
+			if (sock_rx_owned(sk))
+				return -EBUSY;
 			sk->sk_disconnects++;
 			err = sk->sk_prot->disconnect(sk, flags);
 			sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
net/ipv4/tcp.c +21 -1
index b9de7c302ba8..6de6ce153fda 100644
@@ -1753,6 +1753,8 @@ out:
 int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
 		  sk_read_actor_t recv_actor)
 {
+	if (sock_rx_owner_conflict(sk, desc, recv_actor))
+		return -EBUSY;
 	return __tcp_read_sock(sk, desc, recv_actor, false,
 			       &tcp_sk(sk)->copied_seq);
 }
@@ -1762,6 +1764,8 @@ int tcp_read_sock_noack(struct sock *sk, read_descriptor_t *desc,
 			sk_read_actor_t recv_actor, bool noack,
 			u32 *copied_seq)
 {
+	if (sock_rx_owner_conflict(sk, desc, recv_actor))
+		return -EBUSY;
 	return __tcp_read_sock(sk, desc, recv_actor, noack, copied_seq);
 }
 
@@ -1770,6 +1774,8 @@ int tcp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
 	struct sk_buff *skb;
 	int copied = 0;
 
+	if (sock_rx_owned(sk))
+		return -EBUSY;
 	if (sk->sk_state == TCP_LISTEN)
 		return -ENOTCONN;
 
@@ -2224,6 +2230,8 @@ static int tcp_zerocopy_receive(struct sock *sk,
 
 	zc->copybuf_len = 0;
 	zc->msg_flags = 0;
+	if (sock_rx_owned(sk))
+		return -EBUSY;
 
 	if (address & (PAGE_SIZE - 1) || address != zc->address)
 		return -EINVAL;
@@ -2678,6 +2686,8 @@ static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
 	u32 peek_offset = 0;
 	u32 urg_hole = 0;
 
+	if (sock_rx_owned(sk))
+		return -EBUSY;
 	err = -ENOTCONN;
 	if (sk->sk_state == TCP_LISTEN)
 		goto out;
@@ -2717,6 +2727,11 @@ static int tcp_recvmsg_locked(struct sock *sk, struct msghdr *msg, size_t len,
 	do {
 		u32 offset;
 
+		/* Ownership may have changed while this reader slept for data. */
+		if (sock_rx_owned(sk)) {
+			copied = copied ?: -EBUSY;
+			break;
+		}
 		/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
 		if (unlikely(tp->urg_data) && tp->urg_seq == *seq) {
 			if (copied)
@@ -3374,6 +3389,9 @@ int tcp_disconnect(struct sock *sk, int flags)
 	struct request_sock *req;
 	u32 seq;
 
+	if (sock_rx_owned(sk))
+		return -EBUSY;
+
 	if (old_state != TCP_CLOSE)
 		tcp_set_state(sk, TCP_CLOSE);
 
@@ -3988,7 +4006,9 @@ int do_tcp_setsockopt(struct sock *sk, int level, int optname,
 		break;
 
 	case TCP_REPAIR:
-		if (!tcp_can_repair_sock(sk))
+		if (sock_rx_owned(sk))
+			err = -EBUSY;
+		else if (!tcp_can_repair_sock(sk))
 			err = -EPERM;
 		else if (val == TCP_REPAIR_ON) {
 			tp->repair = 1;
net/ipv4/tcp_input.c +1 -0
index e1f2d9765f81..2d17fcdf73dd 100644
@@ -5637,6 +5637,7 @@ err:
 
 void tcp_data_ready(struct sock *sk)
 {
+	sock_rx_owner_data_ready(sk);
 	if (tcp_epollin_ready(sk, sk->sk_rcvlowat) || sock_flag(sk, SOCK_DONE))
 		READ_ONCE(sk->sk_data_ready)(sk);
 }
net/ipv4/tcp_ulp.c +2 -0
index b58045df101e..77abc21bcb63 100644
@@ -164,6 +164,8 @@ int tcp_set_ulp(struct sock *sk, const char *name)
 
 	sock_owned_by_me(sk);
 
+	if (sock_rx_owned(sk))
+		return -EBUSY;
 	ulp_ops = __tcp_ulp_find_autoload(name);
 	if (!ulp_ops)
 		return -ENOENT;

base-commit: 4dd16e31135ea8437a720222df34e8745f385d6d

Signature · 1 line
2.34.1
#2 lore raw

Re: [RFC PATCH net-next 01/12] net: add an exclusive TCP receive claim

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] tcp: returning -EBUSY in tcp_disconnect() breaks internal callers - [Medium] net: missing…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] tcp: returning -EBUSY in tcp_disconnect() breaks internal callers
- [Medium] net: missing sock_rx_owned() checks in kcm_attach() and ovpn_tcp_socket_attach()
--

commit db5306ce28288ea69fe78b0895ec7be46b42bf0b
Author: Alex Markuze <[email protected]>

net: add an exclusive TCP receive claim

This commit adds an optional sk_rx_owner pointer to struct sock so a tcp_read_sock() consumer can claim exclusive access to a TCP socket's receive sequence and reject competing readers or operations that reset the receive stream.

Quoted 5 lines
net/core/skmsg.c +0 -0
index df385a5a961e8..5c753bcb808c5 100644

net/core/skmsg.c struct sk_psock *sk_psock_init(struct sock *sk, int node) · line 763

Quoted 10 lines
net/core/skmsg.c +4 -0
@@ -754,6 +754,10 @@ struct sk_psock *sk_psock_init(struct sock *sk, int node)
 
 	write_lock_bh(&sk->sk_callback_lock);
 
+	if (sock_rx_owned(sk)) {
+		psock = ERR_PTR(-EBUSY);
+		goto out;
+	}
 	if (sk_is_inet(sk) && inet_csk_has_ulp(sk)) {
 		psock = ERR_PTR(-EINVAL);
 		goto out;

[Severity: Medium]
Should kcm_attach() and ovpn_tcp_socket_attach() also check sock_rx_owned()?

Like sk_psock_init(), both attach to a TCP socket by checking only sk->sk_user_data, which remains NULL when sk_rx_owner is set. Attaching via kcm_attach() installs a strparser and replaces sk->sk_state_change with psock_state_change(), which sets sk->sk_err = EPIPE on a normal peer FIN and causes the receive owner to fail with -EPIPE instead of clean EOF. Attaching via ovpn_tcp_socket_attach() replaces sk->sk_prot and sk->sk_socket->ops with ovpn_tcp_recvmsg(), bypassing the sock_rx_owned() checks.

Quoted 17 lines
net/ipv4/af_inet.c +2 -0
index 7677b0343abd4..54c30a59bbce4 100644
@@ -649,6 +649,8 @@ int __inet_stream_connect(struct socket *sock, struct sockaddr_unsized *uaddr,
 			return -EINVAL;
 
 		if (uaddr->sa_family == AF_UNSPEC) {
+			if (sock_rx_owned(sk))
+				return -EBUSY;
 			sk->sk_disconnects++;
 			err = sk->sk_prot->disconnect(sk, flags);
 			sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
net/ipv4/tcp.c +0 -0
index b9de7c302ba83..6de6ce153fda1 100644

[ ... ]

net/ipv4/tcp.c int tcp_disconnect(struct sock *sk, int flags) · line 3397

Quoted 10 lines
net/ipv4/tcp.c +3 -0
@@ -3374,6 +3389,9 @@ int tcp_disconnect(struct sock *sk, int flags)
 	struct request_sock *req;
 	u32 seq;
 
+	if (sock_rx_owned(sk))
+		return -EBUSY;
+
 	if (old_state != TCP_CLOSE)
 		tcp_set_state(sk, TCP_CLOSE);
 

[Severity: Medium]
Does returning -EBUSY from tcp_disconnect() break internal callers of sk->sk_prot->disconnect()?

__inet_stream_connect() already rejects connect(AF_UNSPEC) above before calling sk->sk_prot->disconnect(). Other callers expect tcp_disconnect() to succeed unconditionally:

net/ipv4/af_inet.c:__inet_stream_connect() {
    ...
sock_error:
	err = sock_error(sk) ? : -ECONNABORTED;
	sock->state = SS_UNCONNECTED;
	sk->sk_disconnects++;
	if (sk->sk_prot->disconnect(sk, flags))
		sock->state = SS_DISCONNECTING;
	goto out;
}

When a socket connects via non-blocking connect(), sock->state stays SS_CONNECTING after the handshake reaches TCP_ESTABLISHED. If a receive owner is attached and the connection is then closed by a peer RST or timeout (moving sk->sk_state to TCP_CLOSE while sk_rx_owner is still set), a subsequent connect() jumps to sock_error:, where disconnect() returns -EBUSY without cleaning up the socket and leaves sock->state permanently wedged in SS_DISCONNECTING even after the owner detaches.

__tcp_close() also ignores the return value of sk->sk_prot->disconnect(sk,
0) on a zero-linger close and assumes it moves sk->sk_state to TCP_CLOSE.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

RFC PATCH 2/12 io_uring/opaque: add data structures and the UAPI header

In reply to Alex Markuze

Define immutable versions, backing extents, stores and request state. TX queues record FIFO positions ordered by enqueue under the store's TX lock, including positions with reference acquisition still pending, and carry a busy socket identity pin.

---
 include/linux/io_uring_types.h       |  10 +
 include/uapi/linux/io_uring/opaque.h | 126 +++++++++++++
 io_uring/opaque.h                    | 155 +++++++++++++++
 io_uring/opaque_internal.h           | 269 +++++++++++++++++++++++++++
 4 files changed, 560 insertions(+)
 create mode 100644 include/uapi/linux/io_uring/opaque.h
 create mode 100644 io_uring/opaque.h
 create mode 100644 io_uring/opaque_internal.h
include/linux/io_uring_types.h +10 -0
index 9140c21ca819..198c6bdb3e2c 100644
@@ -412,6 +412,9 @@ struct io_ring_ctx {
 		struct io_alloc_cache	netmsg_cache;
 		struct io_alloc_cache	rw_cache;
 		struct io_alloc_cache	cmd_cache;
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		struct io_alloc_cache	opaque_cache;
+#endif
 
 		int (*loop_step)(struct iou_ctx *,
 				 struct iou_loop_params *);
@@ -421,6 +424,9 @@ struct io_ring_ctx {
 		 * ->uring_cmd() by io_uring_cmd_insert_cancelable()
 		 */
 		struct hlist_head	cancelable_uring_cmd;
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		struct list_head	opaque_waits;
+#endif
 		/*
 		 * For Hybrid IOPOLL, runtime in hybrid polling, without
 		 * scheduling time
@@ -491,6 +497,10 @@ struct io_ring_ctx {
 
 	/* Stores zcrx object pointers of type struct io_zcrx_ifq */
 	struct xarray			zcrx_ctxs;
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+	struct xarray			opaque_stores;
+	bool				opaque_stores_dying;
+#endif
 
 	/* Used for accounting references on pages in registered buffers */
 	struct xarray		hpage_acct;
include/uapi/linux/io_uring/opaque.h new file +126 -0

126 lines not on this page · raw message

io_uring/opaque.h new file +155 -0

155 lines not on this page · raw message

io_uring/opaque_internal.h new file +269 -0

269 lines not on this page · raw message

Signature · 1 line
2.34.1
#4 lore raw

RFC PATCH 3/12 io_uring/opaque: add backing accounting and immutable versions

In reply to Alex Markuze

Add bounded backing-byte and extent accounting, immutable version references, vectors and generation handles. Separate ordinary capacity, reply reserve and transient reservations; update byte/transient pairs coherently for watermark hysteresis. Capacity returns precede batched collector wakes. The feature selects the exclusive receive-owner support.

---
 io_uring/Kconfig  |  11 ++
 io_uring/Makefile |   1 +
 io_uring/opaque.c | 399 ++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 411 insertions(+)
 create mode 100644 io_uring/opaque.c
io_uring/Kconfig +11 -0
index a283d9e53787..5b696cf266f6 100644
@@ -15,6 +15,17 @@ config IO_URING_BPF
 	depends on BPF
 	depends on NET
 
+config IO_URING_OPAQUE_OBJ
+	bool "io_uring opaque TCP payload objects"
+	default n
+	depends on IO_URING && INET
+	select SOCK_RX_OWNER
+	help
+	  Retain immutable TCP payloads as kernel-resident objects that can
+	  be inspected, transmitted and compacted through io_uring. No network
+	  device zerocopy support or mapped receive area is required.
+	  Applications manage payload lifetime through generation handles.
+
 config IO_URING_BPF_OPS
 	def_bool y
 	depends on IO_URING
io_uring/Makefile +1 -0
index 965bb60e9f7b..81710127046c 100644
@@ -17,6 +17,7 @@ obj-$(CONFIG_IO_URING)		+= io_uring.o opdef.o kbuf.o rsrc.o notif.o \
 					query.o loop.o
 
 obj-$(CONFIG_IO_URING_ZCRX)	+= zcrx.o
+obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o
 obj-$(CONFIG_IO_WQ)		+= io-wq.o
 obj-$(CONFIG_FUTEX)		+= futex.o
 obj-$(CONFIG_EPOLL)		+= epoll.o
io_uring/opaque.c new file +399 -0

399 lines not on this page · raw message

Signature · 1 line
2.34.1
#5 lore raw

Re: [RFC PATCH net-next 03/12] io_uring/opaque: add backing accounting and immutable versions

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] io_uring/opaque: wake batch limit bypassed in io_opaque_wake_budget() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] io_uring/opaque: wake batch limit bypassed in io_opaque_wake_budget()
--

commit 330c6e48123376b4807cfeaa9a7e897d4c81a279
Author: Alex Markuze <[email protected]>

io_uring/opaque: add backing accounting and immutable versions

This commit adds backing-byte and extent accounting, immutable payload version references, bvec/anchor vector building, and generation handle lookup for io_uring opaque TCP payload objects.

Quoted 6 lines
io_uring/opaque.c new file +0 -0
new file mode 100644
index 0000000000000..2fd9db898e672
@@ -0,0 +1,399 @@

[ ... ]

Quoted 19 lines
io_uring/opaque.c new file +19 -0
+static bool io_opaque_wake_budget(struct io_opaque_store *store)
+{
+	struct io_opaque_req *op, *next;
+	unsigned long delay = MAX_JIFFY_OFFSET;
+	unsigned long now = jiffies;
+	unsigned int woken = 0;
+	bool stopped, more = false;
+
+	guard(spinlock)(&store->wait_lock);
+	stopped = READ_ONCE(store->dead);
+	list_for_each_entry_safe(op, next, &store->budget_waits, wait) {
+		struct socket *sock = sock_from_file(op->req->file);
+
+		if (!stopped && !READ_ONCE(op->stream->closed)) {
+			if (time_before(now, op->retry_at)) {
+				delay = min(delay, op->retry_at - now);
+				continue;
+			}
+			if (!io_opaque_budget_ready(op, now))

io_uring/opaque.c line 71

Quoted 10 lines
io_uring/opaque.c new file +10 -0
+				continue;
+			if (woken == IO_OPAQUE_WAKE_BATCH) {
+				delay = 1;
+				more = true;
+				continue;
+			}
+		}
+		list_del_init(&op->wait);
+		/* A wake is not a reservation; the collector rechecks on entry. */
+		woken++;

[Severity: Medium]
Can a closed-stream entry bypass the IO_OPAQUE_WAKE_BATCH limit here?

Once woken reaches IO_OPAQUE_WAKE_BATCH, any later entry on store->budget_waits with op->stream->closed set skips the conditional block and increments woken to IO_OPAQUE_WAKE_BATCH + 1. For all subsequent open, budget-ready waiters on the list, woken == IO_OPAQUE_WAKE_BATCH is then false, so they are all woken under a single store->wait_lock hold instead of being deferred with woken >= IO_OPAQUE_WAKE_BATCH.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#6 lore raw

RFC PATCH 4/12 io_uring/opaque: add owned-page helpers for dense copies

In reply to Alex Markuze

Add the accounted destination-page allocator used by CREATE and compaction. Prefer compound allocations up to 64 KiB, or one base page when larger, and fall back to smaller orders.

---
 io_uring/Makefile         |  2 +-
 io_uring/opaque_compact.c | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 io_uring/opaque_compact.c
io_uring/Makefile +1 -1
index 81710127046c..191316972e04 100644
@@ -17,7 +17,7 @@ obj-$(CONFIG_IO_URING)		+= io_uring.o opdef.o kbuf.o rsrc.o notif.o \
 					query.o loop.o
 
 obj-$(CONFIG_IO_URING_ZCRX)	+= zcrx.o
-obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o
+obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o opaque_compact.o
 obj-$(CONFIG_IO_WQ)		+= io-wq.o
 obj-$(CONFIG_FUTEX)		+= futex.o
 obj-$(CONFIG_EPOLL)		+= epoll.o
io_uring/opaque_compact.c new file +33 -0
new file mode 100644
index 000000000000..b59c7cb95d42
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Workers copy immutable backing without holding object table locks. */
+#include <linux/highmem.h>
+#include <linux/memcontrol.h>
+#include <linux/mm.h>
+#include <linux/overflow.h>
+#include <linux/sched.h>
+#include <linux/sizes.h>
+#include <linux/slab.h>
+
+#include "io_uring.h"
+#include "opaque_internal.h"
+
+struct page *io_opaque_owned_page(unsigned int *order)
+{
+	struct page *page;
+
+	for (;;) {
+		page = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_COMP | __GFP_NORETRY |
+				   __GFP_NOWARN, *order);
+		if (page || !*order)
+			return page;
+		(*order)--;
+	}
+}
+
+/* Destination allocation for dense copies and CREATE. */
+struct page *io_opaque_dest_page(struct io_opaque_store *store, u64 pages_left,
+				 unsigned int *order)
+{
+	*order = min_t(unsigned int, IO_OPAQUE_MAX_ORDER, ilog2(pages_left));
+	return io_opaque_owned_page(order);
+}
Signature · 1 line
2.34.1
#7 lore raw

RFC PATCH 5/12 io_uring/opaque: add store registration and IORING_OP_OPAQUE_OBJ

In reply to Alex Markuze

Add IORING_REGISTER_OPAQUE_STORE and the object controls, together with their request and store lifetimes.

Registration requires DEFER_TASKRUN and either CQE32 or CQE_MIXED. The configuration supplies limits for backing bytes, object size, objects, streams and extents, with optional watermarks and a reply reserve. Creation accounts the hard byte limit against the ring's user and mm, as registered buffers do. The creating task's live memory cgroup owns the backing charges; the store retains that reference for its lifetime. Flags and reserved fields must be zero. An xarray assigns the ring-local store ID, removed if copying the registration result to userspace fails.

IORING_OP_OPAQUE_OBJ takes the control in sqe->ioprio, the store ID in sqe->opaque_store_id, a handle or stream token in sqe->addr, a byte offset in sqe->off, a length in sqe->len and a user pointer in sqe->addr3.

- INSPECT copies up to 64 KiB of retained stream bytes without consuming them, waiting if no byte is available at the requested offset.
- AVAILABLE returns the contiguous retained length without copying, stopping at the next pending receive or discard decision.
- RECV_OBJECT reserves a slot and assembles a declared stream range. Its completed CQE returns the length, handle and forwarding-only flag.
- DISCARD consumes a declared range without retaining an object.
- READ_OBJECT copies up to 64 KiB from a published object; FREE removes its handle without invalidating references already held by requests.
- STAT, OBJECT_STAT and STREAM_STAT return size-versioned statistics.
- STREAM_CLOSE ends a stream.

Pending receive and discard ranges are non-overlapping and ordered by offset. A failed or canceled receive returns its private prefix while the stream is open, allowing inspection, retry or discard. Cancellation, linked timeouts and request cleanup release all acquired references. Request state is cached per ring.

Handles carry a slot generation; stream tokens additionally carry a tag. Stale or wrong-kind names fail with -ESTALE. Exhausted generations retire their slots. A store stops when its user count reaches zero, closing its streams and releasing table-owned objects. Its reference count retains memory and accounting until outstanding requests finish.

The ring lock serializes issue, task work, cancellation and cleanup. The table mutex protects handle tables; the stream mutex protects one stream's extents and decisions; wait_lock protects request phases and wait lists. The order is uring_lock, then tables or stream->lock, then wait_lock. The table and stream mutexes never nest.

---
 include/uapi/linux/io_uring.h |    5 +
 io_uring/Makefile             |    2 +-
 io_uring/cancel.c             |    5 +
 io_uring/io_uring.c           |    9 +
 io_uring/opaque.c             | 1200 +++++++++++++++++++++++++++++++++
 io_uring/opaque_register.c    |   90 +++
 io_uring/opdef.c              |   16 +
 io_uring/register.c           |    7 +
 8 files changed, 1333 insertions(+), 1 deletion(-)
 create mode 100644 io_uring/opaque_register.c
include/uapi/linux/io_uring.h +5 -0
index b456f45fa8de..081f30605410 100644
@@ -91,6 +91,7 @@ struct io_uring_sqe {
 		__s32	splice_fd_in;
 		__u32	file_index;
 		__u32	zcrx_ifq_idx;
+		__u32	opaque_store_id;
 		__u32	optlen;
 		struct {
 			__u16	addr_len;
@@ -319,6 +320,7 @@ enum io_uring_op {
 	IORING_OP_PIPE,
 	IORING_OP_NOP128,
 	IORING_OP_URING_CMD128,
+	IORING_OP_OPAQUE_OBJ,
 
 	/* this goes last, obviously */
 	IORING_OP_LAST,
@@ -724,6 +726,9 @@ enum io_uring_register_op {
 	/* register bpf filtering programs */
 	IORING_REGISTER_BPF_FILTER		= 37,
 
+	/* register, import or export a kernel opaque object store */
+	IORING_REGISTER_OPAQUE_STORE	= 38,
+
 	/* this goes last */
 	IORING_REGISTER_LAST,
 
io_uring/Makefile +1 -1
index 191316972e04..912b1861c0a5 100644
@@ -17,7 +17,7 @@ obj-$(CONFIG_IO_URING)		+= io_uring.o opdef.o kbuf.o rsrc.o notif.o \
 					query.o loop.o
 
 obj-$(CONFIG_IO_URING_ZCRX)	+= zcrx.o
-obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o opaque_compact.o
+obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o opaque_register.o opaque_compact.o
 obj-$(CONFIG_IO_WQ)		+= io-wq.o
 obj-$(CONFIG_FUTEX)		+= futex.o
 obj-$(CONFIG_EPOLL)		+= epoll.o
io_uring/cancel.c +5 -0
index 6f7a6cf356c2..e35720f41721 100644
@@ -19,6 +19,7 @@
 #include "waitid.h"
 #include "futex.h"
 #include "cancel.h"
+#include "opaque.h"
 #include "wait.h"
 
 struct io_cancel {
@@ -130,6 +131,9 @@ int io_try_cancel(struct io_uring_task *tctx, struct io_cancel_data *cd,
 		cd->running = true;
 
 	ret = io_poll_cancel(ctx, cd, issue_flags);
+	if (ret != -ENOENT)
+		return ret;
+	ret = io_opaque_cancel(ctx, cd, issue_flags);
 	if (ret != -ENOENT)
 		return ret;
 
@@ -582,6 +586,7 @@ __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
 	mutex_lock(&ctx->uring_lock);
 	ret |= io_cancel_defer_files(ctx, tctx, cancel_all);
 	ret |= io_poll_remove_all(ctx, tctx, cancel_all);
+	ret |= io_opaque_cancel_all(ctx, tctx, cancel_all);
 	ret |= io_waitid_remove_all(ctx, tctx, cancel_all);
 	ret |= io_futex_remove_all(ctx, tctx, cancel_all);
 	ret |= io_uring_try_cancel_uring_cmd(ctx, tctx);
io_uring/io_uring.c +9 -0
index 8ffe0c9a4e29..fddf9e0ebc8b 100644
@@ -88,6 +88,7 @@
 #include "msg_ring.h"
 #include "memmap.h"
 #include "zcrx.h"
+#include "opaque.h"
 #include "bpf-ops.h"
 
 #include "timeout.h"
@@ -220,6 +221,7 @@ static void io_free_alloc_caches(struct io_ring_ctx *ctx)
 	io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
 	io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free);
 	io_futex_cache_free(ctx);
+	io_opaque_cache_free(ctx);
 	io_rsrc_cache_free(ctx);
 }
 
@@ -267,6 +269,7 @@ static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
 			    sizeof(struct io_async_cmd),
 			    sizeof(struct io_async_cmd));
 	ret |= io_futex_cache_init(ctx);
+	ret |= io_opaque_cache_init(ctx);
 	ret |= io_rsrc_cache_init(ctx);
 	if (ret)
 		goto free_ref;
@@ -287,6 +290,10 @@ static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
 	ctx->submit_state.free_list.next = NULL;
 	INIT_HLIST_HEAD(&ctx->waitid_list);
 	xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC);
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+	xa_init_flags(&ctx->opaque_stores, XA_FLAGS_ALLOC);
+	INIT_LIST_HEAD(&ctx->opaque_waits);
+#endif
 #ifdef CONFIG_FUTEX
 	INIT_HLIST_HEAD(&ctx->futex_list);
 #endif
@@ -2294,6 +2301,7 @@ static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
 
 	mutex_lock(&ctx->uring_lock);
 	io_unregister_zcrx(ctx);
+	io_unregister_opaque(ctx);
 	io_cqring_overflow_kill(ctx);
 	io_eventfd_unregister(ctx);
 	io_free_alloc_caches(ctx);
@@ -2638,6 +2646,7 @@ static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
 	xa_for_each(&ctx->personalities, index, creds)
 		io_unregister_personality(ctx, index);
 	io_terminate_zcrx(ctx);
+	io_terminate_opaque(ctx);
 	/* Drop these now, rather than async, to unpin the files */
 	io_sqe_buffers_unregister(ctx);
 	io_sqe_files_unregister(ctx);
io_uring/opaque.c +1200 -0

1,233 lines not on this page · raw message

io_uring/opaque_register.c new file +90 -0

90 lines not on this page · raw message

io_uring/opdef.c +16 -0
index cf3aa2242cd7..256c7c533118 100644
@@ -38,6 +38,7 @@
 #include "futex.h"
 #include "truncate.h"
 #include "zcrx.h"
+#include "opaque.h"
 
 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
 {
@@ -591,6 +592,17 @@ const struct io_issue_def io_issue_defs[] = {
 		.prep			= io_uring_cmd_prep,
 		.issue			= io_uring_cmd,
 	},
+	[IORING_OP_OPAQUE_OBJ] = {
+		.audit_skip		= 1,
+		.ioprio			= 1,
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		.async_size		= sizeof(struct io_opaque_req),
+		.prep			= io_opaque_prep,
+		.issue			= io_opaque_issue,
+#else
+		.prep			= io_eopnotsupp_prep,
+#endif
+	},
 };
 
 const struct io_cold_def io_cold_defs[] = {
@@ -849,6 +861,10 @@ const struct io_cold_def io_cold_defs[] = {
 		.sqe_copy		= io_uring_cmd_sqe_copy,
 		.cleanup		= io_uring_cmd_cleanup,
 	},
+	[IORING_OP_OPAQUE_OBJ] = {
+		.name			= "OPAQUE_OBJ",
+		.cleanup		= io_opaque_cleanup,
+	},
 };
 
 const char *io_uring_get_opcode(u8 opcode)
io_uring/register.c +7 -0
index 2ce36623e25a..1e450554ca38 100644
@@ -32,6 +32,7 @@
 #include "msg_ring.h"
 #include "memmap.h"
 #include "zcrx.h"
+#include "opaque.h"
 #include "query.h"
 #include "bpf_filter.h"
 
@@ -1013,6 +1014,12 @@ static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
 	case IORING_REGISTER_QUERY:
 		ret = io_query(arg, nr_args);
 		break;
+	case IORING_REGISTER_OPAQUE_STORE:
+		ret = -EINVAL;
+		if (!arg || nr_args != 1)
+			break;
+		ret = io_register_opaque(ctx, arg);
+		break;
 	case IORING_REGISTER_ZCRX_CTRL:
 		ret = io_zcrx_ctrl(ctx, arg, nr_args);
 		break;
Signature · 1 line
2.34.1
#8 lore raw

RFC PATCH 6/12 io_uring/opaque: allow rings to share a store

In reply to Alex Markuze

A multi-threaded server often uses one ring per thread. Allow an object received or created through one ring to be used through another ring without copying its payload.

Add EXPORT and IMPORT controls to IORING_REGISTER_OPAQUE_STORE. EXPORT returns a close-on-exec anonymous-inode descriptor; IMPORT registers its store under a new ring-local ID. The descriptor cannot read, map or poll payload. Handles and stream tokens belong to the store and are valid through every ring sharing it.

Each registered ring entry and export file holds one user reference and one lifetime reference. The last user stops the store; the last lifetime reference releases its memory and accounting. An export file can keep a store alive after the creating ring exits. Import preserves the store's memory-cgroup ownership and original ring user/mm accounting and adds no backing charge.

Export reserves the descriptor and creates the file, copies the number to userspace, and installs it only after that copy succeeds. Failure unwinds the references and descriptor reservation. Import erases the new ring-local ID if copying its result to userspace fails.

---
 include/uapi/linux/io_uring/opaque.h |  3 +
 io_uring/opaque_register.c           | 84 ++++++++++++++++++++++++----
 2 files changed, 76 insertions(+), 11 deletions(-)
include/uapi/linux/io_uring/opaque.h +3 -0
index 692daa7d7e32..9a129b5da5af 100644
@@ -16,6 +16,9 @@ struct io_uring_opaque_register {
 	__u64 __resv[2];
 };
 
+#define IORING_OPAQUE_REG_IMPORT	(1U << 0)
+#define IORING_OPAQUE_REG_EXPORT	(1U << 1)
+
 /* config/config_size select a size-versioned configuration on creation. */
 struct io_uring_opaque_config {
 	__u64 hard_limit;
io_uring/opaque_register.c +73 -11

98 lines not on this page · raw message

Signature · 1 line
2.34.1
#9 lore raw

RFC PATCH 7/12 io_uring/opaque: add IORING_OP_OPAQUE_OBJ_SEND

In reply to Alex Markuze

Add an operation that queues an optional prefix, an object range and an optional suffix to a TCP socket, reporting the queued byte count in one CQE.

sqe->fd names the socket; addr, off and len select the object range; addr3 optionally points to an io_uring_opaque_frame descriptor. Combined framing is limited to 64 KiB. ioprio accepts SEND_LAST and msg_flags accepts MSG_MORE and MSG_DONTWAIT. With a zero handle, offset and length, the request sends only framing bytes as an object-free reply.

Preparation copies the frame descriptor when the kernel consumes this SQE. Its storage must survive until that consumption, which a short or failed submission may leave pending. Prefix and suffix bytes are copied at first issue, before handle acquisition, and must remain valid until then. The request owns the resulting copy, charged to the store and its memory cgroup; framing can use the reply reserve.

The body uses MSG_SPLICE_PAGES over the immutable version's bio_vecs. Indexed segment lookup finds the range's start. One cursor tracks prefix, body and suffix so retries continue at the first unqueued byte. Without MSG_DONTWAIT, the request waits for socket space until it finishes or an error, signal or cancellation ends it. The result counts bytes queued to TCP, not delivered to the peer.

Sends through one store to one socket enter a FIFO under the store's TX lock after frame import during first issue. The ordering is by enqueue, not SQE submission or the start of issue on concurrent rings. Only the head sends and polls; followers resume through their own ring's task work. The head leaves when its frame finishes or terminates. If it ends after queuing only part of the frame, its followers complete -ECANCELED, including admissions still acquiring object references. The failure remains visible until both linked requests and admissions drain. A head that queued nothing does not fail its followers. Cancellation of linked followers proceeds in batches of 32 outside the queue lock between batches. Writers outside this store do not participate in the FIFO.

The store indexes queues by socket address under tx_lock. Up to 64 empty queues are retained for reuse. Their keys are compared, never dereferenced; a reused address finds an empty, nonfailed queue.

An ordinary send pins the current version while leaving the handle usable. SEND_LAST removes the handle at acquisition and transfers its reference to the request. CONSUMED reports that transfer even if the request later fails, is canceled or completes short. A failure before acquisition consumes nothing. Competing LAST requests cannot both acquire the same handle.

For plain TCP, the head acquires its references, sends each frame part, advances the queue and drops nonfinal references under one socket lock. Final version release follows release_sock(). The issue performs the security hook, RPS recording and send-length tracing normally supplied by sock_sendmsg(); the hook runs before lock_sock(), since it may take that lock. A replaced TCP protocol uses sock_sendmsg() instead, and the direct path rechecks the protocol between frame parts after TCP may have dropped the socket lock.

With IO_URING_F_UNLOCKED, the ring lock is dropped before acquiring the socket lock. Inline issue retains its ring lock. Nothing may wait for a socket lock while holding the table mutex. Short and failed sends fail their link chain.

Reserve the FIFO position in the first TX lock hold, before acquiring references, including queue creation, but after frame import. Queue metadata uses accounted nonblocking allocation; ENOMEM precedes handle acquisition or LAST. A busy queue holds a socket reference independently of request files. That reference is released outside the TX lock when its last position drains. Idle queues pin no socket. Pending failures keep their position through cleanup, preserving
the failure barrier without allowing socket-address reuse.

---
 include/uapi/linux/io_uring.h        |   4 +
 include/uapi/linux/io_uring/opaque.h |   3 +
 io_uring/opaque.c                    | 933 ++++++++++++++++++++++++++-
 io_uring/opdef.c                     |  21 +
 4 files changed, 958 insertions(+), 3 deletions(-)
include/uapi/linux/io_uring.h +4 -0
index 081f30605410..1759f4f805b1 100644
@@ -321,6 +321,7 @@ enum io_uring_op {
 	IORING_OP_NOP128,
 	IORING_OP_URING_CMD128,
 	IORING_OP_OPAQUE_OBJ,
+	IORING_OP_OPAQUE_OBJ_SEND,
 
 	/* this goes last, obviously */
 	IORING_OP_LAST,
@@ -534,6 +535,8 @@ struct io_uring_cqe {
  *			if a large CQE is attempted posted when the ring has
  *			just a single small CQE worth of space left before
  *			wrapping.
+ * IORING_CQE_F_OPAQUE_CONSUMED OPAQUE_OBJ_SEND took ownership of the entire
+ *			object handle. Also valid on short or failed completions.
  * IORING_CQE_F_32	If set, this is a 32b/big-cqe posting. Use with rings
  *			setup in a mixed CQE mode, where both 16b and 32b
  *			CQEs may be posted to the CQ ring.
@@ -544,6 +547,7 @@ struct io_uring_cqe {
 #define IORING_CQE_F_NOTIF		(1U << 3)
 #define IORING_CQE_F_BUF_MORE		(1U << 4)
 #define IORING_CQE_F_SKIP		(1U << 5)
+#define IORING_CQE_F_OPAQUE_CONSUMED	(1U << 6)
 #define IORING_CQE_F_32			(1U << 15)
 
 #define IORING_CQE_BUFFER_SHIFT		16
include/uapi/linux/io_uring/opaque.h +3 -0
index 9a129b5da5af..2a862d76a40e 100644
@@ -59,6 +59,9 @@ enum io_uring_opaque_op {
 	IORING_OPAQUE_AVAILABLE,
 };
 
+/* IORING_OP_OPAQUE_OBJ_SEND: sqe->ioprio contains these flags. */
+#define IORING_OPAQUE_SEND_LAST	(1U << 0)
+
 /* Optional SEND sqe->addr3 framing; size includes zero reserved extensions. */
 struct io_uring_opaque_frame {
 	__u32 size;
io_uring/opaque.c +930 -3

996 lines not on this page · raw message

io_uring/opdef.c +21 -0
index 256c7c533118..a80a56b19581 100644
@@ -601,6 +601,20 @@ const struct io_issue_def io_issue_defs[] = {
 		.issue			= io_opaque_issue,
 #else
 		.prep			= io_eopnotsupp_prep,
+#endif
+	},
+	[IORING_OP_OPAQUE_OBJ_SEND] = {
+		.audit_skip		= 1,
+		.ioprio			= 1,
+		.needs_file		= 1,
+		.unbound_nonreg_file	= 1,
+		.pollout			= 1,
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		.async_size		= sizeof(struct io_opaque_req),
+		.prep			= io_opaque_send_prep,
+		.issue			= io_opaque_send,
+#else
+		.prep			= io_eopnotsupp_prep,
 #endif
 	},
 };
@@ -865,6 +879,13 @@ const struct io_cold_def io_cold_defs[] = {
 		.name			= "OPAQUE_OBJ",
 		.cleanup		= io_opaque_cleanup,
 	},
+	[IORING_OP_OPAQUE_OBJ_SEND] = {
+		.name			= "OPAQUE_OBJ_SEND",
+		.cleanup		= io_opaque_cleanup,
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		.fail			= io_opaque_fail,
+#endif
+	},
 };
 
 const char *io_uring_get_opcode(u8 opcode)
Signature · 1 line
2.34.1
#10 lore raw

Re: [RFC PATCH net-next 07/12] io_uring/opaque: add IORING_OP_OPAQUE_OBJ_SEND

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] io_uring/opaque: missing IO_URING_F_NONBLOCK check in io_opaque_send() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] io_uring/opaque: missing IO_URING_F_NONBLOCK check in io_opaque_send()
--

commit 1e659b6cd96d02ac2bb983ff5c26c204fe0a5ef3
Author: Alex Markuze <[email protected]>

io_uring/opaque: add IORING_OP_OPAQUE_OBJ_SEND

This commit adds the IORING_OP_OPAQUE_OBJ_SEND operation to send an optional prefix, an opaque object range, and an optional suffix to a TCP socket with per-socket FIFO ordering across the store.

Quoted 4 lines
io_uring/opaque.c +0 -0
index 81fbf2011446d..b62c4be92fead 100644

[ ... ]

Quoted 1 line
io_uring/opaque.c +0 -0
@@ -1591,9 +1669,858 @@ void io_opaque_cleanup(struct io_kiocb *req)

[ ... ]

Quoted 15 lines
io_uring/opaque.c +15 -0
+sent:
+	if (ret > 0) {
+		if (body)
+			op->iter = msg.msg_iter;
+		op->progress += ret;
+		if (op->progress < op->total_length && !iov_iter_count(&msg.msg_iter)) {
+			/*
+			 * TCP lets go of the socket while it waits for room, and a
+			 * protocol may have taken it over by then: ask again.
+			 */
+			if (owned && !io_opaque_send_direct(sk)) {
+				release_sock(sk);
+				io_ring_submit_lock(req->ctx, issue_flags);
+				owned = false;
+			}

io_uring/opaque.c void io_opaque_cleanup(struct io_kiocb *req) · line 2491

Quoted 10 lines
io_uring/opaque.c +10 -0
+			goto again;
+		}
+		if (op->progress < op->total_length && !(req->flags & REQ_F_NOWAIT)) {
+			ret = -EAGAIN;
+			goto leave;
+		}
+	} else if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK) &&
+		   !(req->flags & REQ_F_NOWAIT)) {
+		goto leave;
+	}

[Severity: Medium]
Should the partial-send check in io_opaque_send() also test (issue_flags & IO_URING_F_NONBLOCK), matching the ret == -EAGAIN branch right below it?

When io_opaque_send() runs in blocking mode from an io-wq worker (!(issue_flags & IO_URING_F_NONBLOCK) and !(req->flags & REQ_F_NOWAIT)), tcp_sendmsg_locked() or sock_sendmsg() can return a partial byte count if sk_stream_wait_memory() is interrupted by a signal, cancellation, socket error, or SO_SNDTIMEO after some bytes have already been queued. Overwriting ret with -EAGAIN and jumping to leave skips the finish path's io_opaque_tx_put() and io_opaque_send_unpin_cheap() before release_sock(), and returns -EAGAIN to io_wq_submit_work() while needs_poll is false:

io_uring/io_uring.c:io_wq_submit_work() {
    ...
		if (!needs_poll) {
			if (!(req->flags & REQ_F_IOPOLL))
				break;
    ...
	if (ret)
		io_req_task_queue_fail(req, ret);
}

Because opaque stores require IORING_SETUP_DEFER_TASKRUN, the abandoned head request stays at the head of tx->requests with tx->failed still false and its object version pinned until the ring's submitter task runs task_work cleanup. Until then, queued followers are not canceled and new sends to the same socket from other rings sharing the store can still pass io_opaque_tx_join() and consume IORING_OPAQUE_SEND_LAST handles.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#11 lore raw

RFC PATCH 8/12 io_uring/opaque: add vectored IORING_OP_OPAQUE_OBJ_SEND

In reply to Alex Markuze

Allow one send request to concatenate several object ranges, amortizing request, queue and CQE work across small objects.

With SEND_VECTOR in sqe->ioprio, addr points to len entries and off must be zero. A vector contains 1 to 1024 io_uring_opaque_send_entry records, each with a handle, offset, nonzero length and zero reserved word. Handles and ranges may repeat. The optional frame wraps the concatenated body; prefix, body and suffix together must fit in INT_MAX bytes.

Preparation copies the entry array when the kernel consumes this SQE. Keep the array valid until that consumption, including across short or failed submissions. The resulting request has one queue entry, one cursor and one completion; retry and ordering follow single-range sends.

Admission resolves and validates every range under the table mutex before taking any reference. Indexed segment lookup uses short walks and binary search; ranges together may span at most 4096 backing segments. A second pass acquires references and, for LAST, removes each distinct handle once. Acquisition is all-or-none; the queued-byte result may still be short. Repeated entries retain the references needed to use the same immutable version.

One request-owned block holds entries, pinned versions, range starts and cursor segments. If it must grow, admission drops the mutex and resolves the handles again after allocation. Cursor construction uses only the versions already pinned by the request.

Ordinary-sized blocks remain with cached requests for reuse. Cleanup frees blocks exceeding 256 entries or segments, and frees every block under KASAN. The VECTOR flag identifies the operation independently of whether a recycled request still carries a block. As with single-range sends, final version release occurs after the socket is unlocked.

Vector admission uses the same already-reserved TX FIFO position as scalar admission. Reference/cursor construction may finish after a head fails; cleanup retains the linked failure barrier and socket identity until the position drains. The vector caller never overtakes an earlier admission.

---
 include/uapi/linux/io_uring/opaque.h |  12 +
 io_uring/opaque.c                    | 405 ++++++++++++++++++++++++++-
 2 files changed, 407 insertions(+), 10 deletions(-)
include/uapi/linux/io_uring/opaque.h +12 -0
index 2a862d76a40e..c04eaed8ce5f 100644
@@ -61,6 +61,18 @@ enum io_uring_opaque_op {
 
 /* IORING_OP_OPAQUE_OBJ_SEND: sqe->ioprio contains these flags. */
 #define IORING_OPAQUE_SEND_LAST	(1U << 0)
+/* addr points at len struct io_uring_opaque_send_entry, off is zero: one send, many ranges. */
+#define IORING_OPAQUE_SEND_VECTOR	(1U << 1)
+/* Entries of one vectored send, as many as SEND_ZC takes iovecs (UIO_MAXIOV). */
+#define IORING_OPAQUE_SEND_VEC_MAX	1024
+
+/* One range of a vectored send, named as addr, off and len name it in a single one. */
+struct io_uring_opaque_send_entry {
+	__u64 handle;
+	__u64 off;
+	__u32 len;
+	__u32 __resv;
+};
 
 /* Optional SEND sqe->addr3 framing; size includes zero reserved extensions. */
 struct io_uring_opaque_frame {
io_uring/opaque.c +395 -10

526 lines not on this page · raw message

Signature · 1 line
2.34.1
#12 lore raw

RFC PATCH 9/12 io_uring/opaque: add IORING_OP_OPAQUE_COLLECT

In reply to Alex Markuze

Add a multishot request that attaches a connected TCP socket to a store and collects its receive stream. sqe->fd names the socket and opaque_store_id the store. ioprio accepts POLL_FIRST; IOSQE_ASYNC and successful-CQE suppression are rejected.

Attachment requires ESTABLISHED or CLOSE_WAIT, the original TCP protocol, no receive owner, repair mode, urgent data or sk_user_data. Authorize receive access under the request's credentials before attachment and before taking the socket lock. This authorization covers the collector's lifetime; subsequent passes do not recheck receive policy. Attachment posts the stream-token CQE before publishing the receive claim. If that CQE cannot be posted, no claim or byte is taken. Stream offset zero is the first unread byte at attachment.

Each issue captures at most 256 KiB through tcp_read_sock(). The actor follows the earliest pending stream decision: DISCARD consumes without retention, RECV_OBJECT builds private backing, and other bytes become undecided. Eligible unshared receive pages are retained by reference; other data is packed into owned copies. Undecided bytes normally stop further collection so TCP flow control can apply. Decisions and waiting inspection requests can make collection resume.

Byte or extent pressure produces a nonterminal -ENOBUFS CQE, at most once per unread offset, and enrolls the collector on the store's budget wait list. Allocation failure imposes a 50-ms retry deadline. Wakeups grant no capacity: reentry checks both budgets and the deadline again. An infeasible partial RECV_OBJECT returns its private prefix and fails instead of holding capacity while waiting for the rest of itself.

Use native multishot socket polling between collection passes. The receive-owner callback, decisions, closure and capacity returns set a persistent private collector predicate before waking the socket waitqueue with kernel-only POLL_RX_OWNER (bit 26). Native poll enrolls before checking the predicate and consumes it only on collector entry. Filter the private key before taking poll ownership: ordinary polls and output async polls ignore it. Eligible payload-read async polls recheck current receive ownership even after coalesced notifications, so the real receive handler reports the owner conflict. Error-queue receives retain their existing behavior. No UAPI poll event is added.

Retain a pass after both initial and multishot batch exhaustion. A worker poll before first issue permits initial attachment unless POLL_FIRST requested ordinary socket readiness. Set NO_LAZY because one collector task-work enqueue can complete several range requests. While budget-blocked, the collector still observes errors, urgent data and EOF, consumes a payload-free FIN, and can execute a DISCARD at its capture cursor without allocating.

EOF, socket error, urgent data, cancellation, stream close or inability to post a pressure CQE ends the collector. Cancellation closes its stream and releases retained undecided data, including cancellation after a native poll-setup failure. A token is not a recovery promise after that failure. EOF and socket errors leave retained data available for pending decisions. The stream token remains until STREAM_CLOSE or store teardown. The stream retains its socket file.

Capture takes stream->lock, then the socket lock, then wait_lock. Attachment takes the socket lock before tables and sk_callback_lock; no table holder waits for the socket lock.

---
 include/linux/poll.h          |   3 +
 include/uapi/linux/io_uring.h |   1 +
 io_uring/opaque.c             | 599 +++++++++++++++++++++++++++++++++-
 io_uring/opaque.h             |   6 +
 io_uring/opaque_internal.h    |   3 +
 io_uring/opdef.c              |  18 +
 io_uring/poll.c               |  58 +++-
 7 files changed, 680 insertions(+), 8 deletions(-)
include/linux/poll.h +3 -0
index 12bb18e8b978..b2a85a503fd9 100644
@@ -12,6 +12,9 @@
 #include <uapi/linux/poll.h>
 #include <uapi/linux/eventpoll.h>
 
+/* Wake-only receive-owner notification, not file readiness or a UAPI event. */
+#define POLL_RX_OWNER	((__force __poll_t)(1U << 26))
+
 /* ~832 bytes of stack space used max in sys_select/sys_poll before allocating
    additional memory. */
 #define MAX_STACK_ALLOC 832
include/uapi/linux/io_uring.h +1 -0
index 1759f4f805b1..6469ab391eec 100644
@@ -322,6 +322,7 @@ enum io_uring_op {
 	IORING_OP_URING_CMD128,
 	IORING_OP_OPAQUE_OBJ,
 	IORING_OP_OPAQUE_OBJ_SEND,
+	IORING_OP_OPAQUE_COLLECT,
 
 	/* this goes last, obviously */
 	IORING_OP_LAST,
io_uring/opaque.c +593 -6

656 lines not on this page · raw message

io_uring/opaque.h +6 -0
index a7210f4bee5e..4001a4484ff9 100644
@@ -102,6 +102,7 @@ void io_opaque_stop(struct io_opaque_store *store);
 void io_opaque_free(struct io_opaque_store *store);
 int io_opaque_recv_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe);
 int io_opaque_recv(struct io_kiocb *req, unsigned int issue_flags);
+__poll_t io_opaque_collect_poll(struct io_kiocb *req);
 int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe);
 int io_opaque_issue(struct io_kiocb *req, unsigned int issue_flags);
 int io_opaque_send_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe);
@@ -113,6 +114,11 @@ int io_opaque_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd,
 bool io_opaque_cancel_all(struct io_ring_ctx *ctx, struct io_uring_task *tctx,
 			  bool cancel_all);
 #else
+static inline __poll_t io_opaque_collect_poll(struct io_kiocb *req)
+{
+	return 0;
+}
+
 static inline bool io_opaque_cache_init(struct io_ring_ctx *ctx)
 {
 	return false;
io_uring/opaque_internal.h +3 -0
index f6b372800c76..2d5f69ee8925 100644
@@ -2,6 +2,7 @@
 #ifndef IO_URING_OPAQUE_INTERNAL_H
 #define IO_URING_OPAQUE_INTERNAL_H
 
+#include <linux/atomic.h>
 #include <linux/bitmap.h>
 #include <linux/bvec.h>
 #include <linux/net.h>
@@ -148,6 +149,8 @@ struct io_opaque_vec {
 
 struct io_opaque_stream {
 	refcount_t refs;
+	/* Consumed only on entry to a collector pass, never by native poll. */
+	atomic_t collect_ready;
 	/* Extents, range decisions and collector state. */
 	struct mutex lock;
 	struct io_opaque_store *store;
io_uring/opdef.c +18 -0
index a80a56b19581..628f908a66ad 100644
@@ -592,6 +592,20 @@ const struct io_issue_def io_issue_defs[] = {
 		.prep			= io_uring_cmd_prep,
 		.issue			= io_uring_cmd,
 	},
+	[IORING_OP_OPAQUE_COLLECT] = {
+		.audit_skip		= 1,
+		.ioprio			= 1,
+		.needs_file		= 1,
+		.unbound_nonreg_file	= 1,
+		.pollin			= 1,
+#ifdef CONFIG_IO_URING_OPAQUE_OBJ
+		.async_size		= sizeof(struct io_opaque_req),
+		.prep			= io_opaque_recv_prep,
+		.issue			= io_opaque_recv,
+#else
+		.prep			= io_eopnotsupp_prep,
+#endif
+	},
 	[IORING_OP_OPAQUE_OBJ] = {
 		.audit_skip		= 1,
 		.ioprio			= 1,
@@ -875,6 +889,10 @@ const struct io_cold_def io_cold_defs[] = {
 		.sqe_copy		= io_uring_cmd_sqe_copy,
 		.cleanup		= io_uring_cmd_cleanup,
 	},
+	[IORING_OP_OPAQUE_COLLECT] = {
+		.name			= "OPAQUE_COLLECT",
+		.cleanup		= io_opaque_cleanup,
+	},
 	[IORING_OP_OPAQUE_OBJ] = {
 		.name			= "OPAQUE_OBJ",
 		.cleanup		= io_opaque_cleanup,
io_uring/poll.c +56 -2

94 lines not on this page · raw message

Signature · 1 line
2.34.1
#13 lore raw

Re: [RFC PATCH net-next 09/12] io_uring/opaque: add IORING_OP_OPAQUE_COLLECT

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] io_uring/opaque: infinite io-wq/task_work loop in io_opaque_recv() - [Medium] io_uring/opaque: wrong…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] io_uring/opaque: infinite io-wq/task_work loop in io_opaque_recv()
- [Medium] io_uring/opaque: wrong need_bytes in io_opaque_append() on tail reuse
- [Medium] io_uring/opaque: stale hold_undecided in io_opaque_actor() after decision
- [Medium] io_uring/opaque: POLL_FIRST collector ignores sock_rx_owned() in poll
--

commit 8d32c303015f5762780ff1306cc30dacc6d593bb
Author: Alex Markuze <[email protected]>

io_uring/opaque: add IORING_OP_OPAQUE_COLLECT

This commit adds the IORING_OP_OPAQUE_COLLECT multishot operation to attach a connected TCP socket to an opaque store and capture its receive stream into decisions or undecided extents using native multishot socket polling.

Quoted 29 lines
io_uring/opaque.c +21 -0
index 0c58900073f72..4610e212a8005 100644
@@ -49,6 +50,38 @@ static void io_opaque_vec_cleanup(struct io_opaque_req *op);
 static void io_opaque_stream_close(struct io_opaque_stream *stream);
 static void io_opaque_tx_put(struct io_opaque_req *op);
 
+/*
+ * Publish before waking; native poll enrolls before reading collect_ready.
+ * This is not TCP readiness: only COLLECT and receive-owner-affected apoll
+ * recheck their predicates. Ordinary poll and output apoll ignore the key.
+ */
+static void io_opaque_collect_wake(struct io_opaque_stream *stream)
+{
+	struct socket *sock = sock_from_file(stream->file);
+
+	atomic_set(&stream->collect_ready, 1);
+	wake_up_interruptible_poll(sk_sleep(sock->sk), POLL_RX_OWNER);
+}
+
+static void io_opaque_data_ready(struct sock *sk, void *data)
+{
+	struct io_opaque_stream *stream = data;
+
+	/* sk_callback_lock pins stream; do not take stream or socket locks here. */
+	atomic_set(&stream->collect_ready, 1);
+	wake_up_interruptible_poll(sk_sleep(sk), POLL_RX_OWNER);
+}

io_uring/opaque.c static void io_opaque_vec_cleanup(struct io_opaque_req *op); · line 83

Quoted 10 lines
io_uring/opaque.c +10 -0
+
+__poll_t io_opaque_collect_poll(struct io_kiocb *req)
+{
+	struct io_opaque_req *op = req->async_data;
+
+	/* io-wq may poll before the first issue, including a trailing link. */
+	if (!op->stream)
+		return op->collect_flags & IORING_RECVSEND_POLL_FIRST ? 0 : EPOLLIN;
+	return atomic_read(&op->stream->collect_ready) ? EPOLLIN : 0;
+}

[Severity: Medium]
When an unattached IORING_OP_OPAQUE_COLLECT request with IORING_RECVSEND_POLL_FIRST is waiting in apoll, does io_opaque_collect_poll() need to return EPOLLIN if sock_rx_owned(sock->sk) is true?

In io_poll_mask(), req->opcode == IORING_OP_OPAQUE_COLLECT calls io_opaque_collect_poll() instead of io_poll_rx_owned(). If another collector is already attached or attaches to the same socket and wakes sk_sleep(sock->sk) with POLL_RX_OWNER, io_opaque_collect_poll() returns 0 for the unattached POLL_FIRST collector, so io_poll_check_events() goes back to sleep when the receive queue is empty instead of issuing io_opaque_recv() -> io_opaque_attach() and failing with -EBUSY.

[ ... ]

Quoted 11 lines
io_uring/opaque.c +7 -0
@@ -1158,6 +1188,269 @@ static void io_opaque_stream_process(struct io_opaque_stream *stream)
 	}
 }
 
+/* Only the earliest undecided range is consulted on the capture hot path. */
+static struct io_opaque_req *io_opaque_next_decision(struct io_opaque_stream *stream)
+{
+	struct rb_node *node = rb_first_cached(&stream->decisions);
+
+	return node ? rb_entry(node, struct io_opaque_req, decision) : NULL;
+}

io_uring/opaque.c static void io_opaque_stream_process(struct io_opaque_stream *stream) · line 1207

Quoted 10 lines
io_uring/opaque.c +10 -0
+
+/* Undecided bytes are collected only when nothing is pending or a request needs later bytes. */
+static bool io_opaque_collect_demand(struct io_opaque_stream *stream)
+{
+	struct io_opaque_req *op = io_opaque_next_decision(stream);
+
+	lockdep_assert_held(&stream->lock);
+	return !stream->undecided || !list_empty(&stream->reads) ||
+	       (op && op->offset > stream->next);
+}

[Severity: Medium]
Does setting stream->hold_undecided once per pass from io_opaque_collect_demand() allow io_opaque_actor() to keep draining trailing undecided bytes after a pending decision completes?

When a pass starts with a pending decision at op->offset > stream->next, io_opaque_collect_demand() returns true and sets stream->hold_undecided = false for the entire tcp_read_sock() call, even when stream->reads is empty. Once io_opaque_actor() captures the gap and finishes that decision (leaving op == NULL and stream->undecided > 0), the "if (stream->hold_undecided && !op) break;" check in io_opaque_actor() does not stop, so capture continues pulling up to 256 KiB of undecided bytes off the socket instead of applying TCP flow control.

Quoted 39 lines
io_uring/opaque.c +39 -0
+
+static struct io_opaque_req *io_opaque_capture_keep(struct io_opaque_stream *stream)
+{
+	struct io_opaque_req *op = io_opaque_next_decision(stream);
+
+	if (op && op->op == IORING_OPAQUE_RECV_OBJECT && stream->next >= op->offset &&
+	    stream->next < op->offset + op->length)
+		return op;
+	return NULL;
+}
+
+static struct io_opaque_extent *io_opaque_capture_tail(struct io_opaque_stream *stream)
+{
+	struct io_opaque_req *op = io_opaque_capture_keep(stream);
+	struct list_head *list = op ? &op->data->extents : &stream->extents;
+
+	return list_last_entry_or_null(list, struct io_opaque_extent, list);
+}
+
+static int io_opaque_append(struct io_opaque_stream *stream, struct page *page,
+			    u32 offset, u32 length, bool take_ref, bool copied)
+{
+	struct io_opaque_req *op = io_opaque_capture_keep(stream);
+	struct list_head *list = &stream->extents;
+	struct io_opaque_extent *extent, *tail;
+	u64 start = stream->next;
+	bool new_backing = false;
+
+	if (op) {
+		list = &op->data->extents;
+		start -= op->offset;
+	}
+	tail = list_last_entry_or_null(list, struct io_opaque_extent, list);
+	offset += (page - compound_head(page)) * PAGE_SIZE;
+	page = compound_head(page);
+	if (tail && tail->backing->page == page) {
+		if (tail->start + tail->length == start &&
+		    tail->offset + tail->length == offset) {
+			tail->length += length;

io_uring/opaque.c static void io_opaque_stream_process(struct io_opaque_stream *stream) · line 1256

Quoted 10 lines
io_uring/opaque.c +10 -0
+			extent = tail;
+			goto accounted;
+		}
+	}
+	stream->need_bytes = page_size(page);
+	if (atomic_read(&stream->store->extents) >= stream->store->config.max_extents - 2)
+		return -ENOBUFS;
+	if (tail && tail->backing->page == page) {
+		if (!io_opaque_extent_reserve(stream->store))
+			return -ENOBUFS;

[Severity: Medium]
Should stream->need_bytes be set to 0 when tail && tail->backing->page == page reuses an already-charged backing page and only needs a new extent slot?

If a stream reuses tail->backing across a non-coalescing boundary (such as after an intervening IORING_OPAQUE_DISCARD advances stream->next) and hits the max_extents - 2 limit, io_opaque_append() sets stream->need_bytes = page_size(page) even though no additional byte budget is needed. If the store's byte usage is within page_size(page) of io_opaque_rx_limit(store), io_opaque_budget_ready() will see op->need_bytes > limit - used and keep the collector stalled in IO_OPAQUE_BUDGET_POLL even after extent slots are freed; on the zero-copy path in io_opaque_capture(), -ENOBUFS from extent exhaustion here also falls through to copy: and charges a redundant page.

[ ... ]

Quoted 11 lines
io_uring/opaque.c +11 -0
+int io_opaque_recv(struct io_kiocb *req, unsigned int issue_flags)
+{
+	struct io_opaque_req *op = req->async_data;
+	struct io_opaque_stream *stream;
+	struct socket *sock = sock_from_file(req->file);
+	read_descriptor_t desc = { .count = IO_OPAQUE_RX_BATCH };
+	struct mem_cgroup *old;
+	bool blocked;
+	int ret;
+
+	io_ring_submit_lock(req->ctx, issue_flags);

io_uring/opaque.c static void io_opaque_stream_close(struct io_opaque_stream *stream) · line 1651

Quoted 10 lines
io_uring/opaque.c +10 -0
+	if (!(req->flags & REQ_F_POLLED) &&
+	    (op->collect_flags & IORING_RECVSEND_POLL_FIRST)) {
+		ret = -EAGAIN;
+		goto out;
+	}
+	if (!op->stream && (issue_flags & IO_URING_F_UNLOCKED)) {
+		io_req_task_queue(req);
+		ret = IOU_ISSUE_SKIP_COMPLETE;
+		goto out;
+	}

[Severity: High]
Can an unattached IORING_OP_OPAQUE_COLLECT request loop forever between io-wq and task_work when REQ_F_FORCE_ASYNC is set on it after prep?

Although io_opaque_recv_prep() rejects REQ_F_FORCE_ASYNC, if IORING_OP_OPAQUE_COLLECT is the head of a link chain and a later SQE in the link sets IOSQE_IO_DRAIN, io_init_drain() sets REQ_F_FORCE_ASYNC on the head after prep:

io_uring/io_uring.c:io_init_drain() {
	if (head) {
		head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
		ctx->int_flags |= IO_RING_F_DRAIN_NEXT;
	}
}

When that request runs on a pollable file without O_NONBLOCK or FMODE_NOWAIT, io_wq_submit_work() calls io_opaque_recv() with IO_URING_F_UNLOCKED, which calls io_req_task_queue(req) without clearing REQ_F_FORCE_ASYNC, and io_req_task_submit() sees req->flags & REQ_F_FORCE_ASYNC and queues the request right back to io-wq in an infinite loop. In addition, because socket validation happens later in io_opaque_attach(), submitting IORING_OP_OPAQUE_COLLECT with IORING_RECVSEND_POLL_FIRST on a non-pollable non-socket file returns -EAGAIN here and fails in io-wq with -EBADFD instead of -EOPNOTSUPP.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#14 lore raw

RFC PATCH 10/12 io_uring/opaque: add IORING_OPAQUE_CREATE

In reply to Alex Markuze

Allow an application to populate an immutable object from its own memory, for example to retain a generated reply for repeated sends. Add CREATE to IORING_OP_OPAQUE_OBJ; its objects support the same reads, sends and FREE as received objects.

sqe->addr3 points to the source and len supplies 1 to INT_MAX bytes; addr and off must be zero. Preparation rejects malformed fields, sizes beyond the store's object or capture limits, and inaccessible or overflowing source ranges. Source memory remains valid through execution.

Issue reserves an object slot and page-rounded backing charge, then copies synchronously under the ring lock. It uses the compaction page allocator, preferring compound allocations and falling back to smaller orders. Each allocation owns an extent and part of the reservation. Copying proceeds by base page and yields between destination allocations. CREATE fails immediately on budget exhaustion rather than waiting.

Success returns the length, handle and forwarding-only flag; OBJECT_STAT marks the dense version as compacted. STAT counts the copied bytes. On failure no handle is published, and cleanup releases the slot, backing and unused reservation. A large CREATE holds the ring lock through the copy and can delay other requests of that ring. There is no per-store pending-request limit.

---
 io_uring/opaque.c | 129 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 127 insertions(+), 2 deletions(-)
io_uring/opaque.c +127 -2
index 4610e212a800..78ae19a6ad82 100644
@@ -1884,7 +1884,6 @@ int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 	    READ_ONCE(sqe->buf_index) || READ_ONCE(sqe->__pad2[0]) ||
 	    cmd > IORING_OPAQUE_AVAILABLE ||
 	    cmd == IORING_OPAQUE_COMPACT || cmd == IORING_OPAQUE_SET_POLICY ||
-	    cmd == IORING_OPAQUE_CREATE ||
 	    (req->flags & (REQ_F_CQE_SKIP | REQ_F_FIXED_FILE)))
 		return -EINVAL;
 	op = io_opaque_req_alloc(req, store);
@@ -1899,6 +1898,21 @@ int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 	op->offset = READ_ONCE(sqe->off);
 	op->length = READ_ONCE(sqe->len);
 	op->addr = u64_to_user_ptr(READ_ONCE(sqe->addr3));
+	if (cmd == IORING_OPAQUE_CREATE) {
+		u64 pointer = READ_ONCE(sqe->addr3);
+
+		if (op->handle || op->offset || !op->length ||
+		    op->length > INT_MAX || !pointer)
+			return -EINVAL;
+		if (op->length > store->config.max_object_size ||
+		    ALIGN((u64)op->length, PAGE_SIZE) > io_opaque_rx_limit(store))
+			return -EMSGSIZE;
+		if (check_add_overflow(pointer, (u64)op->length, &end) ||
+		    pointer > ULONG_MAX || end > ULONG_MAX ||
+		    !access_ok(op->addr, op->length))
+			return -EFAULT;
+		return 0;
+	}
 	if (check_add_overflow(op->offset, (u64)op->length, &end))
 		return -EOVERFLOW;
 	if (cmd <= IORING_OPAQUE_READ_OBJECT || cmd == IORING_OPAQUE_AVAILABLE) {
@@ -2046,12 +2060,110 @@ static int io_opaque_stat(struct io_opaque_req *op)
 	return io_opaque_stat_copy(op, &stat, sizeof(stat));
 }
 
+/* Construction is synchronous under the ring lock, like READ_OBJECT copies. */
+static int io_opaque_create_build(struct io_opaque_req *op)
+{
+	struct io_opaque_store *store = op->store;
+	struct mem_cgroup *old = set_active_memcg(store->memcg);
+	u64 done = 0;
+	int ret = 0;
+
+	while (done < op->length) {
+		u64 pages_left = DIV_ROUND_UP_ULL(op->length - done, PAGE_SIZE);
+		struct io_opaque_extent *extent;
+		unsigned int order;
+		struct page *page;
+		u32 chunk, written = 0;
+
+		page = io_opaque_dest_page(store, pages_left, &order);
+		if (!page) {
+			ret = -ENOMEM;
+			goto out;
+		}
+		chunk = min_t(u64, op->length - done, PAGE_SIZE << order);
+		extent = io_opaque_extent_new(store, page, 0, chunk, done, true);
+		if (IS_ERR(extent)) {
+			put_page(page);
+			ret = PTR_ERR(extent);
+			goto out;
+		}
+		op->create_reserved -= page_size(page);
+		extent->backing->copied = true;
+		list_add_tail(&extent->list, &op->data->extents);
+		while (written < chunk) {
+			u32 bytes = min_t(u32, chunk - written, PAGE_SIZE);
+			unsigned long left;
+			void *mapped;
+
+			mapped = kmap_local_page(page + (written >> PAGE_SHIFT));
+			left = copy_from_user(mapped, op->addr + done + written, bytes);
+			kunmap_local(mapped);
+			atomic64_add(bytes - left, &store->copied);
+			if (left) {
+				ret = -EFAULT;
+				goto out;
+			}
+			written += bytes;
+		}
+		done += chunk;
+		op->data->length = done;
+		cond_resched();
+	}
+	ret = io_opaque_vector(op->data);
+	if (!ret)
+		op->data->dense = true;
+out:
+	set_active_memcg(old);
+	return ret;
+}
+
+static int io_opaque_create(struct io_opaque_req *op, unsigned int issue_flags)
+{
+	struct io_ring_ctx *ctx = op->req->ctx;
+	u64 charge = ALIGN((u64)op->length, PAGE_SIZE);
+	u64 object_flags = 0;
+	struct mem_cgroup *old;
+	int ret;
+
+	io_ring_submit_lock(ctx, issue_flags);
+	if (READ_ONCE(op->store->dead)) {
+		ret = -ESHUTDOWN;
+		goto unlock;
+	}
+	old = set_active_memcg(op->store->memcg);
+	op->data = io_opaque_data_alloc();
+	set_active_memcg(old);
+	if (!op->data) {
+		ret = -ENOMEM;
+		goto unlock;
+	}
+	ret = io_opaque_slot_reserve(op);
+	if (ret)
+		goto unlock;
+	if (!io_opaque_charge(op->store, charge, true)) {
+		ret = -ENOBUFS;
+		goto unlock;
+	}
+	op->create_reserved = charge;
+	ret = io_opaque_create_build(op);
+	if (!ret)
+		ret = io_opaque_publish(op, &object_flags);
+unlock:
+	io_req_set_res32(op->req, ret, 0, ret >= 0 ? op->handle : 0, object_flags);
+	if (ret < 0)
+		req_set_fail(op->req);
+	io_ring_submit_unlock(ctx, issue_flags);
+	return IOU_COMPLETE;
+}
+
 int io_opaque_issue(struct io_kiocb *req, unsigned int issue_flags)
 {
 	struct io_opaque_req *op = req->async_data;
 	struct io_opaque_store *store = op->store;
 	int ret;
 
+	if (op->op == IORING_OPAQUE_CREATE)
+		return io_opaque_create(op, issue_flags);
 	io_ring_submit_lock(req->ctx, issue_flags);
 	/* Pair with the cancellation search before any opaque wait enrollment. */
 	if (io_wq_cancel_seen(req, issue_flags)) {
@@ -2224,6 +2336,16 @@ bool io_opaque_cancel_all(struct io_ring_ctx *ctx, struct io_uring_task *tctx,
 	return found;
 }
 
+static void io_opaque_create_release(struct io_opaque_req *op)
+{
+	io_opaque_data_put(op->store, op->data);
+	op->data = NULL;
+	if (op->create_reserved) {
+		io_opaque_uncharge(op->store, op->create_reserved);
+		op->create_reserved = 0;
+	}
+}
+
 void io_opaque_cleanup(struct io_kiocb *req)
 {
 	struct io_opaque_req *op = req->async_data;
@@ -2287,7 +2409,10 @@ void io_opaque_cleanup(struct io_kiocb *req)
 	}
 	if (unlikely(op->vec))
 		io_opaque_vec_cleanup(op);
-	io_opaque_data_put(store, op->data);
+	if (op->op == IORING_OPAQUE_CREATE)
+		io_opaque_create_release(op);
+	else
+		io_opaque_data_put(store, op->data);
 	io_opaque_stream_put(op->stream);
 	lockdep_assert_held(&req->ctx->uring_lock);
 	io_opaque_req_free(req->ctx, op);
Signature · 1 line
2.34.1
#15 lore raw

Re: [RFC PATCH net-next 10/12] io_uring/opaque: add IORING_OPAQUE_CREATE

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] io_uring/opaque: double fetch of sqe->addr3 in io_opaque_prep() - [Medium] io_uring/opaque: active…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] io_uring/opaque: double fetch of sqe->addr3 in io_opaque_prep()
- [Medium] io_uring/opaque: active memcg kept for user copy in io_opaque_create_build()
--

commit 990f7cf758f745b1bd5de4e8984b2d7a6df26c8e
Author: Alex Markuze <[email protected]>

io_uring/opaque: add IORING_OPAQUE_CREATE

This commit adds the IORING_OPAQUE_CREATE operation to IORING_OP_OPAQUE_OBJ, allowing applications to construct immutable opaque objects synchronously from userspace memory.

Quoted 21 lines
io_uring/opaque.c +5 -1
index 4610e212a8005..78ae19a6ad82f 100644
@@ -1884,7 +1884,6 @@ int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 	    READ_ONCE(sqe->buf_index) || READ_ONCE(sqe->__pad2[0]) ||
 	    cmd > IORING_OPAQUE_AVAILABLE ||
 	    cmd == IORING_OPAQUE_COMPACT || cmd == IORING_OPAQUE_SET_POLICY ||
-	    cmd == IORING_OPAQUE_CREATE ||
 	    (req->flags & (REQ_F_CQE_SKIP | REQ_F_FIXED_FILE)))
 		return -EINVAL;
 	op = io_opaque_req_alloc(req, store);
@@ -1899,6 +1898,21 @@ int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
 	op->offset = READ_ONCE(sqe->off);
 	op->length = READ_ONCE(sqe->len);
 	op->addr = u64_to_user_ptr(READ_ONCE(sqe->addr3));
+	if (cmd == IORING_OPAQUE_CREATE) {
+		u64 pointer = READ_ONCE(sqe->addr3);
+
+		if (op->handle || op->offset || !op->length ||
+		    op->length > INT_MAX || !pointer)

io_uring/opaque.c int io_opaque_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) · line 1915

Quoted 10 lines
io_uring/opaque.c +10 -0
+			return -EINVAL;
+		if (op->length > store->config.max_object_size ||
+		    ALIGN((u64)op->length, PAGE_SIZE) > io_opaque_rx_limit(store))
+			return -EMSGSIZE;
+		if (check_add_overflow(pointer, (u64)op->length, &end) ||
+		    pointer > ULONG_MAX || end > ULONG_MAX ||
+		    !access_ok(op->addr, op->length))
+			return -EFAULT;
+		return 0;
+	}

[Severity: Medium]
Does reading sqe->addr3 twice from the shared submission ring allow op->addr and pointer to diverge if userspace modifies the SQE concurrently?

The non-NULL, overflow, and 32-bit truncation checks validate the second read in pointer, whereas access_ok() and the later copy_from_user() in io_opaque_create_build() use op->addr from the first read. Reading sqe->addr3 once into a local u64 and deriving op->addr from it would keep the checks and copy consistent.

Quoted 32 lines
io_uring/opaque.c +28 -0
@@ -2046,12 +2060,110 @@ static int io_opaque_stat(struct io_opaque_req *op)
 	return io_opaque_stat_copy(op, &stat, sizeof(stat));
 }
 
+/* Construction is synchronous under the ring lock, like READ_OBJECT copies. */
+static int io_opaque_create_build(struct io_opaque_req *op)
+{
+	struct io_opaque_store *store = op->store;
+	struct mem_cgroup *old = set_active_memcg(store->memcg);
+	u64 done = 0;
+	int ret = 0;
+
+	while (done < op->length) {
+		u64 pages_left = DIV_ROUND_UP_ULL(op->length - done, PAGE_SIZE);
+		struct io_opaque_extent *extent;
+		unsigned int order;
+		struct page *page;
+		u32 chunk, written = 0;
+
+		page = io_opaque_dest_page(store, pages_left, &order);
+		if (!page) {
+			ret = -ENOMEM;
+			goto out;
+		}
+		chunk = min_t(u64, op->length - done, PAGE_SIZE << order);
+		extent = io_opaque_extent_new(store, page, 0, chunk, done, true);
+		if (IS_ERR(extent)) {
+			put_page(page);
+			ret = PTR_ERR(extent);
+			goto out;
+		}
+		op->create_reserved -= page_size(page);

io_uring/opaque.c static int io_opaque_stat(struct io_opaque_req *op) · line 2100

Quoted 10 lines
io_uring/opaque.c +10 -0
+		extent->backing->copied = true;
+		list_add_tail(&extent->list, &op->data->extents);
+		while (written < chunk) {
+			u32 bytes = min_t(u32, chunk - written, PAGE_SIZE);
+			unsigned long left;
+			void *mapped;
+
+			mapped = kmap_local_page(page + (written >> PAGE_SHIFT));
+			left = copy_from_user(mapped, op->addr + done + written, bytes);
+			kunmap_local(mapped);

[Severity: Medium]
Does keeping store->memcg active across copy_from_user() charge the caller's user page faults to store->memcg?

If copy_from_user() faults on unpopulated user pages when store->memcg differs from the calling task's memcg (for instance on an imported store), filemap page-cache allocations and __GFP_ACCOUNT fault allocations such as user page tables are charged to active_memcg() (store->memcg) rather than the faulting task's cgroup, and remain charged after the opaque object is freed. Scoping set_active_memcg(store->memcg) around the kernel allocations (as io_opaque_frame_import() does) would avoid charging user faults to the store.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#16 lore raw

RFC PATCH 11/12 io_uring/opaque: add manual and automatic compaction

In reply to Alex Markuze

Sparse retained receive allocations can cost much more backing capacity than their payload length. Add COMPACT to copy an object into dense backing and publish the replacement under the same handle. Requests already using the old version keep their references. A dense object completes immediately; concurrent compaction of the same object returns -EBUSY.

SET_POLICY configures automatic compaction with a flag, byte rate, burst size and per-copy temporary-backing limit. Preparation snapshots the policy when its SQE is consumed. Updating candidates walks the object table in chunks of 256, dropping the mutex and yielding between chunks. Newly published objects see the new policy immediately; a newer update stops an older walk. Store shutdown ends the update with -ESHUTDOWN.

One delayed work item serializes copies for each store. A run handles up to eight manual requests and one automatic copy. Automatic selection examines up to 32 candidates and skips young, forwarding-only and dense objects. It estimates a nonnegative saving from current charge minus the page-rounded payload length, considering an estimate of at least a quarter of the charge or multiple source extents with zero estimated saving. Selection does not guarantee fewer destination extents or an immediate reduction in retained charge: allocations can fall back to smaller orders, and old versions or shared backing may remain pinned. Rate tokens and a 100-ms scan interval bound automatic work. These rules are implementation heuristics, not ABI guarantees.

Every copy reserves destination capacity under the hard store limit. Publication requires that the handle still name the source version; if FREE or LAST removed it, the replacement is discarded. Compaction never evicts an object. Disabling automatic work preserves accepted manual requests; shutdown completes them and waits for the work item to finish. Run reserve/build, publication and accounting settlement in the existing per-store dispatcher before readiness enqueue. A deferred ring owns only delivery of the decided result, not active accounting or source pins, so independent shared-backing copies cannot be excluded by idle ring task work. Only concurrent compaction of the same slot returns EBUSY.

Prepare whole extent releases before final version zero, including shared versions and releases started before tagging. Retain backing metadata through prepared puts, credit source charge after physical release, and settle credits, unused reservation and transient exclusion coherently. Keep a private published-replacement pin through the handoff. Predicate waitqueues drain already-started frees, not live readers; physical frees, mode updates and wakes occur outside accounting spinlocks.

Failed setup detaches partial tags before returning. Automatic setup failure refunds tokens within the same policy generation and burst. Publication and cancellation share a bounded commit decision; committed copies cannot be retroactively canceled or published twice by task work.

---
 include/uapi/linux/io_uring/opaque.h |   1 +
 io_uring/opaque.c                    | 363 ++++++++++++++++++++++--
 io_uring/opaque.h                    |   6 +
 io_uring/opaque_compact.c            | 394 ++++++++++++++++++++++++++-
 io_uring/opaque_internal.h           |  25 +-
 5 files changed, 757 insertions(+), 32 deletions(-)
include/uapi/linux/io_uring/opaque.h +1 -0
index c04eaed8ce5f..410061906684 100644
@@ -92,6 +92,7 @@ struct io_uring_opaque_frame {
 #define IORING_OPAQUE_OBJECT_F_COMPACTING	(1U << 1)
 #define IORING_OPAQUE_OBJECT_F_FORWARD_ONLY (1U << 2)
 #define IORING_OPAQUE_STREAM_F_EOF		(1U << 0)
+#define IORING_OPAQUE_POLICY_F_AUTO_COMPACT	(1U << 0)
 
 enum io_uring_opaque_memory_mode {
 	IORING_OPAQUE_MEMORY_NORMAL,
io_uring/opaque.c +333 -30

489 lines not on this page · raw message

io_uring/opaque.h +6 -0
index 4001a4484ff9..f63729c19af5 100644
@@ -14,6 +14,7 @@ struct io_uring_opaque_config;
 #ifdef CONFIG_IO_URING_OPAQUE_OBJ
 struct io_opaque_stream;
 struct io_opaque_data;
+struct io_opaque_handoff;
 struct io_opaque_tx;
 struct io_opaque_vec;
 
@@ -74,6 +75,11 @@ struct io_opaque_req {
 		};
 		struct {
 			struct io_opaque_data *replacement;
+			/* Private pin retained after the table takes the replacement. */
+			struct io_opaque_data *published;
+			struct io_opaque_handoff *handoff;
+			bool copy_committed;
+			bool copy_reserved;
 			u64 reserved;
 			u64 transient;
 		};
io_uring/opaque_compact.c +393 -1

409 lines not on this page · raw message

io_uring/opaque_internal.h +24 -1
index 2d5f69ee8925..f27c30d32e13 100644
@@ -7,6 +7,7 @@
 #include <linux/bvec.h>
 #include <linux/net.h>
 #include <linux/sizes.h>
+#include <linux/wait.h>
 #include <linux/workqueue.h>
 #include <uapi/linux/io_uring/opaque.h>
 
@@ -44,8 +45,22 @@
 /* The head of its queue, still to take its references. */
 #define IO_OPAQUE_TX_SETTLE	2
 
+/* One copy's deferred source credits; mutable fields use transient_lock. */
+struct io_opaque_handoff {
+	refcount_t refs;
+	u64 released;
+	unsigned int pending;
+	bool active;
+	wait_queue_head_t wait;
+};
+
 struct io_opaque_backing {
 	refcount_t refs;
+	/* Owns a handoff reference until retagged or physically released. */
+	struct io_opaque_handoff *handoff;
+	/* Prepared extent puts keep metadata alive through physical release. */
+	unsigned int pending;
+	bool released;
 	struct page *page;
 	u64 charge;
 	u32 filled;
@@ -214,7 +229,7 @@ struct io_opaque_store {
 	 * that move bytes and transient together are one seqcount write.
 	 */
 	atomic64_t transient;
-	/* Serializes transient_seq writers. */
+	/* Transient writers, backing handoffs and potential last-version drops. */
 	spinlock_t transient_lock;
 	seqcount_spinlock_t transient_seq;
 	atomic_t extents;
@@ -269,4 +284,12 @@ struct io_opaque_slot *io_opaque_lookup(struct io_opaque_store *store,
 					u64 handle);
 void io_opaque_wait(struct io_opaque_req *op, enum io_opaque_phase phase);
 void io_opaque_queue_ready(struct io_opaque_req *op, int result);
+int io_opaque_compact_reserve(struct io_opaque_req *op, u64 charge);
+int io_opaque_compact_publish(struct io_opaque_req *op);
+void io_opaque_compact_end(struct io_opaque_req *op);
+void io_opaque_compact_work(struct work_struct *work);
+int io_opaque_compact_start(struct io_opaque_req *op);
+int io_opaque_policy_prep(struct io_opaque_req *op);
+int io_opaque_set_policy(struct io_opaque_req *op);
+
 #endif
Signature · 1 line
2.34.1
#17 lore raw

RFC PATCH 12/12 io_uring/opaque: add basic KUnit tests

In reply to Alex Markuze

Check receive-budget admission and watermark transitions, then build a page-backed immutable version and check its vector, payload, held version reference and final backing/reference release.

Use existing internal helpers without adding production test hooks. These are basic helper checks; the matching liburing example exercises a real ring and loopback TCP connection.

---
 io_uring/Kconfig       |  10 ++++
 io_uring/Makefile      |   1 +
 io_uring/opaque_test.c | 128 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 139 insertions(+)
 create mode 100644 io_uring/opaque_test.c
io_uring/Kconfig +10 -0
index 5b696cf266f6..db6e3c5a317d 100644
@@ -30,3 +30,13 @@ config IO_URING_BPF_OPS
 	def_bool y
 	depends on IO_URING
 	depends on BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
+config IO_URING_OPAQUE_OBJ_KUNIT_TEST
+	bool "KUnit smoke tests for opaque objects" if !KUNIT_ALL_TESTS
+	depends on KUNIT=y && IO_URING_OPAQUE_OBJ
+	default KUNIT_ALL_TESTS
+	help
+	  Check receive-budget admission and watermark transitions, and the
+	  vector representation and reference lifetime of an immutable version.
+	  The tests call internal helpers without a userspace ring or TCP socket.
+	  They are a small smoke test, not a pressure or concurrency suite.
io_uring/Makefile +1 -0
index 912b1861c0a5..b7fcc2d3c714 100644
@@ -18,6 +18,7 @@ obj-$(CONFIG_IO_URING)		+= io_uring.o opdef.o kbuf.o rsrc.o notif.o \
 
 obj-$(CONFIG_IO_URING_ZCRX)	+= zcrx.o
 obj-$(CONFIG_IO_URING_OPAQUE_OBJ)	+= opaque.o opaque_register.o opaque_compact.o
+obj-$(CONFIG_IO_URING_OPAQUE_OBJ_KUNIT_TEST) += opaque_test.o
 obj-$(CONFIG_IO_WQ)		+= io-wq.o
 obj-$(CONFIG_FUTEX)		+= futex.o
 obj-$(CONFIG_EPOLL)		+= epoll.o
io_uring/opaque_test.c new file +128 -0

128 lines not on this page · raw message

Signature · 1 line
2.34.1