← Writing

A CPU Scheduler Written in BPF

Contents

On Linux 6.12, a scheduler of 156 lines of C, compiled to BPF, took over every ordinary task on an eight-CPU machine without a reboot, and one kill signal to its loader handed them all straight back. A 36-line scheduler that deliberately never ran one shell script was thrown out by the kernel’s own watchdog after 5.02 seconds, and the script carried on as if nothing had happened. Measured against the kernel’s default scheduler, the simple one kept up on throughput and lost a hundredfold on wakeup latency under load: 15.7 milliseconds at the 99th percentile, against 165 microseconds.

That is sched_ext, new in Linux 6.12, and underneath it is a mechanism BPF has had since 2020, which lets a BPF program stand in for a function pointer in one of the kernel’s own tables. This part covers both: the mechanism first, on a TCP congestion control, then a CPU scheduler built on it, read line by line, broken on purpose, and measured.

This is Part 14 of a series on eBPF, written for C programmers who know what a process, a system call and a socket are, and nothing about kernel internals. Everything here ran on Linux 6.12, the long-term release of 17 November, in a virtual machine with eight CPUs and an Ubuntu 24.04 userland: clang 18, libbpf 1.3, and the bpftool and example schedulers from the 6.12 source tree. The output is pasted from those runs, and the note at the end says exactly where and how.

So far, BPF has watched and vetoed

Every program in this series so far has sat at the edge of a decision the kernel was going to make anyway. Part 1’s counter watched execve() go by. The XDP programs in Part 8 chose between drop and pass for each packet, but what “pass” meant was still the kernel’s business. The LSM programs in Part 10 could refuse an exec, which is a veto, not a policy. None of them decided how the kernel does a job: how fast a connection should send, or which task gets a CPU next.

That takes a different kind of hook. A filter is one function with a yes-or-no answer. A policy is a set of functions that cooperate and share state: one is told a task woke up, another is asked which task to run next, a third is told the task has stopped, and between them they keep the books. The kernel already organises its replaceable policies exactly like that, as a C struct full of function pointers, one struct per policy. For BPF to supply a policy, a BPF program had to be able to sit in one of those pointers. The mechanism that allows it is called struct_ops. It arrived in 2020, for TCP, and for four years its best-known user was a congestion-control algorithm. In November, Linux 6.12 shipped its second big one: the CPU scheduler.

This post takes them in that order. First the mechanism, on the small case: a TCP congestion control written in BPF, loaded without a line of user-space C, and chosen for a socket with one setsockopt. Then enough scheduling theory to know what a scheduler has to decide. Then sched_ext, the scheduler class that lets a BPF program make those decisions for the whole machine, through its smallest example, scx_simple, read line by line, run, broken on purpose and measured against the kernel’s own scheduler.

struct_ops: a kernel table, filled in by BPF

Start with how the kernel picks a TCP congestion control, because it is the pattern everything else follows. Every algorithm is a struct tcp_congestion_ops, defined in include/net/tcp.h. In 6.12 it has thirteen function pointers and a name. Here are the ones that matter, with the kernel’s own comments:

struct tcp_congestion_ops {
	/* return slow start threshold (required) */
	u32 (*ssthresh)(struct sock *sk);
	/* do new cwnd calculation (required) */
	void (*cong_avoid)(struct sock *sk, u32 ack, u32 acked);
	/* call before changing ca_state (optional) */
	void (*set_state)(struct sock *sk, u8 new_state);
	/* new value of cwnd after loss (required) */
	u32  (*undo_cwnd)(struct sock *sk);
	/* initialize private data (optional) */
	void (*init)(struct sock *sk);
	/* ... and eight more ... */
	char name[TCP_CA_NAME_MAX];
};

CUBIC, the default, is one instance of that struct in net/ipv4/tcp_cubic.c, with .name = "cubic" and .cong_avoid = cubictcp_cong_avoid. When a module registers an instance, its name appears in net.ipv4.tcp_available_congestion_control, and from then on the TCP stack calls through those pointers for every socket that chose it: cong_avoid on each ACK, ssthresh when it detects a loss, and so on. The stack does not know or care which algorithm it is calling.

Linux 5.6 (March 2020) let BPF provide such an instance. Martin KaFai Lau’s patches added a program type, BPF_PROG_TYPE_STRUCT_OPS, and a map type, BPF_MAP_TYPE_STRUCT_OPS, and used them for exactly one struct, tcp_congestion_ops. The idea is general, and the pieces are worth naming:

  • The kernel subsystem opts in. It registers a description of its struct with the BPF core: which members a BPF program may implement, how to check a filled-in instance, and two functions to call when one is registered and unregistered. For TCP, that is net/ipv4/bpf_tcp_ca.c, and its register function is the same tcp_register_congestion_control() a module would call.
  • Each member is one BPF program. A struct_ops program is loaded with the struct’s BTF type and the member’s index as its attach target. The verifier uses the member’s function prototype, from BTF, to type the program’s arguments. So cong_avoid’s first argument arrives as a trusted struct sock *, readable field by field without bpf_probe_read, and the subsystem decides which fields may be written: for TCP, the congestion window and a handful of others.
  • The struct itself is a map. User space creates a BPF_MAP_TYPE_STRUCT_OPS map with one element, whose value is the struct, with program file descriptors where the function pointers go. Writing that element is the moment of registration: the kernel builds a small trampoline for each program, the same machinery that fentry programs use, puts the trampolines’ addresses into a kernel-side copy of the struct, and calls the subsystem’s register function with it. From then on the kernel cannot tell the BPF instance from a compiled-in one.
  • Since 6.4, a link can hold it. Originally the registration lived as long as the map did. Kui-Feng Lee’s 6.4 patches let the map be created with BPF_F_LINK and registered through BPF_LINK_CREATE instead, so the registration belongs to a link, and ends when the link’s last file descriptor is closed, exactly like the links of Part 3. That detail turns out to matter a great deal for schedulers.

One table, three fillings

The kernel calls through a struct of function pointers. Who fills the slots is the only difference.

struct tcp_congestion_ops cubictcp · name "cubic" · net/ipv4/tcp_cubic.c

Built into the kernel image. Each slot holds the address of a compiled C function; empty slots are NULL, and the TCP stack skips the call or uses its own default.

.ssthresh→cubictcp_recalc_ssthresh()
.cong_avoid→cubictcp_cong_avoid()
.set_state→cubictcp_state()
.cwnd_event→cubictcp_cwnd_event()
.in_ack_event→NULL
.pkts_acked→cubictcp_acked()
.min_tso_segs→NULL
.cong_control→NULL
.undo_cwnd→tcp_reno_undo_cwnd()
.sndbuf_expand→NULL
.get_info→NULL
.init→cubictcp_init()
.release→NULL

struct tcp_congestion_ops reno_ops · name "bpf_reno" · map id 184, type struct_ops

Written by bpftool struct_ops register: one map element, whose value is this struct with program descriptors in the slots. The kernel replaced each descriptor with a trampoline that calls the program, validated the result with the same check a module gets, and registered it as a congestion control.

.ssthresh→trampoline → prog 268 reno_ssthresh
.cong_avoid→trampoline → prog 269 reno_cong_avoid
.set_state→trampoline → prog 271 reno_set_state
.cwnd_event→NULL
.in_ack_event→NULL
.pkts_acked→NULL
.min_tso_segs→NULL
.cong_control→NULL
.undo_cwnd→trampoline → prog 270 reno_undo_cwnd
.sndbuf_expand→NULL
.get_info→NULL
.init→trampoline → prog 267 reno_init
.release→NULL

struct sched_ext_ops simple_ops · name "simple" · map id 203, held by link 17

33 callbacks, all optional. scx_simple fills eight (green, with the program that implements each); for the other 25 sched_ext does its default. The map is registered through a link, so the scheduler lasts exactly as long as the loader holds the link.

.select_cpuprog 301 simple_select_cpu .enqueueprog 303 simple_enqueue .dequeue .dispatchprog 304 simple_dispatch .tick .runnable .runningprog 305 simple_running .stoppingprog 306 simple_stopping .quiescent .yield .core_sched_before .set_weight .set_cpumask .update_idle .cpu_acquire .cpu_release .init_task .exit_task .enableprog 307 simple_enable .disable .dump .dump_cpu .dump_task .cgroup_init .cgroup_exit .cgroup_prep_move .cgroup_move .cgroup_cancel_move .cgroup_set_weight .cpu_online .cpu_offline .initprog 308 simple_init .exitprog 309 simple_exit

Teal: a compiled kernel function. Green: a BPF program, reached through a trampoline. Grey: empty. Program and map IDs are from one run of the post's examples on Linux 6.12.

A congestion control in 85 lines

Here is TCP Reno’s window logic as a BPF struct_ops: grow the window by one segment for each segment acknowledged while in slow start, by one segment per window’s worth of acknowledgements after that, and halve it on a loss. It also counts how often the kernel calls each function, in global variables, which libbpf keeps in a map.

// bpf_reno.bpf.c — TCP Reno's window rules as a tcp_congestion_ops in BPF
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

char LICENSE[] SEC("license") = "GPL";

/* How often the kernel called each function. Globals live in a map. */
__u64 n_init, n_ssthresh, n_cong_avoid, n_undo, n_set_state, n_acked;

static struct tcp_sock *tcp_sk(struct sock *sk)
{
	return (struct tcp_sock *)sk;
}

SEC("struct_ops")
void BPF_PROG(reno_init, struct sock *sk)
{
	__sync_fetch_and_add(&n_init, 1);
}

/* A loss was detected: the new slow-start threshold is half the window. */
SEC("struct_ops")
__u32 BPF_PROG(reno_ssthresh, struct sock *sk)
{
	struct tcp_sock *tp = tcp_sk(sk);

	__sync_fetch_and_add(&n_ssthresh, 1);
	return tp->snd_cwnd / 2 > 2 ? tp->snd_cwnd / 2 : 2;
}

/* An ACK arrived for `acked` segments: grow the window. */
SEC("struct_ops")
void BPF_PROG(reno_cong_avoid, struct sock *sk, __u32 ack, __u32 acked)
{
	struct tcp_sock *tp = tcp_sk(sk);

	__sync_fetch_and_add(&n_cong_avoid, 1);
	__sync_fetch_and_add(&n_acked, acked);

	if (tp->snd_cwnd < tp->snd_ssthresh) {
		/* slow start: one more segment per segment acked */
		__u32 cwnd = tp->snd_cwnd + acked;

		if (cwnd > tp->snd_ssthresh)
			cwnd = tp->snd_ssthresh;
		acked -= cwnd - tp->snd_cwnd;
		tp->snd_cwnd = cwnd;
		if (!acked)
			return;
	}
	/* congestion avoidance: one more segment per window acked */
	tp->snd_cwnd_cnt += acked;
	if (tp->snd_cwnd_cnt >= tp->snd_cwnd) {
		tp->snd_cwnd_cnt -= tp->snd_cwnd;
		if (tp->snd_cwnd < tp->snd_cwnd_clamp)
			tp->snd_cwnd++;
	}
}

/* The loss was spurious: put the window back. */
SEC("struct_ops")
__u32 BPF_PROG(reno_undo_cwnd, struct sock *sk)
{
	struct tcp_sock *tp = tcp_sk(sk);

	__sync_fetch_and_add(&n_undo, 1);
	return tp->snd_cwnd > tp->prior_cwnd ? tp->snd_cwnd : tp->prior_cwnd;
}

SEC("struct_ops")
void BPF_PROG(reno_set_state, struct sock *sk, __u8 new_state)
{
	__sync_fetch_and_add(&n_set_state, 1);
}

SEC(".struct_ops")
struct tcp_congestion_ops reno_ops = {
	.init       = (void *)reno_init,
	.ssthresh   = (void *)reno_ssthresh,
	.cong_avoid = (void *)reno_cong_avoid,
	.undo_cwnd  = (void *)reno_undo_cwnd,
	.set_state  = (void *)reno_set_state,
	.name       = "bpf_reno",
};

The parts that are new in this series:

  • SEC("struct_ops") marks each function as a struct_ops program. Which member it implements is not in the section name. libbpf works it out from the struct below, where the function’s address is assigned to a member.
  • BPF_PROG(...), from libbpf’s bpf_tracing.h, unpacks the raw argument array the trampoline passes into named, typed arguments. The types must match the member’s prototype in the kernel’s BTF, or the verifier refuses the program.
  • tcp_sk() is a cast, as it is in the kernel: a struct tcp_sock begins with its struct sock. Reading tp->snd_cwnd is a plain load. Writing it is allowed because bpf_tcp_ca.c lists snd_cwnd, snd_cwnd_cnt and snd_ssthresh among the fields a congestion control may change. Assign to any other field of the socket and the load fails with no write support to tcp_sock at off and the offset; write through a pointer to any other kind of structure and it fails with only read is supported.
  • SEC(".struct_ops") marks the variable reno_ops as the struct itself. Its type is the kernel’s own struct tcp_congestion_ops, straight from vmlinux.h. libbpf turns it into the struct_ops map and fills the pointers with the programs’ file descriptors.
  • The kernel insists on three members, ssthresh, undo_cwnd, and one of cong_avoid or cong_control. That check is tcp_validate_congestion_control(), the same one a module meets.

Two simplifications, so nobody mistakes this for the kernel’s Reno: the kernel’s cong_avoid first checks that the sender is actually using the window it has (tcp_is_cwnd_limited()) and does not grow it otherwise, and it grows the window by more than one segment if an ACK covers more than a window. This version does neither, which is harmless for a bulk transfer.

Registering it without writing a loader

A struct_ops map needs no attach point, so it needs no custom loader either. bpftool can open the object, load every program, create the map and write its one element:

bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c bpf_reno.bpf.c -o bpf_reno.bpf.o
# the kernel's own BPF CUBIC, from the 6.12 source tarball's selftests
P=linux-6.12/tools/testing/selftests/bpf/progs
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I. -I$P -c $P/bpf_cubic.c -o bpf_cubic.bpf.o
sysctl net.ipv4.tcp_available_congestion_control
bpftool struct_ops register bpf_reno.bpf.o
bpftool struct_ops register bpf_cubic.bpf.o
bpftool struct_ops show
sysctl net.ipv4.tcp_available_congestion_control
net.ipv4.tcp_available_congestion_control = reno cubic
Registered tcp_congestion_ops reno_ops id 184
Registered tcp_congestion_ops cubic id 190
184: reno_ops        tcp_congestion_ops
190: cubic           tcp_congestion_ops
net.ipv4.tcp_available_congestion_control = reno cubic bpf_reno bpf_cubic

Name in, name out. As far as the TCP stack is concerned, a new module has registered a congestion control called bpf_reno. The second object is bpf_cubic.c, a BPF port of CUBIC that the kernel’s BPF selftests carry as a test of this machinery. Its own header says it “is not necessarily the same as the tcp_cubic.c”; it reads CONFIG_HZ from the kernel’s configuration through a __kconfig variable, and otherwise follows the same arithmetic.

bpftool struct_ops dump shows the kernel’s copy of the struct. Trimmed to the members that are set, it is the figure above made concrete:

$ sudo bpftool struct_ops dump name reno_ops
...
        "bpf_struct_ops_tcp_congestion_ops": {
            "common": {
                "refcnt": {
                    "refs": {
                        "counter": 1
                    }
                },
                "state": "BPF_STRUCT_OPS_STATE_INUSE"
            },
            "data": {
                "ssthresh": "u32 (struct sock *) reno_ssthresh/prog_id:268",
                "cong_avoid": "void (struct sock *, u32, u32) reno_cong_avoid/prog_id:269",
                "set_state": "void (struct sock *, u8) reno_set_state/prog_id:271",
                "cwnd_event": "void (struct sock *, enum tcp_ca_event) 0",
                ...
                "undo_cwnd": "u32 (struct sock *) reno_undo_cwnd/prog_id:270",
                ...
                "name": "bpf_reno",
                ...
                "init": "void (struct sock *) reno_init/prog_id:267",
                "release": "void (struct sock *) 0"
            }
        }
$ sudo bpftool prog show name reno_cong_avoid
269: struct_ops  name reno_cong_avoid  tag 7fabe8018ee3ff4f  gpl
	[loaded_at line trimmed]
	xlated 392B  jited 248B  memlock 4096B  map_ids 183
	btf_id 215

Choosing it for a socket

An application picks a congestion control per socket with setsockopt(TCP_CONGESTION), and an administrator picks the default for new sockets with the sysctl. To have something to measure I wrote a small Python script that connects to itself over loopback, picks a congestion control, sends a number of mebibytes and prints what TCP_INFO says about the connection at the end:

# xfer.py — send N MiB over loopback TCP with a chosen congestion control
import socket, struct, sys, threading, time

cc = sys.argv[1] if len(sys.argv) > 1 else ""
mib = int(sys.argv[2]) if len(sys.argv) > 2 else 50

srv = socket.socket()
srv.bind(("127.0.0.1", 0))
srv.listen(1)

def sink():
    conn, _ = srv.accept()
    while conn.recv(1 << 20):
        pass

t = threading.Thread(target=sink)
t.start()

s = socket.socket()
if cc:
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_CONGESTION, cc.encode())
s.connect(srv.getsockname())
buf = b"x" * (1 << 20)
t0 = time.monotonic()
for _ in range(mib):
    s.sendall(buf)
s.shutdown(socket.SHUT_WR)
t.join()
secs = time.monotonic() - t0

name = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_CONGESTION, 16)
info = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_INFO, 104)
u32 = struct.unpack_from("24I", info, 8)   # the u32 fields after 8 bytes of u8s
print(f"{name.rstrip(b'\0').decode():9} {mib} MiB in {secs:5.2f} s   "
      f"cwnd {u32[18]:3}  ssthresh {u32[17]:3}  retransmitted {u32[23]}")

Loopback never loses a packet and has a round trip of microseconds, so on its own it would never make an algorithm do anything interesting. I made it a bad network first: an MTU of 1,500 bytes instead of loopback’s 65,536, segmentation offloads off so that packets really are 1,500 bytes on their way through (otherwise netem drops 64 KB batches), and the netem queueing discipline adding 2 ms of delay in each direction and dropping 0.1% of packets.

ip link set lo mtu 1500
ethtool -K lo tso off gso off gro off
tc qdisc add dev lo root netem delay 2ms loss 0.1%
for cc in cubic bpf_cubic bpf_reno reno; do python3 xfer.py $cc 50; done
cubic     50 MiB in  1.53 s   cwnd 196  ssthresh  14  retransmitted 7
bpf_cubic 50 MiB in  0.18 s   cwnd  93  ssthresh 798  retransmitted 921
bpf_reno  50 MiB in  0.17 s   cwnd 419  ssthresh 419  retransmitted 1288
reno      50 MiB in  0.27 s   cwnd 579  ssthresh 536  retransmitted 881

That is the first of five rounds, and it shows how little one round means: the built-in CUBIC took 1.53 s, because it lost a packet very early and left slow start with a threshold of 14 segments, while in the other four rounds it took 0.15 to 0.24 s. Over all five, the median times were 0.22 s for the built-in CUBIC, 0.19 s for bpf_cubic, 0.29 s for bpf_reno and 0.27 s for the built-in Reno, and every one of them ranged widely from round to round (bpf_reno from 0.17 to 0.32 s, the built-in Reno from 0.21 to 0.43 s), because which packets netem drops, and when, decides most of it. A transfer this short is not a congestion-control benchmark, and I would not read a ranking into it. What it shows is the thing that matters here: the socket reported bpf_reno and bpf_cubic as its algorithm, every transfer saw losses (a slow-start threshold that is no longer “infinite”, 2,147,483,647), and the windows ended in the same few hundred segments as the compiled-in algorithms’. (The retransmission counts are far higher than 0.1% of some 36,000 segments would suggest, and vary as wildly as the times. I did not chase why; it is not what this experiment is for.)

The counters tell the rest. After the transfers above, bpf_reno’s globals read:

$ sudo bpftool map dump name bpf_reno.bss
[{
        "value": {
            ".bss": [{
                    "n_init": 5
                },{
                    "n_ssthresh": 16
                },{
                    "n_cong_avoid": 2803
                },{
                    "n_undo": 0
                },{
                    "n_set_state": 36
                },{
                    "n_acked": 152883
                }
            ]
        }
    }
]

Five connections, five calls to init. Sixteen loss episodes across the five transfers, each one a call to ssthresh, which halved the window. Thirty-six state changes (into loss recovery and back out). No spurious-loss undo. And 2,803 calls to cong_avoid, which between them acknowledged 152,883 segments: about 55 segments per ACK the algorithm was shown, because by the time an ACK reaches the congestion control, delayed ACKs and the receiver’s batching have folded many segments into it. Two hundred and fifty mebibytes is about 181,000 segments of 1,448 bytes; the rest were acknowledged while the connection was in loss recovery or otherwise not allowed to grow its window, and then the stack does not call cong_avoid at all.

Finally, the sysctl makes it the default, so a socket that never asks gets it:

$ sudo sysctl -w net.ipv4.tcp_congestion_control=bpf_reno
net.ipv4.tcp_congestion_control = bpf_reno
$ python3 xfer.py "" 5
bpf_reno  5 MiB in  0.04 s   cwnd 2256  ssthresh 2147483647  retransmitted 0
$ sudo sysctl -w net.ipv4.tcp_congestion_control=cubic
net.ipv4.tcp_congestion_control = cubic
$ sudo bpftool struct_ops unregister name reno_ops
Unregistered tcp_congestion_ops reno_ops id 184
$ sysctl net.ipv4.tcp_available_congestion_control
net.ipv4.tcp_available_congestion_control = reno cubic bpf_cubic

That is struct_ops in full: a kernel table, the kernel’s own validation, BPF programs in the slots, and an interface (sysctl, setsockopt) that predates BPF and does not know it is involved. Now for the table that made it famous.

What a CPU scheduler decides

A CPU can run one thread at a time. A machine has a few CPUs and, at any moment, some number of threads that want one. The scheduler is the part of the kernel that decides, every time a CPU becomes free or a thread becomes ready, which thread runs where and for how long. (The kernel says task for a thread, since processes and threads are the same object to it, and so will I.)

Its basic data structure is the run queue: one per CPU, holding the tasks that are ready to run there but are not running. A task that blocks, in read() on an empty pipe say, leaves the run queue and sleeps. When the data arrives, the kernel wakes it: it picks a CPU for it, puts it on that CPU’s run queue and, if the task deserves to run sooner than whatever is running there, asks that CPU to reschedule. When a running task blocks, exhausts its time, or is preempted, the CPU picks the next task from its run queue. Those are the questions any scheduler answers:

  1. Placement. When a task wakes, which CPU’s queue should it join? The one it last ran on has its data in cache; an idle one can run it now.
  2. Ordering. Which of the queued tasks runs next?
  3. Slicing. How long may it run before something else gets a turn?
  4. Preemption. When a task wakes, does it get to interrupt the one running?
  5. Balancing. When one CPU’s queue is long and another’s is empty, what moves?

Scheduling classes

Linux answers those questions differently for different kinds of task, and the code that answers them for one kind is a scheduling class: struct sched_class, another table of function pointers (enqueue_task, dequeue_task, pick_next_task, select_task_rq, task_tick and about twenty more). In 6.12 there are six, linked in a fixed order of precedence: stop (the kernel’s own “stop everything on this CPU” task), dl (SCHED_DEADLINE), rt (SCHED_FIFO and SCHED_RR), fair, ext, and idle. When a CPU needs a task, the core scheduler asks each class in that order and runs the first task it is offered. A real-time task therefore always beats a normal one, and the idle class only runs when nobody else has anything.

Almost everything on an ordinary machine is in fair: every task with the default policy, SCHED_NORMAL (spelt SCHED_OTHER in POSIX), plus SCHED_BATCH and SCHED_IDLE. That class was CFS, the Completely Fair Scheduler, from Linux 2.6.23 in October 2007 until Linux 6.6 in October 2023, when Peter Zijlstra replaced its core with EEVDF, Earliest Eligible Virtual Deadline First, an algorithm from a 1995 paper by Ion Stoica and Hussein Abdel-Wahab. The two share the idea that matters here.

Why changing it was slow

The fair class is one implementation for every machine Linux runs on, from phones to thousand-thread servers, and every change to it is judged against all of them. That is the right standard for a default, and it makes the scheduler one of the hardest parts of the kernel to experiment with. Trying an idea meant patching kernel/sched/, rebuilding, rebooting the test machine, running the workload, and repeating; and an idea that helped one workload had to be shown not to hurt any other before it could go upstream. Companies with unusual workloads carried out-of-tree scheduler patches instead. Google published one such system at SOSP in 2021, ghOSt, which moved scheduling decisions into a user-space agent, with a kernel patch to delegate to it.

The other door, letting a loadable module replace the scheduling policy, has every problem Part 1 listed for modules, multiplied: a scheduler with a bad pointer crashes the machine, and a scheduler that forgets a task hangs it. A BPF scheduler is different on both counts. The verifier rules out the bad pointer, and because the kernel keeps the means to take the policy away at any moment, a forgotten task costs seconds, not a reboot. That is the pitch for sched_ext.

sched_ext: a scheduling class whose policy is a struct_ops

sched_ext is a sixth scheduling class, ext, that does not schedule anything itself. It implements the core scheduler’s side of struct sched_class and forwards each decision to a struct sched_ext_ops, which a BPF program fills in through struct_ops. Tejun Heo and David Vernet started it at Meta; its first posting was in November 2022, its sixth in May 2024, and it was merged for Linux 6.12, released on 17 November. The class sits below fair in the precedence order, and it is empty until a BPF scheduler is loaded. When one is, every SCHED_NORMAL, SCHED_BATCH and SCHED_IDLE task on the machine is moved to it (unless the scheduler asks for “partial” mode, in which only tasks that chose the new SCHED_EXT policy are), and the core skips fair altogether. Real-time and deadline tasks are untouched.

struct sched_ext_ops in 6.12 has 33 callbacks. All of them are optional. The only required member is the name. The ones that carry a task from waking to running are:

  • select_cpu(p, prev_cpu, wake_flags): a task is waking up; pick a CPU for it. The answer is a hint, and choosing an idle CPU also wakes that CPU up.
  • enqueue(p, enq_flags): the task is ready to run; put it somewhere.
  • dispatch(cpu, prev): a CPU has nothing to run; give it something.
  • running(p) and stopping(p, runnable): the task has started, or stopped, running on a CPU. This is where a scheduler does its accounting.
  • enable(p), init_task, exit_task: a task joins or leaves the BPF scheduler.
  • init() and exit(info): the scheduler as a whole starts and stops.

The rest cover CPU hot-plug, cgroups, yielding, idle tracking, core scheduling, and debugging dumps. Leave a callback out and sched_ext does something reasonable instead; leave them all out and you have a working global FIFO scheduler.

Dispatch queues

The callbacks do not return “run this task”. They move tasks between dispatch queues, DSQs, which are where sched_ext keeps its queued tasks so that the BPF side does not have to:

  • Local DSQs, one per CPU, SCX_DSQ_LOCAL. A CPU only ever runs the task at the head of its own local DSQ. This is the BPF scheduler’s equivalent of the run queue.
  • The global DSQ, SCX_DSQ_GLOBAL, a single FIFO any CPU will take from.
  • Custom DSQs, created by the scheduler with scx_bpf_create_dsq(id, node), each either a FIFO or a priority queue ordered by a 64-bit virtual time the scheduler chooses.

The BPF program moves tasks with kfuncs, kernel functions exported to BPF (Part 10 met the mechanism). In 6.12 the main ones are:

  • scx_bpf_dispatch(p, dsq_id, slice, enq_flags): put task p at the tail of a DSQ, with a time slice in nanoseconds (SCX_SLICE_DFL is 20 ms).
  • scx_bpf_dispatch_vtime(p, dsq_id, slice, vtime, enq_flags): put it in a custom DSQ’s priority order, by vtime. The built-in DSQs are FIFOs only.
  • scx_bpf_consume(dsq_id): from dispatch(), move the first task of a custom DSQ to this CPU’s local DSQ.
  • scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle): the default CPU selection, which looks for an idle CPU near prev_cpu, for schedulers that do not want to write their own.

Those names have a short shelf life. In the 6.13 release candidates (rc1 was on 1 December) they are renamed: scx_bpf_dispatch becomes scx_bpf_dsq_insert, scx_bpf_dispatch_vtime becomes scx_bpf_dsq_insert_vtime, and scx_bpf_consume becomes scx_bpf_dsq_move_to_local. The old names still work there, printing a warning once, and the comment beside them says they “will be removed in v6.15”. The documentation is plain about it: the kfuncs and the ops table “have no stability guarantees”. A BPF scheduler is written against one kernel’s interface, and the scx headers carry compatibility macros for the differences.

The cycle

When a CPU needs a task, sched_ext runs this sequence, from Documentation/scheduler/sched-ext.rst:

  1. If the CPU’s local DSQ has a task, run it.
  2. Otherwise, if the global DSQ has one, move it to the local DSQ and run it.
  3. Otherwise call the BPF scheduler’s dispatch(), then look at the local DSQ again.
  4. If it is still empty, keep running the previous task if it is still runnable; else go idle.

And when a task wakes up, select_cpu() runs first; if it dispatches the task straight to SCX_DSQ_LOCAL, the task lands on the chosen CPU’s local DSQ and enqueue() is skipped, otherwise enqueue() is called to place it. The figure in the next section walks one task through this, using scx_simple’s actual code.

What keeps it safe

A BPF scheduler is verified like any BPF program, so it cannot dereference a bad pointer or loop forever. But a scheduler can be wrong in a way no verifier can see: it can simply never run a task. sched_ext has three ways out, and every one of them ends the same way, with every task moved back to the fair class and the machine carrying on:

  • The watchdog. Every runnable task records when it became runnable. A kernel work item checks all of them every half-timeout, and if any task has been runnable without running for longer than the timeout, the BPF scheduler is ejected with a “runnable task stall” error. The timeout is the scheduler’s timeout_ms, capped at, and defaulting to, 30 seconds.
  • SysRq-S. The magic SysRq key, or echo S > /proc/sysrq-trigger, ejects the BPF scheduler from the keyboard of a machine that is otherwise unusable.
  • The link. A BPF scheduler loaded the usual way is registered through a struct_ops link. When the last descriptor to the link closes, because the loader exited, crashed or was killed with SIGKILL, the scheduler is unregistered.

Any error the kernel detects in the scheduler’s behaviour, such as dispatching to a DSQ that does not exist or to a CPU the task may not run on, does the same. We will trigger the watchdog on purpose shortly.

scx_simple, line by line

The kernel tree carries four example schedulers in tools/sched_ext/: scx_simple, scx_qmap, scx_central and scx_flatcg. scx_simple is the smallest, 156 lines of BPF C, and despite the name it is a real scheduler: a single global queue ordered by weighted virtual time, much like the idea in the box above, or, with -f, a plain FIFO. Here it is, from the 6.12 tarball, in pieces.

#include <scx/common.bpf.h>

char _license[] SEC("license") = "GPL";

const volatile bool fifo_sched;

static u64 vtime_now;
UEI_DEFINE(uei);

/*
 * Built-in DSQs such as SCX_DSQ_GLOBAL cannot be used as priority queues
 * (meaning, cannot be dispatched to with scx_bpf_dispatch_vtime()). We
 * therefore create a separate DSQ with ID 0 that we dispatch to and consume
 * from. If scx_simple only supported global FIFO scheduling, then we could
 * just use SCX_DSQ_GLOBAL.
 */
#define SHARED_DSQ 0

fifo_sched is const volatile, so it goes into the object’s read-only data. The loader sets it before loading, and the verifier then knows its value and drops whichever branch is dead, the same trick as Part 6’s configuration constants. vtime_now is an ordinary global: the scheduler’s idea of “now” in virtual time, which only ever moves forward. UEI_DEFINE declares the place where the exit reason will be copied for user space. SHARED_DSQ is the one custom queue; the comment explains why it cannot be the built-in global DSQ, which is FIFO-only.

struct {
	__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
	__uint(key_size, sizeof(u32));
	__uint(value_size, sizeof(u64));
	__uint(max_entries, 2);			/* [local, global] */
} stats SEC(".maps");

static void stat_inc(u32 idx)
{
	u64 *cnt_p = bpf_map_lookup_elem(&stats, &idx);
	if (cnt_p)
		(*cnt_p)++;
}

static inline bool vtime_before(u64 a, u64 b)
{
	return (s64)(a - b) < 0;
}

The statistics: a per-CPU array of two counters, local and global, so no CPU waits for another to count. vtime_before() compares two 64-bit virtual times with the subtraction trick that survives wrap-around, as TCP’s before() does for sequence numbers.

s32 BPF_STRUCT_OPS(simple_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags)
{
	bool is_idle = false;
	s32 cpu;

	cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle);
	if (is_idle) {
		stat_inc(0);	/* count local queueing */
		scx_bpf_dispatch(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
	}

	return cpu;
}

select_cpu. Ask the default selection for a CPU. If it found one that is idle, there is no decision to make: dispatch the task straight to that CPU’s local DSQ with a full 20 ms slice, and count it as “local”. enqueue() will not be called for this wakeup. If no CPU is idle, return the suggestion and let enqueue() decide.

void BPF_STRUCT_OPS(simple_enqueue, struct task_struct *p, u64 enq_flags)
{
	stat_inc(1);	/* count global queueing */

	if (fifo_sched) {
		scx_bpf_dispatch(p, SHARED_DSQ, SCX_SLICE_DFL, enq_flags);
	} else {
		u64 vtime = p->scx.dsq_vtime;

		/*
		 * Limit the amount of budget that an idling task can accumulate
		 * to one slice.
		 */
		if (vtime_before(vtime, vtime_now - SCX_SLICE_DFL))
			vtime = vtime_now - SCX_SLICE_DFL;

		scx_bpf_dispatch_vtime(p, SHARED_DSQ, SCX_SLICE_DFL, vtime,
				       enq_flags);
	}
}

enqueue. Every task that was not placed directly comes here, counted as “global”. In FIFO mode it joins the tail of the shared queue. In vtime mode it is inserted in order of p->scx.dsq_vtime, a per-task field sched_ext provides for exactly this. The if is the one piece of policy that needs thought: a task that slept for a minute has a virtual time far behind everyone else’s, and would monopolise the CPU on waking until it caught up. So its virtual time is pulled forward to at most one slice behind vtime_now. Sleeping earns a little priority, and only a little.

void BPF_STRUCT_OPS(simple_dispatch, s32 cpu, struct task_struct *prev)
{
	scx_bpf_consume(SHARED_DSQ);
}

dispatch. A CPU’s local DSQ and the global DSQ are both empty; take the first task of the shared queue, which in vtime mode is the one with the smallest virtual time.

void BPF_STRUCT_OPS(simple_running, struct task_struct *p)
{
	if (fifo_sched)
		return;

	/*
	 * Global vtime always progresses forward as tasks start executing. The
	 * test and update can be performed concurrently from multiple CPUs and
	 * thus racy. Any error should be contained and temporary. Let's just
	 * live with it.
	 */
	if (vtime_before(vtime_now, p->scx.dsq_vtime))
		vtime_now = p->scx.dsq_vtime;
}

void BPF_STRUCT_OPS(simple_stopping, struct task_struct *p, bool runnable)
{
	if (fifo_sched)
		return;

	/*
	 * Scale the execution time by the inverse of the weight and charge.
	 *
	 * Note that the default yield implementation yields by setting
	 * @p->scx.slice to zero and the following would treat the yielding task
	 * as if it has consumed all its slice. If this penalizes yielding tasks
	 * too much, determine the execution time by taking explicit timestamps
	 * instead of depending on @p->scx.slice.
	 */
	p->scx.dsq_vtime += (SCX_SLICE_DFL - p->scx.slice) * 100 / p->scx.weight;
}

running advances vtime_now to the virtual time of whatever just started running. stopping charges the task for what it used: SCX_SLICE_DFL - p->scx.slice is how much of its 20 ms slice it consumed, since sched_ext counts the slice down as the task runs, and dividing by the task’s weight (100 for nice 0 here, sched_ext’s scale) makes heavier tasks age more slowly. That one line is the whole of the weighting. The comments admit two shortcuts: the update to vtime_now races between CPUs, and a task that yields is charged as if it had used its whole slice.

void BPF_STRUCT_OPS(simple_enable, struct task_struct *p)
{
	p->scx.dsq_vtime = vtime_now;
}

s32 BPF_STRUCT_OPS_SLEEPABLE(simple_init)
{
	return scx_bpf_create_dsq(SHARED_DSQ, -1);
}

void BPF_STRUCT_OPS(simple_exit, struct scx_exit_info *ei)
{
	UEI_RECORD(uei, ei);
}

SCX_OPS_DEFINE(simple_ops,
	       .select_cpu		= (void *)simple_select_cpu,
	       .enqueue			= (void *)simple_enqueue,
	       .dispatch		= (void *)simple_dispatch,
	       .running			= (void *)simple_running,
	       .stopping		= (void *)simple_stopping,
	       .enable			= (void *)simple_enable,
	       .init			= (void *)simple_init,
	       .exit			= (void *)simple_exit,
	       .name			= "simple");

enable starts each task that joins the scheduler at the current virtual time. init creates the shared DSQ; it is sleepable, because creating a queue allocates memory. exit copies the exit information for the loader to print. And SCX_OPS_DEFINE is the struct: a sched_ext_ops in a .struct_ops.link section, so libbpf will create it with BPF_F_LINK and register it through a link. Eight callbacks of 33.

The user-space half, scx_simple.c, is 107 lines. It opens the skeleton, sets fifo_sched if given -f, loads it, attaches the struct_ops map (which creates the link), and then prints the two counters once a second until it is interrupted or the scheduler exits. It holds the link the whole time; that is its main job.

One wakeup through scx_simple

Which callback runs when, and what it does to the queues. The code is scx_simple's own; the tasks, CPUs and virtual times are illustrative.

Scenario 1: an idle CPU is free

kernel · try_to_wake_up → select_task_rq_scx

Task T wakes up

T was blocked in read(); the data has arrived. Before T goes on any queue, sched_ext asks the BPF scheduler where it should run, passing the CPU it last ran on.

T
T · vtime 480waking, last ran on CPU 2
CPU 2 local
empty, CPU idle
SHARED_DSQ 0
empty

BPF · ops.select_cpu

simple_select_cpu: is anything idle?

s32 BPF_STRUCT_OPS(simple_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags)
{
	bool is_idle = false;
	s32 cpu;

	cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle);
	if (is_idle) {
		stat_inc(0);	/* count local queueing */
		scx_bpf_dispatch(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
	}

	return cpu;
}

The default selection prefers prev_cpu if it is idle, then an idle CPU nearby. CPU 2 is idle, so cpu = 2 and is_idle = true.

BPF · still in ops.select_cpu

Dispatch straight to CPU 2

	if (is_idle) {
		stat_inc(0);	/* count local queueing */
		scx_bpf_dispatch(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
	}
	return cpu;

T goes on CPU 2's local DSQ with a 20 ms slice, and the "local" counter goes up. Because the task was dispatched here, sched_ext skips ops.enqueue() for this wakeup and kicks CPU 2 out of idle.

CPU 2 local
T · slice 20 ms
SHARED_DSQ 0
empty

kernel · CPU 2 picks its next task

The local DSQ is not empty: run T

A CPU always runs the head of its own local DSQ first. Nothing else is asked: no dispatch, no lock on a shared queue.

CPU 2
running T

BPF · ops.running

simple_running: move "now" forward

void BPF_STRUCT_OPS(simple_running, struct task_struct *p)
{
	if (fifo_sched)
		return;
	if (vtime_before(vtime_now, p->scx.dsq_vtime))
		vtime_now = p->scx.dsq_vtime;
}

The global vtime_now becomes at least T's virtual time. In this example it was already 500, ahead of T's 480, so it stays.

BPF · ops.stopping

T blocks after 3 ms: charge it

void BPF_STRUCT_OPS(simple_stopping, struct task_struct *p, bool runnable)
{
	if (fifo_sched)
		return;
	p->scx.dsq_vtime += (SCX_SLICE_DFL - p->scx.slice) * 100 / p->scx.weight;
}

sched_ext counted T's slice down from 20 ms to 17 ms while it ran. T is nice 0, weight 100, so it is charged (20 − 17) × 100 / 100 = 3 ms of virtual time: 480 becomes 483. A nice-10 task (weight 11) would have been charged about 27 ms for the same 3 ms of CPU. T is not runnable, so it waits for its next wakeup.

T
T · vtime 483sleeping

Scenario 2: every CPU is busy

BPF · ops.select_cpu

No idle CPU: return a hint, dispatch nothing

	cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &is_idle);
	if (is_idle) {
		...
	}
	return cpu;

T wakes after a long sleep, but all CPUs are running CPU-bound tasks A, B, C… The default selection finds nothing idle, is_idle stays false, and T is not dispatched yet.

T
T · vtime 120slept a long time
vtime_now
500
SHARED_DSQ 0
B · 505C · 512

BPF · ops.enqueue

simple_enqueue: cap the sleeper's credit

void BPF_STRUCT_OPS(simple_enqueue, struct task_struct *p, u64 enq_flags)
{
	stat_inc(1);	/* count global queueing */
	if (fifo_sched) {
		scx_bpf_dispatch(p, SHARED_DSQ, SCX_SLICE_DFL, enq_flags);
	} else {
		u64 vtime = p->scx.dsq_vtime;
		if (vtime_before(vtime, vtime_now - SCX_SLICE_DFL))
			vtime = vtime_now - SCX_SLICE_DFL;
		scx_bpf_dispatch_vtime(p, SHARED_DSQ, SCX_SLICE_DFL, vtime, enq_flags);
	}
}

T's 120 is far behind vtime_now (500). Left alone, T would run ahead of everyone until it had used 380 ms of CPU. The cap lifts it to 500 − 20 = 480, which still puts it at the head of the queue.

SHARED_DSQ 0
T · 480B · 505C · 512

kernel · scheduler tick on CPU 5

T waits: nobody is preempted

scx_simple implements no preemption. T is at the front of the queue, but every CPU keeps running its current task until that task's 20 ms slice runs out or it blocks. This wait, up to a slice long, is what the latency measurement later in the post shows. Here A, on CPU 5, uses up its slice first.

CPU 5
running A · slice 0
SHARED_DSQ 0
T · 480B · 505C · 512

BPF · ops.stopping, then ops.enqueue for A

A is charged a full slice and queued again

	p->scx.dsq_vtime += (SCX_SLICE_DFL - p->scx.slice) * 100 / p->scx.weight;

A started at 498 and used all 20 ms: 518. Still runnable, so it goes back through simple_enqueue and joins the queue in vtime order, behind C.

SHARED_DSQ 0
T · 480B · 505C · 512A · 518

BPF · ops.dispatch

CPU 5 has nothing local: simple_dispatch

void BPF_STRUCT_OPS(simple_dispatch, s32 cpu, struct task_struct *prev)
{
	scx_bpf_consume(SHARED_DSQ);
}

CPU 5's local DSQ is empty and so is the built-in global DSQ, so sched_ext calls ops.dispatch(). Consuming moves the head of the shared queue, the task with the smallest virtual time, to CPU 5's local DSQ.

CPU 5 local
T · slice 20 ms
SHARED_DSQ 0
B · 505C · 512A · 518

BPF · ops.running

T runs on CPU 5

	if (vtime_before(vtime_now, p->scx.dsq_vtime))
		vtime_now = p->scx.dsq_vtime;

T's 480 is behind vtime_now, so "now" does not move. T runs, and the cycle repeats from stopping when it blocks or its slice ends.

CPU 5
running T

Teal: the sched_ext core, in the kernel. Green: a scx_simple callback, in BPF, with the lines that run highlighted. Copper: where the simple design costs latency. Virtual times are in milliseconds for readability; the code keeps nanoseconds.

Running it

The example schedulers build with the kernel tree’s own tools: make -C tools/sched_ext builds the tree’s libbpf (1.5 in 6.12) and bpftool, generates vmlinux.h from the running kernel, and builds scx_simple, scx_qmap, scx_central and scx_flatcg. It needs clang 16 or newer; Ubuntu 24.04’s clang 18 is fine. Before loading anything:

$ cat /sys/kernel/sched_ext/state /sys/kernel/sched_ext/enable_seq
disabled
15

(enable_seq counts BPF schedulers loaded since boot. It is 15 because the measurements later in this post ran first, in the same boot, and loaded scx_simple and scx_qmap fifteen times.)

Then I started scx_simple in the background, gave it four seconds, and looked:

$ sudo scx_simple > simple.out &
$ cat /sys/kernel/sched_ext/state /sys/kernel/sched_ext/root/ops
enabled
simple
$ cat /sys/kernel/sched_ext/enable_seq /sys/kernel/sched_ext/switch_all /sys/kernel/sched_ext/nr_rejected
16
1
0
$ grep ext /proc/self/sched
ext.enabled                                  :                    1

state is enabled and root/ops names the scheduler. enable_seq has gone up by one, switch_all says every eligible task was moved (no partial mode), and nr_rejected counts tasks that asked for the SCHED_EXT policy and were refused by the scheduler. The last line is the shell’s own grep reporting, through /proc/self/sched, that it is being scheduled by sched_ext: an ordinary process, started after the switch, scheduled by BPF without being asked.

From the BPF side, the scheduler is a struct_ops map, eight programs, and a link:

$ sudo bpftool struct_ops show
190: cubic           tcp_congestion_ops
203: simple_ops      sched_ext_ops
$ sudo bpftool prog show name simple_select_cpu
301: struct_ops  name simple_select_cpu  tag e6df28df4bb7fa71  gpl
	[loaded_at line trimmed]
	xlated 304B  jited 184B  memlock 4096B  map_ids 197,199
	btf_id 249
	pids scx_simple(9344)
$ sudo bpftool prog show name simple_dispatch
304: struct_ops  name simple_dispatch  tag a2be6a5a9ef03385  gpl
	[loaded_at line trimmed]
	xlated 24B  jited 22B  memlock 4096B  map_ids 199
	btf_id 249
	pids scx_simple(9344)
$ sudo bpftool link show
17: struct_ops  map 203
	pids scx_simple(9344)

The CUBIC port registered earlier is still there: two struct_ops of two different kinds side by side. simple_dispatch is three instructions, 22 bytes of x86-64: a call to scx_bpf_consume and a return. The link, owned by the scx_simple process, is what holds the scheduler in place.

Loading it took this many bpf() calls (from strace -e trace=bpf, trimmed to the ones that make it a scheduler):

bpf(BPF_MAP_CREATE, {map_type=BPF_MAP_TYPE_STRUCT_OPS, key_size=4, value_size=512, max_entries=1,
    map_flags=BPF_F_LINK, map_name="simple_ops", ..., btf_vmlinux_value_type_id=82343, ...}) = 10
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_STRUCT_OPS, insn_cnt=30, prog_name="simple_select_c",
    expected_attach_type=BPF_CGROUP_INET_INGRESS, ..., attach_btf_id=82257, ...}) = 10
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_STRUCT_OPS, insn_cnt=38, prog_name="simple_enqueue",
    expected_attach_type=BPF_CGROUP_INET_EGRESS, ..., attach_btf_id=82257, ...}) = 11
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_STRUCT_OPS, insn_cnt=3, prog_name="simple_dispatch",
    expected_attach_type=BPF_CGROUP_SOCK_OPS, ..., attach_btf_id=82257, ...}) = 12
...
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_STRUCT_OPS, insn_cnt=4, prog_flags=BPF_F_SLEEPABLE,
    prog_name="simple_init", expected_attach_type=BPF_CGROUP_INET4_GETSOCKNAME, ...,
    attach_btf_id=82257, ...}) = 16
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_STRUCT_OPS, insn_cnt=30, prog_name="simple_exit",
    expected_attach_type=BPF_CGROUP_INET6_GETSOCKNAME, ..., attach_btf_id=82257, ...}) = 17
bpf(BPF_MAP_UPDATE_ELEM, {map_fd=8, key=..., value=..., flags=BPF_ANY}) = 0
bpf(BPF_LINK_CREATE, {link_create={prog_fd=8, target_fd=0, attach_type=BPF_STRUCT_OPS, flags=0}}) = 18

58 calls in all; most are libbpf probing the kernel’s features and creating the ordinary maps (stats, .rodata, .bss, .data), as in Part 1. Three things are particular to struct_ops:

  • The map comes first, as a BPF_MAP_TYPE_STRUCT_OPS with BPF_F_LINK, a 512-byte value, and btf_vmlinux_value_type_id naming the kernel’s wrapper type for sched_ext_ops. (Every map is created as descriptor 10 and then moved to a descriptor libbpf reserved when it opened the object, which is why the struct_ops map is used as 8 at the end.)
  • Every program carries the struct’s BTF id, 82257, as attach_btf_id, and its member index in expected_attach_type. strace does not know that, and decodes the index as if it were an attach type: BPF_CGROUP_INET_INGRESS is 0, member 0 is select_cpu; BPF_CGROUP_INET_EGRESS is 1, enqueue; BPF_CGROUP_SOCK_OPS is 3, dispatch (2 is dequeue, which scx_simple leaves empty); and BPF_CGROUP_INET6_GETSOCKNAME, 32, is exit, the 33rd and last callback. init is loaded with BPF_F_SLEEPABLE.
  • Registration is two calls. BPF_MAP_UPDATE_ELEM writes the struct, with the eight program descriptors in its slots, into map 8; the kernel checks it and builds the trampolines. Then BPF_LINK_CREATE with attach_type=BPF_STRUCT_OPS and the map’s descriptor in the prog_fd field creates the link, and it is at this moment that sched_ext’s register function runs and every task on the machine changes class.

Interrupting it prints the counters it had reached and the exit reason it copied out in exit():

$ sudo kill -INT %1; wait
$ cat simple.out
local=5 global=0
local=605 global=9
local=618 global=15
local=630 global=19
local=1443 global=29
EXIT: unregistered from user space
$ cat /sys/kernel/sched_ext/state
disabled

In four seconds on an almost idle machine, 1,443 wakeups found an idle CPU in select_cpu and went straight to its local DSQ, and only 29 went through enqueue to the shared queue. That ratio is the whole reason select_cpu exists.

The link is what matters most. Killing the loader with SIGKILL, so that it has no chance to clean up, does the same thing:

$ sudo scx_simple -f > simple2.out &
$ cat /sys/kernel/sched_ext/state /sys/kernel/sched_ext/root/ops
enabled
simple
$ sudo kill -9 %1; sleep 0.5
Killed
$ cat /sys/kernel/sched_ext/state /sys/kernel/sched_ext/enable_seq
disabled
17

No exit message this time, because the process that would have printed it is dead; but the kernel closed its descriptors, the link went with them, and the scheduler was unregistered. enable_seq has gone up by one more. A crashing scheduler daemon cannot leave the machine scheduled by a policy nobody is maintaining.

Breaking it on purpose

The interesting failure is not a crash, which the verifier rules out, but neglect. Here is a whole scheduler that runs every task except one called victim, which it accepts in enqueue() and then never queues anywhere:

// stall.bpf.c — a sched_ext scheduler that never runs a task called "victim"
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

char LICENSE[] SEC("license") = "GPL";

void scx_bpf_dispatch(struct task_struct *p, u64 dsq_id, u64 slice,
		      u64 enq_flags) __ksym;

/* Always say "stay where you were", so every wakeup reaches enqueue. */
SEC("struct_ops")
s32 BPF_PROG(stall_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags)
{
	return prev_cpu;
}

SEC("struct_ops")
void BPF_PROG(stall_enqueue, struct task_struct *p, u64 enq_flags)
{
	const char *c = p->comm;

	if (c[0] == 'v' && c[1] == 'i' && c[2] == 'c' && c[3] == 't' &&
	    c[4] == 'i' && c[5] == 'm' && c[6] == '\0')
		return;		/* queued nowhere: it can never run again */

	scx_bpf_dispatch(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
}

SEC(".struct_ops")
struct sched_ext_ops stall_ops = {
	.select_cpu = (void *)stall_select_cpu,
	.enqueue    = (void *)stall_enqueue,
	.timeout_ms = 5000,
	.name       = "stall",
};

It is the smallest useful sched_ext_ops: a select_cpu that always says “stay where you were”, so that every wakeup goes through enqueue (without it, sched_ext’s default select_cpu would place a task on an idle CPU directly and enqueue would never see it); an enqueue that sends everything else to the global DSQ; a five-second timeout_ms; no dispatch, because the global DSQ is consumed automatically. It uses no user-space loader at all: it is a plain .struct_ops map, which bpftool can register and leave behind, like the congestion control above. I started a CPU-bound process named victim (a copy of yes writing to /dev/null), registered the scheduler, and watched the victim’s total run time in /proc/<pid>/sched:

clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c stall.bpf.c -o stall.bpf.o
cat > victim <<'EOF'
#!/bin/sh
while :; do echo tick >> /tmp/ticks; sleep 0.1; done
EOF
chmod +x victim
./victim &
sleep 2; wc -l < /tmp/ticks
bpftool struct_ops register stall.bpf.o
for i in 1 2 3 4 5 6 7 8 9 10; do
	sleep 1; echo "$i s: $(wc -l < /tmp/ticks) ticks, $(cat /sys/kernel/sched_ext/state)"
done
dmesg | grep -A6 'sched_ext: BPF scheduler "stall"'
19
Registered sched_ext_ops stall_ops id 235
1 s: 20 ticks, enabled
2 s: 20 ticks, enabled
3 s: 20 ticks, enabled
4 s: 20 ticks, enabled
5 s: 21 ticks, disabling
6 s: 30 ticks, disabled
7 s: 40 ticks, disabled
8 s: 49 ticks, disabled
9 s: 58 ticks, disabled
10 s: 68 ticks, disabled
[  449.024805] sched_ext: BPF scheduler "stall" enabled
[  454.121965] sched_ext: BPF scheduler "stall" disabled (runnable task stall)
[  454.121969] sched_ext: stall: victim[9377] failed to run for 5.020s
[  454.121970]    scx_watchdog_workfn+0x174/0x230
[  454.121975]    process_one_work+0x174/0x350
[  454.121977]    worker_thread+0x33a/0x470
[  454.121978]    kthread+0xe1/0x110

Here victim is a shell script, so its process is called victim: it appends a line to a file and sleeps for a tenth of a second, forever, a little under ten ticks a second. The moment the scheduler was registered, the ticks stopped at 20. Every time the script’s shell woke from sleep, it went through enqueue, and enqueue dropped it. The rest of the machine carried on: the loop printing these lines ran once a second as usual. Then, 5.10 seconds after the scheduler was enabled by the kernel’s clock, the watchdog found a task that had been runnable without running for 5.020 seconds, more than timeout_ms, and ejected the scheduler with the reason, the culprit and its PID. The loop even caught the state in passing, disabling, while sched_ext was moving every task back. The ticks resumed at the old rate within a second. Nothing had to be killed, and the kernel never noticed anything worse than one slow shell script.

Two details. The watchdog only looks every half-timeout, so a stall is caught somewhere between one and one and a half timeouts after it starts; in an earlier run of a version of this experiment the message said 7.248 s. And after the ejection bpftool struct_ops show still listed stall_ops: a plain .struct_ops map stays registered until someone unregisters it, but it no longer schedules anything, and scx_simple loaded straight away afterwards. That is one more reason real schedulers use a link.

An earlier version of this experiment used a copy of yes, a task that never sleeps, as the victim, and was less clean: the victim kept getting some CPU time during the stall. When a CPU’s local DSQ and the global DSQ are both empty and the task that was running is still runnable, sched_ext keeps running it rather than idling, without going through enqueue. A task that never blocks can therefore survive on a CPU nobody else wants. A task that sleeps cannot.

The same ejection is available by hand. With scx_simple running, echo S > /proc/sysrq-trigger:

$ cat simple3.out
local=4 global=0
local=605 global=11
EXIT: disabled by sysrq-S
$ dmesg | tail -3
[  459.393296] sched_ext: BPF scheduler "simple" enabled
[  461.318457] sysrq: Disable sched_ext and revert all tasks to CFS
[  461.350933] sched_ext: BPF scheduler "simple" disabled (disabled by sysrq-S)

The kernel’s own message still says CFS, a year after EEVDF replaced it.

Measuring it against the default

The comment at the top of scx_simple.bpf.c says what to expect: it “should work reasonably well on CPUs with a uniform L3 cache topology”, it does not implement preemption, and in FIFO mode “saturating threads can easily drown out interactive ones”. I measured four configurations on the same eight-CPU guest: the default (EEVDF, no BPF scheduler loaded), scx_simple in its default weighted-vtime mode, scx_simple -f, and scx_qmap, the tree’s second example, a five-level FIFO built on BPF_MAP_TYPE_QUEUE maps that picks the level from the task’s weight.

Four workloads, all from Ubuntu 24.04’s packages:

  • hackbench (rt-tests 2.5): 10 groups of 20 senders and 20 receivers over sockets, each sender writing 4,000 100-byte messages to every receiver in its group. Lots of short wakeups and context switches; time to finish, lower is better.
  • wakeup latency, idle: cyclictest with one ordinary (SCHED_OTHER) thread that sleeps for 1 ms and measures how late it wakes, for 4 seconds, on an otherwise idle machine.
  • wakeup latency under load: the same, for 6 seconds, while stress-ng runs 16 CPU-bound workers, two per CPU. The workers’ total throughput (bogo-operations per second) is the CPU-bound number.
  • weights: 8 CPU-bound stress-ng workers at nice 0 against 8 at nice 10, for 5 seconds. The number is the share of CPU time the nice-0 group got.

Everything ran in one sitting with nothing else on the host’s virtual machines, in five rounds; each round ran all four configurations, in an order rotated from round to round.

Four schedulers, four workloads

Median of five rounds (big dot), each round (small dots), and their range (bar). Linux 6.12, 8 vCPUs.

The medians as a table
configurationhackbench sidle p99 µsloaded p50 µsloaded p99 µsloaded max µshogs kbogo-ops/snice-0 share %
EEVDF (default)1.6621957165567934.388.6
scx_simple1.762021508156571752334.377.9
scx_simple -f (FIFO)1.924295279193593734.550
scx_qmap1.9323591259483391834.673.7

hackbench: 10 groups × 40 processes over sockets, each sender writing 4,000 messages to every receiver in its group. Wakeup latency: cyclictest, one SCHED_OTHER thread, 1 ms interval, 4 s idle or 6 s while 16 stress-ng CPU workers run. Hog throughput: those 16 workers' summed bogo-ops per second. Weights: 8 workers at nice 0 against 8 at nice 10 for 5 s, the nice-0 group's share of CPU time. One sitting, nothing else running; the guest is a VM inside a VM, so compare configurations, not absolute values.

What the numbers say

Throughput is a tie. Sixteen CPU-bound workers did 34.3 thousand bogo-operations a second under EEVDF and 34.3, 34.5 and 34.6 thousand under scx_simple, its FIFO mode and scx_qmap, with every round of every configuration between 33.5 and 34.7. When every task wants the CPU all the time, it hardly matters who decides the order.

Wakeups on an idle machine are a tie too. With nothing else running, the cyclictest thread’s 99th percentile was 219 µs under EEVDF and 202 to 242 µs under the three BPF schedulers, and the rounds of all four overlap. When a CPU is free, select_cpu finds it, dispatches the task straight to its local DSQ, and that is as fast as the fair class. (The absolute numbers are a nested virtual machine’s, where every timer interrupt passes through two hypervisors; compare the rows, not the values.)

hackbench is where the default first pulls ahead. EEVDF finished in 1.66 s (1.63 to 1.71 over the five rounds), scx_simple in 1.76 s (1.72 to 1.82), its FIFO mode in 1.90 s and scx_qmap in 1.93 s. The ranges do not overlap: the simple scheduler was about 6% slower, FIFO about 14%, scx_qmap 16%. hackbench is thousands of tasks waking each other through sockets, and every wakeup that does not find an idle CPU goes through enqueue into one queue shared by all eight CPUs, where EEVDF keeps a run queue per CPU. That is the likeliest reason; I did not profile it.

Under load, latency is where it loses, badly. With sixteen CPU hogs running, the cyclictest thread, an ordinary task that sleeps for a millisecond at a time, woke within 57 µs at the median under EEVDF and within 165 µs at the 99th percentile. EEVDF gives a task that wakes with an earlier virtual deadline the CPU straight away, and a task that sleeps most of the time always has the earlier deadline. Under scx_simple the median was 1.5 ms and the 99th percentile 15.7 ms, a hundred times worse. The woken thread does get the front of the queue, because it has been asleep and its virtual time is behind; but scx_simple never preempts, so it then waits for the next CPU whose hog reaches the end of its 20 ms slice, which with eight CPUs is a millisecond or two on average and up to a whole slice. FIFO mode and scx_qmap show the opposite shape: the median stays under 100 µs, but the 99th percentile is 26 to 28 ms and the worst case 34 to 36 ms, the time it takes a queue of hogs to rotate. One wakeup in twenty, roughly, lands behind all of them.

The tail is worse than those percentiles suggest, because a late thread misses its next wakeups too. In six seconds the thread should complete about 6,000 cycles. Under EEVDF it completed 5,932 (median of five rounds); under scx_simple 1,637, and under FIFO and scx_qmap about 2,800. Three quarters of the simple scheduler’s cycles never happened.

Weights are honoured, approximately. Eight hogs at nice 0 against eight at nice 10 should split the CPU about 90 to 10, which is what the weights 1024 and 110 promise. EEVDF gave the nice-0 group 88.6%. scx_simple gave it 77.9%: it does weight its charges, but my reading of the code is that its cap on sleepers’ credit works against it here, since vtime_now is dragged forward by the fast-ageing nice-10 tasks and the nice-0 tasks’ virtual time is then pulled up behind it. scx_qmap gave 73.7%, close to the 4:1 its design implies (it takes four tasks from the queue a nice-0 task lands in for every one from the nice-10 queue). FIFO mode gave exactly 50.0%: it has no notion of weight at all, which its own comment warns about.

None of this is a verdict on sched_ext. It is a verdict on a 156-line example whose header says it has no preemption, against the scheduler every Linux machine runs, which has had seventeen years of work on exactly these cases. What it shows is that the policy really is the BPF program’s: change eight callbacks and the machine’s latency, fairness and throughput change with them, measurably, without a reboot. The schedulers in the scx repository exist to do better than scx_simple on the latency column, and the next section is about them.

The ecosystem, in December 2024

sched_ext has been usable out of tree for two years, so it arrived in 6.12 with an ecosystem already around it.

The schedulers. The sched-ext/scx repository on GitHub holds the schedulers meant for real use, in C and in Rust, along with libraries and packaging; its latest release is v1.0.7, from 6 December. (1.0.0 came out in July, rebased on the code headed for mainline; the repository’s own README, at v1.0.7, still says the kernel feature “is not upstream yet”.) At that tag it carries, besides copies of the kernel’s examples:

  • scx_rusty, a multi-domain scheduler, with one scheduling domain per last-level cache by default; its BPF half does round-robin within a domain and a Rust user-space half balances load between domains.
  • scx_layered, which sorts tasks into configurable “layers” (by cgroup, name, and so on), each with its own policy and CPU share.
  • scx_lavd, “Latency-criticality Aware Virtual Deadline”, which estimates how latency-critical each task is from its runtime and wakeup frequencies; its README says it was “initially motivated by gaming workloads”.
  • scx_bpfland, a vruntime scheduler, derived from scx_rustland but entirely in BPF, that treats tasks with frequent voluntary context switches as interactive and gives them a higher-priority queue.
  • scx_rustland, which makes its decisions in user-space Rust, deliberately, as a template; its README says plainly that this is not the fast option.
  • scx_flash (an earliest-deadline-first scheduler with dynamic latency weights), scx_nest, scx_pair, scx_central, scx_userland, scx_mitosis and scx_rlfifo.

Who uses it. The cover letter of the sixth posting, in May, is the clearest public statement: Meta was “now deploying a sched_ext scheduler on one large production” workload, its web tier, running wide-scale verification on an ads workload, and preparing to deploy on ML training, “all using scx_layered”. Google, which already runs ghOSt in its fleet, was “working to port ghOSt schedulers on top of sched_ext”. Valve was working with Igalia on a sched_ext scheduler for the Steam Deck, and the letter says it was “already happy with the results (more consistent FPS)”. The same letter reports scx_flatcg beating CFS by about 3% with the CPU controller off, and about 10% with two Apache instances, on a wrk benchmark.

Where you can get it. A kernel needs CONFIG_SCHED_CLASS_EXT=y and BTF. Arch Linux’s linux package turned it on with its first 6.12 build, on 18 November, the day after the release. Fedora’s kernel configuration tree turned it on in a change written in September, for its 6.12 kernels. Ubuntu did not: 24.04 ships 6.8, which predates sched_ext entirely, and the request to enable it in 24.10 was closed “Won’t Fix” for that release, so 24.10’s 6.11 kernel does not have it either. The Ubuntu mainline builds I used here do.

The rest of the toolchain. libbpf 1.5, released on 29 October, lets a skeleton attach .struct_ops maps itself during __attach(). The compat.h in 6.12’s tools/sched_ext already turns that off, so the explicit bpf_map__attach_struct_ops() in the loaders does not attach the scheduler twice. And on 31 October, BPF’s instruction set itself became an IETF standard, RFC 9669; struct_ops programs are made of the same instructions as every other kind.

What we covered

  • struct_ops lets BPF programs fill in a kernel struct of function pointers. It arrived in Linux 5.6 (2020) for tcp_congestion_ops: the subsystem opts in and decides what may be written, each member is a BPF program typed against the member’s prototype, and the struct is a one-element BPF_MAP_TYPE_STRUCT_OPS map whose update registers it, through trampolines. Since 6.4 a link can own the registration.
  • An 85-line Reno in BPF registered with nothing but bpftool struct_ops register, appeared in tcp_available_congestion_control, was picked per socket with setsockopt(TCP_CONGESTION) and as the default with a sysctl, and counted the calls the TCP stack made into it.
  • A CPU scheduler answers placement, ordering, slicing, preemption and balancing. Linux does it per scheduling class, in a fixed order; ordinary tasks are in fair, which has been EEVDF since 6.6.
  • sched_ext (6.12) adds a class, ext, whose decisions come from a sched_ext_ops struct_ops: 33 optional callbacks, dispatch queues (per-CPU local, one global, any number of custom FIFO or vtime-ordered ones), and kfuncs to move tasks between them (scx_bpf_dispatch, scx_bpf_dispatch_vtime, scx_bpf_consume in 6.12, renamed in the 6.13 release candidates).
  • It is safe to get wrong: a watchdog ejects a scheduler that leaves a runnable task unrun past its timeout, SysRq-S ejects it by hand, and closing the link (even by SIGKILL) unregisters it. Every task goes back to the fair class.
  • scx_simple, 156 lines, is a global weighted-vtime queue in eight callbacks; with -f a global FIFO. It ran the whole machine, and was removed by Ctrl-C, by kill -9 and by SysRq-S.
  • A 36-line scheduler that ignores one task froze it for 5.02 s until the watchdog ejected it.
  • Against EEVDF on eight virtual CPUs, scx_simple matched CPU-bound throughput and idle wakeups, was 6% slower on hackbench, and under load woke an interactive thread in 15.7 ms at the 99th percentile against 165 µs, because it never preempts. Its FIFO mode gave nice-0 and nice-10 tasks exactly half each.

A later part turns from what BPF programs can do to who is allowed to load them in the first place.

A note on the evidence

What I ran, and where. Every listing in this post is pasted from a real run. The machine was a KVM virtual machine with 8 virtual CPUs and 4 GiB of memory, itself running inside another virtual machine, booting the Ubuntu mainline build of Linux 6.12, 6.12.0-061200-generic #202411220723, whose configuration has CONFIG_SCHED_CLASS_EXT=y, CONFIG_HZ=1000 and automatic task grouping on. The userland was a minimal Ubuntu 24.04 built from the release archive only: clang 18.1.3, libbpf 1.3.0, rt-tests 2.5 (hackbench, cyclictest), stress-ng 0.17.06, iproute2 6.1 and ethtool 6.7. From the Linux 6.12 source tarball I built bpftool (it reports v7.5.0, with the tree’s libbpf 1.5) and, with make -C tools/sched_ext, scx_simple and scx_qmap; Ubuntu’s own bpftool wrapper has no build for a mainline kernel. bpf_reno.bpf.c, stall.bpf.c, xfer.py and the shell commands were extracted from this page and run in that order, in one boot; bpf_cubic.c and scx_simple’s source are quoted from the tarball unchanged.

What I trimmed. Run-time timestamps (loaded_at), as in Part 1. The struct_ops dump is cut to the members that are set, marked .... bpftool prog show is cut to the programs discussed. The strace lines are cut to the arguments that matter, marked ..., and to the calls that are particular to struct_ops; the full trace has 58 bpf() calls. Program, map and link IDs, PIDs, descriptor numbers and the kernel’s own timestamps in dmesg are as printed in that boot. The watchdog’s backtrace is cut after five frames. In the listings I added $ prompts and sudo to show which commands were typed; they ran as root.

The counts. The scheduler measurements were one sitting under vrun-alone, with no other test VM running: five rounds, each running EEVDF, scx_simple, scx_simple -f and scx_qmap in an order rotated by one per round (so round five repeated round one’s). Each configuration ran hackbench -g 10 -l 4000; cyclictest -q -m -t 1 -i 1000 -D 4 --policy=other on the idle machine; the same for six seconds while stress-ng --cpu 16 --cpu-method int64 -t 7 ran; then stress-ng --cpu 8 --cpu-method int64 -t 5 at nice 0 and at nice 10 together. Percentiles are computed from cyclictest’s 1 µs histogram for each round; the figure shows the median of the five rounds and their range. A first attempt passed -p 0 after --policy=other, and this cyclictest then switches to SCHED_FIFO (it says “defaulting realtime priority to 2”): its thread was a real-time task, outside sched_ext’s reach altogether. I threw that run away, and checked in the guest that the measurement thread was policy 0 and, under scx_simple, ext.enabled 1. The TCP transfer times are five rounds of the loop in the post, run in the same sitting straight after the scheduler measurements, followed by everything else in the post in the same boot; the strace listing is from an earlier boot of the same image, identical in every value shown. The 7.248 s stall is from an earlier version of the stall experiment with a CPU-bound victim.

What I cited rather than ran. The history: when struct_ops (5.6), struct_ops links (6.4), EEVDF (6.6) and sched_ext (6.12) were merged, which I checked against the release tags that first contain their commits, and CFS’s arrival in 2.6.23. The 6.13 renames are read from kernel/sched/ext.c at the v6.13-rc1 tag. Meta’s, Google’s and Valve’s use of sched_ext are as stated in the May 2024 cover letter of the sixth posting, not anything I could check. The scx schedulers are described from their READMEs at the v1.0.7 tag; I did not run them. The distribution status is from Arch’s and Fedora’s kernel configurations and Ubuntu’s bug tracker.

What I’d still change. The scheduler measurements come from one virtual machine inside another, where the host’s own scheduler decides when my eight virtual CPUs run at all; absolute latencies here are worse than on bare metal, and the ordering between configurations is what I would trust. Five rounds of each is enough to see the differences above and not enough for small ones, such as hackbench’s. And I measured scx_simple against EEVDF on purpose, as the smallest scheduler against the most worked-on; the schedulers in the scx repository, which exist precisely to do better than scx_simple on latency, deserve their own run on real hardware.

More