From 5e2822f9b624ca3cd292d25947202b5f677e3785 Mon Sep 17 00:00:00 2001 From: Kabir Sikand Date: Wed, 29 Jul 2026 17:56:58 +0000 Subject: [PATCH] net/tstun: hoist the subnet route lookup table onto the Wrapper Gating the packet path on subnetCountersActive() cost a second atomic load on every packet, because it loaded the subnetCounters and then its table. Measured, that doubled what a node with counting disabled pays: 0.375 -> 0.735 ns/op. The subnetCounters must survive a disable, but the packet path never needs the object itself, only the table. Publishing the table on the Wrapper puts the gate back to one nil-able atomic load, and lets the hooks take a *bart.Table[*routeCounters] and do the lookup directly. linux/arm64, 5-route table, 2M iterations: disabled hook 0.375 -> 0.394 ns/op 0 allocs (parity) enabled hook 66.9 -> 64.8 ns/op 0 allocs Updates tailscale/corp#45684 Change-Id: I8a4292268c0a78cdcf567720119bf144a3072bab Signed-off-by: Kabir Sikand --- net/tstun/subnetmetrics.go | 15 ++++++--- net/tstun/subnetmetrics_test.go | 23 ++++++++------ net/tstun/wrap.go | 55 ++++++++++++++++----------------- 3 files changed, 51 insertions(+), 42 deletions(-) diff --git a/net/tstun/subnetmetrics.go b/net/tstun/subnetmetrics.go index 28da4ca21..8c0cf6a2a 100644 --- a/net/tstun/subnetmetrics.go +++ b/net/tstun/subnetmetrics.go @@ -112,9 +112,12 @@ type subnetCounters struct { // route containing it. setRoutes swaps in a wholly new table rather than // mutating the published one, so the packet path needs no locking. // - // It is nil when no countable route is advertised, which is how the packet - // path skips its work: see [Wrapper.subnetCountersActive]. - table atomicPrefixTable + // It holds nil when no countable route is advertised, which is how the + // packet path skips its work. It is owned by the [Wrapper] rather than + // stored inline here so that the packet path reaches it with a single + // atomic load, without first loading the subnetCounters: a node that has + // not opted in must pay no more than one nil check per packet. + table *atomicPrefixTable // counters holds the counters for every route advertised recently, // including withdrawn ones, up to maxRetainedRoutes entries. @@ -156,9 +159,11 @@ func (a *atomicPrefixTable) store(t *bart.Table[*routeCounters]) { } // newSubnetCounters returns a subnetCounters that publishes its per-route -// series into reg. It starts with no routes, i.e. inactive. -func newSubnetCounters(reg *usermetric.Registry) *subnetCounters { +// series into reg and its lookup table into table. It starts with no routes, +// i.e. inactive. +func newSubnetCounters(reg *usermetric.Registry, table *atomicPrefixTable) *subnetCounters { sc := &subnetCounters{ + table: table, counters: map[netip.Prefix]*routeCounters{}, active: map[netip.Prefix]bool{}, } diff --git a/net/tstun/subnetmetrics_test.go b/net/tstun/subnetmetrics_test.go index 9a4f55a14..43d12d475 100644 --- a/net/tstun/subnetmetrics_test.go +++ b/net/tstun/subnetmetrics_test.go @@ -16,6 +16,12 @@ import ( "tailscale.com/util/usermetric" ) +// newTestSubnetCounters returns a standalone subnetCounters with its own +// registry and lookup table, for tests that don't need a whole Wrapper. +func newTestSubnetCounters() *subnetCounters { + return newSubnetCounters(new(usermetric.Registry), new(atomicPrefixTable)) +} + // routeCountsFor returns the four counter values for the given route, or // zeroes if the route is not being counted. func routeCountsFor(t *testing.T, sc *subnetCounters, route string) (txBytes, rxBytes, txPackets, rxPackets int64) { @@ -85,7 +91,7 @@ func TestSubnetCountersAttribution(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() sc.setRoutes(mustPrefixes(t, tt.routes)) remote := netip.MustParseAddr(tt.remote) @@ -121,7 +127,7 @@ func mustPrefixes(t *testing.T, ss []string) []netip.Prefix { } func TestSubnetCountersDirections(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() sc.setRoutes(mustPrefixes(t, []string{"10.1.0.0/16"})) // Two packets into the subnet, one back out of it. @@ -145,8 +151,7 @@ func TestSubnetCountersDirections(t *testing.T) { } func TestSubnetCountersRouteWithdrawal(t *testing.T) { - reg := new(usermetric.Registry) - sc := newSubnetCounters(reg) + sc := newTestSubnetCounters() sc.setRoutes(mustPrefixes(t, []string{"10.1.0.0/16", "192.168.0.0/24"})) sc.forAddr(netip.MustParseAddr("10.1.2.3")).add(100, false) @@ -196,7 +201,7 @@ func seriesCount(sc *subnetCounters) int { // implementation formats the prefix into a label value on every packet, which // costs two allocations and roughly 4.7x the time; see the design doc. func TestSubnetCountersNoAllocs(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() sc.setRoutes(mustPrefixes(t, []string{"10.0.0.0/8", "10.1.0.0/16", "192.168.0.0/24"})) addr := netip.MustParseAddr("10.1.2.3") @@ -354,7 +359,7 @@ func aggregateRegisteredCount() int { // the aggregates, which are counters) but unbounded retention lets an // unexpectedly churning route set grow memory without limit. func TestSubnetCountersRetentionBound(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() // Churn far more distinct routes than the cap, counting a byte on each so // that eviction has to preserve something. @@ -400,7 +405,7 @@ func TestSubnetCountersExitNodeOnlyNotEnabled(t *testing.T) { // countSubnetRouteTraffic can never attribute a packet to one, and publishing // four permanently-zero series would read as "this route is idle". func TestSubnetCountersViaRouteExcluded(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() // 4via6 form of 10.1.0.0/16 through site 7. via := netip.MustParsePrefix("fd7a:115c:a1e0:b1a:0:7:a01:0/112") if !tsaddr.IsViaPrefix(via) { @@ -573,7 +578,7 @@ func TestSubnetCountersHotPathNoAllocs(t *testing.T) { func BenchmarkSubnetCountersAdd(b *testing.B) { b.ReportAllocs() - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() sc.setRoutes(benchRoutes) addr := netip.MustParseAddr("10.1.2.3") for range b.N { @@ -777,7 +782,7 @@ func TestWrapperSubnetRouteCountingOffByDefault(t *testing.T) { // The aggregates are process-global and other tests in this package register // counters with them, so this compares deltas rather than absolute values. func TestSubnetCountersAggregateAgreement(t *testing.T) { - sc := newSubnetCounters(new(usermetric.Registry)) + sc := newTestSubnetCounters() sc.setRoutes(mustPrefixes(t, []string{"10.1.0.0/16", "192.168.0.0/24"})) base := [4]int64{ diff --git a/net/tstun/wrap.go b/net/tstun/wrap.go index 5fd9da420..0d7bc8086 100644 --- a/net/tstun/wrap.go +++ b/net/tstun/wrap.go @@ -223,14 +223,19 @@ type Wrapper struct { // subnetRouteCounters counts forwarded traffic per advertised subnet // route. It is nil until SetSubnetRoutes is called with at least one - // countable route, so nodes that are not subnet routers, and nodes that - // have not opted in, pay only a nil load on the packet path. + // countable route, and stays non-nil afterwards even while counting is + // disabled, because it owns registrations that cannot be undone. // - // Once created it stays non-nil, because it owns registrations that cannot - // be undone; use [Wrapper.subnetCountersActive] on the packet path, which - // also covers the currently-disabled case. + // The packet path does not read it: it reads subnetRouteTable, which is + // non-nil exactly when traffic should be counted. So a node that is not a + // subnet router, or has not opted in, pays a single nil atomic load. subnetRouteCounters atomic.Pointer[subnetCounters] + // subnetRouteTable is the published lookup table of subnetRouteCounters, + // or nil when no countable route is advertised. See + // [Wrapper.subnetCountersActive]. + subnetRouteTable atomicPrefixTable + // selfAddrs holds this node's own Tailscale addresses, used by the subnet // counters to tell forwarded traffic from the node's own. Nil until // SetSelfTailscaleAddrs is called. @@ -936,8 +941,8 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) { // Traffic leaving the TUN toward a tailnet peer: on a subnet router // this is a response coming back out of the subnet, so it is rx. // p is already decoded here, so attribute it without re-parsing. - if sc := t.subnetCountersActive(); sc != nil { - t.countSubnetRouteParsed(sc, p, true) + if tbl := t.subnetCountersActive(); tbl != nil { + t.countSubnetRouteParsed(tbl, p, true) } // Make sure to do SNAT after filtering, so that any flow tracking in @@ -1118,9 +1123,9 @@ func (t *Wrapper) injectedRead(res tunInjectedRead, outBuffs [][]byte, sizes []i } // Injected packets travel the same direction as Read: out to a tailnet // peer, i.e. rx from the subnet router's point of view. - if sc := t.subnetCountersActive(); sc != nil { + if tbl := t.subnetCountersActive(); tbl != nil { for i := range n { - t.countSubnetRoutePacket(sc, outBuffs[i][offset:offset+sizes[i]], true) + t.countSubnetRoutePacket(tbl, outBuffs[i][offset:offset+sizes[i]], true) } } @@ -1317,9 +1322,9 @@ func (t *Wrapper) tdevWrite(buffs [][]byte, offset int) (int, error) { } // Traffic entering the TUN from a tailnet peer: on a subnet router this is // sent onward into the subnet, so it is tx. - if sc := t.subnetCountersActive(); sc != nil { + if tbl := t.subnetCountersActive(); tbl != nil { for i := range buffs { - t.countSubnetRoutePacket(sc, buffs[i][offset:], false) + t.countSubnetRoutePacket(tbl, buffs[i][offset:], false) } } return t.tdev.Write(buffs, offset) @@ -1567,11 +1572,10 @@ func (t *Wrapper) SetSubnetRoutes(routes []netip.Prefix) { if !anyCountableRoute(routes) { // Never enabled and nothing to enable it for. Don't create the // counters at all, so nodes that are not subnet routers, and nodes - // that have not opted in, publish no series and pay only a nil - // load on the packet path. + // that have not opted in, publish no series. return } - sc = newSubnetCounters(t.usermetrics) + sc = newSubnetCounters(t.usermetrics, &t.subnetRouteTable) t.subnetRouteCounters.Store(sc) } sc.setRoutes(routes) @@ -1583,18 +1587,13 @@ func (t *Wrapper) subnetCounters() *subnetCounters { return t.subnetRouteCounters.Load() } -// subnetCountersActive returns the per-route counters if traffic should be -// counted right now, or nil if per-route counting is disabled or no countable -// route is advertised. +// subnetCountersActive returns the lookup table to attribute packets with, or +// nil if per-route counting is disabled or no countable route is advertised. // -// This is the packet path's gate: two nil-able atomic loads, no decode and no +// This is the packet path's gate: one nil-able atomic load, no decode and no // lookup when counting is off. -func (t *Wrapper) subnetCountersActive() *subnetCounters { - sc := t.subnetRouteCounters.Load() - if sc == nil || sc.table.load() == nil { - return nil - } - return sc +func (t *Wrapper) subnetCountersActive() *bart.Table[*routeCounters] { + return t.subnetRouteTable.load() } // SubnetRouteCountingEnabledForTest reports whether per-route subnet load @@ -1649,7 +1648,7 @@ func (t *Wrapper) IsSelfTailscaleAddrForTest(a netip.Addr) bool { // // Addresses outside every advertised route are not counted, which excludes exit // node traffic. -func (t *Wrapper) countSubnetRouteParsed(sc *subnetCounters, p *packet.Parsed, rx bool) { +func (t *Wrapper) countSubnetRouteParsed(tbl *bart.Table[*routeCounters], p *packet.Parsed, rx bool) { if p.IPVersion == 0 { // Decode bailed out. Src and Dst are not cleared on that path and p is // pool-reused across packets, so they may hold a previous packet's @@ -1676,7 +1675,7 @@ func (t *Wrapper) countSubnetRouteParsed(sc *subnetCounters, p *packet.Parsed, r if t.isSelfTailscaleAddr(tailnetEnd) { return } - if rc := sc.forAddr(remote); rc != nil { + if rc, ok := tbl.Lookup(remote); ok { // p.TotalLen(), not len(p.Buffer()): the buffer may have trailing // slack, e.g. the full-MTU buffers wireguard-go hands Write. rc.add(p.TotalLen(), rx) @@ -1685,10 +1684,10 @@ func (t *Wrapper) countSubnetRouteParsed(sc *subnetCounters, p *packet.Parsed, r // countSubnetRoutePacket decodes just enough of b to attribute it to an // advertised subnet route. -func (t *Wrapper) countSubnetRoutePacket(sc *subnetCounters, b []byte, rx bool) { +func (t *Wrapper) countSubnetRoutePacket(tbl *bart.Table[*routeCounters], b []byte, rx bool) { var p packet.Parsed p.Decode(b) - t.countSubnetRouteParsed(sc, &p, rx) + t.countSubnetRouteParsed(tbl, &p, rx) } var (