Commit Graph
14 Commits
Author SHA1 Message Date
Brad Fitzpatrick 867eaea830 kernel/linux/src: recruit fewer crypt workers, and go inline for slow peers
One 7 Gbps tunnel between 128-CPU hosts had its crypt work spread over
33 CPUs, each about 15% busy, mostly waking up and going back to sleep,
for up to 1.6x wireguard-go's CPU per GB: a worker was recruited
whenever more than one GRO packet's worth waited, which GRO's bursts
always did. Now one is recruited only when more than recruit_factor
(default 16) times that waits for each worker draining, capped at a
quarter of the ring, and from a compact set of CPUs after the caller's,
twice as many as were draining at once in the last 10ms, rather than
round robin over every CPU.

And for request/response traffic, the handoff to a worker is on each
response's critical path, so a local socket's bulk sends to a peer
sending under tx_inline_mbps (default 2000) are encrypted inline, and
rx_inline_mbps drops from 4000 to 1000, so faster peers' receives go
the parallel way sooner.

Between two c6in.32xlarge hosts on EC2, at EC2's per-flow limit, tswg
now uses 0.52-1.02x wireguard-go's CPU per GB (was up to 1.6x), and one
HTTP-like stream gets 3.0 Gbps to its 3.3 (was 2.5). Crawling 37 peers
goes from 76 to 89 Gbps; routing and serving are unchanged.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I777adf1eadb4f309c62111ed3b2695a816350c56
2026-11-08 23:20:47 +00:00
Brad Fitzpatrick b74f56be78 kernel/linux/{src,DESIGN.md}: pick steering homes by load; record wireguard-go's best
Steering homes were the first CPU, from a point a peer's ID hashed to,
not receiving from the NIC or known to be overloaded. But a CPU learned
its own load only when it received from the NIC, which homes don't, so
busy homes looked idle, and peers piled onto a few. Now any CPU's load
comes from its idle time (get_cpu_idle_time_us, for any CPU), and a
peer's home is the least loaded of 8 spread from its hash, kept while
it isn't overloaded. With 37 peers on 11 of the NIC's 32 queues (this
boot's RSS key), uploads through the router go from 28 to 44 Gbps,
crawling from 42 to 51.

Also record wireguard-go's scaling with flow count across all the
scenarios, so as not to misrepresent it: 6-11 Gbps from 1 client to 37,
and 1 flow each to 64, best with fewer flows, using 3-6% of the host's
CPU (serialized, not CPU-bound), and unmoved by GOGC or GOMAXPROCS. And
what the sweep found against tswg: on one tunnel between big hosts, both
at EC2's per-flow limit, tswg uses up to 2x wireguard-go's CPU per GB;
and the NIC's random RSS key decides how many queues few peers get,
which swung tswg's results 2x between boots.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I0760b24dd84f246005a4bc7c43429a016287223d
2026-11-08 20:36:38 +00:00
Brad Fitzpatrick 96695d4464 kernel/linux/src: scale a big host serving and crawling many peers
A 128-CPU host on the tailnet, serving HTTP-like responses to 37 peers
or crawling them all at once, was held back by three things, each fixed
here:

Sending by combining: a peer's encrypted packets went out from its tx
worker, one work item on one CPU at a time, which on a NIC without UDP
segmentation offload (EC2's ENA) also segments them, so the CPUs the
tx workers landed on ran at 90% and more. Now the encrypt worker that
makes an entry ready sends what's ready, in order, itself, unless
another CPU is sending the peer's (a trylock), which then sends it.

Local sockets' lone packets (TCP's ACKs, small requests) are encrypted
and sent inline, when nothing of the peer's is on its way through the
workers to be overtaken: a crawler spent 7% of its CPU on the encrypt
ring's lock for its ACKs.

Steering: with more peers than NIC queues, RSS puts several peers' UDP
flows on some CPUs, and receiving inline left those at 100% and the
rest idle. When a CPU is over rx_steer_busy (default 90%) busy, by its
idle time, or its softirq work runs out of budget, its peers' packets
go to each peer's home CPU (one not receiving from a NIC, by hash)
through a lockless per-CPU list and that CPU's NAPI: RPS, per peer, for
our packets, when needed. A peer changes between inline, steered and the
parallel way only when the way it was going is empty, so as not to
reorder.

On EC2 (c6in.32xlarge, 32 NIC queues, MTU 1280): serving goes from
84-98 to 133-137 Gbps (plain TCP without a tunnel: 152; wireguard-go:
5.5), at 3.9 CPU-s/GB, and crawling from 41-51 to 80-83 (plain: 128;
wireguard-go: 8.5), where the NIC's busiest queues, with two or three
peers each, are at ENA's limit of about 680k packets per second.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I011ab98d61296b5beef172ae1581d463820179a5
2026-11-08 11:52:01 +00:00
Brad Fitzpatrick 925022517f kernel/linux/src: run forwarded packets and most received ones to completion
On a 128-CPU subnet router sending big responses to hundreds of flows,
75-83% of the router's CPU spun on the encrypt ring's consumer lock.
Upstream's design hands every packet to a crypt worker on another CPU,
through a ring all CPUs share, and back through the peer's in-order
queue to a third, so that one flow's packets can be encrypted in
parallel and still go out in order. Forwarded packets don't need that:
RSS already spreads flows over CPUs and keeps each in order on one.

So tswg_xmit_now encrypts and sends packets with no socket (forwarded)
right in wg_xmit, on the CPU they arrived on, as IPsec does: no queues,
rings or other CPUs. Local sockets' packets still go to the workers, so
that one flow is encrypted on several CPUs; much of a TCP sender's
sending is in softirq too, as ACKs arrive, and inlining it cost a
stream half its throughput. Module parameter tx_inline: 0 never, 1
forwarded (the default), 2 always.

And tswg_receive_now decrypts a peer's packets in encap_rcv, on the CPU
its UDP flow arrives on, delivering them through the device's per-CPU
GRO cells, as VXLAN does, rather than through the decrypt ring, a
worker, the peer's in-order queue and its NAPI. That's one CPU per peer,
which a fast one outruns (a stream: 12.2 -> 6.4 Gbps in the lab), so a
peer receiving more than rx_inline_mbps (default 4000) over 10ms goes
the parallel way for at least 100ms, coming back once that way has
delivered what it had, so that switching doesn't reorder.

On EC2's 128-CPU c6in router with 37 clients: HTTP-like fetches go from
37 to 69 Gbps, and 27 to 3.7 CPU-s/GB; uploads from 66 to 68 Gbps, and
6.8 to 3.1 CPU-s/GB; wireguard-go does 6.2 either way. The 32 CPUs
taking the NIC's interrupts are now the limit, which RPS lifts for
fetches to 78 Gbps. In the lab, one stream through a tunnel is
unchanged at 12 Gbps, and RTT under load is down from 1.5 to 1.1ms.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I8b1cbbed3c87a8e6a9a7cf8a91a2c18dcfb4e62a
2026-11-08 06:48:49 +00:00
Brad Fitzpatrick ee627ef16e kernel/linux/src: implement wireguard-go's hybrid post-quantum handshake
Tailscale's wireguard-go has a hybrid handshake,
Noise_IKhfs+psk2_25519+MLKEM768, which both peers must agree to use,
with no fallback to the classic one. A kernel-mode node without it
would be cut off from any peer that asked for it.

The initiation now may carry an ephemeral ML-KEM-768 encapsulation
key, sealed under the es key (with the static key then using nonce
1), and the response a ciphertext for it, sealed under the ee key,
whose shared secret is mixed into the chaining key before se. That's
per peer, with the new TSWGPEER_F_HYBRID flag. Hybrid retries carry
wireguard-go's retry bit (bit 31 of the type), which we accept, set and
echo, and which the socket's message classifier now allows.

Linux has no ML-KEM, and its SHA-3 is too new for the kernels we build
for, so src/mlkem.c is a FIPS 203 ML-KEM-768 with its own Keccak.
tests/mlkem checks it against Go's crypto/mlkem: the same keys from the
same seeds, each decapsulating the other's ciphertexts, and the same
implicit rejection. The natlab tests in tailscale.com check the
handshake against wireguard-go, in both roles.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ic524483d6cd27d36900a730553e1b21e4530c399
2026-11-08 02:24:12 +00:00
Brad Fitzpatrick c306c02b44 kernel/linux/src: do lone packets' crypto inline, and run NAPI in softirq
Handing a packet to a crypt worker, the tx worker or a NAPI kthread on
another CPU can wake a halted vCPU, which in a VM is a VM exit and a
trip through the host's scheduler. tswg's idle round trip time was
1.5-2x wireguard-go's in VMs because of it.

So when the crypt workers look idle, a packet that isn't part of a
batch is encrypted or decrypted where it is, after going on the peer's
in-order queue as before. To keep TCP ACKs under load from moving
crypto onto the CPUs taking the NIC's interrupts (8% off a subnet
router), it's limited to 8 packets per CPU per jiffy, and never done
for encryption from softirq (forwarding). And peers' NAPI runs in
softirq again, not kthreads, unless napi_threaded is set.

