Repository navigation
TCP buffers: SO_RCVBUF/SO_SNDBUF, receive autotuning, window scale 9, memory budget - #19
Closed
KoganTheDev wants to merge 17 commits into
Closed
KoganTheDev wants to merge 17 commits into
KoganTheDev wants to merge 17 commits into
Conversation
The working limits move from the static constants (now only the defaults) to _send_capacity / _receive_capacity, used by _advertised_window(), the window-reopen threshold, the reorder-buffer bound (via the window) and send_space_available(). Setters clamp to [max(4 KiB, 2*MSS), 16 MiB]; a shrunk receive capacity never moves the advertised right edge left. receive_capacity_locked() is exposed for a later autotuning step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Plumbed like TCP_NODELAY: Socket fields, setsockopt/getsockopt cases, _apply_options, inheritance from a listener. getsockopt returns double the (clamped) value set, as Linux does; the payload capacity is the undoubled value. Setting SO_RCVBUF marks the receive capacity locked for the later autotuning step. UDP stores and reads back but does not apply (its queue is bounded by datagram count). KernelStack already forwards the options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A connection that only receives had no RTT estimate at all: the sender's comes from acks of its own data. Receive autotuning needs one. Measured as Linux's tcp_rcv_rtt_measure_ts / tcp_rcv_rtt_measure: with timestamps, now minus the echoed TSval (turned back onto this connection's clock) on a full-sized segment advancing RCV.NXT, each echo once, smoothed with gain 1/8; without, the time RCV.NXT takes to reach RCV.NXT + RCV.WND as noted when the measurement started, kept as a running minimum because a sender that is not window-limited makes it longer than the RTT. WINDOW_SCALE_SHIFT becomes public so tests can read a scaled window. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fixed receive buffer caps a connection at capacity / RTT. As Linux's tcp_rcv_space_adjust: once per receiver RTT (every 200 ms until there is a sample) read() compares what the application read in that interval with the largest such count so far; if it is larger, the capacity grows to 2 * read + 16 segments, plus twice the relative growth while the rate is climbing, bounded by MAX_BUFFER_CAPACITY. Never when locked (SO_RCVBUF), never without window scaling. Capacity only grows, so the advertised edge never moves left; a growth that at least doubles the offered window is announced at once, as tcp_cleanup_rbuf does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unless the application set SO_SNDBUF, the send capacity follows max(SEND_BUFFER_CAPACITY, 2 * cwnd), bounded by MAX_BUFFER_CAPACITY, checked on every ack in ESTABLISHED and CLOSE_WAIT: a full window in flight while the next is already queued. The new room reaches a waiting writer through the send-space callback (EPOLLOUT). TcpConnection gets set_send_capacity_locked(), which ustack sets with SO_SNDBUF. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Like Linux's tcp_mem: each NetworkStack holds a TcpMemoryBudget (64 MiB by default, set_tcp_memory_limit()) that autotuning's growth above the default capacities is drawn from, per connection and per buffer, with partial grants. Once it is spent no connection grows further; nothing is shrunk, so no offered window is taken back. A connection gives its share back on reaching TIME_WAIT or CLOSED, when it is destroyed, and when the application sets that capacity itself (which is not counted). Tested with 100 connections growing at once through stacks whose budgets cover a fraction of what they want. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Releasing autotuning's whole charge on TIME_WAIT/CLOSED gave back memory that unread (or unacked) data could still be holding: many connections parked with full unread buffers would exceed the stack-wide cap. Now those states keep the part of each charge that the bytes still buffered occupy beyond the default capacity, and give it back as read() drains them; destruction (reaping) releases the rest, as before. Found by an automated security review (MEDIUM). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WINDOW_SCALE_SHIFT was a fixed 1, capping every window at 128 KiB - and so autotuning, whatever the buffer grew to. It is now the smallest shift with which the 16-bit field describes MAX_BUFFER_CAPACITY, computed the way Linux's tcp_select_initial_window() does from tcp_rmem[2]: 9 for 16 MiB (0xFFFF << 8 falls 256 bytes short). Linux's default 7 comes from its 6 MiB tcp_rmem[2]. Scaling now rounds the window to 512-byte units, so an edge already offered is rounded up rather than pulled back. The .pkt scripts' expected SYN options say wscale 9; the reorder and duplicate-ack tests read the window through the constant and use segments large enough to show at the new resolution. SYN cookies are unaffected: a cookie SYN-ACK offers no window scale (the cookie cannot remember one), and existing tests tell cookie SYN-ACKs apart by exactly that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Rounding the scaled window up to keep an offered edge recorded the rounded edge as the new promise, so the next ack rounded up from there: a peer sending exactly to each advertised edge in non-unit sizes walked the edge forward by up to 511 bytes per ack, past the buffer without bound (with shift 9). Now only the rounded-down window is a promise; the edge actually sent is tracked apart and only widens what is accepted, so it stays within one unit of the promise. The sent edge may then retreat by less than a unit, which RFC 7323 2.4 allows; the promised edge (C1's no-shrink rule) still never moves left. Defense in depth: in-order data is now trimmed to the acceptance window (RFC 9293 3.10.7.4) instead of being taken whole, so buffered bytes stay within the promised edge plus one unit - the capacity plus one unit, or the edge promised before a capacity shrink. A coalesced- retransmission test that relied on taking 71 KB through a 64 KiB window now stays inside it. Found by an automated security review (HIGH). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INITIAL_SSTHRESH was 64 KiB, so slow start ended at 45 segments on any path. Harmless while windows were capped near 64 KiB; with window scale 9 and autotuning it became the limit - on a 100 Mbit/s, 100 ms path the sender left slow start at a twentieth of the bandwidth-delay product and CUBIC took seconds to climb from there (15% of the link where the throughput test that follows expects 70%). RFC 5681 asks for the largest possible advertised window; it is now MAX_CWND, as Linux uses infinity. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mark_losses() ran on every ack with SACK in use and walked the whole scoreboard even when nothing was SACKed, so nothing could be marked: O(flight) per ack on a lossless path. With windows of thousands of segments (window scale 9, autotuning) that was most of the sender's work - 4.2 million entry visits for one lossless 8 MiB transfer over a 100 Mbit/s, 100 ms link, 11 thousand after. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
100 Mbit/s (12500 bytes/ms), 50 ms each way, 8 MiB. With autotuning the second half of the transfer runs at >= 70% of the link (95% measured); with the receive capacity locked at 128 KiB it stays near 128 KiB per round trip (9.4% of the link). A third run with a 300-frame bottleneck recovers from slow-start overshoot at a window of hundreds of segments without a timeout. The steady-state rate is asserted rather than the whole-transfer one: from a 10-segment initial window, slow start alone takes about seven round trips to reach the 1.25 MB bandwidth-delay product, which no buffer policy changes. Suite SimThroughput, not *SimTransfer*: that pattern is the seeded sweep (make sim, ctest label sim) that runs each matching test once per seed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SO_RCVBUF / SO_SNDBUF on a connected TCP socket now read the connection's capacity as it is now - autotuning's growth included - rather than the value last set, doubled as before; Linux reports sk_rcvbuf / sk_sndbuf the same way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…emory cap Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With INITIAL_SSTHRESH uncapped, nothing stopped a lossless connection that never fills its window (request/response, trickle) from growing cwnd by every byte acked, forever, and _tune_send_capacity charged 2 * cwnd of it - up to 16 MiB per connection - to the 64 MiB stack budget. A few light connections could starve the busy ones. CongestionControl::on_ack now takes the flight as the ack arrived (prior_in_flight, sampled before SACK or cumulative retirement) and grows only when is_cwnd_limited(): in slow start in-flight * 2 >= cwnd (Linux: cwnd < 2 * max_packets_out), past ssthresh in-flight >= cwnd minus one MSS (RFC 7661's idea). The check sits in the base class, so Reno and CUBIC both get it. CUBIC pauses its epoch clock across an app-limited stretch (as Linux does after idle), so the curve does not come back far ahead and close the gap in one burst. _tune_send_capacity grows only after an ack that found the sender cwnd-limited, so a window grown in an earlier bulk phase no longer pulls the buffer up for a connection that has gone quiet. New tests: CongestionControl.AnAppLimitedSenderDoesNotGrowTheWindow, CongestionControl.CubicDoesNotCountAnAppLimitedStretchAsGrowthTime, TcpAutotune.AnAppLimitedConnectionKeepsItsWindowAndSendBuffer (500 request/response rounds: cwnd stays at IW, send buffer at 128 KiB; before this it reached 2 MB of cwnd). Test changes in test_congestion_control.cpp, all of which modelled an app-limited sender while expecting growth: - acknowledge() defaulted in_flight to 0. It now defaults to FULL_WINDOW, meaning cc.window() at each ack, i.e. a bulk sender. Every test using it (slow start doubling, established_at setup, fast convergence) means a bulk sender. - CubicGrowthIsDrivenByElapsedTime, RenoGrowthIgnoresElapsedTime, TheTcpFriendlyRegion and FastConvergence passed a fixed in-flight (the window they started at) while cwnd grew past it, which would now stop growth one MSS later. They pass each flow's current window. The unused started_at locals went with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
_acceptance_window() took the larger of the advertised window and _rcv_wire_edge_unwrapped, the highest edge the rounded-up scaled field had ever carried, kept as a monotonic max. Once RCV.NXT reached the promised edge and the window went to 0, up to 511 bytes past it were still accepted - including a zero-window probe's byte - so the receive queue grew past its capacity. Acceptance is now _advertised_window(): the free space, or the promised edge, whichever is further. The wire edge is gone. Under a zero window nothing past RCV.NXT is queued, so a probe is acked with window 0 and dropped (RFC 9293 3.8.6.1). RFC 7323 2.4's tolerance for data sent before a retreat of less than one unit is kept as far as the buffer has room - free space is part of the advertised window, so such bytes are accepted whenever the application has read since; otherwise they are trimmed and resent, never queued past the capacity. (Clipping the old wire-edge term to the free space would give the same result, since the advertised window already includes all free space.) New test: TcpAutotune.AZeroWindowProbeIsAckedButNotQueued (full buffer behind a rounded-up edge, zero window, a 1-byte probe: not queued, the ack carries window 0 and the old RCV.NXT, buffered <= capacity; before the fix 131073 of 131072 bytes were buffered). Test changed: RoundingUpTheScaledWindowNeverGrowsTheBufferPastCapacity bounded the buffer at capacity plus one scale unit, which encoded the slack the wire edge allowed. The bound is now the capacity itself (the old code reached 131434 of 131072 under it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
KoganTheDev
force-pushed
the
feat/buffers
branch
from
November 19, 2026 17:40
9469bdb to
1048948
Compare
Owner
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Item C of the follow-up plan. The receive buffer was a fixed 128 KiB with window scale 1, so one connection was capped at 128 KiB per RTT on a long fat path. Stacked on #18 (base retargets to main when #18 merges).
SO_RCVBUF/SO_SNDBUFwith Linux semantics (getsockopt doubles, clamps, listener inheritance, setting locks the size).Results
Review
Two automated security findings (memory charge released while bytes were still buffered; scaled-window rounding ratcheting the edge) and two code-review findings (cwnd growth while app-limited draining the budget; a stale edge accepting past a zero window) are fixed, each with a test that failed before the fix.
Tests
make test(1231), asan, tsan, strict,SIM_SEEDS=2000 make sim,make soak(heap flat),make bench(no regression beyond noise), clang-format, clang-tidy, cppcheck.🤖 Generated with Claude Code