public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
* [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF
@ 2026-11-12 12:41 Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox v7 01/21] network-types: mac address: add an accessor for the bytes Hannes Laimer
                   ` (20 more replies)
  0 siblings, 21 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

This series adds a second DHCP backend, ebpf, next to dnsmasq. A zone
picks its backend. dnsmasq stays limited to simple zones, while ebpf
answers on the guest's own interface and works on every zone type. A
guest on a zone with the ebpf backend gets the address its NIC has in
the IPAM. There is no daemon per zone and no lease file. The answers
are held in the kernel and do not depend on the IPAM being reachable.

The responder is a BPF program on the ingress of each guest interface
of a zone with the ebpf backend. It answers a request from the record
of that interface, and the exchange never reaches the bridge. A
request whose client MAC is not the interface's own passes on
unanswered. So a guest cannot read another guest's record, and a
nested client does not get the outer guest's address.

An edit through /cluster/sdn/vnets/{vnet}/ips is proxied to the
guest's node and updates the backend there. The guest sees the change
at its next renewal, so the lease time bounds how long an old answer
survives. Subnets get a dhcp-lease-time property for both backends.
Without it dnsmasq hands out infinite leases and the responder ten
minutes. An apply attaches the responder to running guests, so a zone
switched to ebpf serves them without a restart.

Changes reach the kernel in the order they read their input. So no
change overwrites a newer one with older input. A hotplug moves the
interface while the new bridge is still a pending change in the guest
config. The responder drops the interface at the move and serves it
again once the change is applied. A request sent in between is not
answered. An apply serves an interface only on the bridge its config
names, and it also repairs an interface whose plug failed. An edit
through the API whose update fails returns an error, with the mapping
saved. Any other change that fails only warns, and the next apply
makes up for it. Nothing of the responder survives a reboot, so it is
loaded again at boot before the guests start.

Only DHCPv4 is answered. A request the guest tagged itself passes
unanswered as well, so a trunk port keeps working as before. The
request is answered on the guest interface, so the guest's firewall
rules, its DHCP firewall option and its rate limit do not apply to it.
The reply leaves through the interface's egress, where the rate limit
shapes it. A request the responder does not answer passes on to the
bridge and through the firewall as before. Mappings changed directly
in an external IPAM are not picked up, as with dnsmasq.

In patch order, the series adds
 - proxmox, a byte accessor for the MAC address type of
   proxmox-network-types
 - pve-rs, the Perl bindings for the responder, and a trigger that
   loads the responder again after an upgrade of pve-rs
 - pve-network, the VXLAN and EVPN MTU taken from the underlay
   interface, the BPF program in a package of its own, the ebpf
   backend, the plug and unplug hooks for the DHCP backends, and DHCP
   on every zone type
 - qemu-server and pve-container, the calls that tell the DHCP backends
   when a guest NIC is plugged, unplugged or moved to another bridge
 - pve-manager, the backend and subnet options in the UI, and the DHCP
   backends started at boot before the guests
 - proxmox-ve-rs, ebpf as a DHCP backend type in proxmox-ve-config,
   and the crate that loads the program and fills its map with the
   answer for each guest interface
 - pve-docs, the MTU VXLAN and EVPN zones take from the underlay, and
   the documentation of the backend

 - proxmox applies on top of the proxmox-ebpf series [1]
 - pve-network, qemu-server and pve-docs apply on top of [2]
 - pve-container applies on top of [3]
 - proxmox-ve-rs needs proxmox-ebpf from [1]
 - pve-rs needs proxmox-sdn-dhcp from proxmox-ve-rs, and
   proxmox-network-types with the byte accessor
 - pve-network needs pve-rs, at build and run time, and clang-21,
   libbpf-dev and proxmox-kernel-libc-dev to build the program
 - pve-network needs the qemu-server and pve-container of this series
   as well, since older ones plug a guest NIC without its MAC
 - qemu-server, pve-container and pve-manager need pve-network
 - proxmox-firewall needs proxmox-ve-config, since an older one
   fails to parse a zone with the ebpf backend and the firewall then
   cannot load its config
An older pve-network fails its apply on the unknown backend, so every
node needs the new one before a zone gets ebpf.

v7:
 * move dhcp update call to after the config commit, this avoids the
   whole problem of the kernel state being newer than the committed
   config. the cost of having (hot)plugs and sdn applies based on the
   same information, is that during a hotplug, there is a short
   timeframe, namely between the unplug and the config commit from
   pending, where no responder is active. so between the interface
   changing, and the committed config reflecting this change the guest
   does not get its dhcp requests answered. this is short, and for dhcp
   it'll just ask again
 * have the zone mtu consider the address family, v6 needs 20 bytes more
   than v4
 * rebased onto the ebpf-lib v9 [1] and current master
 * the program moved from proxmox to pve-network, into the new
   pve-network-ebpf package. the tests for the C bpf programs stayed in
   rust, with perl we cant call the compiled program directly, and
   having them in C seemed worse than rust, even if the cargo build-dep
   for the tests seemed a little odd
 * the code that loads the program moved from proxmox into the new
   proxmox-sdn-dhcp crate in proxmox-ve-rs
 * new pve-rs patch, the responder is loaded again after an upgrade of
   pve-rs
 * an apply asks the IPAM for missing addresses before it takes the
   responder's lock
 * new pve-network patch, the underlay lookup of VXLAN and EVPN zones
   in a function of its own

v6:
 * like the ebpf-lib v8 that this is based on, this moved into the
   proxmox workspace
 * rebased onto the ipam series v6 [2]
 * rebased onto current master
 * an apply repairs an interface whose plug failed, once it sits on
   the bridge its config names
 * a plug reads the zone's backend under the responder's lock, so an
   apply switching it meanwhile is not undone
 * a map replacement that cannot write every entry keeps the old maps
 * an API edit whose DHCP update fails returns an error
 * the bindings use the MAC address type of proxmox-network-types
 * docs: the MTU default of VXLAN and EVPN zones

v5:
 * rebased onto ebpf-lib v5
 * the MAC cache and dnsmasq fixes moved to [2], as did running a
   mapping edit on the guest's node and the push on resume
 * a mapping edit only changes the answers on its own vnet
 * the VXLAN and EVPN bridges get the MTU that DHCP hands out, both
   take it from the underlay interface
 * a MAC change on the same vnet is no longer undone by an apply
   running meanwhile

v4, thanks @Stefan!:
 * a mapping edit runs on the guest's node instead of being pushed to
   it, the node endpoint is gone
 * the MAC cache is read and written with lower-case keys, and its
   three fixes are three commits
 * the guest NIC list is keyed by MAC
 * add the missing proxmox-ve-rs patch, the ebpf variant of the dhcp
   backend type
 * reword log lines and warnings
 * (notes on patches with changes)

v3:
 * drop the generation counter. Every change takes the responder's
   lock before it reads its input instead. An edit takes it
   exclusively
 * the resume at the end of a live migration pushes the guest's
   mappings again on the target, so an edit made during the migration
   reaches it
 * new first pve-network commit, a dnsmasq fix that replaces a stale
   reservation of another MAC instead of dropping it
 * no MTU option for a zone without an MTU, where v2 handed out 1500
 * a mapping edit without a MAC no longer reaches the backends
 * rewrite commit messages, cover letter and parts of the docs
 * rebase onto current master

pre-build packages are on sani(`packages/ebpf-dhcp-v7`)

[1] https://lore.proxmox.com/pve-devel/20261110135005.2847847-1-h.laimer@proxmox.com/
[2] https://lore.proxmox.com/pve-devel/20261105093529.209052-1-h.laimer@proxmox.com/
[3] https://lore.proxmox.com/pve-devel/20261112104059.2377096-1-h.laimer@proxmox.com/


proxmox:

Hannes Laimer (1):
  network-types: mac address: add an accessor for the bytes

 proxmox-network-types/src/mac_address.rs | 5 +++++
 1 file changed, 5 insertions(+)


proxmox-perl-rs:

Hannes Laimer (2):
  pve-rs: sdn: add bindings for the eBPF DHCP responder
  pve-rs: fire the pve-ebpf-update trigger on upgrade

 pve-rs/Cargo.toml               |   2 +
 pve-rs/Makefile                 |   3 +
 pve-rs/debian/control           |   1 +
 pve-rs/debian/triggers          |   1 +
 pve-rs/src/bindings/sdn/dhcp.rs | 200 ++++++++++++++++++++++++++++++++
 pve-rs/src/bindings/sdn/mod.rs  |   1 +
 6 files changed, 208 insertions(+)
 create mode 100644 pve-rs/src/bindings/sdn/dhcp.rs


pve-network:

Hannes Laimer (10):
  sdn: zones: take the VXLAN and EVPN MTU from the underlay interface
  sdn: zones: account for IPv6 in the VXLAN and EVPN MTU
  sdn: dhcp: make the lease time configurable per subnet
  sdn: dhcp: require a backend only if a zone on this node uses it
  bpf: add the build, the package and a native harness for BPF programs
  sdn: dhcp: add the per-tap DHCPv4 responder program
  sdn: dhcp: add an eBPF backend answering on each guest interface
  sdn: zones: report interface plugs and unplugs to the DHCP backends
  sdn: zones: factor out the underlay lookup of VXLAN and EVPN zones
  sdn: zones: allow the ebpf DHCP backend on every zone type

 .gitignore                                    |    3 +
 Makefile                                      |    1 +
 debian/control                                |   14 +
 debian/libpve-network-perl.postinst           |   22 +
 debian/libpve-network-perl.prerm              |   13 +
 debian/pve-network-ebpf.install               |    1 +
 debian/pve-network-ebpf.lintian-overrides     |    2 +
 debian/triggers                               |    1 +
 src/Makefile                                  |    3 +-
 src/PVE/API2/Network/SDN/Zones.pm             |   16 +-
 src/PVE/Network/SDN/Dhcp.pm                   |  109 +-
 src/PVE/Network/SDN/Dhcp/Dnsmasq.pm           |    5 +-
 src/PVE/Network/SDN/Dhcp/Ebpf.pm              |  395 ++++++
 src/PVE/Network/SDN/Dhcp/Makefile             |    2 +-
 src/PVE/Network/SDN/Dhcp/Plugin.pm            |   24 +-
 src/PVE/Network/SDN/SubnetPlugin.pm           |   11 +
 src/PVE/Network/SDN/Vnets.pm                  |    2 +-
 src/PVE/Network/SDN/Zones.pm                  |   42 +-
 src/PVE/Network/SDN/Zones/EvpnPlugin.pm       |   98 +-
 src/PVE/Network/SDN/Zones/FaucetPlugin.pm     |    1 +
 src/PVE/Network/SDN/Zones/QinQPlugin.pm       |    7 +
 src/PVE/Network/SDN/Zones/SimplePlugin.pm     |    2 +-
 src/PVE/Network/SDN/Zones/VlanPlugin.pm       |    7 +
 src/PVE/Network/SDN/Zones/VxlanPlugin.pm      |  105 +-
 src/bpf/Makefile                              |   37 +
 src/bpf/dhcp/dhcp.bpf.c                       |  393 ++++++
 src/bpf/dhcp/types.h                          |   27 +
 src/bpf/harness/Cargo.toml                    |    8 +
 src/bpf/harness/build.rs                      |  101 ++
 src/bpf/harness/shim/bpf/bpf_helpers.h        |   35 +
 src/bpf/harness/shim/bpf_debug.h              |   10 +
 src/bpf/harness/shim/linux/bpf.h              |   28 +
 src/bpf/harness/tests/bpf/fixture.bpf.c       |   37 +
 src/bpf/harness/tests/common/mod.rs           |  267 ++++
 src/bpf/harness/tests/dhcp.rs                 |  804 +++++++++++
 src/bpf/harness/tests/harness.rs              |   98 ++
 src/bpf/include/bpf_debug.h                   |   12 +
 src/bpf/order                                 |    1 +
 src/test/run_test_vnets_blackbox.pl           | 1183 ++++++++++++++++-
 .../evpn/ipv6underlay/expected_sdn_interfaces |    8 +-
 .../expected_sdn_interfaces                   |    8 +-
 .../expected_sdn_interfaces                   |    8 +-
 .../underlay_mtu/expected_controller_config   |   44 +
 .../evpn/underlay_mtu/expected_sdn_interfaces |   42 +
 src/test/zones/evpn/underlay_mtu/interfaces   |    8 +
 src/test/zones/evpn/underlay_mtu/sdn_config   |   26 +
 .../zones/vxlan/ipv6/expected_sdn_interfaces  |    4 +-
 .../underlay_mtu/expected_sdn_interfaces      |   16 +
 src/test/zones/vxlan/underlay_mtu/interfaces  |    8 +
 src/test/zones/vxlan/underlay_mtu/sdn_config  |   11 +
 .../underlay_mtu_ipv6/expected_sdn_interfaces |   16 +
 .../zones/vxlan/underlay_mtu_ipv6/interfaces  |    8 +
 .../zones/vxlan/underlay_mtu_ipv6/sdn_config  |   17 +
 53 files changed, 4028 insertions(+), 123 deletions(-)
 create mode 100755 debian/libpve-network-perl.prerm
 create mode 100644 debian/pve-network-ebpf.install
 create mode 100644 debian/pve-network-ebpf.lintian-overrides
 create mode 100644 src/PVE/Network/SDN/Dhcp/Ebpf.pm
 create mode 100644 src/bpf/Makefile
 create mode 100644 src/bpf/dhcp/dhcp.bpf.c
 create mode 100644 src/bpf/dhcp/types.h
 create mode 100644 src/bpf/harness/Cargo.toml
 create mode 100644 src/bpf/harness/build.rs
 create mode 100644 src/bpf/harness/shim/bpf/bpf_helpers.h
 create mode 100644 src/bpf/harness/shim/bpf_debug.h
 create mode 100644 src/bpf/harness/shim/linux/bpf.h
 create mode 100644 src/bpf/harness/tests/bpf/fixture.bpf.c
 create mode 100644 src/bpf/harness/tests/common/mod.rs
 create mode 100644 src/bpf/harness/tests/dhcp.rs
 create mode 100644 src/bpf/harness/tests/harness.rs
 create mode 100644 src/bpf/include/bpf_debug.h
 create mode 100644 src/bpf/order
 create mode 100644 src/test/zones/evpn/underlay_mtu/expected_controller_config
 create mode 100644 src/test/zones/evpn/underlay_mtu/expected_sdn_interfaces
 create mode 100644 src/test/zones/evpn/underlay_mtu/interfaces
 create mode 100644 src/test/zones/evpn/underlay_mtu/sdn_config
 create mode 100644 src/test/zones/vxlan/underlay_mtu/expected_sdn_interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu/interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu/sdn_config
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/expected_sdn_interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/sdn_config


qemu-server:

Hannes Laimer (1):
  network: sdn: keep the DHCP backends current on guest NICs

 src/PVE/CLI/qm.pm                                |  4 ++--
 src/PVE/QemuServer.pm                            | 16 ++++++++++++++++
 src/PVE/QemuServer/Network.pm                    | 10 ++++++++--
 .../aarch64/net-add-pci-bridge.conf.expected     |  1 +
 src/test/hotplug/aarch64/net-add.conf.expected   |  1 +
 .../aarch64/x86-guest-net-add.conf.expected      |  1 +
 .../hotplug/net-add-pci-bridge.conf.expected     |  1 +
 src/test/hotplug/net-add.conf.expected           |  1 +
 src/test/hotplug/net-change-bridge.conf.expected |  4 +++-
 src/test/hotplug/net-change-model.conf.expected  |  1 +
 src/test/hotplug/net-change-rate.conf.expected   |  1 +
 src/test/run_hotplug_tests.pl                    |  5 ++++-
 src/usr/pve-bridge                               |  8 +++++++-
 src/usr/pve-bridgedown                           |  4 ++--
 14 files changed, 49 insertions(+), 9 deletions(-)


pve-container:

Hannes Laimer (1):
  net: report NIC plugs and removals to the SDN DHCP backends

 src/PVE/LXC.pm            | 33 +++++++++++++++++++++++++++------
 src/PVE/LXC/Config.pm     |  3 ++-
 src/lxc-pve-poststop-hook |  6 +++---
 3 files changed, 32 insertions(+), 10 deletions(-)


pve-manager:

Hannes Laimer (2):
  ui: sdn: add zone DHCP backend selector and subnet DHCP options
  sdn: bring up the DHCP backends at boot before the guests start

 bin/pve-sdn-commit                   |  4 ++++
 services/pve-sdn-commit.service      |  1 +
 www/manager6/sdn/SubnetEdit.js       | 23 +++++++++++++++++++++++
 www/manager6/sdn/zones/Base.js       | 17 +++++++++++++++++
 www/manager6/sdn/zones/SimpleEdit.js | 11 -----------
 5 files changed, 45 insertions(+), 11 deletions(-)


proxmox-ve-rs:

Hannes Laimer (2):
  ve-config: sdn: add the ebpf dhcp backend
  sdn-dhcp: add the crate that runs the eBPF DHCP responder

 Cargo.toml                            |   2 +
 proxmox-sdn-dhcp/Cargo.toml           |  18 +
 proxmox-sdn-dhcp/debian/changelog     |   5 +
 proxmox-sdn-dhcp/debian/control       |  42 ++
 proxmox-sdn-dhcp/debian/copyright     |  18 +
 proxmox-sdn-dhcp/debian/debcargo.toml |   7 +
 proxmox-sdn-dhcp/src/lib.rs           | 688 ++++++++++++++++++++++++++
 proxmox-sdn-dhcp/src/types.rs         |  42 ++
 proxmox-ve-config/src/sdn/config.rs   |   3 +
 9 files changed, 825 insertions(+)
 create mode 100644 proxmox-sdn-dhcp/Cargo.toml
 create mode 100644 proxmox-sdn-dhcp/debian/changelog
 create mode 100644 proxmox-sdn-dhcp/debian/control
 create mode 100644 proxmox-sdn-dhcp/debian/copyright
 create mode 100644 proxmox-sdn-dhcp/debian/debcargo.toml
 create mode 100644 proxmox-sdn-dhcp/src/lib.rs
 create mode 100644 proxmox-sdn-dhcp/src/types.rs


pve-docs:

Hannes Laimer (2):
  sdn: zones: document the MTU taken from the underlay interface
  sdn: dhcp: add eBPF backend section

 pvesdn.adoc | 154 +++++++++++++++++++++++++++++++++++++++-------------
 1 file changed, 117 insertions(+), 37 deletions(-)


Summary over all repositories:
  92 files changed, 5309 insertions(+), 190 deletions(-)

-- 
Generated by murpp 0.12.0




^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH proxmox v7 01/21] network-types: mac address: add an accessor for the bytes
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 02/21] pve-rs: sdn: add bindings for the eBPF DHCP responder Hannes Laimer
                   ` (19 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 proxmox-network-types/src/mac_address.rs | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/proxmox-network-types/src/mac_address.rs b/proxmox-network-types/src/mac_address.rs
index d76a04ab8c20..35aa1dda7d97 100644
--- a/proxmox-network-types/src/mac_address.rs
+++ b/proxmox-network-types/src/mac_address.rs
@@ -145,6 +145,11 @@ impl MacAddress {
         Self(address)
     }
 
+    /// Returns the six bytes of the address.
+    pub fn octets(&self) -> [u8; 6] {
+        self.0
+    }
+
     /// Generates a link-local IPv6 address according to RFC 4291 (Appendix A).
     ///
     /// This method performs the EUI-64 transformation, inserting `FF:FE` in the middle of the MAC
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH proxmox-perl-rs v7 02/21] pve-rs: sdn: add bindings for the eBPF DHCP responder
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox v7 01/21] network-types: mac address: add an accessor for the bytes Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 03/21] pve-rs: fire the pve-ebpf-update trigger on upgrade Hannes Laimer
                   ` (18 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The responder answers from records the Perl side builds. They have to
be built under the responder's lock. Otherwise a full pass could
overwrite a newer record with one it built earlier.

So the lock is an object, and every call that takes records is a
method of it. Records cannot be passed in without holding the lock.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 pve-rs/Cargo.toml               |   2 +
 pve-rs/Makefile                 |   3 +
 pve-rs/debian/control           |   1 +
 pve-rs/src/bindings/sdn/dhcp.rs | 200 ++++++++++++++++++++++++++++++++
 pve-rs/src/bindings/sdn/mod.rs  |   1 +
 5 files changed, 207 insertions(+)
 create mode 100644 pve-rs/src/bindings/sdn/dhcp.rs

diff --git a/pve-rs/Cargo.toml b/pve-rs/Cargo.toml
index f22e3aee5674..66769865d9e6 100644
--- a/pve-rs/Cargo.toml
+++ b/pve-rs/Cargo.toml
@@ -45,6 +45,7 @@ proxmox-openid = "1.0.2"
 proxmox-resource-scheduling = "2"
 proxmox-schema = "5"
 proxmox-section-config = "3"
+proxmox-sdn-dhcp = "0.1"
 proxmox-sdn-types = "0.2.5"
 proxmox-shared-cache = "1"
 proxmox-subscription = "1.0.2"
@@ -71,6 +72,7 @@ proxmox-wireguard = { version = "0.1.2" }
 # proxmox-config-digest = { path = "../../proxmox/proxmox-config-digest" }
 # proxmox-daemon = { path = "../../proxmox/proxmox-daemon" }
 # proxmox-dns-api = { path = "../../proxmox/proxmox-dns-api" }
+# proxmox-ebpf = { path = "../../proxmox/proxmox-ebpf" }
 # proxmox-http-error = { path = "../../proxmox/proxmox-http-error" }
 # proxmox-http = { path = "../../proxmox/proxmox-http" }
 # proxmox-human-byte = { path = "../../proxmox/proxmox-human-byte" }
diff --git a/pve-rs/Makefile b/pve-rs/Makefile
index 60f68c7a21be..c597401f789b 100644
--- a/pve-rs/Makefile
+++ b/pve-rs/Makefile
@@ -33,6 +33,9 @@ PERLMOD_PACKAGES := \
 	  PVE::RS::OpenId \
 	  PVE::RS::ResourceScheduling::Static \
 	  PVE::RS::ResourceScheduling::Dynamic \
+	  PVE::RS::SDN::Dhcp \
+	  PVE::RS::SDN::Dhcp::ExclusiveLock \
+	  PVE::RS::SDN::Dhcp::SharedLock \
 	  PVE::RS::SDN::Fabrics \
 	  PVE::RS::SDN::PrefixLists \
 	  PVE::RS::SDN::RouteMaps \
diff --git a/pve-rs/debian/control b/pve-rs/debian/control
index 25b7be8b26e6..fca271543db1 100644
--- a/pve-rs/debian/control
+++ b/pve-rs/debian/control
@@ -33,6 +33,7 @@ Build-Depends: debhelper-compat (= 13),
                librust-proxmox-oci-0.2+default-dev (>= 0.2.2-~~),
                librust-proxmox-openid-1+default-dev (>= 1.0.2-~~),
                librust-proxmox-resource-scheduling-2+default-dev (>= 2.0.0-~~),
+               librust-proxmox-sdn-dhcp-0.1+default-dev,
                librust-proxmox-sdn-types-0.2+default-dev (>= 0.2.5-~~),
                librust-proxmox-section-config-3+default-dev,
                librust-proxmox-shared-cache-1+default-dev,
diff --git a/pve-rs/src/bindings/sdn/dhcp.rs b/pve-rs/src/bindings/sdn/dhcp.rs
new file mode 100644
index 000000000000..09af79486c88
--- /dev/null
+++ b/pve-rs/src/bindings/sdn/dhcp.rs
@@ -0,0 +1,200 @@
+#[perlmod::package(name = "PVE::RS::SDN::Dhcp", lib = "pve_rs")]
+pub mod pve_rs_sdn_dhcp {
+    //! The `PVE::RS::SDN::Dhcp` package.
+    //!
+    //! Bindings for the per-tap eBPF DHCP responder. Interfaces and the records they answer with
+    //! are handed in here and served directly from the kernel. The calls that change the responder
+    //! are methods of a lock object, so nothing writes to it without holding the lock in the mode
+    //! the change needs.
+
+    use std::net::Ipv4Addr;
+
+    use anyhow::Error;
+    use serde::Deserialize;
+
+    use proxmox_network_types::mac_address::MacAddress;
+    use proxmox_sdn_dhcp::{Iface, Record};
+
+    /// One interface's DHCP answer, the address and every option the reply carries.
+    #[derive(Deserialize)]
+    pub struct PerlRecord {
+        ip: Ipv4Addr,
+        prefixlen: u8,
+        server_id: Ipv4Addr,
+        lease: u32,
+        #[serde(default)]
+        router: Option<Ipv4Addr>,
+        #[serde(default)]
+        dns: Option<Ipv4Addr>,
+        #[serde(default)]
+        mtu: Option<u16>,
+    }
+
+    /// One guest interface to serve, with its MAC and the record it answers with.
+    #[derive(Deserialize)]
+    pub struct PerlIface {
+        name: String,
+        #[serde(default)]
+        mac: Option<MacAddress>,
+        #[serde(default)]
+        record: Option<PerlRecord>,
+    }
+
+    impl From<PerlRecord> for Record {
+        fn from(r: PerlRecord) -> Self {
+            Record {
+                ip: r.ip,
+                prefixlen: r.prefixlen,
+                server_id: r.server_id,
+                lease: r.lease,
+                router: r.router,
+                dns: r.dns,
+                mtu: r.mtu,
+            }
+        }
+    }
+
+    impl From<PerlIface> for Iface {
+        fn from(i: PerlIface) -> Self {
+            Iface {
+                name: i.name,
+                mac: i.mac.map(|mac| mac.octets()),
+                record: i.record.map(Record::from),
+            }
+        }
+    }
+
+    pub(super) fn to_ifaces(ifaces: Vec<PerlIface>) -> Vec<Iface> {
+        ifaces.into_iter().map(Iface::from).collect()
+    }
+
+    /// A tap unplug. The interface is gone or going and takes its record with it.
+    #[export]
+    pub fn detach(iface: &str) -> Result<(), Error> {
+        proxmox_sdn_dhcp::detach(iface)
+    }
+}
+
+#[perlmod::package(name = "PVE::RS::SDN::Dhcp::SharedLock", lib = "pve_rs")]
+pub mod pve_rs_sdn_dhcp_shared_lock {
+    //! The `PVE::RS::SDN::Dhcp::SharedLock` package.
+    //!
+    //! The responder's lock taken shared, what a tap plug and a guest's own record change hold.
+    //! Released when the object goes away.
+
+    use anyhow::Error;
+    use perlmod::Value;
+
+    use proxmox_network_types::mac_address::MacAddress;
+    use proxmox_sdn_dhcp::{Iface, Outcome, Record, SharedLock};
+
+    use super::pve_rs_sdn_dhcp::{PerlIface, PerlRecord, to_ifaces};
+
+    /// The lock as Perl holds it.
+    pub struct PerlSharedLock {
+        lock: SharedLock,
+    }
+
+    perlmod::declare_magic!(Box<PerlSharedLock> : &PerlSharedLock as "PVE::RS::SDN::Dhcp::SharedLock");
+
+    /// Class method: take the lock. Plugs hold it next to each other and wait only behind a full
+    /// pass or a record change.
+    #[export]
+    pub fn new(#[raw] class: Value) -> Result<Value, Error> {
+        let lock = proxmox_sdn_dhcp::lock_shared()?;
+        Ok(perlmod::instantiate_magic!(&class, MAGIC => Box::new(PerlSharedLock { lock })))
+    }
+
+    /// Method: a tap plug with the NIC's MAC and the record it answers. Without a record the
+    /// interface gets a link and no entry. Returns false when nothing is loaded yet. An interface
+    /// gone already counts as done.
+    #[export]
+    pub fn attach(
+        #[try_from_ref] this: &PerlSharedLock,
+        iface: String,
+        mac: Option<MacAddress>,
+        record: Option<PerlRecord>,
+    ) -> Result<bool, Error> {
+        let iface = Iface {
+            name: iface,
+            mac: mac.map(|mac| mac.octets()),
+            record: record.map(Record::from),
+        };
+        Ok(this.lock.attach(&iface)? == Outcome::Done)
+    }
+
+    /// Method: a plug onto a bridge the responder does not serve. The interface loses its link and
+    /// its entry.
+    #[export]
+    pub fn detach(#[try_from_ref] this: &PerlSharedLock, iface: &str) -> Result<(), Error> {
+        this.lock.detach(iface)
+    }
+
+    /// Method: a record change for the listed interfaces by a caller holding the guest lock.
+    /// Returns false when nothing is loaded to write into, so a full pass is due.
+    #[export]
+    pub fn update(
+        #[try_from_ref] this: &PerlSharedLock,
+        ifaces: Vec<PerlIface>,
+    ) -> Result<bool, Error> {
+        Ok(this.lock.update(&to_ifaces(ifaces))? == Outcome::Done)
+    }
+}
+
+#[perlmod::package(name = "PVE::RS::SDN::Dhcp::ExclusiveLock", lib = "pve_rs")]
+pub mod pve_rs_sdn_dhcp_exclusive_lock {
+    //! The `PVE::RS::SDN::Dhcp::ExclusiveLock` package.
+    //!
+    //! The responder's lock taken exclusively, what a full pass and a record change hold. Released
+    //! when the object goes away.
+
+    use std::sync::Mutex;
+
+    use anyhow::Error;
+    use perlmod::Value;
+
+    use proxmox_sdn_dhcp::{ExclusiveLock, Outcome};
+
+    use super::pve_rs_sdn_dhcp::{PerlIface, to_ifaces};
+
+    /// The lock as Perl holds it. A full pass and a clear take it mutably, and Perl hands out
+    /// shared references only.
+    pub struct PerlExclusiveLock {
+        lock: Mutex<ExclusiveLock>,
+    }
+
+    perlmod::declare_magic!(Box<PerlExclusiveLock> : &PerlExclusiveLock as "PVE::RS::SDN::Dhcp::ExclusiveLock");
+
+    /// Class method: take the lock, waiting out every plug in flight.
+    #[export]
+    pub fn new(#[raw] class: Value) -> Result<Value, Error> {
+        let lock = Mutex::new(proxmox_sdn_dhcp::lock_exclusive()?);
+        Ok(perlmod::instantiate_magic!(&class, MAGIC => Box::new(PerlExclusiveLock { lock })))
+    }
+
+    /// Method: the full pass over the guest interfaces to serve. Those found here get a link, and
+    /// an entry where they have a record. Every other link and entry goes.
+    #[export]
+    pub fn apply(
+        #[try_from_ref] this: &PerlExclusiveLock,
+        ifaces: Vec<PerlIface>,
+    ) -> Result<(), Error> {
+        this.lock.lock().unwrap().apply(&to_ifaces(ifaces))
+    }
+
+    /// Method: a record change for the listed interfaces. Those not found here are skipped.
+    /// Returns false when nothing is loaded to write into, so a full pass is due.
+    #[export]
+    pub fn update(
+        #[try_from_ref] this: &PerlExclusiveLock,
+        ifaces: Vec<PerlIface>,
+    ) -> Result<bool, Error> {
+        Ok(this.lock.lock().unwrap().update(&to_ifaces(ifaces))? == Outcome::Done)
+    }
+
+    /// Method: detach the responder everywhere and drop its pinned state.
+    #[export]
+    pub fn clear(#[try_from_ref] this: &PerlExclusiveLock) -> Result<(), Error> {
+        this.lock.lock().unwrap().clear()
+    }
+}
diff --git a/pve-rs/src/bindings/sdn/mod.rs b/pve-rs/src/bindings/sdn/mod.rs
index dcae046a7e46..4b99b8fa10e5 100644
--- a/pve-rs/src/bindings/sdn/mod.rs
+++ b/pve-rs/src/bindings/sdn/mod.rs
@@ -1,3 +1,4 @@
+pub(crate) mod dhcp;
 pub(crate) mod fabrics;
 pub(crate) mod prefix_lists;
 pub(crate) mod route_maps;
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH proxmox-perl-rs v7 03/21] pve-rs: fire the pve-ebpf-update trigger on upgrade
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox v7 01/21] network-types: mac address: add an accessor for the bytes Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 02/21] pve-rs: sdn: add bindings for the eBPF DHCP responder Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 04/21] sdn: zones: take the VXLAN and EVPN MTU from the underlay interface Hannes Laimer
                   ` (17 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

After an upgrade that changes a map layout, the library finds nothing
loaded until pve-network runs the full apply this trigger starts.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 pve-rs/debian/triggers | 1 +
 1 file changed, 1 insertion(+)

diff --git a/pve-rs/debian/triggers b/pve-rs/debian/triggers
index 59dd6885a5f9..828e5411da90 100644
--- a/pve-rs/debian/triggers
+++ b/pve-rs/debian/triggers
@@ -1 +1,2 @@
 activate-noawait pve-api-updates
+activate-noawait pve-ebpf-update
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 04/21] sdn: zones: take the VXLAN and EVPN MTU from the underlay interface
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (2 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 03/21] pve-rs: fire the pve-ebpf-update trigger on upgrade Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 05/21] sdn: zones: account for IPv6 in the VXLAN and EVPN MTU Hannes Laimer
                   ` (16 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The MTU of a VXLAN or EVPN zone without its own setting is the MTU of
the interface that reaches its peers, minus the 50 bytes of VXLAN
encapsulation. The lookup read that interface one level too high in
the parsed network configuration and never found it. So the vnets
always got the default of 1450.

A zone whose underlay interface has an MTU set gets that MTU minus the
encapsulation at its next apply, such as 8950 on a 9000 byte underlay.
A zone on a fabric has no such interface to look up and keeps the
default.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---

Notes:
    v5:
     * new

 src/PVE/Network/SDN/Zones/EvpnPlugin.pm       |  8 ++--
 src/PVE/Network/SDN/Zones/VxlanPlugin.pm      | 18 +++++---
 .../underlay_mtu/expected_controller_config   | 44 +++++++++++++++++++
 .../evpn/underlay_mtu/expected_sdn_interfaces | 42 ++++++++++++++++++
 src/test/zones/evpn/underlay_mtu/interfaces   |  8 ++++
 src/test/zones/evpn/underlay_mtu/sdn_config   | 26 +++++++++++
 .../underlay_mtu/expected_sdn_interfaces      | 16 +++++++
 src/test/zones/vxlan/underlay_mtu/interfaces  |  8 ++++
 src/test/zones/vxlan/underlay_mtu/sdn_config  | 11 +++++
 9 files changed, 171 insertions(+), 10 deletions(-)
 create mode 100644 src/test/zones/evpn/underlay_mtu/expected_controller_config
 create mode 100644 src/test/zones/evpn/underlay_mtu/expected_sdn_interfaces
 create mode 100644 src/test/zones/evpn/underlay_mtu/interfaces
 create mode 100644 src/test/zones/evpn/underlay_mtu/sdn_config
 create mode 100644 src/test/zones/vxlan/underlay_mtu/expected_sdn_interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu/interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu/sdn_config

diff --git a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
index c31b6c6a2bfd..1720e1ff5735 100644
--- a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
@@ -218,11 +218,9 @@ sub generate_sdn_config {
     my $is_evpn_gateway = $plugin_config->{'exitnodes'}->{$local_node};
     my $exitnodes_local_routing = $plugin_config->{'exitnodes-local-routing'};
 
-    my $mtu = 1450;
-    if ($iface) {
-        $mtu = $interfaces_config->{$iface}->{mtu} - 50 if $interfaces_config->{$iface}->{mtu};
-    }
-    $mtu = $plugin_config->{mtu} if $plugin_config->{mtu};
+    my $mtu = PVE::Network::SDN::Zones::VxlanPlugin::vxlan_mtu(
+        $plugin_config, $iface, $interfaces_config,
+    );
 
     #vxlan interface
     my $vxlan_iface = "vxlan_$vnetid";
diff --git a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
index b8b1ef0eeb7f..4992757c1c5b 100644
--- a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
@@ -48,6 +48,18 @@ sub properties {
     };
 }
 
+# the vnet bridge takes the underlay interface's MTU minus the vxlan
+# encapsulation where the peers name a local interface, the default
+# otherwise. An explicit zone MTU wins
+sub vxlan_mtu {
+    my ($plugin_config, $iface, $interfaces_config) = @_;
+
+    return $plugin_config->{mtu} if $plugin_config->{mtu};
+    return $interfaces_config->{ifaces}->{$iface}->{mtu} - 50
+        if $iface && $interfaces_config->{ifaces}->{$iface}->{mtu};
+    return 1450;
+}
+
 sub options {
     return {
         nodes => { optional => 1 },
@@ -120,11 +132,7 @@ sub generate_sdn_config {
         die "neither peers nor fabric configured for VXLAN zone $plugin_config->{id}";
     }
 
-    my $mtu = 1450;
-    if ($iface) {
-        $mtu = $interfaces_config->{$iface}->{mtu} - 50 if $interfaces_config->{$iface}->{mtu};
-    }
-    $mtu = $plugin_config->{mtu} if $plugin_config->{mtu};
+    my $mtu = vxlan_mtu($plugin_config, $iface, $interfaces_config);
 
     #vxlan interface
     my @iface_config = ();
diff --git a/src/test/zones/evpn/underlay_mtu/expected_controller_config b/src/test/zones/evpn/underlay_mtu/expected_controller_config
new file mode 100644
index 000000000000..0c6cc0939d15
--- /dev/null
+++ b/src/test/zones/evpn/underlay_mtu/expected_controller_config
@@ -0,0 +1,44 @@
+frr version 10.6.1
+frr defaults datacenter
+hostname localhost
+log syslog informational
+service integrated-vtysh-config
+!
+vrf vrf_myzone
+ vni 1000
+exit-vrf
+!
+router bgp 65000
+ bgp router-id 192.168.0.1
+ no bgp hard-administrative-reset
+ no bgp default ipv4-unicast
+ coalesce-time 1000
+ no bgp graceful-restart notification
+ neighbor VTEP peer-group
+ neighbor VTEP remote-as 65000
+ neighbor VTEP bfd
+ neighbor 192.168.0.2 peer-group VTEP
+ neighbor 192.168.0.3 peer-group VTEP
+ !
+ address-family l2vpn evpn
+  neighbor VTEP activate
+  neighbor VTEP route-map MAP_VTEP_IN in
+  neighbor VTEP route-map MAP_VTEP_OUT out
+  advertise-all-vni
+ exit-address-family
+exit
+!
+router bgp 65000 vrf vrf_myzone
+ bgp router-id 192.168.0.1
+ no bgp hard-administrative-reset
+ no bgp graceful-restart notification
+exit
+!
+route-map MAP_VTEP_IN permit 1
+exit
+!
+route-map MAP_VTEP_OUT permit 1
+exit
+!
+line vty
+!
diff --git a/src/test/zones/evpn/underlay_mtu/expected_sdn_interfaces b/src/test/zones/evpn/underlay_mtu/expected_sdn_interfaces
new file mode 100644
index 000000000000..66d6c3d40a08
--- /dev/null
+++ b/src/test/zones/evpn/underlay_mtu/expected_sdn_interfaces
@@ -0,0 +1,42 @@
+#version:1
+
+auto myvnet
+iface myvnet
+	address 10.0.0.1/24
+	hwaddress A2:1D:CB:1A:C0:8B
+	bridge_ports vxlan_myvnet
+	bridge_stp off
+	bridge_fd 0
+	mtu 8950
+	ip-forward on
+	arp-accept on
+	vrf vrf_myzone
+
+auto vrf_myzone
+iface vrf_myzone
+	vrf-table auto
+	post-up ip route add vrf vrf_myzone unreachable default metric 4278198272
+
+auto vrfbr_myzone
+iface vrfbr_myzone
+	bridge-ports vrfvx_myzone
+	bridge_stp off
+	bridge_fd 0
+	mtu 8950
+	vrf vrf_myzone
+
+auto vrfvx_myzone
+iface vrfvx_myzone
+	vxlan-id 1000
+	vxlan-local-tunnelip 192.168.0.1
+	bridge-learning off
+	bridge-arp-nd-suppress on
+	mtu 8950
+
+auto vxlan_myvnet
+iface vxlan_myvnet
+	vxlan-id 100
+	vxlan-local-tunnelip 192.168.0.1
+	bridge-learning off
+	bridge-arp-nd-suppress on
+	mtu 8950
diff --git a/src/test/zones/evpn/underlay_mtu/interfaces b/src/test/zones/evpn/underlay_mtu/interfaces
new file mode 100644
index 000000000000..c32f92e1a7fc
--- /dev/null
+++ b/src/test/zones/evpn/underlay_mtu/interfaces
@@ -0,0 +1,8 @@
+auto vmbr0
+iface vmbr0 inet static
+	address 192.168.0.1/24
+	gateway 192.168.0.254
+	mtu 9000
+        bridge-ports eth0
+        bridge-stp off
+        bridge-fd 0
diff --git a/src/test/zones/evpn/underlay_mtu/sdn_config b/src/test/zones/evpn/underlay_mtu/sdn_config
new file mode 100644
index 000000000000..dd73b5cdc140
--- /dev/null
+++ b/src/test/zones/evpn/underlay_mtu/sdn_config
@@ -0,0 +1,26 @@
+{
+  version => 1,
+  vnets   => {
+               ids => {
+                        myvnet => { tag => "100", type => "vnet", zone => "myzone" },
+                      },
+             },
+
+  zones   => {
+               ids => { myzone => { ipam => "pve", type => "evpn", controller => "evpnctl", 'vrf-vxlan' => 1000, 'mac' => 'A2:1D:CB:1A:C0:8B' } },
+             },
+  controllers  => {
+               ids => { evpnctl => { type => "evpn", 'peers' => '192.168.0.1,192.168.0.2,192.168.0.3', asn => "65000" } },
+             },
+
+  subnets => {
+              ids => { 'myzone-10.0.0.0-24' => {
+							'type' => 'subnet',
+							'vnet' => 'myvnet',
+							'gateway' => '10.0.0.1',
+						  }
+		     }
+	     }
+}
+
+
diff --git a/src/test/zones/vxlan/underlay_mtu/expected_sdn_interfaces b/src/test/zones/vxlan/underlay_mtu/expected_sdn_interfaces
new file mode 100644
index 000000000000..425021084781
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu/expected_sdn_interfaces
@@ -0,0 +1,16 @@
+#version:1
+
+auto myvnet
+iface myvnet
+	bridge_ports vxlan_myvnet
+	bridge_stp off
+	bridge_fd 0
+	mtu 8950
+
+auto vxlan_myvnet
+iface vxlan_myvnet
+	vxlan-id 100
+	vxlan-local-tunnelip 192.168.0.1
+	vxlan_remoteip 192.168.0.2
+	vxlan_remoteip 192.168.0.3
+	mtu 8950
diff --git a/src/test/zones/vxlan/underlay_mtu/interfaces b/src/test/zones/vxlan/underlay_mtu/interfaces
new file mode 100644
index 000000000000..c32f92e1a7fc
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu/interfaces
@@ -0,0 +1,8 @@
+auto vmbr0
+iface vmbr0 inet static
+	address 192.168.0.1/24
+	gateway 192.168.0.254
+	mtu 9000
+        bridge-ports eth0
+        bridge-stp off
+        bridge-fd 0
diff --git a/src/test/zones/vxlan/underlay_mtu/sdn_config b/src/test/zones/vxlan/underlay_mtu/sdn_config
new file mode 100644
index 000000000000..f929304206c9
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu/sdn_config
@@ -0,0 +1,11 @@
+{
+  version => 1,
+  vnets   => {
+               ids => {
+                        myvnet => { tag => 100, type => "vnet", zone => "myzone" },
+                      },
+             },
+  zones   => {
+               ids => { myzone => { ipam => "pve", type => "vxlan", peers => "192.168.0.1,192.168.0.2,192.168.0.3" } },
+             },
+}
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 05/21] sdn: zones: account for IPv6 in the VXLAN and EVPN MTU
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (3 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 04/21] sdn: zones: take the VXLAN and EVPN MTU from the underlay interface Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 06/21] sdn: dhcp: make the lease time configurable per subnet Hannes Laimer
                   ` (15 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

VXLAN encapsulation takes 50 bytes over IPv4 and 70 over IPv6, since
the IPv6 header is 20 bytes larger. The MTU of a VXLAN or EVPN zone
without its own setting always had 50 taken off, so over an IPv6
underlay it came out 20 bytes too large.

The encapsulation now follows the address family of the local tunnel
address. A zone with an IPv6 underlay and no MTU of its own gets 1430
where it got 1450, or its underlay interface's MTU minus 70.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/PVE/Network/SDN/Zones/EvpnPlugin.pm         |  2 +-
 src/PVE/Network/SDN/Zones/VxlanPlugin.pm        | 16 +++++++++-------
 .../evpn/ipv6underlay/expected_sdn_interfaces   |  8 ++++----
 .../expected_sdn_interfaces                     |  8 ++++----
 .../expected_sdn_interfaces                     |  8 ++++----
 .../zones/vxlan/ipv6/expected_sdn_interfaces    |  4 ++--
 .../underlay_mtu_ipv6/expected_sdn_interfaces   | 16 ++++++++++++++++
 .../zones/vxlan/underlay_mtu_ipv6/interfaces    |  8 ++++++++
 .../zones/vxlan/underlay_mtu_ipv6/sdn_config    | 17 +++++++++++++++++
 9 files changed, 65 insertions(+), 22 deletions(-)
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/expected_sdn_interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/interfaces
 create mode 100644 src/test/zones/vxlan/underlay_mtu_ipv6/sdn_config

diff --git a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
index 1720e1ff5735..9a85a9d9bf72 100644
--- a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
@@ -219,7 +219,7 @@ sub generate_sdn_config {
     my $exitnodes_local_routing = $plugin_config->{'exitnodes-local-routing'};
 
     my $mtu = PVE::Network::SDN::Zones::VxlanPlugin::vxlan_mtu(
-        $plugin_config, $iface, $interfaces_config,
+        $plugin_config, $iface, $interfaces_config, $ifaceip,
     );
 
     #vxlan interface
diff --git a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
index 4992757c1c5b..d8301bac0f3a 100644
--- a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
@@ -49,15 +49,17 @@ sub properties {
 }
 
 # the vnet bridge takes the underlay interface's MTU minus the vxlan
-# encapsulation where the peers name a local interface, the default
-# otherwise. An explicit zone MTU wins
+# encapsulation where the peers name a local interface, and 1500 minus the
+# encapsulation otherwise. The encapsulation takes 50 bytes over IPv4 and 70
+# over IPv6, by the family of the local tunnel address. An explicit zone MTU
+# wins
 sub vxlan_mtu {
-    my ($plugin_config, $iface, $interfaces_config) = @_;
+    my ($plugin_config, $iface, $interfaces_config, $ifaceip) = @_;
 
     return $plugin_config->{mtu} if $plugin_config->{mtu};
-    return $interfaces_config->{ifaces}->{$iface}->{mtu} - 50
-        if $iface && $interfaces_config->{ifaces}->{$iface}->{mtu};
-    return 1450;
+    my $family = PVE::Network::SDN::Zones::Plugin::ip_family($ifaceip) // 4;
+    my $underlay = ($iface && $interfaces_config->{ifaces}->{$iface}->{mtu}) || 1500;
+    return $underlay - ($family == 6 ? 70 : 50);
 }
 
 sub options {
@@ -132,7 +134,7 @@ sub generate_sdn_config {
         die "neither peers nor fabric configured for VXLAN zone $plugin_config->{id}";
     }
 
-    my $mtu = vxlan_mtu($plugin_config, $iface, $interfaces_config);
+    my $mtu = vxlan_mtu($plugin_config, $iface, $interfaces_config, $ifaceip);
 
     #vxlan interface
     my @iface_config = ();
diff --git a/src/test/zones/evpn/ipv6underlay/expected_sdn_interfaces b/src/test/zones/evpn/ipv6underlay/expected_sdn_interfaces
index 3b91f75eb3dd..c39cd77209ab 100644
--- a/src/test/zones/evpn/ipv6underlay/expected_sdn_interfaces
+++ b/src/test/zones/evpn/ipv6underlay/expected_sdn_interfaces
@@ -7,7 +7,7 @@ iface myvnet
 	bridge_ports vxlan_myvnet
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	ip6-forward on
 	arp-accept on
 	vrf vrf_myzone
@@ -22,7 +22,7 @@ iface vrfbr_myzone
 	bridge-ports vrfvx_myzone
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	vrf vrf_myzone
 
 auto vrfvx_myzone
@@ -31,7 +31,7 @@ iface vrfvx_myzone
 	vxlan-local-tunnelip 2a08:2200:100:1::10
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
 
 auto vxlan_myvnet
 iface vxlan_myvnet
@@ -39,4 +39,4 @@ iface vxlan_myvnet
 	vxlan-local-tunnelip 2a08:2200:100:1::10
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
diff --git a/src/test/zones/evpn/openfabric_fabric_ipv6/expected_sdn_interfaces b/src/test/zones/evpn/openfabric_fabric_ipv6/expected_sdn_interfaces
index d01771386658..6286fea4052b 100644
--- a/src/test/zones/evpn/openfabric_fabric_ipv6/expected_sdn_interfaces
+++ b/src/test/zones/evpn/openfabric_fabric_ipv6/expected_sdn_interfaces
@@ -7,7 +7,7 @@ iface vnet0
 	bridge_ports vxlan_vnet0
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	ip-forward on
 	arp-accept on
 	vrf vrf_evpn
@@ -22,7 +22,7 @@ iface vrfbr_evpn
 	bridge-ports vrfvx_evpn
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	vrf vrf_evpn
 
 auto vrfvx_evpn
@@ -31,7 +31,7 @@ iface vrfvx_evpn
 	vxlan-local-tunnelip fd00::1
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
 
 auto vxlan_vnet0
 iface vxlan_vnet0
@@ -39,7 +39,7 @@ iface vxlan_vnet0
 	vxlan-local-tunnelip fd00::1
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
 
 auto dummy_test
 iface dummy_test inet static
diff --git a/src/test/zones/evpn/openfabric_fabric_ipv6_only/expected_sdn_interfaces b/src/test/zones/evpn/openfabric_fabric_ipv6_only/expected_sdn_interfaces
index 51507d7d3fbe..6e56e9cda300 100644
--- a/src/test/zones/evpn/openfabric_fabric_ipv6_only/expected_sdn_interfaces
+++ b/src/test/zones/evpn/openfabric_fabric_ipv6_only/expected_sdn_interfaces
@@ -7,7 +7,7 @@ iface vnet0
 	bridge_ports vxlan_vnet0
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	ip-forward on
 	arp-accept on
 	vrf vrf_evpn
@@ -22,7 +22,7 @@ iface vrfbr_evpn
 	bridge-ports vrfvx_evpn
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 	vrf vrf_evpn
 
 auto vrfvx_evpn
@@ -31,7 +31,7 @@ iface vrfvx_evpn
 	vxlan-local-tunnelip fd00::1
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
 
 auto vxlan_vnet0
 iface vxlan_vnet0
@@ -39,7 +39,7 @@ iface vxlan_vnet0
 	vxlan-local-tunnelip fd00::1
 	bridge-learning off
 	bridge-arp-nd-suppress on
-	mtu 1450
+	mtu 1430
 
 auto dummy_test
 iface dummy_test inet6 static
diff --git a/src/test/zones/vxlan/ipv6/expected_sdn_interfaces b/src/test/zones/vxlan/ipv6/expected_sdn_interfaces
index 14354f61f923..85ea38b59502 100644
--- a/src/test/zones/vxlan/ipv6/expected_sdn_interfaces
+++ b/src/test/zones/vxlan/ipv6/expected_sdn_interfaces
@@ -5,7 +5,7 @@ iface myvnet
 	bridge_ports vxlan_myvnet
 	bridge_stp off
 	bridge_fd 0
-	mtu 1450
+	mtu 1430
 
 auto vxlan_myvnet
 iface vxlan_myvnet
@@ -13,4 +13,4 @@ iface vxlan_myvnet
 	vxlan-local-tunnelip 2a08:2200:100:1::10
 	vxlan_remoteip 2a08:2200:100:1::11
 	vxlan_remoteip 2a08:2200:100:1::12
-	mtu 1450
+	mtu 1430
diff --git a/src/test/zones/vxlan/underlay_mtu_ipv6/expected_sdn_interfaces b/src/test/zones/vxlan/underlay_mtu_ipv6/expected_sdn_interfaces
new file mode 100644
index 000000000000..9a3b009459a8
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu_ipv6/expected_sdn_interfaces
@@ -0,0 +1,16 @@
+#version:1
+
+auto myvnet
+iface myvnet
+	bridge_ports vxlan_myvnet
+	bridge_stp off
+	bridge_fd 0
+	mtu 8930
+
+auto vxlan_myvnet
+iface vxlan_myvnet
+	vxlan-id 100
+	vxlan-local-tunnelip 2a08:2200:100:1::10
+	vxlan_remoteip 2a08:2200:100:1::11
+	vxlan_remoteip 2a08:2200:100:1::12
+	mtu 8930
diff --git a/src/test/zones/vxlan/underlay_mtu_ipv6/interfaces b/src/test/zones/vxlan/underlay_mtu_ipv6/interfaces
new file mode 100644
index 000000000000..1f61faea7fc5
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu_ipv6/interfaces
@@ -0,0 +1,8 @@
+auto vmbr0
+iface vmbr0 inet6 static
+	address 2a08:2200:100:1::10/64
+	gateway 2a08:2200:100:1::1
+	mtu 9000
+        bridge-ports eth0
+        bridge-stp off
+        bridge-fd 0
diff --git a/src/test/zones/vxlan/underlay_mtu_ipv6/sdn_config b/src/test/zones/vxlan/underlay_mtu_ipv6/sdn_config
new file mode 100644
index 000000000000..484be230512d
--- /dev/null
+++ b/src/test/zones/vxlan/underlay_mtu_ipv6/sdn_config
@@ -0,0 +1,17 @@
+{
+  version => 1,
+  vnets   => {
+               ids => {
+                        myvnet => { tag => 100, type => "vnet", zone => "myzone" },
+                      },
+             },
+  zones   => {
+               ids => {
+                        myzone => {
+                                    ipam => "pve",
+                                    type => "vxlan",
+                                    peers => "2a08:2200:100:1::10,2a08:2200:100:1::11,2a08:2200:100:1::12",
+                                  },
+                      },
+             },
+}
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 06/21] sdn: dhcp: make the lease time configurable per subnet
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (4 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 05/21] sdn: zones: account for IPv6 in the VXLAN and EVPN MTU Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 07/21] sdn: dhcp: require a backend only if a zone on this node uses it Hannes Laimer
                   ` (14 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

dnsmasq hands out infinite leases, so a guest asks for its address
again only at its next reboot or network restart. A finite lease makes
it renew within the lease time. An address changed in the IPAM goes to
dnsmasq on the guest's node, so the guest picks up the new address at
its next renewal.

A subnet without a lease time keeps infinite leases.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
Reviewed-by: Stefan Hanreich <s.hanreich@proxmox.com>
Tested-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 src/PVE/Network/SDN/Dhcp/Dnsmasq.pm |  3 +-
 src/PVE/Network/SDN/SubnetPlugin.pm | 11 +++++++
 src/test/run_test_vnets_blackbox.pl | 51 +++++++++++++++++++++++++++++
 3 files changed, 64 insertions(+), 1 deletion(-)

diff --git a/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm b/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
index e99bfa75e506..491c7cb1789b 100644
--- a/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
+++ b/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
@@ -232,7 +232,8 @@ sub configure_subnet {
         $mask = join('.', unpack("C4", pack("N", $mask)));
     }
 
-    push @{$config}, "dhcp-range=set:$tag,$network,static,$mask,infinite";
+    my $lease = $subnet_config->{'dhcp-lease-time'} // 'infinite';
+    push @{$config}, "dhcp-range=set:$tag,$network,static,$mask,$lease";
 
     my $option_string;
     if (ip_is_ipv6($subnet_config->{network})) {
diff --git a/src/PVE/Network/SDN/SubnetPlugin.pm b/src/PVE/Network/SDN/SubnetPlugin.pm
index e2a0e50d0211..29edf7b65330 100644
--- a/src/PVE/Network/SDN/SubnetPlugin.pm
+++ b/src/PVE/Network/SDN/SubnetPlugin.pm
@@ -177,6 +177,16 @@ sub properties {
             description => 'IP address for the DNS server',
             optional => 1,
         },
+        'dhcp-lease-time' => {
+            type => 'integer',
+            minimum => 60,
+            maximum => 4294967295,
+            description =>
+                'Lease time in seconds for DHCP answers. Without it dnsmasq hands out'
+                . ' infinite leases, and it raises anything below two minutes to two'
+                . ' minutes.',
+            optional => 1,
+        },
     };
 }
 
@@ -189,6 +199,7 @@ sub options {
         dnszoneprefix => { optional => 1 },
         'dhcp-range' => { optional => 1 },
         'dhcp-dns-server' => { optional => 1 },
+        'dhcp-lease-time' => { optional => 1 },
     };
 }
 
diff --git a/src/test/run_test_vnets_blackbox.pl b/src/test/run_test_vnets_blackbox.pl
index b00be65bae48..64215d68a005 100755
--- a/src/test/run_test_vnets_blackbox.pl
+++ b/src/test/run_test_vnets_blackbox.pl
@@ -396,6 +396,11 @@ sub create_dhcp_subnet {
     });
 }
 
+sub update_subnet {
+    my ($params) = @_;
+    PVE::API2::Network::SDN::Subnets->update($params);
+}
+
 sub get_ipam_entries {
     return PVE::API2::Network::SDN::Ipams->ipamindex({ ipam => "pve" });
 }
@@ -1374,6 +1379,52 @@ sub test_failed_mapping_push {
 
 run_test(\&test_failed_mapping_push);
 
+sub test_dnsmasq_lease_time {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+
+    # the subnet's lease time reaches the range, and infinite stays the default
+    create_zone({
+        type => "simple",
+        dhcp => "dnsmasq",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+    my $range = sub {
+        my $subnets = PVE::Network::SDN::Vnets::get_subnets($vnetid, 1);
+        my $config = [];
+        for my $id (sort keys %$subnets) {
+            PVE::Network::SDN::Dhcp::Dnsmasq->configure_subnet(
+                $config, $zoneid, $vnetid, $subnets->{$id},
+            );
+        }
+        my ($line) = grep { m/^dhcp-range=/ } @$config;
+        return $line;
+    };
+    like($range->(), qr/,infinite$/, "$test_name: no lease time means infinite leases");
+    update_subnet({
+        vnet => $vnetid,
+        subnet => "$zoneid-10.0.0.0-24",
+        'dhcp-lease-time' => 300,
+    });
+    like($range->(), qr/,300$/, "$test_name: the lease time reaches the range");
+}
+
+run_test(\&test_dnsmasq_lease_time);
+
 sub test_mapping_edit_target {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
     my $zoneid = "TESTZONE";
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 07/21] sdn: dhcp: require a backend only if a zone on this node uses it
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (5 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 06/21] sdn: dhcp: make the lease time configurable per subnet Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 08/21] bpf: add the build, the package and a native harness for BPF programs Hannes Laimer
                   ` (13 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

A network reload failed on a node without the dnsmasq package as soon
as any zone had DHCP, even a zone confined to other nodes. On a node
with dnsmasq, the reload wrote such a zone's configuration and started
an instance for it, although none of the zone's vnets exist there.

A reload now skips the zones confined to other nodes, so a backend is
required and started only for the zones on the reloading node.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
Reviewed-by: Stefan Hanreich <s.hanreich@proxmox.com>
Tested-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 src/PVE/Network/SDN/Dhcp.pm         | 13 +++++++--
 src/test/run_test_vnets_blackbox.pl | 43 +++++++++++++++++++++++++++++
 2 files changed, 53 insertions(+), 3 deletions(-)

diff --git a/src/PVE/Network/SDN/Dhcp.pm b/src/PVE/Network/SDN/Dhcp.pm
index a986408ecbfa..d00f0b960de8 100644
--- a/src/PVE/Network/SDN/Dhcp.pm
+++ b/src/PVE/Network/SDN/Dhcp.pm
@@ -79,17 +79,24 @@ sub regenerate_config {
 
     my $plugins = PVE::Network::SDN::Dhcp::Plugin->lookup_types();
 
-    my $any_zone_needs_dhcp = grep { $_->{dhcp} } values $zone_cfg->{ids}->%*;
+    my %plugin_needed = ();
+    for my $zone (values $zone_cfg->{ids}->%*) {
+        next if !$zone->{dhcp};
+        # a zone confined to other nodes runs no backend here
+        next if defined($zone->{nodes}) && !$zone->{nodes}->{$nodename};
+        $plugin_needed{ $zone->{dhcp} } = 1;
+    }
 
     foreach my $plugin_name (@$plugins) {
         my $plugin = PVE::Network::SDN::Dhcp::Plugin->lookup($plugin_name);
-        eval { $plugin->before_regenerate(!$any_zone_needs_dhcp) };
+        eval { $plugin->before_regenerate(!$plugin_needed{$plugin_name}) };
         die "Could not run before_regenerate for DHCP plugin $plugin_name $@\n" if $@;
     }
 
     foreach my $zoneid (sort keys %{ $zone_cfg->{ids} }) {
         my $zone = $zone_cfg->{ids}->{$zoneid};
         next if !$zone->{dhcp};
+        next if defined($zone->{nodes}) && !$zone->{nodes}->{$nodename};
 
         my $dhcp_plugin_name = $zone->{dhcp};
         my $dhcp_plugin = PVE::Network::SDN::Dhcp::Plugin->lookup($dhcp_plugin_name);
@@ -130,7 +137,7 @@ sub regenerate_config {
             warn "Could not configure vnet $vnetid: $@\n" if $@;
         }
 
-        eval { $dhcp_plugin->after_configure($zoneid, !$any_zone_needs_dhcp) };
+        eval { $dhcp_plugin->after_configure($zoneid, !$plugin_needed{$dhcp_plugin_name}) };
         warn "Could not run after_configure for DHCP server $zoneid $@\n" if $@;
 
     }
diff --git a/src/test/run_test_vnets_blackbox.pl b/src/test/run_test_vnets_blackbox.pl
index 64215d68a005..0d8e760561d2 100755
--- a/src/test/run_test_vnets_blackbox.pl
+++ b/src/test/run_test_vnets_blackbox.pl
@@ -109,6 +109,13 @@ my $mocked_pve_sdn;
 $mocked_pve_sdn = Test::MockModule->new('PVE::Network::SDN');
 $mocked_pve_sdn->mock(
     cfs_lock_file => $mocked_cfs_lock_file,
+    running_config => sub {
+        return {
+            zones => $test_state->{zones_config},
+            vnets => $test_state->{vnets_config},
+            subnets => $test_state->{subnets_config},
+        };
+    },
 );
 
 my $mocked_pve_tools = Test::MockModule->new('PVE::Tools');
@@ -1425,6 +1432,42 @@ sub test_dnsmasq_lease_time {
 
 run_test(\&test_dnsmasq_lease_time);
 
+sub test_dhcp_backend_needed_per_node {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+
+    # a backend is told whether a zone on this node uses it. A zone confined
+    # to other nodes runs nothing here
+    my $asked = [];
+    my $configured = [];
+    $mocked_sdn_dhcp_dnsmasq->mock(
+        before_regenerate => sub { push @$asked, $_[1] ? 'optional' : 'needed'; },
+        after_configure => sub { push @$configured, $_[1]; },
+    );
+    create_zone({
+        type => "simple",
+        dhcp => "dnsmasq",
+        ipam => "pve",
+        zone => "DNSZONE",
+        nodes => 'other',
+    });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff(
+        $asked,
+        ['optional'],
+        "$test_name: a dnsmasq zone confined elsewhere needs no dnsmasq here",
+    );
+    eq_or_diff($configured, [], "$test_name: and is not configured here");
+
+    @$asked = ();
+    update_zone("DNSZONE", { delete => 'nodes' });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff($asked, ['needed'], "$test_name: a dnsmasq zone on this node needs it");
+    eq_or_diff($configured, ['DNSZONE'], "$test_name: and is configured");
+    $mocked_sdn_dhcp_dnsmasq->unmock($_) for qw(before_regenerate after_configure);
+}
+
+run_test(\&test_dhcp_backend_needed_per_node);
+
 sub test_mapping_edit_target {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
     my $zoneid = "TESTZONE";
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 08/21] bpf: add the build, the package and a native harness for BPF programs
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (6 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 07/21] sdn: dhcp: require a backend only if a zone on this node uses it Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 09/21] sdn: dhcp: add the per-tap DHCPv4 responder program Hannes Laimer
                   ` (12 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The SDN stack's BPF programs are C sources under src/bpf, one
directory per subsystem. They are compiled for the BPF target, and the
new pve-network-ebpf package installs the objects to
/usr/lib/proxmox-ebpf. The proxmox-ebpf library loads them from there
at runtime. So a program change ships with this package alone, without
a new build of the library or of pve-rs. BPF bytecode is the same on
every host architecture, so the package is architecture independent.

The order file next to the sources lists the subsystems in the order
their programs run on an interface, and is installed with the objects.

The test harness compiles the programs natively against shim headers,
so tests call them as plain functions with the kernel helpers mocked.
It runs with the package's tests and needs cargo only for them.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 .gitignore                                |   3 +
 Makefile                                  |   1 +
 debian/control                            |  13 ++
 debian/pve-network-ebpf.install           |   1 +
 debian/pve-network-ebpf.lintian-overrides |   2 +
 src/Makefile                              |   3 +-
 src/bpf/Makefile                          |  37 ++++
 src/bpf/harness/Cargo.toml                |   8 +
 src/bpf/harness/build.rs                  | 101 +++++++++++
 src/bpf/harness/shim/bpf/bpf_helpers.h    |  34 ++++
 src/bpf/harness/shim/bpf_debug.h          |  10 ++
 src/bpf/harness/shim/linux/bpf.h          |  25 +++
 src/bpf/harness/tests/bpf/fixture.bpf.c   |  37 ++++
 src/bpf/harness/tests/common/mod.rs       | 208 ++++++++++++++++++++++
 src/bpf/harness/tests/harness.rs          |  84 +++++++++
 src/bpf/include/bpf_debug.h               |  12 ++
 src/bpf/order                             |   0
 17 files changed, 578 insertions(+), 1 deletion(-)
 create mode 100644 debian/pve-network-ebpf.install
 create mode 100644 debian/pve-network-ebpf.lintian-overrides
 create mode 100644 src/bpf/Makefile
 create mode 100644 src/bpf/harness/Cargo.toml
 create mode 100644 src/bpf/harness/build.rs
 create mode 100644 src/bpf/harness/shim/bpf/bpf_helpers.h
 create mode 100644 src/bpf/harness/shim/bpf_debug.h
 create mode 100644 src/bpf/harness/shim/linux/bpf.h
 create mode 100644 src/bpf/harness/tests/bpf/fixture.bpf.c
 create mode 100644 src/bpf/harness/tests/common/mod.rs
 create mode 100644 src/bpf/harness/tests/harness.rs
 create mode 100644 src/bpf/include/bpf_debug.h
 create mode 100644 src/bpf/order

diff --git a/.gitignore b/.gitignore
index 4694865f324f..852fbae7396f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,6 @@
 /.vscode/
 /libpve-network-perl-[0-9]*/
 /libpve-network-perl_[0-9]*.tar.xz
+/src/bpf/*.bpf.o
+/src/bpf/harness/Cargo.lock
+/src/bpf/harness/target/
diff --git a/Makefile b/Makefile
index 9ced6fa0f9dd..77e04517f455 100644
--- a/Makefile
+++ b/Makefile
@@ -7,6 +7,7 @@ BUILDDIR ?= $(PACKAGE)-$(DEB_VERSION_UPSTREAM)
 DEBS=\
       $(PACKAGE)_$(DEB_VERSION_UPSTREAM_REVISION)_all.deb \
       libpve-network-api-perl_$(DEB_VERSION_UPSTREAM_REVISION)_all.deb \
+      pve-network-ebpf_$(DEB_VERSION_UPSTREAM_REVISION)_all.deb \
 
 DSC=$(PACKAGE)_$(DEB_VERSION_UPSTREAM_REVISION).dsc
 
diff --git a/debian/control b/debian/control
index bcdc8e50fe76..03c4b60ca7e8 100644
--- a/debian/control
+++ b/debian/control
@@ -3,7 +3,10 @@ Section: perl
 Priority: optional
 Maintainer: Proxmox Support Team <support@proxmox.com>
 Build-Depends: debhelper-compat (= 13),
+               cargo <!nocheck>,
+               clang-21,
                lintian,
+               libbpf-dev,
                libfile-slurp-perl,
                libpve-common-perl (>= 9.2.4),
                libpve-guest-common-perl,
@@ -12,10 +15,12 @@ Build-Depends: debhelper-compat (= 13),
                libtest-mockmodule-perl,
                libtest-differences-perl,
                perl,
+               proxmox-kernel-libc-dev,
                pve-cluster (>= 9.0.1),
                pve-firewall (>= 5.1.0~),
                pve-doc-generator (>= 5.3-3),
                libpve-access-control (>= 9.0.1),
+               rustc <!nocheck>,
 Standards-Version: 4.6.1
 Homepage: https://www.proxmox.com
 
@@ -54,3 +59,11 @@ Replaces: libpve-network-perl (<< 0.9.9~),
 Description: API endpoints for Proxmox VE's SDN stack
  This package contains the API endpoints for the Software Defined Network of
  Proxmox VE.
+
+Package: pve-network-ebpf
+Architecture: all
+Depends: ${misc:Depends},
+Description: eBPF programs of Proxmox VE's SDN stack
+ This package contains the compiled eBPF programs of the Software Defined
+ Network implementation for Proxmox VE and the order they run in on an
+ interface.
diff --git a/debian/pve-network-ebpf.install b/debian/pve-network-ebpf.install
new file mode 100644
index 000000000000..2fa0a689b253
--- /dev/null
+++ b/debian/pve-network-ebpf.install
@@ -0,0 +1 @@
+usr/lib/proxmox-ebpf
diff --git a/debian/pve-network-ebpf.lintian-overrides b/debian/pve-network-ebpf.lintian-overrides
new file mode 100644
index 000000000000..0f148a600654
--- /dev/null
+++ b/debian/pve-network-ebpf.lintian-overrides
@@ -0,0 +1,2 @@
+# BPF bytecode, the same on every host architecture
+pve-network-ebpf: arch-independent-package-contains-binary-or-object [usr/lib/proxmox-ebpf/*.bpf.o]
diff --git a/src/Makefile b/src/Makefile
index c4056b480251..9b3074780f47 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -1,4 +1,4 @@
-SUBDIRS := PVE services
+SUBDIRS := PVE services bpf
 
 all:
 	set -e && for i in $(SUBDIRS); do $(MAKE) -C $$i; done
@@ -11,6 +11,7 @@ clean:
 .PHONY: test
 test:
 	$(MAKE) -C $@
+	$(MAKE) -C bpf $@
 
 .PHONY: install
 install:
diff --git a/src/bpf/Makefile b/src/bpf/Makefile
new file mode 100644
index 000000000000..c22a43b1b7d7
--- /dev/null
+++ b/src/bpf/Makefile
@@ -0,0 +1,37 @@
+BPFDIR = $(DESTDIR)/usr/lib/proxmox-ebpf
+
+CLANG = clang-21
+
+MULTIARCH := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
+
+SOURCES := $(wildcard */*.bpf.c)
+OBJECTS := $(patsubst %.c,%.o,$(notdir $(SOURCES)))
+HEADERS := $(wildcard include/*.h */*.h)
+
+# -g makes clang emit the BTF the loader needs. The UAPI headers reach asm/ through the multiarch
+# directory, which clang searches for the host target only
+BPF_CFLAGS = -O2 -g -Wall -target bpf -I include -I /usr/include/$(MULTIARCH)
+ifeq ($(BPF_DEBUG),1)
+BPF_CFLAGS += -DBPF_DEBUG
+endif
+
+vpath %.bpf.c $(dir $(SOURCES))
+
+all: $(OBJECTS)
+
+%.bpf.o: %.bpf.c $(HEADERS)
+	$(CLANG) $(BPF_CFLAGS) -I $(<D) -c $< -o $@
+
+.PHONY: test
+test:
+	cd harness && CLANG=$(CLANG) cargo test --offline
+
+.PHONY: install
+install: $(OBJECTS)
+	install -d $(BPFDIR)
+	install -t $(BPFDIR) -m 0644 $(OBJECTS) order
+
+.PHONY: clean
+clean:
+	rm -f *.bpf.o
+	rm -rf harness/target harness/Cargo.lock
diff --git a/src/bpf/harness/Cargo.toml b/src/bpf/harness/Cargo.toml
new file mode 100644
index 000000000000..061e9b5a6a6b
--- /dev/null
+++ b/src/bpf/harness/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "bpf-harness"
+description = "Runs the BPF C programs natively as plain functions in tests"
+version = "0.0.0"
+edition = "2024"
+publish = false
+
+[workspace]
diff --git a/src/bpf/harness/build.rs b/src/bpf/harness/build.rs
new file mode 100644
index 000000000000..2cf09b421b3d
--- /dev/null
+++ b/src/bpf/harness/build.rs
@@ -0,0 +1,101 @@
+use std::env;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+fn main() {
+    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
+    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
+    let bpf_dir = manifest_dir.parent().expect("harness/ has a parent");
+    let global_include = bpf_dir.join("include");
+    let shim_include = manifest_dir.join("shim");
+
+    println!("cargo:rerun-if-changed=build.rs");
+    println!("cargo:rerun-if-env-changed=CLANG");
+    println!("cargo:rerun-if-changed={}", shim_include.display());
+    println!("cargo:rerun-if-changed={}", global_include.display());
+    // a new program comes with a line in this file
+    println!("cargo:rerun-if-changed={}", bpf_dir.join("order").display());
+
+    let mut program_dirs: Vec<PathBuf> = std::fs::read_dir(bpf_dir)
+        .expect("read the BPF directory")
+        .map(|entry| entry.expect("read the BPF directory entry").path())
+        .filter(|path| path.is_dir())
+        .collect();
+    program_dirs.push(manifest_dir.join("tests").join("bpf"));
+
+    let mut native_objs = Vec::new();
+    for dir in &program_dirs {
+        for entry in std::fs::read_dir(dir).expect("read a program directory") {
+            let path = entry.expect("read a program directory entry").path();
+            let is_program = path
+                .file_name()
+                .and_then(|s| s.to_str())
+                .is_some_and(|s| s.ends_with(".bpf.c"));
+            if !is_program {
+                continue;
+            }
+            println!("cargo:rerun-if-changed={}", dir.display());
+            native_objs.push(compile_native(
+                &path,
+                dir,
+                &global_include,
+                &shim_include,
+                &out_dir,
+            ));
+        }
+    }
+
+    // archived so a test binary only links the programs it references
+    let archive = out_dir.join("libbpf_native.a");
+    let _ = std::fs::remove_file(&archive);
+    let status = Command::new("ar")
+        .arg("rcs")
+        .arg(&archive)
+        .args(&native_objs)
+        .status()
+        .expect("failed to invoke ar");
+    assert!(
+        status.success(),
+        "ar failed to create {}",
+        archive.display()
+    );
+    println!("cargo:rustc-link-search=native={}", out_dir.display());
+    // the crate has no library target, so cargo passes this to every test
+    println!("cargo:rustc-link-lib=static=bpf_native");
+}
+
+// native build against the shim headers, so tests call the program as a plain function
+fn compile_native(
+    src: &Path,
+    local_include: &Path,
+    global_include: &Path,
+    shim_include: &Path,
+    out_dir: &Path,
+) -> PathBuf {
+    let stem = src.file_stem().unwrap().to_str().unwrap();
+    let obj_path = out_dir.join(format!("{stem}.native.o"));
+
+    // the Makefile hands over the compiler it builds the BPF objects with
+    let clang = env::var("CLANG").unwrap_or_else(|_| "clang".to_string());
+    let status = Command::new(&clang)
+        .args(["-O2", "-g", "-Wall", "-fPIC"])
+        // shim first, it shadows linux/bpf.h and bpf_helpers.h
+        .arg("-I")
+        .arg(shim_include)
+        .arg("-I")
+        .arg(global_include)
+        .arg("-I")
+        .arg(local_include)
+        .arg("-c")
+        .arg(src)
+        .arg("-o")
+        .arg(&obj_path)
+        .status()
+        .unwrap_or_else(|e| panic!("failed to invoke {clang}: {e}"));
+    assert!(
+        status.success(),
+        "clang failed to compile {} natively",
+        src.display()
+    );
+    obj_path
+}
diff --git a/src/bpf/harness/shim/bpf/bpf_helpers.h b/src/bpf/harness/shim/bpf/bpf_helpers.h
new file mode 100644
index 000000000000..b4bcfdf5717f
--- /dev/null
+++ b/src/bpf/harness/shim/bpf/bpf_helpers.h
@@ -0,0 +1,34 @@
+#ifndef PROXMOX_EBPF_SHIM_BPF_HELPERS_H
+#define PROXMOX_EBPF_SHIM_BPF_HELPERS_H
+
+// Native stand-in for <bpf/bpf_helpers.h>. The helpers become plain extern
+// functions the test harness provides. Sections reduce to weak linkage so the
+// program objects can be linked into one test binary. Weak symbols of one
+// name link silently, so program and map names must stay distinct across
+// subsystems. The map definition macros keep their libbpf shapes, which are
+// plain C already.
+
+#include <linux/types.h>
+
+#define SEC(name) __attribute__((weak))
+#ifndef __always_inline
+#define __always_inline inline __attribute__((always_inline))
+#endif
+#define __uint(name, val) int(*name)[val]
+#define __type(name, val) typeof(val) *name
+
+#ifndef barrier_var
+#define barrier_var(var) asm volatile("" : "+r"(var))
+#endif
+
+// the value is irrelevant natively
+#define LIBBPF_PIN_BY_NAME 1
+
+extern void *bpf_map_lookup_elem(void *map, const void *key);
+extern long bpf_skb_load_bytes(const void *skb, __u32 offset, void *to, __u32 len);
+extern long bpf_skb_store_bytes(void *skb, __u32 offset, const void *from, __u32 len, __u64 flags);
+extern long bpf_skb_pull_data(void *skb, __u32 len);
+extern long bpf_skb_change_tail(void *skb, __u32 new_len, __u64 flags);
+extern long bpf_redirect(__u32 ifindex, __u64 flags);
+
+#endif
diff --git a/src/bpf/harness/shim/bpf_debug.h b/src/bpf/harness/shim/bpf_debug.h
new file mode 100644
index 000000000000..a7e5eac0d3b3
--- /dev/null
+++ b/src/bpf/harness/shim/bpf_debug.h
@@ -0,0 +1,10 @@
+#ifndef PROXMOX_EBPF_SHIM_BPF_DEBUG_H
+#define PROXMOX_EBPF_SHIM_BPF_DEBUG_H
+
+// Native stand-in for bpf_debug.h, debug printing is a no-op in tests.
+
+#define DBG(...)                                                                                   \
+    do {                                                                                           \
+    } while (0)
+
+#endif
diff --git a/src/bpf/harness/shim/linux/bpf.h b/src/bpf/harness/shim/linux/bpf.h
new file mode 100644
index 000000000000..ff259c329522
--- /dev/null
+++ b/src/bpf/harness/shim/linux/bpf.h
@@ -0,0 +1,25 @@
+#ifndef PROXMOX_EBPF_SHIM_LINUX_BPF_H
+#define PROXMOX_EBPF_SHIM_LINUX_BPF_H
+
+// Native stand-in for <linux/bpf.h>, only what the programs touch. The other UAPI headers
+// compile natively as they are.
+
+#include <linux/types.h>
+
+// data and data_end are wide enough for native pointers, keep in sync with SkBuff in
+// tests/common/mod.rs
+struct __sk_buff {
+    unsigned long data;
+    unsigned long data_end;
+    __u32 len;
+    __u32 ifindex;
+    __u32 mark;
+};
+
+// map-definition constants, the values are irrelevant natively
+enum {
+    BPF_MAP_TYPE_HASH = 1,
+};
+#define BPF_F_NO_PREALLOC 1
+
+#endif
diff --git a/src/bpf/harness/tests/bpf/fixture.bpf.c b/src/bpf/harness/tests/bpf/fixture.bpf.c
new file mode 100644
index 000000000000..d5fa96818d50
--- /dev/null
+++ b/src/bpf/harness/tests/bpf/fixture.bpf.c
@@ -0,0 +1,37 @@
+// The harness's own program, compiled against the shim like a subsystem's. It touches what a
+// subsystem program touches, the skb fields, the helpers and a map, so the shim is run by the
+// harness tests themselves.
+#include <linux/bpf.h>
+#include <linux/pkt_cls.h>
+#include <bpf/bpf_endian.h>
+#include <bpf/bpf_helpers.h>
+
+struct {
+    __uint(type, BPF_MAP_TYPE_HASH);
+    __uint(max_entries, 16);
+    __type(key, __u32);
+    __type(value, __u8);
+} fixture_stamps SEC(".maps");
+
+// writes the interface's stamp and the frame length over the first two bytes and keeps the
+// bytes they replaced in the mark, accepts a frame of an interface without a stamp as it is
+SEC("tc")
+int fixture(struct __sk_buff *skb)
+{
+    void *data = (void *)(long)skb->data;
+    void *data_end = (void *)(long)skb->data_end;
+    if (data + 2 > data_end)
+        return TC_ACT_OK;
+    __u8 *stamp = bpf_map_lookup_elem(&fixture_stamps, &skb->ifindex);
+    if (!stamp)
+        return TC_ACT_OK;
+    __u8 bytes[2];
+    if (bpf_skb_load_bytes(skb, 0, bytes, sizeof(bytes)))
+        return TC_ACT_OK;
+    skb->mark = bpf_ntohs(*(__be16 *)bytes);
+    bytes[0] = *stamp;
+    bytes[1] = skb->len;
+    if (bpf_skb_store_bytes(skb, 0, bytes, sizeof(bytes), 0))
+        return TC_ACT_OK;
+    return TC_ACT_UNSPEC;
+}
diff --git a/src/bpf/harness/tests/common/mod.rs b/src/bpf/harness/tests/common/mod.rs
new file mode 100644
index 000000000000..c4c1371e6a17
--- /dev/null
+++ b/src/bpf/harness/tests/common/mod.rs
@@ -0,0 +1,208 @@
+//! Native harness for the subsystems' BPF C programs. A test declares a program's symbol and
+//! calls it like a plain function on a fake skb, with the helpers as bounds-checked functions
+//! over its buffer and a per-thread map registry. Nothing here touches the kernel. A test of
+//! the pinned state or the links needs root and a kernel.
+
+// every test crate compiles the harness and uses its own part of it
+#![allow(dead_code)]
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::ffi::{c_int, c_long, c_void};
+
+pub const TC_ACT_UNSPEC: c_int = -1;
+pub const TC_ACT_OK: c_int = 0;
+pub const TC_ACT_REDIRECT: c_int = 7;
+
+pub const PKT_CAP: usize = 2048;
+
+/// Keep in sync with struct __sk_buff in shim/linux/bpf.h.
+#[repr(C)]
+pub struct SkBuff {
+    pub data: usize,
+    pub data_end: usize,
+    pub len: u32,
+    pub ifindex: u32,
+    pub mark: u32,
+}
+
+/// The skb handed to a program plus the buffer behind it. The helpers get the skb pointer and
+/// cast back to this, so the skb must stay the first field.
+#[repr(C)]
+pub struct TestSkb {
+    skb: SkBuff,
+    buf: Box<[u8; PKT_CAP]>,
+}
+
+impl TestSkb {
+    pub fn new(packet: &[u8], ifindex: u32) -> Self {
+        assert!(packet.len() <= PKT_CAP);
+        let mut buf = Box::new([0u8; PKT_CAP]);
+        buf[..packet.len()].copy_from_slice(packet);
+        let mut t = TestSkb {
+            skb: SkBuff {
+                data: 0,
+                data_end: 0,
+                len: packet.len() as u32,
+                ifindex,
+                mark: 0,
+            },
+            buf,
+        };
+        t.sync();
+        t
+    }
+
+    fn sync(&mut self) {
+        let base = self.buf.as_mut_ptr() as usize;
+        self.skb.data = base;
+        self.skb.data_end = base + self.skb.len as usize;
+    }
+
+    pub fn packet(&self) -> &[u8] {
+        &self.buf[..self.skb.len as usize]
+    }
+
+    pub fn mark(&self) -> u32 {
+        self.skb.mark
+    }
+
+    pub fn run(&mut self, prog: unsafe extern "C" fn(*mut SkBuff) -> c_int) -> c_int {
+        REDIRECTED.with(|r| *r.borrow_mut() = None);
+        unsafe { prog((self as *mut TestSkb).cast()) }
+    }
+}
+
+struct MockMap {
+    key_size: usize,
+    entries: HashMap<Vec<u8>, Box<[u8]>>,
+}
+
+thread_local! {
+    static MAPS: RefCell<HashMap<usize, MockMap>> = RefCell::new(HashMap::new());
+    static REDIRECTED: RefCell<Option<(u32, u64)>> = const { RefCell::new(None) };
+}
+
+pub fn register_map(map: *const c_void, key_size: usize) {
+    MAPS.with(|maps| {
+        maps.borrow_mut().insert(
+            map as usize,
+            MockMap {
+                key_size,
+                entries: HashMap::new(),
+            },
+        )
+    });
+}
+
+pub fn map_insert(map: *const c_void, key: &[u8], value: &[u8]) {
+    MAPS.with(|maps| {
+        let mut maps = maps.borrow_mut();
+        let m = maps.get_mut(&(map as usize)).expect("map not registered");
+        assert_eq!(key.len(), m.key_size);
+        m.entries.insert(key.to_vec(), value.into());
+    });
+}
+
+/// The ifindex of the redirect the last run issued, if any.
+pub fn redirected() -> Option<u32> {
+    REDIRECTED.with(|r| r.borrow().map(|(ifindex, _)| ifindex))
+}
+
+/// The flags of the redirect the last run issued, zero sends out of the interface.
+pub fn redirect_flags() -> Option<u64> {
+    REDIRECTED.with(|r| r.borrow().map(|(_, flags)| flags))
+}
+
+unsafe fn testskb<'a>(skb: *mut c_void) -> &'a mut TestSkb {
+    unsafe { &mut *(skb as *mut TestSkb) }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_map_lookup_elem(map: *mut c_void, key: *const c_void) -> *mut c_void {
+    MAPS.with(|maps| {
+        let mut maps = maps.borrow_mut();
+        let Some(m) = maps.get_mut(&(map as usize)) else {
+            panic!("lookup on unregistered map");
+        };
+        let key = unsafe { std::slice::from_raw_parts(key as *const u8, m.key_size) };
+        match m.entries.get_mut(key) {
+            // the box's heap allocation stays put while the registry holds it
+            Some(v) => v.as_mut_ptr() as *mut c_void,
+            None => std::ptr::null_mut(),
+        }
+    })
+}
+
+const ENOMEM: c_long = 12;
+const EFAULT: c_long = 14;
+const EINVAL: c_long = 22;
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_skb_load_bytes(
+    skb: *mut c_void,
+    offset: u32,
+    to: *mut c_void,
+    len: u32,
+) -> c_long {
+    let t = unsafe { testskb(skb) };
+    let (offset, len) = (offset as usize, len as usize);
+    if offset + len > t.skb.len as usize {
+        // the kernel clears the destination of a failed read
+        unsafe { std::ptr::write_bytes(to as *mut u8, 0, len) };
+        return -EFAULT;
+    }
+    unsafe { std::ptr::copy_nonoverlapping(t.buf.as_ptr().add(offset), to as *mut u8, len) };
+    0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_skb_store_bytes(
+    skb: *mut c_void,
+    offset: u32,
+    from: *const c_void,
+    len: u32,
+    _flags: u64,
+) -> c_long {
+    let t = unsafe { testskb(skb) };
+    let (offset, len) = (offset as usize, len as usize);
+    if offset + len > t.skb.len as usize {
+        return -EFAULT;
+    }
+    unsafe {
+        std::ptr::copy_nonoverlapping(from as *const u8, t.buf.as_mut_ptr().add(offset), len)
+    };
+    0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_skb_pull_data(skb: *mut c_void, len: u32) -> c_long {
+    // the buffer is always linear, pulling within it is a no-op
+    let t = unsafe { testskb(skb) };
+    if len > t.skb.len { -ENOMEM } else { 0 }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_skb_change_tail(skb: *mut c_void, new_len: u32, _flags: u64) -> c_long {
+    let t = unsafe { testskb(skb) };
+    // the kernel refuses to cut into the headers it knows, which is the link header here.
+    // Growing stops at the harness buffer
+    let min_len = 14;
+    if new_len < min_len || new_len as usize > PKT_CAP {
+        return -EINVAL;
+    }
+    // like the kernel, grown room reads as zeros
+    let old = t.skb.len as usize;
+    if new_len as usize > old {
+        t.buf[old..new_len as usize].fill(0);
+    }
+    t.skb.len = new_len;
+    t.sync();
+    0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_redirect(ifindex: u32, flags: u64) -> c_long {
+    REDIRECTED.with(|r| *r.borrow_mut() = Some((ifindex, flags)));
+    TC_ACT_REDIRECT as c_long
+}
diff --git a/src/bpf/harness/tests/harness.rs b/src/bpf/harness/tests/harness.rs
new file mode 100644
index 000000000000..470e0a1cd88b
--- /dev/null
+++ b/src/bpf/harness/tests/harness.rs
@@ -0,0 +1,84 @@
+//! The harness's own tests, the frame, the helpers, the map registry and a program built
+//! against the shim.
+mod common;
+
+use std::ffi::{c_int, c_void};
+
+use common::*;
+
+unsafe extern "C" {
+    fn fixture(skb: *mut SkBuff) -> c_int;
+    static fixture_stamps: c_void;
+}
+
+unsafe extern "C" fn pass(_skb: *mut SkBuff) -> c_int {
+    TC_ACT_UNSPEC
+}
+
+unsafe extern "C" fn accept(_skb: *mut SkBuff) -> c_int {
+    TC_ACT_OK
+}
+
+#[test]
+fn skb_round_trips_the_frame() {
+    let frame = [1u8, 2, 3, 4];
+    let mut skb = TestSkb::new(&frame, 7);
+    assert_eq!(skb.run(pass), TC_ACT_UNSPEC);
+    assert_eq!(skb.run(accept), TC_ACT_OK);
+    assert_eq!(skb.packet(), &frame);
+    assert_eq!(redirected(), None);
+    assert_eq!(redirect_flags(), None);
+}
+
+#[test]
+fn helpers_read_and_write_the_frame() {
+    let mut skb = TestSkb::new(&[1, 2, 3, 4, 5, 6], 7);
+    let raw = (&mut skb as *mut TestSkb).cast::<c_void>();
+    let mut out = [0u8; 2];
+    assert_eq!(bpf_skb_load_bytes(raw, 2, out.as_mut_ptr().cast(), 2), 0);
+    assert_eq!(out, [3, 4]);
+    assert_eq!(
+        bpf_skb_store_bytes(raw, 4, [9u8, 9].as_ptr().cast(), 2, 0),
+        0
+    );
+    assert_eq!(skb.packet(), &[1, 2, 3, 4, 9, 9]);
+    // past the frame, the kernel clears the destination on a failed load
+    assert_ne!(bpf_skb_load_bytes(raw, 5, out.as_mut_ptr().cast(), 2), 0);
+    assert_eq!(out, [0, 0]);
+    assert_ne!(
+        bpf_skb_store_bytes(raw, 5, [9u8, 9].as_ptr().cast(), 2, 0),
+        0
+    );
+    assert_eq!(skb.packet(), &[1, 2, 3, 4, 9, 9]);
+}
+
+#[test]
+fn maps_answer_registered_entries() {
+    // any address serves as a map's identity, the program hands the map's address to the helper
+    let map = 0x1000 as *const c_void;
+    register_map(map, 4);
+    map_insert(map, &7u32.to_ne_bytes(), &[9, 8, 7]);
+    let key = 7u32.to_ne_bytes();
+    let hit = bpf_map_lookup_elem(map.cast_mut(), key.as_ptr().cast());
+    assert!(!hit.is_null());
+    assert_eq!(
+        unsafe { std::slice::from_raw_parts(hit as *const u8, 3) },
+        &[9, 8, 7]
+    );
+    let key = 8u32.to_ne_bytes();
+    assert!(bpf_map_lookup_elem(map.cast_mut(), key.as_ptr().cast()).is_null());
+}
+
+#[test]
+fn a_program_runs_against_the_shim() {
+    let stamps = &raw const fixture_stamps;
+    register_map(stamps, 4);
+    map_insert(stamps, &7u32.to_ne_bytes(), &[0xab]);
+    let mut skb = TestSkb::new(&[0x12, 0x34, 5, 6], 9);
+    assert_eq!(skb.run(fixture), TC_ACT_OK);
+    assert_eq!(skb.packet(), &[0x12, 0x34, 5, 6]);
+    let mut skb = TestSkb::new(&[0x12, 0x34, 5, 6], 7);
+    assert_eq!(skb.run(fixture), TC_ACT_UNSPEC);
+    assert_eq!(skb.packet(), &[0xab, 4, 5, 6]);
+    assert_eq!(skb.mark(), 0x1234);
+}
diff --git a/src/bpf/include/bpf_debug.h b/src/bpf/include/bpf_debug.h
new file mode 100644
index 000000000000..29bd0b0f7ef9
--- /dev/null
+++ b/src/bpf/include/bpf_debug.h
@@ -0,0 +1,12 @@
+#ifndef BPF_DEBUG_H
+#define BPF_DEBUG_H
+
+#include <bpf/bpf_helpers.h>
+
+#ifdef BPF_DEBUG
+#define DBG(fmt, ...) bpf_printk(fmt, ##__VA_ARGS__)
+#else
+#define DBG(fmt, ...) ((void)0)
+#endif
+
+#endif
diff --git a/src/bpf/order b/src/bpf/order
new file mode 100644
index 000000000000..e69de29bb2d1
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 09/21] sdn: dhcp: add the per-tap DHCPv4 responder program
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (7 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 08/21] bpf: add the build, the package and a native harness for BPF programs Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 10/21] sdn: dhcp: add an eBPF backend answering on each guest interface Hannes Laimer
                   ` (11 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The program answers a guest's DISCOVER and REQUEST on the guest's own
tap from the record stored for that interface, so the exchange never
reaches the bridge. It keeps no lease state and needs no address of
the host in the guest's subnet. Only the NIC's own MAC gets the
record's address. A REQUEST for another address gets a NAK, which
ends a stale lease right away. Anything else passes on unchanged,
such as a REQUEST that selects another server or one from a network
the guest runs itself.

A tc program cannot create a packet, so the reply overwrites the
request and is sent out as that packet. The kernel then treats it as
it would have treated the request, and completes the UDP checksum on
the way out only if the guest sent with checksum offload. The field
has to hold the pseudo-header sum in that case and a valid checksum
otherwise, and the program cannot read which. It finds out by adding
one to a zeroed field through the kernel's checksum helper, whose
result differs between the two.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/bpf/dhcp/dhcp.bpf.c                | 393 ++++++++++++
 src/bpf/dhcp/types.h                   |  27 +
 src/bpf/harness/shim/bpf/bpf_helpers.h |   1 +
 src/bpf/harness/shim/linux/bpf.h       |   3 +
 src/bpf/harness/tests/common/mod.rs    |  69 ++-
 src/bpf/harness/tests/dhcp.rs          | 804 +++++++++++++++++++++++++
 src/bpf/harness/tests/harness.rs       |  14 +
 src/bpf/order                          |   1 +
 8 files changed, 1307 insertions(+), 5 deletions(-)
 create mode 100644 src/bpf/dhcp/dhcp.bpf.c
 create mode 100644 src/bpf/dhcp/types.h
 create mode 100644 src/bpf/harness/tests/dhcp.rs

diff --git a/src/bpf/dhcp/dhcp.bpf.c b/src/bpf/dhcp/dhcp.bpf.c
new file mode 100644
index 000000000000..edc160bed617
--- /dev/null
+++ b/src/bpf/dhcp/dhcp.bpf.c
@@ -0,0 +1,393 @@
+// Per-tap DHCPv4 responder. Attached on tap ingress, it answers DISCOVER and
+// REQUEST on interfaces with a record by rewriting the request into the reply
+// in place and redirecting it back out the same interface. The redirect
+// consumes the request, so nothing upstream on the bridge sees it. Everything
+// else, including requests on interfaces without a record, is handed on
+// untouched to whatever runs after this program on the interface.
+
+#include <linux/bpf.h>
+#include <linux/if_ether.h>
+#include <linux/in.h>
+#include <linux/ip.h>
+#include <linux/pkt_cls.h>
+#include <linux/udp.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include "types.h"
+#include "bpf_debug.h"
+
+char LICENSE[] SEC("license") = "GPL";
+
+// the library loads this object only into a process built for the same number
+const __u32 proxmox_schema SEC(".proxmox.schema") = DHCP_SCHEMA_VERSION;
+
+#define BOOTP_LEN 236
+// replies are padded up to the minimal BOOTP message size (RFC 1542), since
+// some old client stacks drop anything shorter
+#define BOOTP_MIN_LEN 300
+#define DHCP_MAGIC 0x63825363
+#define BOOTP_FLAG_BCAST 0x8000
+
+#define BOOTREQUEST 1
+#define BOOTREPLY 2
+
+#define DHCP_DISCOVER 1
+#define DHCP_OFFER 2
+#define DHCP_REQUEST 3
+#define DHCP_ACK 5
+#define DHCP_NAK 6
+
+#define OPT_PAD 0
+#define OPT_NETMASK 1
+#define OPT_ROUTER 3
+#define OPT_DNS 6
+#define OPT_MTU 26
+#define OPT_REQUESTED_IP 50
+#define OPT_LEASE 51
+#define OPT_MSGTYPE 53
+#define OPT_SERVER_ID 54
+#define OPT_WPAD 252
+#define OPT_END 255
+
+// the answer of every attached interface, keyed by ifindex
+struct {
+    __uint(type, BPF_MAP_TYPE_HASH);
+    __type(key, __u32);
+    __type(value, struct dhcp_record);
+    __uint(max_entries, 16384);
+    __uint(map_flags, BPF_F_NO_PREALLOC);
+    __uint(pinning, LIBBPF_PIN_BY_NAME);
+} dhcp_iface_records SEC(".maps");
+
+struct bootp {
+    __u8 op;
+    __u8 htype;
+    __u8 hlen;
+    __u8 hops;
+    __u32 xid;
+    __u16 secs;
+    __u16 flags;
+    __u32 ciaddr;
+    __u32 yiaddr;
+    __u32 siaddr;
+    __u32 giaddr;
+    __u8 chaddr[16];
+    __u8 sname[64];
+    __u8 file[128];
+};
+
+struct reply_pkt {
+    struct iphdr ip;
+    struct udphdr udp;
+    struct bootp bp;
+    __u32 cookie;
+    __u8 opts[BOOTP_MIN_LEN - BOOTP_LEN - 4];
+} __attribute__((packed));
+
+// the responder has no address on the tap, so replies carry a fixed locally
+// administered source MAC that nothing ever learns
+static const __u8 SRC_MAC[6] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x01 };
+static const __u8 BCAST_MAC[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
+
+static __always_inline __u16 csum_fold(__u32 sum)
+{
+    sum = (sum & 0xffff) + (sum >> 16);
+    sum = (sum & 0xffff) + (sum >> 16);
+    return sum;
+}
+
+static __always_inline __u16 ip_csum(const __u8 *hdr)
+{
+    __u32 sum = 0;
+#pragma unroll
+    for (int i = 0; i < 10; i++) {
+        __u16 word;
+        __builtin_memcpy(&word, hdr + 2 * i, 2);
+        sum += word;
+    }
+    return ~csum_fold(sum);
+}
+
+// the pseudo-header sum, the starting value the kernel expects in a
+// checksum it completes on the way out
+static __always_inline __u16 udp_pseudo_csum(__u32 saddr, __u32 daddr, __u16 len)
+{
+    __u32 sum = (saddr & 0xffff) + (saddr >> 16) + (daddr & 0xffff) + (daddr >> 16);
+    sum += bpf_htons(IPPROTO_UDP) + len;
+    return csum_fold(sum);
+}
+
+#define UDP_CHECK_OFF (ETH_HLEN + sizeof(struct iphdr) + 6)
+
+// what is left alone gets TC_ACT_UNSPEC, since TC_ACT_OK would end the
+// chain before the qdisc filters, where the rate limiter sits
+SEC("classifier")
+int tc_dhcp_ingress(struct __sk_buff *skb)
+{
+    __u32 min_len = ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr) + BOOTP_LEN + 4;
+
+    // the kernel strips a VLAN tag before this hook. A request the guest
+    // tagged itself belongs to a network of the guest's own and passes
+    if (skb->vlan_present)
+        return TC_ACT_UNSPEC;
+
+    // everything shorter is not a DHCP request
+    if (skb->len < min_len)
+        return TC_ACT_UNSPEC;
+
+    // the headers are read in place. A large packet from the guest is mostly
+    // outside the linear part, and pulling it in would cost every one of them
+    struct {
+        struct ethhdr eth;
+        struct iphdr ip;
+        struct udphdr udp;
+    } __attribute__((packed)) hdr;
+    if (bpf_skb_load_bytes(skb, 0, &hdr, sizeof(hdr)))
+        return TC_ACT_UNSPEC;
+    if (hdr.eth.h_proto != bpf_htons(ETH_P_IP))
+        return TC_ACT_UNSPEC;
+    if (hdr.ip.version != 4 || hdr.ip.ihl != 5 || hdr.ip.protocol != IPPROTO_UDP)
+        return TC_ACT_UNSPEC;
+    // a fragment is never a whole request, and past the first one the bytes at
+    // the UDP header offset are arbitrary payload
+    if (hdr.ip.frag_off & bpf_htons(0x3fff))
+        return TC_ACT_UNSPEC;
+    if (hdr.udp.dest != bpf_htons(67))
+        return TC_ACT_UNSPEC;
+
+    void *data = (void *)(long)skb->data;
+    void *data_end = (void *)(long)skb->data_end;
+
+    if (data + min_len > data_end) {
+        // a request may sit in a non-linear skb
+        if (bpf_skb_pull_data(skb, min_len))
+            return TC_ACT_UNSPEC;
+        data = (void *)(long)skb->data;
+        data_end = (void *)(long)skb->data_end;
+        if (data + min_len > data_end)
+            return TC_ACT_UNSPEC;
+    }
+
+    struct bootp *req = data + ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr);
+    if (req->op != BOOTREQUEST || req->htype != 1 || req->hlen != 6)
+        return TC_ACT_UNSPEC;
+
+    // a reply to a relayed request must go unicast to the relay instead of the
+    // client. Those are left to a server that speaks relay
+    if (req->giaddr) {
+        DBG("dhcp: request relayed via %pI4 passed", &req->giaddr);
+        return TC_ACT_UNSPEC;
+    }
+
+    __u32 *magic = (void *)req + BOOTP_LEN;
+    if (*magic != bpf_htonl(DHCP_MAGIC))
+        return TC_ACT_UNSPEC;
+
+    // only the NIC's own MAC gets the interface's answer. The client identifier
+    // option is not honored either, so the reply goes back to the hardware
+    // address the request came with. That is manual allocation in RFC 2131
+    // terms
+    __u8 chaddr[6];
+    __builtin_memcpy(chaddr, req->chaddr, 6);
+    __u32 ifindex = skb->ifindex;
+    struct dhcp_record *rec = bpf_map_lookup_elem(&dhcp_iface_records, &ifindex);
+    if (!rec) {
+        DBG("dhcp: no record for ifindex %d", ifindex);
+        return TC_ACT_UNSPEC;
+    }
+    for (int i = 0; i < 6; i++) {
+        if (chaddr[i] != rec->mac[i]) {
+            DBG("dhcp: chaddr is not the NIC's on ifindex %d", ifindex);
+            return TC_ACT_UNSPEC;
+        }
+    }
+
+    __u8 msgtype = 0;
+    __u32 requested_ip = 0;
+    __u32 server_id = 0;
+    __u32 off = min_len;
+    // the options end with the UDP datagram. Whatever the IP datagram or the
+    // frame carries beyond it is padding or a trailer, not the guest's request
+    __u32 end = ETH_HLEN + sizeof(struct iphdr) + bpf_ntohs(hdr.udp.len);
+    if (end > ETH_HLEN + bpf_ntohs(hdr.ip.tot_len))
+        end = ETH_HLEN + bpf_ntohs(hdr.ip.tot_len);
+    if (end > skb->len)
+        end = skb->len;
+
+    for (int i = 0; i < 128; i++) {
+        __u8 code, len;
+        if (off >= end || bpf_skb_load_bytes(skb, off, &code, 1))
+            break;
+        if (code == OPT_END)
+            break;
+        if (code == OPT_PAD) {
+            off += 1;
+            continue;
+        }
+        if (off + 2 > end || bpf_skb_load_bytes(skb, off + 1, &len, 1))
+            break;
+        if (off + 2 + len > end)
+            break;
+        if (code == OPT_MSGTYPE && len == 1)
+            bpf_skb_load_bytes(skb, off + 2, &msgtype, 1);
+        else if (code == OPT_REQUESTED_IP && len == 4)
+            bpf_skb_load_bytes(skb, off + 2, &requested_ip, 4);
+        else if (code == OPT_SERVER_ID && len == 4)
+            bpf_skb_load_bytes(skb, off + 2, &server_id, 4);
+        off += 2 + len;
+    }
+
+    __u8 reply;
+    if (msgtype == DHCP_DISCOVER) {
+        reply = DHCP_OFFER;
+    } else if (msgtype == DHCP_REQUEST) {
+        // a REQUEST naming another server declines our offer and is
+        // answered, if at all, by that server
+        if (server_id && server_id != rec->server_id) {
+            DBG("dhcp: request selected server %pI4, passed", &server_id);
+            return TC_ACT_UNSPEC;
+        }
+        // a NAK on a stale address makes the client re-DISCOVER instead of
+        // keeping the old address until its lease ends
+        __u32 want = requested_ip ? requested_ip : req->ciaddr;
+        reply = want == rec->ip ? DHCP_ACK : DHCP_NAK;
+        if (reply == DHCP_NAK)
+            DBG("dhcp: request for %pI4 against record %pI4, nak", &want, &rec->ip);
+    } else {
+        DBG("dhcp: message type %d passed", msgtype);
+        return TC_ACT_UNSPEC;
+    }
+
+    __u32 xid = req->xid;
+    __u16 flags = req->flags;
+    __u32 ciaddr = req->ciaddr;
+
+    struct reply_pkt buf = {};
+
+    buf.bp.op = BOOTREPLY;
+    buf.bp.htype = 1;
+    buf.bp.hlen = 6;
+    buf.bp.xid = xid;
+    buf.bp.flags = flags;
+    __builtin_memcpy(buf.bp.chaddr, chaddr, 6);
+
+    buf.cookie = bpf_htonl(DHCP_MAGIC);
+
+    __u32 o = 0;
+    buf.opts[o++] = OPT_MSGTYPE;
+    buf.opts[o++] = 1;
+    buf.opts[o++] = reply;
+    buf.opts[o++] = OPT_SERVER_ID;
+    buf.opts[o++] = 4;
+    __builtin_memcpy(&buf.opts[o], &rec->server_id, 4);
+    o += 4;
+
+    if (reply != DHCP_NAK) {
+        buf.bp.yiaddr = rec->ip;
+
+        buf.opts[o++] = OPT_LEASE;
+        buf.opts[o++] = 4;
+        __builtin_memcpy(&buf.opts[o], &rec->lease, 4);
+        o += 4;
+        buf.opts[o++] = OPT_NETMASK;
+        buf.opts[o++] = 4;
+        __builtin_memcpy(&buf.opts[o], &rec->netmask, 4);
+        o += 4;
+        if (rec->router) {
+            buf.opts[o++] = OPT_ROUTER;
+            buf.opts[o++] = 4;
+            __builtin_memcpy(&buf.opts[o], &rec->router, 4);
+            o += 4;
+        }
+        if (rec->dns) {
+            buf.opts[o++] = OPT_DNS;
+            buf.opts[o++] = 4;
+            __builtin_memcpy(&buf.opts[o], &rec->dns, 4);
+            o += 4;
+        }
+        if (rec->mtu) {
+            buf.opts[o++] = OPT_MTU;
+            buf.opts[o++] = 2;
+            __builtin_memcpy(&buf.opts[o], &rec->mtu, 2);
+            o += 2;
+        }
+        // an empty WPAD answer, without it some Windows versions
+        // probe for a proxy config indefinitely
+        buf.opts[o++] = OPT_WPAD;
+        buf.opts[o++] = 1;
+        buf.opts[o++] = '\n';
+    }
+    buf.opts[o++] = OPT_END;
+
+    // the zeroed tail of opts pads short replies out to the minimum, and on
+    // the wire those zeros read as pad options after the end option
+    __u32 bootp_out = BOOTP_LEN + 4 + o;
+    if (bootp_out < BOOTP_MIN_LEN)
+        bootp_out = BOOTP_MIN_LEN;
+
+    __u32 payload = sizeof(struct udphdr) + bootp_out;
+
+    buf.ip.version = 4;
+    buf.ip.ihl = 5;
+    buf.ip.ttl = 64;
+    buf.ip.protocol = IPPROTO_UDP;
+    buf.ip.tot_len = bpf_htons(sizeof(struct iphdr) + payload);
+    buf.ip.saddr = rec->server_id;
+    // a renewing client has an address and gets a unicast answer.
+    // Everything else cannot be addressed yet
+    buf.ip.daddr = (reply != DHCP_NAK && ciaddr) ? ciaddr : 0xffffffff;
+    buf.ip.check = ip_csum((const __u8 *)&buf.ip);
+
+    buf.udp.source = bpf_htons(67);
+    buf.udp.dest = bpf_htons(68);
+    buf.udp.len = bpf_htons(payload);
+
+    __u32 wlen = sizeof(struct iphdr) + payload;
+    if (wlen > sizeof(buf))
+        return TC_ACT_UNSPEC;
+
+    if (bpf_skb_change_tail(skb, ETH_HLEN + wlen, 0))
+        return TC_ACT_UNSPEC;
+    // the request is gone from here on, so a failed write drops the frame
+    // rather than forwarding what is left of it
+
+    // NAKs are always broadcast, and a client without an address that set the
+    // BROADCAST flag asked for a broadcast reply
+    __u8 eth_hdr[ETH_HLEN];
+    if (reply == DHCP_NAK || (!ciaddr && (flags & bpf_htons(BOOTP_FLAG_BCAST)))) {
+        __builtin_memcpy(eth_hdr, BCAST_MAC, 6);
+    } else {
+        __builtin_memcpy(eth_hdr, chaddr, 6);
+    }
+    __builtin_memcpy(eth_hdr + 6, SRC_MAC, 6);
+    eth_hdr[12] = 0x08;
+    eth_hdr[13] = 0x00;
+
+    if (bpf_skb_store_bytes(skb, 0, eth_hdr, ETH_HLEN, 0))
+        return TC_ACT_SHOT;
+    if (bpf_skb_store_bytes(skb, ETH_HLEN, &buf, wlen, 0))
+        return TC_ACT_SHOT;
+
+    // The reply reuses the request's skb, whose checksum state the program
+    // cannot see. A request sent with checksum offload is completed by the kernel
+    // on the way out, and it expects the pseudo-header sum in the field. Any
+    // other request needs the field valid as it is, and zero is valid. The
+    // helper below folds a checksum field once more when the kernel still
+    // has to complete it, so adding one to the zeroed field ends up as 1 in
+    // that state and as its complement otherwise. The low flag bits give
+    // the width of the field.
+    if (bpf_l4_csum_replace(skb, UDP_CHECK_OFF, 0, 1, BPF_F_PSEUDO_HDR | 2))
+        return TC_ACT_SHOT;
+    __u16 probe = 0;
+    if (bpf_skb_load_bytes(skb, UDP_CHECK_OFF, &probe, 2))
+        return TC_ACT_SHOT;
+    __u16 check = probe == 1 ? udp_pseudo_csum(buf.ip.saddr, buf.ip.daddr, buf.udp.len) : 0;
+    if (bpf_skb_store_bytes(skb, UDP_CHECK_OFF, &check, 2, 0))
+        return TC_ACT_SHOT;
+
+#ifdef BPF_DEBUG
+    __u32 yiaddr = buf.bp.yiaddr;
+    DBG("dhcp: reply type %d with %pI4 to ifindex %d", reply, &yiaddr, skb->ifindex);
+#endif
+    return bpf_redirect(skb->ifindex, 0);
+}
diff --git a/src/bpf/dhcp/types.h b/src/bpf/dhcp/types.h
new file mode 100644
index 000000000000..cecb36932402
--- /dev/null
+++ b/src/bpf/dhcp/types.h
@@ -0,0 +1,27 @@
+#ifndef PROXMOX_EBPF_DHCP_TYPES_H
+#define PROXMOX_EBPF_DHCP_TYPES_H
+
+// Keep in sync with proxmox-sdn-dhcp/src/types.rs in proxmox-ve-rs
+// __u8/__u16/__u32 come from linux/types.h
+
+// goes up with any change to a map's key or value layout, together with SCHEMA_VERSION in
+// proxmox-sdn-dhcp/src/lib.rs
+#define DHCP_SCHEMA_VERSION 1
+
+// addresses, lease and mtu are stored in network byte order, so a
+// reply copies them into the packet as-is
+struct dhcp_record {
+    __u32 ip;
+    __u32 netmask;
+    __u32 router; // 0 = not served
+    __u32 dns; // 0 = not served
+    __u32 server_id;
+    __u32 lease;
+    __u16 mtu; // 0 = not served
+    __u8 mac[6]; // the NIC's, a request carrying another is passed on
+};
+
+_Static_assert(sizeof(struct dhcp_record) == 32, "dhcp_record layout");
+_Static_assert(__builtin_offsetof(struct dhcp_record, mac) == 26, "dhcp_record layout");
+
+#endif
diff --git a/src/bpf/harness/shim/bpf/bpf_helpers.h b/src/bpf/harness/shim/bpf/bpf_helpers.h
index b4bcfdf5717f..a45e5829ea1e 100644
--- a/src/bpf/harness/shim/bpf/bpf_helpers.h
+++ b/src/bpf/harness/shim/bpf/bpf_helpers.h
@@ -29,6 +29,7 @@ extern long bpf_skb_load_bytes(const void *skb, __u32 offset, void *to, __u32 le
 extern long bpf_skb_store_bytes(void *skb, __u32 offset, const void *from, __u32 len, __u64 flags);
 extern long bpf_skb_pull_data(void *skb, __u32 len);
 extern long bpf_skb_change_tail(void *skb, __u32 new_len, __u64 flags);
+extern long bpf_l4_csum_replace(void *skb, __u32 offset, __u64 from, __u64 to, __u64 flags);
 extern long bpf_redirect(__u32 ifindex, __u64 flags);
 
 #endif
diff --git a/src/bpf/harness/shim/linux/bpf.h b/src/bpf/harness/shim/linux/bpf.h
index ff259c329522..0042bda49dd0 100644
--- a/src/bpf/harness/shim/linux/bpf.h
+++ b/src/bpf/harness/shim/linux/bpf.h
@@ -14,6 +14,7 @@ struct __sk_buff {
     __u32 len;
     __u32 ifindex;
     __u32 mark;
+    __u32 vlan_present;
 };
 
 // map-definition constants, the values are irrelevant natively
@@ -22,4 +23,6 @@ enum {
 };
 #define BPF_F_NO_PREALLOC 1
 
+#define BPF_F_PSEUDO_HDR 0x10
+
 #endif
diff --git a/src/bpf/harness/tests/common/mod.rs b/src/bpf/harness/tests/common/mod.rs
index c4c1371e6a17..2607020739f1 100644
--- a/src/bpf/harness/tests/common/mod.rs
+++ b/src/bpf/harness/tests/common/mod.rs
@@ -24,13 +24,16 @@ pub struct SkBuff {
     pub len: u32,
     pub ifindex: u32,
     pub mark: u32,
+    pub vlan_present: u32,
 }
 
 /// The skb handed to a program plus the buffer behind it. The helpers get the skb pointer and
-/// cast back to this, so the skb must stay the first field.
+/// cast back to this, so the skb must stay the first field. `partial` models a checksum the
+/// kernel still has to complete, the state a request sent with checksum offload carries.
 #[repr(C)]
 pub struct TestSkb {
     skb: SkBuff,
+    pub partial: bool,
     buf: Box<[u8; PKT_CAP]>,
 }
 
@@ -46,7 +49,9 @@ impl TestSkb {
                 len: packet.len() as u32,
                 ifindex,
                 mark: 0,
+                vlan_present: 0,
             },
+            partial: false,
             buf,
         };
         t.sync();
@@ -59,6 +64,11 @@ impl TestSkb {
         self.skb.data_end = base + self.skb.len as usize;
     }
 
+    /// The frame arrived tagged, and the kernel keeps the tag beside the data.
+    pub fn tag_vlan(&mut self) {
+        self.skb.vlan_present = 1;
+    }
+
     pub fn packet(&self) -> &[u8] {
         &self.buf[..self.skb.len as usize]
     }
@@ -185,10 +195,10 @@ pub extern "C" fn bpf_skb_pull_data(skb: *mut c_void, len: u32) -> c_long {
 #[unsafe(no_mangle)]
 pub extern "C" fn bpf_skb_change_tail(skb: *mut c_void, new_len: u32, _flags: u64) -> c_long {
     let t = unsafe { testskb(skb) };
-    // the kernel refuses to cut into the headers it knows, which is the link header here.
-    // Growing stops at the harness buffer
-    let min_len = 14;
-    if new_len < min_len || new_len as usize > PKT_CAP {
+    // the kernel refuses to cut into the headers it knows. tun sets the transport header on
+    // every frame it hands in, so an IPv4 UDP frame keeps 34 bytes. Growing stops at the harness
+    // buffer
+    if new_len < 34 || new_len as usize > PKT_CAP {
         return -EINVAL;
     }
     // like the kernel, grown room reads as zeros
@@ -196,11 +206,60 @@ pub extern "C" fn bpf_skb_change_tail(skb: *mut c_void, new_len: u32, _flags: u6
     if new_len as usize > old {
         t.buf[old..new_len as usize].fill(0);
     }
+    // the checksum field of an IPv4 UDP frame ends at byte 42. A trim that cuts into it ends the
+    // checksum offload in the kernel
+    if (new_len as usize) < old && new_len < 42 {
+        t.partial = false;
+    }
     t.skb.len = new_len;
     t.sync();
     0
 }
 
+// the kernel's ones' complement primitives, csum_fold complements its result
+fn csum_add(a: u32, b: u32) -> u32 {
+    let (r, carry) = a.overflowing_add(b);
+    r + carry as u32
+}
+fn csum_fold(sum: u32) -> u16 {
+    let mut s = (sum & 0xffff) + (sum >> 16);
+    s = (s & 0xffff) + (s >> 16);
+    !(s as u16)
+}
+
+/// The kernel's field update, inet_proto_csum_replace4 for a 16-bit field. A partial checksum
+/// gets the difference folded in, and any other is complemented around the update. So the same
+/// call ends in different values.
+#[unsafe(no_mangle)]
+pub extern "C" fn bpf_l4_csum_replace(
+    skb: *mut c_void,
+    offset: u32,
+    from: u64,
+    to: u64,
+    flags: u64,
+) -> c_long {
+    let t = unsafe { testskb(skb) };
+    let offset = offset as usize;
+    assert_eq!(flags & 0xf, 2, "the responder updates the 16-bit field");
+    assert!(
+        flags & 0x10 != 0,
+        "the responder passes the pseudo-header flag"
+    );
+    if offset + 2 > t.skb.len as usize {
+        return -EFAULT;
+    }
+    let field = u16::from_ne_bytes([t.buf[offset], t.buf[offset + 1]]) as u32;
+    // a 16-bit field takes 16-bit values, so the kernel narrows both before the update
+    let (from, to) = (from as u16 as u32, to as u16 as u32);
+    let new = if t.partial {
+        !csum_fold(csum_add(csum_add(field, !from), to))
+    } else {
+        csum_fold(csum_add(csum_add(!field, !from), to))
+    };
+    t.buf[offset..offset + 2].copy_from_slice(&new.to_ne_bytes());
+    0
+}
+
 #[unsafe(no_mangle)]
 pub extern "C" fn bpf_redirect(ifindex: u32, flags: u64) -> c_long {
     REDIRECTED.with(|r| *r.borrow_mut() = Some((ifindex, flags)));
diff --git a/src/bpf/harness/tests/dhcp.rs b/src/bpf/harness/tests/dhcp.rs
new file mode 100644
index 000000000000..ba97a04d4e0e
--- /dev/null
+++ b/src/bpf/harness/tests/dhcp.rs
@@ -0,0 +1,804 @@
+//! The dhcp responder program run natively, crafted requests in and the rewritten reply out.
+
+mod common;
+
+use std::ffi::{c_int, c_void};
+
+use common::*;
+
+unsafe extern "C" {
+    fn tc_dhcp_ingress(skb: *mut SkBuff) -> c_int;
+    static dhcp_iface_records: u8;
+}
+
+const MAC: [u8; 6] = [0xda, 0x65, 0x8f, 0x18, 0x9b, 0x6f];
+const SRC_MAC: [u8; 6] = [0x02, 0x00, 0x00, 0x00, 0x00, 0x01];
+const BCAST: [u8; 6] = [0xff; 6];
+const IFINDEX: u32 = 42;
+
+const IP: [u8; 4] = [10, 0, 0, 100];
+const MASK: [u8; 4] = [255, 255, 255, 0];
+const GW: [u8; 4] = [10, 0, 0, 1];
+const DNS: [u8; 4] = [1, 1, 1, 1];
+const LEASE: u32 = 300;
+const MTU: u16 = 1500;
+
+const OPTS_OFF: usize = 14 + 20 + 8 + 236 + 4;
+
+const DISCOVER: &[u8] = &[53, 1, 1];
+const REQUEST: &[u8] = &[53, 1, 3];
+
+fn records_map() -> *const c_void {
+    (unsafe { &dhcp_iface_records } as *const u8).cast()
+}
+
+// the record map of a node, still empty
+fn setup_maps() {
+    register_map(records_map(), 4);
+}
+
+// the record map is keyed by the interface the request arrives on
+fn key() -> [u8; 4] {
+    IFINDEX.to_ne_bytes()
+}
+
+fn record(
+    ip: [u8; 4],
+    mask: [u8; 4],
+    router: [u8; 4],
+    dns: [u8; 4],
+    server: [u8; 4],
+    lease: u32,
+    mtu: u16,
+) -> [u8; 32] {
+    let mut r = [0u8; 32];
+    r[0..4].copy_from_slice(&ip);
+    r[4..8].copy_from_slice(&mask);
+    r[8..12].copy_from_slice(&router);
+    r[12..16].copy_from_slice(&dns);
+    r[16..20].copy_from_slice(&server);
+    r[20..24].copy_from_slice(&lease.to_be_bytes());
+    r[24..26].copy_from_slice(&mtu.to_be_bytes());
+    r[26..32].copy_from_slice(&MAC);
+    r
+}
+
+fn setup_full_record() {
+    setup_maps();
+    map_insert(
+        records_map(),
+        &key(),
+        &record(IP, MASK, GW, DNS, GW, LEASE, MTU),
+    );
+}
+
+struct Request {
+    mac: [u8; 6],
+    xid: [u8; 4],
+    flags: [u8; 2],
+    ciaddr: [u8; 4],
+    giaddr: [u8; 4],
+    options: Vec<u8>,
+    dport: u16,
+    ethertype: [u8; 2],
+    ipproto: u8,
+    frag_off: [u8; 2],
+    ip_options: Vec<u8>,
+    op: u8,
+    htype: u8,
+    hlen: u8,
+    end: bool,
+    trailer: Vec<u8>,
+    // claimed on top of the real IP total length
+    tot_len_excess: u16,
+}
+
+impl Default for Request {
+    fn default() -> Self {
+        Request {
+            mac: MAC,
+            xid: [0xde, 0xad, 0xbe, 0xef],
+            flags: [0, 0],
+            ciaddr: [0; 4],
+            giaddr: [0; 4],
+            options: DISCOVER.to_vec(),
+            dport: 67,
+            ethertype: [0x08, 0x00],
+            ipproto: 17,
+            frag_off: [0, 0],
+            ip_options: Vec::new(),
+            op: 1,
+            htype: 1,
+            hlen: 6,
+            end: true,
+            trailer: Vec::new(),
+            tot_len_excess: 0,
+        }
+    }
+}
+
+impl Request {
+    fn build(&self) -> Vec<u8> {
+        assert_eq!(self.ip_options.len() % 4, 0);
+        let ihl = 5 + self.ip_options.len() / 4;
+        let payload = 8 + 236 + 4 + self.options.len() + usize::from(self.end);
+        let mut p = Vec::new();
+        // ethernet
+        p.extend_from_slice(&BCAST);
+        p.extend_from_slice(&self.mac);
+        p.extend_from_slice(&self.ethertype);
+        // ipv4
+        p.extend_from_slice(&[0x40 | ihl as u8, 0]);
+        p.extend_from_slice(&((ihl * 4 + payload) as u16 + self.tot_len_excess).to_be_bytes());
+        p.extend_from_slice(&[0, 0]); // id
+        p.extend_from_slice(&self.frag_off);
+        p.extend_from_slice(&[64, self.ipproto, 0, 0]);
+        p.extend_from_slice(&[0, 0, 0, 0]); // saddr
+        p.extend_from_slice(&[255, 255, 255, 255]); // daddr
+        p.extend_from_slice(&self.ip_options);
+        // udp
+        p.extend_from_slice(&68u16.to_be_bytes());
+        p.extend_from_slice(&self.dport.to_be_bytes());
+        p.extend_from_slice(&(payload as u16).to_be_bytes());
+        p.extend_from_slice(&[0, 0]);
+        // bootp
+        p.extend_from_slice(&[self.op, self.htype, self.hlen, 0]);
+        p.extend_from_slice(&self.xid);
+        p.extend_from_slice(&[0, 0]); // secs
+        p.extend_from_slice(&self.flags);
+        p.extend_from_slice(&self.ciaddr);
+        p.extend_from_slice(&[0; 8]); // yiaddr, siaddr
+        p.extend_from_slice(&self.giaddr);
+        p.extend_from_slice(&self.mac);
+        p.extend_from_slice(&[0; 10]); // chaddr padding
+        p.extend_from_slice(&[0; 192]); // sname, file
+        // cookie and options
+        p.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);
+        p.extend_from_slice(&self.options);
+        if self.end {
+            p.push(255);
+        }
+        // bytes past the datagram, padding or a trailer the frame carries
+        p.extend_from_slice(&self.trailer);
+        p
+    }
+
+    fn run(&self) -> (c_int, TestSkb) {
+        self.run_on(IFINDEX)
+    }
+
+    fn run_on(&self, ifindex: u32) -> (c_int, TestSkb) {
+        let mut skb = TestSkb::new(&self.build(), ifindex);
+        let verdict = skb.run(tc_dhcp_ingress);
+        (verdict, skb)
+    }
+}
+
+// the options of a reply and the offset just past its end option
+fn walk_opts(pkt: &[u8]) -> (Vec<(u8, Vec<u8>)>, usize) {
+    let mut opts = Vec::new();
+    let mut off = OPTS_OFF;
+    loop {
+        let code = pkt[off];
+        if code == 255 {
+            return (opts, off + 1);
+        }
+        if code == 0 {
+            off += 1;
+            continue;
+        }
+        let len = pkt[off + 1] as usize;
+        opts.push((code, pkt[off + 2..off + 2 + len].to_vec()));
+        off += 2 + len;
+    }
+}
+
+fn parse_opts(pkt: &[u8]) -> Vec<(u8, Vec<u8>)> {
+    walk_opts(pkt).0
+}
+
+// a REQUEST that names the address it asks for
+fn request_for(ip: [u8; 4]) -> Vec<u8> {
+    let mut options = REQUEST.to_vec();
+    options.extend_from_slice(&[50, 4]);
+    options.extend_from_slice(&ip);
+    options
+}
+
+fn ip_csum_ok(pkt: &[u8]) -> bool {
+    let mut sum = 0u32;
+    for w in pkt[14..34].chunks(2) {
+        sum += u32::from(u16::from_be_bytes([w[0], w[1]]));
+    }
+    while sum > 0xffff {
+        sum = (sum & 0xffff) + (sum >> 16);
+    }
+    sum == 0xffff
+}
+
+/// What every reply has to look like whatever the request was. The addressing and the answer
+/// itself are the caller's to check.
+fn assert_reply_invariants(pkt: &[u8]) {
+    assert_eq!(&pkt[6..12], &SRC_MAC, "eth src");
+    assert_eq!(&pkt[12..14], &[0x08, 0x00], "ethertype");
+
+    assert_eq!(pkt[14], 0x45, "ihl/version");
+    assert_eq!(pkt[22], 64, "ttl");
+    assert_eq!(pkt[23], 17, "protocol");
+    assert_eq!(&pkt[26..30], &GW, "ip src is the server id");
+    assert!(ip_csum_ok(pkt), "ip checksum");
+    let tot_len = u16::from_be_bytes([pkt[16], pkt[17]]) as usize;
+    assert_eq!(tot_len, pkt.len() - 14, "ip total length");
+
+    assert_eq!(&pkt[34..36], &67u16.to_be_bytes(), "udp sport");
+    assert_eq!(&pkt[36..38], &68u16.to_be_bytes(), "udp dport");
+    let udp_len = u16::from_be_bytes([pkt[38], pkt[39]]) as usize;
+    assert_eq!(udp_len, pkt.len() - 34, "udp length");
+    assert_eq!(&pkt[40..42], &[0, 0], "udp checksum zero, none to complete");
+    assert!(pkt.len() - 42 >= 300, "bootp minimum message size");
+
+    assert_eq!(&pkt[42..45], &[2, 1, 6], "bootp reply op, htype, hlen");
+    assert_eq!(&pkt[46..50], &[0xde, 0xad, 0xbe, 0xef], "xid preserved");
+    assert_eq!(&pkt[70..76], &MAC, "chaddr");
+    assert_eq!(&pkt[278..282], &[0x63, 0x82, 0x53, 0x63], "cookie");
+    assert!(
+        matches!(parse_opts(pkt).first(), Some((53, t)) if t.len() == 1 && [2, 5, 6].contains(&t[0])),
+        "message type leads the options"
+    );
+    let end = walk_opts(pkt).1;
+    assert!(
+        pkt[end..].iter().all(|&b| b == 0),
+        "padding after the end option is zero"
+    );
+}
+
+fn assert_reply_headers(pkt: &[u8], eth_dst: [u8; 6], ip_dst: [u8; 4], yiaddr: [u8; 4]) {
+    assert_reply_invariants(pkt);
+    assert_eq!(&pkt[0..6], &eth_dst, "eth dst");
+    assert_eq!(&pkt[30..34], &ip_dst, "ip dst");
+    assert_eq!(&pkt[58..62], &yiaddr, "yiaddr");
+}
+
+#[test]
+fn discover_gets_full_offer() {
+    setup_full_record();
+    let (verdict, skb) = Request::default().run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_eq!(redirected(), Some(IFINDEX));
+    assert_eq!(
+        redirect_flags(),
+        Some(0),
+        "the reply leaves through the tap"
+    );
+
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, MAC, [255, 255, 255, 255], IP);
+    assert_eq!(
+        parse_opts(pkt),
+        vec![
+            (53, vec![2]),
+            (54, GW.to_vec()),
+            (51, LEASE.to_be_bytes().to_vec()),
+            (1, MASK.to_vec()),
+            (3, GW.to_vec()),
+            (6, DNS.to_vec()),
+            (26, MTU.to_be_bytes().to_vec()),
+            (252, vec![b'\n']),
+        ],
+    );
+}
+
+#[test]
+fn offer_skips_unset_options() {
+    setup_maps();
+    map_insert(
+        records_map(),
+        &key(),
+        &record(IP, MASK, [0; 4], [0; 4], GW, LEASE, 0),
+    );
+    let (verdict, skb) = Request::default().run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let codes: Vec<u8> = parse_opts(skb.packet()).iter().map(|(c, _)| *c).collect();
+    assert_eq!(codes, vec![53, 54, 51, 1, 252]);
+}
+
+#[test]
+fn matching_request_gets_ack() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        options: request_for(IP),
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, MAC, [255, 255, 255, 255], IP);
+    assert_eq!(parse_opts(pkt)[0], (53, vec![5]));
+}
+
+// the pseudo-header sum, the starting value the kernel expects in a checksum it completes on
+// the way out
+fn udp_pseudo(pkt: &[u8]) -> [u8; 2] {
+    let words = [
+        u16::from_be_bytes([pkt[26], pkt[27]]),
+        u16::from_be_bytes([pkt[28], pkt[29]]),
+        u16::from_be_bytes([pkt[30], pkt[31]]),
+        u16::from_be_bytes([pkt[32], pkt[33]]),
+        17,
+        u16::from_be_bytes([pkt[38], pkt[39]]),
+    ];
+    let mut s: u32 = words.iter().map(|&w| w as u32).sum();
+    while s >> 16 != 0 {
+        s = (s & 0xffff) + (s >> 16);
+    }
+    (s as u16).to_be_bytes()
+}
+
+#[test]
+fn offloaded_request_gets_the_pseudo_header_sum() {
+    setup_full_record();
+    let mut skb = TestSkb::new(&Request::default().build(), IFINDEX);
+    skb.partial = true;
+    assert_eq!(skb.run(tc_dhcp_ingress), TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_eq!(
+        &pkt[40..42],
+        &udp_pseudo(pkt),
+        "udp checksum holds the pseudo-header sum"
+    );
+    assert_ne!(&pkt[40..42], &[0, 0]);
+}
+
+#[test]
+fn tagged_request_passes() {
+    setup_full_record();
+    let mut skb = TestSkb::new(&Request::default().build(), IFINDEX);
+    skb.tag_vlan();
+    assert_eq!(skb.run(tc_dhcp_ingress), TC_ACT_UNSPEC);
+}
+
+#[test]
+fn trailer_past_the_datagram_is_not_read_as_options() {
+    setup_full_record();
+    // no END option, and the frame goes on with bytes shaped like a server
+    // identifier naming another server
+    let (verdict, skb) = Request {
+        options: request_for(IP),
+        end: false,
+        trailer: vec![54, 4, 10, 9, 9, 9],
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_eq!(parse_opts(skb.packet())[0], (53, vec![5]));
+}
+
+#[test]
+fn bytes_past_the_udp_datagram_are_not_read_as_options() {
+    setup_full_record();
+    // the IP length claims the trailer and the UDP length does not. The
+    // trailer is shaped like a server identifier naming another server
+    let (verdict, skb) = Request {
+        options: request_for(IP),
+        end: false,
+        trailer: vec![54, 4, 10, 9, 9, 9],
+        tot_len_excess: 6,
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_eq!(parse_opts(skb.packet())[0], (53, vec![5]));
+}
+
+#[test]
+fn claimed_length_past_the_frame_is_clamped() {
+    // the message type is followed by a second one cut off by the frame. A walk trusting the
+    // claimed length would read past the frame and take the zeroed result as the type
+    setup_full_record();
+    let mut options = DISCOVER.to_vec();
+    options.extend_from_slice(&[53, 1]);
+    let req = Request {
+        options,
+        end: false,
+        tot_len_excess: 1,
+        ..Request::default()
+    };
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_reply_invariants(skb.packet());
+}
+
+#[test]
+fn request_without_options_passes_untouched() {
+    setup_full_record();
+    let req = Request {
+        options: Vec::new(),
+        end: false,
+        ..Request::default()
+    };
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(skb.packet(), &req.build()[..]);
+}
+
+#[test]
+fn stale_request_gets_nak() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        options: request_for([10, 0, 0, 77]),
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, BCAST, [255, 255, 255, 255], [0; 4]);
+    assert_eq!(parse_opts(pkt), vec![(53, vec![6]), (54, GW.to_vec())]);
+}
+
+#[test]
+fn renewal_is_answered_unicast() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        options: REQUEST.to_vec(),
+        ciaddr: IP,
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, MAC, IP, IP);
+    assert_eq!(parse_opts(pkt)[0], (53, vec![5]));
+}
+
+#[test]
+fn request_selecting_another_server_passes_untouched() {
+    setup_full_record();
+    let mut options = REQUEST.to_vec();
+    options.extend_from_slice(&[54, 4, 192, 168, 7, 7]);
+    options.extend_from_slice(&[50, 4, 10, 0, 0, 77]);
+    let req = Request {
+        options,
+        ..Request::default()
+    };
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(redirected(), None);
+    assert_eq!(skb.packet(), &req.build()[..]);
+}
+
+#[test]
+fn relayed_request_passes_untouched() {
+    setup_full_record();
+    let req = Request {
+        giaddr: [10, 0, 0, 254],
+        ..Request::default()
+    };
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(redirected(), None);
+    assert_eq!(skb.packet(), &req.build()[..]);
+}
+
+#[test]
+fn fragments_pass_untouched() {
+    setup_full_record();
+    for frag_off in [[0x20, 0x00], [0x00, 0x01]] {
+        let req = Request {
+            frag_off,
+            ..Request::default()
+        };
+        let (verdict, skb) = req.run();
+        assert_eq!(verdict, TC_ACT_UNSPEC);
+        assert_eq!(skb.packet(), &req.build()[..]);
+    }
+
+    let (verdict, _) = Request {
+        frag_off: [0x40, 0x00],
+        ..Request::default()
+    }
+    .run();
+    assert_eq!(verdict, TC_ACT_REDIRECT, "DF alone is not a fragment");
+}
+
+#[test]
+fn broadcast_flag_gets_l2_broadcast_reply() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        flags: [0x80, 0],
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, BCAST, [255, 255, 255, 255], IP);
+    assert_eq!(&pkt[52..54], &[0x80, 0], "flags echoed");
+
+    // ciaddr wins over the flag, since a renewing client is addressable
+    let (verdict, skb) = Request {
+        flags: [0x80, 0],
+        ciaddr: IP,
+        options: REQUEST.to_vec(),
+        ..Request::default()
+    }
+    .run();
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_reply_headers(skb.packet(), MAC, IP, IP);
+}
+
+#[test]
+fn interface_without_a_record_passes_untouched() {
+    setup_maps();
+    let req = Request::default();
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(redirected(), None);
+    assert_eq!(skb.packet(), &req.build()[..]);
+
+    // the record is one interface's, so a request arriving on any other gets nothing from it
+    setup_full_record();
+    let (verdict, skb) = req.run_on(IFINDEX + 1);
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(redirected(), None);
+    assert_eq!(skb.packet(), &req.build()[..]);
+}
+
+#[test]
+fn another_mac_on_the_interface_passes_untouched() {
+    // a request carrying another MAC than the NIC's is left to the bridge
+    setup_full_record();
+    let other = [0x02, 0x11, 0x22, 0x33, 0x44, 0x55];
+    let req = Request {
+        mac: other,
+        ..Request::default()
+    };
+    let before = req.build();
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(skb.packet(), &before[..], "untouched");
+}
+
+#[test]
+fn non_dhcp_traffic_passes_untouched() {
+    setup_full_record();
+    let variants = [
+        Request {
+            dport: 53,
+            ..Request::default()
+        },
+        Request {
+            ethertype: [0x86, 0xdd],
+            ..Request::default()
+        },
+        Request {
+            ipproto: 6,
+            ..Request::default()
+        },
+    ];
+    for req in variants {
+        let (verdict, skb) = req.run();
+        assert_eq!(verdict, TC_ACT_UNSPEC);
+        assert_eq!(skb.packet(), &req.build()[..]);
+    }
+
+    let frame = Request::default().build();
+    let mut skb = TestSkb::new(&frame[..100], IFINDEX);
+    assert_eq!(skb.run(tc_dhcp_ingress), TC_ACT_UNSPEC);
+
+    let mut corrupted = frame.clone();
+    corrupted[278] = 0;
+    let mut skb = TestSkb::new(&corrupted, IFINDEX);
+    assert_eq!(skb.run(tc_dhcp_ingress), TC_ACT_UNSPEC);
+}
+
+#[test]
+fn options_walk_handles_padding_and_early_end() {
+    setup_full_record();
+
+    let mut options = vec![0, 0, 0];
+    options.extend_from_slice(DISCOVER);
+    let (verdict, _) = Request {
+        options,
+        ..Request::default()
+    }
+    .run();
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+
+    let mut options = vec![255];
+    options.extend_from_slice(DISCOVER);
+    let (verdict, _) = Request {
+        options,
+        ..Request::default()
+    }
+    .run();
+    assert_eq!(
+        verdict, TC_ACT_UNSPEC,
+        "message type after end is not parsed"
+    );
+    assert_eq!(redirected(), None);
+}
+
+#[test]
+fn stale_renewal_gets_broadcast_nak() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        options: REQUEST.to_vec(),
+        ciaddr: [10, 0, 0, 77],
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, BCAST, [255, 255, 255, 255], [0; 4]);
+    assert_eq!(parse_opts(pkt), vec![(53, vec![6]), (54, GW.to_vec())]);
+}
+
+#[test]
+fn request_without_address_gets_nak() {
+    setup_full_record();
+    let (verdict, skb) = Request {
+        options: REQUEST.to_vec(),
+        ..Request::default()
+    }
+    .run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert_reply_headers(pkt, BCAST, [255, 255, 255, 255], [0; 4]);
+    assert_eq!(parse_opts(pkt)[0], (53, vec![6]));
+}
+
+#[test]
+fn realistic_request_is_answered_and_shrunk() {
+    setup_full_record();
+    let mut options = REQUEST.to_vec();
+    // a client identifier naming something else is ignored and the chaddr decides
+    options.extend_from_slice(&[61, 7, 1, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x01]);
+    options.extend_from_slice(&[50, 4]);
+    options.extend_from_slice(&IP);
+    options.extend_from_slice(&[54, 4]);
+    options.extend_from_slice(&GW);
+    options.extend_from_slice(&[12, 14]);
+    options.extend_from_slice(b"dhcp-client-01");
+    options.extend_from_slice(&[60, 32]);
+    options.extend_from_slice(b"PXEClient:Arch:00007:UNDI:003016");
+    options.extend_from_slice(&[55, 20]);
+    options.extend_from_slice(&[
+        1, 2, 3, 6, 12, 15, 17, 26, 28, 40, 41, 42, 51, 54, 58, 59, 66, 67, 119, 121,
+    ]);
+    options.extend_from_slice(&[57, 2, 0x05, 0xdc]);
+    options.extend_from_slice(&[93, 2, 0, 7]);
+    options.extend_from_slice(&[94, 3, 1, 3, 16]);
+    options.extend_from_slice(&[97, 17, 0]);
+    options.extend_from_slice(&[0x11; 16]);
+    let req = Request {
+        options,
+        ..Request::default()
+    };
+    let request_len = req.build().len();
+    let (verdict, skb) = req.run();
+
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    let pkt = skb.packet();
+    assert!(pkt.len() < request_len, "reply is shorter than the request");
+    assert_eq!(
+        pkt.len(),
+        14 + 20 + 8 + 300,
+        "trimmed to the padded minimum"
+    );
+    assert_reply_headers(pkt, MAC, [255, 255, 255, 255], IP);
+    assert_eq!(parse_opts(pkt)[0], (53, vec![5]));
+}
+
+#[test]
+fn other_message_types_pass_untouched() {
+    setup_full_record();
+    for msgtype in [4, 7, 8] {
+        let req = Request {
+            options: vec![53, 1, msgtype],
+            ..Request::default()
+        };
+        let (verdict, skb) = req.run();
+        assert_eq!(verdict, TC_ACT_UNSPEC, "message type {msgtype}");
+        assert_eq!(redirected(), None);
+        assert_eq!(skb.packet(), &req.build()[..]);
+    }
+}
+
+#[test]
+fn foreign_bootp_passes_untouched() {
+    setup_full_record();
+    let variants = [
+        // a reply coming in from the guest side, a guest running its own server
+        Request {
+            op: 2,
+            ..Request::default()
+        },
+        Request {
+            htype: 6,
+            ..Request::default()
+        },
+        Request {
+            hlen: 16,
+            ..Request::default()
+        },
+        Request {
+            ip_options: vec![1, 1, 1, 1],
+            ..Request::default()
+        },
+    ];
+    for req in variants {
+        let (verdict, skb) = req.run();
+        assert_eq!(verdict, TC_ACT_UNSPEC);
+        assert_eq!(redirected(), None);
+        assert_eq!(skb.packet(), &req.build()[..]);
+    }
+}
+
+#[test]
+fn truncated_option_ends_the_walk() {
+    setup_full_record();
+
+    // a length running past the packet before the message type leaves nothing to answer
+    let mut options = vec![12, 200];
+    options.extend_from_slice(DISCOVER);
+    let req = Request {
+        options,
+        ..Request::default()
+    };
+    let (verdict, skb) = req.run();
+    assert_eq!(verdict, TC_ACT_UNSPEC);
+    assert_eq!(redirected(), None);
+    assert_eq!(skb.packet(), &req.build()[..]);
+
+    // after the message type it only cuts the walk short, and what was read still counts
+    let mut options = DISCOVER.to_vec();
+    options.extend_from_slice(&[12, 200]);
+    let (verdict, skb) = Request {
+        options,
+        ..Request::default()
+    }
+    .run();
+    assert_eq!(verdict, TC_ACT_REDIRECT);
+    assert_reply_headers(skb.packet(), MAC, [255, 255, 255, 255], IP);
+}
+
+#[test]
+fn arbitrary_option_bytes_never_break_the_reply() {
+    setup_full_record();
+    let mut lcg = 0x2545f4914f6cdd1du64;
+    let mut rand = move || {
+        lcg = lcg
+            .wrapping_mul(6364136223846793005)
+            .wrapping_add(1442695040888963407);
+        (lcg >> 33) as u8
+    };
+
+    for _ in 0..500 {
+        let len = (rand() % 60) as usize;
+        let options: Vec<u8> = (0..len).map(|_| rand()).collect();
+        let (verdict, skb) = Request {
+            options,
+            ..Request::default()
+        }
+        .run();
+        assert!(verdict == TC_ACT_UNSPEC || verdict == TC_ACT_REDIRECT);
+        if verdict == TC_ACT_REDIRECT {
+            assert_reply_invariants(skb.packet());
+        }
+    }
+}
diff --git a/src/bpf/harness/tests/harness.rs b/src/bpf/harness/tests/harness.rs
index 470e0a1cd88b..704d373511aa 100644
--- a/src/bpf/harness/tests/harness.rs
+++ b/src/bpf/harness/tests/harness.rs
@@ -52,6 +52,20 @@ fn helpers_read_and_write_the_frame() {
     assert_eq!(skb.packet(), &[1, 2, 3, 4, 9, 9]);
 }
 
+#[test]
+fn a_trim_into_the_checksum_field_ends_the_offload() {
+    let mut skb = TestSkb::new(&[0u8; 60], 7);
+    skb.partial = true;
+    let raw = (&mut skb as *mut TestSkb).cast::<c_void>();
+    assert_eq!(bpf_skb_change_tail(raw, 42, 0), 0);
+    assert!(skb.partial);
+    assert_eq!(bpf_skb_change_tail(raw, 41, 0), 0);
+    assert!(!skb.partial);
+    // the headers stay, with or without offload
+    assert_ne!(bpf_skb_change_tail(raw, 33, 0), 0);
+    assert_eq!(skb.packet().len(), 41);
+}
+
 #[test]
 fn maps_answer_registered_entries() {
     // any address serves as a map's identity, the program hands the map's address to the helper
diff --git a/src/bpf/order b/src/bpf/order
index e69de29bb2d1..72ab18f1efa0 100644
--- a/src/bpf/order
+++ b/src/bpf/order
@@ -0,0 +1 @@
+dhcp
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 10/21] sdn: dhcp: add an eBPF backend answering on each guest interface
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (8 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 09/21] sdn: dhcp: add the per-tap DHCPv4 responder program Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 11/21] sdn: zones: report interface plugs and unplugs to the DHCP backends Hannes Laimer
                   ` (10 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The ebpf DHCP backend answers DHCPv4 from a program in the kernel on
every guest interface of its zones, with the address the SDN MAC cache
holds for the interface's MAC. No server runs per zone, and IPv6
subnets are not served. A subnet without a gateway is served under a
link-local server identifier no host owns, so its guests renew by
broadcast at their rebinding time.

An apply runs a full pass on each node, and on a node that no zone
with the ebpf backend includes, the pass removes the responder
altogether. A record change rewrites the answers for its MAC on the
node the change is made on, and the other nodes catch up at their
next apply.

An apply asks the IPAM for the addresses the cache lacks before it
takes the responder's lock. Under the lock every address comes from
the cache, so a slow IPAM holds up no guest start.

The responder is pinned in bpffs and does not survive a reboot, so a
boot hook runs a full pass. Removing the package deletes those pins,
since nothing would detach the responder afterward. An upgrade of the
package or of libpve-rs-perl runs a full pass as well, so new programs
or a new map layout take over right away.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 debian/control                      |   1 +
 debian/libpve-network-perl.postinst |  22 +
 debian/libpve-network-perl.prerm    |  13 +
 debian/triggers                     |   1 +
 src/PVE/API2/Network/SDN/Zones.pm   |   3 +-
 src/PVE/Network/SDN/Dhcp.pm         |  96 +++-
 src/PVE/Network/SDN/Dhcp/Dnsmasq.pm |   2 +-
 src/PVE/Network/SDN/Dhcp/Ebpf.pm    | 395 ++++++++++++++
 src/PVE/Network/SDN/Dhcp/Makefile   |   2 +-
 src/PVE/Network/SDN/Dhcp/Plugin.pm  |  24 +-
 src/PVE/Network/SDN/SubnetPlugin.pm |   4 +-
 src/PVE/Network/SDN/Vnets.pm        |   2 +-
 src/test/run_test_vnets_blackbox.pl | 779 +++++++++++++++++++++++++++-
 13 files changed, 1324 insertions(+), 20 deletions(-)
 create mode 100755 debian/libpve-network-perl.prerm
 create mode 100644 src/PVE/Network/SDN/Dhcp/Ebpf.pm

diff --git a/debian/control b/debian/control
index 03c4b60ca7e8..52d2d5c907ee 100644
--- a/debian/control
+++ b/debian/control
@@ -36,6 +36,7 @@ Depends: libpve-common-perl (>= 9.2.4),
          libpve-access-control (>= 9.2.0~),
          libpve-rs-perl (>= 0.15.4),
          libuuid-perl,
+         pve-network-ebpf (= ${binary:Version}),
          ${misc:Depends},
          ${perl:Depends},
 Recommends: frr-pythontools (>= 10.3.1-1+pve2~),
diff --git a/debian/libpve-network-perl.postinst b/debian/libpve-network-perl.postinst
index 99faedf48f56..0c183638761b 100644
--- a/debian/libpve-network-perl.postinst
+++ b/debian/libpve-network-perl.postinst
@@ -22,6 +22,19 @@ migrate_mac_cache() {
   fi
 }
 
+# A full pass loads the shipped BPF programs and moves the links onto them. An
+# upgrade of libpve-rs-perl fires the pve-ebpf-update trigger to run it. When both
+# packages are upgraded in one run, this package is only unpacked when the library
+# is set up, so dpkg drops the trigger and the configure runs the pass. The backend
+# is called directly since PVE::Network::SDN::Dhcp::boot only warns about a failure.
+apply_ebpf_dhcp() {
+  test -f /etc/pve/local/pve-ssl.pem || return 0
+  test -e /proxmox_install_mode && return 0
+
+  perl -MPVE::Network::SDN -e 'PVE::Network::SDN::Dhcp::Ebpf->boot() or exit 1' \
+    || echo "loading the eBPF DHCP responder failed, run an SDN apply or a network reload"
+}
+
 case "$1" in
   configure)
     # TODO: remove with PVE 9+
@@ -29,6 +42,15 @@ case "$1" in
       migrate_ipam_db
       migrate_mac_cache
     fi
+    apply_ebpf_dhcp
+  ;;
+
+  triggered)
+    case " $2 " in
+      *" pve-ebpf-update "*)
+        apply_ebpf_dhcp
+      ;;
+    esac
   ;;
 esac
 
diff --git a/debian/libpve-network-perl.prerm b/debian/libpve-network-perl.prerm
new file mode 100755
index 000000000000..d28c74fe284d
--- /dev/null
+++ b/debian/libpve-network-perl.prerm
@@ -0,0 +1,13 @@
+#!/bin/sh
+
+set -e
+
+case "$1" in
+  remove)
+    # the eBPF DHCP responder stays attached through its pins in bpffs, and with
+    # the package gone nothing would ever update or detach it
+    rm -rf /sys/fs/bpf/proxmox-ebpf/dhcp
+  ;;
+esac
+
+exit 0
diff --git a/debian/triggers b/debian/triggers
index 59dd6885a5f9..1ae80155f635 100644
--- a/debian/triggers
+++ b/debian/triggers
@@ -1 +1,2 @@
 activate-noawait pve-api-updates
+interest-noawait pve-ebpf-update
diff --git a/src/PVE/API2/Network/SDN/Zones.pm b/src/PVE/API2/Network/SDN/Zones.pm
index 74b10f032bf4..4f61e1e858aa 100644
--- a/src/PVE/API2/Network/SDN/Zones.pm
+++ b/src/PVE/API2/Network/SDN/Zones.pm
@@ -14,6 +14,7 @@ use PVE::Network::SDN::Dns;
 use PVE::Network::SDN::Subnets;
 use PVE::Network::SDN::Vnets;
 use PVE::Network::SDN;
+use PVE::Network::SDN::Dhcp;
 
 use PVE::Network::SDN::Zones::EvpnPlugin;
 use PVE::Network::SDN::Zones::FaucetPlugin;
@@ -57,7 +58,7 @@ my $ZONE_PROPERTIES = {
     },
     dhcp => {
         type => 'string',
-        enum => ['dnsmasq'],
+        enum => PVE::Network::SDN::Dhcp->plugin_types(),
         optional => 1,
         description => 'Name of DHCP server backend for this zone.',
     },
diff --git a/src/PVE/Network/SDN/Dhcp.pm b/src/PVE/Network/SDN/Dhcp.pm
index d00f0b960de8..4a8ef716387b 100644
--- a/src/PVE/Network/SDN/Dhcp.pm
+++ b/src/PVE/Network/SDN/Dhcp.pm
@@ -9,6 +9,7 @@ use PVE::Network::SDN;
 use PVE::Network::SDN::Subnets;
 use PVE::Network::SDN::Dhcp::Plugin;
 use PVE::Network::SDN::Dhcp::Dnsmasq;
+use PVE::Network::SDN::Dhcp::Ebpf;
 
 use PVE::INotify;
 
@@ -17,12 +18,15 @@ PVE::Network::SDN::Dhcp::Plugin->init();
 PVE::Network::SDN::Dhcp::Dnsmasq->register();
 PVE::Network::SDN::Dhcp::Dnsmasq->init();
 
+PVE::Network::SDN::Dhcp::Ebpf->register();
+PVE::Network::SDN::Dhcp::Ebpf->init();
+
 sub plugin_types {
     return PVE::Network::SDN::Dhcp::Plugin->lookup_types();
 }
 
 sub update_mapping {
-    my ($vnetid, $mac, $resume) = @_;
+    my ($vnetid, $mac, $resume, $vmid) = @_;
 
     # a record without a MAC has no guest NIC behind it, so no backend serves it
     return if !$mac;
@@ -40,31 +44,101 @@ sub update_mapping {
     return if defined($zone->{nodes}) && !$zone->{nodes}->{ PVE::INotify::nodename() };
 
     PVE::Network::SDN::Dhcp::Plugin->lookup($zone->{dhcp})
-        ->update_ip_mapping($zoneid, $vnetid, $mac, $resume);
+        ->update_ip_mapping($zoneid, $vnetid, $mac, $resume, $vmid);
 }
 
-sub guest_node_by_mac {
-    my ($vnetid, $mac) = @_;
-
-    return if !$mac;
+# the NIC lines come from pmxcfs in one go, so no guest config gets parsed for
+# this. With a vmid only that guest's lines are fetched. The map is keyed by
+# the lower-cased MAC and holds a list per key, since a MAC is unique within a
+# guest but not across the cluster
+sub guest_nics {
+    my ($vmid) = @_;
 
+    # a hook script starts with the cluster cache empty
+    PVE::Cluster::cfs_update();
     my $vmlist = PVE::Cluster::get_vmlist();
-    my $nets = PVE::Cluster::get_guest_config_properties([map { "net$_" } 0 .. 31]);
+    my $nets = PVE::Cluster::get_guest_config_properties([map { "net$_" } 0 .. 31], $vmid);
+    my $nics = {};
     for my $vmid (sort keys %$nets) {
         my $guest = $vmlist->{ids}->{$vmid} // next;
-        for my $net (values %{ $nets->{$vmid} }) {
+        my $prefix = ($guest->{type} // '') eq 'lxc' ? 'veth' : 'tap';
+        for my $key (sort keys %{ $nets->{$vmid} }) {
+            my ($index) = $key =~ m/^net(\d+)$/ or next;
+            my $net = $nets->{$vmid}->{$key};
             my ($bridge) = $net =~ m/(?:^|,)bridge=([^,]+)/ or next;
-            next if $bridge ne $vnetid;
             # a VM names the MAC as the value of its model, a container as hwaddr
-            my ($nic_mac) = $net =~ m/(?:^|,)[a-z0-9_-]+=([0-9a-f]{2}(?::[0-9a-f]{2}){5})(?:,|$)/i
+            my ($mac) = $net =~ m/(?:^|,)[a-z0-9_-]+=([0-9a-f]{2}(?::[0-9a-f]{2}){5})(?:,|$)/i
                 or next;
-            return ($guest->{node}, $vmid) if lc($nic_mac) eq lc($mac);
+            push $nics->{ lc($mac) }->@*,
+                {
+                    vmid => $vmid,
+                    node => $guest->{node},
+                    iface => "$prefix${vmid}i$index",
+                    bridge => $bridge,
+                    mac => lc($mac),
+                };
         }
     }
 
+    return $nics;
+}
+
+sub guest_node_by_mac {
+    my ($vnetid, $mac) = @_;
+
+    return if !$mac;
+
+    for my $nic ((guest_nics()->{ lc($mac) } // [])->@*) {
+        return ($nic->{node}, $nic->{vmid}) if $nic->{bridge} eq $vnetid;
+    }
+
     return;
 }
 
+my sub unplug_backends {
+    my ($iface, $target, $skip) = @_;
+
+    for my $type (PVE::Network::SDN::Dhcp::Plugin->lookup_types()->@*) {
+        next if defined($skip) && $type eq $skip;
+        eval { PVE::Network::SDN::Dhcp::Plugin->lookup($type)->tap_unplug($iface, $target) };
+        warn "could not unplug $iface from the $type dhcp backend: $@" if $@;
+    }
+}
+
+sub tap_plug {
+    my ($bridge, $iface, $mac) = @_;
+
+    my $vnet = PVE::Network::SDN::Vnets::get_vnet($bridge, 1);
+    my $zone = $vnet ? PVE::Network::SDN::Zones::get_zone($vnet->{zone}, 1) : undef;
+    my $backend = $zone ? $zone->{dhcp} : undef;
+
+    # every other backend hears where the interface sits now. A plain bridge
+    # is no vnet
+    unplug_backends($iface, { vnet => $vnet ? $bridge : undef, mac => $mac }, $backend);
+    return if !$backend;
+
+    eval {
+        PVE::Network::SDN::Dhcp::Plugin->lookup($backend)
+            ->tap_plug($vnet->{zone}, $bridge, $iface, $mac);
+    };
+    warn "could not plug $iface into the dhcp backend of zone $vnet->{zone}: $@" if $@;
+}
+
+sub boot {
+    for my $type (PVE::Network::SDN::Dhcp::Plugin->lookup_types()->@*) {
+        eval { PVE::Network::SDN::Dhcp::Plugin->lookup($type)->boot() };
+        warn "could not bring up the $type dhcp backend: $@" if $@;
+    }
+}
+
+# the interface is usually gone already and with it any way to its zone, so
+# every backend is told
+sub tap_unplug {
+    my ($iface) = @_;
+
+    unplug_backends($iface);
+}
+
 sub regenerate_config {
     my ($reload) = @_;
 
diff --git a/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm b/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
index 491c7cb1789b..4cb68188bfb1 100644
--- a/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
+++ b/src/PVE/Network/SDN/Dhcp/Dnsmasq.pm
@@ -54,7 +54,7 @@ sub update_lease {
 }
 
 sub update_ip_mapping {
-    my ($class, $dhcpid, $vnetid, $mac, $resume) = @_;
+    my ($class, $dhcpid, $vnetid, $mac, $resume, $vmid) = @_;
     $mac = lc($mac);
 
     my $ethers_file = ethers_file($dhcpid);
diff --git a/src/PVE/Network/SDN/Dhcp/Ebpf.pm b/src/PVE/Network/SDN/Dhcp/Ebpf.pm
new file mode 100644
index 000000000000..081aa0e2e78f
--- /dev/null
+++ b/src/PVE/Network/SDN/Dhcp/Ebpf.pm
@@ -0,0 +1,395 @@
+package PVE::Network::SDN::Dhcp::Ebpf;
+
+use strict;
+use warnings;
+
+use base qw(PVE::Network::SDN::Dhcp::Plugin);
+
+use Net::IP;
+use Net::Subnet qw(subnet_matcher);
+
+use PVE::Cluster;
+use PVE::INotify;
+use PVE::RESTEnvironment qw(log_warn);
+
+use PVE::RS::SDN::Dhcp;
+use PVE::RS::SDN::Dhcp::ExclusiveLock;
+use PVE::RS::SDN::Dhcp::SharedLock;
+
+my $DEFAULT_LEASE_TIME = 600;
+
+# a subnet without a gateway is served under a link-local server identifier,
+# which no host on the subnet owns. A guest cannot renew by unicast then and
+# broadcasts at its rebinding time instead
+my $SERVER_ID_NO_GATEWAY = '169.254.0.1';
+
+sub type {
+    return 'ebpf';
+}
+
+# the MTU option is 16 bits wide with 68 the smallest MTU IPv4 allows, so a
+# zone MTU outside that is reported on an apply and not handed out. A zone
+# without one hands out none and the guest keeps its own setting
+my sub zone_mtu {
+    my ($zoneid, $zone, $report) = @_;
+
+    my $mtu = PVE::Network::SDN::Zones::Plugin->lookup($zone->{type})->get_mtu($zone);
+    return undef if !defined($mtu);
+    return $mtu if $mtu >= 68 && $mtu <= 65535;
+    log_warn("zone $zoneid has MTU $mtu, not handing it out over DHCP") if $report;
+    return undef;
+}
+
+my sub dhcp_record {
+    my ($ip4, $subnet, $mtu) = @_;
+
+    my $gateway = $subnet->{gateway};
+
+    # a DNS server has to be reachable over the address family served
+    my $dns = $subnet->{'dhcp-dns-server'};
+    $dns = undef if defined($dns) && !Net::IP::ip_is_ipv4($dns);
+
+    # the config hands its numbers over as strings, while the bindings take integers only
+    return {
+        ip => $ip4,
+        prefixlen => int($subnet->{mask}),
+        server_id => $gateway // $SERVER_ID_NO_GATEWAY,
+        lease => int($subnet->{'dhcp-lease-time'} // $DEFAULT_LEASE_TIME),
+        router => $gateway,
+        dns => $dns,
+        mtu => defined($mtu) ? int($mtu) : undef,
+    };
+}
+
+# the IPv4 subnets of a vnet, warning about a DNS server the reply cannot
+# carry when asked to. Only the apply asks, so a guest start does not repeat
+# the warning
+my sub served_subnets {
+    my ($subnets, $report) = @_;
+
+    my $served = [];
+    for my $subnetid (sort keys %$subnets) {
+        my $subnet = $subnets->{$subnetid};
+        next if !Net::IP::ip_is_ipv4($subnet->{network});
+        if (
+            $report
+            && defined($subnet->{'dhcp-dns-server'})
+            && !Net::IP::ip_is_ipv4($subnet->{'dhcp-dns-server'})
+        ) {
+            log_warn("subnet $subnetid has an IPv6 DNS server, not handing it out over IPv4");
+        }
+        push @$served, $subnet;
+    }
+
+    return $served;
+}
+
+my $matchers = {};
+
+# the vnet's subnet holding the address decides the answer
+my sub vnet_record {
+    my ($subnets, $mtu, $ip4) = @_;
+
+    return undef if !$ip4;
+    # the most specific of overlapping subnets is the one to answer from
+    for my $subnet (sort { $b->{mask} <=> $a->{mask} } @$subnets) {
+        my $matcher = $matchers->{ $subnet->{cidr} } //= subnet_matcher($subnet->{cidr});
+        next if !$matcher->($ip4);
+        # the vnet's own gateway address is cached too and never a lease
+        return undef if defined($subnet->{gateway}) && $ip4 eq $subnet->{gateway};
+        return dhcp_record($ip4, $subnet, $mtu);
+    }
+
+    return undef;
+}
+
+# the bridge an interface is attached to. With the firewall on, the interface
+# sits on a bridge of its own, and a veth peer of that bridge sits on the vnet
+sub attached_bridge {
+    my ($iface) = @_;
+
+    my $master = readlink("/sys/class/net/$iface/master") // return undef;
+    if ($master =~ m!/fwbr(\d+)i(\d+)$!) {
+        $master = readlink("/sys/class/net/fwpr$1p$2/master") // return undef;
+    }
+    return $master =~ s!^.*/!!r;
+}
+
+# the zones of this node with ebpf as their DHCP backend. A zone confined to other nodes runs
+# no responder here
+my sub ebpf_zones {
+    my ($zones) = @_;
+
+    my $nodename = PVE::INotify::nodename();
+    my %ebpf = map { $_ => 1 } grep {
+        ($zones->{$_}->{dhcp} // '') eq 'ebpf'
+            && (!defined($zones->{$_}->{nodes}) || $zones->{$_}->{nodes}->{$nodename})
+    } keys %$zones;
+    return \%ebpf;
+}
+
+# the guest NICs a full pass serves, each with the id of its zone
+my sub served_nics {
+    my ($vnets, $ebpf) = @_;
+
+    my $served = [];
+    my @nics = map { $_->@* } values PVE::Network::SDN::Dhcp::guest_nics()->%*;
+    for my $nic (sort { $a->{vmid} cmp $b->{vmid} || $a->{iface} cmp $b->{iface} } @nics) {
+        my $vnetid = $nic->{bridge};
+        my $zoneid = $vnets->{$vnetid} ? $vnets->{$vnetid}->{zone} : undef;
+        next if !$zoneid || !$ebpf->{$zoneid};
+        # during a hotplug the NIC's new bridge is still pending in the guest config. The NIC is
+        # served once the change is applied
+        next if (attached_bridge($nic->{iface}) // '') ne $vnetid;
+        push @$served, { $nic->%*, zone => $zoneid };
+    }
+    return $served;
+}
+
+# the address the MAC cache holds for a MAC on a vnet, none if the cache does not trust its entry
+my sub cached_ip4 {
+    my ($cache, $vnetid, $mac, $subnets) = @_;
+
+    return undef if !PVE::Network::SDN::Ipams::cache_witnessed($cache, $vnetid, $mac);
+    my ($ip4) = PVE::Network::SDN::Ipams::cached_ips_from_mac($cache, $vnetid, $mac, $subnets);
+    return $ip4;
+}
+
+# the answer for a MAC on a vnet, from the address the MAC cache holds for it
+my sub nic_record {
+    my ($cache, $vnetid, $zoneid, $zone, $mac) = @_;
+
+    my $subnets = PVE::Network::SDN::Vnets::get_subnets($vnetid, 1) // {};
+    my $ip4 = cached_ip4($cache, $vnetid, $mac, $subnets);
+    return vnet_record(served_subnets($subnets, 0), zone_mtu($zoneid, $zone, 0), $ip4);
+}
+
+# asks the IPAM for every served NIC whose address the cache lacks or does not trust, and the
+# lookup fills the cache. An apply runs this before it takes the lock, so a slow IPAM holds up
+# no plug. The first lookup that fails ends it
+my sub fill_cache {
+    eval {
+        PVE::Cluster::cfs_update();
+        my $cfg = PVE::Network::SDN::running_config();
+        my $zones = $cfg->{zones}->{ids} // {};
+        my $ebpf = ebpf_zones($zones);
+        return if !%$ebpf;
+
+        my $cache = PVE::Network::SDN::Ipams::read_cache();
+        my (%subnets, %served);
+        for my $nic (served_nics($cfg->{vnets}->{ids} // {}, $ebpf)->@*) {
+            my $vnetid = $nic->{bridge};
+            next if !$nic->{mac} || !$zones->{ $nic->{zone} }->{ipam};
+            $subnets{$vnetid} //= PVE::Network::SDN::Vnets::get_subnets($vnetid, 1) // {};
+            $served{$vnetid} //= served_subnets($subnets{$vnetid}, 0);
+            next if !$served{$vnetid}->@*;
+            next if defined(cached_ip4($cache, $vnetid, $nic->{mac}, $subnets{$vnetid}));
+            my ($ip4) = PVE::Network::SDN::Vnets::get_ips_from_mac($vnetid, $nic->{mac}, 1);
+            next if !defined($ip4);
+            # the lookup skips its cache write if the cache changed meanwhile, and the pass
+            # reads the cache alone
+            my $filled = PVE::Network::SDN::Ipams::read_cache();
+            next if defined(cached_ip4($filled, $vnetid, $nic->{mac}, $subnets{$vnetid}));
+            log_warn("could not cache the IPAM address of $nic->{iface},"
+                . " the interface is not served until the next SDN apply");
+        }
+    };
+    log_warn("could not fill the MAC cache from the IPAM: $@") if $@;
+}
+
+my sub full_state {
+    my ($report) = @_;
+
+    # the configs and the cache are read after the cluster state is refreshed,
+    # since a copy from before the lock was taken would hand the pass older input
+    PVE::Cluster::cfs_update();
+    my $cfg = PVE::Network::SDN::running_config();
+    my $zones = $cfg->{zones}->{ids} // {};
+    my $vnets = $cfg->{vnets}->{ids} // {};
+    my $ebpf = ebpf_zones($zones);
+    return (0, []) if !%$ebpf;
+
+    my (%mtu, %subnets, %served);
+    # a subnet or a zone MTU the responder cannot serve is reported per apply,
+    # guests or not
+    for my $vnetid (sort keys %$vnets) {
+        my $zoneid = $vnets->{$vnetid}->{zone};
+        next if !$zoneid || !$ebpf->{$zoneid};
+        $subnets{$vnetid} = PVE::Network::SDN::Vnets::get_subnets($vnetid, 1) // {};
+        $served{$vnetid} = served_subnets($subnets{$vnetid}, $report);
+        $mtu{$zoneid} = zone_mtu($zoneid, $zones->{$zoneid}, $report) if !exists $mtu{$zoneid};
+    }
+    my $ifaces = [];
+    # every plug waits for the pass, so it reads the cache alone and only once
+    my $cache = PVE::Network::SDN::Ipams::read_cache();
+    for my $nic (served_nics($vnets, $ebpf)->@*) {
+        my ($vnetid, $zoneid) = $nic->@{qw(bridge zone)};
+        my $record;
+        if ($nic->{mac} && $zones->{$zoneid}->{ipam}) {
+            my $ip4 = cached_ip4($cache, $vnetid, $nic->{mac}, $subnets{$vnetid});
+            $record = vnet_record($served{$vnetid}, $mtu{$zoneid}, $ip4);
+        }
+        push @$ifaces, { name => $nic->{iface}, mac => $nic->{mac}, record => $record };
+    }
+
+    return (scalar(keys %$ebpf), $ifaces);
+}
+
+my sub full_pass {
+    my ($report) = @_;
+
+    my $lock = eval { PVE::RS::SDN::Dhcp::ExclusiveLock->new() };
+    if (!$lock) {
+        log_warn("could not lock the DHCP responder: $@");
+        return;
+    }
+
+    my ($zones, $ifaces) = eval { full_state($report) };
+    if ($@) {
+        log_warn("could not collect the DHCP responder state: $@");
+        return;
+    }
+
+    eval { $zones ? $lock->apply($ifaces) : $lock->clear() };
+    if ($@) {
+        log_warn("could not apply the DHCP responder state: $@");
+        return;
+    }
+    return 1;
+}
+
+my sub mac_ifaces {
+    my ($vnetid, $mac, $vmid) = @_;
+
+    my $cfg = PVE::Network::SDN::running_config();
+    my $zones = $cfg->{zones}->{ids} // {};
+    my $vnets = $cfg->{vnets}->{ids} // {};
+    my $ifaces = [];
+    my $cache = PVE::Network::SDN::Ipams::read_cache();
+    for my $nic ((PVE::Network::SDN::Dhcp::guest_nics($vmid)->{ lc($mac) } // [])->@*) {
+        next if $nic->{bridge} ne $vnetid;
+        my $vnet = $vnets->{ $nic->{bridge} } // next;
+        my $zone = $zones->{ $vnet->{zone} } // next;
+        next if ($zone->{dhcp} // '') ne 'ebpf';
+        my $record;
+        $record = nic_record($cache, $vnetid, $vnet->{zone}, $zone, $mac)
+            if $zone->{ipam} && (attached_bridge($nic->{iface}) // '') eq $vnetid;
+        push @$ifaces, { name => $nic->{iface}, mac => $nic->{mac}, record => $record };
+    }
+
+    return $ifaces;
+}
+
+# under the guest lock nothing else writes the guest's entries, so a caller
+# that names the guest takes the shared lock. An API edit names no guest and
+# takes the exclusive one
+sub update_ip_mapping {
+    my ($class, $dhcpid, $vnetid, $mac, $resume, $vmid) = @_;
+
+    # a resume finds the entries current. The plug of an incoming migration
+    # wrote them, and an edit waits for the migration to end
+    return if $resume;
+
+    my $update = sub {
+        my $lock =
+            defined($vmid)
+            ? PVE::RS::SDN::Dhcp::SharedLock->new()
+            : PVE::RS::SDN::Dhcp::ExclusiveLock->new();
+        PVE::Cluster::cfs_update();
+        my $ifaces = mac_ifaces($vnetid, $mac, $vmid);
+        return 1 if !@$ifaces;
+        return $lock->update($ifaces);
+    };
+
+    my $done = eval { $update->() };
+    die "could not update the DHCP responder records of $mac: $@" if $@;
+    return if $done;
+
+    # nothing loaded, the pass takes its own lock once the update's is gone
+    full_pass(0) or die "could not load the DHCP responder\n";
+}
+
+# the dispatcher's per-zone walk is not needed, since the full pass collects
+# the state itself
+sub before_regenerate { }
+sub before_configure { }
+sub configure_subnet { }
+sub configure_range { }
+sub configure_vnet { }
+sub after_configure { }
+
+sub after_regenerate {
+    my ($class) = @_;
+
+    fill_cache();
+    full_pass(1);
+}
+
+sub boot {
+    my ($class) = @_;
+
+    fill_cache();
+    return full_pass(1);
+}
+
+# a plug onto a vnet or a plain bridge. The caller picked the backend from a
+# config read before the lock, so the zone is read again under it. An apply
+# that switched the backend meanwhile is then either seen here or runs after
+my sub plug {
+    my ($iface, $vnetid, $mac) = @_;
+
+    my $lock = PVE::RS::SDN::Dhcp::SharedLock->new();
+    if (!defined($vnetid)) {
+        $lock->detach($iface);
+        return 1;
+    }
+    PVE::Cluster::cfs_update();
+    my $vnet = PVE::Network::SDN::Vnets::get_vnet($vnetid, 1);
+    my $zoneid = $vnet ? $vnet->{zone} : undef;
+    my $zone = $zoneid ? PVE::Network::SDN::Zones::get_zone($zoneid, 1) : undef;
+    if (!$zone || ($zone->{dhcp} // '') ne 'ebpf') {
+        $lock->detach($iface);
+        return 1;
+    }
+    my $record;
+    $record = nic_record(PVE::Network::SDN::Ipams::read_cache(), $vnetid, $zoneid, $zone, $mac)
+        if $mac && $zone->{ipam};
+    return $lock->attach($iface, $mac || undef, $record);
+}
+
+my sub plug_or_warn {
+    my ($iface, $vnetid, $mac) = @_;
+
+    my $done = eval { plug($iface, $vnetid, $mac) };
+    if ($@) {
+        log_warn("could not update the DHCP responder on $iface: $@");
+        return;
+    }
+    return if $done;
+
+    # nothing is loaded, after a rebuild or a boot where the SDN commit loaded
+    # nothing. The plug's lock is gone by here, so the pass can take its own
+    full_pass(0);
+    $done = eval { plug($iface, $vnetid, $mac) };
+    log_warn("could not update the DHCP responder on $iface: " . ($@ || "nothing is loaded"))
+        if $@ || !$done;
+}
+
+sub tap_unplug {
+    my ($class, $iface, $target) = @_;
+
+    if ($target) {
+        plug_or_warn($iface, $target->{vnet}, $target->{mac});
+        return;
+    }
+    eval { PVE::RS::SDN::Dhcp::detach($iface) };
+    log_warn("could not detach the DHCP responder from $iface: $@") if $@;
+}
+
+sub tap_plug {
+    my ($class, $dhcpid, $vnetid, $iface, $mac) = @_;
+
+    plug_or_warn($iface, $vnetid, $mac);
+}
+
+1;
diff --git a/src/PVE/Network/SDN/Dhcp/Makefile b/src/PVE/Network/SDN/Dhcp/Makefile
index 65465135a51c..ce86aaef97a2 100644
--- a/src/PVE/Network/SDN/Dhcp/Makefile
+++ b/src/PVE/Network/SDN/Dhcp/Makefile
@@ -1,4 +1,4 @@
-SOURCES=Plugin.pm Dnsmasq.pm
+SOURCES=Plugin.pm Dnsmasq.pm Ebpf.pm
 
 
 PERL5DIR=${DESTDIR}/usr/share/perl5
diff --git a/src/PVE/Network/SDN/Dhcp/Plugin.pm b/src/PVE/Network/SDN/Dhcp/Plugin.pm
index a3e5102b601a..3a0823565589 100644
--- a/src/PVE/Network/SDN/Dhcp/Plugin.pm
+++ b/src/PVE/Network/SDN/Dhcp/Plugin.pm
@@ -25,9 +25,10 @@ sub private {
 # the MAC's records on the vnet changed, so make the backend serve the current
 # ones. With no record left its reservation on the vnet goes. Dies if the
 # backend could not be updated. For a resume the push does not wait long for
-# a busy backend
+# a busy backend. The vmid names the guest when the caller knows it, which an
+# API edit does not
 sub update_ip_mapping {
-    my ($class, $dhcpid, $vnetid, $mac, $resume) = @_;
+    my ($class, $dhcpid, $vnetid, $mac, $resume, $vmid) = @_;
     die 'implement in sub class';
 }
 
@@ -61,9 +62,28 @@ sub before_regenerate {
     die 'implement in sub class';
 }
 
+# the node booted. A backend whose state does not survive a reboot brings it
+# back here, before the guests start
+sub boot {
+    my ($class) = @_;
+}
+
 sub after_regenerate {
     my ($class) = @_;
     die 'implement in sub class';
 }
 
+# a guest interface was plugged into a vnet of a zone using this backend.
+# Backends serving the bridge rather than the interface have nothing to do
+sub tap_plug {
+    my ($class, $dhcpid, $vnetid, $iface, $mac) = @_;
+}
+
+# a guest interface left its vnet or went away, and by then nothing says which
+# zone it was on. The target is the vnet it sits on now, none for a plain
+# bridge, with the NIC's MAC. Without a target the backend drops it
+sub tap_unplug {
+    my ($class, $iface, $target) = @_;
+}
+
 1;
diff --git a/src/PVE/Network/SDN/SubnetPlugin.pm b/src/PVE/Network/SDN/SubnetPlugin.pm
index 29edf7b65330..38579f213206 100644
--- a/src/PVE/Network/SDN/SubnetPlugin.pm
+++ b/src/PVE/Network/SDN/SubnetPlugin.pm
@@ -183,8 +183,8 @@ sub properties {
             maximum => 4294967295,
             description =>
                 'Lease time in seconds for DHCP answers. Without it dnsmasq hands out'
-                . ' infinite leases, and it raises anything below two minutes to two'
-                . ' minutes.',
+                . ' infinite leases and the ebpf responder ten minutes. dnsmasq raises'
+                . ' anything below two minutes to two minutes.',
             optional => 1,
         },
     };
diff --git a/src/PVE/Network/SDN/Vnets.pm b/src/PVE/Network/SDN/Vnets.pm
index 58db0f803f8b..3543345a6f01 100644
--- a/src/PVE/Network/SDN/Vnets.pm
+++ b/src/PVE/Network/SDN/Vnets.pm
@@ -242,7 +242,7 @@ sub add_dhcp_mapping {
     ($ip4, $ip6) = PVE::Network::SDN::Vnets::get_ips_from_mac($vnetid, $mac);
     return if !$ip4 && !$ip6;
     # a guest start does not fail on its DHCP backend
-    eval { PVE::Network::SDN::Dhcp::update_mapping($vnetid, $mac) };
+    eval { PVE::Network::SDN::Dhcp::update_mapping($vnetid, $mac, undef, $vmid) };
     warn $@ if $@;
 }
 
diff --git a/src/test/run_test_vnets_blackbox.pl b/src/test/run_test_vnets_blackbox.pl
index 0d8e760561d2..23d1844274d7 100755
--- a/src/test/run_test_vnets_blackbox.pl
+++ b/src/test/run_test_vnets_blackbox.pl
@@ -51,6 +51,11 @@ sub clear_test_state {
         macdb => {},
         ipamdb => {},
         dnsmasq_calls => [],
+        ebpf_calls => [],
+        lock_modes => [],
+        nic_listings => [],
+        order => [],
+        warnings => [],
         ipam_config => {
             'ids' => {
                 'pve' => {
@@ -59,6 +64,8 @@ sub clear_test_state {
             },
         },
         fabrics => {},
+        ebpf_answer => undef,
+        attached => {},
     };
     PVE::Tools::file_set_contents($TMP_ETHERS_FILE, "\n");
 }
@@ -252,6 +259,52 @@ $mocked_sdn_fabrics->mock(
     cfs_lock_file => $mocked_cfs_lock_file,
 );
 
+my $mocked_pve_rs_dhcp = Test::MockModule->new('PVE::RS::SDN::Dhcp');
+$mocked_pve_rs_dhcp->mock(
+    detach => sub {
+        push $test_state->{ebpf_calls}->@*, { method => 'detach', args => [@_] };
+        return $test_state->{ebpf_answer}->{detach} // 1;
+    },
+);
+
+# taking a lock is the ordered step, and the responder calls are its methods
+my %mocked_pve_rs_dhcp_locks;
+for my $class (qw(SharedLock ExclusiveLock)) {
+    my $package = "PVE::RS::SDN::Dhcp::$class";
+    my $mock = Test::MockModule->new($package, no_auto => 1);
+    $mock->mock(
+        new => sub {
+            push $test_state->{order}->@*, 'lock';
+            push $test_state->{lock_modes}->@*, $class eq 'SharedLock' ? 'shared' : 'exclusive';
+            return bless {}, $package;
+        },
+        map {
+            my $method = $_;
+            $method => sub {
+                my ($self, @args) = @_;
+                push $test_state->{order}->@*, 'write';
+                push $test_state->{ebpf_calls}->@*, { method => $method, args => [@args] };
+                return $test_state->{ebpf_answer}->{$method} // 1;
+            };
+        } ($class eq 'SharedLock' ? qw(attach detach update) : qw(apply update clear)),
+    );
+    $mocked_pve_rs_dhcp_locks{$class} = $mock;
+}
+
+my $mocked_sdn_dhcp_ebpf = Test::MockModule->new('PVE::Network::SDN::Dhcp::Ebpf');
+$mocked_sdn_dhcp_ebpf->mock(
+    log_warn => sub { push $test_state->{warnings}->@*, $_[0]; },
+    # an interface sits on the bridge its guest config names, unless a test moved it
+    attached_bridge => sub {
+        my ($iface) = @_;
+        return $test_state->{attached}->{$iface} if exists $test_state->{attached}->{$iface};
+        my ($vmid, $index) = $iface =~ m/^(?:tap|veth)(\d+)i(\d+)$/ or return undef;
+        my $nets = ($test_state->{guest_nets} // {})->{$vmid} // return undef;
+        my ($bridge) = ($nets->{"net$index"} // '') =~ m/(?:^|,)bridge=([^,]+)/;
+        return $bridge;
+    },
+);
+
 my $mocked_api_zones = Test::MockModule->new('PVE::API2::Network::SDN::Zones');
 $mocked_api_zones->mock(
     create_etc_interfaces_sdn_dir => sub { },
@@ -287,11 +340,18 @@ $mocked_pve_cluster_obj->mock(
     # a vmlist change a test parks here lands with the next refresh, as a
     # change made meanwhile on the cluster does
     cfs_update => sub {
+        push $test_state->{order}->@*, 'refresh';
         $test_state->{vmlist} = delete $test_state->{vmlist_pending}
             if $test_state->{vmlist_pending};
     },
     get_vmlist => sub { return $test_state->{vmlist} // { ids => {} }; },
-    get_guest_config_properties => sub { return $test_state->{guest_nets} // {}; },
+    get_guest_config_properties => sub {
+        my ($properties, $vmid) = @_;
+        my $nets = $test_state->{guest_nets} // {};
+        push $test_state->{nic_listings}->@*, $vmid;
+        return $nets if !defined($vmid);
+        return exists $nets->{$vmid} ? { $vmid => $nets->{$vmid} } : {};
+    },
 );
 
 # ------- TEST FUNCTIONS --------------
@@ -427,6 +487,24 @@ sub delete_ip {
     return PVE::API2::Network::SDN::Ips->ipdelete($param);
 }
 
+sub take_ebpf_calls {
+    my $calls = $test_state->{ebpf_calls};
+    $test_state->{ebpf_calls} = [];
+    return $calls;
+}
+
+# the lock takes, cluster refreshes and responder writes in the order they
+# ran, a repeated step collapsed into one
+sub take_order {
+    my $order = $test_state->{order};
+    $test_state->{order} = [];
+    my @shape;
+    for my $step (@$order) {
+        push @shape, $step if !@shape || $shape[-1] ne $step;
+    }
+    return \@shape;
+}
+
 sub run_test {
     my $test = shift;
     clear_test_state();
@@ -1951,4 +2029,703 @@ sub test_dnsmasq_reservation_per_vnet {
 
 run_test(\&test_dnsmasq_reservation_per_vnet);
 
+# -------------- ebpf dhcp backend
+my $ebpf_record = sub {
+    my ($ip, %over) = @_;
+    return {
+        ip => $ip,
+        prefixlen => 24,
+        server_id => '10.0.0.1',
+        lease => 600,
+        router => '10.0.0.1',
+        dns => undef,
+        mtu => undef,
+        %over,
+    };
+};
+
+sub test_ebpf_backend {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+
+    # the guest behind the MAC runs here, so its interface gets the record
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    take_ebpf_calls();
+    $test_state->{nic_listings} = [];
+    $test_state->{lock_modes} = [];
+    eval { nic_start($vnetid, $mac, "999", "testhostname"); };
+    if ($@) {
+        fail("$test_name: nic_start: $@");
+        return;
+    }
+    is(
+        $test_state->{nic_listings}->[0],
+        999,
+        "$test_name: the start reads its own guest's config only",
+    );
+    eq_or_diff(
+        $test_state->{lock_modes},
+        ['shared'],
+        "$test_name: and writes its record under the shared lock",
+    );
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'update',
+            args => [[{
+                name => 'tap999i0',
+                mac => $mac,
+                record => $ebpf_record->("10.0.0.100"),
+            }]],
+        }],
+        "$test_name: a guest start writes the record of its interface",
+    );
+
+    # a mapping edit rewrites it, and a delete leaves the interface without one
+    $test_state->{lock_modes} = [];
+    update_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.150",
+    });
+    eq_or_diff(
+        $test_state->{lock_modes},
+        ['exclusive'],
+        "$test_name: an edit names no guest and writes under the exclusive lock",
+    );
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'update',
+            args => [[{
+                name => 'tap999i0',
+                mac => $mac,
+                record => $ebpf_record->("10.0.0.150"),
+            }]],
+        }],
+        "$test_name: a mapping edit rewrites the record",
+    );
+
+    # a hotplug moved the interface and its new bridge is still pending in the config
+    $test_state->{attached}->{tap999i0} = 'vmbr0';
+    PVE::Network::SDN::Dhcp::update_mapping($vnetid, $mac);
+    delete $test_state->{attached}->{tap999i0};
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'update', args => [[{ name => 'tap999i0', mac => $mac, record => undef }]] }],
+        "$test_name: a record change writes no record for an interface off its config's bridge",
+    );
+
+    delete_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.150",
+    });
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'update',
+            args => [[{ name => 'tap999i0', mac => $mac, record => undef }]],
+        }],
+        "$test_name: a mapping delete drops the record",
+    );
+
+    # the pass and the plug below answer with this mapping
+    create_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.150",
+    });
+    take_ebpf_calls();
+
+    # a resume finds the entries current and takes no lock the guest would
+    # wait on
+    $test_state->{order} = [];
+    PVE::Network::SDN::Dhcp::update_mapping($vnetid, $mac, 1);
+    eq_or_diff(take_ebpf_calls(), [], "$test_name: a resume leaves the responder alone");
+    eq_or_diff($test_state->{order}, [], "$test_name: without taking its lock");
+
+    # the full pass hands in every guest NIC on an ebpf vnet with its answer.
+    # A NIC on a plain bridge is left out, and so is a guest the vmlist does
+    # not know
+    $test_state->{vmlist} = {
+        ids => {
+            100 => { type => 'qemu', node => 'localnode' },
+            101 => { type => 'lxc', node => 'localnode' },
+            103 => { type => 'qemu', node => 'localnode' },
+        },
+    };
+    $test_state->{guest_nets} = {
+        100 => {
+            net0 => "virtio=$mac,bridge=$vnetid,firewall=1",
+            net1 => "virtio=00:11:22:33:44:55,bridge=vmbr0",
+        },
+        101 => { net2 => "name=eth0,bridge=$vnetid,hwaddr=00:11:22:33:44:66" },
+        102 => { net0 => "virtio=00:11:22:33:44:77,bridge=$vnetid" },
+        # a line without a MAC has nothing to answer and is left out
+        103 => { net0 => "virtio,bridge=$vnetid" },
+    };
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'apply',
+            args => [[
+                { name => 'tap100i0', mac => $mac, record => $ebpf_record->("10.0.0.150") },
+                { name => 'veth101i2', mac => '00:11:22:33:44:66', record => undef },
+            ]],
+        }],
+        "$test_name: the full pass hands in the NICs on an ebpf vnet with their answers",
+    );
+
+    # a hotplug moved an interface and its new bridge is still pending in the config
+    $test_state->{attached}->{veth101i2} = 'vmbr0';
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    delete $test_state->{attached}->{veth101i2};
+    eq_or_diff(
+        [map { $_->{name} } take_ebpf_calls()->[0]->{args}->[0]->@*],
+        ['tap100i0'],
+        "$test_name: the full pass leaves out an interface off its config's bridge",
+    );
+
+    # a responder with nothing loaded cannot take a single record, so the
+    # full pass loads it and fills everything
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    $test_state->{ebpf_answer} = { update => 0 };
+    $test_state->{lock_modes} = [];
+    nic_start($vnetid, $mac, "999", "testhostname");
+    $test_state->{ebpf_answer} = undef;
+    eq_or_diff(
+        [map { $_->{method} } take_ebpf_calls()->@*],
+        ['update', 'apply'],
+        "$test_name: an unloaded responder gets the full pass",
+    );
+    eq_or_diff(
+        $test_state->{lock_modes},
+        ['shared', 'exclusive'],
+        "$test_name: which takes its own lock after the record change let go",
+    );
+
+    # a plug attaches the interface with the answer its MAC gets on the
+    # vnet. With nothing loaded the full pass runs first and the attach is
+    # retried
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug($zoneid, $vnetid, 'tap999i0', $mac);
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', $mac, $ebpf_record->("10.0.0.150")] }],
+        "$test_name: a plug attaches its interface with the record",
+    );
+    $test_state->{ebpf_answer} = { attach => 0 };
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug($zoneid, $vnetid, 'tap999i0', $mac);
+    $test_state->{ebpf_answer} = undef;
+    eq_or_diff(
+        [map { $_->{method} } take_ebpf_calls()->@*],
+        ['attach', 'apply', 'attach'],
+        "$test_name: a plug with nothing loaded runs the full pass first",
+    );
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug($zoneid, $vnetid, 'tap999i0');
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', undef, undef] }],
+        "$test_name: a plug without a MAC attaches with nothing to answer",
+    );
+}
+
+sub test_ebpf_backend_edge_cases {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # a regenerate without any ebpf zone tears the responder state down
+    create_zone({
+        type => "simple",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'clear', args => [] }],
+        "$test_name: regenerate without an ebpf zone clears the responder",
+    );
+
+    # an ebpf zone confined to other nodes runs no responder here either
+    update_zone($zoneid, { dhcp => "ebpf", nodes => 'other' });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'clear', args => [] }],
+        "$test_name: an ebpf zone confined to other nodes clears the responder here",
+    );
+    update_zone($zoneid, { delete => 'nodes' });
+
+    # the SDN commit brings the responder back at boot, one full pass
+    PVE::Network::SDN::Dhcp::boot();
+    eq_or_diff(
+        [map { $_->{method} } take_ebpf_calls()->@*],
+        ['apply'],
+        "$test_name: the boot runs the full pass",
+    );
+
+    # the zone switches to ebpf, but its subnets lack what a record needs
+    update_zone($zoneid, { dhcp => "ebpf" });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "fd00::/64",
+        gateway => "fd00::1",
+        'dhcp-range' => ["start-address=fd00::100,end-address=fd00::200"],
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+
+    take_ebpf_calls();
+    eval { nic_start($vnetid, $mac, "999", "testhostname"); };
+    if ($@) {
+        fail("$test_name: nic_start: $@");
+        return;
+    }
+
+    # a gateway-less v4 subnet is served under a link-local identifier and
+    # without a router. The v6 subnet yields nothing
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'update',
+            args => [[{
+                name => 'tap999i0',
+                mac => $mac,
+                record => $ebpf_record->(
+                    "10.0.0.100",
+                    server_id => '169.254.0.1',
+                    router => undef,
+                ),
+            }]],
+        }],
+        "$test_name: a subnet without a gateway is served without a router",
+    );
+    $test_state->{warnings} = [];
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    take_ebpf_calls();
+    is(scalar($test_state->{warnings}->@*), 0, "$test_name: and the full pass has nothing to say");
+
+    # a v6 resolver on a v4 subnet is dropped from the record instead of
+    # failing the whole set
+    update_subnet({
+        vnet => $vnetid,
+        subnet => "$zoneid-10.0.0.0-24",
+        gateway => "10.0.0.1",
+        'dhcp-dns-server' => "fd00::53",
+    });
+    $test_state->{warnings} = [];
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    my $calls = take_ebpf_calls();
+    is(scalar(@$calls), 1, "$test_name: regenerate applies once");
+    my $iface = $calls->[0]->{args}->[0]->[0];
+    is($iface->{name}, 'tap999i0', "$test_name: the guest interface is listed");
+    is($iface->{record}->{ip}, '10.0.0.100', "$test_name: the v4 subnet now yields the record");
+    is($iface->{record}->{dns}, undef, "$test_name: the IPv6 resolver is not handed out");
+    is(
+        scalar(grep { m/IPv6 DNS server/ } $test_state->{warnings}->@*),
+        1,
+        "$test_name: and the full pass says so",
+    );
+}
+
+run_test(\&test_ebpf_backend);
+run_test(\&test_ebpf_backend_edge_cases);
+
+sub test_ebpf_mac_case {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # a mapping typed in lower case for a NIC whose config spells the MAC in
+    # upper case is the same mapping
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=" . uc($mac) . ",bridge=$vnetid" } };
+    create_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.100",
+    });
+    take_ebpf_calls();
+    take_order();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'apply',
+            args => [[{
+                name => 'tap999i0',
+                mac => $mac,
+                record => $ebpf_record->("10.0.0.100"),
+            }]],
+        }],
+        "$test_name: the full pass finds the mapping however the config spells the MAC",
+    );
+    # the lock is taken before the refresh and the reads of the pass. The
+    # refresh ahead of it belongs to the fill of the cache
+    is_deeply(
+        take_order(),
+        ['refresh', 'lock', 'refresh', 'write'],
+        "$test_name: the pass locks, refreshes, then writes",
+    );
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug($zoneid, $vnetid, 'tap999i0', uc($mac));
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{
+            method => 'attach',
+            args => ['tap999i0', uc($mac), $ebpf_record->("10.0.0.100")],
+        }],
+        "$test_name: and so does a plug",
+    );
+
+    # an entry split across spellings is read as one
+    $test_state->{macdb} = {
+        macs => { uc($mac) => { ip4 => '10.0.0.100' }, $mac => { ip6 => '8888::100' } },
+    };
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{ip},
+        '10.0.0.100',
+        "$test_name: a cache entry split across spellings is read as one",
+    );
+}
+
+run_test(\&test_ebpf_mac_case);
+
+sub test_ebpf_cache_only {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # under the responder's lock every address comes from the MAC cache. Only
+    # an apply asks the IPAM for what the cache lacks, before it takes the lock
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    create_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.100",
+    });
+    my $asked = 0;
+    my $mocked_pve_plugin = Test::MockModule->new('PVE::Network::SDN::Ipams::PVEPlugin');
+    $mocked_pve_plugin->mock(
+        get_ips_from_mac => sub {
+            $asked++;
+            push $test_state->{order}->@*, 'ipam';
+            return $mocked_pve_plugin->original('get_ips_from_mac')->(@_);
+        },
+    );
+
+    # the IPAM holds the address and the cache lost it
+    $test_state->{macdb} = {};
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug($zoneid, $vnetid, 'tap999i0', $mac);
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', $mac, undef] }],
+        "$test_name: a plug attaches without a record when the cache holds none",
+    );
+    is($asked, 0, "$test_name: and does not ask the IPAM");
+
+    take_order();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is($asked, 1, "$test_name: an apply asks the IPAM for the address the cache lacks");
+    is_deeply(
+        take_order(),
+        ['refresh', 'ipam', 'lock', 'refresh', 'write'],
+        "$test_name: before it takes the lock",
+    );
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{ip},
+        '10.0.0.100',
+        "$test_name: and serves the address the lookup put into the cache",
+    );
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is($asked, 1, "$test_name: the next apply finds it in the cache");
+
+    # a deleted mapping leaves nothing to look up
+    take_ebpf_calls();
+    delete_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.100",
+    });
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'update', args => [[{ name => 'tap999i0', mac => $mac, record => undef }]] }],
+        "$test_name: a deleted mapping drops the record",
+    );
+    is($asked, 1, "$test_name: without asking the IPAM for it");
+
+    # an IPAM that does not answer does not stop the apply
+    $mocked_pve_plugin->mock(get_ips_from_mac => sub { $asked++; die "IPAM down\n"; });
+    $test_state->{warnings} = [];
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    $mocked_pve_plugin->unmock('get_ips_from_mac');
+    is(
+        scalar(
+            grep { m/could not fill the MAC cache from the IPAM: IPAM down/ }
+                $test_state->{warnings}->@*
+        ),
+        1,
+        "$test_name: a failed lookup before the lock only warns",
+    );
+    is(
+        take_ebpf_calls()->[0]->{method}, 'apply', "$test_name: and the pass still runs",
+    );
+}
+
+run_test(\&test_ebpf_cache_only);
+
+sub test_ebpf_equal_subnets {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+
+    # two ebpf zones carry the same subnet. Each interface is answered from
+    # the subnet of the vnet it sits on, whatever address the cache holds
+    # for its MAC
+    for my $net (['ZONEA', 'vneta', '10.0.0.1'], ['ZONEB', 'vnetb', '10.0.0.2']) {
+        my ($zoneid, $vnetid, $gateway) = @$net;
+        create_zone({
+            type => "simple",
+            dhcp => "ebpf",
+            ipam => "pve",
+            zone => $zoneid,
+        });
+        create_vnet({
+            type => "vnet",
+            zone => $zoneid,
+            vnet => $vnetid,
+        });
+        create_subnet({
+            type => "subnet",
+            vnet => $vnetid,
+            subnet => "10.0.0.0/24",
+            gateway => $gateway,
+        });
+    }
+    $test_state->{vmlist} = {
+        ids => {
+            100 => { type => 'qemu', node => 'localnode' },
+            101 => { type => 'qemu', node => 'localnode' },
+        },
+    };
+    $test_state->{guest_nets} = {
+        100 => { net0 => "virtio=da:65:8f:18:9b:6f,bridge=vneta" },
+        101 => { net0 => "virtio=da:65:8f:18:9b:70,bridge=vnetb" },
+    };
+    $test_state->{macdb} = {
+        vnets => {
+            vneta => { 'da:65:8f:18:9b:6f' => { ip4 => '10.0.0.150' } },
+            vnetb => { 'da:65:8f:18:9b:70' => { ip4 => '10.0.0.150' } },
+        },
+        macs => {
+            'da:65:8f:18:9b:6f' => { ip4 => '10.0.0.150' },
+            'da:65:8f:18:9b:70' => { ip4 => '10.0.0.150' },
+        },
+    };
+
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    my $ifaces = take_ebpf_calls()->[0]->{args}->[0];
+    eq_or_diff(
+        [map { [$_->{name}, $_->{record}->{router}] } @$ifaces],
+        [['tap100i0', '10.0.0.1'], ['tap101i0', '10.0.0.2']],
+        "$test_name: each interface is answered from its own vnet",
+    );
+}
+
+run_test(\&test_ebpf_equal_subnets);
+
+sub test_ebpf_zone_mtu {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # a zone MTU the DHCP option cannot carry is reported on the apply and
+    # left out of the answer. The API refuses such an MTU, a config written
+    # before it did may still hold one
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    $test_state->{zones_config}->{ids}->{$zoneid}->{mtu} = 10;
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    $test_state->{macdb} = {
+        vnets => { $vnetid => { $mac => { ip4 => '10.0.0.100' } } },
+        macs => { $mac => { ip4 => '10.0.0.100' } },
+    };
+
+    take_ebpf_calls();
+    $test_state->{warnings} = [];
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        scalar(grep { m/MTU 10/ } $test_state->{warnings}->@*),
+        1,
+        "$test_name: the zone MTU is reported once",
+    );
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{mtu},
+        undef,
+        "$test_name: and not handed out",
+    );
+
+    update_zone($zoneid, { mtu => 9000 });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{mtu},
+        9000,
+        "$test_name: a zone MTU the option carries is handed out",
+    );
+}
+
+run_test(\&test_ebpf_zone_mtu);
+
+sub test_ebpf_overlapping_subnets {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # a vnet with overlapping subnets answers from the most specific one
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/16",
+        gateway => "10.0.255.1",
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    $test_state->{macdb} = {
+        vnets => { $vnetid => { $mac => { ip4 => '10.0.0.100' } } },
+        macs => { $mac => { ip4 => '10.0.0.100' } },
+    };
+
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    my $record = take_ebpf_calls()->[0]->{args}->[0]->[0]->{record};
+    is_deeply(
+        [$record->@{qw(prefixlen router)}],
+        [24, '10.0.0.1'],
+        "$test_name: the most specific subnet answers",
+    );
+}
+
+run_test(\&test_ebpf_overlapping_subnets);
+
 done_testing();
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 11/21] sdn: zones: report interface plugs and unplugs to the DHCP backends
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (9 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 10/21] sdn: dhcp: add an eBPF backend answering on each guest interface Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 12/21] sdn: zones: factor out the underlay lookup of VXLAN and EVPN zones Hannes Laimer
                   ` (9 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The ebpf DHCP backend answers on each guest interface rather than on
the bridge, so the zone layer now reports every plug to the DHCP
backends. The plug takes the guest's MAC along, since the address to
hand out is recorded per MAC. A plug onto a plain bridge is reported
too, since a running guest's interface can move there from a vnet.
A failing backend only warns and the plug goes ahead.

A hotplug moves an interface while its new bridge is still a pending
change in the guest config. A plug marked as pending therefore only
reports the interface as gone, and a separate call reports it once
the change is applied. So the backends never serve from a pending
change.

The zone layer also gains an unplug and a veth removal, which report
the interface to the backends as gone.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/PVE/Network/SDN/Zones.pm        |  42 +++++-
 src/test/run_test_vnets_blackbox.pl | 191 ++++++++++++++++++++++++++++
 2 files changed, 229 insertions(+), 4 deletions(-)

diff --git a/src/PVE/Network/SDN/Zones.pm b/src/PVE/Network/SDN/Zones.pm
index c189652a79eb..f8dfce12733e 100644
--- a/src/PVE/Network/SDN/Zones.pm
+++ b/src/PVE/Network/SDN/Zones.pm
@@ -333,16 +333,22 @@ sub veth_create {
 }
 
 sub tap_plug {
-    my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_;
+    my ($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts) = @_;
+
+    # during a hotplug the new bridge is still pending in the guest config. The dhcp backends
+    # only drop the interface here and hear of it again in tap_commit
+    PVE::Network::SDN::Dhcp::tap_unplug($iface) if $opts->{pending};
 
     my $vnet = PVE::Network::SDN::Vnets::get_vnet($bridge, 1);
     if (!$vnet) { # fallback for classic bridge
         my $interfaces_config = PVE::INotify::read_file('interfaces');
-        my $opts = {};
-        $opts->{learning} = 0
+        my $bridge_opts = {};
+        $bridge_opts->{learning} = 0
             if $interfaces_config->{ifaces}->{$bridge}
             && $interfaces_config->{ifaces}->{$bridge}->{'bridge-disable-mac-learning'};
-        PVE::Network::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts);
+        PVE::Network::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, $bridge_opts);
+        # the dhcp backends hear of an interface moving onto a plain bridge as well
+        PVE::Network::SDN::Dhcp::tap_plug($bridge, $iface, $opts->{mac}) if !$opts->{pending};
         return;
     }
 
@@ -353,7 +359,35 @@ sub tap_plug {
         if $plugin_config->{nodes} && !defined($plugin_config->{nodes}->{$nodename});
 
     my $plugin = PVE::Network::SDN::Zones::Plugin->lookup($plugin_config->{type});
+
     $plugin->tap_plug($plugin_config, $vnet, $tag, $iface, $bridge, $firewall, $trunks, $rate);
+    # the dhcp backends hear of the interface after it joined the bridge, since a full pass
+    # skips one that is not on its bridge. Dhcp.pm comes in through Vnets.pm, since a use of it
+    # here would create a load-order cycle
+    PVE::Network::SDN::Dhcp::tap_plug($bridge, $iface, $opts->{mac}) if !$opts->{pending};
+}
+
+# the dhcp backends hear of a hotplugged interface once its change is applied to the guest
+# config. An error only warns, since the hotplug is done by then
+sub tap_commit {
+    my ($iface, $bridge, $mac) = @_;
+
+    eval { PVE::Network::SDN::Dhcp::tap_plug($bridge, $iface, $mac) };
+    warn "could not plug $iface into the dhcp backends: $@" if $@;
+}
+
+sub tap_unplug {
+    my ($iface) = @_;
+
+    PVE::Network::SDN::Dhcp::tap_unplug($iface);
+    PVE::Network::tap_unplug($iface);
+}
+
+sub veth_delete {
+    my ($veth) = @_;
+
+    PVE::Network::SDN::Dhcp::tap_unplug($veth);
+    PVE::Network::veth_delete($veth);
 }
 
 sub add_bridge_fdb {
diff --git a/src/test/run_test_vnets_blackbox.pl b/src/test/run_test_vnets_blackbox.pl
index 23d1844274d7..a3a6547313ce 100755
--- a/src/test/run_test_vnets_blackbox.pl
+++ b/src/test/run_test_vnets_blackbox.pl
@@ -2372,6 +2372,197 @@ sub test_ebpf_backend_edge_cases {
 }
 
 run_test(\&test_ebpf_backend);
+
+sub test_zone_tap_plug {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+    my $vnetid = "testvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # the zone plug hands the MAC on to the dhcp backends, and a plug onto a
+    # plain bridge tells them where the interface went
+    create_zone({
+        type => "simple",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+        'dhcp-range' => ["start-address=10.0.0.100,end-address=10.0.0.200"],
+    });
+    create_ip({
+        zone => $zoneid,
+        vnet => $vnetid,
+        mac => $mac,
+        ip => "10.0.0.100",
+    });
+    my $bridged = [];
+    my $unplugged = [];
+    $mocked_sdn_zones_super_plugin->mock(
+        tap_plug => sub {
+            push @$bridged, $_[5];
+            push $test_state->{order}->@*, 'bridge';
+        },
+    );
+    my $mocked_pve_network = Test::MockModule->new('PVE::Network');
+    $mocked_pve_network->mock(
+        tap_plug => sub {
+            push @$bridged, $_[1];
+            push $test_state->{order}->@*, 'bridge';
+        },
+        tap_unplug => sub { push @$unplugged, $_[0]; },
+        veth_delete => sub { push @$unplugged, $_[0]; },
+    );
+    $mocked_pve_inotify->mock(read_file => sub { return { ifaces => {} }; });
+    take_ebpf_calls();
+    take_order();
+
+    PVE::Network::SDN::Zones::tap_plug('tap999i0', $vnetid, undef, 0, undef, undef,
+        { mac => $mac });
+    eq_or_diff($bridged, [$vnetid], "$test_name: the zone plugin plugs the interface");
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', $mac, $ebpf_record->("10.0.0.100")] }],
+        "$test_name: and the dhcp backend attaches it with the MAC's record",
+    );
+    is_deeply(
+        take_order(),
+        ['bridge', 'lock', 'refresh', 'write'],
+        "$test_name: the interface joins the bridge before the responder attaches",
+    );
+
+    # during a hotplug the new bridge is still pending in the guest config
+    @$bridged = ();
+    PVE::Network::SDN::Zones::tap_plug(
+        'tap999i0',
+        $vnetid,
+        undef,
+        0,
+        undef,
+        undef,
+        { mac => $mac, pending => 1 },
+    );
+    eq_or_diff($bridged, [$vnetid], "$test_name: a pending plug still joins the bridge");
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'detach', args => ['tap999i0'] }],
+        "$test_name: and the dhcp backends only drop the interface",
+    );
+    is_deeply(take_order(), ['bridge'], "$test_name: and plug it into none of them");
+    PVE::Network::SDN::Zones::tap_commit('tap999i0', $vnetid, $mac);
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', $mac, $ebpf_record->("10.0.0.100")] }],
+        "$test_name: once the change is applied the interface is attached with the MAC's record",
+    );
+
+    # by then the hotplug is done, so a failed plug only warns
+    my $mocked_sdn_dhcp = Test::MockModule->new('PVE::Network::SDN::Dhcp');
+    $mocked_sdn_dhcp->mock(tap_plug => sub { die "no responder\n"; });
+    my @warnings;
+    eval {
+        local $SIG{__WARN__} = sub { push @warnings, $_[0]; };
+        PVE::Network::SDN::Zones::tap_commit('tap999i0', $vnetid, $mac);
+    };
+    is($@, '', "$test_name: a failed plug after the change is applied does not die");
+    $mocked_sdn_dhcp->unmock('tap_plug');
+    is(
+        scalar(grep { m/could not plug tap999i0 into the dhcp backends: no responder/ } @warnings),
+        1,
+        "$test_name: and warns",
+    );
+
+    @$bridged = ();
+    PVE::Network::SDN::Zones::tap_plug('tap999i0', 'vmbr0', undef, 0, undef, undef,
+        { mac => $mac });
+    eq_or_diff($bridged, ['vmbr0'], "$test_name: a plain bridge is plugged the classic way");
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'detach', args => ['tap999i0'] }],
+        "$test_name: and the ebpf backend drops the interface",
+    );
+
+    # the same holds for a vnet of another backend
+    create_zone({
+        type => "simple",
+        dhcp => "dnsmasq",
+        ipam => "pve",
+        zone => "DNSZONE",
+    });
+    create_vnet({
+        type => "vnet",
+        zone => "DNSZONE",
+        vnet => "dnsvnet",
+    });
+    @$bridged = ();
+    PVE::Network::SDN::Zones::tap_plug(
+        'tap999i0',
+        'dnsvnet',
+        undef,
+        0,
+        undef,
+        undef,
+        { mac => $mac },
+    );
+    eq_or_diff(
+        $bridged,
+        ['dnsvnet'],
+        "$test_name: a vnet of another backend is plugged by its zone",
+    );
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'detach', args => ['tap999i0'] }],
+        "$test_name: and the ebpf backend drops the interface there too",
+    );
+
+    # the backend a plug was handed to came from a config read before the
+    # responder's lock, an apply may have switched it since
+    take_order();
+    PVE::Network::SDN::Dhcp::Ebpf->tap_unplug('tap999i0', { vnet => $vnetid, mac => $mac });
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'attach', args => ['tap999i0', $mac, $ebpf_record->("10.0.0.100")] }],
+        "$test_name: a move onto a vnet that uses ebpf by now attaches",
+    );
+    is_deeply(
+        take_order(),
+        ['lock', 'refresh', 'write'],
+        "$test_name: and reads the zone under the responder's lock",
+    );
+    PVE::Network::SDN::Dhcp::Ebpf->tap_plug('DNSZONE', 'dnsvnet', 'tap999i0', $mac);
+    eq_or_diff(
+        take_ebpf_calls(),
+        [{ method => 'detach', args => ['tap999i0'] }],
+        "$test_name: a plug onto a vnet that left ebpf by now detaches",
+    );
+
+    # the zone unplug and the veth delete report the interface gone before
+    # the classic ones run
+    PVE::Network::SDN::Zones::tap_unplug('tap999i0');
+    PVE::Network::SDN::Zones::veth_delete('veth999i0');
+    eq_or_diff($unplugged, ['tap999i0', 'veth999i0'], "$test_name: the classic unplugs run");
+    eq_or_diff(
+        take_ebpf_calls(),
+        [
+            { method => 'detach', args => ['tap999i0'] },
+            { method => 'detach', args => ['veth999i0'] },
+        ],
+        "$test_name: and the dhcp backends hear the interfaces are gone",
+    );
+    $mocked_sdn_zones_super_plugin->unmock('tap_plug');
+    $mocked_pve_inotify->unmock('read_file');
+}
+
+run_test(\&test_zone_tap_plug);
 run_test(\&test_ebpf_backend_edge_cases);
 
 sub test_ebpf_mac_case {
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 12/21] sdn: zones: factor out the underlay lookup of VXLAN and EVPN zones
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (10 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 11/21] sdn: zones: report interface plugs and unplugs to the DHCP backends Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-network v7 13/21] sdn: zones: allow the ebpf DHCP backend on every zone type Hannes Laimer
                   ` (8 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

A VXLAN or EVPN zone finds its local tunnel address and the interface
that has it while it generates the interfaces config. Move that
lookup into a function of its own for each of the two zone types, so
it can be used without generating the config. No functional change
intended.

For a zone on a fabric, the EVPN lookup also built a peer list and a
loopback name that nothing read. Both are dropped.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/PVE/Network/SDN/Zones/EvpnPlugin.pm  | 74 ++++++++++++-----------
 src/PVE/Network/SDN/Zones/VxlanPlugin.pm | 76 +++++++++++++-----------
 2 files changed, 80 insertions(+), 70 deletions(-)

diff --git a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
index 9a85a9d9bf72..5c951dae120a 100644
--- a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
@@ -132,40 +132,16 @@ sub options {
     };
 }
 
-# Plugin implementation
-sub generate_sdn_config {
-    my (
-        $class,
-        $plugin_config,
-        $zoneid,
-        $vnetid,
-        $vnet,
-        $controller,
-        $controller_cfg,
-        $subnet_cfg,
-        $interfaces_config,
-        $config,
-    ) = @_;
+my sub find_underlay {
+    my ($plugin_config, $controller, $controller_cfg) = @_;
 
-    my $tag = $vnet->{tag};
-    my $alias = $vnet->{alias};
-    my $mac = $plugin_config->{'mac'};
-    my $vxlanport = $plugin_config->{'vxlan-port'};
-
-    my $vrf_iface = "vrf_$zoneid";
-    my $vrfvxlan = $plugin_config->{'vrf-vxlan'};
     my $local_node = PVE::INotify::nodename();
-
-    die "missing vxlan tag" if !$tag;
-    die "missing controller" if !$controller;
-
-    my @peers;
-    my $loopback = undef;
     my $ifaceip = undef;
     my $iface = undef;
 
     if ($controller->{peers}) {
-        @peers = PVE::Tools::split_list($controller->{'peers'});
+        my @peers = PVE::Tools::split_list($controller->{'peers'});
+        my $loopback = undef;
 
         my $bgprouter = PVE::Network::SDN::Controllers::EvpnPlugin::find_bgp_controller(
             $local_node, $controller_cfg,
@@ -182,8 +158,6 @@ sub generate_sdn_config {
 
         ($ifaceip, $iface) =
             PVE::Network::SDN::Zones::Plugin::find_local_ip_interface_peers(\@peers, $loopback);
-        log_warn("EVPN zone $zoneid, VNet $vnetid: no local address found for peers")
-            if !defined($ifaceip);
     } elsif ($controller->{fabric}) {
         my $config = PVE::Network::SDN::Fabrics::config(1);
 
@@ -204,17 +178,45 @@ sub generate_sdn_config {
             "Node $local_node requires a $addr_key address in the fabric $fabric->{id} to configure the EVPN zone"
             if !$current_node->{$addr_key};
 
-        for my $node_id (sort keys %$nodes) {
-            push @peers, $nodes->{$node_id}->{$addr_key};
-        }
-
-        $loopback = "dummy_$fabric->{id}";
-
         $ifaceip = $current_node->{$addr_key};
     } else {
         die "neither fabric nor peers configured for EVPN controller $controller->{id}";
     }
 
+    return ($ifaceip, $iface);
+}
+
+# Plugin implementation
+sub generate_sdn_config {
+    my (
+        $class,
+        $plugin_config,
+        $zoneid,
+        $vnetid,
+        $vnet,
+        $controller,
+        $controller_cfg,
+        $subnet_cfg,
+        $interfaces_config,
+        $config,
+    ) = @_;
+
+    my $tag = $vnet->{tag};
+    my $alias = $vnet->{alias};
+    my $mac = $plugin_config->{'mac'};
+    my $vxlanport = $plugin_config->{'vxlan-port'};
+
+    my $vrf_iface = "vrf_$zoneid";
+    my $vrfvxlan = $plugin_config->{'vrf-vxlan'};
+    my $local_node = PVE::INotify::nodename();
+
+    die "missing vxlan tag" if !$tag;
+    die "missing controller" if !$controller;
+
+    my ($ifaceip, $iface) = find_underlay($plugin_config, $controller, $controller_cfg);
+    log_warn("EVPN zone $zoneid, VNet $vnetid: no local address found for peers")
+        if !defined($ifaceip);
+
     my $is_evpn_gateway = $plugin_config->{'exitnodes'}->{$local_node};
     my $exitnodes_local_routing = $plugin_config->{'exitnodes-local-routing'};
 
diff --git a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
index d8301bac0f3a..d9f86c8ef478 100644
--- a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
@@ -62,6 +62,45 @@ sub vxlan_mtu {
     return $underlay - ($family == 6 ? 70 : 50);
 }
 
+my sub find_underlay {
+    my ($plugin_config) = @_;
+
+    my @peers;
+    my $ifaceip;
+    my $iface;
+
+    if ($plugin_config->{peers}) {
+        @peers = PVE::Tools::split_list($plugin_config->{peers});
+        ($ifaceip, $iface) =
+            PVE::Network::SDN::Zones::Plugin::find_local_ip_interface_peers(\@peers);
+    } elsif ($plugin_config->{fabric}) {
+        my $local_node = PVE::INotify::nodename();
+        my $config = PVE::Network::SDN::Fabrics::config(1);
+
+        my $fabric = eval { $config->get_fabric($plugin_config->{fabric}) };
+        die "could not configure VXLAN zone $plugin_config->{id}: $@" if $@;
+
+        my $nodes = $config->list_nodes_fabric($plugin_config->{fabric});
+
+        my $current_node = eval { $config->get_node($plugin_config->{fabric}, $local_node) };
+        die "could not configure VXLAN zone $plugin_config->{id}: $@" if $@;
+
+        die
+            "Node $local_node requires an IP in the fabric $fabric->{id} to configure the VXLAN zone $plugin_config->{id}"
+            if !$current_node->{ip};
+
+        for my $node (values %$nodes) {
+            push @peers, $node->{ip} if $node->{ip};
+        }
+
+        $ifaceip = $current_node->{ip};
+    } else {
+        die "neither peers nor fabric configured for VXLAN zone $plugin_config->{id}";
+    }
+
+    return ($ifaceip, $iface, @peers);
+}
+
 sub options {
     return {
         nodes => { optional => 1 },
@@ -99,40 +138,9 @@ sub generate_sdn_config {
 
     die "missing vxlan tag" if !$tag;
 
-    my @peers;
-    my $ifaceip;
-    my $iface;
-
-    if ($plugin_config->{peers}) {
-        @peers = PVE::Tools::split_list($plugin_config->{'peers'}) if $plugin_config->{'peers'};
-        ($ifaceip, $iface) =
-            PVE::Network::SDN::Zones::Plugin::find_local_ip_interface_peers(\@peers);
-        log_warn("VXLAN zone $zoneid, VNet $vnetid: no local address found for peers")
-            if !defined($ifaceip);
-    } elsif ($plugin_config->{fabric}) {
-        my $local_node = PVE::INotify::nodename();
-        my $config = PVE::Network::SDN::Fabrics::config(1);
-
-        my $fabric = eval { $config->get_fabric($plugin_config->{fabric}) };
-        die "could not configure VXLAN zone $plugin_config->{id}: $@" if $@;
-
-        my $nodes = $config->list_nodes_fabric($plugin_config->{fabric});
-
-        my $current_node = eval { $config->get_node($plugin_config->{fabric}, $local_node) };
-        die "could not configure VXLAN zone $plugin_config->{id}: $@" if $@;
-
-        die
-            "Node $local_node requires an IP in the fabric $fabric->{id} to configure the VXLAN zone $plugin_config->{id}"
-            if !$current_node->{ip};
-
-        for my $node (values %$nodes) {
-            push @peers, $node->{ip} if $node->{ip};
-        }
-
-        $ifaceip = $current_node->{ip};
-    } else {
-        die "neither peers nor fabric configured for VXLAN zone $plugin_config->{id}";
-    }
+    my ($ifaceip, $iface, @peers) = find_underlay($plugin_config);
+    log_warn("VXLAN zone $zoneid, VNet $vnetid: no local address found for peers")
+        if !defined($ifaceip);
 
     my $mtu = vxlan_mtu($plugin_config, $iface, $interfaces_config, $ifaceip);
 
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-network v7 13/21] sdn: zones: allow the ebpf DHCP backend on every zone type
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (11 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 12/21] sdn: zones: factor out the underlay lookup of VXLAN and EVPN zones Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH qemu-server v7 14/21] network: sdn: keep the DHCP backends current on guest NICs Hannes Laimer
                   ` (7 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The ebpf backend answers each guest on the guest's own tap or veth
device, so the zone type makes no difference to it. dnsmasq stays
limited to simple zones, since every node runs its own instance on
the vnet bridge and only a simple zone's bridge is cut off from the
other nodes. Choosing it elsewhere fails on create and on update.

Every zone type now reports the MTU its guests should use. The ebpf
backend hands it out, and until now only simple zones could answer.
A VXLAN or EVPN zone without an MTU setting takes it from the
interface that reaches its peers, or gets the default if it is on a
fabric.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/PVE/API2/Network/SDN/Zones.pm         |  13 ++-
 src/PVE/Network/SDN/Zones/EvpnPlugin.pm   |  16 +++
 src/PVE/Network/SDN/Zones/FaucetPlugin.pm |   1 +
 src/PVE/Network/SDN/Zones/QinQPlugin.pm   |   7 ++
 src/PVE/Network/SDN/Zones/SimplePlugin.pm |   2 +-
 src/PVE/Network/SDN/Zones/VlanPlugin.pm   |   7 ++
 src/PVE/Network/SDN/Zones/VxlanPlugin.pm  |   9 ++
 src/test/run_test_vnets_blackbox.pl       | 123 +++++++++++++++++++++-
 8 files changed, 174 insertions(+), 4 deletions(-)

diff --git a/src/PVE/API2/Network/SDN/Zones.pm b/src/PVE/API2/Network/SDN/Zones.pm
index 4f61e1e858aa..218d13018353 100644
--- a/src/PVE/API2/Network/SDN/Zones.pm
+++ b/src/PVE/API2/Network/SDN/Zones.pm
@@ -60,7 +60,7 @@ my $ZONE_PROPERTIES = {
         type => 'string',
         enum => PVE::Network::SDN::Dhcp->plugin_types(),
         optional => 1,
-        description => 'Name of DHCP server backend for this zone.',
+        description => 'DHCP backend serving the zone. dnsmasq works on simple zones only.',
     },
     'rt-import' => {
         type => 'string',
@@ -358,6 +358,13 @@ sub create_etc_interfaces_sdn_dir {
     mkdir("/etc/pve/sdn");
 }
 
+my sub assert_dhcp_backend {
+    my ($plugin, $dhcp) = @_;
+
+    raise_param_exc({ dhcp => "the dnsmasq backend only supports simple zones" })
+        if ($dhcp // '') eq 'dnsmasq' && $plugin->type() ne 'simple';
+}
+
 __PACKAGE__->register_method({
     name => 'create',
     protected => 1,
@@ -406,6 +413,8 @@ __PACKAGE__->register_method({
                 raise_param_exc({ dnszone => "missing dns server" })
                     if $dnszone && !$dnsserver;
 
+                assert_dhcp_backend($plugin, $opts->{dhcp});
+
                 $zone_cfg->{ids}->{$id} = $opts;
                 $plugin->on_update_hook($id, $zone_cfg, $controller_cfg);
 
@@ -493,6 +502,8 @@ __PACKAGE__->register_method({
                 my $dnszone = $opts->{dnszone};
                 raise_param_exc({ dnszone => "missing dns server" }) if $dnszone && !$dnsserver;
 
+                assert_dhcp_backend($plugin, $scfg->{dhcp});
+
                 $plugin->on_update_hook($id, $zone_cfg, $controller_cfg);
 
                 PVE::Network::SDN::Zones::write_config($zone_cfg);
diff --git a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
index 5c951dae120a..5e062f976686 100644
--- a/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/EvpnPlugin.pm
@@ -129,6 +129,7 @@ sub options {
         reversedns => { optional => 1 },
         dnszone => { optional => 1 },
         ipam => { optional => 1 },
+        dhcp => { optional => 1 },
     };
 }
 
@@ -187,6 +188,21 @@ my sub find_underlay {
 }
 
 # Plugin implementation
+sub get_mtu {
+    my ($class, $plugin_config) = @_;
+
+    return $plugin_config->{mtu} if $plugin_config->{mtu};
+
+    my $controller_cfg = PVE::Network::SDN::running_config()->{controllers};
+    my $controller = $controller_cfg->{ids}->{ $plugin_config->{controller} // '' };
+    # a zone whose underlay cannot be found gets the default MTU
+    my ($ifaceip, $iface) =
+        $controller ? eval { find_underlay($plugin_config, $controller, $controller_cfg) } : ();
+    return PVE::Network::SDN::Zones::VxlanPlugin::vxlan_mtu(
+        $plugin_config, $iface, PVE::INotify::read_file('interfaces'), $ifaceip,
+    );
+}
+
 sub generate_sdn_config {
     my (
         $class,
diff --git a/src/PVE/Network/SDN/Zones/FaucetPlugin.pm b/src/PVE/Network/SDN/Zones/FaucetPlugin.pm
index 5f069aea85de..4e3f5eff8a8b 100644
--- a/src/PVE/Network/SDN/Zones/FaucetPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/FaucetPlugin.pm
@@ -30,6 +30,7 @@ sub options {
         reversedns => { optional => 1 },
         dnszone => { optional => 1 },
         ipam => { optional => 1 },
+        dhcp => { optional => 1 },
     };
 }
 
diff --git a/src/PVE/Network/SDN/Zones/QinQPlugin.pm b/src/PVE/Network/SDN/Zones/QinQPlugin.pm
index 894bba16a20e..6031e0ad5002 100644
--- a/src/PVE/Network/SDN/Zones/QinQPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/QinQPlugin.pm
@@ -39,6 +39,12 @@ sub properties {
     };
 }
 
+sub get_mtu {
+    my ($class, $plugin_config) = @_;
+
+    return $plugin_config->{mtu};
+}
+
 sub options {
     return {
         nodes => { optional => 1 },
@@ -51,6 +57,7 @@ sub options {
         reversedns => { optional => 1 },
         dnszone => { optional => 1 },
         ipam => { optional => 1 },
+        dhcp => { optional => 1 },
     };
 }
 
diff --git a/src/PVE/Network/SDN/Zones/SimplePlugin.pm b/src/PVE/Network/SDN/Zones/SimplePlugin.pm
index 347eee9a46ba..655f7e41cf37 100644
--- a/src/PVE/Network/SDN/Zones/SimplePlugin.pm
+++ b/src/PVE/Network/SDN/Zones/SimplePlugin.pm
@@ -31,7 +31,7 @@ sub properties {
             description => "dns domain zone  ex: mydomain.com",
         },
         dhcp => {
-            description => 'Type of the DHCP backend for this zone',
+            description => 'DHCP backend serving the zone. dnsmasq works on simple zones only.',
             type => 'string',
             enum => PVE::Network::SDN::Dhcp->plugin_types(),
         },
diff --git a/src/PVE/Network/SDN/Zones/VlanPlugin.pm b/src/PVE/Network/SDN/Zones/VlanPlugin.pm
index de19755d04f5..46b00d747b80 100644
--- a/src/PVE/Network/SDN/Zones/VlanPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/VlanPlugin.pm
@@ -38,6 +38,12 @@ sub properties {
     };
 }
 
+sub get_mtu {
+    my ($class, $plugin_config) = @_;
+
+    return $plugin_config->{mtu};
+}
+
 sub options {
 
     return {
@@ -49,6 +55,7 @@ sub options {
         reversedns => { optional => 1 },
         dnszone => { optional => 1 },
         ipam => { optional => 1 },
+        dhcp => { optional => 1 },
     };
 }
 
diff --git a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
index d9f86c8ef478..ba38739abc6f 100644
--- a/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
+++ b/src/PVE/Network/SDN/Zones/VxlanPlugin.pm
@@ -101,6 +101,14 @@ my sub find_underlay {
     return ($ifaceip, $iface, @peers);
 }
 
+sub get_mtu {
+    my ($class, $plugin_config) = @_;
+
+    # a zone whose underlay cannot be found gets the default MTU
+    my ($ifaceip, $iface) = eval { find_underlay($plugin_config) };
+    return vxlan_mtu($plugin_config, $iface, PVE::INotify::read_file('interfaces'), $ifaceip);
+}
+
 sub options {
     return {
         nodes => { optional => 1 },
@@ -112,6 +120,7 @@ sub options {
         dnszone => { optional => 1 },
         ipam => { optional => 1 },
         fabric => { optional => 1 },
+        dhcp => { optional => 1 },
     };
 }
 
diff --git a/src/test/run_test_vnets_blackbox.pl b/src/test/run_test_vnets_blackbox.pl
index a3a6547313ce..4598c6d1ce16 100755
--- a/src/test/run_test_vnets_blackbox.pl
+++ b/src/test/run_test_vnets_blackbox.pl
@@ -1622,6 +1622,55 @@ sub test_mapping_edit_target {
 
 run_test(\&test_mapping_edit_target);
 
+sub test_zone_dhcp_backends {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "TESTZONE";
+
+    # dnsmasq answers on the vnet bridge, so it only fits zones confined to
+    # one node. The ebpf backend answers on the guest's tap and fits any
+    my $zone = {
+        type => "vlan",
+        bridge => "vmbr0",
+        ipam => "pve",
+        zone => $zoneid,
+    };
+    eval { PVE::API2::Network::SDN::Zones->create({ %$zone, dhcp => "dnsmasq" }); };
+    like(
+        $@,
+        qr/dnsmasq backend only supports simple zones/,
+        "$test_name: dnsmasq is refused on a vlan zone",
+    );
+
+    create_zone({ %$zone, dhcp => "ebpf" });
+    is(get_zone($zoneid)->{dhcp}, "ebpf", "$test_name: ebpf is accepted on a vlan zone");
+
+    eval { update_zone($zoneid, { dhcp => "dnsmasq" }); };
+    like(
+        $@,
+        qr/dnsmasq backend only supports simple zones/,
+        "$test_name: switching a vlan zone to dnsmasq is refused",
+    );
+
+    # every other zone type offers the backend as well
+    $test_state->{controller_config} = {
+        ids => { ctrl => { type => 'evpn', asn => 65000, peers => '10.0.0.1' } },
+    };
+    my $params = {
+        qinq => { bridge => 'vmbr0', tag => 100 },
+        vxlan => { peers => '10.0.0.1' },
+        evpn => { controller => 'ctrl', 'vrf-vxlan' => 1000 },
+        faucet => { 'dp-id' => 1, controller => 'ctrl' },
+    };
+    for my $type (sort keys %$params) {
+        my $id = uc($type) . "Z";
+        my $zone = { type => $type, ipam => "pve", zone => $id, %{ $params->{$type} } };
+        create_zone({ %$zone, dhcp => "ebpf" });
+        is(get_zone($id)->{dhcp}, "ebpf", "$test_name: ebpf is accepted on a $type zone");
+    }
+}
+
+run_test(\&test_zone_dhcp_backends);
+
 sub test_ipam_per_vnet {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
     my $zoneid = "TESTZONE";
@@ -2257,6 +2306,8 @@ sub test_ebpf_backend {
     );
 }
 
+run_test(\&test_ebpf_backend);
+
 sub test_ebpf_backend_edge_cases {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
     my $zoneid = "TESTZONE";
@@ -2371,7 +2422,7 @@ sub test_ebpf_backend_edge_cases {
     );
 }
 
-run_test(\&test_ebpf_backend);
+run_test(\&test_ebpf_backend_edge_cases);
 
 sub test_zone_tap_plug {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
@@ -2563,7 +2614,6 @@ sub test_zone_tap_plug {
 }
 
 run_test(\&test_zone_tap_plug);
-run_test(\&test_ebpf_backend_edge_cases);
 
 sub test_ebpf_mac_case {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
@@ -2870,6 +2920,75 @@ sub test_ebpf_zone_mtu {
 
 run_test(\&test_ebpf_zone_mtu);
 
+sub test_ebpf_vxlan_mtu {
+    my $test_name = (split(/::/, (caller(0))[3]))[-1];
+    my $zoneid = "VXZONE";
+    my $vnetid = "vxvnet";
+    my $mac = "da:65:8f:18:9b:6f";
+
+    # a vxlan zone without an MTU of its own answers with the one its bridge
+    # takes from the underlay, the encapsulation overhead taken off
+    my $mocked_zone_plugin = Test::MockModule->new('PVE::Network::SDN::Zones::Plugin');
+    $mocked_zone_plugin->mock(
+        find_local_ip_interface_peers => sub { return ('10.10.10.1', 'eno1'); });
+    $mocked_pve_inotify->mock(
+        read_file => sub { return { ifaces => { eno1 => { mtu => 1400 } } }; });
+    create_zone({
+        type => "vxlan",
+        peers => "10.10.10.2",
+        dhcp => "ebpf",
+        ipam => "pve",
+        zone => $zoneid,
+    });
+    create_vnet({
+        type => "vnet",
+        zone => $zoneid,
+        vnet => $vnetid,
+        tag => 100,
+    });
+    create_subnet({
+        type => "subnet",
+        vnet => $vnetid,
+        subnet => "10.0.0.0/24",
+        gateway => "10.0.0.1",
+    });
+    $test_state->{vmlist} = { ids => { 999 => { type => 'qemu', node => 'localnode' } } };
+    $test_state->{guest_nets} = { 999 => { net0 => "virtio=$mac,bridge=$vnetid" } };
+    $test_state->{macdb} = {
+        vnets => { $vnetid => { $mac => { ip4 => '10.0.0.100' } } },
+        macs => { $mac => { ip4 => '10.0.0.100' } },
+    };
+
+    take_ebpf_calls();
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{mtu},
+        1350,
+        "$test_name: the underlay's MTU minus the encapsulation is handed out",
+    );
+
+    # over IPv6 the encapsulation takes 70 bytes
+    $mocked_zone_plugin->mock(find_local_ip_interface_peers => sub { return ('fd00::1', 'eno1'); });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{mtu},
+        1330,
+        "$test_name: over an IPv6 underlay 70 bytes are taken off",
+    );
+    $mocked_zone_plugin->mock(
+        find_local_ip_interface_peers => sub { return ('10.10.10.1', 'eno1'); });
+    update_zone($zoneid, { mtu => 1500 });
+    PVE::Network::SDN::Dhcp::regenerate_config();
+    is(
+        take_ebpf_calls()->[0]->{args}->[0]->[0]->{record}->{mtu},
+        1500,
+        "$test_name: an explicit zone MTU wins",
+    );
+    $mocked_pve_inotify->unmock('read_file');
+}
+
+run_test(\&test_ebpf_vxlan_mtu);
+
 sub test_ebpf_overlapping_subnets {
     my $test_name = (split(/::/, (caller(0))[3]))[-1];
     my $zoneid = "TESTZONE";
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH qemu-server v7 14/21] network: sdn: keep the DHCP backends current on guest NICs
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (12 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-network v7 13/21] sdn: zones: allow the ebpf DHCP backend on every zone type Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-container v7 15/21] net: report NIC plugs and removals to the SDN DHCP backends Hannes Laimer
                   ` (6 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

A DHCP backend that serves the guest's tap itself has to hear of
every plug and removal of that tap. The plug now carries the NIC's
MAC, so the backend can look up the NIC's record. Removing a tap now
goes through the SDN layer as well, so the backend drops its entry
for that tap.

A hotplug moves the tap while the NIC's new bridge is still a pending
change in the config. So it marks its plug as pending, and the NIC is
reported to the backends again once the change is applied.

A bridge change allocated the NIC's address in the new vnet, but
unlike a start or a hotplug it never pushed the mapping to the
backend of that vnet's zone. It now does.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---

Notes:
    v5:
     * the resume push moved to the IPAM series

 src/PVE/CLI/qm.pm                                |  4 ++--
 src/PVE/QemuServer.pm                            | 16 ++++++++++++++++
 src/PVE/QemuServer/Network.pm                    | 10 ++++++++--
 .../aarch64/net-add-pci-bridge.conf.expected     |  1 +
 src/test/hotplug/aarch64/net-add.conf.expected   |  1 +
 .../aarch64/x86-guest-net-add.conf.expected      |  1 +
 .../hotplug/net-add-pci-bridge.conf.expected     |  1 +
 src/test/hotplug/net-add.conf.expected           |  1 +
 src/test/hotplug/net-change-bridge.conf.expected |  4 +++-
 src/test/hotplug/net-change-model.conf.expected  |  1 +
 src/test/hotplug/net-change-rate.conf.expected   |  1 +
 src/test/run_hotplug_tests.pl                    |  5 ++++-
 src/usr/pve-bridge                               |  8 +++++++-
 src/usr/pve-bridgedown                           |  4 ++--
 14 files changed, 49 insertions(+), 9 deletions(-)

diff --git a/src/PVE/CLI/qm.pm b/src/PVE/CLI/qm.pm
index f62fe0366b97..4917760fca78 100755
--- a/src/PVE/CLI/qm.pm
+++ b/src/PVE/CLI/qm.pm
@@ -22,7 +22,7 @@ use PVE::GuestHelpers;
 use PVE::GuestImport::OVF;
 use PVE::INotify;
 use PVE::JSONSchema qw(get_standard_option);
-use PVE::Network;
+use PVE::Network::SDN::Zones;
 use PVE::RPCEnvironment;
 use PVE::SafeSyslog;
 use PVE::Tools qw(extract_param file_get_contents);
@@ -1143,7 +1143,7 @@ __PACKAGE__->register_method({
                     foreach my $opt (keys %$conf) {
                         next if $opt !~ m/^net(\d+)$/;
                         my $interface = $1;
-                        PVE::Network::tap_unplug("tap${vmid}i${interface}");
+                        PVE::Network::SDN::Zones::tap_unplug("tap${vmid}i${interface}");
                     }
                 }
 
diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm
index 55abde5e219d..32367ea2826e 100644
--- a/src/PVE/QemuServer.pm
+++ b/src/PVE/QemuServer.pm
@@ -4627,6 +4627,7 @@ sub vmconfig_hotplug_pending {
     }
 
     my $cloudinit_opt;
+    my $hotplugged_nets = [];
     foreach my $opt (keys %{ $conf->{pending} }) {
         next if $selection && !$selection->{$opt};
         my $value = $conf->{pending}->{$opt};
@@ -4735,6 +4736,7 @@ sub vmconfig_hotplug_pending {
             $cloudinit_record_changed->($conf, $opt, $conf->{$opt}, $value);
             $conf->{$opt} = $value;
             delete $conf->{pending}->{$opt};
+            push $hotplugged_nets->@*, $opt if $opt =~ m/^net\d+$/;
         }
     }
 
@@ -4778,6 +4780,16 @@ sub vmconfig_hotplug_pending {
 
     PVE::QemuConfig->write_config($vmid, $conf);
 
+    # the SDN DHCP backends serve a hotplugged NIC only once its change is applied to the config
+    for my $opt ($hotplugged_nets->@*) {
+        my $net = PVE::QemuServer::Network::parse_net($conf->{$opt});
+        next if !$net || !$net->{bridge};
+        my ($index) = $opt =~ m/^net(\d+)$/;
+        PVE::QemuServer::Network::tap_commit(
+            "tap${vmid}i$index", $net->{bridge}, $net->{macaddr},
+        );
+    }
+
     if ($hotplug_features->{cloudinit} && PVE::QemuServer::Cloudinit::has_changes($conf)) {
         PVE::QemuServer::vmconfig_update_cloudinit_drive($storecfg, $conf, $vmid);
     }
@@ -5000,6 +5012,9 @@ sub vmconfig_update_net {
                     PVE::Network::SDN::Vnets::add_next_free_cidr(
                         $newnet->{bridge}, $conf->{name}, $newnet->{macaddr}, $vmid, undef, 1,
                     );
+                    PVE::Network::SDN::Vnets::add_dhcp_mapping(
+                        $newnet->{bridge}, $newnet->{macaddr}, $vmid, $conf->{name},
+                    );
                 }
 
                 PVE::QemuServer::Network::tap_plug(
@@ -5009,6 +5024,7 @@ sub vmconfig_update_net {
                     $newnet->{firewall},
                     $newnet->{trunks},
                     $newnet->{rate},
+                    { mac => $newnet->{macaddr}, pending => 1 },
                 );
                 # unplugging the interface dropped its forwarding database entries
                 eval { PVE::QemuServer::Network::add_nets_bridge_fdb({ $opt => $value }, $vmid) };
diff --git a/src/PVE/QemuServer/Network.pm b/src/PVE/QemuServer/Network.pm
index 1bad0196e179..cf0930c09a75 100644
--- a/src/PVE/QemuServer/Network.pm
+++ b/src/PVE/QemuServer/Network.pm
@@ -368,10 +368,16 @@ sub delete_ifaces_ipams_ips {
 }
 
 sub tap_plug {
-    my ($iface, $bridge, $tag, $firewall, $trunks, $rate) = @_;
+    my ($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts) = @_;
 
     $firewall = $firewall && PVE::Firewall::Helpers::needs_fwbr($bridge);
-    PVE::Network::SDN::Zones::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate);
+    PVE::Network::SDN::Zones::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts);
+}
+
+sub tap_commit {
+    my ($iface, $bridge, $mac) = @_;
+
+    PVE::Network::SDN::Zones::tap_commit($iface, $bridge, $mac);
 }
 
 sub get_nets_host_mtu {
diff --git a/src/test/hotplug/aarch64/net-add-pci-bridge.conf.expected b/src/test/hotplug/aarch64/net-add-pci-bridge.conf.expected
index 40aa47c562c4..bc0a2d18fffe 100644
--- a/src/test/hotplug/aarch64/net-add-pci-bridge.conf.expected
+++ b/src/test/hotplug/aarch64/net-add-pci-bridge.conf.expected
@@ -3,3 +3,4 @@ sdn add_dhcp_mapping ["vmbr0","BA:DC:0F:FE:E0:06","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net6","ifname":"tap8006i6","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap","vhost":true}
 hmp device_add driver=virtio-net-pci,mac=BA:DC:0F:FE:E0:06,netdev=net6,bus=pci.1,addr=0x1,id=net6,rx_queue_size=1024,tx_queue_size=256,host_mtu=1500
 qmp set_link {"name":"net6","up":true}
+net tap_commit ["tap8006i6","vmbr0","BA:DC:0F:FE:E0:06"]
diff --git a/src/test/hotplug/aarch64/net-add.conf.expected b/src/test/hotplug/aarch64/net-add.conf.expected
index 8d5521215b7c..35599f8ed3fb 100644
--- a/src/test/hotplug/aarch64/net-add.conf.expected
+++ b/src/test/hotplug/aarch64/net-add.conf.expected
@@ -3,3 +3,4 @@ sdn add_dhcp_mapping ["vmbr0","BA:DC:0F:FE:E0:01","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net1","ifname":"tap8006i1","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap","vhost":true}
 hmp device_add driver=virtio-net-pci,mac=BA:DC:0F:FE:E0:01,netdev=net1,bus=pcie.0,addr=0x13,id=net1,rx_queue_size=1024,tx_queue_size=256,host_mtu=1500
 qmp set_link {"name":"net1","up":true}
+net tap_commit ["tap8006i1","vmbr0","BA:DC:0F:FE:E0:01"]
diff --git a/src/test/hotplug/aarch64/x86-guest-net-add.conf.expected b/src/test/hotplug/aarch64/x86-guest-net-add.conf.expected
index 7f2b08a81987..e27c5c80c01c 100644
--- a/src/test/hotplug/aarch64/x86-guest-net-add.conf.expected
+++ b/src/test/hotplug/aarch64/x86-guest-net-add.conf.expected
@@ -3,3 +3,4 @@ sdn add_dhcp_mapping ["vmbr0","BA:DC:0F:FE:E0:01","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net1","ifname":"tap8006i1","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap"}
 hmp device_add driver=virtio-net-pci,mac=BA:DC:0F:FE:E0:01,netdev=net1,bus=pci.0,addr=0x13,id=net1,rx_queue_size=1024,tx_queue_size=256,host_mtu=1500
 qmp set_link {"name":"net1","up":true}
+net tap_commit ["tap8006i1","vmbr0","BA:DC:0F:FE:E0:01"]
diff --git a/src/test/hotplug/net-add-pci-bridge.conf.expected b/src/test/hotplug/net-add-pci-bridge.conf.expected
index 40aa47c562c4..bc0a2d18fffe 100644
--- a/src/test/hotplug/net-add-pci-bridge.conf.expected
+++ b/src/test/hotplug/net-add-pci-bridge.conf.expected
@@ -3,3 +3,4 @@ sdn add_dhcp_mapping ["vmbr0","BA:DC:0F:FE:E0:06","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net6","ifname":"tap8006i6","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap","vhost":true}
 hmp device_add driver=virtio-net-pci,mac=BA:DC:0F:FE:E0:06,netdev=net6,bus=pci.1,addr=0x1,id=net6,rx_queue_size=1024,tx_queue_size=256,host_mtu=1500
 qmp set_link {"name":"net6","up":true}
+net tap_commit ["tap8006i6","vmbr0","BA:DC:0F:FE:E0:06"]
diff --git a/src/test/hotplug/net-add.conf.expected b/src/test/hotplug/net-add.conf.expected
index 562bfb1293be..edb2a48b4611 100644
--- a/src/test/hotplug/net-add.conf.expected
+++ b/src/test/hotplug/net-add.conf.expected
@@ -3,3 +3,4 @@ sdn add_dhcp_mapping ["vmbr0","BA:DC:0F:FE:E0:01","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net1","ifname":"tap8006i1","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap","vhost":true}
 hmp device_add driver=virtio-net-pci,mac=BA:DC:0F:FE:E0:01,netdev=net1,bus=pci.0,addr=0x13,id=net1,rx_queue_size=1024,tx_queue_size=256,host_mtu=1500
 qmp set_link {"name":"net1","up":true}
+net tap_commit ["tap8006i1","vmbr0","BA:DC:0F:FE:E0:01"]
diff --git a/src/test/hotplug/net-change-bridge.conf.expected b/src/test/hotplug/net-change-bridge.conf.expected
index a745b2e58e50..8f9d548cdddb 100644
--- a/src/test/hotplug/net-change-bridge.conf.expected
+++ b/src/test/hotplug/net-change-bridge.conf.expected
@@ -2,5 +2,7 @@ net tap_unplug ["tap8006i0"]
 qmp set_link {"name":"net0","up":false}
 sdn del_ips_from_mac ["vmbr0","A2:C0:43:77:08:A0","hotplug"]
 sdn add_next_free_cidr ["vmbr1","hotplug","A2:C0:43:77:08:A0","8006",null,1]
-net tap_plug ["tap8006i0","vmbr1","100",null,null,null]
+sdn add_dhcp_mapping ["vmbr1","A2:C0:43:77:08:A0","8006","hotplug"]
+net tap_plug ["tap8006i0","vmbr1","100",null,null,null,{"mac":"A2:C0:43:77:08:A0","pending":1}]
 qmp set_link {"name":"net0","up":true}
+net tap_commit ["tap8006i0","vmbr1","A2:C0:43:77:08:A0"]
diff --git a/src/test/hotplug/net-change-model.conf.expected b/src/test/hotplug/net-change-model.conf.expected
index b61756cd7c94..204470b28f2e 100644
--- a/src/test/hotplug/net-change-model.conf.expected
+++ b/src/test/hotplug/net-change-model.conf.expected
@@ -6,3 +6,4 @@ sdn add_dhcp_mapping ["vmbr0","A2:C0:43:77:08:A0","8006","hotplug"]
 qmp netdev_add {"downscript":"/usr/libexec/qemu-server/pve-bridgedown","id":"net0","ifname":"tap8006i0","script":"/usr/libexec/qemu-server/pve-bridge-hotplug","type":"tap"}
 hmp device_add driver=e1000,mac=A2:C0:43:77:08:A0,netdev=net0,bus=pci.0,addr=0x12,id=net0
 qmp set_link {"name":"net0","up":true}
+net tap_commit ["tap8006i0","vmbr0","A2:C0:43:77:08:A0"]
diff --git a/src/test/hotplug/net-change-rate.conf.expected b/src/test/hotplug/net-change-rate.conf.expected
index c4e24dae7bd0..c11e049e7fc9 100644
--- a/src/test/hotplug/net-change-rate.conf.expected
+++ b/src/test/hotplug/net-change-rate.conf.expected
@@ -1 +1,2 @@
 net tap_rate_limit ["tap8006i0","10"]
+net tap_commit ["tap8006i0","vmbr0","A2:C0:43:77:08:A0"]
diff --git a/src/test/run_hotplug_tests.pl b/src/test/run_hotplug_tests.pl
index fd3bc1fe4787..58f07eaf579f 100644
--- a/src/test/run_hotplug_tests.pl
+++ b/src/test/run_hotplug_tests.pl
@@ -663,7 +663,10 @@ $pve_common_network->mock(
 );
 
 my $qemu_network_module = Test::MockModule->new('PVE::QemuServer::Network');
-$qemu_network_module->mock(tap_plug => recorder('net', 'tap_plug'));
+$qemu_network_module->mock(
+    tap_plug => recorder('net', 'tap_plug'),
+    tap_commit => recorder('net', 'tap_commit'),
+);
 
 my $sdn_vnets_module = Test::MockModule->new('PVE::Network::SDN::Vnets');
 $sdn_vnets_module->mock(
diff --git a/src/usr/pve-bridge b/src/usr/pve-bridge
index c7260c6b5a82..c7ac7a3b3c5e 100755
--- a/src/usr/pve-bridge
+++ b/src/usr/pve-bridge
@@ -43,7 +43,13 @@ die "unable to parse network config '$netid'\n" if !$net;
 PVE::Network::SDN::Vnets::add_dhcp_mapping($net->{bridge}, $net->{macaddr}, $vmid, $conf->{name});
 PVE::Network::SDN::Zones::tap_create($iface, $net->{bridge});
 PVE::QemuServer::Network::tap_plug(
-    $iface, $net->{bridge}, $net->{tag}, $net->{firewall}, $net->{trunks}, $net->{rate},
+    $iface,
+    $net->{bridge},
+    $net->{tag},
+    $net->{firewall},
+    $net->{trunks},
+    $net->{rate},
+    { mac => $net->{macaddr}, pending => $hotplug },
 );
 
 exit 0;
diff --git a/src/usr/pve-bridgedown b/src/usr/pve-bridgedown
index e867b640207a..79a3722bd46a 100755
--- a/src/usr/pve-bridgedown
+++ b/src/usr/pve-bridgedown
@@ -2,7 +2,7 @@
 
 use strict;
 use warnings;
-use PVE::Network;
+use PVE::Network::SDN::Zones;
 
 my $iface = shift;
 
@@ -11,6 +11,6 @@ die "no interface specified\n" if !$iface;
 die "got strange interface name '$iface'\n"
     if $iface !~ m/^tap(\d+)i(\d+)$/;
 
-PVE::Network::tap_unplug($iface);
+PVE::Network::SDN::Zones::tap_unplug($iface);
 
 exit 0;
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-container v7 15/21] net: report NIC plugs and removals to the SDN DHCP backends
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (13 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH qemu-server v7 14/21] network: sdn: keep the DHCP backends current on guest NICs Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-manager v7 16/21] ui: sdn: add zone DHCP backend selector and subnet DHCP options Hannes Laimer
                   ` (5 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

An SDN DHCP backend answers a guest NIC with the address IPAM holds
for its MAC. A NIC joining its bridge now hands its MAC to the SDN
plug, so the backend of its vnet can answer it. Deleting a veth also
reports it as gone to the backends, since their state for an
interface can outlive it.

A hotplug moves the veth while its new bridge is still a pending
change in the config. So it marks its plug as pending, and the NIC is
reported to the backends again once the change is applied.

On a running container, a bridge change now pushes the DHCP mapping
for the new vnet, as adding a NIC or changing its MAC already does.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 src/PVE/LXC.pm            | 33 +++++++++++++++++++++++++++------
 src/PVE/LXC/Config.pm     |  3 ++-
 src/lxc-pve-poststop-hook |  6 +++---
 3 files changed, 32 insertions(+), 10 deletions(-)

diff --git a/src/PVE/LXC.pm b/src/PVE/LXC.pm
index 59d803d2592c..aea41a545abe 100644
--- a/src/PVE/LXC.pm
+++ b/src/PVE/LXC.pm
@@ -1074,8 +1074,8 @@ sub vm_stop_cleanup {
     kill_dhclients($vmid);
 }
 
-sub net_tap_plug : prototype($$) {
-    my ($iface, $net) = @_;
+sub net_tap_plug : prototype($$;$) {
+    my ($iface, $net, $pending) = @_;
 
     if ($net->{link_down}) {
         PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'down']);
@@ -1090,13 +1090,27 @@ sub net_tap_plug : prototype($$) {
     my $create_firewall_bridges = $net->{firewall} && PVE::Firewall::Helpers::needs_fwbr($bridge);
 
     PVE::Network::SDN::Zones::tap_plug(
-        $iface, $bridge, $tag, $create_firewall_bridges, $trunks, $rate,
+        $iface,
+        $bridge,
+        $tag,
+        $create_firewall_bridges,
+        $trunks,
+        $rate,
+        { mac => $hwaddr, pending => $pending },
     );
     PVE::Network::SDN::Zones::add_bridge_fdb($iface, $hwaddr, $bridge);
 
     PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'up']);
 }
 
+# the SDN DHCP backends serve a hotplugged NIC only once its change is applied to the config
+sub net_tap_commit {
+    my ($iface, $net) = @_;
+
+    return if $net->{link_down} || !$net->{bridge};
+    PVE::Network::SDN::Zones::tap_commit($iface, $net->{bridge}, $net->{hwaddr});
+}
+
 sub update_net {
     my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
 
@@ -1116,7 +1130,7 @@ sub update_net {
             || safe_string_ne($oldnet->{name}, $newnet->{name})
         ) {
 
-            PVE::Network::veth_delete($veth);
+            PVE::Network::SDN::Zones::veth_delete($veth);
 
             if (safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr})) {
                 eval {
@@ -1171,8 +1185,11 @@ sub update_net {
                     PVE::Network::SDN::Vnets::add_next_free_cidr(
                         $newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1,
                     );
+                    PVE::Network::SDN::Vnets::add_dhcp_mapping(
+                        $newnet->{bridge}, $newnet->{hwaddr}, $vmid, $conf->{hostname},
+                    );
                 }
-                eval { PVE::LXC::net_tap_plug($veth, $newnet) };
+                eval { PVE::LXC::net_tap_plug($veth, $newnet, 1) };
                 if (my $err = $@) {
                     eval { PVE::LXC::net_tap_plug($veth, $oldnet) };
                     warn "restoring old network due to hot-plug failure for $veth failed - $@"
@@ -1192,6 +1209,8 @@ sub update_net {
             }
             $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
             PVE::LXC::Config->write_config($vmid, $conf);
+            # $oldnet keeps a link_down that the change cleared
+            net_tap_commit($veth, $newnet);
         }
     } else {
         PVE::Network::SDN::Vnets::add_next_free_cidr(
@@ -1218,7 +1237,7 @@ sub hotplug_net {
         $veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr},
     );
 
-    PVE::LXC::net_tap_plug($veth, $newnet);
+    PVE::LXC::net_tap_plug($veth, $newnet, 1);
 
     # attach peer in container
     my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth"];
@@ -1236,6 +1255,8 @@ sub hotplug_net {
     $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
 
     PVE::LXC::Config->write_config($vmid, $conf);
+
+    net_tap_commit($veth, $newnet);
 }
 
 sub get_interfaces {
diff --git a/src/PVE/LXC/Config.pm b/src/PVE/LXC/Config.pm
index b2f623394b21..14bc60a22b8d 100644
--- a/src/PVE/LXC/Config.pm
+++ b/src/PVE/LXC/Config.pm
@@ -12,6 +12,7 @@ use PVE::GuestHelpers;
 use PVE::INotify;
 use PVE::JSONSchema qw(get_standard_option);
 use PVE::Network::SDN::Vnets;
+use PVE::Network::SDN::Zones;
 use PVE::RESTEnvironment;
 use PVE::Tools;
 
@@ -1699,7 +1700,7 @@ sub vmconfig_hotplug_pending {
                 my $net = $class->parse_lxc_network($conf->{$opt});
                 PVE::LXC::kill_dhclients($vmid, $net->{name}) if $net->{'host-managed'};
 
-                PVE::Network::veth_delete("veth${vmid}i$netid");
+                PVE::Network::SDN::Zones::veth_delete("veth${vmid}i$netid");
                 print "delete ips from $opt\n";
                 eval {
                     PVE::Network::SDN::Vnets::del_ips_from_mac(
diff --git a/src/lxc-pve-poststop-hook b/src/lxc-pve-poststop-hook
index c8bbb7972156..c5d1059fae02 100755
--- a/src/lxc-pve-poststop-hook
+++ b/src/lxc-pve-poststop-hook
@@ -11,7 +11,7 @@ use PVE::GuestHelpers;
 use PVE::LXC::Config;
 use PVE::LXC::Tools;
 use PVE::LXC;
-use PVE::Network;
+use PVE::Network::SDN::Zones;
 use PVE::RESTEnvironment;
 use PVE::Storage;
 use PVE::Tools;
@@ -49,8 +49,8 @@ PVE::LXC::Tools::lxc_hook(
             my $ind = $1;
             my $net = PVE::LXC::Config->parse_lxc_network($conf->{$k});
             next if $net->{type} ne 'veth';
-            # veth_delete tests with '-d /sys/class/net/$name' before running the command
-            PVE::Network::veth_delete("veth${vmid}i$ind");
+            # reports the unplug and deletes the veth only where it still exists
+            PVE::Network::SDN::Zones::veth_delete("veth${vmid}i$ind");
         }
 
         my $config_updated = 0;
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-manager v7 16/21] ui: sdn: add zone DHCP backend selector and subnet DHCP options
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (14 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-container v7 15/21] net: report NIC plugs and removals to the SDN DHCP backends Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH pve-manager v7 17/21] sdn: bring up the DHCP backends at boot before the guests start Hannes Laimer
                   ` (4 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

Zones of every type can now get DHCP from the eBPF backend, while
dnsmasq stays limited to simple zones. The checkbox that enabled
dnsmasq on simple zones becomes a backend selector in the advanced
options of every zone dialog.

The subnet dialog gains fields for the new DHCP lease time and for the
DHCP DNS server, which could be set only through the API until now.
The eBPF backend hands out a DNS server only when the subnet sets one.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
Reviewed-by: Stefan Hanreich <s.hanreich@proxmox.com>
Tested-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 www/manager6/sdn/SubnetEdit.js       | 23 +++++++++++++++++++++++
 www/manager6/sdn/zones/Base.js       | 17 +++++++++++++++++
 www/manager6/sdn/zones/SimpleEdit.js | 11 -----------
 3 files changed, 40 insertions(+), 11 deletions(-)

diff --git a/www/manager6/sdn/SubnetEdit.js b/www/manager6/sdn/SubnetEdit.js
index a360842891a3..a1d36eeb07d1 100644
--- a/www/manager6/sdn/SubnetEdit.js
+++ b/www/manager6/sdn/SubnetEdit.js
@@ -56,6 +56,29 @@ Ext.define('PVE.sdn.SubnetInputPanel', {
                 deleteEmpty: '{!isCreate}',
             },
         },
+        {
+            xtype: 'proxmoxtextfield',
+            name: 'dhcp-dns-server',
+            vtype: 'IP64Address',
+            fieldLabel: gettext('DHCP DNS Server'),
+            allowBlank: true,
+            skipEmptyText: true,
+            cbind: {
+                deleteEmpty: '{!isCreate}',
+            },
+        },
+        {
+            xtype: 'proxmoxintegerfield',
+            name: 'dhcp-lease-time',
+            fieldLabel: gettext('DHCP Lease Time') + ' (s)',
+            emptyText: Proxmox.Utils.defaultText,
+            minValue: 60,
+            maxValue: 4294967295,
+            allowBlank: true,
+            cbind: {
+                deleteEmpty: '{!isCreate}',
+            },
+        },
     ],
 });
 
diff --git a/www/manager6/sdn/zones/Base.js b/www/manager6/sdn/zones/Base.js
index 66f93de0dff2..7696136d1ec0 100644
--- a/www/manager6/sdn/zones/Base.js
+++ b/www/manager6/sdn/zones/Base.js
@@ -82,6 +82,23 @@ Ext.define('PVE.panel.SDNZoneBase', {
             },
         );
 
+        let dhcpBackends = [
+            ['__default__', Proxmox.Utils.NoneText],
+            ['ebpf', 'eBPF'],
+        ];
+        if (me.type === 'simple') {
+            dhcpBackends.splice(1, 0, ['dnsmasq', 'dnsmasq']);
+        }
+
+        me.advancedItems.push({
+            xtype: 'proxmoxKVComboBox',
+            name: 'dhcp',
+            fieldLabel: gettext('DHCP Backend'),
+            comboItems: dhcpBackends,
+            value: '__default__',
+            deleteEmpty: !me.isCreate,
+        });
+
         me.callParent();
     },
 });
diff --git a/www/manager6/sdn/zones/SimpleEdit.js b/www/manager6/sdn/zones/SimpleEdit.js
index ba10bb3616ea..aeb076aeec85 100644
--- a/www/manager6/sdn/zones/SimpleEdit.js
+++ b/www/manager6/sdn/zones/SimpleEdit.js
@@ -19,17 +19,6 @@ Ext.define('PVE.sdn.zones.SimpleInputPanel', {
         var me = this;
 
         me.items = [];
-        me.advancedItems = [
-            {
-                xtype: 'proxmoxcheckbox',
-                name: 'dhcp',
-                inputValue: 'dnsmasq',
-                uncheckedValue: null,
-                checked: false,
-                fieldLabel: gettext('Automatic DHCP'),
-                deleteEmpty: !me.isCreate,
-            },
-        ];
 
         me.callParent();
     },
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-manager v7 17/21] sdn: bring up the DHCP backends at boot before the guests start
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (15 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-manager v7 16/21] ui: sdn: add zone DHCP backend selector and subnet DHCP options Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 18/21] ve-config: sdn: add the ebpf dhcp backend Hannes Laimer
                   ` (3 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The eBPF DHCP responder keeps its programs and maps pinned in bpffs,
so they are gone after a reboot. The SDN commit helper now brings the
DHCP backends back up on every boot, not only when it has changes to
commit.

The helper runs before the node and HA start the guests at boot.
Otherwise the first guest interface plug loads the responder with a
full pass, which holds the responder's lock exclusively. A guest
starting meanwhile waits for that lock. One that waits too long comes
up without the responder on its interface.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---

Notes:
    v4:
     * log that the DHCP backends are being brought up

 bin/pve-sdn-commit              | 4 ++++
 services/pve-sdn-commit.service | 1 +
 2 files changed, 5 insertions(+)

diff --git a/bin/pve-sdn-commit b/bin/pve-sdn-commit
index aa7e9b29056a..13231e4f4fd2 100644
--- a/bin/pve-sdn-commit
+++ b/bin/pve-sdn-commit
@@ -96,6 +96,10 @@ sub sdn_changed {
     return fabrics_changed();
 }
 
+# the dhcp backends bring back what a reboot took, pending changes or not
+print "bringing up the DHCP backends\n";
+PVE::Network::SDN::Dhcp::boot();
+
 if (!sdn_changed()) {
     print "No changes to SDN configuration detected, skipping reload\n";
     exit 0;
diff --git a/services/pve-sdn-commit.service b/services/pve-sdn-commit.service
index ff723725ddcd..825926be81bf 100644
--- a/services/pve-sdn-commit.service
+++ b/services/pve-sdn-commit.service
@@ -3,6 +3,7 @@ Description=Commit Proxmox VE SDN changes
 DefaultDependencies=no
 Wants=pve-cluster.service network.target
 After=frr.service network.target corosync.service
+Before=pve-guests.service pve-ha-lrm.service
 
 [Service]
 ExecStart=/usr/share/pve-manager/helpers/pve-sdn-commit
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH proxmox-ve-rs v7 18/21] ve-config: sdn: add the ebpf dhcp backend
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (16 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH pve-manager v7 17/21] sdn: bring up the DHCP backends at boot before the guests start Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 19/21] sdn-dhcp: add the crate that runs the eBPF DHCP responder Hannes Laimer
                   ` (2 subsequent siblings)
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---

Notes:
    v4:
     * new

 proxmox-ve-config/src/sdn/config.rs | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/proxmox-ve-config/src/sdn/config.rs b/proxmox-ve-config/src/sdn/config.rs
index 55df9dd20c9c..65945526c9df 100644
--- a/proxmox-ve-config/src/sdn/config.rs
+++ b/proxmox-ve-config/src/sdn/config.rs
@@ -111,6 +111,7 @@ impl Display for ZoneType {
 #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
 pub enum DhcpType {
     Dnsmasq,
+    Ebpf,
     Unknown(String),
 }
 proxmox_serde::forward_deserialize_to_from_str!(DhcpType);
@@ -122,6 +123,7 @@ impl FromStr for DhcpType {
     fn from_str(s: &str) -> Result<Self, Self::Err> {
         match s {
             "dnsmasq" => Ok(DhcpType::Dnsmasq),
+            "ebpf" => Ok(DhcpType::Ebpf),
             _ => Ok(DhcpType::Unknown(s.to_string())),
         }
     }
@@ -131,6 +133,7 @@ impl Display for DhcpType {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
         f.write_str(match self {
             DhcpType::Dnsmasq => "dnsmasq",
+            DhcpType::Ebpf => "ebpf",
             DhcpType::Unknown(ty) => ty,
         })
     }
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH proxmox-ve-rs v7 19/21] sdn-dhcp: add the crate that runs the eBPF DHCP responder
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (17 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 18/21] ve-config: sdn: add the ebpf dhcp backend Hannes Laimer
@ 2026-11-12 12:41 ` Hannes Laimer
  2026-11-12 12:42 ` [PATCH pve-docs v7 20/21] sdn: zones: document the MTU taken from the underlay interface Hannes Laimer
  2026-11-12 12:42 ` [PATCH pve-docs v7 21/21] sdn: dhcp: add eBPF backend section Hannes Laimer
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:41 UTC (permalink / raw)
  To: pve-devel

The crate loads the responder program pve-network ships, pins a map
holding the answer of each guest interface and attaches the program
to the interfaces it serves. Callers run a full pass over the guest
interfaces to serve, plug or unplug one interface, or change the
records of a guest's interfaces.

A load starts with an empty map, and only a full pass is handed every
interface to serve. So only a full pass loads. It fills the new map
before any link moves. A plug or a record change that finds nothing
loaded reports that a full pass has to run first.

A hotplug moves a tap while its new bridge or MAC is still a pending
change in the guest config, and no lock closes that gap. So the
caller detaches the program at the move and attaches it again once
the change is applied, and a pass is only handed interfaces that sit
on the bridge their config names. Every answer then comes from a
config that names the bridge the interface is on, and a pass removes
the entry of every interface it is not handed.

A plug holds the lock shared, so plugs run next to each other. A
mapping edit takes it exclusively, so no plug that read the older
address writes after it.

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 Cargo.toml                            |   2 +
 proxmox-sdn-dhcp/Cargo.toml           |  18 +
 proxmox-sdn-dhcp/debian/changelog     |   5 +
 proxmox-sdn-dhcp/debian/control       |  42 ++
 proxmox-sdn-dhcp/debian/copyright     |  18 +
 proxmox-sdn-dhcp/debian/debcargo.toml |   7 +
 proxmox-sdn-dhcp/src/lib.rs           | 688 ++++++++++++++++++++++++++
 proxmox-sdn-dhcp/src/types.rs         |  42 ++
 8 files changed, 822 insertions(+)
 create mode 100644 proxmox-sdn-dhcp/Cargo.toml
 create mode 100644 proxmox-sdn-dhcp/debian/changelog
 create mode 100644 proxmox-sdn-dhcp/debian/control
 create mode 100644 proxmox-sdn-dhcp/debian/copyright
 create mode 100644 proxmox-sdn-dhcp/debian/debcargo.toml
 create mode 100644 proxmox-sdn-dhcp/src/lib.rs
 create mode 100644 proxmox-sdn-dhcp/src/types.rs

diff --git a/Cargo.toml b/Cargo.toml
index 72d4cb6812e7..022236063ff3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,6 +2,7 @@
 members = [
     "proxmox-ve-config",
     "proxmox-frr",
+    "proxmox-sdn-dhcp",
     "proxmox-sdn-types",
 ]
 exclude = [
@@ -24,6 +25,7 @@ regex = "1.7"
 serde = { version = "1" }
 thiserror = "2.0.0"
 
+proxmox-ebpf = { version = "0.1" }
 proxmox-fixed-string = { version = "0.1.1" }
 proxmox-frr = { version = "0.6.0", path = "proxmox-frr" }
 proxmox-network-types = { version = "1.1.2" }
diff --git a/proxmox-sdn-dhcp/Cargo.toml b/proxmox-sdn-dhcp/Cargo.toml
new file mode 100644
index 000000000000..4ce2ccbf2c7d
--- /dev/null
+++ b/proxmox-sdn-dhcp/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "proxmox-sdn-dhcp"
+description = "Per-tap eBPF DHCPv4 responder of the SDN stack"
+version = "0.1.0"
+authors.workspace = true
+edition = "2024"
+license.workspace = true
+homepage.workspace = true
+exclude.workspace = true
+rust-version = "1.88"
+
+[dependencies]
+anyhow = { workspace = true }
+aya = "0.13"
+log = "0.4.17"
+nix = { version = "0.29", features = [ "net" ] }
+
+proxmox-ebpf = { workspace = true }
diff --git a/proxmox-sdn-dhcp/debian/changelog b/proxmox-sdn-dhcp/debian/changelog
new file mode 100644
index 000000000000..f7b51db859de
--- /dev/null
+++ b/proxmox-sdn-dhcp/debian/changelog
@@ -0,0 +1,5 @@
+rust-proxmox-sdn-dhcp (0.1.0-1) trixie; urgency=medium
+
+  * Initial release.
+
+ -- Proxmox Support Team <support@proxmox.com>  Fri, 06 Nov 2026 14:00:00 +0100
diff --git a/proxmox-sdn-dhcp/debian/control b/proxmox-sdn-dhcp/debian/control
new file mode 100644
index 000000000000..d47cbbbea57c
--- /dev/null
+++ b/proxmox-sdn-dhcp/debian/control
@@ -0,0 +1,42 @@
+Source: rust-proxmox-sdn-dhcp
+Section: rust
+Priority: optional
+Build-Depends: debhelper-compat (= 13),
+ dh-sequence-cargo
+Build-Depends-Arch: cargo:native <!nocheck>,
+ rustc:native (>= 1.88) <!nocheck>,
+ libstd-rust-dev <!nocheck>,
+ librust-anyhow-1+default-dev <!nocheck>,
+ librust-aya-0.13+default-dev <!nocheck>,
+ librust-log-0.4+default-dev (>= 0.4.17-~~) <!nocheck>,
+ librust-nix-0.29+default-dev <!nocheck>,
+ librust-nix-0.29+net-dev <!nocheck>,
+ librust-proxmox-ebpf-0.1+default-dev <!nocheck>
+Maintainer: Proxmox Support Team <support@proxmox.com>
+Standards-Version: 4.7.2
+Vcs-Git: git://git.proxmox.com/git/proxmox-ve-rs.git
+Vcs-Browser: https://git.proxmox.com/?p=proxmox-ve-rs.git
+Homepage: https://proxmox.com
+X-Cargo-Crate: proxmox-sdn-dhcp
+
+Package: librust-proxmox-sdn-dhcp-dev
+Architecture: any
+Multi-Arch: same
+Depends:
+ ${misc:Depends},
+ librust-anyhow-1+default-dev,
+ librust-aya-0.13+default-dev,
+ librust-log-0.4+default-dev (>= 0.4.17-~~),
+ librust-nix-0.29+default-dev,
+ librust-nix-0.29+net-dev,
+ librust-proxmox-ebpf-0.1+default-dev
+Provides:
+ librust-proxmox-sdn-dhcp+default-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0+default-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0.1-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0.1+default-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0.1.0-dev (= ${binary:Version}),
+ librust-proxmox-sdn-dhcp-0.1.0+default-dev (= ${binary:Version})
+Description: Per-tap eBPF DHCPv4 responder of the SDN stack - Rust source code
+ Source code for Debianized Rust crate "proxmox-sdn-dhcp"
diff --git a/proxmox-sdn-dhcp/debian/copyright b/proxmox-sdn-dhcp/debian/copyright
new file mode 100644
index 000000000000..77952eba571e
--- /dev/null
+++ b/proxmox-sdn-dhcp/debian/copyright
@@ -0,0 +1,18 @@
+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+
+Files:
+ *
+Copyright: 2019 - 2026 Proxmox Server Solutions GmbH <support@proxmox.com>
+License: AGPL-3.0-or-later
+ This program is free software: you can redistribute it and/or modify it under
+ the terms of the GNU Affero General Public License as published by the Free
+ Software Foundation, either version 3 of the License, or (at your option) any
+ later version.
+ .
+ This program is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+ details.
+ .
+ You should have received a copy of the GNU Affero General Public License along
+ with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/proxmox-sdn-dhcp/debian/debcargo.toml b/proxmox-sdn-dhcp/debian/debcargo.toml
new file mode 100644
index 000000000000..87a787e6d03e
--- /dev/null
+++ b/proxmox-sdn-dhcp/debian/debcargo.toml
@@ -0,0 +1,7 @@
+overlay = "."
+crate_src_path = ".."
+maintainer = "Proxmox Support Team <support@proxmox.com>"
+
+[source]
+vcs_git = "git://git.proxmox.com/git/proxmox-ve-rs.git"
+vcs_browser = "https://git.proxmox.com/?p=proxmox-ve-rs.git"
diff --git a/proxmox-sdn-dhcp/src/lib.rs b/proxmox-sdn-dhcp/src/lib.rs
new file mode 100644
index 000000000000..38fb96b006ff
--- /dev/null
+++ b/proxmox-sdn-dhcp/src/lib.rs
@@ -0,0 +1,688 @@
+//! The dhcp subsystem, a per-tap DHCPv4 responder answering from a pinned map of one entry per
+//! interface.
+//!
+//! The map holds nothing of its own. The SDN side hands in the guest interfaces to serve, each
+//! with the answer it gets, if any. A full pass loads the program and a fresh map from the object
+//! file `/usr/lib/proxmox-ebpf/dhcp.bpf.o` and replaces the running ones with them. It fills the
+//! new map before any link moves. Afterward every interface it was handed has a link, and those
+//! with an answer have an entry. A record change or a plug writes its own interfaces only.
+//!
+//! A plug runs under the shared lock and a pass under the exclusive one. An edit pushes its
+//! record change under the exclusive lock as well, so no plug that read the older address writes
+//! after it. A guest's own start holds the guest lock, so nothing else plugs its interfaces
+//! meanwhile and it writes its records under the shared lock.
+//!
+//! The SDN side reads a guest config without its pending changes, and during a hotplug the
+//! interface's new bridge is still one of them. So it detaches the program when the interface
+//! moves, and attaches the program again once the change is applied to the config. In between
+//! the interface has no entry. A full pass leaves it out as well, since it is not on the bridge
+//! its config names. So every answer is built from a config that names the bridge the interface
+//! is on.
+mod types;
+
+use std::collections::{HashMap, HashSet};
+use std::io::ErrorKind;
+use std::net::Ipv4Addr;
+
+use anyhow::{Context, bail};
+use aya::maps::MapError;
+
+use proxmox_ebpf::subsystem::{
+    ApplyLock, Exclusive, MapHandle, NotLoaded, Shared, Staged, TcPrograms,
+};
+use proxmox_ebpf::tc::{Direction, LinkPin};
+
+use self::types::*;
+
+/// One guest interface to serve. `mac` is the NIC's MAC, which a record needs. `record` is the
+/// answer it gets. Without one the interface gets a link and no entry.
+pub struct Iface {
+    pub name: String,
+    pub mac: Option<[u8; 6]>,
+    pub record: Option<Record>,
+}
+
+/// One interface's answer, the address and every option the reply carries.
+pub struct Record {
+    pub ip: Ipv4Addr,
+    pub prefixlen: u8,
+    pub server_id: Ipv4Addr,
+    pub lease: u32,
+    pub router: Option<Ipv4Addr>,
+    pub dns: Option<Ipv4Addr>,
+    pub mtu: Option<u16>,
+}
+
+/// What a single-entry step did.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Outcome {
+    /// Nothing is left to do. The entry is in place, or its interface is not here.
+    Done,
+    /// Nothing is loaded to write into. Only a full pass loads, so the caller runs one and retries.
+    NeedsFullPass,
+}
+
+const RECORDS_MAP: &str = "dhcp_iface_records";
+const MAPS: [&str; 1] = [RECORDS_MAP];
+
+// bump with any change to the key or value layout of a map in pve-network's
+// src/bpf/dhcp/dhcp.bpf.c, together with DHCP_SCHEMA_VERSION in its types.h
+const SCHEMA_VERSION: u32 = 1;
+
+// requests only arrive from the guest side and replies leave through a redirect, so only ingress
+// carries a program
+const PROGRAM_NAMES: [(Direction, &str); 1] = [(Direction::Ingress, "tc_dhcp_ingress")];
+
+type RecordsMap<'a> = MapHandle<'a, u32, DhcpRecord>;
+
+static PROGRAMS: TcPrograms = TcPrograms::new("dhcp", &PROGRAM_NAMES, &MAPS, SCHEMA_VERSION);
+
+/// The lock a plug runs under, held until [`attach`](SharedLock::attach) returns. Plugs run next
+/// to each other and wait only behind an exclusive holder.
+pub fn lock_shared() -> anyhow::Result<SharedLock> {
+    Ok(SharedLock {
+        lock: PROGRAMS.lock_shared()?,
+    })
+}
+
+/// The lock a full pass or a record change runs under, held until the change is written.
+pub fn lock_exclusive() -> anyhow::Result<ExclusiveLock> {
+    Ok(ExclusiveLock {
+        lock: PROGRAMS.lock_exclusive()?,
+    })
+}
+
+/// A tap unplug, the interface loses its link and its entry. It may be gone by then, so its link
+/// is found by the name the pin carries.
+pub fn detach(iface: &str) -> anyhow::Result<()> {
+    // resolved before the lock wait, an interface recreated under the name meanwhile is not
+    // this unplug's and keeps its link
+    let now = ifindex_of(iface)?;
+    // every guest unplug on the host lands here. Most never had a link and must not wait
+    // behind a pass. One without a link whose interface is gone leaves its entry to the
+    // next pass. A failed listing takes the lock like a pinned link does
+    if matches!(PROGRAMS.is_link_pinned(iface), Ok(false)) && now.is_none() {
+        return Ok(());
+    }
+    detach_under(&PROGRAMS.lock_shared()?, iface, now)
+}
+
+/// The shared lock of the responder, what a plug holds, and the record change of a guest's own
+/// start.
+pub struct SharedLock {
+    lock: ApplyLock<'static, Shared>,
+}
+
+impl SharedLock {
+    /// A plug onto a bridge the responder does not serve, decided under this lock. See
+    /// [`detach`](crate::detach).
+    pub fn detach(&self, iface: &str) -> anyhow::Result<()> {
+        detach_under(&self.lock, iface, ifindex_of(iface)?)
+    }
+
+    /// A tap plug, the entry goes in and the program on. The plug loads nothing, so with nothing
+    /// pinned the caller runs a full pass first.
+    pub fn attach(&self, iface: &Iface) -> anyhow::Result<Outcome> {
+        if !self.lock.is_current() {
+            return Ok(Outcome::NeedsFullPass);
+        }
+        let Some(ifindex) = ifindex_of(iface.name.as_str())? else {
+            log::info!("dhcp attach: {} is gone, nothing to do", iface.name);
+            return Ok(Outcome::Done);
+        };
+        // the entry goes in before the program runs. An interface whose record the reply cannot
+        // carry gets none, since a guest start must not fail on a bad record
+        let mut map: RecordsMap = self.lock.hash_map(RECORDS_MAP)?;
+        let entry = match iface.entry() {
+            Ok(entry) => entry,
+            Err(e) => {
+                log::warn!(
+                    "dhcp: {} attaches with nothing to answer: {e:#}",
+                    iface.name
+                );
+                None
+            }
+        };
+        write_entry(&mut map, ifindex, entry)?;
+        match self.lock.attach_iface(ifindex) {
+            Ok(()) => Ok(Outcome::Done),
+            Err(e) if e.downcast_ref::<NotLoaded>().is_some() => Ok(Outcome::NeedsFullPass),
+            Err(e) => Err(e).with_context(|| format!("dhcp responder for {}", iface.name)),
+        }
+    }
+
+    /// A record change for a caller that holds the guest lock. Nothing else plugs the guest's
+    /// interfaces under that lock, so the shared lock is enough. It writes like
+    /// [`ExclusiveLock::update`].
+    pub fn update(&self, ifaces: &[Iface]) -> anyhow::Result<Outcome> {
+        update_entries(&self.lock, ifaces)
+    }
+}
+
+/// The exclusive lock of the responder, what a full pass and a record change hold.
+pub struct ExclusiveLock {
+    lock: ApplyLock<'static, Exclusive>,
+}
+
+impl ExclusiveLock {
+    /// The full pass. Afterward the program and the map are new, loaded from the object file. Every
+    /// interface handed in that exists here has a link, and an entry if it has a record. Every
+    /// other link and entry is gone. A record that cannot be built leaves its interface the entry
+    /// it had, with a warning. A failed write fails the pass, and the old program and map keep
+    /// serving.
+    pub fn apply(&mut self, ifaces: &[Iface]) -> anyhow::Result<()> {
+        let present = present_ifindexes(ifaces)?;
+        let live = read_records(&self.lock)?;
+        let entries = desired_entries(&live, &present);
+        let wanted: HashSet<u32> = present.keys().copied().collect();
+        self.lock
+            .replace_state(&wanted, |staged| write_entries(staged, &entries))
+    }
+
+    /// A record change. Interfaces not found here are skipped. The rest are written whether they
+    /// have a link yet or not. One without a record loses its entry. A record the reply cannot
+    /// carry leaves its interface as it is. With nothing loaded the caller runs a full pass first,
+    /// like a plug.
+    pub fn update(&self, ifaces: &[Iface]) -> anyhow::Result<Outcome> {
+        update_entries(&self.lock, ifaces)
+    }
+
+    /// Detach everywhere and drop the pinned state, for the last zone leaving the backend.
+    pub fn clear(&mut self) -> anyhow::Result<()> {
+        self.lock.clear()
+    }
+}
+
+fn detach_under(
+    lock: &ApplyLock<'static, Shared>,
+    iface: &str,
+    now: Option<u32>,
+) -> anyhow::Result<()> {
+    if !lock.is_current() {
+        log::debug!("dhcp detach: nothing current, {iface} is left to the next full pass");
+        return Ok(());
+    }
+    // the map is opened before the links go, so a failure there leaves them attached
+    let mut map: RecordsMap = lock.hash_map(RECORDS_MAP)?;
+    let mut ifindexes = lock.detach_named(iface, |pin| {
+        Some(pin.ifindex) != now && pin_alive(pin).unwrap_or(false)
+    })?;
+    // the entry goes in before the link, so an attach that failed in between leaves an entry
+    // without a link
+    if let Some(now) = now.filter(|now| !ifindexes.contains(now)) {
+        ifindexes.push(now);
+    }
+    remove_entries(&mut map, &ifindexes)
+}
+
+fn update_entries<M>(lock: &ApplyLock<'static, M>, ifaces: &[Iface]) -> anyhow::Result<Outcome> {
+    if !lock.is_current() {
+        return Ok(Outcome::NeedsFullPass);
+    }
+    let mut map: RecordsMap = lock.hash_map(RECORDS_MAP)?;
+    let mut failed = 0usize;
+    for iface in ifaces {
+        let ifindex = match ifindex_of(iface.name.as_str()) {
+            Ok(Some(ifindex)) => ifindex,
+            Ok(None) => continue,
+            Err(e) => {
+                log::warn!("dhcp: {e:#}");
+                failed += 1;
+                continue;
+            }
+        };
+        let entry = match iface.entry() {
+            Ok(entry) => entry,
+            Err(e) => {
+                log::warn!("dhcp: {} is left as it is: {e:#}", iface.name);
+                continue;
+            }
+        };
+        if let Err(e) = write_entry(&mut map, ifindex, entry) {
+            log::warn!("dhcp: could not write the entry of {}: {e:#}", iface.name);
+            failed += 1;
+        }
+    }
+    if failed > 0 {
+        bail!("{failed} interfaces could not be updated");
+    }
+    Ok(Outcome::Done)
+}
+
+const NO_MAC: [u8; 6] = [0; 6];
+
+fn remove_entries(map: &mut impl RecordStore, ifindexes: &[u32]) -> anyhow::Result<()> {
+    for &ifindex in ifindexes {
+        map.remove(ifindex)?;
+    }
+    Ok(())
+}
+
+// the record map as the single-entry writers see it, so their decisions run against a plain map in
+// tests
+trait RecordStore {
+    fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()>;
+    // a missing entry is removed already
+    fn remove(&mut self, ifindex: u32) -> anyhow::Result<()>;
+}
+
+impl RecordStore for RecordsMap<'_> {
+    fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()> {
+        aya::maps::HashMap::insert(self, ifindex, rec, 0)?;
+        Ok(())
+    }
+
+    fn remove(&mut self, ifindex: u32) -> anyhow::Result<()> {
+        match aya::maps::HashMap::remove(self, &ifindex) {
+            Ok(()) => Ok(()),
+            // the kernel answers a missing key with ENOENT, and aya passes that through as is
+            Err(MapError::SyscallError(e)) if e.io_error.kind() == ErrorKind::NotFound => Ok(()),
+            Err(e) => Err(e.into()),
+        }
+    }
+}
+
+fn write_entry(
+    map: &mut impl RecordStore,
+    ifindex: u32,
+    entry: Option<DhcpRecord>,
+) -> anyhow::Result<()> {
+    match entry {
+        Some(entry) => map.insert(ifindex, entry),
+        None => map.remove(ifindex),
+    }
+}
+
+// the entries of the live map, none when nothing is pinned. A record the listing cannot read is one
+// the pass cannot carry over, so the pass fails before it replaces anything
+fn read_records(lock: &ApplyLock<'static, Exclusive>) -> anyhow::Result<HashMap<u32, DhcpRecord>> {
+    let map: RecordsMap = match lock.hash_map(RECORDS_MAP) {
+        Ok(map) => map,
+        Err(e) if e.downcast_ref::<NotLoaded>().is_some() => return Ok(HashMap::new()),
+        Err(e) => return Err(e),
+    };
+    map.iter()
+        .collect::<Result<_, _>>()
+        .context("listing the records")
+}
+
+fn desired_entries(
+    live: &HashMap<u32, DhcpRecord>,
+    present: &HashMap<u32, &Iface>,
+) -> HashMap<u32, DhcpRecord> {
+    let mut entries = HashMap::new();
+    for (ifindex, iface) in present {
+        let entry = match iface.entry() {
+            Ok(entry) => entry,
+            // one bad record must not fail the pass
+            Err(e) => {
+                log::warn!("dhcp: {} is left as it is: {e:#}", iface.name);
+                live.get(ifindex).copied()
+            }
+        };
+        if let Some(entry) = entry {
+            entries.insert(*ifindex, entry);
+        }
+    }
+
+    let dropped = live
+        .keys()
+        .filter(|ifindex| !entries.contains_key(ifindex))
+        .count();
+    log::info!("dhcp: {} entries, {dropped} dropped", entries.len());
+    entries
+}
+
+fn write_entries(staged: &Staged<'_>, entries: &HashMap<u32, DhcpRecord>) -> anyhow::Result<()> {
+    let mut map: RecordsMap = staged.hash_map(RECORDS_MAP)?;
+    for (ifindex, entry) in entries {
+        aya::maps::HashMap::insert(&mut map, *ifindex, *entry, 0)
+            .with_context(|| format!("write the entry of ifindex {ifindex}"))?;
+    }
+    Ok(())
+}
+
+// the interface's index here, none when it does not exist. Any other failure says nothing about
+// the interface, and a step taking it for gone would detach what it could not resolve
+fn ifindex_of(name: &str) -> anyhow::Result<Option<u32>> {
+    match nix::net::if_::if_nametoindex(name) {
+        Ok(ifindex) => Ok(Some(ifindex)),
+        Err(nix::errno::Errno::ENODEV) => Ok(None),
+        Err(e) => Err(e).with_context(|| format!("resolve interface {name}")),
+    }
+}
+
+// the handed-in interfaces that still exist, by index
+fn present_ifindexes(ifaces: &[Iface]) -> anyhow::Result<HashMap<u32, &Iface>> {
+    let local = nix::net::if_::if_nameindex().context("list interfaces")?;
+    let by_name: HashMap<&str, u32> = local
+        .iter()
+        .filter_map(|i| i.name().to_str().ok().map(|name| (name, i.index())))
+        .collect();
+    Ok(ifaces
+        .iter()
+        .filter_map(|iface| {
+            by_name
+                .get(iface.name.as_str())
+                .map(|&ifindex| (ifindex, iface))
+        })
+        .collect())
+}
+
+// whether the link's interface still exists under the name and index its pin carries
+fn pin_alive(pin: &LinkPin) -> anyhow::Result<bool> {
+    Ok(ifindex_of(pin.name.as_str())? == Some(pin.ifindex))
+}
+
+impl Iface {
+    fn entry(&self) -> anyhow::Result<Option<DhcpRecord>> {
+        let Some(record) = &self.record else {
+            return Ok(None);
+        };
+        record
+            .entry(self.mac.unwrap_or(NO_MAC))
+            .with_context(|| format!("record for {}", self.name))
+            .map(Some)
+    }
+}
+
+impl Record {
+    // refused here is what the reply cannot carry. Zero stands for absent in the entry, so an
+    // address or an MTU of zero cannot be told from none
+    fn entry(&self, mac: [u8; 6]) -> anyhow::Result<DhcpRecord> {
+        if self.prefixlen == 0 || self.prefixlen > 32 {
+            bail!("prefixlen {} out of range", self.prefixlen);
+        }
+        if self.ip.is_unspecified() {
+            bail!("no address");
+        }
+        if self.server_id.is_unspecified() {
+            bail!("no server address");
+        }
+        if self.lease == 0 {
+            bail!("lease of zero seconds");
+        }
+        if self.mtu.is_some_and(|mtu| mtu < 68) {
+            bail!("mtu below the IPv4 minimum of 68");
+        }
+        if mac == NO_MAC {
+            bail!("no MAC");
+        }
+        let netmask = u32::MAX << (32 - self.prefixlen);
+        Ok(DhcpRecord {
+            ip: u32::from(self.ip).to_be(),
+            netmask: netmask.to_be(),
+            router: u32::from(self.router.unwrap_or(Ipv4Addr::UNSPECIFIED)).to_be(),
+            dns: u32::from(self.dns.unwrap_or(Ipv4Addr::UNSPECIFIED)).to_be(),
+            server_id: u32::from(self.server_id).to_be(),
+            lease: self.lease.to_be(),
+            mtu: self.mtu.unwrap_or(0).to_be(),
+            mac,
+        })
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use std::collections::BTreeMap;
+
+    use super::*;
+
+    fn record() -> Record {
+        Record {
+            ip: Ipv4Addr::new(10, 0, 0, 100),
+            prefixlen: 24,
+            server_id: Ipv4Addr::new(10, 0, 0, 1),
+            lease: 300,
+            router: Some(Ipv4Addr::new(10, 0, 0, 1)),
+            dns: Some(Ipv4Addr::new(1, 1, 1, 1)),
+            mtu: Some(1500),
+        }
+    }
+
+    const MAC: [u8; 6] = [0xda, 0x65, 0x8f, 0x18, 0x9b, 0x6f];
+
+    #[test]
+    fn converts_full_record() {
+        let rec = record().entry(MAC).unwrap();
+        assert_eq!(
+            u32::from_be(rec.ip),
+            u32::from(Ipv4Addr::new(10, 0, 0, 100))
+        );
+        assert_eq!(u32::from_be(rec.netmask), 0xffffff00);
+        assert_eq!(
+            u32::from_be(rec.router),
+            u32::from(Ipv4Addr::new(10, 0, 0, 1))
+        );
+        assert_eq!(u32::from_be(rec.dns), u32::from(Ipv4Addr::new(1, 1, 1, 1)));
+        assert_eq!(
+            u32::from_be(rec.server_id),
+            u32::from(Ipv4Addr::new(10, 0, 0, 1))
+        );
+        assert_eq!(u32::from_be(rec.lease), 300);
+        assert_eq!(u16::from_be(rec.mtu), 1500);
+        assert_eq!(rec.mac, MAC);
+
+        let rec = Record {
+            router: None,
+            dns: None,
+            mtu: None,
+            ..record()
+        }
+        .entry(MAC)
+        .unwrap();
+        assert_eq!(rec.router, 0);
+        assert_eq!(rec.dns, 0);
+        assert_eq!(rec.mtu, 0);
+    }
+
+    #[test]
+    fn refuses_what_the_reply_cannot_carry() {
+        for (what, rec) in [
+            (
+                "a prefix above 32",
+                Record {
+                    prefixlen: 33,
+                    ..record()
+                },
+            ),
+            (
+                "a prefix of 0",
+                Record {
+                    prefixlen: 0,
+                    ..record()
+                },
+            ),
+            (
+                "no server address",
+                Record {
+                    server_id: Ipv4Addr::UNSPECIFIED,
+                    ..record()
+                },
+            ),
+            (
+                "a lease of 0",
+                Record {
+                    lease: 0,
+                    ..record()
+                },
+            ),
+            (
+                "no address",
+                Record {
+                    ip: Ipv4Addr::UNSPECIFIED,
+                    ..record()
+                },
+            ),
+            (
+                "an MTU of 67",
+                Record {
+                    mtu: Some(67),
+                    ..record()
+                },
+            ),
+        ] {
+            assert!(rec.entry(MAC).is_err(), "accepted {what}");
+        }
+        assert!(record().entry(NO_MAC).is_err());
+        let iface = Iface {
+            mac: None,
+            ..iface("a", Some(record()))
+        };
+        assert!(iface.entry().is_err());
+    }
+
+    #[test]
+    fn accepts_the_bounds_the_reply_can_carry() {
+        let rec = Record {
+            mtu: Some(68),
+            ..record()
+        };
+        assert_eq!(u16::from_be(rec.entry(MAC).unwrap().mtu), 68);
+
+        let rec = Record {
+            prefixlen: 32,
+            ..record()
+        };
+        assert_eq!(u32::from_be(rec.entry(MAC).unwrap().netmask), u32::MAX);
+        let rec = Record {
+            prefixlen: 1,
+            ..rec
+        };
+        assert_eq!(u32::from_be(rec.entry(MAC).unwrap().netmask), 1 << 31);
+    }
+
+    impl RecordStore for BTreeMap<u32, DhcpRecord> {
+        fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()> {
+            BTreeMap::insert(self, ifindex, rec);
+            Ok(())
+        }
+
+        fn remove(&mut self, ifindex: u32) -> anyhow::Result<()> {
+            BTreeMap::remove(self, &ifindex);
+            Ok(())
+        }
+    }
+
+    fn entry() -> DhcpRecord {
+        record().entry(MAC).unwrap()
+    }
+
+    fn other_answer() -> DhcpRecord {
+        Record {
+            ip: Ipv4Addr::new(10, 0, 0, 200),
+            ..record()
+        }
+        .entry(MAC)
+        .unwrap()
+    }
+
+    const OTHER_MAC: [u8; 6] = [0xda, 0x65, 0x8f, 0x18, 0x9b, 0x70];
+
+    fn other_mac() -> DhcpRecord {
+        record().entry(OTHER_MAC).unwrap()
+    }
+
+    fn bad_record() -> Record {
+        Record {
+            lease: 0,
+            ..record()
+        }
+    }
+
+    #[test]
+    fn a_plug_or_record_change_writes_whatever_is_there() {
+        let mut map = BTreeMap::new();
+        write_entry(&mut map, 1, Some(entry())).unwrap();
+        assert_eq!(map[&1], entry());
+        map.insert(1, other_mac());
+        write_entry(&mut map, 1, Some(other_answer())).unwrap();
+        assert_eq!(map[&1], other_answer());
+    }
+
+    #[test]
+    fn a_plug_or_record_change_without_a_record_removes_the_entry() {
+        let mut map = BTreeMap::new();
+        map.insert(1, entry());
+        let iface = iface("a", None);
+        write_entry(&mut map, 1, iface.entry().unwrap()).unwrap();
+        assert!(map.is_empty());
+        // a missing entry is removed already
+        write_entry(&mut map, 1, iface.entry().unwrap()).unwrap();
+        assert!(map.is_empty());
+    }
+
+    #[test]
+    fn a_detach_removes_the_entries_of_every_index_it_was_given() {
+        let mut map = BTreeMap::new();
+        map.insert(1, entry());
+        map.insert(2, entry());
+        map.insert(3, entry());
+        remove_entries(&mut map, &[1, 2]).unwrap();
+        assert_eq!(map.keys().copied().collect::<Vec<_>>(), [3]);
+        // a missing entry is removed already
+        remove_entries(&mut map, &[1, 4]).unwrap();
+        assert_eq!(map.keys().copied().collect::<Vec<_>>(), [3]);
+    }
+
+    fn iface(name: &str, record: Option<Record>) -> Iface {
+        Iface {
+            name: name.into(),
+            mac: Some(MAC),
+            record,
+        }
+    }
+
+    #[test]
+    fn the_pass_syncs_the_records_it_knows() {
+        let mut live = HashMap::new();
+        live.insert(1, entry()); // same answer as the config
+        live.insert(2, other_answer()); // a changed answer
+        live.insert(3, other_mac()); // a MAC the config does not name
+        let ifaces = [
+            iface("a", Some(record())),
+            iface("b", Some(record())),
+            iface("c", Some(record())),
+            iface("d", Some(record())), // no entry yet
+        ];
+        let present: HashMap<u32, &Iface> = (1..=4).zip(ifaces.iter()).collect();
+        let entries = desired_entries(&live, &present);
+
+        assert_eq!(entries[&1], entry());
+        assert_eq!(entries[&2], entry(), "a changed answer is rewritten");
+        assert_eq!(entries[&3], entry(), "the MAC follows the config");
+        assert_eq!(entries[&4], entry(), "a new interface gets its entry");
+    }
+
+    #[test]
+    fn the_pass_keeps_only_handed_in_interfaces_with_a_record() {
+        let mut live = HashMap::new();
+        live.insert(1, entry()); // handed in with a record
+        live.insert(2, entry()); // handed in without one
+        live.insert(3, entry()); // not handed in
+        let ifaces = [iface("a", Some(record())), iface("b", None)];
+        let present: HashMap<u32, &Iface> = (1..=2).zip(ifaces.iter()).collect();
+        let entries = desired_entries(&live, &present);
+
+        assert_eq!(
+            entries.keys().copied().collect::<HashSet<_>>(),
+            HashSet::from([1])
+        );
+    }
+
+    #[test]
+    fn bad_input_leaves_its_interface_alone() {
+        let mut live = HashMap::new();
+        live.insert(1, other_answer());
+        let ifaces = [
+            iface("a", Some(bad_record())),
+            iface("b", Some(record())),
+            iface("c", Some(bad_record())),
+        ];
+        let present: HashMap<u32, &Iface> = (1..=3).zip(ifaces.iter()).collect();
+        let entries = desired_entries(&live, &present);
+        assert_eq!(entries[&1], other_answer(), "the old entry stays");
+        assert_eq!(entries[&2], entry(), "the rest is written");
+        assert!(!entries.contains_key(&3), "one without an entry gets none");
+    }
+}
diff --git a/proxmox-sdn-dhcp/src/types.rs b/proxmox-sdn-dhcp/src/types.rs
new file mode 100644
index 000000000000..9d3503b599bf
--- /dev/null
+++ b/proxmox-sdn-dhcp/src/types.rs
@@ -0,0 +1,42 @@
+//! Keep in sync with 'src/bpf/dhcp/types.h' in pve-network.
+
+/// Addresses, lease and mtu are stored in network byte order, so a reply copies them into the
+/// packet as-is.
+#[repr(C)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
+pub struct DhcpRecord {
+    pub ip: u32,
+    pub netmask: u32,
+    /// 0 = not served
+    pub router: u32,
+    /// 0 = not served
+    pub dns: u32,
+    pub server_id: u32,
+    pub lease: u32,
+    /// 0 = not served
+    pub mtu: u16,
+    /// The NIC's MAC, a request carrying another is passed on.
+    pub mac: [u8; 6],
+}
+
+unsafe impl aya::Pod for DhcpRecord {}
+
+#[cfg(test)]
+mod layout {
+    use core::mem::{offset_of, size_of};
+
+    use super::*;
+
+    #[test]
+    fn matches_bpf_abi() {
+        assert_eq!(size_of::<DhcpRecord>(), 32);
+        assert_eq!(offset_of!(DhcpRecord, ip), 0);
+        assert_eq!(offset_of!(DhcpRecord, netmask), 4);
+        assert_eq!(offset_of!(DhcpRecord, router), 8);
+        assert_eq!(offset_of!(DhcpRecord, dns), 12);
+        assert_eq!(offset_of!(DhcpRecord, server_id), 16);
+        assert_eq!(offset_of!(DhcpRecord, lease), 20);
+        assert_eq!(offset_of!(DhcpRecord, mtu), 24);
+        assert_eq!(offset_of!(DhcpRecord, mac), 26);
+    }
+}
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-docs v7 20/21] sdn: zones: document the MTU taken from the underlay interface
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (18 preceding siblings ...)
  2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 19/21] sdn-dhcp: add the crate that runs the eBPF DHCP responder Hannes Laimer
@ 2026-11-12 12:42 ` Hannes Laimer
  2026-11-12 12:42 ` [PATCH pve-docs v7 21/21] sdn: dhcp: add eBPF backend section Hannes Laimer
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:42 UTC (permalink / raw)
  To: pve-devel

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 pvesdn.adoc | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)

diff --git a/pvesdn.adoc b/pvesdn.adoc
index 72f597859e5a..c8f0bd70c6e2 100644
--- a/pvesdn.adoc
+++ b/pvesdn.adoc
@@ -308,8 +308,11 @@ Peers Address List:: A list of IP addresses of each node in the VXLAN zone. This
 SDN Fabric:: Instead of manually defining all the peers, use a
   xref:pvesdn_config_fabrics[Fabric] for automatically generating the peer list.
 
-MTU:: Because VXLAN encapsulation uses 50 bytes, the MTU needs to be 50 bytes
-  lower than the outgoing physical interface.
+MTU:: Because VXLAN encapsulation uses 50 bytes over IPv4 and 70 bytes over
+  IPv6, the MTU needs to be that much lower than the outgoing physical
+  interface.  Optional, defaults to the MTU configured on the interface holding
+  this node's peer address minus the encapsulation. Without such an interface
+  or MTU, it defaults to 1450 over IPv4 and 1430 over IPv6.
 
 
 [[pvesdn_zone_plugin_evpn]]
@@ -368,9 +371,12 @@ Disable ARP ND Suppression:: Don't suppress ARP or ND (Neighbor Discovery)
 Route-target Import:: Allows you to import a list of external EVPN route
   targets. Used for cross-DC or different EVPN network interconnects.  Optional.
 
-MTU:: Because VXLAN encapsulation uses 50 bytes, the MTU needs to be 50 bytes
-  less than the maximal MTU of the outgoing physical interface.  Optional,
-  defaults to 1450.
+MTU:: Because VXLAN encapsulation uses 50 bytes over IPv4 and 70 bytes over
+  IPv6, the MTU needs to be that much less than the maximal MTU of the outgoing
+  physical interface.  Optional, defaults to the MTU configured on the
+  interface holding this node's address from the controller's peers minus the
+  encapsulation. Without such an interface or MTU, it defaults to 1450 over
+  IPv4 and 1430 over IPv6.
 
 
 [[pvesdn_config_vnet]]
@@ -1763,7 +1769,8 @@ The example assumes a cluster with three nodes, with the node IP addresses
 192.168.0.1, 192.168.0.2 and 192.168.0.3.
 
 Create a VXLAN zone named `myvxlanzone` and add all IPs from the nodes to the
-peer address list. Use the default MTU of 1450 or configure accordingly.
+peer address list. Leave the MTU unset or configure accordingly. Without an MTU
+configured on the interfaces holding these addresses, the zone uses 1450.
 
 ----
 ID: myvxlanzone
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH pve-docs v7 21/21] sdn: dhcp: add eBPF backend section
  2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
                   ` (19 preceding siblings ...)
  2026-11-12 12:42 ` [PATCH pve-docs v7 20/21] sdn: zones: document the MTU taken from the underlay interface Hannes Laimer
@ 2026-11-12 12:42 ` Hannes Laimer
  20 siblings, 0 replies; 22+ messages in thread
From: Hannes Laimer @ 2026-11-12 12:42 UTC (permalink / raw)
  To: pve-devel

Signed-off-by: Hannes Laimer <h.laimer@proxmox.com>
---
 pvesdn.adoc | 135 ++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 104 insertions(+), 31 deletions(-)

diff --git a/pvesdn.adoc b/pvesdn.adoc
index c8f0bd70c6e2..c936cd4fc9b7 100644
--- a/pvesdn.adoc
+++ b/pvesdn.adoc
@@ -98,10 +98,12 @@ source /etc/network/interfaces.d/*
 DHCP IPAM
 ~~~~~~~~~
 
-The DHCP integration into the built-in 'PVE' IP Address Management stack
-currently uses `dnsmasq` for giving out DHCP leases. This is currently opt-in.
+The DHCP integration into the built-in 'PVE' IP Address Management stack gives
+out leases either through `dnsmasq` or through an eBPF backend built into
+{pve}. Each zone selects its backend, and DHCP is opt-in per zone.
 
-To use that feature you need to install the `dnsmasq` package on every node:
+The eBPF backend needs no additional package. To use the `dnsmasq` backend you
+need to install the `dnsmasq` package on every node:
 
 ----
 apt update
@@ -153,9 +155,8 @@ in your SDN setup.
 * xref:pvesdn_config_controllers[Controllers]: For controlling layer 3 routing
   in complex setups
 
-* xref:pvesdn_config_dhcp[DHCP]: Define a DHCP server for a zone that
-  automatically allocates IPs for guests in the IPAM and leases them to the
-  guests via DHCP.
+* xref:pvesdn_config_dhcp[DHCP]: Let a zone automatically allocate IPs for
+  guests in the IPAM and lease them to the guests via DHCP.
 
 * xref:pvesdn_config_ipam[IPAM]: Enables external for IP address management for
   guests
@@ -229,6 +230,11 @@ DNSZone:: DNS domain name. Used to register hostnames, such as
 `<hostname>.<domain>`. The DNS zone must already exist on the DNS server.
 Optional.
 
+DHCP Backend:: Hand out leases to the zone's guests through this backend, see
+  xref:pvesdn_config_dhcp[DHCP]. The `dnsmasq` backend is only available for
+  Simple Zones. The `ebpf` backend works with every zone type. Optional,
+  defaults to none, which disables DHCP.
+
 
 [[pvesdn_zone_plugin_simple]]
 Simple Zones
@@ -449,6 +455,15 @@ SNAT:: Enable Source NAT which allows VMs from inside a
 DNS Zone Prefix:: Add a prefix to the domain registration, like
   <hostname>.prefix.<domain>  Optional.
 
+DHCP DNS Server:: The DNS server handed out to guests with their lease.
+  Optional.
+
+DHCP Lease Time:: The lease time in seconds, at least 60. A guest picks up a
+  changed mapping when it renews its lease, so a shorter lease time applies
+  changes sooner. Without it `dnsmasq` hands out infinite leases and the `ebpf`
+  backend ten-minute leases. `dnsmasq` raises anything below two minutes to
+  two minutes. Optional.
+
 
 [[pvesdn_config_controllers]]
 Controllers
@@ -1269,12 +1284,15 @@ update and delete IP mappings. This is particularly convenient in conjunction
 with the xref:pvesdn_config_dhcp[DHCP feature].
 
 If you are using DHCP, you can use the IPAM panel to create or edit leases for
-specific VMs, which enables you to change the IPs allocated via DHCP. When
-editing an IP of a VM that is using DHCP you must make sure to force the guest
-to acquire a new DHCP leases. This can usually be done by reloading the network
-stack of the guest or rebooting it. The edit updates the DHCP reservation on the
-node of the guest right away. It is refused while the guest is being migrated,
-repeat it once the migration is done.
+specific VMs, which enables you to change the IPs allocated via DHCP. The edit
+updates the DHCP reservation on the node of the guest right away. It is refused
+while the guest is being migrated, repeat it once the migration is done.
+
+A guest picks up an edited IP when it next renews its DHCP lease. With an
+infinite lease, the default of the `dnsmasq` backend, the guest never renews.
+Then you have to make it acquire a new lease, for example by reloading its
+network stack or rebooting it. The subnet option *DHCP Lease Time* sets a
+finite lease time, see xref:pvesdn_config_subnet[Subnets].
 
 [[pvesdn_ipam_plugin_netbox]]
 NetBox IPAM Plugin
@@ -1391,9 +1409,9 @@ DHCP
 ------
 
 The DHCP plugin in {pve} SDN can be used to automatically deploy a DHCP server
-for a Zone. It provides DHCP for all Subnets in a Zone that have a DHCP range
-configured. Currently the only available backend plugin for DHCP is the dnsmasq
-plugin.
+for a Zone. It provides DHCP for all Subnets in a Zone. Each zone selects one of
+two backend plugins, `dnsmasq` or `ebpf`. Both answer from the MAC address and
+IP mappings in the IPAM. The `ebpf` backend serves IPv4 subnets only.
 
 The DHCP plugin works by allocating an IP in the IPAM plugin configured in the
 Zone when adding a new network interface to a VM/CT. You can find more
@@ -1411,16 +1429,18 @@ available when using the xref:pvesdn_ipam_plugin_pveipam[PVE IPAM plugin].
 Configuration
 ~~~~~~~~~~~~~
 
-You can enable automatic DHCP for a zone in the Web UI via the Zones panel and
-enabling DHCP in the advanced options of a zone.
+You can enable automatic DHCP for a zone in the web interface via the Zones
+panel by selecting a backend in the *DHCP Backend* field of the zone's advanced
+options.
 
-NOTE: Currently only Simple Zones have support for automatic DHCP
+NOTE: The `dnsmasq` backend is only available for Simple Zones. The `ebpf`
+backend works with every zone type.
 
-After automatic DHCP has been enabled for a Zone, DHCP Ranges need to be
-configured for the subnets in a Zone. In order to that, go to the Vnets panel and
-select the Subnet for which you want to configure DHCP ranges. In the edit
-dialogue you can configure DHCP ranges in the respective Tab. Alternatively you
-can set DHCP ranges for a Subnet via the following CLI command:
+After automatic DHCP has been enabled for a Zone, you can configure DHCP Ranges
+for its subnets to limit which IPs get allocated. To do that, go to the Vnets
+panel and select the Subnet for which you want to configure DHCP ranges. In the
+edit dialog you can configure DHCP ranges in the respective Tab. Alternatively
+you can set DHCP ranges for a Subnet via the following CLI command:
 
 ----
 pvesh set /cluster/sdn/vnets/<vnet>/subnets/<subnet>
@@ -1428,22 +1448,26 @@ pvesh set /cluster/sdn/vnets/<vnet>/subnets/<subnet>
  -dhcp-range start-address=10.0.2.100,end-address=10.0.2.200
 ----
 
-You also need to have a gateway configured for the subnet - otherwise
-automatic DHCP will not work.
+The DHCP plugin then allocates IPs in the IPAM only in the configured ranges.
+A subnet without ranges gets IPs allocated from its whole address range. The
+ranges only limit the allocation. Both backends answer every mapping in the
+Zone, including mappings outside the ranges.
 
-The DHCP plugin will then allocate IPs in the IPAM only in the configured
-ranges.
+The `dnsmasq` backend needs a gateway on the subnet. The `ebpf` backend also
+serves a subnet without one, but then hands out no default route.
 
-Do not forget to follow the installation steps for the
-xref:pvesdn_install_dhcp_ipam[dnsmasq DHCP plugin] as well.
+The subnet options *DHCP DNS Server* and *DHCP Lease Time* set the DNS server
+and the lease time handed out, see xref:pvesdn_config_subnet[Subnets].
+
+When using the `dnsmasq` backend, do not forget to follow the installation
+steps for the xref:pvesdn_install_dhcp_ipam[dnsmasq DHCP plugin] as well.
 
 Plugins
 ~~~~~~~
 
 Dnsmasq Plugin
 ^^^^^^^^^^^^^^
-Currently this is the only DHCP plugin and therefore the plugin that gets used
-when you enable DHCP for a zone.
+This plugin serves zones with `dnsmasq` as their DHCP backend.
 
 .Installation
 For installation see the xref:pvesdn_install_dhcp_ipam[DHCP IPAM] section.
@@ -1486,6 +1510,55 @@ For more information please consult the documentation of
 xref:pvesdn_ipam_plugin_pveipam[the PVE IPAM plugin]. Changing DHCP leases is
 currently not supported for the other IPAM plugins.
 
+[[pvesdn_dhcp_plugin_ebpf]]
+eBPF Plugin
+^^^^^^^^^^^
+This plugin serves zones with `ebpf` as their DHCP backend.
+
+.Installation
+The backend needs no additional package. It requires host kernel version 6.6
+or newer.
+
+Instead of a DHCP server on the bridge, the backend attaches a small eBPF
+program to the network interface of every guest on the zone's VNets. The
+program answers the guest's DHCP requests from the MAC address and IP mapping
+in the IPAM, so these requests never reach the bridge. It only answers
+requests that carry the MAC address of its own network interface. Requests on
+a network interface without a mapping pass through untouched, so such a guest
+can still reach another DHCP server on the network.
+
+The backend attaches the program when a guest starts. For a network interface
+that is hot-plugged or moved to another bridge, it attaches the program once
+the pending change is applied to the guest's configuration. A request the
+guest sends before that goes unanswered, and the guest repeats it. Applying
+the SDN configuration attaches the program to running guests as well, so a
+zone switched to `ebpf` serves them without a restart.
+
+A mapping changed through {pve} reaches a running guest when it next renews
+its lease. After a mapping is deleted, the backend stops answering the guest,
+which keeps its address until the lease runs out.
+
+The answer carries the address, netmask, lease time, and server address. The
+zone's MTU, the subnet's gateway, and its IPv4 DNS server are included where
+the zone or subnet has one. Options `dnsmasq` can add through its custom
+configuration, such as a domain name or PXE boot parameters, are not
+available.
+
+.Notes
+The backend serves IPv4 only. Only untagged requests are answered, so a guest
+tagging its own traffic, for example on a trunk port, is not served. A guest
+with a mapping cannot use another DHCP server on the network, since the
+program answers its request for an address before the request reaches the
+bridge. Clients behind a guest, such as containers bridged inside a virtual
+machine, get no answer, and neither does a guest that changed its MAC address
+in the guest OS.
+
+NOTE: Requests this backend answers never reach the firewall of the guest's
+network interface, so the guest's firewall rules and the DHCP option of its
+firewall have no effect on them. The rate limit applies to the reply only.
+Requests the backend does not answer pass the firewall and the rate limit as
+usual.
+
 [[pvesdn_firewall_integration]]
 Firewall Integration
 --------------------
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2026-11-12 12:45 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-12 12:41 [PATCH container/docs/manager/network/proxmox{,-perl-rs,-ve-rs}/qemu-server v7 00/21] sdn: implement DHCP for all zones using eBPF Hannes Laimer
2026-11-12 12:41 ` [PATCH proxmox v7 01/21] network-types: mac address: add an accessor for the bytes Hannes Laimer
2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 02/21] pve-rs: sdn: add bindings for the eBPF DHCP responder Hannes Laimer
2026-11-12 12:41 ` [PATCH proxmox-perl-rs v7 03/21] pve-rs: fire the pve-ebpf-update trigger on upgrade Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 04/21] sdn: zones: take the VXLAN and EVPN MTU from the underlay interface Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 05/21] sdn: zones: account for IPv6 in the VXLAN and EVPN MTU Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 06/21] sdn: dhcp: make the lease time configurable per subnet Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 07/21] sdn: dhcp: require a backend only if a zone on this node uses it Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 08/21] bpf: add the build, the package and a native harness for BPF programs Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 09/21] sdn: dhcp: add the per-tap DHCPv4 responder program Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 10/21] sdn: dhcp: add an eBPF backend answering on each guest interface Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 11/21] sdn: zones: report interface plugs and unplugs to the DHCP backends Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 12/21] sdn: zones: factor out the underlay lookup of VXLAN and EVPN zones Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-network v7 13/21] sdn: zones: allow the ebpf DHCP backend on every zone type Hannes Laimer
2026-11-12 12:41 ` [PATCH qemu-server v7 14/21] network: sdn: keep the DHCP backends current on guest NICs Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-container v7 15/21] net: report NIC plugs and removals to the SDN DHCP backends Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-manager v7 16/21] ui: sdn: add zone DHCP backend selector and subnet DHCP options Hannes Laimer
2026-11-12 12:41 ` [PATCH pve-manager v7 17/21] sdn: bring up the DHCP backends at boot before the guests start Hannes Laimer
2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 18/21] ve-config: sdn: add the ebpf dhcp backend Hannes Laimer
2026-11-12 12:41 ` [PATCH proxmox-ve-rs v7 19/21] sdn-dhcp: add the crate that runs the eBPF DHCP responder Hannes Laimer
2026-11-12 12:42 ` [PATCH pve-docs v7 20/21] sdn: zones: document the MTU taken from the underlay interface Hannes Laimer
2026-11-12 12:42 ` [PATCH pve-docs v7 21/21] sdn: dhcp: add eBPF backend section Hannes Laimer

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal