Architecture detection and platform-specific constants.
Provides runtime detection of CPU architecture and appropriate syscall numbers, libc paths, and other platform-specific values.
Architecture detection and platform-specific constants. Provides runtime detection of CPU architecture and appropriate syscall numbers, libc paths, and other platform-specific values.
BPF assembly utilities including label resolution.
Provides symbolic label support for BPF programs, eliminating the need for manual jump offset calculations.
Example: (require '[clj-ebpf.asm :as asm] '[clj-ebpf.dsl :as dsl])
(asm/assemble-with-labels [(dsl/mov :r0 0) (asm/jmp-imm :jeq :r1 0 :success) (dsl/mov :r0 -1) (asm/jmp :done) (asm/label :success) (dsl/mov :r0 1) (asm/label :done) (dsl/exit-insn)])
BPF assembly utilities including label resolution.
Provides symbolic label support for BPF programs, eliminating
the need for manual jump offset calculations.
Example:
(require '[clj-ebpf.asm :as asm]
'[clj-ebpf.dsl :as dsl])
(asm/assemble-with-labels
[(dsl/mov :r0 0)
(asm/jmp-imm :jeq :r1 0 :success)
(dsl/mov :r0 -1)
(asm/jmp :done)
(asm/label :success)
(dsl/mov :r0 1)
(asm/label :done)
(dsl/exit-insn)])BTF (BPF Type Format) parsing and type introspection
BTF (BPF Type Format) parsing and type introspection
Cgroup v2 BPF program attachment for container and process control
Cgroup v2 BPF program attachment for container and process control
BPF constants and enumerations from linux/bpf.h
BPF constants and enumerations from linux/bpf.h
Main API for clj-ebpf - eBPF programming in Clojure
Main API for clj-ebpf - eBPF programming in Clojure
Idiomatic Clojure DSL for BPF programming
Idiomatic Clojure DSL for BPF programming
ALU (Arithmetic Logic Unit) operations for BPF programs.
Provides 32-bit and 64-bit arithmetic operations:
ALU (Arithmetic Logic Unit) operations for BPF programs. Provides 32-bit and 64-bit arithmetic operations: - Arithmetic: add, sub, mul, div, mod, neg - Bitwise: and, or, xor, lsh, rsh, arsh - Data movement: mov - Endianness conversion: end-to-be, end-to-le
Atomic memory operations for BPF programs.
Provides thread-safe operations for concurrent access to shared memory, essential for implementing lock-free counters, statistics, and data structures.
Available operations:
Fetch variants return the original value:
All operations support 32-bit (:w) and 64-bit (:dw) sizes.
Example:
;; Increment counter atomically
(atomic-add :dw :r1 :r2 0) ; *r1 += r2
;; Fetch and add (returns old value in src register)
(atomic-fetch-add :dw :r1 :r2 0) ; r2 = fetch_add(*r1, r2)
Atomic memory operations for BPF programs. Provides thread-safe operations for concurrent access to shared memory, essential for implementing lock-free counters, statistics, and data structures. Available operations: - atomic-add : *dst += src - atomic-or : *dst |= src - atomic-and : *dst &= src - atomic-xor : *dst ^= src - atomic-xchg : src = xchg(*dst, src) - atomic-cmpxchg: r0 = cmpxchg(*dst, r0, src) Fetch variants return the original value: - atomic-fetch-add, atomic-fetch-or, atomic-fetch-and, atomic-fetch-xor All operations support 32-bit (:w) and 64-bit (:dw) sizes. Example: ```clojure ;; Increment counter atomically (atomic-add :dw :r1 :r2 0) ; *r1 += r2 ;; Fetch and add (returns old value in src register) (atomic-fetch-add :dw :r1 :r2 0) ; r2 = fetch_add(*r1, r2) ```
Core DSL module that re-exports all DSL functionality.
This namespace provides a unified API for BPF program construction:
(require '[clj-ebpf.dsl.core :as dsl])
;; Build a simple XDP program that drops all packets
(def drop-all
(dsl/assemble
[(dsl/mov :r0 1) ; XDP_DROP = 1
(dsl/exit-insn)]))
For more focused imports, use the submodules directly:
Core DSL module that re-exports all DSL functionality.
This namespace provides a unified API for BPF program construction:
```clojure
(require '[clj-ebpf.dsl.core :as dsl])
;; Build a simple XDP program that drops all packets
(def drop-all
(dsl/assemble
[(dsl/mov :r0 1) ; XDP_DROP = 1
(dsl/exit-insn)]))
```
For more focused imports, use the submodules directly:
- clj-ebpf.dsl.instructions - Low-level instruction encoding
- clj-ebpf.dsl.alu - Arithmetic operations
- clj-ebpf.dsl.mem - Memory operations
- clj-ebpf.dsl.jump - Control flow
- clj-ebpf.dsl.atomic - Atomic memory operations
- clj-ebpf.dsl.structs - Event structure definitions
- clj-ebpf.dsl.kprobe - Kprobe program helpersHigh-level Fentry/Fexit DSL for BPF programs.
Fentry (function entry) and Fexit (function exit) programs are modern BPF tracing programs that attach to kernel functions using BPF trampolines. They provide typed access to function arguments via BTF (BPF Type Format).
Advantages over kprobes:
Fentry/Fexit programs receive arguments directly:
Example: (deffentry-instructions trace-tcp-connect {:function "tcp_v4_connect" :args [:sk :addr :addr-len]} ;; sk is in r1, addr in r2, addr-len in r3 [])
High-level Fentry/Fexit DSL for BPF programs.
Fentry (function entry) and Fexit (function exit) programs are
modern BPF tracing programs that attach to kernel functions using
BPF trampolines. They provide typed access to function arguments
via BTF (BPF Type Format).
Advantages over kprobes:
- Lower overhead (no software breakpoints)
- Typed arguments via BTF
- Fexit can access both arguments and return value
- Better verifier support
Fentry/Fexit programs receive arguments directly:
- r1-r5: Function arguments (up to 5)
- Fexit: r0 contains return value at exit
Example:
(deffentry-instructions trace-tcp-connect
{:function "tcp_v4_connect"
:args [:sk :addr :addr-len]}
;; sk is in r1, addr in r2, addr-len in r3
[])Low-level BPF instruction encoding.
This namespace provides the fundamental BPF instruction encoding primitives. It defines:
BPF instructions are 64-bit: |immediate:32|offset:16|src_reg:4|dst_reg:4|opcode:8|
Low-level BPF instruction encoding. This namespace provides the fundamental BPF instruction encoding primitives. It defines: - Instruction format constants - Opcode construction - Single instruction encoding - Register definitions BPF instructions are 64-bit: |immediate:32|offset:16|src_reg:4|dst_reg:4|opcode:8|
Jump and control flow operations for BPF programs.
Provides:
Jump and control flow operations for BPF programs. Provides: - Conditional jumps (jeq, jne, jgt, jge, etc.) - Unconditional jumps (ja) - Function calls (call, call-helper) - Program exit (exit)
High-level kprobe definition macros for BPF programs.
Provides the defkprobe macro for defining kprobe handlers with automatic argument extraction and common setup patterns.
Example: (defkprobe tcp-connect :function "tcp_v4_connect" :args [sk] ; First function argument (concat (helper-get-current-pid-tgid) [(mov-reg :r6 :r0)] ; Save pid_tgid ;; ... rest of program [(exit-insn)]))
High-level kprobe definition macros for BPF programs.
Provides the defkprobe macro for defining kprobe handlers with
automatic argument extraction and common setup patterns.
Example:
(defkprobe tcp-connect
:function "tcp_v4_connect"
:args [sk] ; First function argument
(concat
(helper-get-current-pid-tgid)
[(mov-reg :r6 :r0)] ; Save pid_tgid
;; ... rest of program
[(exit-insn)]))High-level LSM (Linux Security Module) DSL for BPF programs.
LSM BPF programs can be attached to security hooks to enforce custom security policies. They run alongside the kernel's LSM infrastructure (SELinux, AppArmor, etc.).
Return values:
LSM programs use BTF for typed argument access.
Example: (deflsm-instructions block-exec {:hook "bprm_check_security" :args [:bprm]} ;; Block execution of specific programs [])
High-level LSM (Linux Security Module) DSL for BPF programs.
LSM BPF programs can be attached to security hooks to enforce
custom security policies. They run alongside the kernel's LSM
infrastructure (SELinux, AppArmor, etc.).
Return values:
- 0: Allow the operation
- <0: Deny with error code (e.g., -EPERM, -EACCES)
LSM programs use BTF for typed argument access.
Example:
(deflsm-instructions block-exec
{:hook "bprm_check_security"
:args [:bprm]}
;; Block execution of specific programs
[])Memory operations for BPF programs.
Provides:
Memory operations for BPF programs. Provides: - Load operations (ldx, ld) - Store operations (stx, st) - Atomic operations (atomic-add, atomic-xchg, etc.) - 64-bit immediate loads (lddw)
High-level Perf Event DSL for BPF programs.
Perf event programs are attached to hardware or software performance events and can sample CPU state, collect stack traces, and more.
Context: bpf_perf_event_data contains pt_regs and sample info.
Example: (defperf-event-instructions sample-cpu {:type :software :config :cpu-clock} [])
High-level Perf Event DSL for BPF programs.
Perf event programs are attached to hardware or software performance
events and can sample CPU state, collect stack traces, and more.
Context: bpf_perf_event_data contains pt_regs and sample info.
Example:
(defperf-event-instructions sample-cpu
{:type :software
:config :cpu-clock}
[])High-level Socket Filter DSL for BPF programs.
Socket filter programs can be attached to sockets to filter incoming packets. They run on each packet and decide whether to pass or drop it.
Return values:
0: Number of bytes to pass (use packet length to pass all)
Socket filters use __sk_buff as context (same as TC).
Example: (defsocket-filter-instructions allow-all {:default-action :accept} [])
High-level Socket Filter DSL for BPF programs.
Socket filter programs can be attached to sockets to filter
incoming packets. They run on each packet and decide whether
to pass or drop it.
Return values:
- 0: Drop the packet
- >0: Number of bytes to pass (use packet length to pass all)
Socket filters use __sk_buff as context (same as TC).
Example:
(defsocket-filter-instructions allow-all
{:default-action :accept}
[])Event structure definition DSL for BPF programs.
Provides macros and functions for defining event structures that can be used with ring buffers. The defevent macro creates structure definitions with automatic offset calculation and store function generation.
Example: (defevent ConnectionEvent [:timestamp :u64] [:pid :u32] [:saddr :u32] [:daddr :u32] [:sport :u16] [:dport :u16] [:protocol :u8] [:direction :u8] [:padding :u8 2] [:comm :char 16])
;; Get size: (event-size ConnectionEvent) => 44 ;; Get offset: (event-field-offset ConnectionEvent :pid) => 8 ;; Generate store: (store-event-field :r6 ConnectionEvent :pid :r7)
Event structure definition DSL for BPF programs.
Provides macros and functions for defining event structures that can
be used with ring buffers. The defevent macro creates structure definitions
with automatic offset calculation and store function generation.
Example:
(defevent ConnectionEvent
[:timestamp :u64]
[:pid :u32]
[:saddr :u32]
[:daddr :u32]
[:sport :u16]
[:dport :u16]
[:protocol :u8]
[:direction :u8]
[:padding :u8 2]
[:comm :char 16])
;; Get size: (event-size ConnectionEvent) => 44
;; Get offset: (event-field-offset ConnectionEvent :pid) => 8
;; Generate store: (store-event-field :r6 ConnectionEvent :pid :r7)High-level TC (Traffic Control) DSL for BPF programs.
TC programs run on the traffic control layer and can be attached to qdisc (queueing discipline) ingress/egress points. They operate on sk_buff and provide access to more metadata than XDP.
TC Actions:
TC programs use __sk_buff as context, which provides richer packet metadata than XDP's xdp_md.
Example: (deftc-instructions simple-filter {:default-action :ok} ;; All packets passed [])
High-level TC (Traffic Control) DSL for BPF programs.
TC programs run on the traffic control layer and can be attached to
qdisc (queueing discipline) ingress/egress points. They operate on
sk_buff and provide access to more metadata than XDP.
TC Actions:
- TC_ACT_OK (0): Continue processing
- TC_ACT_SHOT (2): Drop packet
- TC_ACT_UNSPEC (-1): Use default action
- TC_ACT_PIPE (3): Continue to next action
- TC_ACT_RECLASSIFY (1): Restart classification
- TC_ACT_REDIRECT (7): Redirect packet
TC programs use __sk_buff as context, which provides richer
packet metadata than XDP's xdp_md.
Example:
(deftc-instructions simple-filter
{:default-action :ok}
;; All packets passed
[])High-level tracepoint definition macros for BPF programs.
Provides the deftracepoint macro for defining tracepoint handlers with automatic field extraction from tracepoint format files.
Tracepoints are static kernel instrumentation points that provide a stable ABI, unlike kprobes which depend on function signatures.
Example: (deftracepoint-instructions sched-switch {:category "sched" :name "sched_switch" :fields [:prev_pid :next_pid]} (concat (helper-get-current-pid-tgid) [(mov-reg :r6 :r0)] [(exit-insn)]))
High-level tracepoint definition macros for BPF programs.
Provides the deftracepoint macro for defining tracepoint handlers with
automatic field extraction from tracepoint format files.
Tracepoints are static kernel instrumentation points that provide a
stable ABI, unlike kprobes which depend on function signatures.
Example:
(deftracepoint-instructions sched-switch
{:category "sched"
:name "sched_switch"
:fields [:prev_pid :next_pid]}
(concat
(helper-get-current-pid-tgid)
[(mov-reg :r6 :r0)]
[(exit-insn)]))High-level uprobe definition macros for BPF programs.
Provides the defuprobe macro for defining uprobe handlers that trace userspace functions with automatic argument extraction.
Uprobes are like kprobes but for userspace applications. They allow tracing functions in user binaries, shared libraries, and interpreters.
Example: (defuprobe-instructions malloc-tracer {:binary "/lib/x86_64-linux-gnu/libc.so.6" :function "malloc" :args [:r6]} ; size argument (concat (helper-get-current-pid-tgid) [(mov-reg :r7 :r0)] [(exit-insn)]))
High-level uprobe definition macros for BPF programs.
Provides the defuprobe macro for defining uprobe handlers that trace
userspace functions with automatic argument extraction.
Uprobes are like kprobes but for userspace applications. They allow
tracing functions in user binaries, shared libraries, and interpreters.
Example:
(defuprobe-instructions malloc-tracer
{:binary "/lib/x86_64-linux-gnu/libc.so.6"
:function "malloc"
:args [:r6]} ; size argument
(concat
(helper-get-current-pid-tgid)
[(mov-reg :r7 :r0)]
[(exit-insn)]))High-level XDP (eXpress Data Path) DSL for BPF programs.
XDP programs run at the earliest point in the network stack, before the kernel allocates an sk_buff. This makes them extremely fast for packet filtering, forwarding, and modification.
XDP Actions:
Example: (defxdp-instructions simple-drop {:action :drop} ;; All packets dropped [])
High-level XDP (eXpress Data Path) DSL for BPF programs.
XDP programs run at the earliest point in the network stack, before
the kernel allocates an sk_buff. This makes them extremely fast for
packet filtering, forwarding, and modification.
XDP Actions:
- XDP_ABORTED (0): Error, packet dropped
- XDP_DROP (1): Silently drop packet
- XDP_PASS (2): Pass to normal network stack
- XDP_TX (3): Transmit back out same interface
- XDP_REDIRECT(4): Redirect to another interface or CPU
Example:
(defxdp-instructions simple-drop
{:action :drop}
;; All packets dropped
[])ELF (Executable and Linkable Format) parser for BPF programs
ELF (Executable and Linkable Format) parser for BPF programs
Structured error handling for clj-ebpf.
Provides:
Structured error handling for clj-ebpf. Provides: - Typed exception hierarchy for BPF operations - Automatic retry for transient errors - Rich error context and diagnostics
Enhanced BPF event reading from ring buffers with memory mapping and epoll support
Enhanced BPF event reading from ring buffers with memory mapping and epoll support
Comprehensive examples demonstrating the clj-ebpf DSL for BPF programming.
These examples showcase various BPF program types and common patterns:
Each example is documented with its purpose, expected behavior, and the BPF concepts it demonstrates.
Comprehensive examples demonstrating the clj-ebpf DSL for BPF programming. These examples showcase various BPF program types and common patterns: - XDP (eXpress Data Path) programs for high-performance packet filtering - TC (Traffic Control) programs for packet classification - Packet parsing (Ethernet, IP, TCP/UDP headers) - BPF map operations (lookup, update, delete) - Tracing and debugging with helper functions - Statistics and counters Each example is documented with its purpose, expected behavior, and the BPF concepts it demonstrates.
BPF helper function metadata and utilities.
Helper metadata is loaded from resources/bpf-helpers.edn, which allows easy extension and customization without code changes.
Usage:
BPF helper function metadata and utilities. Helper metadata is loaded from resources/bpf-helpers.edn, which allows easy extension and customization without code changes. Usage: - (get-helper-info :map-lookup-elem) - Get metadata for a helper - (get-helper-id :ktime-get-ns) - Get helper function ID - (helpers-by-category :network) - Get all network helpers - (available-helpers :xdp "5.8") - Get helpers for program type and kernel
Low-level memory management using Panama FFI.
This namespace provides the foundational memory primitives used throughout clj-ebpf. It wraps Java's Foreign Function & Memory API (Panama) to provide a Clojure-friendly interface for:
INTERNAL: This namespace is for internal use only. Public APIs should use clj-ebpf.utils for memory operations.
Low-level memory management using Panama FFI. This namespace provides the foundational memory primitives used throughout clj-ebpf. It wraps Java's Foreign Function & Memory API (Panama) to provide a Clojure-friendly interface for: - Memory allocation and deallocation - Reading and writing primitive types - Memory segment manipulation - Buffer management for BPF operations INTERNAL: This namespace is for internal use only. Public APIs should use clj-ebpf.utils for memory operations.
LSM (Linux Security Modules) BPF hook support for security policies
LSM (Linux Security Modules) BPF hook support for security policies
BPF map operations and abstractions
BPF map operations and abstractions
BPF program instruction helpers for map operations.
These functions generate instruction sequences for common map operations within BPF programs. They handle the setup of map FD loading, pointer construction, and helper calls.
Unlike the functions in clj-ebpf.maps (which operate on maps from userspace), these helpers generate BPF bytecode for in-program map access.
Usage example: (concat ;; ... set up key on stack at offset -16 ... (build-map-lookup my-map-fd -16) ;; r0 now contains pointer to value or NULL [(asm/jmp-imm :jeq :r0 0 :not-found)] ;; ... process value ... )
BPF program instruction helpers for map operations.
These functions generate instruction sequences for common map operations
within BPF programs. They handle the setup of map FD loading, pointer
construction, and helper calls.
Unlike the functions in clj-ebpf.maps (which operate on maps from userspace),
these helpers generate BPF bytecode for in-program map access.
Usage example:
(concat
;; ... set up key on stack at offset -16 ...
(build-map-lookup my-map-fd -16)
;; r0 now contains pointer to value or NULL
[(asm/jmp-imm :jeq :r0 0 :not-found)]
;; ... process value ...
)Memory operation helpers for BPF programs.
Provides helper functions for common memory operations on the BPF stack:
These operations require multiple BPF instructions and are error-prone when done manually. These helpers generate correct, efficient sequences.
Usage: (require '[clj-ebpf.memory :as mem])
;; Zero 40 bytes at stack[-64] (mem/build-zero-bytes -64 40)
;; Copy 16 bytes from stack[-32] to stack[-64] (mem/build-memcpy-stack -32 -64 16)
;; Set 16 bytes to 0xFF (mem/build-memset -16 0xFF 16)
Memory operation helpers for BPF programs. Provides helper functions for common memory operations on the BPF stack: - Zeroing memory regions - Copying data between stack locations - Setting memory to specific values These operations require multiple BPF instructions and are error-prone when done manually. These helpers generate correct, efficient sequences. Usage: (require '[clj-ebpf.memory :as mem]) ;; Zero 40 bytes at stack[-64] (mem/build-zero-bytes -64 40) ;; Copy 16 bytes from stack[-32] to stack[-64] (mem/build-memcpy-stack -32 -64 16) ;; Set 16 bytes to 0xFF (mem/build-memset -16 0xFF 16)
Networking helpers for eBPF programs.
Provides reusable primitives for packet parsing, manipulation, and checksum operations for load balancers, NAT gateways, firewalls, and other networking applications.
Networking helpers for eBPF programs. Provides reusable primitives for packet parsing, manipulation, and checksum operations for load balancers, NAT gateways, firewalls, and other networking applications.
Packet bounds checking helpers for BPF programs.
These helpers generate BPF verifier-safe packet bounds checks. Every XDP/TC program must check packet bounds before accessing data.
The BPF verifier requires specific instruction patterns to mark memory ranges as safe. These helpers generate compliant patterns.
Usage: (require '[clj-ebpf.net.bounds :as bounds])
;; Check if we can read 14 bytes (Ethernet header) (bounds/build-bounds-check :r6 :r7 0 14 10)
;; With label-based jumps (bounds/build-bounds-check-label :r6 :r7 0 14 :drop)
Packet bounds checking helpers for BPF programs. These helpers generate BPF verifier-safe packet bounds checks. Every XDP/TC program must check packet bounds before accessing data. The BPF verifier requires specific instruction patterns to mark memory ranges as safe. These helpers generate compliant patterns. Usage: (require '[clj-ebpf.net.bounds :as bounds]) ;; Check if we can read 14 bytes (Ethernet header) (bounds/build-bounds-check :r6 :r7 0 14 10) ;; With label-based jumps (bounds/build-bounds-check-label :r6 :r7 0 14 :drop)
Checksum calculation helpers for eBPF programs.
These helpers use BPF kernel helper functions for efficient checksum updates. Most are designed for TC/SKB programs.
Checksum calculation helpers for eBPF programs. These helpers use BPF kernel helper functions for efficient checksum updates. Most are designed for TC/SKB programs.
Ethernet frame parsing and manipulation helpers for eBPF programs.
Ethernet frame parsing and manipulation helpers for eBPF programs.
IPv4 packet parsing and manipulation helpers for eBPF programs.
IPv4 packet parsing and manipulation helpers for eBPF programs.
IPv6 address loading helpers for packet parsing.
IPv6 addresses are 16 bytes and require multiple load/store operations. These helpers simplify loading IPv6 addresses from packets to stack and provide a 'unified' format for dual-stack (IPv4/IPv6) handling.
Usage: (require '[clj-ebpf.net.ipv6 :as ipv6])
;; Load IPv6 source address from packet to stack (ipv6/build-load-ipv6-address :r9 ipv6/IPV6-OFF-SRC -84)
;; Load IPv4 address in unified 16-byte format (ipv6/build-load-ipv4-unified :r9 12 -84)
IPv6 address loading helpers for packet parsing. IPv6 addresses are 16 bytes and require multiple load/store operations. These helpers simplify loading IPv6 addresses from packets to stack and provide a 'unified' format for dual-stack (IPv4/IPv6) handling. Usage: (require '[clj-ebpf.net.ipv6 :as ipv6]) ;; Load IPv6 source address from packet to stack (ipv6/build-load-ipv6-address :r9 ipv6/IPV6-OFF-SRC -84) ;; Load IPv4 address in unified 16-byte format (ipv6/build-load-ipv4-unified :r9 12 -84)
NAT (Network Address Translation) primitives for eBPF programs.
Provides high-level operations for DNAT (Destination NAT) and SNAT (Source NAT) that combine packet modification with checksum updates.
These helpers are primarily designed for TC/SKB programs that have access to kernel checksum helper functions.
NAT (Network Address Translation) primitives for eBPF programs. Provides high-level operations for DNAT (Destination NAT) and SNAT (Source NAT) that combine packet modification with checksum updates. These helpers are primarily designed for TC/SKB programs that have access to kernel checksum helper functions.
TCP packet parsing and manipulation helpers for eBPF programs.
TCP packet parsing and manipulation helpers for eBPF programs.
UDP packet parsing and manipulation helpers for eBPF programs.
UDP packet parsing and manipulation helpers for eBPF programs.
Perf event buffer support for BPF event streaming
Perf event buffer support for BPF event streaming
BPF program loading and attachment
BPF program loading and attachment
Token bucket rate limiting helpers for BPF programs.
Provides comprehensive token bucket rate limiting implementation for XDP/TC programs. Common use cases include:
Token Bucket Algorithm:
Data Structures:
Usage: (require '[clj-ebpf.rate-limit :as rl])
;; Build rate limit check (rl/build-rate-limit-check config-map-fd 0 bucket-map-fd -16 -48 :pass :drop)
Token bucket rate limiting helpers for BPF programs.
Provides comprehensive token bucket rate limiting implementation
for XDP/TC programs. Common use cases include:
- Source IP rate limiting (DDoS protection)
- Backend rate limiting (overload protection)
- API rate limiting
- Connection rate limiting
Token Bucket Algorithm:
1. Each bucket has: tokens (current count), last_update (timestamp)
2. Config has: rate (tokens per second), burst (max tokens)
3. On each packet:
a. Calculate elapsed time since last_update
b. Add new tokens: elapsed_ns * rate / 1e9
c. Cap tokens at burst
d. If tokens >= 1, consume and allow
e. Else, rate limit (drop)
Data Structures:
- Config map (array): 16 bytes per entry (rate: 8, burst: 8)
- Bucket map (LRU hash): 16 bytes per entry (tokens: 8, last_update: 8)
- Token scale: 1000 (for sub-second precision)
Usage:
(require '[clj-ebpf.rate-limit :as rl])
;; Build rate limit check
(rl/build-rate-limit-check
config-map-fd 0 bucket-map-fd -16 -48 :pass :drop)Idiomatic Clojure references for BPF data structures.
This namespace provides Clojure reference types that implement standard protocols (IDeref, IBlockingDeref, IAtom, ITransientCollection), enabling natural use of @, deref, reset!, swap!, and conj! with BPF maps.
== Read-Only References ==
RingBufRef - Blocking reads from ring buffers @ref ; blocks until event available (deref ref 1000 nil) ; 1s timeout
QueueRef/StackRef - Blocking pops from queue/stack maps @ref ; blocks until item available
MapWatcher - Watch for a key to appear/change @ref ; blocks until key exists
== Writable References ==
MapEntryRef - Atom-like access to map entries @ref ; read value (reset! ref val) ; write value (swap! ref inc) ; read-modify-write
QueueWriter/StackWriter - Push to queues/stacks (conj! ref val) ; push value @ref ; peek (non-blocking)
QueueChannel/StackChannel - Bidirectional access (conj! ref val) ; push @ref ; blocking pop
Idiomatic Clojure references for BPF data structures. This namespace provides Clojure reference types that implement standard protocols (IDeref, IBlockingDeref, IAtom, ITransientCollection), enabling natural use of @, deref, reset!, swap!, and conj! with BPF maps. == Read-Only References == 1. RingBufRef - Blocking reads from ring buffers @ref ; blocks until event available (deref ref 1000 nil) ; 1s timeout 2. QueueRef/StackRef - Blocking pops from queue/stack maps @ref ; blocks until item available 3. MapWatcher - Watch for a key to appear/change @ref ; blocks until key exists == Writable References == 4. MapEntryRef - Atom-like access to map entries @ref ; read value (reset! ref val) ; write value (swap! ref inc) ; read-modify-write 5. QueueWriter/StackWriter - Push to queues/stacks (conj! ref val) ; push value @ref ; peek (non-blocking) 6. QueueChannel/StackChannel - Bidirectional access (conj! ref val) ; push @ref ; blocking pop
CO-RE (Compile Once - Run Everywhere) relocation support.
This namespace provides functionality for BPF CO-RE relocations, enabling BPF programs to be portable across different kernel versions by using BTF information to relocate field accesses and type information at load time.
CO-RE relocations allow BPF programs to:
Key concepts:
CO-RE (Compile Once - Run Everywhere) relocation support. This namespace provides functionality for BPF CO-RE relocations, enabling BPF programs to be portable across different kernel versions by using BTF information to relocate field accesses and type information at load time. CO-RE relocations allow BPF programs to: - Access struct fields regardless of their offset in different kernel versions - Check for field/type/enum existence at load time - Get accurate field sizes and types - Handle bitfield operations correctly - Support both local and target BTF type IDs Key concepts: - Field relocations: Adjust field offsets, sizes, existence - Type relocations: Check type existence, size, matches - Enum relocations: Get enum values, check existence - BTF-based resolution: Use kernel BTF to resolve relocations
Ring buffer helpers for BPF event streaming.
Ring buffers are the modern way to stream events from BPF programs to userspace. They're more efficient than perf buffers and support variable-sized records.
Usage: (require '[clj-ebpf.ringbuf :as rb])
;; Reserve space in ring buffer (rb/build-ringbuf-reserve event-ringbuf-fd 64) ;; r0 = pointer to reserved space, or NULL on failure
;; After writing data, submit (rb/build-ringbuf-submit :r9)
;; Or discard if not needed (rb/build-ringbuf-discard :r9)
Ring buffer helpers for BPF event streaming. Ring buffers are the modern way to stream events from BPF programs to userspace. They're more efficient than perf buffers and support variable-sized records. Usage: (require '[clj-ebpf.ringbuf :as rb]) ;; Reserve space in ring buffer (rb/build-ringbuf-reserve event-ringbuf-fd 64) ;; r0 = pointer to reserved space, or NULL on failure ;; After writing data, submit (rb/build-ringbuf-submit :r9) ;; Or discard if not needed (rb/build-ringbuf-discard :r9)
Low-level BPF syscall interface using Java Panama FFI (Java 25+)
Low-level BPF syscall interface using Java Panama FFI (Java 25+)
TC (Traffic Control) support for BPF packet filtering and QoS
TC (Traffic Control) support for BPF packet filtering and QoS
Time and random number helpers for BPF programs.
These helpers provide access to kernel time and pseudo-random numbers. Common uses include:
Usage: (require '[clj-ebpf.time :as t])
;; Get current kernel time in nanoseconds (t/build-ktime-get-ns)
;; Get random number (t/build-get-prandom-u32)
;; Get random in range [0, 99] (t/build-random-mod 100)
Time and random number helpers for BPF programs. These helpers provide access to kernel time and pseudo-random numbers. Common uses include: - Connection tracking timestamps (created_at, last_seen) - Rate limiting (token bucket timing) - Load balancing (weighted random selection) - Metrics (latency measurement) Usage: (require '[clj-ebpf.time :as t]) ;; Get current kernel time in nanoseconds (t/build-ktime-get-ns) ;; Get random number (t/build-get-prandom-u32) ;; Get random in range [0, 99] (t/build-random-mod 100)
Utility functions for BPF programming using Panama FFI
Utility functions for BPF programming using Panama FFI
XDP (eXpress Data Path) support for high-performance packet processing
XDP (eXpress Data Path) support for high-performance packet processing
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |