Skip to content

net/tstun,wgengine/netstack: avoid deadlocks on full outbound queues - #21668

Merged
raggi merged 3 commits into
mainfrom
raggi/netstack-blocking
Oct 13, 2026
Merged

raggi merged 3 commits into
mainfrom
raggi/netstack-blocking

Conversation

@raggi

@raggi raggi commented Oct 6, 2026

Copy link
Copy Markdown
Member

gVisor can generate replies on the TUN reader or loopback consumer. If the outbound queue is full, a blocking write can stop the very goroutine needed to make progress. The queue split on main avoids the exact 1.98 cycle in #21638, but the loopback consumer can still block trying to put a reset into its own full queue.

Make queue writes nonblocking, keeping the existing queues and sizes. This gives up the burst backpressure added by 4903d6c: TCP can retransmit, but UDP and other non-retrying traffic may lose packets under load.

Close linkEP before aborting gVisor endpoints so shutdown-generated resets cannot get stuck behind stopped consumers (#21631). Also let netstack cancel an injection already waiting inside tstun. Closing the link queues alone does not release that wait.

Release rejected and canceled packets, drain unread injections when the wrapper closes, and release the capture hook's temporary buffer. Preserve ownership of packets already accepted by the wrapper.

Add fast paths for lock acquisition and enqueue. These bring the extra injection/read cost down from about 42 ns to 8 ns in local benchmarks, without adding allocations. The handoff benchmark still shows roughly 12.5% lower throughput for small packets and 6% lower for 1280-byte packets. End-to-end VPN performance has not been measured.

Add tests for saturation, loopback progress, shutdown, cancellation, and packet ownership, including TCP recovery after forced drops. The deadlock tests fail against the old implementation.

Tested the affected packages and tsnet under -race, with 100 runs of the focused regressions. Also tested the reduced-feature build and cross-compiled for darwin/arm64.

Fixes #21631
Updates #21638
Related: #21632, #21639

@illotum illotum left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two comments and a larger suggestion: after #21665 and its followup land, the tstun part of this diff should mostly collapse. You'll have a smaller diff, and I won't have to churn over your work in mine. Going to post the follow-up end of today, try rebasing on it?

Comment thread wgengine/netstack/netstack.go Resolved
Comment thread wgengine/netstack/link_endpoint.go Resolved
@raggi
raggi force-pushed the raggi/netstack-blocking branch 3 times, most recently from 08b440e to 9b05d33 Compare October 7, 2026 21:46
raggi added 2 commits October 8, 2026 20:56
Make link queue writes nonblocking: gVisor can generate replies on the
reader needed to drain the queue. A full queue drops only the rejected
packet and reports ErrNoBufferSpace, which gVisor counts and TCP handles
by arming its retransmit timer. UDP sockets do not see the error unless
IP_RECVERR is set, matching Linux. Count WireGuard-bound drops as
reason="queue_full" in tailscaled_outbound_dropped_packets_total, and
per-queue drops in debug and client metrics.

Add Wrapper.TryInjectOutbound for best-effort replies generated while
processing packets (TSMP rejects and pongs, conn25 rejects, fake-mode
echo replies), so those paths drop instead of stalling behind the
injection queue's reader. Its drops are also counted as queue_full.

Make outbound injection waits cancellable and close link queues before
abort-generated replies. Stop the WireGuard injection pump on ErrClosed.
Release injected packets still queued at Close, outside closeOnce to
allow reentrant release callbacks; a sender whose send races with Close
releases the packet itself. Release temporary capture buffers.

Copy injected payload views directly into the WireGuard slab, avoiding
an intermediate allocation and copy.

Test queue saturation, multiqueue progress, cancellation, concurrent
shutdown, reference ownership, fragmented payloads, and GSO.

Performance versus the parent commit, on a 4-core Xeon 6975P-C:

  inject+read 64B / 1280B       245ns / 479ns -> 187ns / 195ns, 0 allocs
  4 injectors, 1 reader         843ns -> 451ns
  64KiB GSO inject+split        10.9us -> 4.4us, 64KiB/op -> 0
  link queue write+read         81.4ns -> 81.5ns
  tsnet TCP, 1 / 8 streams      448 / 580 MB/s -> 492 / 674 MB/s

BenchmarkTCPQueueBottleneck shows that dropping on full queues keeps
throughput at the bottleneck rate (117 MB/s at 100k packets/s, as with
blocking writes), at the cost of more retransmits with many streams.

Fixes #21631
Updates #21638
Updates #21632
Updates #21639

Signed-off-by: James Tucker <[email protected]>
…OBUFS

Export ErrInjectionQueueFull, returned by TryInjectOutbound when a full
injection queue forced a packet drop, and define it to wrap
syscall.ENOBUFS on platforms that define that errno. Callers can now
test for buffer exhaustion generically with errors.Is(err,
syscall.ENOBUFS) instead of knowing about tstun's error type. plan9 and
tamago have no ENOBUFS in their syscall packages, so there the error is
a plain sentinel; code that must build on those platforms (or on all
platforms, like feature/conn25) can still match the exported sentinel.

Also stop conn25 from logging queue-full TSMP rejections: those drops
are expected under saturation and are already counted as reason="queue_full"
in the outbound usermetric.

Signed-off-by: James Tucker <[email protected]>
@raggi
raggi force-pushed the raggi/netstack-blocking branch from 5c198b0 to e6c6970 Compare October 9, 2026 01:12

@illotum illotum left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! This does not cover ICMP we generate, does it?

And idle thought, consider if it's worth splitting injection into explicit blocking and nonblocking queues. Pretty sure the machinery will not change, but a blocking InjectX can maintain an independent channel depth.

Edit. And a reminder re tailscale/corp#45544

@raggi

raggi commented Oct 13, 2026

Copy link
Copy Markdown
Member Author

LGTM! This does not cover ICMP we generate, does it?

And idle thought, consider if it's worth splitting injection into explicit blocking and nonblocking queues. Pretty sure the machinery will not change, but a blocking InjectX can maintain an independent channel depth.

Edit. And a reminder re tailscale/corp#45544

We might eventually want a write path that's essentially a caller controlled non-lossy write, so it "blocks"/retries until written or caller driven condition, but I elided that for now as it's a lot to think about in the caller side synchronization challenges

…on queue

Add regression guards for the inbound reply paths (TSMP pong, TSMP
connection reject, and the conn25 unmapped Transit IP reject) that were
made nonblocking via TryInjectOutbound: with the injection queue full
and its reader not draining (as when the reader is blocked behind
wireguard-go's device.peers lock held by RemovePeer), generating a
reply must drop rather than block, because the replying goroutine
must complete for the peer teardown to finish. A blocking injection
there deadlocks peer removal against inbound packet processing, as in
tailscale/corp#45544.

The tests run in synctest bubbles: the full queue is the only blocking
operation on these paths, so after synctest.Wait the reply either
completed or is provably stuck on the queue, and no timeout-based
failure is needed. A regressed, blocking sender is unblocked by
closing the Wrapper before the test fails, so the bubble settles.

Updates tailscale/corp#45544
Updates #21631

Signed-off-by: James Tucker <[email protected]>
@raggi
raggi force-pushed the raggi/netstack-blocking branch from 093c222 to 8a367df Compare October 13, 2026 22:41
@raggi
raggi merged commit fb79793 into main Oct 13, 2026
62 checks passed
@raggi
raggi deleted the raggi/netstack-blocking branch October 13, 2026 22:55
bradfitz added a commit to tailscale/tailcat that referenced this pull request Nov 18, 2026
Before tailscale/tailscale#21668, netstack.Impl.Close blocked forever
once more TCP endpoints needed a reset than its 512-packet outbound
queue held, leaking the WireGuard engine, the DERP connection and
their goroutines. Endpoints stay in TIME-WAIT for 60 seconds, so a
few hundred recent short connections were enough. go.mod already has
the fix; add a test so it stays fixed.

The test hangs in Close against the pre-fix tailscale.com
(a0e471a35b8f) and passes in about 2s now.

Updates #151

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I55d3c83555abecf45250de51da935d8f726fb1fe
knight42 added a commit to knight42/krelay that referenced this pull request Dec 2, 2026
With tailcat v0.7.0, Client.Close hangs forever once more than ~512
tunnel connections closed within the last minute: netstack's Close
blocks queueing RSTs for TIME-WAIT endpoints into its 512-packet
outbound queue (tailscale/tailscale#21668). krelay closes the tailcat
client before deleting the server Job, so Ctrl-C on a busy port-forward
or SOCKS session hangs the CLI and leaves the Job running until its idle
timeout. v0.8.0 pulls in the netstack fix and shortens TIME-WAIT to 5s.

It also makes DERP connections honor HTTPS_PROXY/ALL_PROXY and fall
back to DERP over WebSocket when a proxy blocks the HTTP upgrade.

v0.8.0 replaces Server.AllowedClients with the AllowClient hook and
requires Go 1.27.4. Addresses stay wire-compatible with v0.7.0 as long
as Server.Hybrid is off, so old clients work with a new server image and
vice versa.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

wgengine/netstack: Impl.Close hangs forever when an outbound queue is full

2 participants