kvaps

Blog

sched_ext: the CPU scheduler as a BPF program, and what to do with it on Kubernetes nodes

kernelbpfschedulerkuberneteskubevirt

How sched_ext from Linux 6.12 works, how scx_rusty, scx_lavd and scx_layered differ, and which of them actually apply to Kubernetes nodes with noisy neighbors and KubeVirt VMs.

Contents

For a long time the Linux CPU scheduler was the part of the kernel you just didn’t touch. Want a different policy? Write a patch, build a kernel, reboot the node, and then convince the maintainers that your use case matters more than everyone else’s. Linux 6.12 brought a simpler way: sched_ext, a scheduler class whose behavior is defined by a BPF program and can be changed on the fly, without a reboot.

Let’s look at how it works under the hood, what lives in the sched-ext/scx repository, and what all of this might mean for Kubernetes nodes, where noisy neighbors, latency-critical pods and KubeVirt VMs share the same machine.

This is a review, not a benchmark report: there are no measurements of my own here, only the kernel documentation, the source code and the READMEs from sched-ext/scx. Links are at the end.

Why bother #

The stock scheduler (CFS, and EEVDF since 6.6) is one algorithm for every occasion. It behaves the same on a desktop, a database, a CI farm and a hypervisor, and its knobs are, frankly, pretty coarse: nice, cgroup weights and limits, affinity, a handful of sysctls.

sched_ext takes a different approach. The kernel exposes a full scheduling interface, and the algorithm is written as BPF programs. According to the kernel documentation, this approach has three key properties:

  • a BPF scheduler can group CPUs however it likes, because tasks are not tied to specific CPUs at wakeup time;
  • it can be turned on and off at any moment;
  • system integrity is preserved no matter what the scheduler does. On any error, when a runnable task stalls, or on SysRq-S, the system falls back to the stock scheduler.

The last point is essentially what makes the whole idea viable. You can get the scheduler wrong, but you can’t take the machine down with it.

How it works #

struct sched_ext_ops #

A BPF scheduler is a set of BPF programs implementing struct sched_ext_ops. There is only one mandatory field: ops.name. All callbacks are optional, and anything left unimplemented falls back to the default behavior.

The minimal example from tools/sched_ext/scx_simple.bpf.c looks like this (abridged, from the kernel documentation):

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

        if (direct)
                scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);
        return cpu;
}

void BPF_STRUCT_OPS(simple_enqueue, struct task_struct *p, u64 enq_flags)
{
        scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
}

SEC(".struct_ops")
struct sched_ext_ops simple_ops = {
        .select_cpu = (void *)simple_select_cpu,
        .enqueue    = (void *)simple_enqueue,
        .name       = "simple",
};

One caveat about versions. In 6.12 the function that inserts a task into a queue was called scx_bpf_dispatch(), and the one that pulls from a queue was scx_bpf_consume(). In 6.13 they were renamed to scx_bpf_dsq_insert() and scx_bpf_dsq_move_to_local(). The examples above already use the new names.

DSQ: dispatch queues #

Between the kernel and the BPF code sits a layer of dispatch queues, DSQs. Each DSQ can work as a FIFO or as a priority queue (ordered by vtime). Out of the box there is one global SCX_DSQ_GLOBAL and one local SCX_DSQ_LOCAL per CPU. The scheduler creates its own queues with scx_bpf_create_dsq(), and it can have as many as it wants.

The main rule: a CPU always runs a task from its own local DSQ. Tasks are inserted into DSQs, and from non-local queues they are moved into the local queue of the target CPU. The built-in queues support FIFO only; priority insertion (scx_bpf_dsq_insert_vtime()) works only with user-created ones.

The scheduling loop #

The path of a task that wakes up looks like this:

  1. ops.select_cpu() is a hint about which CPU the task should wake up on, and it also wakes that CPU if it is idle. The hint is not binding: the final CPU is chosen at the end. If the task is inserted straight into SCX_DSQ_LOCAL from here, ops.enqueue() is skipped.
  2. ops.enqueue() decides where the task goes: directly into the global or a local DSQ, into a custom DSQ, or kept in the scheduler’s own BPF data structures.
  3. When a CPU is ready to pick the next task, it checks its local DSQ, then the global one, and only if both are empty does it call ops.dispatch(). That callback can insert tasks into any DSQ or move a task from a custom queue into the local one.
  4. If no work turns up after ops.dispatch(), the CPU tries the global queue once more, may keep running the previous task if it is still runnable, and eventually goes idle.

Around this there are lifecycle callbacks: init_task, enable, runnable, running, tick, stopping, quiescent, disable, exit_task. If a scheduler only uses the built-in DSQs and places everything right in enqueue, it doesn’t need dispatch at all.

What it schedules #

By default, once a BPF scheduler is loaded, all tasks with the SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE and SCHED_EXT policies move under sched_ext. With the SCX_OPS_SWITCH_PARTIAL flag, only tasks that explicitly set SCHED_EXT move, and the rest stay with the fair class. Real-time tasks (SCHED_FIFO, SCHED_RR) and SCHED_DEADLINE are left alone: their classes sit higher.

If a task sets SCHED_EXT on itself while no BPF scheduler is loaded, it simply runs as SCHED_NORMAL.

Fallback and the watchdog #

Fault tolerance comes in three layers.

  • Fallback to the fair class. Termination of the scheduler process, SysRq-S, or any internal error aborts the BPF scheduler and hands all tasks back to the stock scheduler. SysRq-D takes a debug dump without disabling it.
  • Watchdog. sched_ext_ops has a timeout_ms field: the maximum time a runnable task may wait for a CPU. Both the default and the maximum are 30 seconds. If a task waits longer, the scheduler is unloaded. The scx README puts it this way: barring kernel bugs, the worst a sched_ext scheduler can do is starve some threads until the watchdog kicks in.
  • Bypass mode. While the scheduler is loading, unloading or recovering from an error, tasks are scheduled in a simplified mode with a fixed time slice. The sched_ext.slice_bypass_us and sched_ext.bypass_lb_intv_us parameters are documented, but they are mostly meant for debugging.

Keep in mind that 30 seconds is not “instant”. For a latency-sensitive service, half a minute of starvation is an incident, even if the machine survived in the end.

What lives in sched-ext/scx #

The sched-ext/scx repository is the main home for schedulers. Minimal C examples live in the kernel’s tools/sched_ext and in a separate scx-c-examples repository, while scx itself now holds schedulers with a userspace part written in Rust. Three of them are interesting for this review.

scx_rusty #

A hybrid of BPF and userspace. The BPF part does simple round robin within each domain, and the Rust part computes domain load and tells BPF how to rebalance tasks. By default a domain is created per LLC. Balancing thresholds, frequency and the domain split are configurable. The README is upfront about two things: rusty doesn’t yet distinguish LLCs in different NUMA nodes, so it does better on a single socket with several CCXs than on multi-socket machines, and, like CFS, it has the “infeasible weights” problem, where a task with a huge weight forces cores to sit idle.

scx_lavd #

LAVD stands for Latency-criticality Aware Virtual Deadline. The scheduler measures how latency-critical a task is and uses that when computing the deadline and the time slice. All decisions are made by the BPF part, while Rust supplies the topology and handles the plumbing. It was originally built for games, to get rid of stutter. Domains are created per LLC, per core type (P/E on Intel, big/LITTLE on ARM) and per NUMA node, and it is aimed primarily at single-socket systems.

scx_layered #

The most interesting one for servers. Tasks are sorted into layers, and each layer has its own policy. Layer membership is defined by matches: cgroup prefix, process name or its leader’s name, nice, UID/GID, PID and a few more exotic options. Matches are combined into OR groups of AND blocks. There are three kinds of layers:

  • Confined: the layer’s tasks are locked to the CPUs assigned to it, and the number of CPUs is adjusted to keep utilization within util_range;
  • Grouped: the same, but tasks can spill over to free CPUs outside the layer when there are any;
  • Open: prefer CPUs not taken by Confined and Grouped layers, and spill over onto occupied ones if no free CPUs are left.

The configuration is passed as a JSON file with an f: prefix, and stats are collected by a separate process:

scx_layered f:layers.json
scx_layered --monitor 1

The scx README says outright that Meta deploys sched_ext at scale in production, and they have a separate write-up on how they use scx_layered.

How to try it yourself #

First, check that your kernel supports it at all:

uname -r
zcat /proc/config.gz 2>/dev/null | grep SCHED_CLASS_EXT \
  || grep SCHED_CLASS_EXT /boot/config-"$(uname -r)"
cat /sys/kernel/sched_ext/state

You need CONFIG_SCHED_CLASS_EXT=y, BPF with JIT and CONFIG_DEBUG_INFO_BTF=y; the full list is in the kernel documentation and in scx/kernel.config. On Talos you can check the same thing with talosctl -n <node> read /proc/config.gz | zcat | grep SCHED_CLASS_EXT, provided the kernel has CONFIG_IKCONFIG_PROC enabled.

Then you install a scheduler from your distribution’s packages (instructions for Ubuntu, Arch, Fedora, Gentoo, Nix and openSUSE are in INSTALL.md) or build it from source, for example cargo install scx_rusty. Starting it is just running the binary:

scx_rusty &
cat /sys/kernel/sched_ext/state          # enabled
cat /sys/kernel/sched_ext/root/ops       # scheduler name
grep ext /proc/self/sched                # ext.enabled : 1

Stopping the process brings back the stock scheduler. For permanent use there is a systemd unit, scx.service; the scheduler and its flags are set in /etc/default/scx via the SCX_SCHEDULER and SCX_FLAGS variables.

It makes no sense to measure “faster or slower in general”. Measure a specific metric of your workload: service tail latency, CI step time, jitter inside a VM. And always on the same machine, under the same background load, with and without the stock scheduler.

What this means for Kubernetes nodes #

Noisy neighbors #

Today CPU isolation on a node rests on three things. Requests turn into cgroup v2 cpu.weight, limits into cpu.max (the CFS quota), and the CPU Manager with the static policy gives Guaranteed pods with integer CPUs exclusive cores via cpuset. All three are fairly blunt tools. The quota throttles a pod even when the node has idle cores, and exclusive cores sit idle when the pod doesn’t need them.

scx_layered lets you express something Kubernetes can’t: “this layer gets priority access to N cores, but if it isn’t using them, let others have them”. With the systemd cgroup driver, pods land in predictable paths, and layers can be built on top of those. This is a sketch, not a recipe:

[
  {
    "name": "besteffort",
    "matches": [[{"CgroupPrefix": "kubepods.slice/kubepods-besteffort.slice/"}]],
    "kind": {"Confined": {"cpus_range": [1, 4], "util_range": [0.8, 0.9]}}
  },
  {
    "name": "system",
    "matches": [[{"CgroupPrefix": "system.slice/"}]],
    "kind": {"Grouped": {"cpus_range": [1, 2], "util_range": [0.5, 0.8]}}
  },
  {
    "name": "rest",
    "matches": [[]],
    "kind": {"Open": {}}
  }
]

Here BestEffort pods are locked to a few cores, system daemons (kubelet, containerd) get their own guaranteed slice with the option to spill over, and everything else runs on the remaining CPUs. The last layer with an empty match catches whatever didn’t fall into the previous ones. You’ll have to tune util_range and cpus_range for your own node.

Latency-critical pods #

For these, the LAVD idea is more interesting: the scheduler figures out who is latency-critical from the task’s behavior, without manual labeling. But LAVD was written for interactive desktop workloads and single-socket machines, so I wouldn’t move it to a multi-socket server with hundreds of pods without careful measurements. A more predictable route is a dedicated layer in scx_layered with a short slice_us and preempt for the pods you yourself consider critical.

KubeVirt VMs #

This is where things get both interesting and hard. A VM’s vCPU is just an ordinary QEMU thread on the host, and the host scheduler knows nothing about what’s happening inside the guest. sched_ext doesn’t solve the classic “preempted a vCPU that was holding a spinlock in the guest” problem, but it does at least let you keep vCPUs of different VMs on separate LLCs, keep them away from noisy containers, and give them time slices according to your own policy. scx_layered has matches on the process name and its leader’s name (CommPrefix, PcommPrefix), so QEMU threads can be put into a separate layer, and virt-launcher pods are already visible by cgroup.

For VMs with dedicated CPUs in KubeVirt, isolation is built on the CPU Manager, and a BPF scheduler won’t break it: the kernel ignores CPU choices outside a task’s allowed mask. But there isn’t much to improve there either: on an exclusive core there’s no competition.

What it can’t do yet #

Here’s the honest list, and it’s longer than I’d like.

  • cgroup limits depend on the scheduler. The fair class enforces cpu.max, cpu.weight and cpu.idle itself. For tasks under sched_ext, the kernel only passes these settings to the BPF scheduler through callbacks, and whether to enforce them is up to the scheduler. 6.12 only had ops.cgroup_set_weight() (with CONFIG_EXT_GROUP_SCHED); the ops.cgroup_set_bandwidth() callback for cpu.max arrived in 6.17. For Kubernetes this means: before loading a scheduler on a node, find out whether it honors your pods’ limits and requests. If it doesn’t, you’ll end up with a node where limits are formally set but don’t actually work.
  • One scheduler per machine. In 6.12 a single root BPF scheduler is loaded for the whole system. Recent kernels (Kconfig since 7.1) have a CONFIG_EXT_SUB_SCHED option for nested schedulers, but that’s still the bleeding edge.
  • Unstable ABI. The kernel documentation says it plainly: sched_ext_ops callbacks, constants and scx_bpf_* kfuncs can change between kernel versions without notice. The 6.13 rename is a live example. The scheduler binary has to be kept in step with the kernel, and kernel upgrades on nodes have to be tested together with it.
  • No Kubernetes integration. kubelet knows nothing about sched_ext, and there’s no field in the pod spec saying “put me in this layer”. All you have are cgroup and process matches that you configure on the node by hand or with your own DaemonSet.
  • The watchdog is not instant protection. Up to 30 seconds of starvation by default, and timeout_ms can only be lowered.
  • Build requirements. Recent clang and libbpf, a kernel with BTF. The README says directly that many distributions still ship tools that are too old.
  • “Production ready” with caveats. Each scheduler’s README says “yes, if configured properly”. That’s honest, but it means the configuration is your job, not the authors'.

My conclusion: sched_ext is already worth poking at, and you should, on nodes with a well-understood mixed workload, especially scx_layered, where the policy is explicit and readable from the config. But I wouldn’t roll it out to every node in the cluster by default just yet, at least not until you’ve checked how your chosen scheduler handles cpu.max and how it survives a kernel upgrade.

Sources #