all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Hannes Laimer <h.laimer@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH pve-network v7 08/21] bpf: add the build, the package and a native harness for BPF programs
Date: Thu, 12 Nov 2026 13:41:48 +0100	[thread overview]
Message-ID: <20261112124201.2844423-9-h.laimer@proxmox.com> (raw)
In-Reply-To: <20261112124201.2844423-1-h.laimer@proxmox.com>

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





  parent reply	other threads:[~2026-11-12 12:45 UTC|newest]

Thread overview: 22+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 ` Hannes Laimer [this message]
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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261112124201.2844423-9-h.laimer@proxmox.com \
    --to=h.laimer@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal