Skip to content

Port to 5.0: io_uring: do not release write memory that the kernel still owns (#17238) - #17358

Merged
normanmaurer merged 1 commit into
netty:5.0from
HwangRock:io-uring-shutdown-output-inflight-write-5.0
Sep 1, 2026
Merged

normanmaurer merged 1 commit into
netty:5.0from
HwangRock:io-uring-shutdown-output-inflight-write-5.0

Conversation

@HwangRock

@HwangRock HwangRock commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

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.

@normanmaurer

Copy link
Copy Markdown
Member

@HwangRock please check the test failures

@HwangRock

Copy link
Copy Markdown
Contributor Author

@normanmaurer Checked and fixed.

The splice test expected the in-flight write to fail with a NativeIoException, but CI got a StacklessClosedChannelException. The check runs after close() has been awaited, so either the kernel completes the write against a socket whose output is shut down, or close() reaps it first.

So 22bf7e8b03 asserts that the write failed rather than which exception failed it. The awslc and graal jobs that caught this are green now.

The remaining NioEventLoopTest failure on windows is an OutOfMemoryError on the runner, unrelated to this PR.

@normanmaurer

Copy link
Copy Markdown
Member

@HwangRock can you please squash and adjust the commit message to match our style ?

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.
@HwangRock
HwangRock force-pushed the io-uring-shutdown-output-inflight-write-5.0 branch from 22bf7e8 to 0da49e8 Compare August 31, 2026 19:30
@HwangRock

HwangRock commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor Author

@normanmaurer Squashed, and the message now follows Motivation / Modification / Result.

Same tree as 22bf7e8b03, so nothing changed but the history.

@testlens-app

testlens-app Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

Build PR / linux-x86_64-java25 build > Netty/Resolver/DNS

Test Runs Flakiness
DnsNameResolverTest > testFollowNsRedirectAndTrySecondNsOnTimeoutDefaultCaches(Dns… > [1] ChannelPerResolver ❌ ✅ 0% 🟢

Build PR / windows-x86_64-java25-boringssl > Netty/Buffer

Test Runs Flakiness
WrappedCompositeByteBufTest > testToStringMultipleThreads() ⚠️ ✅ 0% 🟢

🏷️ Commit: 0da49e8
▶️ Tests: 75477 executed
⚪️ Checks: 12/12 completed


Learn more about TestLens at testlens.app/docs.

@normanmaurer
normanmaurer merged commit f293a92 into netty:5.0 Sep 1, 2026
21 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants