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 — io_uring: do not release write memory that the kernel still owns by HwangRock · Pull Request #17238 · netty/netty

Conversation

@HwangRock

@HwangRock HwangRock commented Aug 7, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

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, because every write-completion path dereferences outboundBuffer(). IoUringIoHandler catches Throwable while dispatching a completion and logs it, so the channel never reaches ioState &= ~WRITE_SCHEDULED, canCloseNow() stays false, the pending delayedClose 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.

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.

Resolves #17237

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. doShutdownOutput() 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, so that contract lives in one type. It holds four members: 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. retainAll() and releaseAll() reach all four.

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 recordForeign(...) keeps them in their own array.

Completions are matched on the opcode as well as the id, because write user_data is not a single namespace. IoUringFileRegion submits fixed values to tell its two splice stages apart, and the domain-socket fd-passing sendmsg submits its MsgHdrMemory index. Neither is registered, and with dense ids those values land inside the occupied range rather than outside it, so the opcode is what keeps such a completion from terminating what it finds.

IovArrayReferenceCollector captures exactly the buffers that entered the iovec, including a composite that IovArray only added part of. IoUringIoHandler owns it alongside the IovArray it fills, so one instance serves every channel on an event loop.

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(). It is not timing-dependent: the write SQE and shutdownOutput() 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. IoUringShutdownOutputDuringInFlightSpliceTest covers the same race for splice, where dropping the last reference to an IoUringFileRegion closes both ends of its pipe and the FileChannel it splices from, all of which the SQE carries as raw fd numbers.

IoUringSocketSendSzSendmsgZcTest covers the existing zero-copy paths unchanged, with the reference-count assertions across IORING_CQE_F_MORE and IORING_CQE_F_NOTIF tightened. IoUringDatagramWriteLifecycleTest covers the sendmsg lifetime. IovArrayReferenceCollectorTest, WriteOperationTest, WriteOperationTrackerTest and WriteOperationTrackerOverflowTest cover the collector, the release rules and all four tracker members on the retain and release paths.

A JMH benchmark drives WriteOperationTracker, WriteOperation and IovArrayReferenceCollector directly rather than a reimplementation of them, so it cannot drift from what ships:

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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@normanmaurer

normanmaurer commented Aug 7, 2026

Copy link
Copy Markdown
Member

/cc @dreamlike-ocean

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dreamlike-ocean

dreamlike-ocean commented Aug 7, 2026

Copy link
Copy Markdown
Member

It looks like the issue stems from AbstractChannel’s model being designed for readiness-based transports.
Im checking....

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dreamlike-ocean

dreamlike-ocean commented Aug 7, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

It seems there may still be an issue. io.netty.channel.AbstractChannel.AbstractUnsafe#closeOutboundBufferForShutdown releases the ByteBuf in the queue. This means there could be a brief window where the write buffer is still held by the kernel even though the underlying ByteBuf has already been released. Would this be considered UB?
maybe....we need delayShutdonwOutput?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock

HwangRock commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

@dreamlike-ocean I think so too — this PR doesn't close that window.

doShutdownOutput() is overridden here, but shutdownOutput(...) nulls this.outboundBuffer before calling it, so the flushed buffers are still alive but unreachable from the override. That's why I stopped at the NPE. The release itself isn't new — it just never mattered before, since the completion died on the NPE and the fd leaked instead.

I left it out because the fix lands in AbstractChannel and every transport sees it, and it's not a straight copy of delayedClose — close() is terminal, while shutdownOutput() is a half-close, so reads continue and a close() mid-delay has to compose with it. I thought it was worth agreeing on the behavior first.

delayShutdownOutput sounds right to me. Happy to add it here or do it separately — your call.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@chris-mcc

chris-mcc commented Aug 8, 2026

Copy link
Copy Markdown

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

HwangRock reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock HwangRock changed the title io_uring: do not NPE when a write completion arrives after the outbound buffer was dropped io_uring: do not release write memory that the kernel still owns Aug 9, 2026
@HwangRock
HwangRock force-pushed the io-uring-shutdown-output-inflight-write branch from e8fd3ff to 1169bab Compare August 9, 2026 09:43
@HwangRock

HwangRock commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@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 IORING_CQE_F_NOTIF for zero-copy writes). This decouples buffer lifetime from ChannelOutboundBuffer without changing shutdown semantics, and removes the need for zcWriteQueue.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock
HwangRock force-pushed the io-uring-shutdown-output-inflight-write branch from 1169bab to da2a88f Compare August 9, 2026 09:52
franz1981
franz1981 reviewed Aug 9, 2026
View reviewed changes
Comment thread transport-classes-io_uring/src/main/java/io/netty/channel/uring/AbstractIoUringChannel.java Outdated
*/
protected final short nextWriteOperationId() {
for (int attempts = 0; attempts < 65535; ++attempts) {
short id = nextOpsId();

@franz1981 franz1981 Aug 9, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@HwangRock HwangRock Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@franz1981 franz1981 Aug 9, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

HwangRock reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

@HwangRock HwangRock Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@dreamlike-ocean

dreamlike-ocean commented Aug 9, 2026

Copy link
Copy Markdown
Member

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 ChannelOutboundBuffer when the Unsafe is constructed, and then determine which messages need to be retained inside doShutdownOutput(). This would ensure that the additional traversal and reference-counting costs are paid only on the shutdown slow path.

franz1981 reacted with heart emoji HwangRock reacted with eyes emoji
All reactions
  • ❤️ 1 reaction
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock

HwangRock commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

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 ^^

HwangRock reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock

HwangRock commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@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 WriteOperation[] indexed by the id now, and the slot hangs onto its operation object so a write doesn't allocate one either.

Datagram needed its own array since those ids come from MsgHdrMemoryArray and overlap with the pooled ones. Thanks for the push.

franz1981 reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

HwangRock added 6 commits August 9, 2026 23:07
@HwangRock
io_uring: do not release write memory that the kernel still owns
fd98f18
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.
@HwangRock
io_uring: remove redundant close race tests
89a98ea
close() already defers while writes are scheduled, so these cases do not exercise the shutdownOutput lifetime bug.
@HwangRock
io_uring: allocate write-operation ids from a free list
4f83b50
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.
@HwangRock
io_uring: index write operations by slot instead of hashing them
38ae434
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.
@HwangRock
io_uring: skip the iovec collector test when the native library is un…
2ead7c5
…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.
@HwangRock
io_uring: guard the zero-copy test on native availability
9e0e5a2
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.
@HwangRock
HwangRock force-pushed the io-uring-shutdown-output-inflight-write branch from 4bae192 to 9e0e5a2 Compare August 9, 2026 14:09
@chris-mcc

chris-mcc commented Aug 9, 2026

Copy link
Copy Markdown

Are there any io uring perf tests? I'd be curious how it affects things

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dreamlike-ocean

dreamlike-ocean commented Aug 10, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

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.

HwangRock reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@franz1981

franz1981 commented Aug 10, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

The suggestion from @dreamlike-ocean looks interesting - retain/release on the hot path is not really cheap!

HwangRock reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock
io_uring: retain in-flight write memory at shutdown rather than at su…
6371985
…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.
@HwangRock

HwangRock commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

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, doShutdownOutput() retains what's in flight, and the completion releases it.

I kept the slot array underneath because of send_zc. Buffers leave the ChannelOutboundBuffer at the primary CQE but the kernel isn't done until the notification, so resolving from the outbound buffer can't see them in that window. Your version keeps zcWriteQueue for it. The slot stays until the notification, so I could delete zcWriteQueue and skip the per-path hooks.

The cost shows up on stream:

retain per message retain at shutdown, outbound buffer retain at shutdown, slot array
single send 69.6M · 24 288.9M · 0 131.7M · 0
writev 16 6.1M · 240 28.7M · 0 9.9M · 160
datagram sendmsg 70.3M · 24 96.9M · 48 173.6M · 0

JMH, 64 byte pooled direct buffers, single thread, M1. Datagram goes the other way because HashMap<Short, Object> boxes above the Short cache, that's the 48 B/op.

Pushed as 6371985. Happy to drop the id if you'd rather cover the send_zc window another way.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock
io_uring: keep zero-copy write memory alive until its notification
1476a7b
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.
@dreamlike-ocean

dreamlike-ocean commented Aug 10, 2026

Copy link
Copy Markdown
Member

There still seems to be a lifetime gap for SEND_ZC/SENDMSG_ZC:

submit
→ primary CQE with IORING_CQE_F_MORE
→ removeBytes(res) releases the ChannelOutboundBuffer reference
→ the ByteBuf refCnt -> 0 but the kernel still owns the memory
→ IORING_CQE_F_NOTIF
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock

HwangRock commented Aug 10, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

@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 removeBytes(res) drops the outbound buffer's own one, so the refCnt doesn't hit 0 while the notification is still pending. It's idempotent with the shutdown walk, so if shutdownOutput() lands in that same window it doesn't add a second retain and the notification still releases exactly once.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock
io_uring: avoid pooled buffer reuse race in test
c6af0ce
The helper already observes refCnt reaching zero on the event loop. Reading it again can see a recycled pooled buffer reset to one.
normanmaurer
normanmaurer reviewed Aug 18, 2026
View reviewed changes
Comment thread transport-classes-io_uring/src/main/java/io/netty/channel/uring/WriteOperation.java Outdated
count = 0;
for (int i = 0; i < finishedCount; i++) {
if (i < releaseCount) {
references[i].release();

@normanmaurer normanmaurer Aug 18, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@HwangRock HwangRock Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

There was a problem hiding this comment.

Choose a reason for 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
normanmaurer
normanmaurer requested changes Aug 18, 2026
View reviewed changes
HwangRock and others added 4 commits August 18, 2026 22:18
@HwangRock
io_uring: describe what the write bookkeeping actually does
5e56be2
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.
@HwangRock
io_uring: let the connect completion carry the full user_data
c47b0c1
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.
@HwangRock
io_uring: do not let one failed release strand the rest
84d933c
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.
@normanmaurer
Merge branch '4.2' into io-uring-shutdown-output-inflight-write
8adae2b
@testlens-app

testlens-app Bot commented Aug 25, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

🚨 TestLens detected 1 failed test 🚨

Here is what you can do:

  1. Inspect the test failures carefully.
  2. If you are convinced that some of the tests are flaky, you can mute them below.
  3. Finally, trigger a rerun by checking the rerun checkbox.

Test Summary

Build PR / linux-x86_64-java11-boringssl build > Netty/Codec/HTTP2

Test Runs Flakiness
DataCompressionHttp2Test > encodingTooBigMessage(int, AsciiString) > [4] 0, snappy ❌ ✅ 1% 🟡
DataCompressionHttp2Test > encodingTooBigMessage(int, AsciiString) > [8] 10, snappy ✅ ❌ 1% 🟡

🏷️ Commit: 8adae2b
▶️ Tests: 32284 executed
⚪️ Checks: 18/18 completed

Test Failures

DataCompressionHttp2Test > encodingTooBigMessage(int, AsciiString) > [8] 10, snappy (Netty/Codec/HTTP2 in Build PR / linux-x86_64-java11-boringssl build)
org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
	at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:151)
	at org.junit.jupiter.api.AssertionFailureBuilder.buildAndThrow(AssertionFailureBuilder.java:132)
	at org.junit.jupiter.api.AssertTrue.failNotTrue(AssertTrue.java:63)
	at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:36)
	at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:31)
	at org.junit.jupiter.api.Assertions.assertTrue(Assertions.java:183)
	at io.netty.handler.codec.http2.DataCompressionHttp2Test$5.call(DataCompressionHttp2Test.java:255)
	at io.netty.handler.codec.http2.DataCompressionHttp2Test$5.call(DataCompressionHttp2Test.java:252)
	at io.netty.handler.codec.http2.DataCompressionHttp2Test.testEncodingMessage(DataCompressionHttp2Test.java:310)
	at io.netty.handler.codec.http2.DataCompressionHttp2Test.encodingTooBigMessage(DataCompressionHttp2Test.java:252)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.Optional.ifPresent(Optional.java:183)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.SpinedBuffer$1Splitr.forEachRemaining(SpinedBuffer.java:364)
	at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
	at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
	at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
	at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
	at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
	at java.base/java.util.concurrent.ForkJoinTask.doJoin(ForkJoinTask.java:396)
	at java.base/java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:721)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
	at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
	at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
	at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
	at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
expected actual
true false

Rerun Controls

Select tests to mute in this pull request:

  • DataCompressionHttp2Test > encodingTooBigMessage(int, AsciiString)

Reuse successful test results:

  • ♻️ Only rerun the tests that failed or were muted before

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer
normanmaurer requested a review from dreamlike-ocean August 27, 2026 06:31
@normanmaurer

normanmaurer commented Aug 27, 2026

Copy link
Copy Markdown
Member

@dreamlike-ocean can you check one more time ?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dreamlike-ocean

dreamlike-ocean commented Aug 27, 2026

Copy link
Copy Markdown
Member

@dreamlike-ocean can you check one more time ?

checking....

normanmaurer reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@dreamlike-ocean

dreamlike-ocean commented Aug 27, 2026

Copy link
Copy Markdown
Member

I have re-reviewed the send paths for ReferenceCounted messages, and everything looks good to me. thx!

normanmaurer and HwangRock reacted with heart emoji
All reactions
  • ❤️ 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Aug 27, 2026

Copy link
Copy Markdown
Member

Let me merge this one @chrisvest . We can do a follow up if something pops up.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer
normanmaurer merged commit ef66d7a into netty:4.2 Aug 27, 2026
33 of 35 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer normanmaurer added the needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. label Aug 27, 2026
@netty-project-bot

netty-project-bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Could not create auto-port PR.
Got conflicts when cherry-picking onto 5.0.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Aug 27, 2026

Copy link
Copy Markdown
Member

@dreamlike-ocean I think we should a separate PR once this is merged.

@dreamlike-ocean want to take a step on this one ?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Aug 27, 2026

Copy link
Copy Markdown
Member

Working on a port to 5.0

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Aug 28, 2026

Copy link
Copy Markdown
Member

@HwangRock are you interested in porting this to 5.0 so I can focus on other things ?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock

HwangRock commented Aug 28, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor Author

@normanmaurer Sure, happy to take it — I will start on the 5.0 port.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Aug 28, 2026

Copy link
Copy Markdown
Member

@HwangRock <3

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HwangRock HwangRock mentioned this pull request Aug 28, 2026
Port to 5.0: io_uring: do not release write memory that the kernel still owns (#17238) #17358
Merged
HwangRock added a commit to HwangRock/netty that referenced this pull request Aug 31, 2026
@HwangRock
io_uring: do not release write memory that the kernel still owns
0da49e8
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.
normanmaurer pushed a commit that referenced this pull request Sep 1, 2026
@HwangRock
Port to 5.0: io_uring: do not release write memory that the kernel st…
f293a92
…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.
@lhotari lhotari mentioned this pull request Sep 10, 2026
[fix][sec] Upgrade Netty to 4.2.18 to address several CVEs and bugs apache/pulsar#26514
Merged
2 of 11 tasks
@dreamlike-ocean dreamlike-ocean mentioned this pull request Sep 29, 2026
IoUring:重构写操作的生命周期管理 dreamlike-ocean/netty#13
Open
@normanmaurer normanmaurer mentioned this pull request Oct 1, 2026
child5 #17695
Closed
@dreamlike-ocean dreamlike-ocean mentioned this pull request Oct 4, 2026
IoUring:Refactor io_uring write lifecycle management #17757
Merged
@normanmaurer normanmaurer removed the needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. label Oct 16, 2026
@normanmaurer normanmaurer mentioned this pull request Oct 26, 2026
crisp nova cceda091 #18109
Closed
normanmaurer pushed a commit that referenced this pull request Oct 29, 2026
@dreamlike-ocean
IoUring:Refactor io_uring write lifecycle management (#17757)
77077ff
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@chrisvest chrisvest chrisvest left review comments
@franz1981 franz1981 franz1981 left review comments
@normanmaurer normanmaurer normanmaurer requested changes
@dreamlike-ocean dreamlike-ocean Awaiting requested review from dreamlike-ocean

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

4.2.18.Final

Development

Successfully merging this pull request may close these issues.

io_uring: close() never completes when shutdownOutput() races an in-flight write

Uh oh!

There was an error while loading. Please reload this page.

7 participants

@HwangRock @normanmaurer @dreamlike-ocean @chris-mcc @franz1981 @netty-project-bot @chrisvest
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.