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:Refactor io_uring write lifecycle management (#17757) · netty/netty@77077ff

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
      • AbstractIoUringStreamChannel.java
      • IoUringDatagramChannel.java
      • IoUringDomainSocketChannel.java
      • IoUringIoHandler.java
      • IoUringSocketChannel.java
      • IovArrayReferenceCollector.java
      • MsgHdr.java
      • MsgHdrMemory.java
      • Native.java
      • PendingZeroCopyWrites.java
      • WriteOperation.java
      • WriteOperationTracker.java
      • WriteOpsSnapshot.java
    • test/java/io/netty/channel/uring
      • PendingZeroCopyWritesTest.java
      • WriteOperationTest.java
  • transport-native-io_uring/src
    • main/c
      • netty_io_uring_native.c
    • test/java/io/netty/channel/uring
      • AbstractWriteOperationTrackerTest.java
      • IovArrayReferenceCollectorTest.java
      • IovBufferCollectorTest.java
      • WriteOperationTrackerOverflowTest.java
      • WriteOperationTrackerTest.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
+128-71Lines changed: 128 additions & 71 deletions
Large diffs are not rendered by default.
Collapse file

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

Copy file name to clipboardExpand all lines: transport-classes-io_uring/src/main/java/io/netty/channel/uring/AbstractIoUringStreamChannel.java
+97-52Lines changed: 97 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
import java.net.SocketAddress;
4040
import java.nio.ByteBuffer;
4141
import java.nio.channels.WritableByteChannel;
42+
import java.util.ArrayList;
43+
import java.util.Collections;
44+
import java.util.List;
4245

4346
import static io.netty.channel.unix.Errors.ioResult;
4447

@@ -254,6 +257,57 @@ protected Object filterOutboundMessage(Object msg) {
254257
return super.filterOutboundMessage(msg);
255258
}
256259

260+
/**
261+
* Collects and retains the messages backing a submitted iov prefix. Keep the non-empty NIO segment
262+
* counting aligned with {@link IovArray#add(ByteBuf, int, int)}. The readable ranges must still match
263+
* those used at submission; the shared iov memory itself may already have been reused.
264+
*/
265+
static final class IovBufferCollector implements ChannelOutboundBuffer.MessageProcessor {
266+
private List<ReferenceCounted> buffers;
267+
private int remaining;
268+
269+
List<ReferenceCounted> collect(ChannelOutboundBuffer buffer, int count) {
270+
if (count == 0) {
271+
return Collections.emptyList();
272+
}
273+
ByteBuf first = (ByteBuf) buffer.current();
274+
// A single message or iov only needs one retained owner, even for a partial composite write.
275+
if (buffer.size() == 1 || count == 1 && first.isReadable()) {
276+
return Collections.<ReferenceCounted>singletonList(first.retain());
277+
}
278+
buffers = new ArrayList<>(Math.min(count, buffer.size()));
279+
remaining = count;
280+
try {
281+
buffer.forEachFlushedMessage(this);
282+
return buffers;
283+
} catch (Exception e) {
284+
throw new IllegalStateException(e);
285+
}
286+
}
287+
288+
@Override
289+
public boolean processMessage(Object msg) {
290+
ByteBuf buf = (ByteBuf) msg;
291+
if (buf.isReadable()) {
292+
buffers.add(buf.retain());
293+
remaining = remainingIovs(buf, remaining);
294+
}
295+
return remaining != 0;
296+
}
297+
298+
static int remainingIovs(ByteBuf buf, int remaining) {
299+
if (buf.nioBufferCount() == 1) {
300+
return remaining - 1;
301+
}
302+
for (ByteBuffer nioBuffer : buf.nioBuffers(buf.readerIndex(), buf.readableBytes())) {
303+
if (nioBuffer.remaining() != 0 && --remaining == 0) {
304+
break;
305+
}
306+
}
307+
return remaining;
308+
}
309+
}
310+
257311
protected class IoUringStreamUnsafe extends AbstractUringUnsafe {
258312

259313
private ByteBuf readBuffer;
@@ -271,39 +325,27 @@ protected int scheduleWriteMultiple(ChannelOutboundBuffer in) {
271325
IovArray iovArray = handler.iovArray();
272326
int offset = iovArray.count();
273327

274-
IovArrayReferenceCollector collector = handler.iovArrayReferenceCollector();
275328
try {
276-
try {
277-
in.forEachFlushedMessage(filterWriteMultiple(collector));
278-
} catch (Exception e) {
279-
// This should never happen, anyway fallback to single write.
280-
return scheduleWriteSingle(in.current());
281-
}
282-
long iovArrayAddress = iovArray.memoryAddress(offset);
283-
int iovArrayLength = iovArray.count() - offset;
284-
// Should not use sendmsg_zc, just use normal writev.
285-
IoUringIoOps ops = IoUringIoOps.newWritev(
286-
fd, (byte) 0, 0, iovArrayAddress, iovArrayLength, nextOpsId());
287-
288-
byte opCode = ops.opcode();
289-
// record(...) copies the collector's references into the slot, so the collector stays reusable.
290-
writeTracker.recordStream(opCode, collector.referencesArray(), collector.referencesCount());
291-
writeId = registration.submit(ops);
292-
writeOpCode = opCode;
293-
if (writeId == 0) {
294-
writeTracker.abandonStream();
295-
return 0;
296-
}
297-
return 1;
298-
} finally {
299-
// The slot copied the references it needs, and an exception must not leave the event loop's
300-
// shared collector holding this write's buffers.
301-
collector.reset();
329+
in.forEachFlushedMessage(filterWriteMultiple(iovArray));
330+
} catch (Exception e) {
331+
// This should never happen, anyway fallback to single write.
332+
return scheduleWriteSingle(in.current());
302333
}
334+
long iovArrayAddress = iovArray.memoryAddress(offset);
335+
int iovArrayLength = iovArray.count() - offset;
336+
// Should not use sendmsg_zc, just use normal writev.
337+
IoUringIoOps ops = IoUringIoOps.newWritev(fd, (byte) 0, 0, iovArrayAddress, iovArrayLength, nextOpsId());
338+
byte opCode = ops.opcode();
339+
writeId = submitWrite(ops);
340+
writeOpCode = opCode;
341+
if (writeId == 0) {
342+
return 0;
343+
}
344+
return 1;
303345
}
304346

305-
protected ChannelOutboundBuffer.MessageProcessor filterWriteMultiple(IovArrayReferenceCollector collector) {
306-
return collector;
347+
protected ChannelOutboundBuffer.MessageProcessor filterWriteMultiple(IovArray iovArray) {
348+
return iovArray;
307349
}
308350

309351
@Override
@@ -331,15 +373,9 @@ protected int scheduleWriteSingle(Object msg) {
331373
ops = IoUringIoOps.newSend(fd, (byte) 0, 0, address, length, nextOpsId());
332374
}
333375
byte opCode = ops.opcode();
334-
// A splice picks its own data to tell its two stages apart, so it never enters the channel-level
335-
// slot array used for zero-copy writes. It still has to occupy this single slot though: the file and
336-
// pipe descriptors it splices between have to outlive the SQE, and writeTracker.retainAll()
337-
// only retains what was recorded here.
338-
writeTracker.recordStream(opCode, (ReferenceCounted) msg);
339-
writeId = registration.submit(ops);
376+
writeId = submitWrite(ops);
340377
writeOpCode = opCode;
341378
if (writeId == 0) {
342-
writeTracker.abandonStream();
343379
return 0;
344380
}
345381
return 1;
@@ -389,19 +425,32 @@ private int scheduleWriteFileRegion(int fd, IoRegistration registration, FileReg
389425
long address = IoUring.memoryAddress(buf) + buf.readerIndex();
390426
int length = buf.readableBytes();
391427
IoUringIoOps ops = IoUringIoOps.newSend(fd, (byte) 0, 0, address, length, nextOpsId());
392-
byte opCode = ops.opcode();
393-
writeTracker.recordStream(opCode, buf);
394-
writeId = registration.submit(ops);
395-
writeOpCode = opCode;
396-
if (writeId == 0) {
397-
writeTracker.abandonStream();
398-
// Submission only fails when the registration is no longer valid (channel is
399-
// being deregistered). Ending the slot above is the only cleanup needed here:
400-
// unregistered() will release fileRegionChunkBuf and the outbound buffer will
401-
// release the FileRegion -- mirroring the plain ByteBuf path above.
402-
return 0;
428+
try {
429+
byte opCode = ops.opcode();
430+
writeId = submitWrite(ops);
431+
writeOpCode = opCode;
432+
if (writeId == 0) {
433+
return 0;
434+
}
435+
return 1;
436+
} finally {
437+
if (writeId == 0) {
438+
releaseFileRegionChunkBuf();
439+
}
403440
}
404-
return 1;
441+
}
442+
443+
@Override
444+
List<ReferenceCounted> retainWriteBuffers(ChannelOutboundBuffer buffer) {
445+
if (currentWrite.opcode() == Native.IORING_OP_WRITEV) {
446+
return new IovBufferCollector().collect(buffer, currentWrite.len());
447+
}
448+
Object msg = buffer.current();
449+
// A generic FileRegion owns an independent chunk buffer until its SEND completes.
450+
if (msg instanceof ByteBuf || msg instanceof IoUringFileRegion) {
451+
return Collections.singletonList(((ReferenceCounted) msg).retain());
452+
}
453+
return Collections.emptyList();
405454
}
406455

407456
private int calculateRecvFlags(boolean first) {
@@ -702,8 +751,6 @@ boolean writeComplete0(byte op, int res, int flags, long data, int outstanding)
702751
// See https://man7.org/linux/man-pages/man2/io_uring_enter.2.html section: IORING_OP_SEND_ZC
703752
writeId = 0;
704753
writeOpCode = 0;
705-
// A completion that never went through the slot finds it inactive, which makes this a no-op.
706-
writeTracker.completeStream(flags);
707754
}
708755
ChannelOutboundBuffer channelOutboundBuffer = unsafe().outboundBuffer();
709756
if (channelOutboundBuffer == null) {
@@ -790,8 +837,6 @@ private void releaseFileRegionChunkBuf() {
790837

791838
@Override
792839
public void unregistered() {
793-
// Abandons the single slot through writeTracker.releaseAll() before the chunk buffer is
794-
// dropped below, so a reference a shutdown retained on that buffer is released first.
795840
super.unregistered();
796841
assert readBuffer == null;
797842
releaseFileRegionChunkBuf();
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
+49-21Lines changed: 49 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
import io.netty.channel.unix.Errors.NativeIoException;
3434
import io.netty.channel.unix.SegmentedDatagramPacket;
3535
import io.netty.channel.unix.Socket;
36+
import io.netty.util.ReferenceCountUtil;
37+
import io.netty.util.ReferenceCounted;
3638
import io.netty.util.UncheckedBooleanSupplier;
3739
import io.netty.util.internal.ObjectUtil;
3840
import io.netty.util.internal.StringUtil;
@@ -49,6 +51,8 @@
4951
import java.net.SocketAddress;
5052
import java.net.SocketException;
5153
import java.nio.channels.UnresolvedAddressException;
54+
import java.util.ArrayList;
55+
import java.util.List;
5256

5357
import static io.netty.channel.unix.Errors.ioResult;
5458

@@ -560,9 +564,8 @@ boolean writeComplete0(byte op, int res, int flags, long data, int outstanding)
560564
int numWritten = sendmsgHdrs.length();
561565
sendmsgHdrs.clear();
562566
ChannelOutboundBuffer outboundBuffer = outboundBuffer();
563-
if (outboundBuffer == null) {
564-
// The completion may arrive after close() or shutdownOutput() already dropped the
565-
// outbound buffer.
567+
if (retainedWriteBuffers != null) {
568+
// Close, shutdownOutput() or an inactive flush may already have failed this batch.
566569
return true;
567570
}
568571
for (int i = 0; i < numWritten; i++) {
@@ -631,35 +634,60 @@ private boolean scheduleWrite(Object msg, boolean first) {
631634
}
632635

633636
long bufferAddress = IoUring.memoryAddress(data) + data.readerIndex();
634-
return scheduleSendmsg(data, remoteAddress, bufferAddress, data.readableBytes(), segmentSize, first);
637+
return scheduleSendmsg(remoteAddress, bufferAddress, data.readableBytes(), segmentSize, first);
635638
}
636639

637-
private boolean scheduleSendmsg(ByteBuf data, InetSocketAddress remoteAddress, long bufferAddress,
640+
private boolean scheduleSendmsg(InetSocketAddress remoteAddress, long bufferAddress,
638641
int bufferLength, int segmentSize, boolean first) {
639642
MsgHdrMemory hdr = sendmsgHdrs.nextHdr();
640643
if (hdr == null) {
641644
// There is no MsgHdrMemory left to use. We need to submit and wait for the writes to complete
642645
// before we can write again.
643646
return false;
644647
}
645-
hdr.set(socket, remoteAddress, bufferAddress, bufferLength, (short) segmentSize);
648+
long id = 0;
649+
try {
650+
hdr.set(socket, remoteAddress, bufferAddress, bufferLength, (short) segmentSize);
651+
int msgFlags = first ? 0 : Native.MSG_DONTWAIT;
652+
IoUringIoOps ops = IoUringIoOps.newSendmsg(
653+
fd().intValue(), (byte) 0, msgFlags, hdr.address(), hdr.idx());
654+
id = submitWrite(ops);
655+
if (id == 0) {
656+
return false;
657+
}
658+
sendmsgHdrs.setId(hdr.idx(), id);
659+
return true;
660+
} finally {
661+
if (id == 0) {
662+
sendmsgHdrs.restoreNextHdr(hdr);
663+
}
664+
}
665+
}
646666

647-
int fd = fd().intValue();
648-
int msgFlags = first ? 0 : Native.MSG_DONTWAIT;
649-
IoRegistration registration = registration();
650-
IoUringIoOps ops = IoUringIoOps.newSendmsg(fd, (byte) 0, msgFlags, hdr.address(), hdr.idx());
651-
short opsId = hdr.idx();
652-
// The id is the MsgHdrMemoryArray index, which that array allocates and recycles itself.
653-
writeTracker.recordForeign(opsId, ops.opcode(), data);
654-
long id = registration.submit(ops);
655-
if (id == 0) {
656-
// Submission failed we don't used the MsgHdrMemory and so should give it back.
657-
sendmsgHdrs.restoreNextHdr(hdr);
658-
writeTracker.abandon(opsId, ops.opcode());
659-
return false;
667+
@Override
668+
List<ReferenceCounted> retainWriteBuffers(ChannelOutboundBuffer buffer) {
669+
final int count = (int) currentWrite.userData() + 1;
670+
final List<ReferenceCounted> buffers = new ArrayList<>(count);
671+
try {
672+
buffer.forEachFlushedMessage(new ChannelOutboundBuffer.MessageProcessor() {
673+
@Override
674+
public boolean processMessage(Object msg) {
675+
int index = buffers.size();
676+
buffers.add(sendmsgHdrs.id(index) != MsgHdrMemoryArray.NO_ID ?
677+
((ReferenceCounted) msg).retain() : null);
678+
return buffers.size() < count;
679+
}
680+
});
681+
} catch (Exception e) {
682+
throw new IllegalStateException(e);
660683
}
661-
sendmsgHdrs.setId(hdr.idx(), id);
662-
return true;
684+
return buffers;
685+
}
686+
687+
@Override
688+
void releaseWriteBuffers(List<ReferenceCounted> buffers, long data) {
689+
// Batched SENDMSG requests may complete out of order; clear and release only the slot indexed by data.
690+
ReferenceCountUtil.safeRelease(buffers.set((int) data, null));
663691
}
664692

665693
@Override

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.