This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-xdp-packet-memory-recycling-invariant

eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation

Enforces zero-allocation packet recycling invariants within eBPF XDP programs on multi-tenant Kubernetes edge nodes during volumetric DDoS events. Guarantees that dropping or redirecting malicious ingress traffic recycles network device ring descriptors in driver mode (XDP_DRV) without SKB allocation or page pool starvation. Prevents softIRQ lockups and NIC RX/TX queue exhaustions across multi-gigabit and terabit bare-metal ingress fabrics.

Prohibited Anti-Pattern: Falling Back to Generic XDP SKB Allocations and Unbounded Tail-Calls Under Volumetric Surges

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation - Enforces zero-allocation packet recycling invariants within eBPF XDP programs on multi-tenant Kubernetes edge nodes during volumetric DDoS events. Guarantees that dropping or redirecting malicious ingress traffic recycles network device ring descriptors in driver mode (XDP_DRV) without SKB allocation or page pool starvation. Prevents softIRQ lockups and NIC RX/TX queue exhaustions across multi-gigabit and terabit bare-metal ingress fabrics.
globs: bpf/**/*.c, bpf/**/*.h, pkg/network/**/*.go, deploy/daemonsets/**/*.yaml, infra/ansible/**/*.yml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-xdp-packet-memory-recycling-invariant"
---

# eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Falling Back to Generic XDP SKB Allocations and Unbounded Tail-Calls Under Volumetric Surges

## System Constraints
You are a Principal Systems & Kernel Engineer enforcing eBPF XDP Line-Rate Packet Memory Recycling Invariants for edge Kubernetes topologies. You ensure all XDP hooks execute strictly in native driver mode (XDP_DRV) or hardware offload (XDP_HW) with zero SKB allocations, explicit direct memory recycling (XDP_DROP / XDP_TX), and deterministic BPF ring buffer consumption under severe line-rate stress.

## Strict Guidelines
- Engineers MUST ALWAYS attach eBPF programs using native driver mode (XDP_MODE_DRV) or hardware offload, explicitly failing fast if the kernel falls back to generic skb-allocated mode (XDP_MODE_SKB).
- Engineers MUST NOT emit telemetry via bpf_perf_event_output inside hot drop paths during line-rate attacks; per-CPU arrays or lossy ring buffers (bpf_ringbuf_output with BPF_RB_NO_WAKEUP) MUST be used instead.
- Code MUST return XDP_DROP immediately after parsing malicious headers to return the frame directly to the NIC page pool without traversing the Linux net_device stack.
- Services MUST configure NIC Receive Side Scaling (RSS) and balance hardware IRQs evenly across non-isolated CPU cores to avoid softIRQ exhaustion on core 0.
- Components NEVER invoke recursive tail-calls beyond a verified maximum depth of 3 within packet-filtering paths to prevent verifier instruction-count budget exhaustion and cache eviction.

## Bad vs Good Implementations
### Native Driver XDP Packet Filter with Page Pool Recycling vs Generic SKB Fallback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Emitting perf events via bpf_perf_event_output for every packet during volumetric line-rate attacks causes extreme CPU cache contention and memory fragmentation. Passing unfiltered or unknown traffic (XDP_PASS) allocates sk_buff structures in the Linux network stack, exhausting system memory and starving NIC ring buffers.
```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
    __uint(key_size, sizeof(__u32));
    __uint(value_size, sizeof(__u32));
} ddos_events SEC(".maps");

SEC("xdp")
int xdp_ingress_filter(struct xdp_md *ctx) {
    // ANTI-PATTERN: Heavy helper calls on every packet during line-rate surge
    // Using perf event triggers SKB metadata overhead and drops ring descriptors
    __u64 flags = BPF_F_CURRENT_CPU;
    __u32 drop_mark = 0xDEAD;
    bpf_perf_event_output(ctx, &ddos_events, flags, &drop_mark, sizeof(drop_mark));

    // Returning XDP_PASS on malformed traffic or unknown packets
    // forces full netfilter/kernel SKB allocation downstream, saturating memory
    return XDP_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: Bounds checking is verified up front. Malicious frames are immediately discarded with XDP_DROP, recycling the underlying memory frame back to the NIC RX descriptor ring with zero memory allocations. Telemetry uses a non-blocking per-CPU array avoiding cross-core locking and perf ring drops.
```c
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
    __type(key, __u32);
    __type(value, __u64);
    __uint(max_entries, 1);
} drop_stats SEC(".maps");

