Repository navigation
IoUring:Refactor io_uring write lifecycle management - #17757
Conversation
d6830a3 to
0334122
Compare
|
Would you have time to review this PR? I think this approach is simpler than the previous one. @normanmaurer |
0334122 to
249fccb
Compare
|
@dreamlike-ocean will try to get done tomorrow latest. |
|
@dreamlike-ocean so can you summarize why this is needed? Is it because we might release buffers while the kernel still holds a reference to it ? |
#17238 does too much bookkeeping on submission. I found a simpler approach: copy a few primitive fields and reconstruct the buffer references on close/shutdown. This simplifies the code, avoids the tracker's GC write-barrier costs on submission, and fixes several pre-existing UAF issues. |
249fccb to
e05943b
Compare
|
@dreamlike-ocean can address the following: I think either of these two is fine. Maybe just keep it in io_uring would be better. |
|
I initially put the hook on AbstractChannel. However, ChannelOutboundBuffer.channel is declared as Channel, even though its constructor accepts an AbstractChannel. A simpler option would be to keep a reference to the original ChannelOutboundBuffer in AbstractUringUnsafe. That would let us reconstruct and retain the references in doShutdownOutput(), even after the core clears its field. This would let us remove the hook from the core API. I think this is worth trying. For uds, I agree with the UDS dup fix: return -errno from the native method and convert it to an IOException in Java, so handleWriteError() follows the expected AUTO_CLOSE behavior |
|
|
I removed the core hook. io_uring now keeps its own reference to the ChannelOutboundBuffer and retains in-flight writes in doShutdownOutput() and flush0(). |
✅ All tests passed ✅🏷️ Commit: 187e8db Learn more about TestLens at testlens.app/docs. |
|
@dreamlike-ocean thanks a lot! Can you do a port for 5.0 as well ? |
I will. I'll work on the port when I have some free time today (UTC+8). |
Motivation: **This is not a 1:1 port of #17757.** In 4.2, a user-called `shutdownOutput()` clears the outbound buffer synchronously while writes may still be in flight, so 4.2 retains the in-flight buffers in `doShutdownOutput()`. The 5.0 core does not have this problem: - The public `shutdown(Outbound)` never touches the outbound buffer. - The private `shutdownOutput()` is only reached from `handleWriteError`, either before a write is submitted or from the CQE of the last in-flight write, so the kernel no longer uses any of the buffers. - `close()` waits for in-flight writes before clearing the outbound buffer. So retaining on shutdown, as both 4.2 and the previous `WriteOperationTracker` did, protects nothing in 5.0. The only place where 5.0 releases buffers that are still in flight is the inactive flush: `writeFlushedNow()` calls `failFlushed()` on an inactive channel. This happens during a TCP Fast Open connect, and after a datagram `disconnect()` while `sendmsg`s are in flight. Modification: - Port #17757: - `WriteOpsSnapshot` replaces `WriteOperationTracker`. - `PendingZeroCopyWrites` holds zero-copy buffers until the notification arrives. - The TFO write lifecycle and `connectId` changes. - The UDS sendfd fd copy. - A per-channel SENDMSG_ZC `MsgHdrMemory`. - Retain in-flight buffers in `isWriteFlushedScheduled()`, the 5.0 counterpart of the 4.2 `flush0()` override. - `doShutdown(Outbound)` no longer retains anything. - Adapt to 5.0: no `Channel.Unsafe`, and stream channels are merged into `IoUringSocketChannel`. - Tests: - Remove the tracker tests. - `IoUringShutdownOutputDuringInFlight{Write,Splice}Test` now expect `refCnt == 1` after shutdown. - Add datagram retry and duplicate-send tests. Result: In-flight write buffers are retained only where 5.0 actually releases them early, and ordinary writes only copy a few primitive fields into `WriteOpsSnapshot` instead of recording references.
…y/netty#17757) Motivation: [netty/netty#17238](netty/netty#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.
Motivation:
#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 introducedWriteOperationTrackerto 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
WriteOperationTrackerwithWriteOpsSnapshot. Ordinary writes copy a few primitive fields at submission, then use them to find and retain in-flight resources before outbound is released.PendingZeroCopyWritesholds 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:
Find in-flight resources from WriteOpsSnapshot before releasing outbound
Each Channel reuses one
WriteOpsSnapshot. After successful submission,submitWrite()copiesopcode,len,union3, anduserDatainto it. These four primitive fields and Channel state are enough to find the in-flight resources. Escape analysis can still eliminate theIoUringIoOpsallocation.Add
prepareToDiscardOutboundMessages(ChannelOutboundBuffer)toChannel.Unsafewith an empty default implementation.ChannelOutboundBuffer.failFlushed()calls it after its reentrancy guard takes effect and before failing and releasing messages.AbstractUringUnsafeuses 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
sendmsgHdrsslots and releases each by its CQE index, including out-of-order completions.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 setsWRITE_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_FASTOPENto identify TFO. TFO falls back to regular connect only if the connection request is still valid.Use connectId to cancel in-flight connect requests
Clear
connectIdwhen the CONNECT/TFO primary CQE arrives, before notifying connect promise listeners. Close calls from those listeners can then see that connect has completed. Close usesconnectId != 0to decide whether to submit cancel. This also covers a cancelled and cleared promise whose operation is still in flight.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 inSCM_RIGHTSagain, so the fd used by the kernel must stay valid until SENDMSG completes. Successfulshutdown(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 and SCM_RIGHTS fd lookup.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.
Hold references for zero-copy notifications in PendingZeroCopyWrites
When the primary CQE carries
MORE,PendingZeroCopyWritescollects references and holds them byuserDatauntil the matchingNOTIFarrives. Notifications from different requests can complete out of order. If shutdown has already retained the references, they transfer to this structure.PendingZeroCopyWritesis created on demand and reusesPendingWriteobjects and reference arrays.freeIdStackstores recycled IDs. When the pool runs out of IDs, new requests go into an overflow map.Cache SENDMSG_ZC MsgHdrMemory per Channel
Each
IoUringIoHandlerpreviously preallocated 1024MsgHdrMemoryobjects 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
MsgHdrMemoryholds the current batch'siovLength. Before releasing outbound, this length andWriteOpsSnapshotidentify 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.
PendingZeroCopyWritesseparately 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.The comparison is between upstream
4.2at059591de569a253117d153f8b5e543788ad1f0f8and 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.hotandallrecordings after warmup, stophotbefore SIGINT, and stopallafter the connections close.Note: allocation depends on JIT inlining and escape analysis. Repeated tests showed no consistent throughput regression. Escape analysis can eliminate the anonymous
MessageProcessorpresent 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.
The extra 528 B for TCP SENDMSG_ZC with 8 buffers mainly comes from the Channel's cached
MsgHdrMemoryand 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
MsgHdrMemoryArrayandIovArrayReferenceCollectorsaves about 332.3 KiB of retained heap perIoUringIoHandler. The total memory change depends on the number of handlers and Channels using SENDMSG_ZC.