GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — IoUring: Fix the recvmmsg emulation (#17187) · netty/netty@e8486ef

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • transport-classes-io_uring/src/main/java/io/netty/channel/uring
    • AbstractIoUringChannel.java
    • IoUringDatagramChannel.java
    • IoUringIoHandler.java
    • Native.java
    • NativeStaticallyReferencedJniMethods.java
  • transport-native-io_uring/src
    • main/c
      • netty_io_uring_native.c
    • test/java/io/netty/channel/uring
      • IoUringDatagramHardlinkTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎transport-classes-io_uring/src/main/java/io/netty/channel/uring/AbstractIoUringChannel.java‎

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/AbstractIoUringChannel.java
+4-5Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -757,13 +757,12 @@ private void readComplete(byte op, int res, int flags, short data) {
757757

758758
boolean multishot = isReadMultishot();
759759
boolean rearm = (flags & Native.IORING_CQE_F_MORE) == 0;
760-
if (rearm) {
761-
// Reset READ_SCHEDULED if there is nothing more to handle and so we need to re-arm. This works for
762-
// multi-shot and non multi-shot variants.
763-
ioState &= ~READ_SCHEDULED;
764-
}
765760
boolean pending = readPending;
766761
if (multishot) {
762+
if (rearm) {
763+
// Reset READ_SCHEDULED if there is nothing more to handle and so we need to re-arm.
764+
ioState &= ~READ_SCHEDULED;
765+
}
767766
// Reset readPending so we can still keep track if we might need to cancel the multi-shot read or
768767
// not.
769768
readPending = false;
Collapse file

‎transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringDatagramChannel.java‎

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringDatagramChannel.java
+8-5Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,8 @@ protected void readComplete0(byte op, int res, int flags, short data, int outsta
471471
@Override
472472
protected int scheduleRead0(boolean first, boolean socketIsEmpty) {
473473
final IoUringRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
474+
IoUringIoHandler ioUringIoHandler = registration().attachment();
475+
int submissionQueueRemaining = ioUringIoHandler.submitIfFullAndGetRemaining();
474476
ByteBuf byteBuf = allocHandle.allocate(alloc());
475477
assert readBuffer == null;
476478
readBuffer = byteBuf;
@@ -480,7 +482,7 @@ protected int scheduleRead0(boolean first, boolean socketIsEmpty) {
480482
int datagramSize = ((IoUringDatagramChannelConfig) config()).getMaxDatagramPayloadSize();
481483

482484
int numDatagram = datagramSize == 0 ? 1 : Math.max(1, byteBuf.writableBytes() / datagramSize);
483-
485+
numDatagram = Math.min(Math.min(submissionQueueRemaining, recvmsgHdrs.capacity()), numDatagram);
484486
int scheduled = scheduleRecvmsg(byteBuf, numDatagram, datagramSize);
485487
if (scheduled == 0) {
486488
// We could not schedule any recvmmsg so we need to release the buffer as there will be no
@@ -495,12 +497,12 @@ private int scheduleRecvmsg(ByteBuf byteBuf, int numDatagram, int datagramSize)
495497
int writable = byteBuf.writableBytes();
496498
long bufferAddress = IoUring.memoryAddress(byteBuf) + byteBuf.writerIndex();
497499
if (numDatagram <= 1) {
498-
return scheduleRecvmsg0(bufferAddress, writable, true) ? 1 : 0;
500+
return scheduleRecvmsg0(bufferAddress, writable, true, false) ? 1 : 0;
499501
}
500502
int i = 0;
501503
// Add multiple IORING_OP_RECVMSG to the submission queue. This basically emulates recvmmsg(...)
502504
for (; i < numDatagram && writable >= datagramSize; i++) {
503-
if (!scheduleRecvmsg0(bufferAddress, datagramSize, i == 0)) {
505+
if (!scheduleRecvmsg0(bufferAddress, datagramSize, i == 0, i + 1 < numDatagram)) {
504506
break;
505507
}
506508
bufferAddress += datagramSize;
@@ -509,7 +511,7 @@ private int scheduleRecvmsg(ByteBuf byteBuf, int numDatagram, int datagramSize)
509511
return i;
510512
}
511513

512-
private boolean scheduleRecvmsg0(long bufferAddress, int bufferLength, boolean first) {
514+
private boolean scheduleRecvmsg0(long bufferAddress, int bufferLength, boolean first, boolean more) {
513515
MsgHdrMemory msgHdrMemory = recvmsgHdrs.nextHdr();
514516
if (msgHdrMemory == null) {
515517
// We can not continue reading before we did not submit the recvmsg(s) and received the results.
@@ -519,11 +521,12 @@ private boolean scheduleRecvmsg0(long bufferAddress, int bufferLength, boolean f
519521

520522
int fd = fd().intValue();
521523
int msgFlags = first ? 0 : Native.MSG_DONTWAIT;
524+
int sqeFlags = more ? Native.IOSQE_HARDLINK : 0;
522525
IoRegistration registration = registration();
523526
// We always use idx here so we can detect if no idx was used by checking if data < 0 in
524527
// readComplete0(...)
525528
IoUringIoOps ops = IoUringIoOps.newRecvmsg(
526-
fd, (byte) 0, msgFlags, msgHdrMemory.address(), msgHdrMemory.idx());
529+
fd, (byte) sqeFlags, msgFlags, msgHdrMemory.address(), msgHdrMemory.idx());
527530
long id = registration.submit(ops);
528531
if (id == 0) {
529532
// Submission failed we don't used the MsgHdrMemory and so should give it back.
Collapse file

‎transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringIoHandler.java‎

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringIoHandler.java
+10Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,16 @@ public int run(IoHandlerContext context) {
190190
return ioCompletions;
191191
}
192192

193+
int submitIfFullAndGetRemaining() {
194+
SubmissionQueue submissionQueue = ringBuffer.ioUringSubmissionQueue();
195+
if (submissionQueue.remaining() == 0) {
196+
if (submitAndClearNow(submissionQueue) == 0) {
197+
throw new IllegalStateException("Submission queue is full and no submissions were accepted");
198+
}
199+
}
200+
return submissionQueue.remaining();
201+
}
202+
193203
private boolean needSubmit(int sqFlags) {
194204
SubmissionQueue submissionQueue = ringBuffer.ioUringSubmissionQueue();
195205
return submissionQueue.count() > 0
Collapse file

‎transport-classes-io_uring/src/main/java/io/netty/channel/uring/Native.java‎

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/Native.java
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ static String opToStr(byte op) {
320320
static final int IORING_ENTER_NO_IOWAIT = 1 << 7;
321321
static final int IOSQE_ASYNC = NativeStaticallyReferencedJniMethods.iosqeAsync();
322322
static final int IOSQE_LINK = NativeStaticallyReferencedJniMethods.iosqeLink();
323+
static final int IOSQE_HARDLINK = NativeStaticallyReferencedJniMethods.iosqeHardlink();
323324
static final int IOSQE_IO_DRAIN = NativeStaticallyReferencedJniMethods.iosqeDrain();
324325
static final int IOSQE_BUFFER_SELECT = NativeStaticallyReferencedJniMethods.iosqeBufferSelect();
325326
static final int IOSQE_CQE_SKIP_SUCCESS = 1 << 6;
Collapse file

‎transport-classes-io_uring/src/main/java/io/netty/channel/uring/NativeStaticallyReferencedJniMethods.java‎

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/NativeStaticallyReferencedJniMethods.java
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ private NativeStaticallyReferencedJniMethods() { }
7474
static native int ioringEnterGetevents();
7575
static native int iosqeAsync();
7676
static native int iosqeLink();
77+
static native int iosqeHardlink();
7778
static native int iosqeDrain();
7879
static native int msgDontwait();
7980
static native int iosqeBufferSelect();
Collapse file

‎transport-native-io_uring/src/main/c/netty_io_uring_native.c‎

Copy file name to clipboardExpand all lines: transport-native-io_uring/src/main/c/netty_io_uring_native.c
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,10 @@ static jint netty_io_uring_iosqeLink(JNIEnv* env, jclass clazz) {
738738
return IOSQE_IO_LINK;
739739
}
740740

741+
static jint netty_io_uring_iosqeHardlink(JNIEnv* env, jclass clazz) {
742+
return IOSQE_IO_HARDLINK;
743+
}
744+
741745
static jint netty_io_uring_iosqeDrain(JNIEnv* env, jclass clazz) {
742746
return IOSQE_IO_DRAIN;
743747
}
@@ -842,6 +846,7 @@ static const JNINativeMethod statically_referenced_fixed_method_table[] = {
842846
{ "ioringEnterGetevents", "()I", (void *) netty_io_uring_ioringEnterGetevents },
843847
{ "iosqeAsync", "()I", (void *) netty_io_uring_iosqeAsync },
844848
{ "iosqeLink", "()I", (void *) netty_io_uring_iosqeLink },
849+
{ "iosqeHardlink", "()I", (void *) netty_io_uring_iosqeHardlink },
845850
{ "iosqeDrain", "()I", (void *) netty_io_uring_iosqeDrain },
846851
{ "iosqeBufferSelect", "()I", (void *) netty_io_uring_BufferSelect },
847852
{ "msgDontwait", "()I", (void *) netty_io_uring_msgDontwait },
Collapse file

‎transport-native-io_uring/src/test/java/io/netty/channel/uring/IoUringDatagramHardlinkTest.java‎

Copy file name to clipboard
+261Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.channel.uring;
17+
18+
import io.netty.bootstrap.Bootstrap;
19+
import io.netty.channel.Channel;
20+
import io.netty.channel.ChannelHandlerContext;
21+
import io.netty.channel.ChannelInboundHandlerAdapter;
22+
import io.netty.channel.ChannelOption;
23+
import io.netty.channel.FixedRecvByteBufAllocator;
24+
import io.netty.channel.IoEvent;
25+
import io.netty.channel.IoHandle;
26+
import io.netty.channel.IoHandler;
27+
import io.netty.channel.IoHandlerContext;
28+
import io.netty.channel.IoHandlerFactory;
29+
import io.netty.channel.IoRegistration;
30+
import io.netty.channel.MultiThreadIoEventLoopGroup;
31+
import io.netty.channel.socket.DatagramPacket;
32+
import io.netty.channel.socket.SocketProtocolFamily;
33+
import io.netty.util.NetUtil;
34+
import io.netty.util.concurrent.ThreadAwareExecutor;
35+
import org.junit.jupiter.api.BeforeAll;
36+
import org.junit.jupiter.api.Test;
37+
import org.junit.jupiter.api.Timeout;
38+
39+
import java.net.InetSocketAddress;
40+
import java.util.ArrayList;
41+
import java.util.Arrays;
42+
import java.util.List;
43+
import java.util.concurrent.TimeUnit;
44+
45+
import static io.netty.channel.unix.Errors.ERRNO_EAGAIN_NEGATIVE;
46+
import static io.netty.channel.unix.Errors.ERRNO_EBADF_NEGATIVE;
47+
import static org.junit.jupiter.api.Assertions.assertEquals;
48+
import static org.junit.jupiter.api.Assertions.assertFalse;
49+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
50+
51+
@Timeout(value = 1, unit = TimeUnit.MINUTES)
52+
public class IoUringDatagramHardlinkTest {
53+
54+
private static final int DATAGRAM_SIZE = 512;
55+
private static final int BATCH_SIZE = 4;
56+
57+
@BeforeAll
58+
public static void loadJNI() {
59+
assumeTrue(IoUring.isAvailable());
60+
}
61+
62+
@Test
63+
public void testRecvmmsgHardlinkOrder() throws Exception {
64+
CompletionRecorder recorder = new CompletionRecorder();
65+
IoHandlerFactory factory = executor -> new RecordingIoUringIoHandler(
66+
IoUringIoHandler.newFactory().newHandler(executor), recorder);
67+
MultiThreadIoEventLoopGroup group = new MultiThreadIoEventLoopGroup(1, factory);
68+
Channel receiver = null;
69+
Channel sender = null;
70+
try {
71+
receiver = newBootstrap(group)
72+
.handler(new ChannelInboundHandlerAdapter())
73+
.bind(new InetSocketAddress(NetUtil.LOCALHOST4, 0))
74+
.sync()
75+
.channel();
76+
77+
sender = new Bootstrap()
78+
.group(group)
79+
.channelFactory(() -> new IoUringDatagramChannel(SocketProtocolFamily.INET))
80+
.handler(new ChannelInboundHandlerAdapter())
81+
.bind(new InetSocketAddress(NetUtil.LOCALHOST4, 0))
82+
.sync()
83+
.channel();
84+
85+
// The hard linked recvmsg chain must park as a whole. Without hard linking the
86+
// MSG_DONTWAIT recvmsg ops would already have completed with EAGAIN here.
87+
Thread.sleep(100);
88+
assertEquals(0, recorder.size());
89+
90+
sender.writeAndFlush(new DatagramPacket(
91+
sender.alloc().buffer(DATAGRAM_SIZE).writeZero(DATAGRAM_SIZE),
92+
(InetSocketAddress) receiver.localAddress())).sync();
93+
recorder.await(BATCH_SIZE);
94+
95+
assertEquals(Arrays.asList(
96+
DATAGRAM_SIZE,
97+
ERRNO_EAGAIN_NEGATIVE,
98+
ERRNO_EAGAIN_NEGATIVE,
99+
ERRNO_EAGAIN_NEGATIVE), recorder.completions());
100+
} finally {
101+
if (sender != null) {
102+
sender.close().syncUninterruptibly();
103+
}
104+
if (receiver != null) {
105+
receiver.close().syncUninterruptibly();
106+
}
107+
group.shutdownGracefully().syncUninterruptibly();
108+
}
109+
}
110+
111+
@Test
112+
public void testClosePendingRecvmmsgHardlink() throws Exception {
113+
CompletionRecorder recorder = new CompletionRecorder();
114+
IoHandlerFactory factory = executor -> new RecordingIoUringIoHandler(
115+
IoUringIoHandler.newFactory().newHandler(executor), recorder);
116+
MultiThreadIoEventLoopGroup group = new MultiThreadIoEventLoopGroup(1, factory);
117+
Channel receiver = null;
118+
Channel sender = null;
119+
try {
120+
receiver = newBootstrap(group)
121+
.handler(new ChannelInboundHandlerAdapter())
122+
.bind(new InetSocketAddress(NetUtil.LOCALHOST4, 0))
123+
.sync()
124+
.channel();
125+
126+
sender = new Bootstrap()
127+
.group(group)
128+
.channelFactory(() -> new IoUringDatagramChannel(SocketProtocolFamily.INET))
129+
.handler(new ChannelInboundHandlerAdapter())
130+
.bind(new InetSocketAddress(NetUtil.LOCALHOST4, 0))
131+
.sync()
132+
.channel();
133+
134+
// Let the read loop schedule the first batch and the AUTO_READ re-scheduled batch.
135+
Thread.sleep(100);
136+
assertEquals(0, recorder.size());
137+
138+
sender.writeAndFlush(new DatagramPacket(
139+
sender.alloc().buffer(DATAGRAM_SIZE).writeZero(DATAGRAM_SIZE),
140+
(InetSocketAddress) receiver.localAddress())).sync();
141+
recorder.await(BATCH_SIZE);
142+
143+
// Close while the re-scheduled (hard linked) batch is still pending. Without the fix in
144+
// readComplete(...) the fd would be closed before all recvmsg ops completed and so some
145+
// of them would complete with EBADF.
146+
receiver.close().syncUninterruptibly();
147+
recorder.await(BATCH_SIZE * 2);
148+
149+
assertFalse(recorder.completions().contains(ERRNO_EBADF_NEGATIVE), recorder.completions().toString());
150+
} finally {
151+
if (sender != null) {
152+
sender.close().syncUninterruptibly();
153+
}
154+
if (receiver != null) {
155+
receiver.close().syncUninterruptibly();
156+
}
157+
group.shutdownGracefully().syncUninterruptibly();
158+
}
159+
}
160+
161+
private static Bootstrap newBootstrap(MultiThreadIoEventLoopGroup group) {
162+
return new Bootstrap()
163+
.group(group)
164+
.channelFactory(() -> new IoUringDatagramChannel(SocketProtocolFamily.INET))
165+
.option(ChannelOption.RECVBUF_ALLOCATOR,
166+
new FixedRecvByteBufAllocator(BATCH_SIZE * DATAGRAM_SIZE))
167+
.option(IoUringChannelOption.MAX_DATAGRAM_PAYLOAD_SIZE, DATAGRAM_SIZE);
168+
}
169+
170+
private static final class CompletionRecorder {
171+
private final List<Integer> completions = new ArrayList<Integer>();
172+
173+
synchronized void record(IoUringIoEvent event) {
174+
if (event.opcode() == Native.IORING_OP_RECVMSG) {
175+
completions.add(event.res());
176+
notifyAll();
177+
}
178+
}
179+
180+
synchronized int size() {
181+
return completions.size();
182+
}
183+
184+
synchronized List<Integer> completions() {
185+
return new ArrayList<Integer>(completions);
186+
}
187+
188+
synchronized void await(int count) throws InterruptedException {
189+
while (completions.size() < count) {
190+
wait();
191+
}
192+
}
193+
}
194+
195+
private static final class RecordingIoUringIoHandler implements IoHandler {
196+
private final IoHandler delegate;
197+
private final CompletionRecorder recorder;
198+
199+
RecordingIoUringIoHandler(IoHandler delegate, CompletionRecorder recorder) {
200+
this.delegate = delegate;
201+
this.recorder = recorder;
202+
}
203+
204+
@Override
205+
public void initialize() {
206+
delegate.initialize();
207+
}
208+
209+
@Override
210+
public int run(IoHandlerContext context) {
211+
return delegate.run(context);
212+
}
213+
214+
@Override
215+
public void prepareToDestroy() {
216+
delegate.prepareToDestroy();
217+
}
218+
219+
@Override
220+
public void destroy() {
221+
delegate.destroy();
222+
}
223+
224+
@Override
225+
public IoRegistration register(IoHandle handle) throws Exception {
226+
IoUringIoHandle ioHandle = (IoUringIoHandle) handle;
227+
return delegate.register(new IoUringIoHandle() {
228+
@Override
229+
public void handle(IoRegistration registration, IoEvent event) {
230+
recorder.record((IoUringIoEvent) event);
231+
ioHandle.handle(registration, event);
232+
}
233+
234+
@Override
235+
public void registered() {
236+
ioHandle.registered();
237+
}
238+
239+
@Override
240+
public void unregistered() {
241+
ioHandle.unregistered();
242+
}
243+
244+
@Override
245+
public void close() throws Exception {
246+
ioHandle.close();
247+
}
248+
});
249+
}
250+
251+
@Override
252+
public void wakeup() {
253+
delegate.wakeup();
254+
}
255+
256+
@Override
257+
public boolean isCompatible(Class<? extends IoHandle> handleType) {
258+
return delegate.isCompatible(handleType);
259+
}
260+
}
261+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.