diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index 88a90c227..c83544e18 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -203,6 +203,7 @@ The [ADD and DEL sequences](cni-cmd-sequence.md) describe attachment; the [GC se - **A packet too big for the fabric gets an ICMP error from the datapath, not a silent drop at the uplink.** `usid_egress` calls `send_too_big` after the MSS clamp and before it encapsulates. A packet longer than `encap_mtu_table`'s limit (the uplink MTU less 40, so 1460 at a 1500-byte fabric) is rewritten in place into an ICMPv6 Packet Too Big, or an ICMPv4 Fragmentation Needed for an IPv4 tenant with DF set, and redirected back out the interface it arrived on. The error carries the limit, comes from the attachment's own IPAM gateway (`tenant_gw_table`, keyed by host-side ifindex and written by `galactic-bgp` at ADD, removed by `galactic-veth`/`galactic-tap` at DEL), and quotes the packet's first 68 bytes with NPTv6 undone, so the tenant's path MTU discovery matches it to the socket that sent it. A GSO packet is judged by its segment length. No error is sent for an IPv4 packet without DF, for an ICMP error, past a per-CPU token bucket of 1,000 a second with a burst of 100 (`pmtu_icmp_bucket`), or for an attachment with no gateway in that family; those are dropped and counted as `fib_frag_needed`. Each outcome is counted in `pmtu_stats`, exported as `galactic_usid_pmtu_packets_total{result}`, and the limit as `galactic_usid_pmtu_limit_bytes`. The same `mssclamp.Reconciler` writes `encap_mtu_table` and `mss_clamp_table` from one `GALACTIC_CNI_TCP_MSS_CLAMP` setting, so the two cannot disagree. A pod's or guest's TCP and UDP packets usually arrive `CHECKSUM_PARTIAL`, which no BPF helper can clear, and a device without checksum offload (a tap whose guest did not negotiate it) would finish that checksum into the middle of the error. So the error is laid out with room pushed at the front until the kernel's checksum spot (the original transport header plus 16 for TCP, 6 otherwise) lands on a trailing slot word, with a pad word chosen so the sum the kernel writes there equals what is already there. `usid_pmtu_tap_test.go` checks this against the kernel through a `virtio_net_hdr` tap, with offload on and off. - **Per-VRF traffic is counted in each direction in its own per-CPU map, not in `vrf_value`.** `vrf_traffic_counters` is a `BPF_MAP_TYPE_PERCPU_HASH` keyed like `vrf_table` (Block<<12|Argument, so one VPC per node) holding packets, tenant bytes and claimed drops for `ingress` and `egress`. Per CPU, because the hot path then increments its own copy with no atomic and no shared cache line; a new map, because changing `vrf_value`'s layout would make `attach.Load` recreate `vrf_table` empty. The datapath only looks rows up: `VRFTable.Register` creates a VRF's row with `BPF_NOEXIST`, so registering again never resets it, `Unregister` removes it, and `Reconcile` ends with `SyncTraffic`, which creates rows for VRFs that predate the map and removes orphans, re-checking `vrf_table` before each delete and again after it, so a VRF registered while it runs keeps its row. `galactic-cni run` also calls `SyncTraffic` once the datapath loads, so an upgraded node counts from its first packet rather than its first 5-minute GC sweep. Every writer of `vrf_table` rows (CNI ADD, the datapath repair, the GC sweep, the ingress sidecar) goes through `VRFTable`, so none needs code of its own. Inbound counts at `usid_ingress`'s two redirects (warm FIB and `bpf_redirect_neigh`). Outbound counts at `usid_egress`'s encapsulating redirect, which covers egress shards, and its VIP reply redirect, and at the service path's redirects, remote ones inside `service_remote_encap` because its caller cannot tell a forwarded packet from a Packet Too Big. Same-node traffic between two attachments never reaches `usid_ingress`: the sender's `usid_egress` matches the receiver's local pass-through entry and hands the packet to the kernel, so that hit counts once in each direction on the shared VPC row, except a destination equal to the sender's own `tenant_gw_table` gateway. Bytes are the tenant packet's own length in both directions, unlike `vrf_value.bytes`, which counts the whole frame at step 6 and stays for `galactic_usid_vrf_bytes_total` and make-before-break checks. Exported as `galactic_usid_vrf_{forwarded_packets,forwarded_bytes,dropped_packets}_total{direction}`; see [docs/metrics.md](../observability/vpc-dataplane.md#traffic). The gateway check reads the destination from `service_fib_scratch` itself rather than taking a pointer to it: passed a map-value pointer as a subprogram argument, `usid_egress`'s verifier cost went past the kernel's 1M-instruction limit. - **An uplink that drops out of auto-detection keeps `usid_ingress` for 60 seconds.** `attach.Watch` re-resolves the uplink set on every netlink link or route event, and an uplink found only through BGP-learned routes leaves that set whenever FRR withdraws them, which it does for every restart (#778). Detaching on the first miss dropped SRv6 traffic still arriving on that uplink until FRR re-learned the routes. An attached interface whose link still exists now keeps its hook, and its place in the published uplink list, until it has been missing for `detachHoldDown`. Watch re-evaluates on its own when the hold-down ends, so an uplink that really stops carrying fabric routes is still detached. A deleted link is dropped at once. +- **`usid_ingress` claims only its side's transport VLAN.** For a VLAN on a bond, `usid_ingress` also runs on the bond's members, and there the kernel has already moved any single 802.1Q tag into `skb->vlan_tci`, so the hook sees every VLAN of the bond. After the locator match, it looks up the receiving ifindex in `transport_vlan_table`, a 4096-bit set of accepted VLAN IDs with bit 0 for untagged, and leaves any other tag, an 802.1ad tag or a priority tag to the kernel, counting it in the row's `unclaimed_packets`. A missing row accepts untagged frames only. `attach.SyncTransport` derives the rows from the selected interfaces' netlink state, with no setting of its own: a selected VLAN netdevice accepts untagged frames, because the kernel removed its tag; its parent and the parent's bond members accept its ID; any other selected interface and its members accept untagged frames. Two VLANs on one parent give the union. `attach.Start` writes the rows before it attaches and fails readiness if it cannot, and `attach.Watch` rewrites them before every re-attach, keeping each row's counter and leaving a held interface's row alone. A selected VLAN that fails validation (802.1ad, an ID outside 1 to 4094, or stacked on another VLAN) loses its rows, so its parent and members fall back to untagged only. The map is new and holds nothing worth keeping, so a layout change only recreates it. The tag is still popped after decapsulation, so no transit tag reaches a tenant. See the [transport contract](../designs/vlan-transport/contract.md). - **CRD-driven config, no sidecar gRPC.** `galactic-bgp` writes `BGPVRFInstance`/`BGPAdvertisement` CRDs directly via a bare controller-runtime client; `galactic-router`'s reconciler picks them up. No in-node gRPC calls between any of the CNI-chain binaries and `galactic-router`. - **DEL is intentionally minimal everywhere in the CNI chain; GC reclaims shared state asynchronously.** Every binary's own `cmdDel` only cleans up what it itself created *and* is safe to release immediately per-container: IPAM deallocation via `galactic-ipam`'s own on-disk marker file; guest-netns flush/host-device DEL in `galactic-veth`; and, in both `galactic-veth`/`galactic-tap`, deleting this attachment's own host/guest veth pair or tap device outright, since that interface is private to one attachment and no sibling pod/VM can ever depend on it. `galactic-bgp` removes its container's entries from this node's `BGPAdvertisement` and deletes it once no container it records is alive, so a replacement whose ADD ran first keeps it. None of them delete the VRF, routes, the eBPF `vrf_table` entry, or the `BGPVRFInstance` — those are keyed by `(vpc, node)` and shared by every attachment on the VPC and node. `galactic-router`'s GC controller (see [ARCHITECTURE-ROUTER.md](../router/architecture.md)) reclaims orphaned CRDs and stale kernel VRFs once no live container still references them; the installer separately sweeps stale eBPF VRF entries — see [docs/cni/gc-cmd-sequence.md](../cni/gc-cmd-sequence.md) for why the host veth/tap interface is reclaimed only with a dead attachment's `BGPAdvertisement`, when its DEL never removed it. - **A DSR backend's node translates the VIP, and its replies leave out the fabric uplink unencapsulated.** `galactic-gateway` carries a client's packet unmodified inside the outer IPv6 header, with Next Header 41 for an IPv6 client and 4 for an IPv4 one, to the backend node's End.DT46 uSID with the backend's slot in bits 81–96. Workloads are IPv6 only, so every backend is IPv6. For an IPv6 client, `usid_ingress` decapsulates the packet and, before the VRF FIB lookup, looks up `vip_xlat_table`'s ingress row by (Block, Argument, slot, protocol, destination address, destination port) and rewrites the destination to the backend's address and port, leaving the client's source alone. On the way back, `usid_egress` (TC ingress of the backend's host-side veth or tap, the same code for both kinds) looks up the egress row by the reply's source address and port, rewrites the source to the VIP, clamps a SYN-ACK's MSS to the IPv6 limit, and redirects the frame unencapsulated to the node's fabric uplink neighbor from `public_uplink_table`, skipping NPTv6 and `egress_route_table` entirely: that table's `::/0` and IPv4 entries would encapsulate the reply toward a NAT shard, which would translate an already correctly addressed reply. The reply is then ordinary routed traffic with the VIP as its source; where the compute node's uplink neighbor is an edge node, as in the containerlab topology, that node's `edge_return` forwards it because its source is in `vip_addr_table` (see [ARCHITECTURE-GATEWAY.md](../gateway/packet-paths.md#return-path-edgedsrc-program-edge_return)). Where the first public uplink's neighbor is the hosting provider's ToR/VRRP gateway, the reply goes straight to the provider and no edge forwards it; `edge_return` applies there only if that uplink loses its neighbor and the row falls back to an interface whose neighbor is an edge. An egress shard never claims it: `nat_ingress` takes only its own SID and masquerade addresses as destinations. Until `public_uplink_table` is written the reply falls through to the ordinary egress path. A packet to a multicast or link-local destination never takes this path: `usid_egress` hands it to the kernel before the VIP lookup and NPTv6, as well as `egress_route_table`, since a VIP's client is never link-local. A host-side TCP probe of the backend's bound port, sourced from the host interface's link-local address, gets its reply that way (see [the backend health design](../gateway/backend-health.md#reply-path)). The row holds one next hop, used for IPv4 frames too: the first resolved IPv6 neighbor of the first eBPF interface, in `attach.ResolveInterfaces` order, that has carrier (`srv6.ResolvePublicUplink`). Every reply from the node takes that uplink, whichever gateway node took the request, so on a compute node dual-homed to two edge nodes the row must follow the uplinks. `galactic-cni run` re-resolves it on every link change and IPv6 neighbor change (`installer.watchPublicUplink`, debounced 250 ms) and on every datapath repair pass (`attachreg.FillNode`), and rewrites it when it differs. A pass that resolves nothing keeps the row it has. `task verify:gateway-node-loss` in `deploy/containerlab/` takes one of `dfw-worker`'s two edge nodes off the fabric and checks the VIP still serves through the other. diff --git a/docs/designs/vlan-transport/contract.md b/docs/designs/vlan-transport/contract.md index 19d41db6f..fa7b0b9bb 100644 --- a/docs/designs/vlan-transport/contract.md +++ b/docs/designs/vlan-transport/contract.md @@ -261,7 +261,8 @@ The Worker branch adds no setting that selects a VLAN or an interface, so [§4]( Source facts used by this contract: - `edge_lb`, `edge_return` and `nat_ingress` classify only Ethernet type IPv4 or IPv6 (`internal/plumbing/ebpf/edgeprog/edgedsr.c:1306`, `:1472`; `internal/plumbing/ebpf/natprog/nat.c:3068`). A frame whose tag is in packet data is not claimed. -- `usid_ingress` pops a metadata tag after decapsulation and documents that an in-frame tag reaches its ethertype check unparsed (`usid.c:4479`, `DROP_REASON_TRACE_ING_ENTRY` comment). +- `usid_ingress` pops a metadata tag after decapsulation (`bpf_skb_vlan_pop` in `usid.c`). A single 802.1Q tag never reaches it in packet data: the kernel moves it into `skb->vlan_tci` before tc ingress whatever the offload settings ([baseline](../../archive/benchmarks/vlan-transport-baseline-2026-11-30.md#finding-a-single-8021q-tag-never-reaches-tc-ingress-in-the-frame)). Only a second tag, or the tag under an 802.1ad outer tag, stays in the frame; it fails the ethertype check and is not claimed, as [§6](#frame-handling-per-mode) requires. +- `usid_ingress` claims a frame only when its tag, or its lack of one, is in the receiving interface's `transport_vlan_table` row, derived from the selected interfaces by `attach.SyncTransport` ([#1402](https://github.com/datum-cloud/galactic/issues/1402)). - Tenant egress redirects to the interface its route uses (`EgressRouteTable.Register`, `PublicUplink.Set`, `internal/plumbing/ebpf/egressroutemap/egressroute.go:349`, `:667`). A route through a VLAN netdevice names that netdevice. - XDP attach in native mode refuses an interface the kernel reports without native support (`checkNativeXDPSupport`, `internal/plumbing/ebpf/xdpattach/gate.go:78`). - `main` has no tagged lab topology; `deploy/containerlab` builds untagged bonds. diff --git a/docs/designs/vlan-transport/packet-paths.md b/docs/designs/vlan-transport/packet-paths.md index 07b65b362..d7192b5f9 100644 --- a/docs/designs/vlan-transport/packet-paths.md +++ b/docs/designs/vlan-transport/packet-paths.md @@ -74,15 +74,16 @@ Names follow the [contract's examples](contract.md#2-routed-public-adjacency): t ### P6. Tenant SRv6 ingress: fabric to tenant -| Field | Value | -| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Ingress program, interface | Fact: `usid_ingress` (tc) on `attach.ResolveInterfaces` targets: the VLAN netdevice and, for a VLAN on a bond, the bond's members (`expandBondSlaves`, `internal/plumbing/ebpf/attach/interfaces.go:304`). | -| Packet representation | Fact: a tag the NIC strips is in `skb->vlan_tci` and the ethertype reads IPv6; a tag left in packet data reaches the ethertype check and is not claimed (`usid.c`, `DROP_REASON_TRACE_ING_ENTRY` comment). | -| FIB and neighbour context | Fact: the tenant attachment comes from the datapath's maps; delivery to a neighbour uses `bpf_redirect_neigh`. | -| Actual transmit interface | Fact: the attachment's veth (`bpf_redirect_peer`) or tap (`bpf_redirect`). | -| Tag removal, insertion | Fact: `bpf_skb_vlan_pop` after decapsulation (`usid.c:4479`). Required: no tag reaches the tenant in any mode. | -| Kernel-stack continuation | Fact: unclaimed packets continue to the kernel unchanged. | -| Coverage | `main` and Worker. | +| Field | Value | +| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Ingress program, interface | Fact: `usid_ingress` (tc) on `attach.ResolveInterfaces` targets: the VLAN netdevice and, for a VLAN on a bond, the bond's members (`expandBondSlaves`, `internal/plumbing/ebpf/attach/interfaces.go:304`). | +| Packet representation | Measured ([baseline](../../archive/benchmarks/vlan-transport-baseline-2026-11-30.md#finding-a-single-8021q-tag-never-reaches-tc-ingress-in-the-frame)): the kernel moves a single 802.1Q tag into `skb->vlan_tci` before tc ingress on the parent or a bond member, whatever the offload settings, and removes it before the VLAN netdevice's hook. Only a second tag, or the tag under an 802.1ad outer tag, stays in packet data; it fails the ethertype check and is not claimed. | +| Claim | Fact: after the locator match, `usid_ingress` checks the frame's tag against `transport_vlan_table` for the receiving interface and leaves any other VLAN, an 802.1ad tag and a priority tag to the kernel. `attach.SyncTransport` writes the rows from the selected interfaces: a VLAN's parent and bond members accept its ID, everything else accepts untagged frames, and a missing row accepts untagged frames only. | +| FIB and neighbour context | Fact: the tenant attachment comes from the datapath's maps; delivery to a neighbour uses `bpf_redirect_neigh`. | +| Actual transmit interface | Fact: the attachment's veth (`bpf_redirect_peer`) or tap (`bpf_redirect`). | +| Tag removal, insertion | Fact: `bpf_skb_vlan_pop` after decapsulation (`usid.c:4479`). Required: no tag reaches the tenant in any mode. | +| Kernel-stack continuation | Fact: unclaimed packets continue to the kernel unchanged. | +| Coverage | `main` and Worker. | ### P7. Tenant SRv6 egress: tenant to fabric diff --git a/internal/plumbing/ebpf/attach/attach.go b/internal/plumbing/ebpf/attach/attach.go index f90c4f34c..50cd6e532 100644 --- a/internal/plumbing/ebpf/attach/attach.go +++ b/internal/plumbing/ebpf/attach/attach.go @@ -106,6 +106,16 @@ func Start(pinDir string) (objs *prog.UsidObjects, ifaces []string, err error) { return nil, nil, fmt.Errorf("attach: resolve interfaces: %w", err) } + // Written before the attach and readiness-fatal: without its row, a hook on + // a tagged side's parent or bond members claims untagged frames only and + // leaves that side's SRv6 traffic to the kernel. + transport, err := SyncTransport(objs.TransportVlanTable, ifaces) + if err != nil { + _ = objs.Close() + return nil, nil, fmt.Errorf("attach: write transport VLAN context: %w", err) + } + slog.Info("attach: usid_ingress transport VLAN context", "accepts", transport) + if err := Attach(objs.UsidIngress, ifaces); err != nil { _ = objs.Close() return nil, nil, fmt.Errorf("attach: %w", err) diff --git a/internal/plumbing/ebpf/attach/transport.go b/internal/plumbing/ebpf/attach/transport.go new file mode 100644 index 000000000..971f64a2e --- /dev/null +++ b/internal/plumbing/ebpf/attach/transport.go @@ -0,0 +1,330 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "errors" + "fmt" + "log/slog" + "os" + "slices" + "strconv" + "strings" + + "github.com/cilium/ebpf" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/bond" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +// Transport VLAN context for usid_ingress. +// +// A side of the node, fabric or public, is untagged or carries one 802.1Q tag +// (docs/designs/vlan-transport/contract.md). Infrastructure creates the VLAN +// netdevice; Galactic derives the mode, VLAN ID and parent from the interface +// it is pointed at and has no setting of its own for either. +// +// usid_ingress runs on the selected interface and, for a bond or a VLAN on a +// bond, on the bond's members. On a member or parent the kernel has already +// moved a single 802.1Q tag into skb metadata, so that hook sees every VLAN of +// the parent. transport_vlan_table tells it which of them, and whether +// untagged frames, belong to a selected side. This file derives those rows. + +// transportResolution is one selected interface's derived transport context. +// It has the shape of the per-side resolution the transport configuration +// work (#1404) adds, which is expected to replace it. +type transportResolution struct { + Interface string + Index int + Tagged bool + VLANID uint16 + Parent string + ParentIndex int + // Members are the bond members under Parent (tagged) or Interface + // (untagged), empty when that is not a bond. + Members []string +} + +// vlanIDMin and vlanIDMax bound a usable transport VLAN ID: 0 marks a +// priority-tagged frame and 4095 is reserved. +const ( + vlanIDMin = 1 + vlanIDMax = 4094 +) + +// resolveTransport derives name's transport context from netlink. A VLAN +// netdevice is tagged with its own ID and parent; anything else is untagged. +// An 802.1ad VLAN, an ID outside 1 to 4094 and a VLAN stacked on another VLAN +// are errors: the contract excludes them. +// +// transportPolicy calls it through resolveTransportFn, the seam the shared +// transport resolution (#1404) replaces it through. +var resolveTransportFn = resolveTransport + +func resolveTransport(name string, links []netlink.Link) (transportResolution, error) { + link, err := linkByNameFn(name) + if err != nil { + return transportResolution{}, fmt.Errorf("look up %q: %w", name, err) + } + r := transportResolution{Interface: name, Index: link.Attrs().Index} + if link.Type() != vlanLinkType { + if bond.IsMaster(link) { + r.Members = bond.SlaveNames(link, links) + } + return r, nil + } + + vlan, ok := link.(*netlink.Vlan) + if !ok { + return transportResolution{}, fmt.Errorf("%q reports type vlan but carries no VLAN attributes", name) + } + if vlan.VlanProtocol != netlink.VLAN_PROTOCOL_UNKNOWN && vlan.VlanProtocol != netlink.VLAN_PROTOCOL_8021Q { + return transportResolution{}, fmt.Errorf("%q uses VLAN protocol %s; only 802.1Q is a transport VLAN", + name, vlan.VlanProtocol) + } + if vlan.VlanId < vlanIDMin || vlan.VlanId > vlanIDMax { + return transportResolution{}, fmt.Errorf("%q has VLAN ID %d, outside %d to %d", + name, vlan.VlanId, vlanIDMin, vlanIDMax) + } + parent, err := linkByIndexFn(link.Attrs().ParentIndex) + if err != nil { + return transportResolution{}, fmt.Errorf("look up parent %d of %q: %w", link.Attrs().ParentIndex, name, err) + } + if parent.Type() == vlanLinkType { + return transportResolution{}, fmt.Errorf("%q is stacked on VLAN %q; stacked tags are not a transport VLAN", + name, parent.Attrs().Name) + } + r.Tagged = true + r.VLANID = uint16(vlan.VlanId) + r.Parent = parent.Attrs().Name + r.ParentIndex = parent.Attrs().Index + if bond.IsMaster(parent) { + r.Members = bond.SlaveNames(parent, links) + } + return r, nil +} + +// transportAccept is the transport VLAN context one hook accepts. +type transportAccept struct { + untagged bool + vlanIDs []uint16 +} + +func (a *transportAccept) addVLAN(id uint16) { + if !slices.Contains(a.vlanIDs, id) { + a.vlanIDs = append(a.vlanIDs, id) + slices.Sort(a.vlanIDs) + } +} + +// value encodes a as a transport_vlan_table row with a zero counter. +func (a transportAccept) value() prog.UsidTransportVlanValue { + var v prog.UsidTransportVlanValue + if a.untagged { + v.Allowed[0] |= 1 + } + for _, id := range a.vlanIDs { + v.Allowed[id/64] |= 1 << (id % 64) + } + return v +} + +func (a transportAccept) String() string { + var parts []string + if a.untagged { + parts = append(parts, "untagged") + } + for _, id := range a.vlanIDs { + parts = append(parts, strconv.Itoa(int(id))) + } + if len(parts) == 0 { + return "none" + } + return strings.Join(parts, ",") +} + +// transportPolicy returns, per hook interface name, the transport VLAN context +// usid_ingress accepts there, for the interfaces in selected: +// +// - A VLAN netdevice accepts untagged frames: the kernel removed the tag +// before its hook runs. Its parent and the parent's bond members accept +// the VLAN's ID. +// - Any other interface, and its bond members when it is a bond, accepts +// untagged frames. +// +// Two selected VLANs on one parent give the parent the union of their IDs. +// An interface that fails to resolve or validate contributes nothing and is +// returned in errs; its hooks keep the table's default, untagged only. +func transportPolicy(selected []string) (policy map[string]*transportAccept, errs []error) { + policy = make(map[string]*transportAccept) + at := func(name string) *transportAccept { + if policy[name] == nil { + policy[name] = &transportAccept{} + } + return policy[name] + } + + links, err := linkListFn() + if err != nil { + return policy, []error{fmt.Errorf("enumerate links for bond members: %w", err)} + } + for _, name := range selected { + r, err := resolveTransportFn(name, links) + if err != nil { + errs = append(errs, err) + continue + } + at(r.Interface).untagged = true + if !r.Tagged { + for _, m := range r.Members { + at(m).untagged = true + } + continue + } + at(r.Parent).addVLAN(r.VLANID) + for _, m := range r.Members { + at(m).addVLAN(r.VLANID) + } + } + return policy, errs +} + +// resolveSelectedFn returns the interfaces selected for usid_ingress before +// bond expansion: the override, or auto-detection. It is the first half of +// ResolveInterfaces and an override point for tests. +var resolveSelectedFn = func() ([]string, error) { + if override := os.Getenv(config.EnvCNIEBPFInterfaces); override != "" { + names := parseInterfaceList(override) + if len(names) == 0 { + return nil, fmt.Errorf("attach: %s is set to %q but contains no usable interface names", + config.EnvCNIEBPFInterfaces, override) + } + return names, nil + } + return autoDetectInterfaces() +} + +// transportTable is the part of *ebpf.Map SyncTransport uses, so tests can +// substitute a fake without root. +type transportTable interface { + Lookup(key, valueOut any) error + Put(key, value any) error + Delete(key any) error + Keys() ([]uint32, error) +} + +// ebpfTransportTable adapts *ebpf.Map to transportTable. +type ebpfTransportTable struct{ *ebpf.Map } + +func (t ebpfTransportTable) Keys() ([]uint32, error) { + var ( + keys []uint32 + key uint32 + value prog.UsidTransportVlanValue + ) + iter := t.Iterate() + for iter.Next(&key, &value) { + keys = append(keys, key) + } + return keys, iter.Err() +} + +// SyncTransport writes transport_vlan_table for the attached interfaces from +// the current interface selection, and returns the context written per +// interface for logging. +// +// Each attached interface the selection covers gets its row, keeping the +// row's unclaimed-frame counter. An attached interface the selection does not +// resolve to, one Watch holds through its hold-down, keeps whatever row it +// had. A row for an ifindex no longer attached is removed. +// +// An interface whose VLAN fails validation, and the parent and members that +// VLAN would have covered, are logged and have their rows removed, which +// leaves them at the default, untagged only: their tagged traffic is not +// claimed rather than claimed from a stale VLAN. +// +// Callers write the rows before attaching, so a new hook on a tagged parent +// never runs with the default in place of its side's VLAN. +func SyncTransport(table *ebpf.Map, attached []string) (map[string]string, error) { + if table == nil { + return nil, errors.New("attach: transport_vlan_table is nil") + } + return syncTransport(ebpfTransportTable{table}, attached) +} + +func syncTransport(table transportTable, attached []string) (map[string]string, error) { + selected, err := resolveSelectedFn() + if err != nil { + return nil, fmt.Errorf("attach: resolve interfaces for transport VLAN context: %w", err) + } + policy, errs := transportPolicy(selected) + for _, e := range errs { + slog.Warn("attach: interface has no usable transport VLAN context; its hooks claim untagged frames only", + "err", e) + } + + // The hook targets the current selection resolves to. An attached + // interface outside it is held; one inside it with no policy failed + // validation, or belongs to a VLAN that did. + resolved := make(map[string]bool) + expanded, err := expandBondSlaves(selected) + if err != nil { + // Without the expansion every uncovered interface counts as held and + // keeps its row until the next pass. + slog.Warn("attach: expand selected interfaces for transport VLAN context; keeping uncovered rows", + "err", err) + } + for _, name := range expanded { + resolved[name] = true + } + + written := make(map[string]string) + keep := make(map[uint32]bool) + var failed []error + for _, name := range attached { + link, err := linkByNameFn(name) + if err != nil { + continue + } + ifindex := uint32(link.Attrs().Index) + accept, ok := policy[name] + if !ok { + // A held interface keeps its row. Any other loses it, falling + // back to the default, so a stale row cannot keep accepting a + // VLAN that no longer validates. + if !resolved[name] { + keep[ifindex] = true + } + continue + } + keep[ifindex] = true + value := accept.value() + var prev prog.UsidTransportVlanValue + if table.Lookup(ifindex, &prev) == nil { + value.UnclaimedPackets = prev.UnclaimedPackets + } + if err := table.Put(ifindex, value); err != nil { + failed = append(failed, fmt.Errorf("write transport_vlan_table[%s]: %w", name, err)) + continue + } + written[name] = accept.String() + } + + keys, err := table.Keys() + if err != nil { + failed = append(failed, fmt.Errorf("iterate transport_vlan_table: %w", err)) + } + for _, k := range keys { + if keep[k] { + continue + } + if err := table.Delete(k); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + failed = append(failed, fmt.Errorf("delete transport_vlan_table[%d]: %w", k, err)) + } + } + return written, errors.Join(failed...) +} diff --git a/internal/plumbing/ebpf/attach/transport_test.go b/internal/plumbing/ebpf/attach/transport_test.go new file mode 100644 index 000000000..27a1a25bd --- /dev/null +++ b/internal/plumbing/ebpf/attach/transport_test.go @@ -0,0 +1,270 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "errors" + "maps" + "slices" + "testing" + + "github.com/cilium/ebpf" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +const ( + tNIC = "nic0" + tBond101 = "bond0.101" + tBond202 = "bond0.202" + tNIC303 = "nic0.303" + tUntagged = "untagged" + tAccept101202 = "101,202" + tBondAD = "bond0.ad" +) + +// transportFixture is a fake host: a NIC, a two-member bond, VLANs 101 and +// 202 on the bond, VLAN 303 on the NIC, an 802.1ad VLAN, a VLAN stacked on a +// VLAN and a VLAN with ID 0. Only synthetic names and IDs. +func transportFixture(t *testing.T) { + t.Helper() + nic := &fakeLink{attrs: netlink.LinkAttrs{Name: tNIC, Index: 2}} + bondMaster := &fakeLink{attrs: netlink.LinkAttrs{Name: attachedBond, Index: 3}, linkType: "bond"} + m1 := &fakeLink{attrs: netlink.LinkAttrs{Name: "m1", Index: 4, MasterIndex: 3}} + m2 := &fakeLink{attrs: netlink.LinkAttrs{Name: "m2", Index: 5, MasterIndex: 3}} + vlan := func(name string, index, parent, id int, proto netlink.VlanProtocol) *netlink.Vlan { + return &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: name, Index: index, ParentIndex: parent}, + VlanId: id, + VlanProtocol: proto, + } + } + all := []netlink.Link{ + nic, bondMaster, m1, m2, + vlan(tBond101, 6, 3, 101, netlink.VLAN_PROTOCOL_8021Q), + vlan(tBond202, 7, 3, 202, netlink.VLAN_PROTOCOL_8021Q), + vlan(tNIC303, 8, 2, 303, netlink.VLAN_PROTOCOL_8021Q), + vlan(tBondAD, 9, 3, 404, netlink.VLAN_PROTOCOL_8021AD), + vlan("stacked", 10, 6, 505, netlink.VLAN_PROTOCOL_8021Q), + vlan("bond0.0", 11, 3, 0, netlink.VLAN_PROTOCOL_8021Q), + } + byName := make(map[string]netlink.Link) + byIndex := make(map[int]netlink.Link) + for _, l := range all { + byName[l.Attrs().Name] = l + byIndex[l.Attrs().Index] = l + } + + origName, origIndex, origList := linkByNameFn, linkByIndexFn, linkListFn + t.Cleanup(func() { linkByNameFn, linkByIndexFn, linkListFn = origName, origIndex, origList }) + linkByNameFn = func(name string) (netlink.Link, error) { + if l, ok := byName[name]; ok { + return l, nil + } + return nil, netlink.LinkNotFoundError{} + } + linkByIndexFn = func(index int) (netlink.Link, error) { + if l, ok := byIndex[index]; ok { + return l, nil + } + return nil, netlink.LinkNotFoundError{} + } + linkListFn = func() ([]netlink.Link, error) { return all, nil } +} + +func policyStrings(policy map[string]*transportAccept) map[string]string { + out := make(map[string]string, len(policy)) + for name, a := range policy { + out[name] = a.String() + } + return out +} + +func TestTransportPolicy(t *testing.T) { + transportFixture(t) + cases := []struct { + name string + selected []string + want map[string]string + wantErrs int + }{ + { + name: "untagged NIC", + selected: []string{tNIC}, + want: map[string]string{tNIC: tUntagged}, + }, + { + name: "untagged bond accepts untagged on its members", + selected: []string{attachedBond}, + want: map[string]string{attachedBond: tUntagged, "m1": tUntagged, "m2": tUntagged}, + }, + { + name: "VLAN on a bond: members accept only that ID", + selected: []string{tBond101}, + want: map[string]string{tBond101: tUntagged, attachedBond: "101", "m1": "101", "m2": "101"}, + }, + { + name: "VLAN on a NIC", + selected: []string{tNIC303}, + want: map[string]string{tNIC303: tUntagged, tNIC: "303"}, + }, + { + name: "two VLANs on one parent take the union", + selected: []string{tBond101, tBond202}, + want: map[string]string{ + tBond101: tUntagged, tBond202: tUntagged, + attachedBond: tAccept101202, "m1": tAccept101202, "m2": tAccept101202, + }, + }, + { + name: "explicitly listed members stay untagged", + selected: []string{"m1", "m2"}, + want: map[string]string{"m1": tUntagged, "m2": tUntagged}, + }, + { + name: "invalid VLANs contribute nothing", + selected: []string{tBondAD, "stacked", "bond0.0", "missing"}, + want: map[string]string{}, + wantErrs: 4, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + policy, errs := transportPolicy(tc.selected) + if got := policyStrings(policy); !maps.Equal(got, tc.want) { + t.Errorf("policy = %v, want %v", got, tc.want) + } + if len(errs) != tc.wantErrs { + t.Errorf("errors = %v, want %d", errs, tc.wantErrs) + } + }) + } +} + +func TestTransportAcceptValue(t *testing.T) { + v := transportAccept{untagged: true, vlanIDs: []uint16{1, 64, 4094}}.value() + want := map[int]uint64{0: 1<<0 | 1<<1, 1: 1 << 0, 63: 1 << 62} + for i, word := range v.Allowed { + if word != want[i] { + t.Errorf("Allowed[%d] = %#x, want %#x", i, word, want[i]) + } + } + if v := (transportAccept{vlanIDs: []uint16{101}}).value(); v.Allowed[0]&1 != 0 { + t.Error("a tagged-only row accepts untagged frames") + } +} + +// fakeTransportTable is an in-memory transport_vlan_table. +type fakeTransportTable map[uint32]prog.UsidTransportVlanValue + +func (f fakeTransportTable) Lookup(key, valueOut any) error { + v, ok := f[key.(uint32)] + if !ok { + return ebpf.ErrKeyNotExist + } + *valueOut.(*prog.UsidTransportVlanValue) = v + return nil +} + +func (f fakeTransportTable) Put(key, value any) error { + f[key.(uint32)] = value.(prog.UsidTransportVlanValue) + return nil +} + +func (f fakeTransportTable) Delete(key any) error { + delete(f, key.(uint32)) + return nil +} + +func (f fakeTransportTable) Keys() ([]uint32, error) { + return slices.Collect(maps.Keys(f)), nil +} + +func TestSyncTransport(t *testing.T) { + transportFixture(t) + orig := resolveSelectedFn + t.Cleanup(func() { resolveSelectedFn = orig }) + resolveSelectedFn = func() ([]string, error) { return []string{tBond101}, nil } + + table := fakeTransportTable{ + 4: {UnclaimedPackets: 7}, // m1: counter kept across the rewrite + 99: {}, // no longer attached: removed + 5: {UnclaimedPackets: 3}, // m2: held, not selected, left alone below + } + held := prog.UsidTransportVlanValue{UnclaimedPackets: 3} + held.Allowed[1] = 1 << (101 - 64) + table[5] = held + + // m2 is attached but the selection is narrowed to cover only m1, as if + // m2 were still in Watch's hold-down after leaving the bond. + linkList := linkListFn + linkListFn = func() ([]netlink.Link, error) { + links, err := linkList() + var out []netlink.Link + for _, l := range links { + if l.Attrs().Name != "m2" { + out = append(out, l) + } + } + return out, err + } + + written, err := syncTransport(table, []string{tBond101, "m1", "m2"}) + if err != nil { + t.Fatalf("syncTransport: %v", err) + } + if want := map[string]string{tBond101: tUntagged, "m1": "101"}; !maps.Equal(written, want) { + t.Errorf("written = %v, want %v", written, want) + } + if _, ok := table[99]; ok { + t.Error("row for an ifindex no longer attached was kept") + } + if got := table[4]; got.UnclaimedPackets != 7 || got.Allowed[1] != 1<<(101-64) || got.Allowed[0] != 0 { + t.Errorf("m1 row = %+v, want VLAN 101 only with its counter kept", got) + } + if got := table[5]; got != held { + t.Errorf("held m2 row changed to %+v", got) + } + if got := table[6]; got.Allowed[0] != 1 { + t.Errorf("bond0.101 row = %+v, want untagged only", got) + } +} + +// A VLAN that stops validating, here replaced by an 802.1ad VLAN of the same +// name, loses its rows on the parent and members rather than keeping the +// old ID. +func TestSyncTransportRemovesRowsOfAnInvalidVLAN(t *testing.T) { + transportFixture(t) + orig := resolveSelectedFn + t.Cleanup(func() { resolveSelectedFn = orig }) + resolveSelectedFn = func() ([]string, error) { return []string{tBondAD}, nil } + + stale := transportAccept{vlanIDs: []uint16{101}}.value() + table := fakeTransportTable{4: stale, 5: stale} + written, err := syncTransport(table, []string{tBondAD, "m1", "m2"}) + if err != nil { + t.Fatalf("syncTransport: %v", err) + } + if len(written) != 0 { + t.Errorf("written = %v, want nothing", written) + } + if len(table) != 0 { + t.Errorf("rows left = %v, want none", table) + } +} + +func TestSyncTransportSelectionFailure(t *testing.T) { + orig := resolveSelectedFn + t.Cleanup(func() { resolveSelectedFn = orig }) + resolveSelectedFn = func() ([]string, error) { return nil, errors.New("no route") } + table := fakeTransportTable{4: {}} + if _, err := syncTransport(table, []string{"m1"}); err == nil { + t.Fatal("syncTransport succeeded without a selection") + } + if _, ok := table[4]; !ok { + t.Error("a failed selection removed existing rows") + } +} diff --git a/internal/plumbing/ebpf/attach/watch.go b/internal/plumbing/ebpf/attach/watch.go index 1318c3d2b..a391262c5 100644 --- a/internal/plumbing/ebpf/attach/watch.go +++ b/internal/plumbing/ebpf/attach/watch.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "log/slog" + "maps" "slices" "sort" "sync" @@ -78,6 +79,28 @@ type Watcher struct { mu sync.Mutex attached []string onChange func([]string) + + // transport is usid_ingress's transport_vlan_table, rewritten after every + // re-evaluation; nil skips that. lastTransport is the context last + // logged, so an unchanged one is not logged again. + transport *ebpf.Map + lastTransport map[string]string +} + +// syncTransport rewrites transport_vlan_table for the attached set. A failure +// is logged and retried on the next re-evaluation, like a failed attach. +func (w *Watcher) syncTransport(attached []string) { + if w == nil || w.transport == nil { + return + } + written, err := SyncTransport(w.transport, attached) + if err != nil { + slog.Warn("attach: write transport VLAN context failed, retrying on the next re-evaluation", "err", err) + } + if !maps.Equal(written, w.lastTransport) { + slog.Info("attach: usid_ingress transport VLAN context", "accepts", written) + w.lastTransport = written + } } // newWatcher creates a Watcher in its not-yet-started state. It is marked alive @@ -353,6 +376,9 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc for _, name := range held { fresh[name] = struct{}{} } + // Rows first, so an interface attached by this pass never runs + // without its transport VLAN context. + w.syncTransport(append(slices.Clone(next), held...)) current = reconcileFn(program, current, fresh) // Held interfaces go after the resolved ones, in their last // published order, so the first entry stays the default-route @@ -389,6 +415,7 @@ func StartWatching(ctx context.Context, pinDir string) ( } watcher = newWatcher() + watcher.transport = objs.TransportVlanTable go func() { if werr := Watch(ctx, objs.UsidIngress, ifaces, watcher); werr != nil { slog.Error("attach: netlink-driven interface watch loop exited unexpectedly", "err", werr) diff --git a/internal/plumbing/ebpf/prog/doc.go b/internal/plumbing/ebpf/prog/doc.go index f7a4512d5..32c1746aa 100644 --- a/internal/plumbing/ebpf/prog/doc.go +++ b/internal/plumbing/ebpf/prog/doc.go @@ -40,4 +40,4 @@ package prog // -cc is deliberately omitted: bpf2go defaults to $BPF2GO_CC or "clang", so CI // can pin an exact version without this directive changing. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_range -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_remote_target_value -type service_peer_key -type service_peer_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type host_only_ports_value -type vpc_attribution_value -type vrf_direction_counter -type vrf_traffic_value -type tp_state_value -type tp_iface_value -type tp_iface_addr_key -type tp_binding_key -type tp_entry -type tp_header -type tp_counter -type tp_fallback_key Usid usid.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_range -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_remote_target_value -type service_peer_key -type service_peer_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type host_only_ports_value -type vpc_attribution_value -type vrf_direction_counter -type vrf_traffic_value -type tp_state_value -type tp_iface_value -type tp_iface_addr_key -type tp_binding_key -type tp_entry -type tp_header -type tp_counter -type tp_fallback_key -type transport_vlan_value Usid usid.c diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index 4605e48a8..cfc725ff5 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -188,6 +188,7 @@ static long (*bpf_skb_change_head)(struct __sk_buff *skb, __u32 len, __u64 flags #define USID_ETH_P_IP 0x0800 #define USID_ETH_P_IPV6 0x86DD +#define USID_ETH_P_8021Q 0x8100 // IPv6 Next Header values naming an inner IPv4 or IPv6 packet directly, that // is, with no extension header between the outer uSID header and the real inner @@ -1220,11 +1221,15 @@ enum drop_reason { // "never invoked" from "always took an uninstrumented path". // // Two of the five are live hypotheses rather than completeness for its own - // sake. ETHERTYPE_MISMATCH is where a VLAN tag left in packet data by a NIC - // that does not strip it would land, silently. LOCATOR_MISS is where a - // Block or Node-ID not matching this node's registration would land, - // equally silently, and it is the one miss in the lookup chain with no - // counter of its own. + // sake. ETHERTYPE_MISMATCH is where a tag still in packet data lands. A + // single 802.1Q tag never does: the kernel moves it into skb->vlan_tci + // before tc ingress whatever the NIC's offload settings (measured in the + // 2026-11-30 VLAN transport baseline). Only a second tag, or the inner + // tag under an 802.1ad outer tag, stays in the frame, and the transport + // contract leaves both unclaimed, which is what this exit does. + // LOCATOR_MISS is where a Block or Node-ID not matching this node's + // registration would land, equally silently, and it is the one miss in + // the lookup chain with no counter of its own. // // drop_reasons is a per-CPU array, so the unconditional entry counter is a // per-CPU increment with no cross-CPU contention, on a program that already @@ -1388,6 +1393,75 @@ struct { __type(value, __u32); // enum egress_kind } ifindex_egress_kind_table SEC(".maps"); +// struct transport_vlan_value is transport_vlan_table's value: the transport +// VLAN context usid_ingress accepts on one interface it is attached to. +// +// A fabric or public side is either untagged or carries exactly one 802.1Q +// tag (docs/designs/vlan-transport/contract.md). By the time tc ingress runs, +// the kernel has moved a single 802.1Q tag out of the frame into +// skb->vlan_tci, on the parent and on every bond member, whatever the NIC's +// receive offload. A hook there therefore sees every VLAN of the parent, and +// without this check would claim a local SID arriving on any of them. A hook +// on the VLAN netdevice itself sees the frame after the kernel removed the tag. +// +// allowed is a bitmap over VLAN IDs. Bit n is VLAN ID n for 1 to 4094. Bit 0 +// stands for a frame with no tag at all, which is safe because VLAN ID 0 +// (priority-tagged) is never a transport VLAN and is never accepted. Bit 4095 +// is never set: that ID is reserved. +// +// unclaimed_packets counts SRv6 frames for one of this node's locators that +// this interface's row turned away, the per-interface "unclaimed tagged +// frames" counter the contract asks for. Userspace only reads it. +struct transport_vlan_value { + __u64 allowed[64]; + __u64 unclaimed_packets; +}; + +// transport_vlan_table: see struct transport_vlan_value. Keyed by the ifindex +// usid_ingress is attached to, written by the process that attaches it +// (internal/plumbing/ebpf/attach, SyncTransport) from the selected interfaces' +// netlink state, and rewritten on every start and re-evaluation. It holds no +// state worth keeping across a layout change. +// +// A miss accepts untagged frames only. That is the behaviour of a hook on an +// untagged interface or on a VLAN netdevice, so a deployment with no VLAN, or +// an interface whose row has not been written yet, keeps forwarding untagged +// traffic exactly as before this map existed. +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 256); + __type(key, __u32); // ifindex usid_ingress is attached to + __type(value, struct transport_vlan_value); +} transport_vlan_table SEC(".maps"); + +// transport_vlan_accepts reports whether the frame's transport VLAN context, +// read from skb metadata, is one the receiving interface accepts. See struct +// transport_vlan_value. An 802.1ad tag, a priority tag (VLAN ID 0) and any ID +// outside the row are refused, and the frame is left to the kernel. +static __always_inline int transport_vlan_accepts(struct __sk_buff *skb) +{ + __u32 ifindex = skb->ifindex; + __u32 vid = 0; + int usable = 1; + + if (skb->vlan_present) { + vid = skb->vlan_tci & 0x0fff; + usable = skb->vlan_proto == __builtin_bswap16(USID_ETH_P_8021Q) && vid != 0; + } + + struct transport_vlan_value *row = bpf_map_lookup_elem(&transport_vlan_table, &ifindex); + + if (usable) { + if (!row) + return !skb->vlan_present; + if (row->allowed[(vid >> 6) & 63] & (1ULL << (vid & 63))) + return 1; + } + if (row) + __sync_fetch_and_add(&row->unclaimed_packets, 1); + return 0; +} + // The Galactic Edge forwarding gate. An edge attachment's host link carries // traffic only for the attachment's own address, which it holds for its // lifetime, and for the prefixes its provider instance currently holds a @@ -4288,6 +4362,15 @@ int usid_ingress(struct __sk_buff *skb) return TC_ACT_UNSPEC; } + // Step 2a: claim only frames that arrived in this interface's transport + // VLAN context. On a parent or bond member the kernel has already moved a + // single 802.1Q tag into skb->vlan_tci, so the checks above see every VLAN + // of that parent alike; see struct transport_vlan_value. Placed after the + // locator match so traffic for other destinations pays no extra lookup, + // and still before the claim: a refused frame goes to the kernel unchanged. + if (!transport_vlan_accepts(skb)) + return TC_ACT_UNSPEC; + __u64 block = locator_key >> 16; // Step 3: read Function from the unmutated packet at its fixed offset, the @@ -4454,10 +4537,10 @@ int usid_ingress(struct __sk_buff *skb) // Drop the outer transit VLAN, which the decapsulated inner packet must not // inherit. // - // When the packet arrives on a VLAN whose tag the NIC strips into skb - // metadata, the ordinary case, the tag lives in skb->vlan_tci rather than - // packet data, so the ethertype check above sees IPv6 and the carve never - // touches it. Stripping the outer header then leaves the tag on a packet it + // When the packet arrives on a parent or bond member of a tagged side, the + // kernel has moved the tag into skb->vlan_tci before tc runs, so the + // ethertype check above sees IPv6 and the carve never touches it. Step 2a + // already checked that the tag is this side's. Stripping the outer header then leaves the tag on a packet it // has nothing to do with: it describes the segment the outer packet // crossed, while the inner packet is addressed inside a tenant VRF and // never belonged to that segment. diff --git a/internal/plumbing/ebpf/prog/usid_redirect_test.go b/internal/plumbing/ebpf/prog/usid_redirect_test.go index d447ff6fe..d6fa3836f 100644 --- a/internal/plumbing/ebpf/prog/usid_redirect_test.go +++ b/internal/plumbing/ebpf/prog/usid_redirect_test.go @@ -572,9 +572,18 @@ func neighborValid(t *testing.T, ifindex uint32, dst net.IP) bool { // to innerDst, into the uplink tap, and returns the payload marker to look for // on the far side. The inner packet is IPv4 or IPv6 to match innerDst. func (lab *redirectLab) send(t *testing.T, innerDst net.IP, label string) []byte { + t.Helper() + return lab.sendTagged(t, innerDst, label) +} + +// sendTagged is send with each tag, a TPID and a TCI, inserted after the +// source MAC, outermost first. +func (lab *redirectLab) sendTagged(t *testing.T, innerDst net.IP, label string, tags ...[2]uint16) []byte { t.Helper() marker := fmt.Appendf(nil, "galactic-egress-kind:%s:%d", label, time.Now().UnixNano()) - payload := make([]byte, 64) + // At least 64 bytes, and never shorter than the marker: a truncated + // marker is never found on the far side. + payload := make([]byte, max(64, len(marker))) copy(payload, marker) var inner []byte @@ -598,7 +607,12 @@ func (lab *redirectLab) send(t *testing.T, innerDst net.IP, label string) []byte frame := make([]byte, 0, ethHeaderLen+ip6HeaderLen+len(inner)) frame = append(frame, lab.uplinkMAC...) - frame = append(frame, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x86, 0xDD) + frame = append(frame, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01) + for _, tag := range tags { + frame = binary.BigEndian.AppendUint16(frame, tag[0]) + frame = binary.BigEndian.AppendUint16(frame, tag[1]) + } + frame = append(frame, 0x86, 0xDD) frame = append(frame, 0x60, 0x00, 0x00, 0x00, byte(len(inner)>>8), byte(len(inner)), outerNextHdr, 64) src := [16]byte{0x20, 0x01, 0x0d, 0xb8, 15: 0x01} frame = append(frame, src[:]...) diff --git a/internal/plumbing/ebpf/prog/usid_transport_vlan_test.go b/internal/plumbing/ebpf/prog/usid_transport_vlan_test.go new file mode 100644 index 000000000..9056afc67 --- /dev/null +++ b/internal/plumbing/ebpf/prog/usid_transport_vlan_test.go @@ -0,0 +1,231 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +import ( + "bytes" + "encoding/binary" + "errors" + "os" + "testing" + "time" + + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" +) + +// These tests write tagged and untagged SRv6 frames into a tap uplink and +// check what usid_ingress claims against transport_vlan_table. The kernel +// moves the outer tag of a frame written into a tap into skb metadata before +// tc ingress, as it does on a NIC or bond member, so the hook on the tap sees +// what a hook on a tagged side's parent sees. + +const ( + tpid8021Q = 0x8100 + tpid8021AD = 0x88a8 +) + +func tag(tpid, tci uint16) [2]uint16 { return [2]uint16{tpid, tci} } + +// transportRow builds a transport_vlan_table row. +func transportRow(untagged bool, ids ...uint16) UsidTransportVlanValue { + var v UsidTransportVlanValue + if untagged { + v.Allowed[0] |= 1 + } + for _, id := range ids { + v.Allowed[id/64] |= 1 << (id % 64) + } + return v +} + +// awaitTapFrame returns the first frame read from the tap that contains +// marker within wait, or nil. +func awaitTapFrame(t *testing.T, fd int, marker []byte, wait time.Duration) []byte { + t.Helper() + deadline := time.Now().Add(wait) + buf := make([]byte, 65536) + for { + remaining := time.Until(deadline) + if remaining <= 0 { + return nil + } + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + ready, err := unix.Poll(fds, int(remaining.Milliseconds())+1) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("poll tap: %v", err) + } + if ready == 0 { + return nil + } + n, err := unix.Read(fd, buf) + if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("read tap: %v", err) + } + if bytes.Contains(buf[:n], marker) { + return bytes.Clone(buf[:n]) + } + } +} + +// expect sends one frame with tags and checks whether it reaches the tap +// attachment. A delivered frame must carry no tag: the transit VLAN never +// reaches tenant delivery. +func (lab *redirectLab) expect(t *testing.T, deliver bool, label string, tags ...[2]uint16) { + t.Helper() + marker := lab.sendTagged(t, tapInnerDst, label, tags...) + wait := quietWait + if deliver { + wait = deliveryWait + } + frame := awaitTapFrame(t, lab.tapFd, marker, wait) + switch { + case deliver && frame == nil: + t.Errorf("%s: not delivered to the tenant tap; nonzero drop_reasons: %v", label, lab.dropReasons(t)) + case !deliver && frame != nil: + t.Errorf("%s: delivered to the tenant tap, want left to the kernel", label) + case len(frame) >= 14: + if et := binary.BigEndian.Uint16(frame[12:14]); et == tpid8021Q || et == tpid8021AD { + t.Errorf("%s: tenant received a tagged frame (ethertype %#04x)", label, et) + } + } +} + +// dropReasons returns every nonzero drop_reasons slot, trace slots included, +// to say where an undelivered frame stopped. +func (lab *redirectLab) dropReasons(t *testing.T) map[uint32]uint64 { + t.Helper() + out := make(map[uint32]uint64) + for i := range lab.objs.DropReasons.MaxEntries() { + if n := sumPerCPU(t, lab.objs.DropReasons, i); n != 0 { + out[i] = n + } + } + return out +} + +func (lab *redirectLab) uplinkIndex(t *testing.T) uint32 { + t.Helper() + link, err := netlink.LinkByName("up0") + if err != nil { + t.Fatalf("look up uplink: %v", err) + } + return uint32(link.Attrs().Index) +} + +func (lab *redirectLab) unclaimed(t *testing.T, ifindex uint32) uint64 { + t.Helper() + var v UsidTransportVlanValue + if err := lab.objs.TransportVlanTable.Lookup(ifindex, &v); err != nil { + t.Fatalf("read transport_vlan_table[%d]: %v", ifindex, err) + } + return v.UnclaimedPackets +} + +// With no row, the hook claims untagged frames only: the behaviour before the +// table existed, minus claiming other VLANs. +func TestUsidIngress_TransportVLANDefaultIsUntaggedOnly(t *testing.T) { + requireRoot(t) + lab := newRedirectLab(t) + lab.registerTap(t) + + lab.expect(t, true, "untagged, no row") + lab.expect(t, false, "VLAN 101, no row", tag(tpid8021Q, 101)) +} + +// A row for one VLAN on a parent claims that VLAN only, pops its tag, and +// counts what it refuses. +func TestUsidIngress_TransportVLANClaimsOnlyItsVLAN(t *testing.T) { + requireRoot(t) + lab := newRedirectLab(t) + lab.registerTap(t) + uplink := lab.uplinkIndex(t) + if err := lab.objs.TransportVlanTable.Put(uplink, transportRow(false, 101)); err != nil { + t.Fatalf("write transport_vlan_table: %v", err) + } + + lab.expect(t, true, "VLAN 101", tag(tpid8021Q, 101)) + lab.expect(t, true, "VLAN 101 with priority bits", tag(tpid8021Q, 5<<13|101)) + lab.expect(t, false, "untagged") + lab.expect(t, false, "VLAN 202", tag(tpid8021Q, 202)) + lab.expect(t, false, "802.1ad 101", tag(tpid8021AD, 101)) + lab.expect(t, false, "priority-tagged", tag(tpid8021Q, 0)) + // The kernel moves the outer tag only; the inner one stays in the frame + // and fails the ethertype check before the locator match, uncounted. + lab.expect(t, false, "two tags", tag(tpid8021Q, 101), tag(tpid8021Q, 202)) + + if got := lab.unclaimed(t, uplink); got != 4 { + t.Errorf("unclaimed_packets = %d, want 4 (untagged, VLAN 202, 802.1ad, priority-tagged)", got) + } +} + +// Two VLANs sharing a parent, plus untagged traffic, each claimed when the +// row lists them. +func TestUsidIngress_TransportVLANSharedParent(t *testing.T) { + requireRoot(t) + lab := newRedirectLab(t) + lab.registerTap(t) + uplink := lab.uplinkIndex(t) + if err := lab.objs.TransportVlanTable.Put(uplink, transportRow(true, 101, 202)); err != nil { + t.Fatalf("write transport_vlan_table: %v", err) + } + + lab.expect(t, true, "untagged") + lab.expect(t, true, "VLAN 101", tag(tpid8021Q, 101)) + lab.expect(t, true, "VLAN 202", tag(tpid8021Q, 202)) + lab.expect(t, false, "VLAN 303", tag(tpid8021Q, 303)) + lab.expect(t, false, "VLAN 4095", tag(tpid8021Q, 4095)) +} + +// A hook on the VLAN netdevice sees the frame after the kernel removed the +// tag, so the default row claims its own VLAN, and another VLAN on the same +// parent never reaches it. +func TestUsidIngress_TransportVLANOnVLANNetdevice(t *testing.T) { + requireRoot(t) + lab := newRedirectLab(t) + lab.registerTap(t) + + parent, err := netlink.LinkByName("up0") + if err != nil { + t.Fatalf("look up uplink: %v", err) + } + filters, err := netlink.FilterList(parent, netlink.HANDLE_MIN_INGRESS) + if err != nil { + t.Fatalf("list the parent's ingress filters: %v", err) + } + for _, f := range filters { + if err := netlink.FilterDel(f); err != nil { + t.Fatalf("remove usid_ingress from the parent: %v", err) + } + } + vlan := &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: "up0.101", ParentIndex: parent.Attrs().Index}, + VlanId: 101, + VlanProtocol: netlink.VLAN_PROTOCOL_8021Q, + } + if err := netlink.LinkAdd(vlan); err != nil { + t.Fatalf("add VLAN netdevice: %v", err) + } + vlanLink := setLinkUp(t, "up0.101") + for _, path := range []string{ + "/proc/sys/net/ipv4/conf/up0.101/forwarding", + "/proc/sys/net/ipv6/conf/up0.101/forwarding", + } { + if err := os.WriteFile(path, []byte("1"), 0o644); err != nil { + t.Fatalf("enable forwarding via %s: %v", path, err) + } + } + attachIngress(t, vlanLink, lab.objs.UsidIngress) + + lab.expect(t, true, "VLAN 101 on its netdevice", tag(tpid8021Q, 101)) + lab.expect(t, false, "VLAN 202 on the same parent", tag(tpid8021Q, 202)) + lab.expect(t, false, "untagged on the parent of "+vlan.Name) +} diff --git a/internal/plumbing/srv6/egress_vlan_test.go b/internal/plumbing/srv6/egress_vlan_test.go new file mode 100644 index 000000000..a658e919c --- /dev/null +++ b/internal/plumbing/srv6/egress_vlan_test.go @@ -0,0 +1,177 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srv6 + +import ( + "fmt" + "net" + "testing" + "time" + + "github.com/containernetworking/plugins/pkg/ns" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/config" +) + +// TestResolvePublicUplink_TaggedSides covers the DSR return uplink on a node +// whose sides are VLANs on one bond: public VLAN 101 and fabric VLAN 202. +// usid_egress redirects a backend's VIP-sourced reply to this uplink, and a +// tc redirect to a VLAN netdevice inserts that VLAN's tag, so the choice +// decides which tag the reply carries. +// +// ResolvePublicUplink takes the first selected interface, in +// GALACTIC_CNI_EBPF_INTERFACES order, that has carrier and a resolved +// neighbor. It picks the VLAN netdevice, never the bond or a member, and it +// does not tell public from fabric: listing the public VLAN first sends the +// reply out the public side. Every name, address and MAC is synthetic. +func TestResolvePublicUplink_TaggedSides(t *testing.T) { + requireRoot(t) + + const ( + bondName = "srv6vbond0" + pubName = "srv6vbond0.101" + fabName = "srv6vbond0.202" + ) + bondMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xB0, 0x00} + pubMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xB1, 0x01} + fabMAC := net.HardwareAddr{0xAA, 0xAA, 0xAA, 0xAA, 0xB2, 0x02} + + nsObj, err := ns.TempNetNS() + if err != nil { + t.Fatalf("create test netns: %v", err) + } + defer func() { _ = nsObj.Close() }() + + index := make(map[string]int) + err = nsObj.Do(func(_ ns.NetNS) error { + // Active-backup: its carrier follows a member without the LACP + // negotiation an 802.3ad bond of dummies may or may not finish. + bond := netlink.NewLinkBond(netlink.LinkAttrs{Name: bondName}) + bond.Mode = netlink.BOND_MODE_ACTIVE_BACKUP + if err := netlink.LinkAdd(bond); err != nil { + return fmt.Errorf("add bond: %w", err) + } + bondLink, err := netlink.LinkByName(bondName) + if err != nil { + return fmt.Errorf("look up bond: %w", err) + } + for _, member := range []string{"srv6vm0", "srv6vm1"} { + if err := netlink.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: member}}); err != nil { + return fmt.Errorf("add member %s: %w", member, err) + } + m, err := netlink.LinkByName(member) + if err != nil { + return fmt.Errorf("look up member %s: %w", member, err) + } + if err := netlink.LinkSetMasterByIndex(m, bondLink.Attrs().Index); err != nil { + return fmt.Errorf("enslave %s: %w", member, err) + } + if err := netlink.LinkSetUp(m); err != nil { + return fmt.Errorf("set %s up: %w", member, err) + } + } + if err := netlink.LinkSetUp(bondLink); err != nil { + return fmt.Errorf("set bond up: %w", err) + } + for _, v := range []struct { + name string + id int + }{{pubName, 101}, {fabName, 202}} { + vlan := &netlink.Vlan{ + LinkAttrs: netlink.LinkAttrs{Name: v.name, ParentIndex: bondLink.Attrs().Index}, + VlanId: v.id, + VlanProtocol: netlink.VLAN_PROTOCOL_8021Q, + } + if err := netlink.LinkAdd(vlan); err != nil { + return fmt.Errorf("add VLAN %s: %w", v.name, err) + } + link, err := netlink.LinkByName(v.name) + if err != nil { + return fmt.Errorf("look up VLAN %s: %w", v.name, err) + } + if err := netlink.LinkSetUp(link); err != nil { + return fmt.Errorf("set %s up: %w", v.name, err) + } + } + // A neighbor on each logical interface, the bond included, so the + // result names which one was chosen. + for i, n := range []struct { + name string + mac net.HardwareAddr + }{{bondName, bondMAC}, {pubName, pubMAC}, {fabName, fabMAC}} { + link, err := netlink.LinkByName(n.name) + if err != nil { + return fmt.Errorf("look up %s: %w", n.name, err) + } + index[n.name] = link.Attrs().Index + if err := netlink.NeighAdd(&netlink.Neigh{ + LinkIndex: link.Attrs().Index, + Family: netlink.FAMILY_V6, + State: netlink.NUD_PERMANENT, + IP: net.ParseIP(fmt.Sprintf("2001:db8:b:%d::1", i)), + HardwareAddr: n.mac, + }); err != nil { + return fmt.Errorf("add neighbor on %s: %w", n.name, err) + } + } + return nil + }) + if err != nil { + t.Fatalf("setup: %v", err) + } + + // The bond, and the VLANs above it, gain carrier asynchronously once a + // member is up. Wait for it rather than race the resolution. + err = nsObj.Do(func(_ ns.NetNS) error { + deadline := time.Now().Add(5 * time.Second) + for _, name := range []string{pubName, fabName} { + for { + link, err := netlink.LinkByName(name) + if err != nil { + return fmt.Errorf("look up %s: %w", name, err) + } + if link.Attrs().RawFlags&unix.IFF_LOWER_UP != 0 { + break + } + if time.Now().After(deadline) { + return fmt.Errorf("%s has no carrier after 5s", name) + } + time.Sleep(50 * time.Millisecond) + } + } + return nil + }) + if err != nil { + t.Fatalf("wait for carrier: %v", err) + } + + for _, tc := range []struct { + selection string + wantName string + wantMAC net.HardwareAddr + }{ + {fabName, fabName, fabMAC}, + {fabName + "," + pubName, fabName, fabMAC}, + {pubName + "," + fabName, pubName, pubMAC}, + } { + t.Setenv(config.EnvCNIEBPFInterfaces, tc.selection) + var gotIndex int + var gotDmac net.HardwareAddr + err := nsObj.Do(func(_ ns.NetNS) error { + var doErr error + gotIndex, gotDmac, _, doErr = ResolvePublicUplink() + return doErr + }) + if err != nil { + t.Fatalf("selection %q: ResolvePublicUplink: %v", tc.selection, err) + } + if gotIndex != index[tc.wantName] || gotDmac.String() != tc.wantMAC.String() { + t.Errorf("selection %q: ResolvePublicUplink() = %d %s, want %s (%d) %s", tc.selection, + gotIndex, gotDmac, tc.wantName, index[tc.wantName], tc.wantMAC) + } + } +}