diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 12230fd24..187b531a2 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -13,7 +13,9 @@ import ( "slices" "sync" + "github.com/cilium/ebpf" "github.com/cilium/ebpf/link" + "github.com/vishvananda/netlink" "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" @@ -21,6 +23,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/edgeattach" "go.datum.net/galactic/internal/plumbing/ebpf/edgemetrics" "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" + "go.datum.net/galactic/internal/plumbing/ebpf/vlanegress" "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" @@ -294,11 +297,51 @@ func installGateway( missing = append(missing, returnSet.reconcile(ctx, returnTargets)...) } coverage.set(missing) - go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage, ipv4) + syncVLANEgress(objs.VlanEgress, publicInterface, internalInterfaces, true) + go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage, ipv4, objs.VlanEgress) return nil } +// syncVLANEgress fills edgedsr.c's vlan_egress from the gateway's configured +// sides: the public interface and every internal interface that is a VLAN +// netdevice. A route the datapath resolves through one of them leaves through +// its lower device with that side's tag pushed in XDP, since a native redirect +// to a VLAN netdevice transmits nothing. A side that cannot be resolved keeps +// no row and is reported; the attachment itself reports a missing interface. +// logSides logs each tagged side, which startup does once. +func syncVLANEgress(m *ebpf.Map, publicInterface string, internalInterfaces []string, logSides bool) { + names := append([]string{publicInterface}, internalInterfaces...) + lowers, ifindexes, err := vlanegress.FromNetlink(names) + if err != nil { + slog.Warn("Cannot resolve every edge gateway interface for VLAN egress; routes through the ones "+ + "left out are redirected to the VLAN device as the FIB names it", "err", err) + } + if err := vlanegress.Sync(m, lowers, ifindexes); err != nil { + slog.Warn("Cannot update the edge gateway's VLAN egress map", "err", err) + } + if !logSides { + return + } + for i, name := range names { + if name == "" { + continue + } + side := "internal" + if i == 0 { + side = "public" + } + l, err := netlink.LinkByName(name) + if err != nil { + continue + } + if lower, vid, ok := lowers.VLANLower(l.Attrs().Index); ok { + slog.Info("Edge gateway side is tagged; its XDP hook runs in generic mode on the VLAN device", + "side", side, "interface", name, "vlanID", vid, "lowerIfindex", lower) + } + } +} + // targetSet keeps one of the gateway's programs on a set of interfaces and // reports the ones it does not cover: xdpattach.Set in direct mode, // xdpattach.DispatchSet in dispatch mode. @@ -566,9 +609,10 @@ func (c *datapathCoverage) configure(targets []string) []string { // resolution failure, such as a bond in the moment between losing a member and // enslaving its replacement, keeps every attachment and skips that pass. func watchTargets(ctx context.Context, publicInterface string, internalInterfaces []string, - publicSet, returnSet targetSet, coverage *datapathCoverage, ipv4 *ipv4Forwarding, + publicSet, returnSet targetSet, coverage *datapathCoverage, ipv4 *ipv4Forwarding, vlanEgress *ebpf.Map, ) { xdpattach.OnNetlinkChange(ctx, func() { + syncVLANEgress(vlanEgress, publicInterface, internalInterfaces, false) var ( targets []string err error diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 530500fef..bae32c543 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -24,6 +24,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/natattach" "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" + "go.datum.net/galactic/internal/plumbing/ebpf/vlanegress" "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" @@ -85,6 +86,10 @@ type natDatapath struct { // resolveErrors counts watchUplinks' failed re-resolutions, which keep // the previous coverage. Nil counts nothing. resolveErrors prometheus.Counter + + // vlanEgress is nat.c's vlan_egress, which syncVLANEgress keeps in step + // with the resolved uplinks. Nil skips it. + vlanEgress *ebpf.Map } // Attached reports whether startup completed its load and attach pass. It is @@ -344,6 +349,8 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // translating established flows until the first reconcile re-derives it // from the EgressShard spec -- or clears it, if that shard is gone. d.shardConfig = natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}) + d.vlanEgress = objs.VlanEgress + d.syncVLANEgress(uplinks, true) var ( set *xdpattach.Set @@ -398,6 +405,35 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, return d, nil } +// syncVLANEgress fills nat.c's vlan_egress from the resolved uplinks: every +// one that is a VLAN netdevice, a tagged uplink, gets a row naming its lower +// device and VLAN ID. A translated packet whose route leaves through it is +// then sent through the lower device with that tag pushed in XDP, since a +// native redirect to a VLAN netdevice transmits nothing. logSides logs each +// tagged uplink, which startup does once. +func (d *natDatapath) syncVLANEgress(uplinks []string, logSides bool) { + if d.vlanEgress == nil { + return + } + lowers, ifindexes, err := vlanegress.FromNetlink(uplinks) + if err != nil { + slog.Warn("Cannot resolve every uplink for VLAN egress; routes through the ones left out are "+ + "redirected to the VLAN device as the FIB names it", "err", err) + } + if err := vlanegress.Sync(d.vlanEgress, lowers, ifindexes); err != nil { + slog.Warn("Cannot update the egress translation VLAN egress map", "err", err) + } + if !logSides { + return + } + for _, ifindex := range ifindexes { + if lower, vid, ok := lowers.VLANLower(ifindex); ok { + slog.Info("Uplink is tagged; its XDP hook runs in generic mode on the VLAN device", + "ifindex", ifindex, "vlanID", vid, "lowerIfindex", lower) + } + } +} + // registerUplinkQueueStats exports the per-queue receive counters of every // uplink d currently resolves. A single stalled NIC receive queue drops packets // before the datapath sees them, so drops_total stays flat through it (#673); @@ -531,6 +567,7 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover } return } + d.syncVLANEgress(uplinks, false) ready := d.adoptUplinks(uplinks) missing := uncovered(uplinks, cover(ready)) diff --git a/docs/designs/vlan-transport/contract.md b/docs/designs/vlan-transport/contract.md index 3480098bb..19d41db6f 100644 --- a/docs/designs/vlan-transport/contract.md +++ b/docs/designs/vlan-transport/contract.md @@ -1,6 +1,6 @@ # Tagged and untagged transport contract -Status: **proposed contract.** Nothing here is implemented or qualified. The [acceptance matrix](acceptance.md) lists the checks that must pass, and the [packet-path worksheet](packet-paths.md) traces each required direction. Issue [#1400](https://github.com/datum-cloud/galactic/issues/1400) delivers this design under epic [#1399](https://github.com/datum-cloud/galactic/issues/1399). +Status: **proposed contract.** Nothing here is qualified. [#1403](https://github.com/datum-cloud/galactic/issues/1403) implements the gateway and NAT hook placement and transmit tagging in [§5](#logical-interface-to-hook-targets); the rest is not implemented yet. The [acceptance matrix](acceptance.md) lists the checks that must pass, and the [packet-path worksheet](packet-paths.md) traces each required direction. Issue [#1400](https://github.com/datum-cloud/galactic/issues/1400) delivers this design under epic [#1399](https://github.com/datum-cloud/galactic/issues/1399). Source facts below were read at `main` commit `c504549a` and at `integration/galactic-worker` commit `bfd69e9c`. A statement marked **Assumption** has not been observed on a running kernel; the question it raises is assigned in [§10](#10-facts-assumptions-and-open-questions). @@ -129,16 +129,18 @@ Galactic validates each side's derived configuration at startup and on every re- Each component turns a side's logical interface into hook targets and tag context: -| Logical interface | tc ingress (`usid_ingress`, today) | XDP (`edge_lb`, `edge_return`, NAT, today) | Tag context for the hook | -| ----------------- | ----------------------------------------- | ------------------------------------------ | --------------------------------------------------------------- | -| NIC | The NIC | The NIC | None | -| Bond | The bond and its members | The members (`bond.XDPTargets`) | None | -| VLAN on a NIC | The VLAN netdevice | The VLAN netdevice | The side's VLAN ID and parent, which a hook on the parent needs | -| VLAN on a bond | The VLAN netdevice and the bond's members | The VLAN netdevice | As above | +| Logical interface | tc ingress (`usid_ingress`, today) | XDP (`edge_lb`, `edge_return`, NAT, today) | Tag context for the hook | +| ----------------- | ----------------------------------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------- | +| NIC | The NIC | The NIC | None | +| Bond | The bond and its members | The members (`bond.XDPTargets`) | None | +| VLAN on a NIC | The VLAN netdevice | The VLAN netdevice, always in generic mode | None at the hook. For transmit, `vlan_egress` maps the VLAN netdevice to its parent and VLAN ID | +| VLAN on a bond | The VLAN netdevice and the bond's members | The VLAN netdevice, always in generic mode | As above, with the bond as the parent | The tc column is `expandBondSlaves` and `vlanBondMaster` (`interfaces.go:304`, `:365`). The XDP column is `edgeattach.ResolveTargets` and `natattach.ResolveTargets` (`internal/plumbing/ebpf/edgeattach/attach.go:150`, `internal/plumbing/ebpf/natattach/attach.go:138`), which expand bonds but not VLANs. -The contract requires that a hook placed on a parent or bond member, rather than on the VLAN netdevice, receives the side's VLAN ID as configuration derived from the netdevice, never as a separate setting. Where XDP hooks go for a tagged side is [#1401](https://github.com/datum-cloud/galactic/issues/1401)'s question Q1. +A tagged side's XDP hooks run on its VLAN netdevice in generic mode, whatever the host's mode ([#1403](https://github.com/datum-cloud/galactic/issues/1403); `xdpmode.ForLink`). The kernel offers a VLAN netdevice no native XDP, and generic XDP runs there after the kernel has matched the frame's VLAN ID and removed the tag, whatever the parent's receive VLAN offload. So the programs never parse a transport tag, each side's hook sees only its own VLAN, and the shared XDP dispatcher stays free of packet parsing. Every other interface keeps the host's mode. + +On transmit, `bpf_fib_lookup` names the VLAN netdevice, and a native redirect to it drops every frame (#1401 Q4). `edgedsr.c` and `nat.c` look the egress interface up in their `vlan_egress` map, which each component fills from netlink for its configured sides only (`internal/plumbing/ebpf/vlanegress`). For a tagged side's VLAN netdevice the program pushes exactly that side's tag and leaves through the parent, with `XDP_TX` when the parent is the ingress interface. A bond parent receives the redirect on the bond master, which transmits in both modes. The VLAN ID is derived from the netdevice, never from a separate setting. ### Reconfiguration @@ -156,18 +158,19 @@ A restart must leave no stale hooks, routes or map rows that name the old netdev ## 6. Supported topologies -| Topology | Untagged mode | Tagged mode | -| -------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------- | -| Single NIC | Required | VLAN on the NIC: required | -| Bond, LACP (802.3ad) or active-backup | Required | VLAN on the bond: required | -| Two VLANs on one parent (one per side) | Not applicable | Required for tc and XDP paths; XDP isolation is open ([§10](#10-facts-assumptions-and-open-questions) Q3) | -| VLAN on a bond member | Not applicable | Excluded: the bond owns its members | -| Other bond modes | Not in the required matrix; not advertised | Not in the required matrix; not advertised | -| QinQ, 802.1ad, stacked VLANs | Not applicable | Excluded | +| Topology | Untagged mode | Tagged mode | +| ------------------------------------------------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Single NIC | Required | VLAN on the NIC: required | +| Bond, LACP (802.3ad) or active-backup | Required | VLAN on the bond: required | +| Two VLANs on one parent (one per side) | Not applicable | Required for tc and XDP paths. Each side's XDP hook runs on its own VLAN netdevice, which isolates them ([§10](#10-facts-assumptions-and-open-questions) Q3) | +| An untagged side on the parent of the other side's VLAN (Q8) | Not supported | Not supported: XDP on that parent sees a frame whose tag is in skb metadata as untagged, so it cannot keep the VLAN's traffic out of the untagged side | +| VLAN on a bond member | Not applicable | Excluded: the bond owns its members | +| Other bond modes | Not in the required matrix; not advertised | Not in the required matrix; not advertised | +| QinQ, 802.1ad, stacked VLANs | Not applicable | Excluded | Other requirements: -- **XDP mode.** Native and generic both apply. `xdpmode` picks one mode per host (`internal/plumbing/ebpf/xdpmode/mode.go:121`; generic where a `bnxt_en` NIC is present). Every required row runs in both modes where the environment supports native XDP. +- **XDP mode.** Native and generic both apply. `xdpmode` picks one mode per host (`internal/plumbing/ebpf/xdpmode/mode.go:121`; generic where a `bnxt_en` NIC is present, or as `GALACTIC_XDP_MODE` forces it). That mode applies to every untagged side's hooks. A tagged side's hooks always run in generic mode on its VLAN netdevice ([§5](#logical-interface-to-hook-targets)). Every required row runs in both host modes where the environment supports native XDP. - **Offloads.** Required with receive VLAN offload (`rx-vlan-offload`) on and off, and transmit VLAN offload (`tx-vlan-offload`) on and off. With receive offload on, the tag is in skb metadata at tc and, for native XDP, outside packet data; with it off, the tag is in packet data. Checksum and segmentation offloads keep their current support. ### Frame handling per mode @@ -222,6 +225,8 @@ Targets are relative to the untagged baseline that [#1401](https://github.com/da | Latency, p99 per direction | At most the untagged p99 plus 10% | As above | | Recovery after each event in [§5](#reconfiguration) | At most the untagged baseline for the same event plus 1 s | Tagging must not add a recovery step. The 1 s covers netdevice recreation and the 20 ms sampling uncertainty. | +On a host whose mode is native, a tagged side runs its XDP hooks in generic mode, which builds an skb for every frame before the program runs. Its throughput and latency can therefore miss the targets above against a native untagged baseline, even though nothing falls back to the kernel stack. [#1405](https://github.com/datum-cloud/galactic/issues/1405) and [#1406](https://github.com/datum-cloud/galactic/issues/1406) measure that cost. A host already in generic mode, such as one with a `bnxt_en` NIC, pays nothing extra. + [#1401](https://github.com/datum-cloud/galactic/issues/1401) records the baselines. If a baseline itself fails, it is discovery evidence, not acceptance, and the target is revisited in the epic. ### Diagnostics @@ -261,17 +266,17 @@ Source facts used by this contract: - 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. -Open feasibility questions. Each is assigned; none is answered by this design. - -| ID | Question | Owner | -| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | -| Q1 | Where do XDP hooks attach for a tagged side: the VLAN netdevice in generic mode, or the parent or members with the tag handled in the program? On `main` a VLAN netdevice stays the XDP target, which suggests native or dispatch attach is refused at startup. | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q2 | With receive offload on and off, where is the tag at each hook (packet data or metadata), and does `XDP_PASS` keep it so the kernel delivers to the VLAN netdevice? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q3 | How does XDP isolate two VLANs sharing one parent when, with receive offload, XDP on the parent sees both untagged? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q4 | Does an XDP redirect to a VLAN netdevice transmit in generic mode, and with the tag? Does `bpf_fib_lookup` return the VLAN netdevice for a route through it? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q5 | Does a tc `bpf_redirect` to a VLAN netdevice insert the tag on every parent type and offload setting? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q6 | Same-node delivery: does a tagged packet handed up from `edge_lb` reach `usid_ingress` with its tag context intact? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | -| Q7 | The Worker branch rewrites `nat_vlan_egress` only when a pair is programmed. Is a VLAN netdevice created later picked up, and how fast? (Inferred from source, not observed.) | [#1404](https://github.com/datum-cloud/galactic/issues/1404) | -| Q8 | Is an untagged side on the same parent as the other side's VLAN (a native VLAN plus a tagged VLAN on one trunk) supported? Not required by the epic; needs an epic decision before any exclusion is recorded. | [#1399](https://github.com/datum-cloud/galactic/issues/1399) | +Open feasibility questions. Each is assigned. Q1, Q3 and Q8 are settled, as each row says. + +| ID | Question | Owner | +| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | +| Q1 | Where do XDP hooks attach for a tagged side: the VLAN netdevice in generic mode, or the parent or members with the tag handled in the program? **Resolved:** on the VLAN netdevice, always in generic mode ([§5](#logical-interface-to-hook-targets)). | [#1401](https://github.com/datum-cloud/galactic/issues/1401), [#1403](https://github.com/datum-cloud/galactic/issues/1403) | +| Q2 | With receive offload on and off, where is the tag at each hook (packet data or metadata), and does `XDP_PASS` keep it so the kernel delivers to the VLAN netdevice? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | +| Q3 | How does XDP isolate two VLANs sharing one parent when, with receive offload, XDP on the parent sees both untagged? **Resolved:** no Galactic XDP hook runs on a tagged side's parent. Each side's hook runs on its own VLAN netdevice, after the kernel matched the VLAN ID. The device-bound VLAN metadata kfunc was rejected: the kernel keeps device-bound programs out of program arrays, which the dispatcher and NAT tail calls need, and it has no generic-mode support. | [#1401](https://github.com/datum-cloud/galactic/issues/1401), [#1403](https://github.com/datum-cloud/galactic/issues/1403) | +| Q4 | Does an XDP redirect to a VLAN netdevice transmit in generic mode, and with the tag? Does `bpf_fib_lookup` return the VLAN netdevice for a route through it? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | +| Q5 | Does a tc `bpf_redirect` to a VLAN netdevice insert the tag on every parent type and offload setting? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | +| Q6 | Same-node delivery: does a tagged packet handed up from `edge_lb` reach `usid_ingress` with its tag context intact? | [#1401](https://github.com/datum-cloud/galactic/issues/1401) | +| Q7 | The Worker branch rewrites `nat_vlan_egress` only when a pair is programmed. Is a VLAN netdevice created later picked up, and how fast? (Inferred from source, not observed.) | [#1404](https://github.com/datum-cloud/galactic/issues/1404) | +| Q8 | Is an untagged side on the same parent as the other side's VLAN (a native VLAN plus a tagged VLAN on one trunk) supported? **Not supported:** the untagged side's XDP hook runs on that parent and sees the VLAN's frames as untagged whenever the tag is in skb metadata, so it cannot keep the other side's traffic out ([§6](#6-supported-topologies)). | [#1399](https://github.com/datum-cloud/galactic/issues/1399), [#1403](https://github.com/datum-cloud/galactic/issues/1403) | [#1401](https://github.com/datum-cloud/galactic/issues/1401) answers Q1 to Q6 before [#1402](https://github.com/datum-cloud/galactic/issues/1402) and [#1403](https://github.com/datum-cloud/galactic/issues/1403) start. The [baseline report](../../archive/benchmarks/vlan-transport-baseline-2026-11-30.md#answers-to-the-contracts-questions) records the answers and labels each as probe-measured or source-inferred. diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index f4cf0c786..5903a95ac 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -39,6 +39,16 @@ exits. It first detaches an idle dispatcher from its interfaces, and refuses to start while another datapath's slot is live there. See [Sharing the XDP hook](packet-paths.md#sharing-the-xdp-hook-xdpdispatch). +A tagged (802.1Q) transport side is configured by naming its VLAN netdevice, +such as `bond0.101`, in `GALACTIC_GATEWAY_PUBLIC_INTERFACE` or +`GALACTIC_GATEWAY_INTERNAL_INTERFACES`. Its XDP hook then runs on that VLAN +netdevice in generic mode, whatever `GALACTIC_XDP_MODE` selects for the rest +of the host, and a reply or encapsulated packet routed through it leaves +through the VLAN's parent with exactly that side's tag. The +[XDP attach mode guide](../operations/xdp-attach-mode.md#vlan-netdevices-always-use-generic-mode) +and the [transport contract](../designs/vlan-transport/contract.md#logical-interface-to-hook-targets) +give the details. Name the parent instead and the side runs untagged. + `GALACTIC_XDP_MODE` has no `GALACTIC_GATEWAY` prefix. `galactic-nat` reads the same name, and both must resolve the same mode on a host. `auto` decides native or generic from the host's NIC drivers, and `native` or `generic` forces that diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 23f288985..56936e6f9 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -54,6 +54,13 @@ loopback (`attach.DetectUplinks`). Either way a bonding master resolves to its slaves, never to itself, since native XDP on a master is unreliable (`natattach.ResolveUplinks`). +A tagged (802.1Q) uplink is named by its VLAN netdevice, such as `bond0.101`. +The XDP program runs on that VLAN netdevice in generic mode, whatever +`GALACTIC_XDP_MODE` selects for the rest of the host, and a translated packet +routed through it leaves through the VLAN's parent with exactly that uplink's +tag. See the +[XDP attach mode guide](../operations/xdp-attach-mode.md#vlan-netdevices-always-use-generic-mode). + Set it on a node where detection is ambiguous — typically one whose management NIC carries the IPv6 default route, as Kind's `eth0` does in the containerlab lab. Detection would attach there too. diff --git a/docs/operations/xdp-attach-mode.md b/docs/operations/xdp-attach-mode.md index 830ef76af..346c1025e 100644 --- a/docs/operations/xdp-attach-mode.md +++ b/docs/operations/xdp-attach-mode.md @@ -136,6 +136,27 @@ one. The new pod's dispatcher overwrites it, and the before. Roll out the release before setting `GALACTIC_XDP_MODE`, so every pod on the host makes a claim. +## VLAN netdevices always use generic mode + +The host's mode applies to every interface except a VLAN netdevice. A VLAN +netdevice always attaches in generic mode, whatever the host's mode or +`GALACTIC_XDP_MODE`: + +- the kernel offers a VLAN netdevice no native XDP; +- generic XDP on it runs after the kernel matched the frame's VLAN ID, so a + tagged transport side's hook sees only its own VLAN, whatever the parent's + receive VLAN offload. + +`galactic-gateway` and `galactic-nat` attach a tagged side's hooks there, +directly or through the dispatcher, and skip the native support check for it. +The rule depends only on the interface, so both components agree on it, and +the [host-wide claim](#one-mode-per-host) is unchanged: it records the host's +mode. A node whose sides are all untagged behaves exactly as before. See the +[transport contract](../designs/vlan-transport/contract.md#logical-interface-to-hook-targets) +for the hook placement and the transmit tagging, and its +[measurement targets](../designs/vlan-transport/contract.md#measurement-and-recovery-targets) +for the generic-mode cost on a native host. + ## Attach, readiness and coverage - **No fallback between modes.** Every attach requests its mode explicitly diff --git a/internal/plumbing/ebpf/edgeattach/vlan_root_test.go b/internal/plumbing/ebpf/edgeattach/vlan_root_test.go new file mode 100644 index 000000000..a666ee07a --- /dev/null +++ b/internal/plumbing/ebpf/edgeattach/vlan_root_test.go @@ -0,0 +1,866 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeattach + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "os" + "strings" + "testing" + "time" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" + "github.com/cilium/ebpf/link" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/safchain/ethtool" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" + "go.datum.net/galactic/internal/plumbing/ebpf/vlanegress" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" +) + +// The VLAN transport tests below run the gateway's programs on a real kernel, +// attached the way galactic-gateway attaches them, across three namespaces: +// +// rtr (external router) <-> gw (edge node) <-> nh (fabric next hop) +// +// The public side is the veth pub (gw) to rtr, the fabric side the veth fab +// (gw) to nh, or a bond fab whose one member fabm pairs with nh. A tagged side +// adds a VLAN netdevice on each end: public ID vtPubVID, fabric ID vtFabVID. +// A tagged public side also carries a second VLAN, vtOtherVID, on the same +// parent. Each case runs once per host mode, as GALACTIC_XDP_MODE forces it. +// All addresses are documentation or unique local ranges. +const ( + vtPubVID = 101 + vtOtherVID = 202 + vtFabVID = 303 + vtPort = 443 + vtRtr = "rtr" +) + +var ( + vtVIP = netip.MustParseAddr("2001:db8:100::10") + vtClient = netip.MustParseAddr("2001:db8:ffff::1") + vtUSID = netip.MustParseAddr("fc00:1:2::a1b2") + vtPubGW = netip.MustParseAddr("fd00:a::1") + vtPubRtr = netip.MustParseAddr("fd00:a::2") + vtOtherGW = netip.MustParseAddr("fd00:c::1") + vtFabGW = netip.MustParseAddr("fd00:b::1") + vtFabNH = netip.MustParseAddr("fd00:b::2") + // vtLocalUSID shares its first 64 bits with vtFabGW, the gateway's + // encapsulation source, which makes it a uSID on the gateway's own node. + vtLocalUSID = netip.MustParseAddr("fd00:b::a1b2") +) + +// vtHostModes are the host modes each case runs in, as GALACTIC_XDP_MODE +// names them. Setting it runs only that mode. +func vtHostModes(t *testing.T) map[string]xdpmode.Mode { + t.Helper() + all := map[string]xdpmode.Mode{ + xdpmode.SettingNativeValue: xdpmode.Native, + xdpmode.SettingGenericValue: xdpmode.Generic, + } + v := os.Getenv(xdpmode.SettingEnv) + if v == "" || v == xdpmode.SettingAutoValue { + return all + } + s, err := xdpmode.ParseSetting(v) + if err != nil { + t.Fatalf("%v", err) + } + return map[string]xdpmode.Mode{v: all[s.String()]} +} + +type vtTopo struct { + pubTagged, fabTagged, fabBond bool + // fabOnPub puts the fabric VLAN on the public parent, with the next hop + // in rtr, so a route from the public hook to the fabric leaves through + // the ingress interface (XDP_TX). + fabOnPub bool + // coldFab leaves the fabric next hop's neighbor entry to the kernel. + coldFab bool + // dispatch runs the programs from the node's XDP dispatcher slots + // instead of attaching them directly. + dispatch bool + // localBackend puts the VIP's only backend on the gateway's own node. + localBackend bool +} + +type vtLab struct { + t *testing.T + gw, rtr, nh ns.NetNS + objs *edgeprog.EdgedsrObjects + // pubLogical and fabLogical are the sides' logical interfaces in gw; + // rtrLogical and nhLogical their peers. + pubLogical, fabLogical string + rtrLogical, nhLogical string + rtrNS, nhNS ns.NetNS // where rtrLogical and nhLogical live + rtrCap, nhCap int // captures on the physical peers + gwPubMAC, gwFabMAC net.HardwareAddr +} + +func newNS(t *testing.T) ns.NetNS { + t.Helper() + n, err := ns.TempNetNS() + if err != nil { + t.Fatalf("create namespace: %v", err) + } + t.Cleanup(func() { _ = n.Close() }) + return n +} + +func in(t *testing.T, n ns.NetNS, fn func() error) { + t.Helper() + if err := n.Do(func(ns.NetNS) error { return fn() }); err != nil { + t.Fatal(err) + } +} + +func vtUp(name string) error { + l, err := netlink.LinkByName(name) + if err != nil { + return err + } + return netlink.LinkSetUp(l) +} + +func vtAddVLAN(parent string, vid int) (string, error) { + p, err := netlink.LinkByName(parent) + if err != nil { + return "", err + } + name := fmt.Sprintf("%s.%d", parent, vid) + if err := netlink.LinkAdd(&netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Name: name, ParentIndex: p.Attrs().Index}, + VlanId: vid, VlanProtocol: netlink.VLAN_PROTOCOL_8021Q}); err != nil { + return "", fmt.Errorf("add VLAN %s: %w", name, err) + } + return name, vtUp(name) +} + +func vtAddr(name string, a netip.Addr) error { + l, err := netlink.LinkByName(name) + if err != nil { + return err + } + return netlink.AddrAdd(l, &netlink.Addr{IPNet: &net.IPNet{IP: a.AsSlice(), Mask: net.CIDRMask(64, 128)}, + Flags: unix.IFA_F_NODAD}) +} + +func vtRoute(name string, dst, via netip.Addr) error { + l, err := netlink.LinkByName(name) + if err != nil { + return err + } + return netlink.RouteAdd(&netlink.Route{LinkIndex: l.Attrs().Index, Gw: via.AsSlice(), + Dst: &net.IPNet{IP: dst.AsSlice(), Mask: net.CIDRMask(128, 128)}}) +} + +func vtNeigh(name string, ip netip.Addr, mac net.HardwareAddr) error { + l, err := netlink.LinkByName(name) + if err != nil { + return err + } + return netlink.NeighSet(&netlink.Neigh{LinkIndex: l.Attrs().Index, Family: netlink.FAMILY_V6, + State: netlink.NUD_PERMANENT, IP: ip.AsSlice(), HardwareAddr: mac}) +} + +func vtSysctl(key, val string) error { + return os.WriteFile("/proc/sys/"+strings.ReplaceAll(key, ".", "/"), []byte(val), 0o644) +} + +// vtVethTo creates a veth name in the current namespace whose peer, peerName, +// moves to peer, and brings both up. +func vtVethTo(name, peerName string, peer ns.NetNS) error { + if err := netlink.LinkAdd(&netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: name}, PeerName: peerName}); err != nil { + return fmt.Errorf("add veth %s: %w", name, err) + } + p, err := netlink.LinkByName(peerName) + if err != nil { + return err + } + if err := netlink.LinkSetNsFd(p, int(peer.Fd())); err != nil { + return err + } + if err := vtUp(name); err != nil { + return err + } + return peer.Do(func(ns.NetNS) error { return vtUp(peerName) }) +} + +// vtPassProgram is an XDP program that passes everything. On a veth it lets +// the peer take natively redirected frames, as a real NIC would. +func vtPassProgram(t *testing.T) *ebpf.Program { + t.Helper() + p, err := ebpf.NewProgram(&ebpf.ProgramSpec{Type: ebpf.XDP, License: "GPL", + Instructions: asm.Instructions{asm.Mov.Imm(asm.R0, 2), asm.Return()}}) + if err != nil { + t.Fatalf("load pass program: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func newVTLab(t *testing.T, topo vtTopo, mode xdpmode.Mode) *vtLab { + t.Helper() + l := &vtLab{t: t, gw: newNS(t), rtr: newNS(t), nh: newNS(t)} + l.rtrNS, l.nhNS = l.rtr, l.nh + l.pubLogical, l.rtrLogical, l.fabLogical, l.nhLogical = "pub", vtRtr, "fab", "nh" + in(t, l.gw, func() error { return l.links(topo) }) + l.vlans(topo) + l.addressing(topo, vtPassProgram(t)) + in(t, l.gw, func() error { return l.load(topo, mode) }) + return l +} + +// links creates the gateway's parents and their peers. +func (l *vtLab) links(topo vtTopo) error { + for _, k := range []string{"net.ipv6.conf.all.forwarding", "net.ipv6.conf.default.forwarding"} { + if err := vtSysctl(k, "1"); err != nil { + return err + } + } + if err := vtVethTo("pub", vtRtr, l.rtr); err != nil { + return err + } + if !topo.fabBond { + return vtVethTo("fab", "nh", l.nh) + } + b := netlink.NewLinkBond(netlink.LinkAttrs{Name: "fab"}) + b.Mode, b.Miimon = netlink.BOND_MODE_ACTIVE_BACKUP, 100 + if err := netlink.LinkAdd(b); err != nil { + return fmt.Errorf("add bond: %w", err) + } + if err := vtVethTo("fabm", "nh", l.nh); err != nil { + return err + } + m, err := netlink.LinkByName("fabm") + if err != nil { + return err + } + _ = netlink.LinkSetDown(m) + if err := netlink.LinkSetMasterByIndex(m, mustIndex("fab")); err != nil { + return fmt.Errorf("enslave fabm: %w", err) + } + if err := vtUp("fabm"); err != nil { + return err + } + return vtUp("fab") +} + +// vlans adds each tagged side's VLAN netdevices on both ends. +func (l *vtLab) vlans(topo vtTopo) { + t := l.t + in(t, l.gw, func() error { + var err error + if topo.pubTagged { + if l.pubLogical, err = vtAddVLAN("pub", vtPubVID); err != nil { + return err + } + other, err := vtAddVLAN("pub", vtOtherVID) + if err != nil { + return err + } + if err := vtAddr(other, vtOtherGW); err != nil { + return err + } + } + switch { + case topo.fabOnPub: + l.fabLogical, err = vtAddVLAN("pub", vtFabVID) + case topo.fabTagged: + l.fabLogical, err = vtAddVLAN("fab", vtFabVID) + } + return err + }) + if topo.fabOnPub { + l.nhNS, l.nhLogical = l.rtr, vtRtr + } + in(t, l.rtr, func() error { + if !topo.pubTagged { + return nil + } + var err error + if l.rtrLogical, err = vtAddVLAN(vtRtr, vtPubVID); err != nil { + return err + } + _, err = vtAddVLAN(vtRtr, vtOtherVID) + return err + }) + in(t, l.nhNS, func() error { + if !topo.fabTagged && !topo.fabOnPub { + return nil + } + var err error + l.nhLogical, err = vtAddVLAN(l.nhLogical, vtFabVID) + return err + }) +} + +// vtPeer gives the physical peer pass an XDP program, as natively redirected +// frames need on a veth, and opens a capture on it. +func vtPeer(t *testing.T, name string, pass *ebpf.Program) (net.HardwareAddr, int, error) { + pl, err := netlink.LinkByName(name) + if err != nil { + return nil, 0, err + } + xl, err := link.AttachXDP(link.XDPOptions{Program: pass, Interface: pl.Attrs().Index, Flags: link.XDPDriverMode}) + if err != nil { + return nil, 0, err + } + t.Cleanup(func() { _ = xl.Close() }) + return pl.Attrs().HardwareAddr, vtCapture(t, pl.Attrs().Index), nil +} + +// addressing adds addresses, routes and neighbors. The routes go through each +// side's logical interface, as infrastructure configures them. +func (l *vtLab) addressing(topo vtTopo, pass *ebpf.Program) { + t := l.t + var rtrMAC, nhMAC net.HardwareAddr + in(t, l.rtrNS, func() error { + if err := vtAddr(l.rtrLogical, vtPubRtr); err != nil { + return err + } + var err error + rtrMAC, l.rtrCap, err = vtPeer(t, vtRtr, pass) + return err + }) + in(t, l.nhNS, func() error { + if err := vtAddr(l.nhLogical, vtFabNH); err != nil { + return err + } + if topo.fabOnPub { + nhMAC, l.nhCap = rtrMAC, l.rtrCap + return nil + } + var err error + nhMAC, l.nhCap, err = vtPeer(t, "nh", pass) + return err + }) + in(t, l.gw, func() error { + if err := vtAddr(l.pubLogical, vtPubGW); err != nil { + return err + } + if err := vtAddr(l.fabLogical, vtFabGW); err != nil { + return err + } + if err := vtRoute(l.pubLogical, vtClient, vtPubRtr); err != nil { + return err + } + if err := vtRoute(l.fabLogical, vtUSID, vtFabNH); err != nil { + return err + } + if err := vtNeigh(l.pubLogical, vtPubRtr, rtrMAC); err != nil { + return err + } + if !topo.coldFab { + if err := vtNeigh(l.fabLogical, vtFabNH, nhMAC); err != nil { + return err + } + } + pl, _ := netlink.LinkByName(l.pubLogical) + fl, _ := netlink.LinkByName(l.fabLogical) + l.gwPubMAC, l.gwFabMAC = pl.Attrs().HardwareAddr, fl.Attrs().HardwareAddr + return nil + }) +} + +// load loads and attaches the programs the way galactic-gateway does: resolve +// each side's targets, attach in the host mode, fill vlan_egress from the +// sides. +func (l *vtLab) load(topo vtTopo, mode xdpmode.Mode) error { + t := l.t + var ( + objs edgeprog.EdgedsrObjects + dispatcher *xdpdispatch.Dispatcher + opts *ebpf.CollectionOptions + ) + if topo.dispatch { + var err error + if dispatcher, err = vtDispatcher(t, mode); err != nil { + return err + } + opts = &ebpf.CollectionOptions{MapReplacements: dispatcher.Maps()} + } + if err := edgeprog.LoadEdgedsrObjects(&objs, opts); err != nil { + return fmt.Errorf("load edge objects: %w", err) + } + t.Cleanup(func() { _ = objs.Close() }) + l.objs = &objs + if err := l.vip(topo.localBackend); err != nil { + return err + } + sides := map[*ebpf.Program]string{l.objs.EdgeLb: l.pubLogical} + if !topo.fabOnPub { // with the fabric VLAN on the public parent, only edge_lb runs + sides[l.objs.EdgeReturn] = l.fabLogical + } + for prog, side := range sides { + targets, err := ResolveTargets(side) + if err != nil { + return err + } + if dispatcher != nil { + err = l.dispatch(dispatcher, prog, targets) + } else { + err = l.attach(prog, targets, mode) + } + if err != nil { + return err + } + if err := vtCheckModes(targets, mode); err != nil { + return err + } + } + lowers, ifindexes, err := vlanegress.FromNetlink([]string{l.pubLogical, l.fabLogical}) + if err != nil { + return err + } + return vlanegress.Sync(l.objs.VlanEgress, lowers, ifindexes) +} + +// vip loads one UDP VIP whose only backend is vtUSID, or vtLocalUSID on +// this node. +func (l *vtLab) vip(local bool) error { + if err := l.objs.EncapConfigTable.Put(uint32(0), edgeprog.EdgedsrEncapConfig{EncapSrc: vtFabGW.As16()}); err != nil { + return err + } + var backend edgeprog.EdgedsrVipValue + backend.BackendCount = 1 + backend.Backends[0].Usid = vtUSID.As16() + if local { + backend.Backends[0].Usid = vtLocalUSID.As16() + } + key := edgeprog.EdgedsrVipKey{Proto: unix.IPPROTO_UDP, Port: vtSwap(vtPort), Vip: vtVIP.As16()} + if err := l.objs.VipTable.Put(key, backend); err != nil { + return err + } + return l.objs.VipAddrTable.Put(edgeprog.EdgedsrVipAddrKey{Vip: vtVIP.As16()}, + edgeprog.EdgedsrVipAddrValue{Generation: 1}) +} + +func (l *vtLab) attach(prog *ebpf.Program, targets []string, mode xdpmode.Mode) error { + links, err := Attach(prog, targets, mode) + if err != nil { + return err + } + for _, xl := range links { + l.t.Cleanup(func() { _ = xl.Close() }) + } + return nil +} + +// vtDispatcher opens a dispatcher pinned under a fresh bpffs directory. +func vtDispatcher(t *testing.T, mode xdpmode.Mode) (*xdpdispatch.Dispatcher, error) { + dir := fmt.Sprintf("/sys/fs/bpf/vlan-transport-test-%d", time.Now().UnixNano()) + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("bpffs not writable: %w", err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + d, err := xdpdispatch.Open(context.Background(), dir, mode) + if err != nil { + return nil, err + } + t.Cleanup(func() { _ = d.Close() }) + return d, nil +} + +// dispatch runs prog from its gateway slot on targets, as galactic-gateway's +// dispatch mode does. +func (l *vtLab) dispatch(d *xdpdispatch.Dispatcher, prog *ebpf.Program, targets []string) error { + slot, role := xdpdispatch.SlotGatewayLB, xdpdispatch.RolePublicLB + if prog == l.objs.EdgeReturn { + slot, role = xdpdispatch.SlotGatewayReturn, xdpdispatch.RoleInternalReturn + } + lock, err := d.Lock(context.Background()) + if err != nil { + return err + } + err = lock.Fill(slot, prog) + lock.Unlock() + if err != nil { + return err + } + if err := d.Renew(slot); err != nil { + return err + } + set, err := xdpattach.NewDispatchSet(d, slot, role, prog) + if err != nil { + return err + } + if missing := set.Reconcile(context.Background(), targets); len(missing) > 0 { + return fmt.Errorf("dispatcher does not cover %v", missing) + } + return nil +} + +// vtCheckModes checks each target holds its XDP program in the mode the host +// mode gives it: generic on a VLAN netdevice, the host mode anywhere else. +func vtCheckModes(targets []string, mode xdpmode.Mode) error { + for _, target := range targets { + want := mode + if strings.Contains(target, ".") { + want = xdpmode.Generic + } + tl, err := netlink.LinkByName(target) + if err != nil { + return err + } + if x := tl.Attrs().Xdp; x == nil || !want.Matches(x.AttachMode) { + return fmt.Errorf("%s holds XDP %+v, want %s mode", target, x, want) + } + } + return nil +} + +func mustIndex(name string) int { + l, err := netlink.LinkByName(name) + if err != nil { + return 0 + } + return l.Attrs().Index +} + +func vtSwap(v uint16) uint16 { return v<<8 | v>>8 } + +// vtCapture opens a packet socket on ifindex that reports a tag the kernel +// moved out of the frame (PACKET_AUXDATA), so a capture sees every tag a frame +// carried on the wire. +func vtCapture(t *testing.T, ifindex int) int { + t.Helper() + proto := vtSwap(unix.ETH_P_ALL) + fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW|unix.SOCK_CLOEXEC, int(proto)) + if err != nil { + t.Fatalf("open packet socket: %v", err) + } + t.Cleanup(func() { _ = unix.Close(fd) }) + if err := unix.SetsockoptInt(fd, unix.SOL_PACKET, unix.PACKET_AUXDATA, 1); err != nil { + t.Fatalf("enable PACKET_AUXDATA: %v", err) + } + if err := unix.Bind(fd, &unix.SockaddrLinklayer{Protocol: proto, Ifindex: ifindex}); err != nil { + t.Fatalf("bind packet socket: %v", err) + } + return fd +} + +// vtWire is one captured frame: its tags, outermost first, wherever the kernel +// kept them, and the EtherType after the last. +type vtWire struct { + tags []uint16 + ether uint16 + frame []byte +} + +// vtAwait returns the first frame on fd containing marker within wait. +func vtAwait(t *testing.T, fd int, marker []byte, wait time.Duration) (vtWire, bool) { + t.Helper() + deadline := time.Now().Add(wait) + buf := make([]byte, 65536) + oob := make([]byte, 256) + for time.Now().Before(deadline) { + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + n, err := unix.Poll(fds, int(time.Until(deadline).Milliseconds())+1) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil || n == 0 { + break + } + n, oobn, _, from, err := unix.Recvmsg(fd, buf, oob, unix.MSG_DONTWAIT) + if err != nil || !bytes.Contains(buf[:n], marker) { + continue + } + // A frame this end sent is not one it received. + if ll, ok := from.(*unix.SockaddrLinklayer); ok && ll.Pkttype == unix.PACKET_OUTGOING { + continue + } + w := vtWire{frame: append([]byte(nil), buf[:n]...)} + msgs, _ := unix.ParseSocketControlMessage(oob[:oobn]) + for _, m := range msgs { + // struct tpacket_auxdata: status, len, snaplen (u32), mac, net, + // vlan_tci, vlan_tpid (u16). TP_STATUS_VLAN_VALID is 0x10. + if m.Header.Level == unix.SOL_PACKET && m.Header.Type == unix.PACKET_AUXDATA && len(m.Data) >= 20 { + if binary.NativeEndian.Uint32(m.Data[0:4])&unix.TP_STATUS_VLAN_VALID != 0 { + w.tags = append(w.tags, binary.NativeEndian.Uint16(m.Data[16:18])&0x0fff) + } + } + } + off := 12 + for { + et := binary.BigEndian.Uint16(buf[off : off+2]) + if et != 0x8100 && et != 0x88a8 { + w.ether = et + break + } + w.tags = append(w.tags, binary.BigEndian.Uint16(buf[off+2:off+4])&0x0fff) + off += 4 + } + return w, true + } + return vtWire{}, false +} + +// vtFrame builds an Ethernet, IPv6 and UDP frame to dstMAC carrying marker. +func vtFrame(dstMAC net.HardwareAddr, src, dst netip.Addr, sport, dport uint16, marker []byte) []byte { + f := make([]byte, 14+40+8, 14+40+8+len(marker)) + copy(f[0:6], dstMAC) + copy(f[6:12], []byte{0x02, 0, 0, 0, 0, 0x99}) + binary.BigEndian.PutUint16(f[12:14], 0x86DD) + f[14] = 0x60 + binary.BigEndian.PutUint16(f[18:20], uint16(8+len(marker))) + f[20], f[21] = unix.IPPROTO_UDP, 64 + s, d := src.As16(), dst.As16() + copy(f[22:38], s[:]) + copy(f[38:54], d[:]) + binary.BigEndian.PutUint16(f[54:56], sport) + binary.BigEndian.PutUint16(f[56:58], dport) + binary.BigEndian.PutUint16(f[58:60], uint16(8+len(marker))) + return append(f, marker...) +} + +// send writes frame out of iface in n, through a packet socket: on a VLAN +// netdevice the kernel tags it as it would any other frame. +func (l *vtLab) send(n ns.NetNS, iface string, frame []byte) { + l.t.Helper() + in(l.t, n, func() error { + fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW|unix.SOCK_CLOEXEC, 0) + if err != nil { + return err + } + defer unix.Close(fd) //nolint:errcheck // test socket + return unix.Sendto(fd, frame, 0, &unix.SockaddrLinklayer{Ifindex: mustIndex(iface), Protocol: vtSwap(0x86DD)}) + }) +} + +func (l *vtLab) vipPackets() uint64 { + l.t.Helper() + var s edgeprog.EdgedsrVipStatsValue + key := edgeprog.EdgedsrVipKey{Proto: unix.IPPROTO_UDP, Port: vtSwap(vtPort), Vip: vtVIP.As16()} + if err := l.objs.VipStatsTable.Lookup(key, &s); err != nil { + return 0 + } + return s.Packets +} + +func marker(label string) []byte { + return fmt.Appendf(nil, "vlan-transport:%s:%d", label, time.Now().UnixNano()) +} + +// wantWire checks a captured frame carries exactly the tags want, outermost +// first, and IPv6 after them. +func wantWire(t *testing.T, what string, w vtWire, want ...uint16) { + t.Helper() + if fmt.Sprint(w.tags) != fmt.Sprint(want) || w.ether != 0x86DD { + t.Errorf("%s: wire tags %v then EtherType %#04x, want tags %v then 0x86dd", what, w.tags, w.ether, want) + } +} + +func tagsFor(tagged bool, vid uint16) []uint16 { + if tagged { + return []uint16{vid} + } + return nil +} + +// TestVLANTransport_GatewayPaths covers gateway ingress and DSR return in all +// four public/fabric combinations, with a single NIC and a bond as the fabric +// parent, in each host mode: each frame leaves with exactly its egress side's +// tag, or none, and never the ingress side's. +func TestVLANTransport_GatewayPaths(t *testing.T) { + requireRoot(t) + for modeName, mode := range vtHostModes(t) { + for _, topo := range []vtTopo{ + {}, {pubTagged: true}, {fabTagged: true}, {pubTagged: true, fabTagged: true}, + {fabBond: true}, {pubTagged: true, fabBond: true}, {fabTagged: true, fabBond: true}, + {pubTagged: true, fabTagged: true, fabBond: true}, + {pubTagged: true, dispatch: true}, {fabTagged: true, dispatch: true}, + {pubTagged: true, fabTagged: true, fabBond: true, dispatch: true}, + } { + name := fmt.Sprintf("%s/public-tagged=%v/fabric-tagged=%v/bond=%v/dispatch=%v", modeName, + topo.pubTagged, topo.fabTagged, topo.fabBond, topo.dispatch) + t.Run(name, func(t *testing.T) { + l := newVTLab(t, topo, mode) + + m := marker("ingress") + l.send(l.rtr, l.rtrLogical, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40000, vtPort, m)) + w, ok := vtAwait(t, l.nhCap, m, 2*time.Second) + if !ok { + t.Fatalf("encapsulated request never reached the fabric next hop (vip packets %d)", l.vipPackets()) + } + wantWire(t, "gateway ingress at the fabric next hop", w, tagsFor(topo.fabTagged, vtFabVID)...) + + m = marker("return") + l.send(l.nh, l.nhLogical, vtFrame(l.gwFabMAC, vtVIP, vtClient, vtPort, 40000, m)) + w, ok = vtAwait(t, l.rtrCap, m, 2*time.Second) + if !ok { + t.Fatalf("DSR reply never reached the external router") + } + wantWire(t, "DSR return at the external router", w, tagsFor(topo.pubTagged, vtPubVID)...) + }) + } + } +} + +// TestVLANTransport_OtherVLANNotClaimed sends VIP traffic on a second VLAN of +// the public parent and untagged on the parent itself. Neither reaches +// edge_lb, which runs on the public VLAN netdevice only, whatever the +// sender's transmit VLAN offload left in the frame. +func TestVLANTransport_OtherVLANNotClaimed(t *testing.T) { + requireRoot(t) + for modeName, mode := range vtHostModes(t) { + for _, txOffload := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/tx-vlan-offload=%v", modeName, txOffload), func(t *testing.T) { + l := newVTLab(t, vtTopo{pubTagged: true, fabTagged: true}, mode) + vtFeatures(t, l.rtr, vtRtr, txOffload) + + for _, iface := range []string{fmt.Sprintf("%s.%d", vtRtr, vtOtherVID), vtRtr} { + m := marker("other-" + iface) + before := l.vipPackets() + l.send(l.rtr, iface, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40001, vtPort, m)) + if _, ok := vtAwait(t, l.nhCap, m, 500*time.Millisecond); ok { + t.Errorf("VIP traffic sent on %s reached the fabric", iface) + } + if got := l.vipPackets(); got != before { + t.Errorf("VIP traffic sent on %s was claimed: vip packets %d, want %d", iface, got, before) + } + } + + m := marker("own") + l.send(l.rtr, l.rtrLogical, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40001, vtPort, m)) + w, ok := vtAwait(t, l.nhCap, m, 2*time.Second) + if !ok { + t.Fatalf("VIP traffic on the public VLAN never reached the fabric") + } + wantWire(t, "gateway ingress", w, vtFabVID) + }) + } + } +} + +func vtEthtool(iface string, cfg map[string]bool) error { + e, err := ethtool.NewEthtool() + if err != nil { + return err + } + defer e.Close() + return e.Change(iface, cfg) +} + +func vtFeatures(t *testing.T, n ns.NetNS, iface string, txVLAN bool) { + t.Helper() + in(t, n, func() error { + return vtEthtool(iface, map[string]bool{"tx-vlan-hw-insert": txVLAN}) + }) +} + +// TestVLANTransport_TagPushWithXDPTX routes the fabric through a VLAN on the +// public parent, which the untagged public hook received the request on: the +// program pushes the fabric tag and transmits with XDP_TX. +func TestVLANTransport_TagPushWithXDPTX(t *testing.T) { + requireRoot(t) + for modeName, mode := range vtHostModes(t) { + t.Run(modeName, func(t *testing.T) { + l := newVTLab(t, vtTopo{fabOnPub: true}, mode) + m := marker("xdp-tx") + l.send(l.rtr, vtRtr, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40002, vtPort, m)) + w, ok := vtAwait(t, l.rtrCap, m, 2*time.Second) + if !ok { + t.Fatalf("encapsulated request never came back out of the public parent") + } + wantWire(t, "XDP_TX toward the fabric VLAN", w, vtFabVID) + }) + } +} + +// TestVLANTransport_ColdNeighborFallsBackInVLANContext leaves the fabric next +// hop unresolved. edge_lb, running on the public VLAN netdevice, hands the +// encapsulated packet to the kernel with XDP_PASS, which forwards it as +// received on the public VLAN: out of the fabric VLAN with only the fabric tag. +func TestVLANTransport_ColdNeighborFallsBackInVLANContext(t *testing.T) { + requireRoot(t) + for modeName, mode := range vtHostModes(t) { + t.Run(modeName, func(t *testing.T) { + l := newVTLab(t, vtTopo{pubTagged: true, fabTagged: true, coldFab: true}, mode) + m := marker("cold") + l.send(l.rtr, l.rtrLogical, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40003, vtPort, m)) + w, ok := vtAwait(t, l.nhCap, m, 3*time.Second) + if !ok { + t.Fatalf("encapsulated request never reached the unresolved fabric next hop") + } + wantWire(t, "kernel fallback toward the fabric", w, vtFabVID) + var fallbacks []uint64 + if err := l.objs.NeighFallbacks.Lookup(uint32(0), &fallbacks); err != nil { + t.Fatalf("read neigh_fallbacks: %v", err) + } + var total uint64 + for _, v := range fallbacks { + total += v + } + if total == 0 { + t.Errorf("neigh_fallbacks = 0, want the request counted as a kernel fallback") + } + }) + } +} + +// TestVLANTransport_LocalDeliveryStaysOnThePublicVLAN covers same-node +// delivery (GALACTIC_GATEWAY_LOCAL_DELIVERY) on a tagged public side. edge_lb +// pushes the outer header and hands the packet to the kernel with XDP_PASS, +// framed as it arrived. A capture on the public VLAN netdevice, which taps the +// frame after its generic XDP hook, sees the encapsulated packet there with no +// tag: the kernel continues it in the public VLAN's receive path, where +// galactic-cni's usid_ingress on that VLAN netdevice claims it. The claim +// itself belongs to usid_ingress and is not run here. +func TestVLANTransport_LocalDeliveryStaysOnThePublicVLAN(t *testing.T) { + requireRoot(t) + for modeName, mode := range vtHostModes(t) { + t.Run(modeName, func(t *testing.T) { + l := newVTLab(t, vtTopo{pubTagged: true, fabTagged: true, localBackend: true}, mode) + var capture int + in(t, l.gw, func() error { + capture = vtCapture(t, mustIndex(l.pubLogical)) + return nil + }) + m := marker("local") + l.send(l.rtr, l.rtrLogical, vtFrame(l.gwPubMAC, vtClient, vtVIP, 40004, vtPort, m)) + w, ok := vtAwait(t, capture, m, 2*time.Second) + if !ok { + t.Fatalf("the locally delivered packet never reached %s's receive path", l.pubLogical) + } + wantWire(t, "local delivery on the public VLAN", w) + const nexthdr, daddr = 14 + 6, 14 + 24 + if got := netip.AddrFrom16([16]byte(w.frame[daddr : daddr+16])); w.frame[nexthdr] != 41 || got != vtLocalUSID { + t.Errorf("handed-up packet has next header %d to %s, want 41 to the local uSID %s", + w.frame[nexthdr], got, vtLocalUSID) + } + if !bytes.Equal(w.frame[0:6], l.gwPubMAC) { + t.Errorf("handed-up packet's destination MAC %x, want the gateway's %s", w.frame[0:6], l.gwPubMAC) + } + var delivered []uint64 + if err := l.objs.LocalDeliveries.Lookup(uint32(0), &delivered); err != nil { + t.Fatalf("read local_deliveries: %v", err) + } + var total uint64 + for _, v := range delivered { + total += v + } + if total != 1 { + t.Errorf("local_deliveries = %d, want 1", total) + } + if _, ok := vtAwait(t, l.nhCap, m, 300*time.Millisecond); ok { + t.Errorf("the locally delivered packet also left through the fabric") + } + }) + } +} diff --git a/internal/plumbing/ebpf/edgeprog/doc.go b/internal/plumbing/ebpf/edgeprog/doc.go index cd02bf997..da1a94b88 100644 --- a/internal/plumbing/ebpf/edgeprog/doc.go +++ b/internal/plumbing/ebpf/edgeprog/doc.go @@ -33,4 +33,4 @@ package edgeprog // This program never takes the address of a field inside a packed struct, so it // needs no warning suppression for that. // -//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 vip_range -type vip_key -type backend -type vip_value -type vip_stats_value -type encap_config -type vip_addr_key -type vip_addr_value Edgedsr edgedsr.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 vip_range -type vip_key -type backend -type vip_value -type vip_stats_value -type encap_config -type vip_addr_key -type vip_addr_value -type vlan_egress_value Edgedsr edgedsr.c diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr.c b/internal/plumbing/ebpf/edgeprog/edgedsr.c index e7c659612..ea19b09c1 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr.c +++ b/internal/plumbing/ebpf/edgeprog/edgedsr.c @@ -111,6 +111,8 @@ static long (*bpf_redirect)(__u32 ifindex, __u64 flags) = (void *) BPF_FUNC_redi #define EDGE_AF_INET6 10 #define EDGE_ETH_P_IP 0x0800 #define EDGE_ETH_P_IPV6 0x86DD +#define EDGE_ETH_P_8021Q 0x8100 +#define EDGE_VLAN_HLEN 4 #define EDGE_IPPROTO_ICMP 1 #define EDGE_IPPROTO_IPIP 4 // the pushed outer header's Next Header for an IPv4 packet #define EDGE_IPPROTO_TCP 6 @@ -460,6 +462,30 @@ struct { __type(value, struct icmp_bucket); } icmp_rate_bucket SEC(".maps"); +// struct vlan_egress_value is vlan_egress's value: the device a VLAN +// netdevice sits on and its 802.1Q VLAN ID, host order. +struct vlan_egress_value { + __u32 lower_ifindex; + __u16 vid; + __u16 pad; +}; + +// vlan_egress maps the VLAN netdevice of each tagged transport side this +// gateway uses to its lower device and VLAN ID. The control plane fills it +// from netlink (internal/plumbing/ebpf/vlanegress); nothing here writes it. +// +// bpf_fib_lookup names the VLAN netdevice for a route through it, and a native +// XDP redirect to a VLAN netdevice drops every frame, since a VLAN netdevice +// has no ndo_xdp_xmit. leave_via therefore pushes the tag itself and leaves +// through the lower device. A VLAN netdevice missing here is redirected to as +// the FIB named it, as before. +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 64); + __type(key, __u32); + __type(value, struct vlan_egress_value); +} vlan_egress SEC(".maps"); + // The node's XDP dispatcher (internal/plumbing/ebpf/xdpdispatch). edge_lb and // edge_return run from its gateway slots, and a packet either does not claim // goes on to the later slots, in practice the egress translation shard, which @@ -813,6 +839,27 @@ static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 s return 0; } +// push_vlan_tag inserts one 802.1Q header carrying vid between the Ethernet +// addresses and the EtherType, which then describes the payload as before. +static EDGE_ALWAYS_INLINE int push_vlan_tag(struct xdp_md *ctx, __u16 vid) +{ + if (bpf_xdp_adjust_head(ctx, -EDGE_VLAN_HLEN) != 0) + return -1; + void *data = (void *) (long) ctx->data; + void *data_end = (void *) (long) ctx->data_end; + if (data + sizeof(struct edge_ethhdr) + EDGE_VLAN_HLEN > data_end) + return -1; + // Move both MAC addresses forward over the new four bytes; the old + // EtherType stays where it is and becomes the tag's encapsulated type. + __builtin_memmove(data, data + EDGE_VLAN_HLEN, 12); + __u8 *tag = (__u8 *) data + 12; + tag[0] = EDGE_ETH_P_8021Q >> 8; + tag[1] = EDGE_ETH_P_8021Q & 0xff; + tag[2] = (vid >> 8) & 0x0f; + tag[3] = vid & 0xff; + return 0; +} + // leave_via turns a resolved egress interface into this packet's verdict, for a // packet whose Ethernet header resolve_fib_and_write_eth has already written. // @@ -825,6 +872,15 @@ static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 s // counts that as a failure. XDP_TX is kept for the case where it is actually // correct, the route egressing the ingress interface, where it is also the // cheaper verdict. +// +// An egress interface in vlan_egress is a tagged side's VLAN netdevice: the +// packet leaves through its lower device carrying exactly that side's tag, +// pushed here (push_vlan_tag). The frame has no tag of its own at this point: +// every hook sees untagged data, a tagged side's hook running on the VLAN +// netdevice after the kernel removed the tag. Where the route egresses the +// ingress interface itself, XDP_TX needs no tag push: only a generic hook on +// a VLAN netdevice can see that, and its transmit goes through the VLAN +// netdevice, which inserts the tag. static EDGE_ALWAYS_INLINE int leave_via(struct xdp_md *ctx, __u32 egress_ifindex, struct vip_stats_value *stats) { @@ -835,6 +891,18 @@ static EDGE_ALWAYS_INLINE int leave_via(struct xdp_md *ctx, __u32 egress_ifindex if (egress_ifindex == ctx->ingress_ifindex) return XDP_TX; + struct vlan_egress_value *vlan = bpf_map_lookup_elem(&vlan_egress, &egress_ifindex); + if (vlan) { + __u32 lower = vlan->lower_ifindex; + if (push_vlan_tag(ctx, vlan->vid) != 0) { + count_claimed_drop(DROP_REASON_ADJUST_HEAD_FAILED, stats); + return XDP_DROP; + } + if (lower == ctx->ingress_ifindex) + return XDP_TX; + egress_ifindex = lower; + } + if (bpf_redirect(egress_ifindex, 0) != XDP_REDIRECT) { count_claimed_drop(DROP_REASON_REDIRECT_FAILED, stats); return XDP_DROP; diff --git a/internal/plumbing/ebpf/natprog/doc.go b/internal/plumbing/ebpf/natprog/doc.go index 7992b85c9..4ac6fc4a3 100644 --- a/internal/plumbing/ebpf/natprog/doc.go +++ b/internal/plumbing/ebpf/natprog/doc.go @@ -86,4 +86,4 @@ const ( // within their packed structs, so they are genuinely 2-byte aligned despite the // packed attribute. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config -type nat_traffic_counter Nat nat.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -Wno-address-of-packed-member -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type conn_key -type conn_value -type shard_config -type nat_traffic_counter -type vlan_egress_value Nat nat.c diff --git a/internal/plumbing/ebpf/natprog/nat.c b/internal/plumbing/ebpf/natprog/nat.c index 1796b7032..a5e32a3d7 100644 --- a/internal/plumbing/ebpf/natprog/nat.c +++ b/internal/plumbing/ebpf/natprog/nat.c @@ -185,6 +185,8 @@ static long (*bpf_xdp_adjust_tail)(void *ctx, int delta) = (void *) BPF_FUNC_xdp #define NAT_AF_INET 2 #define NAT_AF_INET6 10 #define NAT_ETH_P_IPV6 0x86DD +#define NAT_ETH_P_8021Q 0x8100 +#define NAT_VLAN_HLEN 4 #define NAT_ETH_P_IP 0x0800 #define NAT_IPPROTO_TCP 6 #define NAT_IPPROTO_UDP 17 @@ -604,6 +606,30 @@ struct { __type(value, __u64); } neigh_fallbacks SEC(".maps"); +// struct vlan_egress_value is vlan_egress's value: the device a VLAN +// netdevice sits on and its 802.1Q VLAN ID, host order. +struct vlan_egress_value { + __u32 lower_ifindex; + __u16 vid; + __u16 pad; +}; + +// vlan_egress maps the VLAN netdevice of each tagged uplink this shard uses to +// its lower device and VLAN ID. The control plane fills it from netlink +// (internal/plumbing/ebpf/vlanegress); nothing here writes it. +// +// bpf_fib_lookup names the VLAN netdevice for a route through it, and a native +// XDP redirect to a VLAN netdevice drops every frame, since a VLAN netdevice +// has no ndo_xdp_xmit. leave_via therefore pushes the tag itself and leaves +// through the lower device. A VLAN netdevice missing here is redirected to as +// the FIB named it, as before. +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 64); + __type(key, __u32); + __type(value, struct vlan_egress_value); +} vlan_egress SEC(".maps"); + // Translated traffic, by address family, direction and how the packet left. // The slot is family * 4 + direction * 2 + action, mirrored in Go by // natprog.TrafficSlot. @@ -1182,6 +1208,27 @@ static NAT_ALWAYS_INLINE void count_fib_drop(long fib_rc) count_drop(DROP_REASON_NAT_FIB_LOOKUP_FAILED); } +// push_vlan_tag inserts one 802.1Q header carrying vid between the Ethernet +// addresses and the EtherType, which then describes the payload as before. +static NAT_ALWAYS_INLINE int push_vlan_tag(struct xdp_md *ctx, __u16 vid) +{ + if (bpf_xdp_adjust_head(ctx, -NAT_VLAN_HLEN) != 0) + return -1; + void *data = (void *) (long) ctx->data; + void *data_end = (void *) (long) ctx->data_end; + if (data + sizeof(struct nat_ethhdr) + NAT_VLAN_HLEN > data_end) + return -1; + // Move both MAC addresses forward over the new four bytes; the old + // EtherType stays where it is and becomes the tag's encapsulated type. + __builtin_memmove(data, data + NAT_VLAN_HLEN, 12); + __u8 *tag = (__u8 *) data + 12; + tag[0] = NAT_ETH_P_8021Q >> 8; + tag[1] = NAT_ETH_P_8021Q & 0xff; + tag[2] = (vid >> 8) & 0x0f; + tag[3] = vid & 0xff; + return 0; +} + // leave_via turns a resolved egress interface into this packet's verdict, for a // packet whose Ethernet header one of the two resolvers above has already // written. Every leg of this program ends here: the forward legs so the kernel @@ -1196,6 +1243,15 @@ static NAT_ALWAYS_INLINE void count_fib_drop(long fib_rc) // nodes it puts a frame carrying the egress link's source and next-hop MACs // onto the wrong wire, where the neighbour discards it -- and the FIB lookup // having succeeded, nothing counts that as a failure. +// +// An egress interface in vlan_egress is a tagged uplink's VLAN netdevice: the +// packet leaves through its lower device carrying exactly that uplink's tag, +// pushed here (push_vlan_tag). The frame has no tag of its own at this point: +// every hook sees untagged data, a tagged uplink's hook running on the VLAN +// netdevice after the kernel removed the tag. Where the route egresses the +// ingress interface itself, XDP_TX needs no tag push: only a generic hook on +// a VLAN netdevice can see that, and its transmit goes through the VLAN +// netdevice, which inserts the tag. static NAT_ALWAYS_INLINE int leave_via(struct xdp_md *ctx, __u32 egress_ifindex) { if (egress_ifindex == 0) { @@ -1205,6 +1261,18 @@ static NAT_ALWAYS_INLINE int leave_via(struct xdp_md *ctx, __u32 egress_ifindex) if (egress_ifindex == ctx->ingress_ifindex) return XDP_TX; + struct vlan_egress_value *vlan = bpf_map_lookup_elem(&vlan_egress, &egress_ifindex); + if (vlan) { + __u32 lower = vlan->lower_ifindex; + if (push_vlan_tag(ctx, vlan->vid) != 0) { + count_drop(DROP_REASON_NAT_ADJUST_HEAD_FAILED); + return XDP_DROP; + } + if (lower == ctx->ingress_ifindex) + return XDP_TX; + egress_ifindex = lower; + } + if (bpf_redirect(egress_ifindex, 0) != XDP_REDIRECT) { count_drop(DROP_REASON_NAT_REDIRECT_FAILED); return XDP_DROP; diff --git a/internal/plumbing/ebpf/natprog/vlan_test.go b/internal/plumbing/ebpf/natprog/vlan_test.go new file mode 100644 index 000000000..a9bef6765 --- /dev/null +++ b/internal/plumbing/ebpf/natprog/vlan_test.go @@ -0,0 +1,309 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package natprog + +import ( + "encoding/binary" + "fmt" + "net" + "net/netip" + "os" + "testing" + + "github.com/cilium/ebpf" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" +) + +// xdpMD is struct xdp_md, the context a program test run takes. +type xdpMD struct { + Data, DataEnd, DataMeta, IngressIfindex, RxQueueIndex, EgressIfindex uint32 +} + +// The VLAN tests below give the shard one parent, up0, carrying a tagged +// public uplink (VLAN vlanPub) and a tagged fabric uplink (VLAN vlanFab), as +// two VLANs on one parent. All addresses are documentation or unique local +// ranges. +const ( + vlanPub = 101 + vlanFab = 202 +) + +var ( + vlanShardSID = netip.MustParseAddr("fc00:1:2::1") + vlanShardPub = netip.MustParseAddr("2001:db8:9999::1") + vlanShardPub4 = netip.MustParseAddr("192.0.2.10") + vlanTenant = netip.MustParseAddr("fc00:3:4::a1b2") + vlanBackend = netip.MustParseAddr("fd20:60::5") + vlanDest6 = netip.MustParseAddr("2001:db8:9998::1") + vlanPeer4 = netip.MustParseAddr("1.1.1.1") + vlanPubHop = netip.MustParseAddr("fd00:a::2") + vlanPubHop4 = netip.MustParseAddr("192.0.2.2") + vlanFabHop = netip.MustParseAddr("fd00:b::2") + vlanPubMAC = net.HardwareAddr{0x02, 0, 0, 0, 0, 0x22} + vlanFabMAC = net.HardwareAddr{0x02, 0, 0, 0, 0, 0x33} +) + +// vlanLink is one test interface's index and MAC address. +type vlanLink struct { + index int + mac net.HardwareAddr +} + +// vlanUplinks builds the parent, both VLANs, and a separate untagged +// interface in0, with routes and warm neighbors toward each side, in the +// current namespace. +func vlanUplinks() (map[string]vlanLink, error) { + for _, key := range []string{"ipv6/conf/all/forwarding", "ipv6/conf/default/forwarding", + "ipv4/conf/all/forwarding", "ipv4/conf/default/forwarding"} { + if err := os.WriteFile("/proc/sys/net/"+key, []byte("1"), 0o644); err != nil { + return nil, err + } + } + for _, pair := range [][2]string{{"up0", "up1"}, {"in0", "in1"}} { + veth := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: pair[0]}, PeerName: pair[1]} + if err := netlink.LinkAdd(veth); err != nil { + return nil, err + } + for _, name := range pair { + l, _ := netlink.LinkByName(name) + if err := netlink.LinkSetUp(l); err != nil { + return nil, err + } + } + } + up0, err := netlink.LinkByName("up0") + if err != nil { + return nil, err + } + sides := []struct { + vid int + local, hop netip.Addr + mac net.HardwareAddr + dst netip.Addr + }{ + {vlanPub, netip.MustParseAddr("fd00:a::1"), vlanPubHop, vlanPubMAC, vlanDest6}, + {vlanFab, netip.MustParseAddr("fd00:b::1"), vlanFabHop, vlanFabMAC, vlanTenant}, + } + for _, s := range sides { + name := fmt.Sprintf("up0.%d", s.vid) + vlan := &netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Name: name, ParentIndex: up0.Attrs().Index}, + VlanId: s.vid, VlanProtocol: netlink.VLAN_PROTOCOL_8021Q} + if err := netlink.LinkAdd(vlan); err != nil { + return nil, err + } + if err := netlink.LinkSetUp(vlan); err != nil { + return nil, err + } + if err := vlanAddrRouteNeigh(vlan, s.local, 64, s.hop, s.mac, s.dst); err != nil { + return nil, err + } + } + pub, err := netlink.LinkByName(fmt.Sprintf("up0.%d", vlanPub)) + if err != nil { + return nil, err + } + if err := vlanAddrRouteNeigh(pub, netip.MustParseAddr("192.0.2.1"), 24, vlanPubHop4, vlanPubMAC, + vlanPeer4); err != nil { + return nil, err + } + + out := map[string]vlanLink{} + for _, name := range []string{"up0", "in0", fmt.Sprintf("up0.%d", vlanPub), fmt.Sprintf("up0.%d", vlanFab)} { + l, err := netlink.LinkByName(name) + if err != nil { + return nil, err + } + out[name] = vlanLink{index: l.Attrs().Index, mac: l.Attrs().HardwareAddr} + } + return out, nil +} + +func vlanAddrRouteNeigh(l netlink.Link, local netip.Addr, bits int, hop netip.Addr, mac net.HardwareAddr, + dst netip.Addr, +) error { + if err := netlink.AddrAdd(l, &netlink.Addr{IPNet: &net.IPNet{IP: local.AsSlice(), + Mask: net.CIDRMask(bits, local.BitLen())}, Flags: unix.IFA_F_NODAD}); err != nil { + return err + } + family := netlink.FAMILY_V6 + if hop.Is4() { + family = netlink.FAMILY_V4 + } + if err := netlink.NeighSet(&netlink.Neigh{LinkIndex: l.Attrs().Index, Family: family, + State: netlink.NUD_PERMANENT, IP: hop.AsSlice(), HardwareAddr: mac}); err != nil { + return err + } + return netlink.RouteAdd(&netlink.Route{LinkIndex: l.Attrs().Index, Gw: hop.AsSlice(), + Dst: &net.IPNet{IP: dst.AsSlice(), Mask: net.CIDRMask(dst.BitLen(), dst.BitLen())}}) +} + +// vlanRun runs nat_ingress on pkt as if it arrived on ingress. +func vlanRun(objs *NatObjects, pkt []byte, ingress int) (uint32, []byte, error) { + out := make([]byte, len(pkt)+128) + ctx := xdpMD{DataEnd: uint32(len(pkt)), IngressIfindex: uint32(ingress)} + opts := &ebpf.RunOptions{Data: pkt, DataOut: out, Context: ctx} + ret, err := objs.NatIngress.Run(opts) + return ret, opts.DataOut, err +} + +// vlanFrame checks out carries exactly one 802.1Q tag with vid, from srcMAC +// to dstMAC, in front of etherType, and returns what follows the tag. +func vlanFrame(out []byte, vid uint16, srcMAC, dstMAC net.HardwareAddr, etherType uint16) ([]byte, error) { + if len(out) < 18 { + return nil, fmt.Errorf("frame is %d bytes", len(out)) + } + if got := binary.BigEndian.Uint16(out[12:14]); got != 0x8100 { + return nil, fmt.Errorf("EtherType %#04x, want 0x8100", got) + } + if got := binary.BigEndian.Uint16(out[14:16]) & 0x0fff; got != vid { + return nil, fmt.Errorf("VLAN ID %d, want %d", got, vid) + } + if got := binary.BigEndian.Uint16(out[16:18]); got != etherType { + return nil, fmt.Errorf("EtherType inside the tag %#04x, want %#04x: exactly one tag", got, etherType) + } + if got := net.HardwareAddr(out[0:6]); got.String() != dstMAC.String() { + return nil, fmt.Errorf("destination MAC %s, want %s", got, dstMAC) + } + if got := net.HardwareAddr(out[6:12]); got.String() != srcMAC.String() { + return nil, fmt.Errorf("source MAC %s, want %s", got, srcMAC) + } + return out[18:], nil +} + +// vlanTenantPacket is a tenant's encapsulated UDP packet to dst. +func vlanTenantPacket(t *testing.T, dst netip.Addr, payload string) []byte { + return buildEncappedUDPPacket(t, sidWithArgument(vlanShardSID, 0x123), vlanTenant, vlanBackend, dst, + []byte(payload)) +} + +// TestNatIngress_TaggedUplinksPushTheirTag runs NAT66 and NAT64, outbound and +// return, between a tagged fabric uplink and a tagged public uplink on one +// parent. Each translated packet leaves through the parent carrying exactly +// the egress side's tag: XDP_REDIRECT when the hook ran on the other VLAN +// netdevice, where a tagged uplink's hook runs, and XDP_TX when it ran on the +// parent itself. A native redirect to the VLAN netdevice the FIB names would +// put nothing on the wire. +func TestNatIngress_TaggedUplinksPushTheirTag(t *testing.T) { + requireRoot(t) + netns, err := ns.TempNetNS() + if err != nil { + t.Fatalf("create namespace: %v", err) + } + t.Cleanup(func() { _ = netns.Close() }) + + // Not subtests: a test run resolves the ingress interface in the calling + // thread's namespace, and a subtest runs on another thread. + err = netns.Do(func(ns.NetNS) error { + links, err := vlanUplinks() + if err != nil { + return err + } + up0 := links["up0"] + pub, fab := links[fmt.Sprintf("up0.%d", vlanPub)], links[fmt.Sprintf("up0.%d", vlanFab)] + + objs := loadObjects(t) + populateProgArray(t, objs) + if err := objs.ShardConfigTable.Put(uint32(0), + nat64ShardConfig(vlanShardSID, vlanShardPub, vlanShardPub4)); err != nil { + return err + } + for vid, l := range map[uint16]vlanLink{vlanPub: pub, vlanFab: fab} { + if err := objs.VlanEgress.Put(uint32(l.index), + NatVlanEgressValue{LowerIfindex: uint32(up0.index), Vid: vid}); err != nil { + return err + } + } + vlanNAT66Outbound(t, objs, links) + return vlanReturns(t, objs, pub, fab) + }) + if err != nil { + t.Fatal(err) + } +} + +func vlanNAT66Outbound(t *testing.T, objs *NatObjects, links map[string]vlanLink) { + pub, fab := links[fmt.Sprintf("up0.%d", vlanPub)], links[fmt.Sprintf("up0.%d", vlanFab)] + for _, tt := range []struct { + name string + ingress int + want uint32 + }{ + {"from the fabric VLAN", fab.index, xdpRedirect}, + {"from another interface", links["in0"].index, xdpRedirect}, + {"from the parent", links["up0"].index, xdpTx}, + } { + ret, out, err := vlanRun(objs, vlanTenantPacket(t, vlanDest6, "nat66 outbound"), tt.ingress) + if err != nil || ret != tt.want { + t.Errorf("NAT66 outbound %s: verdict %d, err %v; want %d", tt.name, ret, err, tt.want) + continue + } + ip6, err := vlanFrame(out, vlanPub, pub.mac, vlanPubMAC, 0x86DD) + if err != nil { + t.Errorf("NAT66 outbound %s: %v", tt.name, err) + continue + } + if got := netip.AddrFrom16([16]byte(ip6[8:24])); got != vlanShardPub { + t.Errorf("NAT66 outbound %s: source %s, want %s", tt.name, got, vlanShardPub) + } + } +} + +// vlanReturns runs NAT66 return, NAT64 outbound and NAT64 return. A reply +// arrives on the public VLAN netdevice and leaves re-encapsulated toward the +// tenant through the fabric VLAN. +func vlanReturns(t *testing.T, objs *NatObjects, pub, fab vlanLink) error { + _, out, err := vlanRun(objs, vlanTenantPacket(t, vlanDest6, "nat66 port"), fab.index) + if err != nil { + return err + } + port := binary.BigEndian.Uint16(out[18+ip6Len : 18+ip6Len+2]) + ret, out, err := vlanRun(objs, buildUDPPacket(t, vlanShardPub, vlanDest6, encappedDstPort, port, + []byte("nat66 return")), pub.index) + if err != nil || ret != xdpRedirect { + return fmt.Errorf("NAT66 return: verdict %d, err %w; want XDP_REDIRECT", ret, err) + } + if err := vlanToTenant(out, fab); err != nil { + return fmt.Errorf("NAT66 return: %w", err) + } + + ret, out, err = vlanRun(objs, vlanTenantPacket(t, synthesize(nat64Prefix, vlanPeer4), "nat64 outbound"), + fab.index) + if err != nil || ret != xdpRedirect { + return fmt.Errorf("NAT64 outbound: verdict %d, err %w; want XDP_REDIRECT", ret, err) + } + ip4, err := vlanFrame(out, vlanPub, pub.mac, vlanPubMAC, 0x0800) + if err != nil { + return fmt.Errorf("NAT64 outbound: %w", err) + } + if got := netip.AddrFrom4([4]byte(ip4[12:16])); got != vlanShardPub4 { + return fmt.Errorf("NAT64 outbound: source %s, want %s", got, vlanShardPub4) + } + port = binary.BigEndian.Uint16(ip4[ip4Len : ip4Len+2]) + + ret, out, err = vlanRun(objs, buildIPv4UDPPacket(t, vlanShardPub4, vlanPeer4, encappedDstPort, port, + []byte("nat64 return")), pub.index) + if err != nil || ret != xdpRedirect { + return fmt.Errorf("NAT64 return: verdict %d, err %w; want XDP_REDIRECT", ret, err) + } + if err := vlanToTenant(out, fab); err != nil { + return fmt.Errorf("NAT64 return: %w", err) + } + return nil +} + +// vlanToTenant checks out leaves through the fabric VLAN, encapsulated to the +// tenant. +func vlanToTenant(out []byte, fab vlanLink) error { + ip6, err := vlanFrame(out, vlanFab, fab.mac, vlanFabMAC, 0x86DD) + if err != nil { + return err + } + if got := netip.AddrFrom16([16]byte(ip6[24:40])); got != vlanTenant { + return fmt.Errorf("outer destination %s, want the tenant %s", got, vlanTenant) + } + return nil +} diff --git a/internal/plumbing/ebpf/vlanegress/vlanegress.go b/internal/plumbing/ebpf/vlanegress/vlanegress.go new file mode 100644 index 000000000..148b77fa8 --- /dev/null +++ b/internal/plumbing/ebpf/vlanegress/vlanegress.go @@ -0,0 +1,168 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package vlanegress fills the vlan_egress map that the edge gateway +// (edgedsr.c) and the egress translation shard (nat.c) read when a route +// leaves through a tagged transport side's VLAN netdevice. +// +// A native XDP redirect to a VLAN netdevice drops every frame, since a VLAN +// netdevice has no ndo_xdp_xmit. For each configured tagged side the map holds +// the VLAN netdevice's lower device and VLAN ID, and the program pushes the tag +// and redirects to the lower device instead. Rows are derived from netlink +// only, never from a separate setting, and only for the logical interfaces the +// component is configured with: see docs/designs/vlan-transport/contract.md. +package vlanegress + +import ( + "errors" + "fmt" + + "github.com/cilium/ebpf" + "github.com/vishvananda/netlink" +) + +// Lowers resolves a configured tagged side's VLAN netdevice to its lower +// device and VLAN ID. ok is false for any ifindex that is not a configured +// tagged side. The shared transport resolution's Set implements it; Netlink is +// a minimal implementation over netlink for the named logical interfaces. +type Lowers interface { + VLANLower(ifindex int) (lower int, vid uint16, ok bool) +} + +// Value is a vlan_egress row: struct vlan_egress_value in edgedsr.c and nat.c. +type Value struct { + LowerIfindex uint32 + VID uint16 + Pad uint16 +} + +// Table is the part of an *ebpf.Map Sync uses. +type Table interface { + Put(key, value any) error + Delete(key any) error + Iterate() *ebpf.MapIterator +} + +// Sync makes m hold exactly one row for every ifindex in ifindexes that lowers +// reports as a tagged side, and no other row. A row whose side became +// untagged, or whose VLAN netdevice is gone, is deleted, so the program falls +// back to the FIB's own egress interface. +func Sync(m Table, lowers Lowers, ifindexes []int) error { + want := make(map[uint32]Value, len(ifindexes)) + for _, ifindex := range ifindexes { + lower, vid, ok := lowers.VLANLower(ifindex) + if !ok { + continue + } + want[uint32(ifindex)] = Value{LowerIfindex: uint32(lower), VID: vid} + } + + var ( + stale []uint32 + key uint32 + val Value + errs []error + ) + iter := m.Iterate() + for iter.Next(&key, &val) { + if w, ok := want[key]; !ok || w != val { + stale = append(stale, key) + } + } + if err := iter.Err(); err != nil { + return fmt.Errorf("vlanegress: read vlan_egress: %w", err) + } + for _, k := range stale { + if _, ok := want[k]; ok { + continue // overwritten below + } + if err := m.Delete(k); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + errs = append(errs, fmt.Errorf("vlanegress: delete row for ifindex %d: %w", k, err)) + } + } + for k, v := range want { + if err := m.Put(k, v); err != nil { + errs = append(errs, fmt.Errorf("vlanegress: write row for ifindex %d: %w", k, err)) + } + } + return errors.Join(errs...) +} + +// linkByNameFn and linkByIndexFn are override points so tests can substitute a +// fake netlink view. +var ( + linkByNameFn = netlink.LinkByName + linkByIndexFn = netlink.LinkByIndex +) + +// Netlink is Lowers over netlink for a fixed set of logical interfaces. +type Netlink struct { + rows map[int]Value +} + +// VLANLower implements Lowers. +func (n *Netlink) VLANLower(ifindex int) (int, uint16, bool) { + v, ok := n.rows[ifindex] + return int(v.LowerIfindex), v.VID, ok +} + +// FromNetlink resolves each of names, the logical interfaces of a component's +// configured sides. It returns their ifindexes, in order, and a Lowers holding +// every one that is an 802.1Q VLAN netdevice with an ID from 1 to 4094 on a +// parent that exists and is not itself a VLAN: a usable tagged side. An empty +// name is skipped. +// +// A name that does not resolve, or a VLAN netdevice that is not a usable +// tagged side, is left out and reported in the returned error; the caller +// decides whether that is fatal. Without a row, the datapath redirects to the +// VLAN netdevice as the FIB names it, which transmits only in generic mode. +func FromNetlink(names []string) (*Netlink, []int, error) { + n := &Netlink{rows: map[int]Value{}} + var ( + ifindexes []int + errs []error + ) + for _, name := range names { + if name == "" { + continue + } + l, err := linkByNameFn(name) + if err != nil { + errs = append(errs, fmt.Errorf("vlanegress: find link %q: %w", name, err)) + continue + } + ifindex := l.Attrs().Index + ifindexes = append(ifindexes, ifindex) + vlan, ok := l.(*netlink.Vlan) + if !ok { + continue + } + if err := usable(vlan); err != nil { + errs = append(errs, err) + continue + } + n.rows[ifindex] = Value{LowerIfindex: uint32(vlan.ParentIndex), VID: uint16(vlan.VlanId)} + } + return n, ifindexes, errors.Join(errs...) +} + +// usable reports why vlan cannot carry a tagged side, or nil. +func usable(vlan *netlink.Vlan) error { + name := vlan.Attrs().Name + if vlan.VlanProtocol != netlink.VLAN_PROTOCOL_UNKNOWN && vlan.VlanProtocol != netlink.VLAN_PROTOCOL_8021Q { + return fmt.Errorf("vlanegress: %s uses VLAN protocol %s; only 802.1Q is a supported transport tag", + name, vlan.VlanProtocol) + } + if vlan.VlanId < 1 || vlan.VlanId > 4094 { + return fmt.Errorf("vlanegress: %s has VLAN ID %d, outside 1 to 4094", name, vlan.VlanId) + } + parent, err := linkByIndexFn(vlan.ParentIndex) + if err != nil { + return fmt.Errorf("vlanegress: find parent %d of %s: %w", vlan.ParentIndex, name, err) + } + if _, stacked := parent.(*netlink.Vlan); stacked { + return fmt.Errorf("vlanegress: %s sits on VLAN %s; stacked tags are not supported", name, parent.Attrs().Name) + } + return nil +} diff --git a/internal/plumbing/ebpf/vlanegress/vlanegress_test.go b/internal/plumbing/ebpf/vlanegress/vlanegress_test.go new file mode 100644 index 000000000..c00c0b35e --- /dev/null +++ b/internal/plumbing/ebpf/vlanegress/vlanegress_test.go @@ -0,0 +1,99 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package vlanegress + +import ( + "fmt" + "strings" + "testing" + + "github.com/vishvananda/netlink" +) + +func fakeLinks(t *testing.T, links ...netlink.Link) { + t.Helper() + byName := map[string]netlink.Link{} + byIndex := map[int]netlink.Link{} + for _, l := range links { + byName[l.Attrs().Name] = l + byIndex[l.Attrs().Index] = l + } + origName, origIndex := linkByNameFn, linkByIndexFn + t.Cleanup(func() { linkByNameFn, linkByIndexFn = origName, origIndex }) + linkByNameFn = func(name string) (netlink.Link, error) { + if l, ok := byName[name]; ok { + return l, nil + } + return nil, fmt.Errorf("link %s not found", name) + } + linkByIndexFn = func(index int) (netlink.Link, error) { + if l, ok := byIndex[index]; ok { + return l, nil + } + return nil, fmt.Errorf("link %d not found", index) + } +} + +func vlan(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, + } +} + +func TestFromNetlink(t *testing.T) { + bond := &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: "bond0", Index: 2}} + nic := &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: "eth1", Index: 3}} + pub := vlan("bond0.101", 10, 2, 101, netlink.VLAN_PROTOCOL_8021Q) + fab := vlan("bond0.202", 11, 2, 202, netlink.VLAN_PROTOCOL_8021Q) + qinq := vlan("bond0.300", 12, 2, 300, netlink.VLAN_PROTOCOL_8021AD) + stacked := vlan("bond0.101.7", 13, 10, 7, netlink.VLAN_PROTOCOL_8021Q) + zero := vlan("eth1.0", 14, 3, 0, netlink.VLAN_PROTOCOL_8021Q) + fakeLinks(t, bond, nic, pub, fab, qinq, stacked, zero) + + n, ifindexes, err := FromNetlink([]string{"bond0.101", "", "bond0.202", "eth1"}) + if err != nil { + t.Fatalf("FromNetlink: %v", err) + } + if want := []int{10, 11, 3}; fmt.Sprint(ifindexes) != fmt.Sprint(want) { + t.Fatalf("ifindexes = %v, want %v", ifindexes, want) + } + for _, tt := range []struct { + ifindex, lower int + vid uint16 + ok bool + }{ + {10, 2, 101, true}, + {11, 2, 202, true}, + {3, 0, 0, false}, + {99, 0, 0, false}, + } { + lower, vid, ok := n.VLANLower(tt.ifindex) + if lower != tt.lower || vid != tt.vid || ok != tt.ok { + t.Errorf("VLANLower(%d) = %d, %d, %v; want %d, %d, %v", tt.ifindex, lower, vid, ok, + tt.lower, tt.vid, tt.ok) + } + } + + for _, tt := range []struct { + name, want string + }{ + {"bond0.300", "only 802.1Q"}, + {"bond0.101.7", "stacked tags"}, + {"eth1.0", "outside 1 to 4094"}, + {"missing0", "find link"}, + } { + t.Run(tt.name, func(t *testing.T) { + n, _, err := FromNetlink([]string{tt.name}) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("FromNetlink(%s) error = %v, want one containing %q", tt.name, err, tt.want) + } + if len(n.rows) != 0 { + t.Fatalf("FromNetlink(%s) kept rows %v", tt.name, n.rows) + } + }) + } +} diff --git a/internal/plumbing/ebpf/xdpattach/attach.go b/internal/plumbing/ebpf/xdpattach/attach.go index ae96b06a8..c462fa010 100644 --- a/internal/plumbing/ebpf/xdpattach/attach.go +++ b/internal/plumbing/ebpf/xdpattach/attach.go @@ -95,6 +95,7 @@ func attachOne(program *ebpf.Program, ifaceName string, mode xdpmode.Mode) (link if err != nil { return nil, fmt.Errorf("xdpattach: find link %q: %w", ifaceName, err) } + mode = xdpmode.ForLink(mode, iface) xdpLink, err := link.AttachXDP(link.XDPOptions{ Program: program, @@ -108,23 +109,32 @@ func attachOne(program *ebpf.Program, ifaceName string, mode xdpmode.Mode) (link return xdpLink, nil } -// checkModeSupport is the pre-attach support check for mode. Only native mode -// needs the driver's support; generic mode runs on any interface. +// checkModeSupport is the pre-attach support check for mode, the host's mode. +// Only native mode needs the driver's support; generic mode runs on any +// interface. A VLAN netdevice always attaches in generic mode +// (xdpmode.ForLink), so it is never checked. func checkModeSupport(ifaceNames []string, mode xdpmode.Mode) error { if mode != xdpmode.Native { return nil } - return checkNativeXDPSupport(ifaceNames) + native := make([]string, 0, len(ifaceNames)) + for _, name := range ifaceNames { + if l, err := linkByNameFn(name); err == nil && xdpmode.IsVLAN(l) { + continue + } + native = append(native, name) + } + return checkNativeXDPSupport(native) } // attachedInMode reports whether ifaceName's XDP hook holds a program attached -// in mode, read back from the kernel rather than assumed from how it was -// attached. +// in the mode xdpmode.ForLink gives it on a host in mode, read back from the +// kernel rather than assumed from how it was attached. func attachedInMode(ifaceName string, mode xdpmode.Mode) (bool, error) { l, err := linkByNameFn(ifaceName) if err != nil { return false, fmt.Errorf("xdpattach: find link %q: %w", ifaceName, err) } xdp := l.Attrs().Xdp - return xdp != nil && xdp.Attached && mode.Matches(xdp.AttachMode), nil + return xdp != nil && xdp.Attached && xdpmode.ForLink(mode, l).Matches(xdp.AttachMode), nil } diff --git a/internal/plumbing/ebpf/xdpattach/gate_test.go b/internal/plumbing/ebpf/xdpattach/gate_test.go index cbf8e80b3..44ed2b585 100644 --- a/internal/plumbing/ebpf/xdpattach/gate_test.go +++ b/internal/plumbing/ebpf/xdpattach/gate_test.go @@ -6,6 +6,7 @@ package xdpattach import ( "errors" + "fmt" "slices" "strings" "testing" @@ -257,3 +258,37 @@ func TestAttachSequentially_AttachesNothingWhenSupportIsMissing(t *testing.T) { t.Errorf("attached %v, want nothing -- the check runs before any link is touched", attached) } } + +// vlanUplink is a VLAN netdevice for the support check below. +const vlanUplink = "bond0.101" + +// A VLAN netdevice always attaches in generic mode, so a native host's support +// check skips it, while the other interfaces are still checked. +func TestCheckModeSupport_SkipsVLANNetdevices(t *testing.T) { + restoreGateVars(t) + linkByNameFn = func(name string) (netlink.Link, error) { + if name == vlanUplink { + return &netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Name: name}, VlanId: 101}, nil + } + return &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: name}}, nil + } + var checked []string + edgepreflight.InterfaceXDPFn = func(name string) (bool, error) { + checked = append(checked, name) + return name != testUplink1, nil + } + + if err := checkModeSupport([]string{vlanUplink, "eth0"}, xdpmode.Native); err != nil { + t.Fatalf("checkModeSupport: %v", err) + } + if fmt.Sprint(checked) != "[eth0]" { + t.Errorf("checked %v, want only eth0", checked) + } + if err := checkModeSupport([]string{vlanUplink, testUplink1}, xdpmode.Native); err == nil { + t.Error("checkModeSupport passed eth1, which lacks native XDP") + } + checked = nil + if err := checkModeSupport([]string{vlanUplink, testUplink1}, xdpmode.Generic); err != nil || checked != nil { + t.Errorf("generic host: err %v, checked %v; want no check", err, checked) + } +} diff --git a/internal/plumbing/ebpf/xdpdispatch/dispatcher.go b/internal/plumbing/ebpf/xdpdispatch/dispatcher.go index 9a198c222..30b6b0452 100644 --- a/internal/plumbing/ebpf/xdpdispatch/dispatcher.go +++ b/internal/plumbing/ebpf/xdpdispatch/dispatcher.go @@ -417,6 +417,18 @@ func (d *Dispatcher) RootID() (ebpf.ProgramID, error) { // Mode returns the XDP attach mode the dispatcher attaches and checks in. func (d *Dispatcher) Mode() xdpmode.Mode { return d.mode } +// ModeFor returns the mode the dispatcher attaches to ifindex and checks it +// in: generic for a VLAN netdevice, the host's mode for every other interface +// (xdpmode.ForLink). An interface it cannot read gets the host's mode; the +// attach that follows reports the missing interface. +func (d *Dispatcher) ModeFor(ifindex int) xdpmode.Mode { + nl, err := linkByIndexFn(ifindex) + if err != nil { + return d.mode + } + return xdpmode.ForLink(d.mode, nl) +} + // attachedMode returns the mode ifindex's XDP hook holds a program in, read // from the kernel, and false when it holds none or holds it some other way. func attachedMode(ifindex int) (xdpmode.Mode, bool, error) { @@ -457,7 +469,7 @@ func (d *Dispatcher) Pinned(ifindex int) (bool, error) { } // Linked reports whether a live pinned dispatcher link holds ifindex in the -// dispatcher's mode, which is when EnsureLink would neither attach nor bounce +// mode ModeFor gives it, which is when EnsureLink would neither attach nor bounce // it. func (d *Dispatcher) Linked(ifindex int) (bool, error) { pinned, err := d.Pinned(ifindex) @@ -468,7 +480,7 @@ func (d *Dispatcher) Linked(ifindex int) (bool, error) { if err != nil { return false, err } - return ok && mode == d.mode, nil + return ok && mode == d.ModeFor(ifindex), nil } // Locked is the dispatch lock, held. Every call that changes shared state @@ -504,7 +516,7 @@ func (l *Locked) Unlock() { } // EnsureLink makes sure the pinned root is attached to ifindex through a -// pinned link, in the dispatcher's mode. bounced reports whether this call +// pinned link, in the mode ModeFor gives it. bounced reports whether this call // attached it, which on most drivers resets the interface; the caller then // waits for a bond member to rejoin. A link running an older root is moved to // the pinned one. A pinned link in the other mode is migrated (migrateLink), @@ -548,12 +560,12 @@ func (l *Locked) EnsureLink(ifindex int) (bounced bool, err error) { if err != nil { return false, err } - if ok && mode == d.mode { + if ok && mode == d.ModeFor(ifindex) { return false, nil } if !ok { return false, fmt.Errorf("xdpdispatch: cannot read the XDP mode ifindex %d's pinned link is "+ - "attached in, so it is not moved to %s mode", ifindex, d.mode) + "attached in, so it is not moved to %s mode", ifindex, d.ModeFor(ifindex)) } if err := d.migrationAllowed(ifindex); err != nil { return false, err @@ -578,7 +590,7 @@ func (l *Locked) EnsureLink(ifindex int) (bounced bool, err error) { ErrForeignProgram, nl.Attrs().Name, ifindex, xdp.ProgId) } - if err := attachPinned(root, ifindex, d.mode, path); err != nil { + if err := attachPinned(root, ifindex, xdpmode.ForLink(d.mode, nl), path); err != nil { return true, fmt.Errorf("xdpdispatch: %s: %w", nl.Attrs().Name, err) } return true, nil @@ -638,7 +650,7 @@ func (d *Dispatcher) recordMigration(ifindex int, err error) { } // migrateLink moves ifindex's pinned link from the mode it is attached in to -// the dispatcher's mode. A bpf_link keeps the mode it was created with, and +// the mode ModeFor gives it. A bpf_link keeps the mode it was created with, and // the kernel will not hold a native and a generic program on one interface at // once, so the link is detached and the root attached again: the interface // carries no program between the two steps, and the driver resets its rings @@ -652,18 +664,19 @@ func (d *Dispatcher) recordMigration(ifindex int, err error) { // reporting, so a later reconcile retries once migrationAllowed lets it. func (l *Locked) migrateLink(ifindex int, pinned link.Link, root *ebpf.Program, from xdpmode.Mode) error { d := l.d + to := d.ModeFor(ifindex) path := d.linkPath(ifindex) if err := pinned.Detach(); err != nil && !errors.Is(err, unix.ENOLINK) { - return fmt.Errorf("xdpdispatch: detach ifindex %d to move it to %s mode: %w", ifindex, d.mode, err) + return fmt.Errorf("xdpdispatch: detach ifindex %d to move it to %s mode: %w", ifindex, to, err) } if err := pinned.Unpin(); err != nil { - return fmt.Errorf("xdpdispatch: unpin ifindex %d to move it to %s mode: %w", ifindex, d.mode, err) + return fmt.Errorf("xdpdispatch: unpin ifindex %d to move it to %s mode: %w", ifindex, to, err) } - err := attachPinned(root, ifindex, d.mode, path) + err := attachPinned(root, ifindex, to, path) if err == nil { return nil } - err = fmt.Errorf("xdpdispatch: move ifindex %d to %s mode: %w", ifindex, d.mode, err) + err = fmt.Errorf("xdpdispatch: move ifindex %d to %s mode: %w", ifindex, to, err) if restoreErr := attachPinned(root, ifindex, from, path); restoreErr != nil { return fmt.Errorf("%w; restoring %s mode also failed, so the interface has no dispatcher: %w", err, from, restoreErr) @@ -950,7 +963,7 @@ func (d *Dispatcher) Coverage(ifindex int, slot Slot, program *ebpf.Program) err if err != nil { return err } - if !ok || mode != d.mode { + if !ok || mode != d.ModeFor(ifindex) { return ErrModeMismatch } diff --git a/internal/plumbing/ebpf/xdpmode/iface.go b/internal/plumbing/ebpf/xdpmode/iface.go new file mode 100644 index 000000000..887f4d037 --- /dev/null +++ b/internal/plumbing/ebpf/xdpmode/iface.go @@ -0,0 +1,31 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpmode + +import "github.com/vishvananda/netlink" + +// ForLink returns the mode an XDP attachment to l uses on a host whose mode is +// host. +// +// A VLAN netdevice always uses generic mode. The kernel offers it no native +// XDP (it has no driver hook), and a tagged transport side's hooks run on its +// VLAN netdevice so that the kernel has already matched the frame's VLAN ID, +// whatever the parent's VLAN receive offload: see +// docs/designs/vlan-transport/contract.md. Every other interface uses host. +// +// The rule depends only on the interface, so every Galactic component on a +// host resolves the same mode for it, and the host-wide mode Claim records is +// unchanged. +func ForLink(host Mode, l netlink.Link) Mode { + if IsVLAN(l) { + return Generic + } + return host +} + +// IsVLAN reports whether l is a VLAN netdevice. +func IsVLAN(l netlink.Link) bool { + return l != nil && l.Type() == "vlan" +} diff --git a/internal/plumbing/ebpf/xdpmode/iface_test.go b/internal/plumbing/ebpf/xdpmode/iface_test.go new file mode 100644 index 000000000..553b95862 --- /dev/null +++ b/internal/plumbing/ebpf/xdpmode/iface_test.go @@ -0,0 +1,34 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpmode + +import ( + "testing" + + "github.com/vishvananda/netlink" +) + +func TestForLink(t *testing.T) { + vlan := &netlink.Vlan{LinkAttrs: netlink.LinkAttrs{Name: "bond0.101"}, VlanId: 101} + for _, tt := range []struct { + name string + host Mode + link netlink.Link + want Mode + }{ + {"VLAN on a native host", Native, vlan, Generic}, + {"VLAN on a generic host", Generic, vlan, Generic}, + {"device on a native host", Native, &netlink.Device{LinkAttrs: netlink.LinkAttrs{Name: "eth0"}}, Native}, + {"bond on a generic host", Generic, &netlink.Bond{LinkAttrs: netlink.LinkAttrs{Name: "bond0"}}, Generic}, + {"veth on a native host", Native, &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "v0"}}, Native}, + {"no link", Native, nil, Native}, + } { + t.Run(tt.name, func(t *testing.T) { + if got := ForLink(tt.host, tt.link); got != tt.want { + t.Fatalf("ForLink(%s, %v) = %s, want %s", tt.host, tt.link, got, tt.want) + } + }) + } +}