GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — io_uring: do not release write memory that the kernel still owns by HwangRock · Pull Request #17238 · netty/netty Conversation
|
| ops/s | B/op | |
|---|---|---|
| stream single send | 150.8M ± 0.6M | 0 |
| stream writev 4 | 21.5M ± 0.03M | 0 |
| stream writev 16 | 8.2M ± 0.3M | 0 |
| send_zc round trip | 93.8M ± 0.4M | 0 |
| datagram sendmsg | 119.5M ± 0.6M | 0 |
64 byte pooled direct buffers, single thread, M1, 99.9% confidence. Nothing allocates per write. Dropping the arraycopy in record(byte, ReferenceCounted[], int) measures 27% at 4 iovecs and 6% at 16, but that copy is what lets one collector be shared across an event loop, so I kept it. The benchmark is not in this PR. I have it and can add it if that is useful.
One gap I left open: the domain-socket fd-passing sendmsg is not registered as a write operation, so it relies on MsgHdrMemory.idx() being 0 and nextOpsId() never handing 0 out. That holds today and nothing enforces it. I can register it as well if you would rather have the invariant explicit.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
/cc @dreamlike-ocean |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
It looks like the issue stems from AbstractChannel’s model being designed for readiness-based transports. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
It seems there may still be an issue. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@dreamlike-ocean I think so too — this PR doesn't close that window.
I left it out because the fix lands in
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Yeah, I agree too NPEs and leaks are just signs I don't think we need to delay the shutdown - its when we should release the memory correctly I've little io uring/netty exp but maybe we can let the outstanding buffer(s) drain async as the notifications come in So essentially ChannelOutboundBuffer might need to be decoupled so the memory isn’t reused accidentally |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
e8fd3ff to
1169bab
Compare
|
@chris-mcc Agreed, that's the right direction — the shutdown itself doesn't need to be delayed; the submitted buffers only need to remain alive until the terminal CQE. The write path now retains the buffers referenced by each SQE at submission time and releases them on the terminal CQE (the notification CQE carrying |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
1169bab to
da2a88f
Compare
| */ | ||
| protected final short nextWriteOperationId() { | ||
| for (int attempts = 0; attempts < 65535; ++attempts) { | ||
| short id = nextOpsId(); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Why the available (write) ops Ids aren't a short stack and we pick things from there? It would make it O(1)
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
It is a linear probe, but it only re-probes on an actual collision. The map holds only the ops with an outstanding CQE, so with N writes in flight the expected number of iterations is 1 / (1 - N/65536) — about 1.02 at N = 1000. The 65535 bound is the give-up path, and hitting it returns 0 and defers the write anyway.
A stack does give an O(1) worst case. I'd want it to be a free list rather than the full id space pre-seeded, though — pushing ids back as they are released and falling back to the counter when empty costs memory proportional to the writes in flight instead of 128KB per channel. Happy to switch to that if you'd rather have the hard bound.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
I'd want it to be a free list
that's my proposal ^^
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Went with the free list — push ids back on release, pop from there. The probe was ~1 iteration on average, but I'd rather not have the worst case sitting in the event loop.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Does tracking every write operation introduce significantly more overhead on the hot write path? And the operation registry introduces additional lifecycle-management concerns. I wonder whether we could capture the original |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@dreamlike-ocean The id lookup is a free list now, so per write it's just a map entry plus the retain/release. If that's still too much I can keep the map for zero-copy only, since there's usually one write in flight. I think the lifetime is already handled though — tryRemove() waits while outstandingCompletions > 0, and a pending IORING_CQE_F_NOTIF keeps it there, so nothing outlives its op. Doing it in doShutdownOutput() won't reach the zero-copy buffers though. The primary CQE already removed them from ChannelOutboundBuffer while the kernel still has them — that's what zcWriteQueue was for. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
If each Id for op is obtained from a free list of contiguous slots (positions) you can save having any map and just a simple growable array indexed per available slot. I am quickly reading the PR but If we are in control of identities usually is always possible to replace any map with a bunch of arrays ^^ |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@franz1981 Ah, you're right — I missed that. Once the ids are contiguous the map has nothing to do, so I dropped it: it's a Datagram needed its own array since those ids come from |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Motivation: `shutdownOutput(...)` in `AbstractChannel` sets `this.outboundBuffer = null` and then `closeOutboundBufferForShutdown(...)` releases the flushed messages. In the io_uring transport a write SQE submitted moments earlier is still in flight at that point, so the kernel keeps reading from memory that was already returned to the allocator, and for a pooled buffer possibly handed to someone else. `close()` is not affected. `AbstractIoUringChannel.AbstractUringUnsafe.close(...)` parks the request in `delayedClose` and waits until `canCloseNow()` reports that neither `WRITE_SCHEDULED` nor `READ_SCHEDULED` is set, so a completion can never observe a dropped outbound buffer through that path. `shutdownOutput()` gets no such protection. What surfaced first was an NPE: every write-completion path dereferenced `outboundBuffer()`. `IoUringIoHandler` catches `Throwable` while dispatching a completion and logs it, so the channel never reached `ioState &= ~WRITE_SCHEDULED`, `canCloseNow()` stayed false, the pending `delayedClose` never ran, and the fd plus its `IoRegistration` leaked. To the application, `close()` simply never completed. The NPE and the leak are symptoms; releasing memory the kernel still owns is the defect. This is reachable without calling `shutdownOutput()` directly. `handleWriteError(...)` routes every non-`IOException` write failure, and every `IOException` when `AUTO_CLOSE` is disabled, into `shutdownOutput(voidPromise(), t)`. epoll is unaffected because `doWrite` there is synchronous, so there is no window in which a write is outstanding while the outbound buffer is being dropped. Modification: Add `WriteOperation`, which retains the references handed to a submitted write and releases them when the terminal CQE arrives: `IORING_CQE_F_NOTIF` for `IORING_OP_SEND_ZC` and `IORING_OP_SENDMSG_ZC`, the completion itself for everything else. `AbstractIoUringChannel` keys these per channel, so the lifetime of write memory no longer depends on `ChannelOutboundBuffer`. `nextWriteOperationId()` hands out an id that no pending write CQE owns. Zero-copy ops awaiting their notification are not counted by `numOutstandingWrites` -- `writeComplete` only decrements when `IORING_CQE_F_NOTIF` is unset -- so they accumulate independently of that bound. When no id is free the submission returns 0 and the terminal CQE re-flushes through `scheduleWriteIfNeeded(...)`. Completions are matched on the opcode as well as the id, because write `user_data` is not a single namespace. `IoUringFileRegion` picks fixed values to tell its two splice stages apart, and the domain-socket fd-passing sendmsg uses `MsgHdrMemory.idx()`. Neither is registered, so neither can terminate an unrelated operation whose id happens to collide. `IovArrayReferenceCollector` captures exactly the buffers that entered the iovec, including a composite that `IovArray` only added part of. `zcWriteQueue` and `ZC_BATCH_MARKER` are gone. `handleWriteCompleteZeroCopy` no longer has to retain buffers itself, so both the `IORING_CQE_F_MORE` and the non-`MORE` path use `removeBytes(res)`, which also stops reporting a partial write as a full one. The outbound-buffer null checks stay in the five write-completion paths. `shutdownOutput()` still nulls it, so a completion must not dereference it even though the memory is now kept alive. Result: Write memory stays live until the kernel is done with it. `close()` completes after `shutdownOutput()` races an in-flight write, and the fd and its registration are released. `IoUringShutdownOutputDuringInFlightWriteTest` covers the plain and the zero-copy paths and asserts the buffer is still live right after `shutdownOutput()`. `IoUringSocketSendSzSendmsgZcTest` covers a local close racing the primary CQE for both `SEND_ZC` and `SENDMSG_ZC`. `IoUringDatagramWriteLifecycleTest` covers the sendmsg lifetime. `IoUringIovArrayReferenceCollectorTest`, `WriteOperationTest` and `IoUringWriteOperationIdTest` cover the collector, the release rules and the id bookkeeping. None are timing-dependent: the write and the close are issued in one event-loop task and `submitAndRunNow()` is a no-op across the transport, so no CQE can have been reaped by the time the outbound buffer is dropped. The domain-socket fd-passing sendmsg is still not registered as a write operation. It cannot collide today -- that channel has no registered `IORING_OP_SENDMSG`, and its `MsgHdrMemory.idx()` is 0, which `nextOpsId()` never hands out -- but nothing enforces either invariant.
close() already defers while writes are scheduled, so these cases do not exercise the shutdownOutput lifetime bug.
Motivation: `nextWriteOperationId()` walked the shared `nextOpsId()` sequence and re-probed whenever the value it landed on was still owned by a write awaiting its CQE. That is about one iteration in the common case, but the bound is 65535 and it runs on the event loop. Modification: Give write operations their own sequence and a free list. An id goes back on the list when its terminal CQE removes the operation, allocation pops from the list first, and the sequence is only asked for ids it has never handed out. Nothing has to be searched, so allocation is O(1) in the worst case, and the list grows with the number of writes in flight rather than with the id space. The datagram sendmsg path registers `MsgHdrMemoryArray` indices, which that array allocates and recycles itself. Those ids go through `retainUnpooledWriteOperation(...)` so they never enter the free list -- index 0 would otherwise be handed out as an operation id, and 0 means "no id". Result: Write-operation id allocation is constant time. Ids are also reused as soon as they are released, so the range in use stays proportional to the writes in flight.
Motivation: Write-operation ids are dense now that they come from a free list, so the `IntObjectHashMap` that held the operations was hashing values that already are array indices. Modification: Keep the operations in a `WriteOperation[]` indexed by the id submitted as the SQE's user_data. Ids run from 1, since 0 stays reserved for "no id", and the array grows with the number of writes in flight. The slot keeps its `WriteOperation` once allocated and the object is reused, so a write no longer allocates one. Ids are bounded by `Short.MAX_VALUE`, which is the bound `scheduleWrite(...)` already puts on the number of outstanding writes. The datagram sendmsg path registers `MsgHdrMemoryArray` indices, which that array allocates and recycles itself, and those overlap with the ids the free list hands out. They live in a separate array reached through `retainUnpooledWriteOperation(...)`, so the two namespaces cannot collide and the boolean that used to mark an id as recyclable is gone. Looking a completion up still matches the opcode. Write `user_data` is not one namespace: the splice stages submit fixed values and the domain-socket fd-passing sendmsg submits its `MsgHdrMemory` index, and neither is registered. With dense ids those values now land inside the occupied range rather than outside it, so the opcode is what keeps such a completion from terminating what it finds. Result: Resolving a write completion is an array index. A write allocates neither a map entry nor a `WriteOperation`, and the memory a channel spends on this is proportional to its writes in flight.
…available Motivation: IoUringIovArrayReferenceCollectorTest builds an IovArray directly, which initializes io.netty.channel.unix.Limits and loads the native library. Without the guard the other io_uring tests use, the test errors instead of being skipped where that library cannot be loaded. Modification: Add the same assumeTrue(IoUring.isAvailable()) guard the neighbouring tests carry. Result: The test skips rather than fails where io_uring is unavailable.
Motivation: The tests in this module share one surefire fork and run in random order, so a class that reaches the native layer before the library is loaded takes the rest of the module down with it. IoUringSocketSendSzSendmsgZcTest builds real channels and carries no guard. Modification: Add the same assumeTrue(IoUring.isAvailable()) guard the neighbouring tests carry. Result: The test skips rather than fails where io_uring is unavailable, whatever order the fork runs in.
4bae192 to
9e0e5a2
Compare
|
Are there any io uring perf tests? I'd be curious how it affects things |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Hi @HwangRock, sorry for the late reply — I just got back to work The main thing I'd like to discuss is the hot-path cost: the current approach does a retain()/release() pair per message on every write, allocates an id per SQE, and copies the references array on every writev — while the lifetime problem only manifests when shutdownOutput() races an in-flight write. I sketched an alternative: keep the hot path to a single plain field access, and do the retain/release on the slow path only — retain the messages referenced by the in-flight SQE in doShutdownOutput() before the outbound buffer is closed, and release once the terminal completion arrive. It covers the stream paths (single/writev/splice/generic FileRegion), send_zc/sendmsg_zc with IORING_CQE_F_MORE, the TFO initial data, and the datagram sendmsg path. You can take a look: dreamlike-ocean@6a3c7d1 I haven't done extensive testing or a full review yet, so there may be edge cases I missed. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
The suggestion from @dreamlike-ocean looks interesting - retain/release on the hot path is not really cheap! |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…bmit Motivation: Retaining every reference a write hands to the kernel keeps the memory alive, but it pays for a rare race on every write. A JMH benchmark of the bookkeeping alone measured a single send at 69.6M ops/s and 24 B/op against 288.9M ops/s and no allocation without the retain/release pair, and a 16-buffer writev at 6.1M ops/s and 240 B/op. The lifetime problem only appears when `shutdownOutput()` drops the outbound buffer while a write is still in flight, so the cost belongs on that path. Modification: A submitted write records its references in its slot without touching the reference count. The outbound buffer still owns them until its own completion path releases them. `doShutdownOutput()` is final and walks both slot arrays, retaining every in-flight operation once, before handing off to `doShutdownOutput0()`. Subclasses override the latter, so the retain cannot end up after the shutdown regardless of what a subclass does. The terminal CQE releases only what the walk retained. Walking the slots rather than the `ChannelOutboundBuffer` is what makes one mechanism enough. A zero-copy batch leaves the outbound buffer at its primary CQE, so between that and `IORING_CQE_F_NOTIF` there is nothing there to find, while the slot lives until the notification. The same walk covers the datagram sendmsg path and the `TCP_FASTOPEN` initial data, so none of them needs a hook of its own. `IovArrayReferenceCollector` is now a channel field reset per write instead of a new instance, and `WriteOperation` copies into its own array rather than taking the caller's. The slot array and the collector array are both reused, so a steady-state write allocates neither. Result: A write no longer touches a reference count or allocates. Write memory still outlives the kernel's use of it, and the guarantee now rests on a single walk at shutdown instead of a retain on every write.
|
Hi @dreamlike-ocean, no worries. I just got off work myself. You're right about the retain/release pair, that was most of the cost. The submit path doesn't retain anything now, the slot just records the references, I kept the slot array underneath because of The cost shows up on stream:
JMH, 64 byte pooled direct buffers, single thread, M1. Datagram goes the other way because Pushed as 6371985. Happy to drop the id if you'd rather cover the |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Motivation: Dropping the retain from the submit path left the outbound buffer holding the only reference to a zero-copy write. `handleWriteCompleteZeroCopy` removes the written bytes at the primary CQE, so with `IORING_CQE_F_MORE` set that release lands while the kernel still owns the memory until the notification, and a pooled buffer can be handed out again in that gap. Modification: Retain the write operation's references at the primary CQE, before `removeBytes(...)` drops the outbound buffer's own reference. The retain is idempotent, so a shutdown that walks the slots in the same window does not add a second one, and the notification releases exactly once. `WriteOperation.retainForShutdown()` becomes `retainReferences()`, since it now has a second caller that has nothing to do with shutdown. It marks itself retained before retaining, so a reference that throws mid-loop is still accounted for, and the walk over the slots no longer lets one failing slot stop the rest. `unregistered()` releases whatever the slots still hold. Completions are dropped once the registration is gone, so a shutdown-time retain would otherwise never be released. Result: Zero-copy write memory stays alive until the kernel is done with it, on the ordinary write path and not only when a shutdown races it.
|
There still seems to be a lifetime gap for SEND_ZC/SENDMSG_ZC: |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
@dreamlike-ocean Yeah, that was real. You caught it right before I pushed the fix, sorry about the timing. 1476a7b retains the write operation's references at the primary CQE, just before |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
The helper already observes refCnt reaching zero on the event loop. Reading it again can see a recycled pooled buffer reset to one.
| count = 0; | ||
| for (int i = 0; i < finishedCount; i++) { | ||
| if (i < releaseCount) { | ||
| references[i].release(); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Should we use ReferenceCountUtil.safeRelease() just in case ?
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Good idea, done in 84d933c638. finish() is where every way a slot ends converges — terminal CQE, failed submission, deregistration — so a throw partway left the references after it neither released nor cleared from the array, and the deregistration case still has a deregisterPromise to settle afterwards. The retain side already logs per slot and carries on, so the two directions now match.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Motivation: Several comments added along the way describe an earlier shape of the code. retainReferences(long, byte) says it is used only from the shutdown path, but its one caller is the zero-copy completion that sees IORING_CQE_F_MORE; the shutdown path goes through retainAll(). abandon(long, byte) and abandonStream() both list deregistration among the situations that reach them, but every caller sits right after a failed submission -- deregistration goes through releaseAll(). matching(...) names the domain-socket sendmsg as a source of colliding ids, which cannot happen since that path submits index 0 while pooled ids start at 1, and it leaves out the real source: every non-zero-copy stream write takes its id from nextOpsId(). record(...) says the id is recycled on the terminal CQE, which is not true of the overflow ids nextZeroCopyId() hands out. Three test names promise something their assertions do not check. Modification: Point each comment at what the code does. Rename the three tests after what they assert: a zero-copy slot without a retain finishes at the notification without releasing, reset() clears what a larger previous write left behind, and close() -- not a retain -- keeps the datagram alive until its terminal CQE. Drop the refCnt assertion that follows awaitRefCntZero(...) in the zero-copy test, the way the datagram one already does, since the awaiter only returns true once the event loop has seen that same zero. Result: The comments and test names hold up against the code they sit next to.
Motivation: Widening the write user_data to a long left four completions narrowing it back to a short at the call site. connectComplete(...) was one of them even though it never reads that parameter, which is an inconsistency with writeComplete(byte, int, int, long) for no gain. The other three narrow without checking, so a later change that hands one of those namespaces a wider id would drop its high bits without a sound. Modification: Give connectComplete(...) a long, which removes the cast at all three of its call sites. Route the remaining three -- read, poll and cancel -- through narrowUserData(...), which asserts the value survives the round-trip first. Those completions all submit ids from short-parameter factories today, so the assert does not fire; it is there to catch a future change that stops being true. Result: One narrowing point instead of four, and it fails loudly rather than quietly.
Motivation: finish() walks the slot's references and releases the ones a shutdown retained. A release that throws leaves the loop, so the references after it are neither released nor cleared from the array. Every way a slot ends -- a terminal CQE, a failed submission, a deregistration -- goes through this loop, and the deregistration case runs from unregistered(), which still has a deregisterPromise to settle afterwards. Modification: Release through ReferenceCountUtil.safeRelease(...), which logs and moves on. The retain side already does this per slot in retainArray(...) and retainSingle(), so the two directions now behave the same way. Result: A reference that refuses to release costs a warning instead of the rest of the slot.
There was an error while loading. Please reload this page.
🚨 TestLens detected 1 failed test 🚨Here is what you can do:
Test SummaryBuild PR / linux-x86_64-java11-boringssl build > Netty/Codec/HTTP2
🏷️ Commit: 8adae2b Test FailuresDataCompressionHttp2Test > encodingTooBigMessage(int, AsciiString) > [8] 10, snappy (Netty/Codec/HTTP2 in Build PR / linux-x86_64-java11-boringssl build)
Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@dreamlike-ocean can you check one more time ? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
checking.... |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
I have re-reviewed the send paths for |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Let me merge this one @chrisvest . We can do a follow up if something pops up. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
Could not create auto-port PR. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
@dreamlike-ocean want to take a step on this one ? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Working on a port to 5.0 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@HwangRock are you interested in porting this to 5.0 so I can focus on other things ? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
@normanmaurer Sure, happy to take it — I will start on the 5.0 port. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@HwangRock <3 |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Motivation: Port of netty#17238 (4.2 commit ef66d7a) to 5.0. A write SQE that is still in flight leaves the kernel reading from the buffers it was handed. The output shutdown path drops the outbound buffer and releases those buffers straight away, so the kernel reads memory that has already gone back to the allocator, and for a pooled buffer possibly to someone else. Zero-copy widens the window: the primary CQE carries `IORING_CQE_F_MORE`, meaning the kernel holds the memory until the notification that follows, and the queue the stream channel kept for that case only covered the span after the primary CQE, not the one before it. This is reachable without shutting the output down explicitly. `handleWriteError(...)` routes write failures into `shutdownOutput(...)`, and the core releases the outbound buffer from the shutdown listener whether or not the transport's shutdown succeeded. The datagram channel gets there the same way, and its shutdown always fails with `UnsupportedOperationException`, so the buffers went away with nothing holding them. What surfaces first is an NPE, because every write-completion path dereferences the outbound buffer. `IoUringIoHandler` catches `Throwable` while dispatching a completion and logs it, so the channel never clears `WRITE_SCHEDULED`, the pending close never runs, and the fd plus its `IoRegistration` leak. To the application, `close()` simply never completes. The NPE and the leak are symptoms; releasing memory the kernel still owns is the defect. Resolves netty#17237 for 5.0. Modification: Add `WriteOperation`, a slot recording the references a submitted write handed to the kernel. Recording does not retain: the outbound buffer still owns them. An output shutdown retains what is in flight, and the terminal CQE releases it, `IORING_CQE_F_NOTIF` for `IORING_OP_SEND_ZC` and `IORING_OP_SENDMSG_ZC` and the completion itself for everything else. `ChannelOutboundBuffer` and the shutdown path are untouched. `WriteOperationTracker` owns the slots, one tracker per channel: a pooled `WriteOperation[]` indexed by the id in the SQE's user_data, a short free stack that hands those ids out from 1 and takes them back on a terminal CQE, an overflow map for the zero-copy ids that outlive the short range, and the single slot a non-zero-copy stream write uses, which needs no id because `WRITE_SCHEDULED` caps a stream channel at one outstanding write. The datagram sendmsg path registers `MsgHdrMemoryArray` indices, which that array allocates and recycles itself and which overlap with the ids the free list hands out, so those live in their own foreign array. `IovArrayReferenceCollector` pairs an `IovArray` with the references backing each iovec so a multi-buffer write retains or releases them as a batch. Completions are matched on the opcode as well as the id. This part is the 4.2 code as merged, so it carries the review that landed there. 5.0 splits the shutdown that 4.2 had as one method, so the retain moves with it: `AbstractIoUringChannel.doShutdown(ChannelShutdownType, Promise<Void>)` is now final and retains through the tracker on an Outbound shutdown before delegating to a new abstract `doShutdown0(...)`, which is the three leaf channels' existing bodies renamed and otherwise unchanged. Inbound needs no retain -- it never touches the outbound buffer, so there is no release to pair with. Completion dispatch reads the full long user_data instead of narrowing it up front, because a zero-copy write's id can fall outside the short range once the pooled id space is exhausted. Write and connect completions keep the untruncated value; read, poll and cancel ids are always short, so they go through a `narrowUserData(...)` that asserts the value round-trips before narrowing. `IoUringIoOps.newSendZc` and `newSendmsgZc` take a long data parameter to match; every other factory method is untouched. `unregistered()` releases every slot the tracker still holds, since no further completion will arrive once a channel is deregistered. The TCP Fast Open connect records its sendmsg through the tracker instead of reusing the `MsgHdrMemoryArray` slot as the SQE id, abandons the slot if submission fails, and falls back to a normal connect if the tracker has no id to hand out. The stream channel's zero-copy batch queue is what the tracker replaces, so `ZC_BATCH_MARKER`, `zcWriteQueue` and `addFlushedToZcWriteQueue` are gone. The retain keys off `IORING_CQE_F_MORE` before `res` is examined, because an errored request can still carry a notification. Completions arriving after the outbound buffer is gone return early rather than dereferencing it. The ported tests are held to what 5.0 does rather than what 4.2 did. The public `shutdown(...)` they call only flips the output-shutdown flag; the private `shutdownOutput(...)` that clears the buffer runs from the write-error path, so a message sits at refCnt 2 after the shutdown -- its own reference plus the one the retain took -- where 4.2 left 1. Neither test pins the exception that fails the in-flight write: the kernel can complete it against a socket whose output is already shut down, or `close()` can reap it first, and asserting the type made the splice test fail on two CI jobs. Result: A write that is in flight when the output shuts down keeps its memory alive until the kernel is done with it, on the stream and datagram channels alike. The references reach refCnt 0 on the terminal CQE, and `close()` completes instead of hanging. The io_uring suites pass on Linux, 21 of 21.
…ill owns (#17238) (#17358) Port of #17238 to 5.0. Motivation: Same defect as on 4.2. A write SQE is still in flight when the output shutdown drops the outbound buffer and releases the flushed messages, so the kernel keeps reading memory that already went back to the allocator, and for a pooled buffer possibly to someone else. #17238 has the full write-up. Modification: `WriteOperation`, `WriteOperationTracker` and `IovArrayReferenceCollector` come over as they were merged on 4.2, so they carry the review that landed there. The wiring is what differs, because this is not a cherry-pick: `AbstractIoUringStreamChannel`, `AbstractIoUringServerChannel` and `IoUringDomainSocketChannel` do not exist here, so the write paths they carried had to be laid out against `IoUringSocketChannel` instead. Three things came out different from 4.2: - 5.0 has no `doShutdownOutput()` hook, so `AbstractIoUringChannel` takes `doShutdown(ChannelShutdownType, Promise)` as final, retains on the outbound direction, and hands off to a new `doShutdown0(...)`. Going through the base keeps the retain ahead of the release for the datagram and server channels too, whose `doShutdown0(...)` fails immediately -- the core drops the outbound buffer from the listener either way. - No separate domain-socket channel, so the null guard 4.2 added there is covered by the shared one already sitting ahead of that branch in `writeComplete0`. - 5.0 splits shutdown into a public `shutdown(...)` that only flips the flag and a private `shutdownOutput(...)` that clears the buffer. The two ported tests call the public one, so they expect the tracker's reference to still be there, and they assert the in-flight write failed without pinning which exception failed it. Completion dispatch had to widen as well: it reads the full long user_data instead of narrowing up front, since a zero-copy id can leave the short range once the pooled ids run out. Read, poll and cancel ids are always short, so they go through a `narrowUserData(...)` that asserts the value round-trips. `IoUringIoOps.newSendZc` and `newSendmsgZc` take a long to match. `zcWriteQueue` and `ZC_BATCH_MARKER` are gone with the rest of the old zero-copy path, which also removes a deregistration that could strand whatever the queue was holding. Result: A write that is in flight when the output shuts down keeps its memory alive until the kernel is done with it. The references reach refCnt 0 on the terminal CQE, and `close()` completes instead of hanging. io_uring tests pass on Linux, 21 of 21.
Motivation: [#17238](#17238) fixed early release of in-flight write buffers during `shutdownOutput()`. The kernel may still access submitted buffers after write promises fail and outbound is cleared. The fix introduced `WriteOperationTracker` to record resource references on write, retain them on output shutdown, and release them when completion arrives. Ordinary writes maintain the tracker's reference arrays on every submission and completion. Batched writes also collect, copy, and clear references. Even with slot and array reuse, these operations have CPU and GC write barrier costs. This PR replaces `WriteOperationTracker` with `WriteOpsSnapshot`. Ordinary writes copy a few primitive fields at submission, then use them to find and retain in-flight resources before outbound is released. `PendingZeroCopyWrites` holds references needed by SEND_ZC / SENDMSG_ZC notifications. The PR also covers resource handling for TFO, UDS fd transfer, and direct failure of flushed messages. Modification: 1. Find in-flight resources from WriteOpsSnapshot before releasing outbound Each Channel reuses one `WriteOpsSnapshot`. After successful submission, `submitWrite()` copies `opcode`, `len`, `union3`, and `userData` into it. These four primitive fields and Channel state are enough to find the in-flight resources. Escape analysis can still eliminate the `IoUringIoOps` allocation. Add `prepareToDiscardOutboundMessages(ChannelOutboundBuffer)` to `Channel.Unsafe` with an empty default implementation. `ChannelOutboundBuffer.failFlushed()` calls it after its reentrancy guard takes effect and before failing and releasing messages. `AbstractUringUnsafe` uses the snapshot and Channel state to retain resources needed by in-flight writes, then releases them on completion. WRITEV uses the submitted iov count to find the ByteBufs. UDP finds in-flight datagrams through `sendmsgHdrs` slots and releases each by its CQE index, including out-of-order completions. 2. Include TFO SENDMSG in the write lifecycle TFO's `SENDMSG(MSG_FASTOPEN)` accesses outbound data. Submission adds it to the in-flight write count and sets `WRITE_SCHEDULED`. `close()` waits for write completion before releasing the buffer. `shutdownOutput()` uses the discard callback to retain the initial data until completion. Ordinary UDP sends can run alongside connect, so completion checks connect state, the SENDMSG opcode, and `MSG_FASTOPEN` to identify TFO. TFO falls back to regular connect only if the connection request is still valid. 3. Use connectId to cancel in-flight connect requests Clear `connectId` when the CONNECT/TFO primary CQE arrives, before notifying connect promise listeners. Close calls from those listeners can then see that connect has completed. Close uses `connectId != 0` to decide whether to submit cancel. This also covers a cancelled and cleared promise whose operation is still in flight. 4. Use a separate fd copy for UDS sendfd A caller can close the original fd in `writeAndFlush(fd).addListener(f -> fd.close())`. When the write promise fails, SENDMSG may still be polling or retrying. A retry may look up the fd number in `SCM_RIGHTS` again, so the fd used by the kernel must stay valid until SENDMSG completes. Successful `shutdown(SHUT_WR)` prevents further sends, but Netty fails and clears outbound messages even if shutdown itself fails. The in-flight SENDMSG still needs its fd in that case. See the [kernel SENDMSG retry path](https://github.com/torvalds/linux/blob/master/io_uring/net.c) and [SCM_RIGHTS fd lookup](https://github.com/torvalds/linux/blob/master/net/core/scm.c). Before submitting sendfd, duplicate the fd with `F_DUPFD_CLOEXEC`. Unsafe holds the copy and closes it when the SENDMSG CQE arrives. Each sendfd submission adds one dup and one close. Ordinary ByteBuf sends keep their submission path. A dup failure goes through write error handling, fails pending write promises, and shuts down output. 5. Hold references for zero-copy notifications in PendingZeroCopyWrites When the primary CQE carries `MORE`, `PendingZeroCopyWrites` collects references and holds them by `userData` until the matching `NOTIF` arrives. Notifications from different requests can complete out of order. If shutdown has already retained the references, they transfer to this structure. `PendingZeroCopyWrites` is created on demand and reuses `PendingWrite` objects and reference arrays. `freeIdStack` stores recycled IDs. When the pool runs out of IDs, new requests go into an overflow map. 6. Cache SENDMSG_ZC MsgHdrMemory per Channel Each `IoUringIoHandler` previously preallocated 1024 `MsgHdrMemory` objects for SENDMSG_ZC. This PR allocates one when a Channel first uses SENDMSG_ZC and reuses it for later sends. This saves the preallocated heap and native memory. Each TCP Channel has one write batch waiting for a primary CQE, so its `MsgHdrMemory` holds the current batch's `iovLength`. Before releasing outbound, this length and `WriteOpsSnapshot` identify the ByteBufs to retain. Result: The four TCP scenarios measured median throughput changes within about 1%. Ordinary writes use less retained heap per Channel, while allocation per round stays close to the baseline. The ordinary write hot path skips collecting, copying, and clearing tracker references. Retain runs before outbound is released. `PendingZeroCopyWrites` separately manages references needed by zero-copy notifications. Performance and allocation: The test host has an Intel Core i5-13600KF, 14 cores / 20 threads, and about 62.6 GiB of visible memory. Tests use loopback on a physical Linux host with CPU affinity `8,10`. The JVM is Oracle GraalVM JDK 25.0.2, using C2 through `-XX:-UseJVMCICompiler`, a fixed 1 GiB heap, and G1. ```text Linux dreamlike-MS-7E01 7.3.0-6-generic #6-Ubuntu SMP PREEMPT_DYNAMIC Mon Sep 21 16:58:57 UTC 2026 x86_64 GNU/Linux ``` The comparison is between upstream `4.2` at `059591de569a253117d153f8b5e543788ad1f0f8` and this PR branch. Each version runs in 3 independent JVMs per scenario, alternating between versions. Each run warms up for 15 s and sends for about 15 s before an external SIGINT starts disconnect. Each round sends 32 KiB and waits for a 1 B ACK before the next round. writeSingle / SEND_ZC use one buffer; WRITEV / SENDMSG_ZC use `8 × 4 KiB`. The table shows medians, and changes use unrounded medians. See the note below for JIT effects on SENDMSG_ZC allocation. - Throughput: acknowledged payload divided by the time from measurement start until both connections close, including shutdown. - Average sender heap allocation per round: bytes allocated by the client EventLoop during measurement divided by completed rounds. Measurement starts after warmup and ends before shutdown. It counts heap allocations on that thread for sends, CQE processing, and ACK reception. Each round covers a 32 KiB send and its ACK. - JFR: separate diagnostic JVMs record allocations; throughput runs have JFR disabled. Diagnostics start `hot` and `all` recordings after warmup, stop `hot` before SIGINT, and stop `all` after the connections close. | Scenario | Baseline MiB/s | This PR MiB/s | Throughput change | Baseline avg. sender heap allocation B/round | This PR avg. sender heap allocation B/round | Allocation delta B/round | Baseline GC count/ms | This PR GC count/ms | |---|---:|---:|---:|---:|---:|---:|---:|---:| | writeSingle | 3304.1 | 3278.5 | -0.77% | 0.00 | 0.00 | ≈0 | 0/0 | 0/0 | | writev | 3127.6 | 3161.3 | +1.08% | 24.00 | 24.00 | ≈0 | 0/0 | 0/0 | | sendzc | 2753.5 | 2754.8 | +0.05% | 0.00 | 0.00 | ≈0 | 0/0 | 0/0 | | sendmsgzc | 2532.7 | 2554.0 | +0.84% | 0.01 | 0 | ≈0 | 0/0 | 0/0 | Note: allocation depends on JIT inlining and escape analysis. Repeated tests showed no consistent throughput regression. Escape analysis can eliminate the anonymous `MessageProcessor` present in both versions. The SENDMSG_ZC entry uses approximately 0 for that case. Retained heap per Channel: These measurements cover an unregistered Channel with default settings and its dedicated Java objects. Shared allocator/EventLoop objects, application handlers, payload, and native memory are outside this count. Both versions use the same JDK, compressed pointers, 8 B alignment, and disabled compact object headers. | Channel type and state | Baseline retained heap B/Channel | This PR retained heap B/Channel | Delta B/Channel | |---|---:|---:|---:| | TCP, newly created | 864 | 832 | -32 | | TCP, after writeSingle | 888 | 832 | -56 | | TCP, after WRITEV with 8 buffers | 912 | 832 | -80 | | TCP, SEND_ZC after recycling one slot | 984 | 976 | -8 | | TCP, SENDMSG_ZC with 8 buffers after recycling one slot | 1008 | 1536 | +528 | | UDP, newly created | 172264 | 172216 | -48 | The extra 528 B for TCP SENDMSG_ZC with 8 buffers mainly comes from the Channel's cached `MsgHdrMemory` and associated objects. They stay available for later sends after the slot is recycled. This memory is allocated when the Channel first uses SENDMSG_ZC. Removing the shared `MsgHdrMemoryArray` and `IovArrayReferenceCollector` saves about 332.3 KiB of retained heap per `IoUringIoHandler`. The total memory change depends on the number of handlers and Channels using SENDMSG_ZC.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
io_uring: close() never completes when shutdownOutput() races an in-flight write
There was an error while loading. Please reload this page.