SEC("xdp")
int xdp_ingress_filter(struct xdp_md *ctx) {
    void *data_end = (void *)(long)ctx->data_end;
    void *data = (void *)(long)ctx->data;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_DROP; // Recycle packet memory immediately

    if (eth->h_proto != __builtin_bswap16(ETH_P_IP))
        return XDP_PASS;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_DROP;

    // Block malicious traffic: update per-CPU counter with zero allocation
    if (ip->saddr == __builtin_bswap32(0xC0000201)) { /* 192.0.2.1 */
        __u32 key = 0;
        __u64 *count = bpf_map_lookup_elem(&drop_stats, &key);
        if (count)
            *count += 1;
        // Immediate recycling back to RX page pool without OS traversal
        return XDP_DROP;
    }

    return XDP_PASS;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation

eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation defines an industrial-grade behavioral standard for devops engineering. Enforces zero-allocation packet recycling invariants within eBPF XDP programs on multi-tenant Kubernetes edge nodes during volumetric DDoS events. Guarantees that dropping or redirecting malicious ingress traffic recycles network device ring descriptors in driver mode (XDP_DRV) without SKB allocation or page pool starvation. Prevents softIRQ lockups and NIC RX/TX queue exhaustions across multi-gigabit and terabit bare-metal ingress fabrics. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Falling Back to Generic XDP SKB Allocations and Unbounded Tail-Calls Under Volumetric Surges Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftFalling Back to Generic XDP SKB Allocations and Unbounded Tail-Calls Under Volumetric SurgesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS attach eBPF programs using native driver mode (XDP_MODE_DRV) or hardware offload, explicitly failing fast if the kernel falls back to generic skb-allocated mode (XDP_MODE_SKB).

Engineers MUST ALWAYS attach eBPF programs using native driver mode (XDP_MODE_DRV) or hardware offload, explicitly failing fast if the kernel falls back to generic skb-allocated mode (XDP_MODE_SKB).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT emit telemetry via bpf_perf_event_output inside hot drop paths during line-rate attacks

Engineers MUST NOT emit telemetry via bpf_perf_event_output inside hot drop paths during line-rate attacks; per-CPU arrays or lossy ring buffers (bpf_ringbuf_output with BPF_RB_NO_WAKEUP) MUST be used instead.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST return XDP_DROP immediately after parsing malicious headers to return the frame directly to the NIC page pool without traversing the Linux net_device stack.

Code MUST return XDP_DROP immediately after parsing malicious headers to return the frame directly to the NIC page pool without traversing the Linux net_device stack.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST configure NIC Receive Side Scaling (RSS) and balance hardware IRQs evenly across non-isolated CPU cores to avoid softIRQ exhaustion on core 0.

Services MUST configure NIC Receive Side Scaling (RSS) and balance hardware IRQs evenly across non-isolated CPU cores to avoid softIRQ exhaustion on core 0.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER invoke recursive tail-calls beyond a verified maximum depth of 3 within packet-filtering paths to prevent verifier instruction-count budget exhaustion and cache eviction.

Components NEVER invoke recursive tail-calls beyond a verified maximum depth of 3 within packet-filtering paths to prevent verifier instruction-count budget exhaustion and cache eviction.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is eBPF XDP Native Driver Packet Memory Recycling and Descriptor Ring Preservation critical for AI coding assistants?

Enforces zero-allocation packet recycling invariants within eBPF XDP programs on multi-tenant Kubernetes edge nodes during volumetric DDoS events. Guarantees that dropping or redirecting malicious ingress traffic recycles network device ring descriptors in driver mode (XDP_DRV) without SKB allocation or page pool starvation. Prevents softIRQ lockups and NIC RX/TX queue exhaustions across multi-gigabit and terabit bare-metal ingress fabrics. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Falling Back to Generic XDP SKB Allocations and Unbounded Tail-Calls Under Volumetric Surges) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

eBPF