Idle RTT p50 is now 0.51ms in the lab (wireguard-go 0.60) and 0.75ms
on EC2 (0.97), with subnet router throughput unchanged at the same
NAPI setting. Threaded NAPI is still 4-5% faster for a CPU-bound
router.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ib5ebd1edcda1a515dac0ae4e55540bcfe52d1d7f
2026-11-08 00:43:31 +00:00
Brad Fitzpatrick 7e5804da87 kernel/linux/src: add zero-copy receive behind a module parameter, off by default
rx_zerocopy (writable at /sys/module/tswg/parameters/rx_zerocopy) makes
tswg_decrypt_gso decrypt data messages in place in the received packet's
pages, when nothing else can see them, and hand out packets that
reference those pages, rather than copy each message into a new packet.

It's off because it doesn't pay: on a CPU-bound subnet router it was 7%
slower, scatterlist decryption costing more than linear decryption of a
cache-hot copy, and on a 200 Gbps c6in.32xlarge router, where the NIC
interrupt CPUs' page allocation is the limit, it took tswg's own page
allocations out but was still no faster (62.5-63.3 Gbps against
63.4-64.7) at 10% more CPU per byte, since ENA's page per received
packet is what binds. It stays for NICs and loads where it might.

The copying path, unchanged, moves into tswg_decrypt_message_copy.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ieb6aa3531f869dd47d768fe367c424fbd22aa3f1
2026-11-07 21:49:17 +00:00
Brad Fitzpatrick 34e785a933 kernel/linux/src: decrypt straight from received packets, and in one ChaCha20 pass
Profiling a CPU-bound tswg subnet router (EC2, 4 CPUs) found two costs
in decrypting merged packets:

Copying. Each message was copied out of the received packet and then
decrypted in place in the copy, two passes over it. When the message is
contiguous in the received packet (in its head or one page frag, as a
message received in one datagram is), decrypt straight from it into the
new packet instead (tswg_contig).

The Poly1305 key. lib/crypto makes it from a separate 32 bytes of
ChaCha20 keystream (block 0), and x86's ChaCha20 does anything up to a
block with its portable code: a scalar ChaCha20 block per message, 5.5%
of the router's CPU. tswg_aead.h has our own ChaCha20-Poly1305 for data
messages, from the library's primitives. When decrypting from one buffer
to another, it runs ChaCha20 from block 0 over the 64 bytes before the
message too (packet headers in the source, headroom in the destination),
and recovers block 0's keystream, the Poly1305 key, as the two XORed:
one SIMD pass per message (tswg_aead_decrypt_ahead). Otherwise, and for
encryption, it asks for two blocks of keystream, which takes the SIMD
path, and sets the counter back.

The 4-CPU router, 4 clients with 16 flows each, medians of 3 runs: 14.1
to 14.9 Gbps, 2.30 to 2.18 CPU-seconds per GB (wireguard-go: 6.6 Gbps,
3.36). Interop with wireguard-go is unchanged; KASAN is quiet.

Also tried, and not kept: zero-copy receive (decrypting in place in the
received pages, 7% worse), and a page pool for decrypted packets (its
pages didn't come back in time to save allocations).

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I98456d17b82d5ef640c55ca1a7fa7a018dc5a279
2026-11-07 18:51:47 +00:00
Brad Fitzpatrick 51ec695feb kernel/linux/src: restore TCP backpressure, and fix tx and queue latency
RTT under a TCP load had grown to about 11ms at p99 (wireguard-go: 3.7).
Instrumenting the queues found three causes:

Backpressure. Upstream encrypts in place, so a packet stays charged to
its socket (for TCP, counted by its small queues, TSQ) until the NIC has
sent it, and TCP is held to the NIC's pace. Our encrypted packets are
new (and earlier ones were orphaned), so TCP could fill the NIC's qdisc
as fast as we encrypt: on a slow uplink with a FIFO qdisc, that would be
massive bufferbloat. Now each encrypted packet takes over its packets'
socket ownership and charge (tswg_move_owner), for destructors that
just uncharge truesize (sock_wfree, and TCP's), settled to its real
size (segments' truesize is about twice their length). TSQ then allowed
TCP only about 1ms in flight, which cost 15-20% of throughput, so
sockets sending over tswg get sk_pacing_shift 9 (about 2ms), as Wi-Fi
drivers set 8 for their aggregation.

The tx worker. Upstream pins a peer's tx worker to one CPU by peer ID.
When that's the CPU taking the NIC's interrupts, softirq work starves
it, and encrypted packets waited up to 20ms to be sent. Queue it on the
CPU that finished encrypting instead (also saving an IPI).

Queue length. The peer queue's limit counted entries, but a GRO entry
is up to 64 packets; count packets, with a limit of 2048.

Medians of interleaved runs in the lean harness, tswg vs. wireguard-go:
TCP 1 stream 10.1 vs. 9.7 Gbps, 4 streams 12.3 vs. 10.8; RTT under load
p50 1.7 vs. 1.7ms. p99 under load is still about 10ms on this testbed:
at full load, the receiving VM's workers sometimes don't run for tens of
milliseconds. That's next to investigate.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ief80aac9a1e443727c89b990c86c7c8f71690954
2026-11-07 14:32:55 +00:00
Brad Fitzpatrick c9f9c52c0c kernel/linux/src: add GRO for WireGuard data messages, and decrypt merged packets whole
Our UDP sockets now have gro_receive/gro_complete callbacks, as UDP
tunnels do. They merge consecutive data messages of a flow that use the
same receiving key and are all the same size but perhaps the last, and
UDP hands the merged packet (SKB_GSO_UDP_TUNNEL) to encap_rcv whole. It
goes through the decrypt ring and the peer's queue as one entry: one
worker decrypts each message into a new packet (copying it out and
decrypting in place there, rather than linearizing in place), and the
peer's NAPI poll delivers them in order. So the IP/UDP input path, the
ring and queue handoffs and the worker kick are paid once per merged
packet rather than per packet. Upstream gets no outer GRO at all.

skb_gro_receive isn't exported to modules, so socket.c has a copy
(tswg_gro_merge). gro_receive_network_flush and udp_tunnel_update_gro_rcv
are newer than 6.8, so they're probed. The latter matters: 7.x may make
the socket's gro_receive a static call, which detaching a user socket
must undo, or it would outlive the module.

Bulk TCP in the lean harness, now with guest USO off (so the receiving
VM sees individual datagrams, as from a physical network): about 9.8
Gbps, against 6.5 before, and within a few percent of wireguard-go
(about 10.0), at about 18% less receiver CPU. Making workers poll the
ring briefly before going idle (to save wakeup IPIs) was tried and
didn't help, so isn't included.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ic22482120c6ce75b9a4d896f16b6cf77aca28b4c
2026-11-07 13:29:26 +00:00
Brad Fitzpatrick 2c3ba4df08 kernel/linux/src: encrypt into page frags, and kick crypt workers on demand
Three changes to the data path, from profiling bulk TCP in the lean
harness:

Encryption. Upstream encrypts each packet in place, which first means
making it linear and writable (skb_cow_data, usually a copy), and the
previous commit then chained the encrypted packets as a GSO frag_list,
which segmentation copied again (skb_segment must unshare each clone's
head to write its headers). Now the encrypt worker copies each inner
packet (finishing its checksum on the way, if needed) into pages of its
own, encrypts it there, and gathers each run of equal-size messages into
a UDP GSO packet whose payload is those pages. Segmenting that needs only
page references, and a device with UDP segmentation offload takes it
whole: virtio with USO now sends 64KB superpackets. Sender CPU at the same
throughput went from about 65% to 43% per vCPU.

Worker kicks. Instead of kicking a crypt worker per packet (or per 16),
kick only when no worker is draining the ring, or when the backlog shows
the busy ones aren't keeping up, and prefer other CPUs than the one
taking packets from the NIC. A tswg_busy flag, paired with the ring
under full barriers, closes the race with a worker going idle.

Queue length. The peer's in-order queue overflowed at 1024 packets (1.5ms
at 7 Gbps) whenever a decrypt worker was held up, and TCP took those
silent drops (0.2% of packets) as congestion. Allow 4096 entries, and
count drops in rx_dropped and rx_fifo_errors, which upstream doesn't.

The receiver is now the bottleneck (about 6.5 Gbps): UDP packets arriving
coalesced are segmented back, with software checksums, before reaching
encap_rcv. That's next.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ib8d9cf9e5541b665e06d57a16b46f653d49bc3ea
2026-11-07 12:26:13 +00:00
Brad Fitzpatrick 1b969a6b3a kernel/linux/src: multicast peer events so that userspace needn't poll
tailscaled was dumping the device every second to notice new sessions
(to send its disco key advertisement, as wireguard-go does) and traffic
on direct paths (to keep magicsock heartbeating active sessions).

Instead, multicast TSWG_CMD_PEER_EVENT messages on a new "events"
genetlink group, in the device's network namespace: one when a new
session is established (from wg_timers_session_derived), and TX and RX
activity notices, each rate limited to one per peer every 2 seconds with
a single comparison on the packet path. Messages are only built when
someone is listening.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I08bdaa23a9f9b01a0bb3a4404296cae5961cde86
2026-11-07 05:37:16 +00:00
Brad Fitzpatrick 189b463b86 kernel/linux/src: add a per-peer flag to stop roaming
Upstream WireGuard moves a peer's endpoint to the source of each
authenticated packet. In Tailscale, disco picks the path, so that would
fight it: a packet that arrives via DERP would steal the endpoint from a
good direct path.

Add TSWGPEER_F_NO_ROAM, set through TSWGPEER_A_FLAGS nested in a new
WGPEER_A_TSWG attribute (numbered 64, like WGDEVICE_A_TSWG) and reported
in dumps. With it set, the endpoint learned from handshake initiations,
handshake responses and data packets is ignored once the peer has an
endpoint, and only userspace changes it. A peer with no endpoint yet
still gets one from its first authenticated packet, so it stays
reachable if it contacts us before userspace has configured one.

The gate, tswg_peer_may_roam, sits at the two learned-endpoint paths
rather than in wg_socket_set_peer_endpoint, which netlink also uses for
explicit updates. The flag is applied before WGPEER_A_ENDPOINT in the
same request, so pinning and setting an endpoint are one step.

Tested by TestTSWG{Gokrazy,Ubuntu}NoRoam in tailscale.com's natlab
vmtests, which fail as expected with the gate disabled.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I621a6e86d3947e154c4cfa582aa845bb49d42b2f
2026-11-06 23:07:32 +00:00
Brad Fitzpatrick af92b849a7 kernel/linux/src: fork WireGuard as the out-of-tree tswg module
Copy upstream/drivers/net/wireguard into src and rename only the
user-visible identifiers: the module (and thus the rtnl link kind and
device type, which come from KBUILD_MODNAME) is now tswg, and the
genetlink family is "tswg". The uapi header moves to
src/include/uapi/linux/tswg.h so it can't collide with the kernel's.
Internal wg_ symbols keep their names to keep upstream merges easy; they
aren't exported, so tswg.ko can coexist with wireguard.ko.

Add an out-of-tree Kbuild and top-level Makefile, plus
scripts/ubuntu-headers.sh, which fetches and unpacks an Ubuntu kernel's
headers so we can build for the natlab Ubuntu guest without installing
anything.

This still only builds against 7.4-era kernels; compat shims follow.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Ia36ef82a53efbbcdb301ed069785162372efda55
2026-11-06 20:55:25 +00:00