Skip to content

device: limit staged packets when pools are bounded - #111

Closed
SunflowersLwtech wants to merge 1 commit into
tailscale:tailscalefrom
SunflowersLwtech:staged-pool-limit
Closed

SunflowersLwtech wants to merge 1 commit into
tailscale:tailscalefrom
SunflowersLwtech:staged-pool-limit

Conversation

@SunflowersLwtech

Copy link
Copy Markdown

Updates tailscale/tailscale#21773

With WithPreallocatedBuffersPerPool (the iOS settings in wgengine/wgcfg/mem_ios.go: 64 buffers, staged queue of 64), the TUN readers and the receive goroutines take packet buffers from the same bounded pool, and a packet staged for a peer without a session keeps its buffer until a handshake completes or gives up. A peer that keeps getting traffic but cannot complete a handshake fills its staged queue and takes every buffer. The TUN reader and the receive goroutines then wait in WaitPool.Get, so nothing moves to or from any peer, including the handshake message that would release the staged packets.

This change limits the packets staged across all peers to half of the pool size when the pool is bounded. After each batch, a TUN reader that finds more than that staged drops the oldest staged batches of the peers with the most staged packets, so a peer that is still waiting for its first handshake keeps its packet. The count is kept only when the pool is bounded; devices with unbounded pools skip it.

Why not the other fixes listed in the issue

  • A smaller staged queue per peer moves the threshold instead of removing it. On the unfixed code with a staged queue of 16 per peer, one unreachable peer is fine, three hold 48 buffers without stalling (that row fails only this change's limit of 32), and four or more stall (raw output below).
  • Not resetting handshakeAttempts on rate-limited sends would end the stall at the 90 s give-up instead of preventing it, and in the exit node runs below the count stopped moving while the device was stalled, so the give-up did not come at all. It would also diverge from the kernel, which resets the count the same way.
  • A separate pool or reserve for the receive path would let a handshake response in, but the TUN reader would still wait for buffers held by staged packets, so traffic to healthy peers and to 100.100.100.100 (answered from tstun.Wrapper.Read) would still stop.

Tests

device/staged_test.go adds an in-memory network (memNet) that can cut a link and add latency, so the tests run in a testing/synctest bubble and cover minutes of handshake timers in well under a second.

  • TestStagedPacketsBoundedPool: one unreachable peer, and eight with a staged queue of 16. Sends twice the pool size to each, then checks that a healthy peer is reachable both ways and that a peer needing its first handshake gets its packet through.
  • TestStagedPacketsExitNode: the worst case. The unreachable peer is an exit node (0.0.0.0/0) over a link with 100 ms one-way latency, the device sends 100 packets/s through it and gets 50 packets/s back. The link is cut for 210 s (past RejectAfterTime), then restored. Checks that a healthy peer stays reachable every second, and that traffic with the exit node resumes within 12 s.
  • TestStagedPacketsCount, TestStagedPacketsCountConcurrent: the staged count against the queues, through trimming, per-peer drops of the oldest batch, keepalives, handshake give-up, peer removal, and four TUN readers at once.

Test teardown flushes staged packets before Device.Close, because on the unfixed code Close (and RemovePeer) can hang in this state: BindClose waits for receive goroutines that are waiting for a buffer, and peer.Stop waits for a keepalive timer callback that is waiting for an outbound element.

Without the fix

origin/tailscale (9d89615) plus staged_test.go without the two count tests, which read the new counter:

=== RUN   TestStagedPacketsBoundedPool
=== RUN   TestStagedPacketsBoundedPool/one_unreachable_peer
    staged_test.go:351: TUN reader blocked after 63 packets to unreachable peers; 64/64 packet buffers in use, 63 staged
=== RUN   TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16
    staged_test.go:351: TUN reader blocked after 63 packets to unreachable peers; 64/64 packet buffers in use, 63 staged
--- FAIL: TestStagedPacketsBoundedPool (0.02s)
    --- FAIL: TestStagedPacketsBoundedPool/one_unreachable_peer (0.01s)
    --- FAIL: TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16 (0.01s)
=== RUN   TestStagedPacketsExitNode
    staged_test.go:469: exit node unreachable for 3m30s: healthy peer unreachable for 15 s; 64/64 packet buffers in use, 63 staged
    staged_test.go:472: healthy peer unreachable for 15 s while the exit node was unreachable
    staged_test.go:482: traffic with the exit node did not resume within 12.1s of the link coming back; 64/64 packet buffers in use, 63 staged
--- FAIL: TestStagedPacketsExitNode (0.28s)
FAIL
FAIL	github.com/tailscale/wireguard-go/device	0.303s
FAIL

With a staged queue of 16 per peer instead of this change (same unfixed tree, extra rows added to the table):

=== RUN   TestStagedPacketsBoundedPool
=== RUN   TestStagedPacketsBoundedPool/one_unreachable_peer
    staged_test.go:354: TUN reader blocked after 63 packets to unreachable peers; 64/64 packet buffers in use, 63 staged
=== RUN   TestStagedPacketsBoundedPool/one_unreachable_peer_staged_16
=== RUN   TestStagedPacketsBoundedPool/three_unreachable_peers_staged_16
    staged_test.go:369: 48 packets staged, want at most 32
=== RUN   TestStagedPacketsBoundedPool/four_unreachable_peers_staged_16
    staged_test.go:354: TUN reader blocked after 63 packets to unreachable peers; 64/64 packet buffers in use, 63 staged
=== RUN   TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16
    staged_test.go:354: TUN reader blocked after 63 packets to unreachable peers; 64/64 packet buffers in use, 63 staged
--- FAIL: TestStagedPacketsBoundedPool (0.07s)
    --- FAIL: TestStagedPacketsBoundedPool/one_unreachable_peer (0.01s)
    --- PASS: TestStagedPacketsBoundedPool/one_unreachable_peer_staged_16 (0.01s)
    --- FAIL: TestStagedPacketsBoundedPool/three_unreachable_peers_staged_16 (0.02s)
    --- FAIL: TestStagedPacketsBoundedPool/four_unreachable_peers_staged_16 (0.02s)
    --- FAIL: TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16 (0.01s)
FAIL
FAIL	github.com/tailscale/wireguard-go/device	0.081s
FAIL

With the fix

=== RUN   TestStagedPacketsBoundedPool
=== RUN   TestStagedPacketsBoundedPool/one_unreachable_peer
=== RUN   TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16
--- PASS: TestStagedPacketsBoundedPool (0.04s)
    --- PASS: TestStagedPacketsBoundedPool/one_unreachable_peer (0.01s)
    --- PASS: TestStagedPacketsBoundedPool/eight_unreachable_peers_staged_16 (0.03s)
=== RUN   TestStagedPacketsExitNode
    staged_test.go:469: exit node unreachable for 3m30s: healthy peer unreachable for 0 s; 34/64 packet buffers in use, 32 staged
    staged_test.go:487: traffic with the exit node resumed 500ms after the link came back
--- PASS: TestStagedPacketsExitNode (0.25s)
=== RUN   TestStagedPacketsCount
--- PASS: TestStagedPacketsCount (0.16s)
=== RUN   TestStagedPacketsCountConcurrent
--- PASS: TestStagedPacketsCountConcurrent (0.04s)
PASS
ok  	github.com/tailscale/wireguard-go/device	0.500s

go test -race ./..., go run ./cmd/check-lockorder and the CI cross-build matrix pass. The lock-order checker reports 252 lock-after observations against 250 before, and no edge from the base is lost.

Mutations

Each row breaks one part of the change and runs go test -race -count=3 -run TestStagedPackets ./device:

Mutation Failing tests (of 3 runs)
M1 no trim after a TUN batch BoundedPool 3, ExitNode 3, Count 3
M2 trim the peer with the fewest staged instead of the most BoundedPool 3 (a new peer's first packet is dropped), Count 3
M3 no decrement when SendStagedPackets takes a batch Count 3, CountConcurrent 3
M4 no increment in StagePackets BoundedPool 3, ExitNode 3, Count 3, CountConcurrent 3
M5 no decrement in FlushStagedPackets Count 3
M6 limit is the whole pool instead of half BoundedPool 3, ExitNode 3
M7 no decrement in trimStagedPackets BoundedPool 3, Count 3, CountConcurrent 2
M8 no increment for a staged keepalive Count 3
M9 no decrement when a full staged queue drops its oldest batch Count 3
M10 count the batch after it is in the queue (len(elems.elems) after the send) CountConcurrent 1, with a data race reported

M10 is a data race rather than a logic error, so it is caught only under -race, and not in every run; the count is taken before the batch is handed to the queue for that reason.

How long the exit node case lasts without the fix

A variant of TestStagedPacketsExitNode (not included) that, after the link comes back, waits up to 10 minutes and records in 10 s steps whether traffic reaches the exit node again:

one-way latency packets/s out, back unfixed: traffic resumed after fixed
0 ms 100, 50 4m46s, 8m4s, 9m10s, 9m10s, 9m10s, not in 10 min 3 of 3 runs within 10 s
50 ms 100, 50 not in 10 min 3 of 3 within 10 s
100 ms 100, 50 1m17s, 4m46s, not in 10 min (4 runs) 3 of 3 within 10 s
100 ms 500, 50 not in 10 min 3 of 3 within 10 s
150 ms 200, 100 not in 10 min 3 of 3 within 10 s
100 ms 500, none 2m56s 3 of 3 within 10 s
100 ms 100, none 1m17s not run

An earlier version of the test, without latency and with a 10 minute deadline, recovered once after 1m11.6s. The three 9m10s results match the zeroKeyMaterial timer (3 × RejectAfterTime, which flushes the staged queue) if it was armed by a handshake right after the link came back; that is not confirmed. In the four stalled runs of the first sweep the handshake attempt count stayed at 7 for the whole 10 minutes, and in another run it went to 0 after one give-up and stayed there, so the 90 s give-up that ends the stall in the original report stopped happening. I have not traced why the retransmit timer stops; this change does not depend on it.

End to end with tailscaled

Three tailscaled processes on one Linux host in userspace-networking mode, with the tstest/integration test control server and DERP server: a "phone", an exit node (0.0.0.0/0 approved with testcontrol.Server.SetSubnetRoutes) and a healthy peer. All three are built from tailscale main with go.mod replacing wireguard-go with either 9d89615 or this branch, plus a local patch (not proposed anywhere) that makes the phone use the mem_ios.go options and a batch size of 1 on Linux when an environment variable is set.

With that batch size, magicsock's Linux UDP receive funcs exit at startup (len(packets): 1 < MinimumReadBatchSize(64)), so the phone used DERP only, as an iPhone away from home often does. That is also why both runs report "The MagicSock function ReceiveIPv4 is not running"; it has nothing to do with this change and is left out below.

The phone keeps 64 connection attempts to 198.51.100.0/24 going through its SOCKS5 proxy (about 20 per second, all through the exit node) and, once a second, sends a TSMP ping with a 1 s timeout to the exit node and to the healthy peer. The exit node is frozen with SIGSTOP for 200 s, resumed with SIGCONT, and the phone is observed for 300 s more.

9d89615 this branch
pings to the healthy peer while the exit node is frozen failing from 169 s after the freeze, when the session with the exit node expired all answered
pings to the exit node after it resumes 0 of 101 answered in 300 s answered from 7.0 s on, 292 of 296
pings to the healthy peer after the exit node resumes 0 of 101 answered 296 of 296
9d89615:     STALL SUMMARY stopped=3m20s healthy_down_while_stopped=12s first_exit_ping_after_resume=-1ns exit_ping_ok_secs_after_resume=0/5m0s healthy_down_after_resume=101s
this branch: STALL SUMMARY stopped=3m20s healthy_down_while_stopped=0s first_exit_ping_after_resume=6.99997883s exit_ping_ok_secs_after_resume=292/5m0s healthy_down_after_resume=0s

(The counts are probes, not seconds: on 9d89615 each probe took about 3 s because both pings timed out.)

Goroutines of the 9d89615 phone during the stall, from its /debug/pprof/goroutine?debug=2, trimmed:

goroutine 99 [sync.Cond.Wait]:
github.com/tailscale/wireguard-go/device.(*WaitPool).Get
github.com/tailscale/wireguard-go/device.(*Device).GetOutboundElement(...)
github.com/tailscale/wireguard-go/device.(*Device).RoutineReadFromTUN(...)

goroutine 105 [sync.Cond.Wait]:
github.com/tailscale/wireguard-go/device.(*WaitPool).Get
github.com/tailscale/wireguard-go/device.(*Device).getPacketBuf(...)
github.com/tailscale/wireguard-go/device.(*Device).RoutineReceiveIncoming(...)

Goroutine 105 is the DERP receive goroutine, the only one left. On this branch at the same point, the TUN reader is in select and the DERP receive goroutine is in magicsock.(*connBind).receiveDERP.

Cost

Unbounded pools: a branch on a field that does not change after NewDevice, at each place a batch enters or leaves a staged queue. Bounded pools: an atomic add at those places and an atomic load per TUN read; the peer scan in trimStagedPackets runs only when the limit is exceeded, which takes a peer that cannot complete a handshake.

With WithPreallocatedBuffersPerPool, the TUN readers and the receive
path take packet buffers from the same bounded pools, and a packet
staged for a peer without a session holds its buffer until a handshake
completes or gives up. A peer that keeps getting traffic but cannot
complete a handshake fills its staged queue, which with the iOS
settings (64 buffers, a staged queue of 64) takes every buffer. The
TUN readers and the receive goroutines then block in WaitPool.Get,
which stops traffic to and from all peers, including the receive of a
handshake message that would release the staged packets.

The stall ends when handshake attempts give up and flush the staged
queue, about 100s later. When the unreachable peer is an exit node,
traffic keeps coming both ways, and in tests the give-up stopped
happening: the stall outlasted the outage by minutes, or did not end
within 10 minutes of the exit node being reachable again.

When pools are bounded, limit the packets staged across all peers to
half of the pool size. A TUN reader that stages past the limit drops
the oldest staged batches of the peers with the most staged, so that a
peer that is still waiting for its first handshake keeps its packet.
Devices with unbounded pools keep no count and are unaffected.

Updates tailscale/tailscale#21773

Signed-off-by: LiuWei <[email protected]>
@bradfitz

bradfitz commented Nov 6, 2026

Copy link
Copy Markdown
Member

Thanks! This looks good to me (minimal, nice tests) and seems like a reasonable short-term fix that doesn’t get in the way of the future buffer management rework.

Objections, @tailscale/dataplane, @raggi?

@bradfitz

Copy link
Copy Markdown
Member

This should now be addressed by #128

@SunflowersLwtech, can you confirm?

@bradfitz bradfitz closed this Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants