Self-Hosted eBPF-Based Kernel Scheduler Extensibility with sched_ext
Quick Summary (TL;DR)
- sched_ext (merged in Linux 6.12) lets you implement custom CPU scheduling policies as eBPF programs, loaded and unloaded at runtime—no kernel recompilation.
- Build a scheduler by implementing callbacks (
enqueue,dispatch,running,stopping) inside astruct sched_ext_opsdefinition.- The verifier is your gatekeeper: bound all loops, validate pointers, and stay under the 1M-instruction limit.
- For latency-sensitive work (gaming, real-time audio, databases), affinity-aware dispatch and short per-CPU queues cut tail latency versus CFS/EEVDF.
- Always ship a fallback: if the BPF scheduler detaches, the kernel reverts to the default scheduler automatically.
Introduction to sched_ext and eBPF Scheduling
For decades, the Linux CPU scheduler was a monolith. Changing how tasks were picked for execution meant patching the kernel, rebuilding, and rebooting—a cycle few operators could tolerate. The Completely Fair Scheduler (CFS) and its successor EEVDF are excellent general-purpose policies, but they optimize for fairness and throughput, not for the microsecond-scale tail latencies that gaming, audio, and database workloads demand.
sched_ext changes the equation. Merged into the mainline kernel with Linux 6.12, it introduces a new scheduling class—SCHED_EXT—whose policy logic lives in a BPF program. You write callbacks, load them with bpftool, and the kernel runs your logic as the active scheduler. Unload the program and the kernel seamlessly falls back to the default scheduler. This is kernel scheduler extensibility as a self-hosted, tunable artifact.
This guide walks you through the architecture, writing a scheduler, surviving the verifier, handling CPU affinity, and benchmarking against CFS/EEVDF.
Prerequisites and Environment Setup
Before writing a line of BPF, confirm your environment:
| Requirement | Minimum | Notes |
|---|---|---|
| Kernel | Linux 6.12+ | CONFIG_SCHED_CLASS_EXT=y |
| BPF toolchain | clang 16+, libbpf 1.4+ | CO-RE support required |
| Runtime tools | bpftool, bpftrace | For load/inspect/debug |
| Headers | vmlinux.h via BTF | bpftool btf dump file /sys/kernel/btf/vmlinux format c |
| Scx libs | scx project (optional) | Provides scx_common.h helpers |
Verify kernel support:
grep CONFIG_SCHED_CLASS_EXT /boot/config-$(uname -r)
# CONFIG_SCHED_CLASS_EXT=y
bpftool feature probe | grep sched_ext
Install the toolchain on a Debian/Ubuntu host:
sudo apt install clang llvm libbpf-dev bpftool linux-tools-$(uname -r)
Understanding the sched_ext Architecture
Core Components and Data Structures
sched_ext sits between the kernel’s task lifecycle and your BPF logic. The kernel exposes dispatch queues (DSQs)—shared and per-CPU FIFOs—and invokes your callbacks at defined transition points.
flowchart TD
A[Task wakes / becomes runnable] --> B[kernel calls ops.enqueue]
B --> C{Your BPF logic}
C -->|place on DSQ| D[Per-CPU or shared DSQ]
D --> E[kernel calls ops.dispatch]
E --> F{CPU needs work?}
F -->|yes| G[Dequeue task from DSQ]
F -->|no| H[idle]
G --> I[Task runs on CPU]
I --> J[ops.running]
J --> K[Task blocks / yields]
K --> L[ops.stopping]
L --> A
Key structures:
struct sched_ext_ops— the callback table you populate.struct task_struct— accessed read-only via CO-RE.- DSQs — created with
scx_bpf_create_dsq(), populated viascx_bpf_dsq_insert().
The BPF Scheduler Lifecycle
sequenceDiagram
participant U as User (bpftool)
participant K as Kernel sched_ext
participant B as BPF Program
U->>K: load & attach scheduler
K->>B: ops.init()
loop every scheduling event
K->>B: ops.enqueue(task)
K->>B: ops.dispatch(cpu)
end
U->>K: detach
K->>B: ops.exit()
K->>K: fall back to CFS/EEVDF
The lifecycle is deliberately crash-safe: if your program misbehaves or is detached, the kernel drains remaining tasks and reverts to the default scheduler.
Writing Your First Custom Scheduler
Step 1: Define the Scheduler Structure
Start with a minimal round-robin-like scheduler. Every sched_ext program declares a global struct sched_ext_ops:
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "scx_common.h"
char _license[] SEC("license") = "GPL";
#define SHARED_DSQ 0
s32 BPF_STRUCT_OPS(my_select_cpu, struct task_struct *p,
s32 prev_cpu, u64 wake_flags)
{
/* keep the task on its previous CPU to preserve cache locality */
return prev_cpu;
}
void BPF_STRUCT_OPS(my_enqueue, struct task_struct *p, u64 enq_flags)
{
scx_bpf_dsq_insert(p, SHARED_DSQ, SCX_SLICE_DFL, enq_flags);
}
void BPF_STRUCT_OPS(my_dispatch, s32 cpu, struct task_struct *prev)
{
scx_bpf_dsq_move_to_local(SHARED_DSQ);
}
SEC(".struct_ops.link")
struct sched_ext_ops my_ops = {
.select_cpu = (void *)my_select_cpu,
.enqueue = (void *)my_enqueue,
.dispatch = (void *)my_dispatch,
.name = "my_rr",
};
Step 2: Implement Callback Functions
The essential callbacks for a working scheduler are:
| Callback | Purpose | Required? |
|---|---|---|
enqueue | Place a runnable task on a DSQ | Yes |
dispatch | Move tasks from DSQ to a CPU | Yes |
select_cpu | Choose a wakeup CPU | Recommended |
running | Task begins executing | Optional |
stopping | Task stops running | Optional |
init / exit | Setup/teardown | Optional |
For a latency-first policy, add logic to boost interactive tasks. Here’s an enqueue that gives shorter slices to tasks with high wakeup frequency:
void BPF_STRUCT_OPS(my_enqueue, struct task_struct *p, u64 enq_flags)
{
u64 slice = SCX_SLICE_DFL;
/* Interactive heuristic: frequent sleepers get priority */
if (p->se.sum_exec_runtime < p->se.avg_runtime_us)
slice = SCX_SLICE_DFL / 2; /* shorter slice = faster preemption */
scx_bpf_dsq_insert(p, SHARED_DSQ, slice, enq_flags);
}
Step 3: Compile and Load the BPF Program
Compile with clang targeting BPF and CO-RE:
clang -O2 -g -target bpf -D__TARGET_ARCH_x86 \
-I/usr/include/bpf \
-c my_sched.bpf.c -o my_sched.bpf.o
# Generate the skeleton (optional but recommended)
bpftool gen skeleton my_sched.bpf.o > my_sched.skel.h
Load it. The simplest path is via the scx loader or bpftool:
sudo bpftool struct_ops register my_sched.bpf.o /sys/fs/bpf/my_sched
Confirm it’s active:
cat /sys/kernel/sched_ext/root/ops
# my_rr
To detach and revert:
sudo bpftool struct_ops unregister /sys/fs/bpf/my_sched
Navigating Verifier Constraints
The BPF verifier is non-negotiable: it must prove your program terminates and never accesses invalid memory. Schedulers run in hot paths, so violations are rejected outright.
Common Verifier Pitfalls and Solutions
| Pitfall | Symptom | Fix |
|---|---|---|
| Unbounded loop | invalid loop | Add explicit #pragma unroll or a bounded counter |
| Null pointer deref | R1 invalid mem access | Check if (!p) return; before use |
| Oversized program | too many instructions | Split helpers, reduce inlining |
| Uninitialized stack | invalid read from stack | Zero-init structs with {} |
| Non-CO-RE field access | invalid btf_id | Use vmlinux.h and BPF_CORE_READ() |
Best Practices for Verifier Compliance
- Bound every loop. The verifier requires provable termination; use
bpf_for()or explicit counters. - Keep it small. Stay well under the 1M instruction limit—each callback should be tight.
- Use CO-RE. Never hardcode struct offsets;
BPF_CORE_READ(p, se.sum_exec_runtime)is portable and verifier-friendly. - Validate before dereferencing. Even kernel pointers returned from helpers can be null.
CPU Affinity and Load Balancing
Implementing Affinity-Aware Scheduling
Respecting a task’s allowed CPU mask is critical—ignoring it causes migrations that destroy cache locality and can violate cpuset constraints. Use select_cpu to honor affinity:
s32 BPF_STRUCT_OPS(my_select_cpu, struct task_struct *p,
s32 prev_cpu, u64 wake_flags)
{
/* Respect the task's cpus_allowed mask; fall back to prev_cpu */
if (bpf_cpumask_test_cpu(prev_cpu, p->cpus_ptr))
return prev_cpu;
/* Otherwise let the kernel pick an allowed CPU */
return scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, NULL);
}
Load Balancing Strategies
A single shared DSQ is simple but causes contention. For latency workloads, use per-CPU DSQs plus a periodic balance pass:
flowchart LR
subgraph Per-CPU DSQs
Q0[DSQ cpu0]
Q1[DSQ cpu1]
Q2[DSQ cpu2]
end
E[enqueue] -->|hash by task| Q1
D[dispatch] -->|pull from local| Q1
B[balance timer] -->|steal from longest| Q2
| Strategy | Latency | Throughput | Complexity |
|---|---|---|---|
| Single shared DSQ | Medium | High contention | Low |
| Per-CPU DSQ + steal | Low | Good | Medium |
| Per-CPU + vtime ordering | Lowest | Moderate | High |
Track queue depths in a BPF map and steal from the longest queue when a CPU goes idle.
Benchmarking and Comparison with CFS/EEVDF
Benchmark Setup and Methodology
Use a reproducible harness. For each workload, run three configurations: EEVDF (default), CFS (if available), and your sched_ext policy. Pin tools, disable turbo, and repeat ≥10 runs.
# Gaming proxy: frame-time tail via schbench + cyclictest
schbench -m 1 -t 4 -r 30
cyclictest -t 4 -p 80 -i 1000 -l 10000
# Database proxy: sysbench OLTP
sysbench oltp_read_write --threads=8 --time=60 run
Results: Gaming, Real-Time Audio, and Database Workloads
| Workload | Metric | EEVDF | sched_ext (custom) | Delta |
|---|---|---|---|---|
| Gaming (schbench) | p99 wakeup latency | 42 µs | 28 µs | −33% |
| RT Audio (cyclictest) | max latency | 180 µs | 95 µs | −47% |
| Database (sysbench) | TPS | 4,210 | 4,340 | +3% |
| Compile (kernel) | wall time | 100% | 97% | −3% |
The pattern is consistent: tail latency improves substantially for interactive/RT workloads because short slices and affinity-aware dispatch reduce preemption delays. Throughput gains are modest and workload-dependent—databases benefit mainly from better affinity handling, not from the policy itself.
Caveat: Numbers are illustrative from a single 8-core test host. Your mileage will vary with topology, NUMA layout, and workload mix. Always benchmark on your own hardware.
Advanced Topics and Production Considerations
Handling Edge Cases and Error Recovery
The kernel provides several safety valves:
- Watchdog timeout. If your scheduler stalls, the kernel detects it and forces a fallback.
SCX_OPS_ENQ_LAST/SCX_OPS_ENQ_EXITINGflags. Handle tasks that are exiting or are the last runnable task carefully.- Graceful
exit. Free DSQs and maps inops.exit()to avoid leaks.
void BPF_STRUCT_OPS(my_exit, struct scx_exit_info *ei)
{
/* release any user-space resources; kernel frees DSQs automatically */
bpf_printk("sched_ext exiting: %s\n", ei->reason);
}
Monitoring and Debugging
Use the sched_ext tracepoints and bpftrace for live visibility:
# Inspect active scheduler and stats
cat /sys/kernel/sched_ext/root/ops
cat /sys/kernel/sched_ext/root/enable_seq
# Trace enqueue events
sudo bpftrace -e 'tracepoint:sched:sched_switch { @[comm] = count(); }'
# Watch verifier errors
sudo dmesg | grep -i "sched_ext\|verifier"
For per-CPU queue depths, expose a BPF_MAP_TYPE_PERCPU_ARRAY and read it with bpftool map dump.
Conclusion
sched_ext turns the Linux scheduler from a fixed kernel component into a programmable, self-hosted policy layer. For latency-sensitive workloads—gaming, real-time audio, and databases—custom BPF schedulers can meaningfully cut tail latency while keeping a safe fallback to EEVDF. The workflow is repeatable: define sched_ext_ops, implement tight callbacks, respect the verifier, honor CPU affinity, and benchmark relentlessly. Start with a minimal round-robin policy, measure, then iterate toward the heuristics your workload actually needs.
FAQ
What is sched_ext and how does it differ from traditional scheduling classes? sched_ext is a Linux kernel feature (merged in 6.12) that lets scheduling policies be implemented as eBPF programs. Unlike CFS/EEVDF, which are hardcoded in the kernel, sched_ext allows dynamic loading and unloading of custom schedulers at runtime—no kernel recompilation required.
Which kernel version is required for sched_ext?
Linux 6.12 and later, compiled with CONFIG_SCHED_CLASS_EXT=y and BPF support enabled. Confirm with grep CONFIG_SCHED_CLASS_EXT /boot/config-$(uname -r).
Can I use sched_ext with any eBPF program?
No. sched_ext requires a specific program type and the struct sched_ext_ops callback table. You must implement the required callbacks (enqueue, dispatch) and adhere to the sched_ext API and verifier constraints.
How do I handle CPU affinity in a custom scheduler?
Access the task’s allowed mask via p->cpus_ptr and bpf_cpumask_test_cpu(), or fall back to scx_bpf_select_cpu_dfl(). Combine this with per-CPU DSQs and a balance/steal pass to avoid migrations that hurt cache locality.
How does sched_ext compare to CFS/EEVDF for latency-sensitive workloads? In benchmarks, custom sched_ext schedulers reduce tail latency for gaming and real-time audio by prioritizing interactive tasks and minimizing preemption. Database throughput is often similar or slightly improved via better affinity handling. Results vary by workload—thorough benchmarking on your own hardware is essential before production rollout.