From 4a54b03dda68165902d9fe11b470e92ef3876d9e Mon Sep 17 00:00:00 2001 From: Galih Tama Date: Tue, 10 Nov 2026 07:22:43 +0700 Subject: [PATCH] scx_flow: update to 5.2.14 Sync scheds/experimental/scx_flow to standalone scx/ at 6d202870 (6d202870f232cbcf1a92f5983faf6902bef7d9a3) over upstream main b0efa3f6 (b0efa3f614c0187df4cb3202d7b514d401f77d2a) via rsync -a --delete --exclude target/ --exclude LICENSE from scx_flow_new/scx. LICENSE stays symlink to ../../../LICENSE, version 5.2.14 kept. libbpf-rs =0.27.2 plus scx_* 1.1.4 path deps match workspace (rust/scx_utils 1.1.4 plus rust/scx_arena 1.1.4); standalone CI pin e7b3a2196 verified the same dep set. Cargo.lock updated for 4.8.16 -> 5.2.14 with scx_arena dep. Old per-CPU .bpf.c layout removed plus new .bpf.h layout added with both lib links tracked. Pure deadline order returns with the wakeup nudge removed plus each per-CPU queue holds tasks in deadline order with equal deadlines in insertion order plus a single kick per run. Bounded overload control adds guaranteed admit plus evict plus reclaim plus admit uses live plus tolerance plus bound plus room plus cap plus a full target evicts at most one ready task with the latest deadline in the lowest band through a bounded scan of at most eight plus rejects stay in fallback in FIFO order plus stopping plus tick reclaim at most one saved burst with idle only kick. Verification: both lib links c2c14b99 plus maps 3 plus headers 7 plus ops 13 plus Cargo 5.2.14 plus cargo metadata --frozen clean. Signed-off-by: Galih Tama --- Cargo.lock | 3 +- scheds/experimental/scx_flow/Cargo.toml | 3 +- scheds/experimental/scx_flow/README.md | 94 +- scheds/experimental/scx_flow/build.rs | 13 +- scheds/experimental/scx_flow/lib | 1 + .../scx_flow/src/bpf/cgroup.bpf.c | 252 --- .../scx_flow/src/bpf/dispatch.bpf.c | 569 ----- .../scx_flow/src/bpf/dispatch.bpf.h | 745 +++++++ .../experimental/scx_flow/src/bpf/edf.bpf.c | 340 --- .../scx_flow/src/bpf/enqueue.bpf.c | 362 ---- .../scx_flow/src/bpf/enqueue.bpf.h | 479 +++++ .../scx_flow/src/bpf/enqueue/insert.bpf.c | 500 ----- .../scx_flow/src/bpf/enqueue/kick.bpf.c | 347 --- .../scx_flow/src/bpf/enqueue/miss.bpf.c | 122 -- .../scx_flow/src/bpf/enqueue/open.bpf.c | 156 -- .../scx_flow/src/bpf/enqueue/target.bpf.c | 37 - .../experimental/scx_flow/src/bpf/fair.bpf.h | 230 ++ scheds/experimental/scx_flow/src/bpf/intf.h | 1916 ++--------------- scheds/experimental/scx_flow/src/bpf/lib | 1 + .../scx_flow/src/bpf/lifecycle.bpf.c | 524 ----- .../experimental/scx_flow/src/bpf/main.bpf.c | 284 +-- .../experimental/scx_flow/src/bpf/maps.bpf.h | 52 + .../scx_flow/src/bpf/preempt.bpf.c | 129 -- .../scx_flow/src/bpf/select.bpf.h | 194 ++ .../scx_flow/src/bpf/select/idle.bpf.c | 71 - .../scx_flow/src/bpf/select/scan.bpf.c | 482 ----- .../scx_flow/src/bpf/select_cpu.bpf.c | 48 - .../experimental/scx_flow/src/bpf/stats.bpf.c | 194 -- .../experimental/scx_flow/src/bpf/stats.bpf.h | 83 + .../scx_flow/src/bpf/task_placement.bpf.c | 219 -- .../experimental/scx_flow/src/bpf/timer.bpf.c | 31 - .../experimental/scx_flow/src/bpf/topology.h | 24 - .../experimental/scx_flow/src/bpf/vtime.bpf.c | 183 -- .../scx_flow/src/bpf/weight.bpf.c | 86 - scheds/experimental/scx_flow/src/cli.rs | 83 + scheds/experimental/scx_flow/src/main.rs | 530 +---- scheds/experimental/scx_flow/src/metrics.rs | 121 ++ scheds/experimental/scx_flow/src/run.rs | 174 ++ .../experimental/scx_flow/src/rust/config.rs | 1408 ------------ .../scx_flow/src/rust/snapshot.rs | 220 -- .../experimental/scx_flow/src/rust/stats.rs | 218 -- .../scx_flow/src/rust/topology.rs | 334 --- .../experimental/scx_flow/src/rust/webui.rs | 473 ---- scheds/experimental/scx_flow/src/stats.rs | 201 ++ scheds/experimental/scx_flow/src/topology.rs | 152 ++ scheds/experimental/scx_flow/ui/index.html | 694 ------ 46 files changed, 2704 insertions(+), 10678 deletions(-) create mode 120000 scheds/experimental/scx_flow/lib delete mode 100644 scheds/experimental/scx_flow/src/bpf/cgroup.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/dispatch.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/dispatch.bpf.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/edf.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue.bpf.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue/insert.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue/kick.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue/miss.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue/open.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/enqueue/target.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/fair.bpf.h create mode 120000 scheds/experimental/scx_flow/src/bpf/lib delete mode 100644 scheds/experimental/scx_flow/src/bpf/lifecycle.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/maps.bpf.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/preempt.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/select.bpf.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/select/idle.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/select/scan.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/select_cpu.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/stats.bpf.c create mode 100644 scheds/experimental/scx_flow/src/bpf/stats.bpf.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/task_placement.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/timer.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/topology.h delete mode 100644 scheds/experimental/scx_flow/src/bpf/vtime.bpf.c delete mode 100644 scheds/experimental/scx_flow/src/bpf/weight.bpf.c create mode 100644 scheds/experimental/scx_flow/src/cli.rs create mode 100644 scheds/experimental/scx_flow/src/metrics.rs create mode 100644 scheds/experimental/scx_flow/src/run.rs delete mode 100644 scheds/experimental/scx_flow/src/rust/config.rs delete mode 100644 scheds/experimental/scx_flow/src/rust/snapshot.rs delete mode 100644 scheds/experimental/scx_flow/src/rust/stats.rs delete mode 100644 scheds/experimental/scx_flow/src/rust/topology.rs delete mode 100644 scheds/experimental/scx_flow/src/rust/webui.rs create mode 100644 scheds/experimental/scx_flow/src/stats.rs create mode 100644 scheds/experimental/scx_flow/src/topology.rs delete mode 100644 scheds/experimental/scx_flow/ui/index.html diff --git a/Cargo.lock b/Cargo.lock index 03c8071918..81eac76100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6068,7 +6068,7 @@ dependencies = [ [[package]] name = "scx_flow" -version = "4.8.16" +version = "5.2.14" dependencies = [ "anyhow", "clap", @@ -6077,6 +6077,7 @@ dependencies = [ "ctrlc", "libbpf-rs 0.27.2", "log", + "scx_arena", "scx_cargo", "scx_stats", "scx_stats_derive", diff --git a/scheds/experimental/scx_flow/Cargo.toml b/scheds/experimental/scx_flow/Cargo.toml index 59a6d793bf..0c4366ee6a 100644 --- a/scheds/experimental/scx_flow/Cargo.toml +++ b/scheds/experimental/scx_flow/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "scx_flow" -version = "4.8.16" +version = "5.2.14" authors = ["Galih Tama "] edition = "2024" rust-version = "1.91" @@ -15,6 +15,7 @@ crossbeam = "0.8" ctrlc = { version = "3", features = ["termination"] } libbpf-rs = "=0.27.2" log = "0.4" +scx_arena = { path = "../../../rust/scx_arena/scx_arena", version = "1.1.4" } scx_stats = { path = "../../../rust/scx_stats", version = "1.1.4" } scx_stats_derive = { path = "../../../rust/scx_stats/scx_stats_derive", version = "1.1.4" } scx_utils = { path = "../../../rust/scx_utils", version = "1.1.4" } diff --git a/scheds/experimental/scx_flow/README.md b/scheds/experimental/scx_flow/README.md index 7ceee6c69e..2e1ef2b49d 100644 --- a/scheds/experimental/scx_flow/README.md +++ b/scheds/experimental/scx_flow/README.md @@ -1,89 +1,23 @@ # scx_flow -### What is it? - -scx_flow runs the earliest strict key as the earlier of deadline plus virtual time. It adds [RED](https://web.cs.umass.edu/publication/docs/1993/UM-CS-1993-025.pdf) admission with guarantee-only tolerance plus five tiers with insert vtime plus value ordered reject queue outside dispatch plus reclaim on completer credit with tiers-empty fallback plus aged cover. See `src/bpf/intf.h` and `src/bpf/edf.bpf.c`. - -### Why? - -The goal is to test strict order with prediction in the kernel and see if short bursts reach a CPU sooner. See `src/bpf/intf.h`. - -### How it works? - -Arrivals pass a gate first, then pass RED with residual plus exceed plus tolerance for the guarantee alone. A zero exceed admits, a critical exceed admits without a swap, else an O(1) newcomer test still decides. Each CPU takes the earliest key it may run. See `src/bpf/enqueue.bpf.c` and `src/bpf/dispatch.bpf.c`. +## What + +scx_flow orders tasks by deadline. Each per-CPU queue holds tasks in +deadline order with equal deadlines in insertion order, plus one fallback +queue in FIFO order. Running tasks pay for burnt time. Virtual deadline adds +a burst scaled nice step to the floored time. Overload admits with live plus +tolerance plus bound plus room plus cap and evicts at most one ready task +with the latest deadline in the lowest band through a bounded scan of at most +eight. Rejects stay in fallback in FIFO order. Stopping plus tick reclaim at +most one saved burst with idle only kick. Dispatch drains local first, +then same LLC, then same node, then remote. Wakeups wake idle only with preempt on an earlier deadline. Slice is fixed at 1ms, and hotplug needs restart. ## Typical Use Cases -- Latency-sensitive applications. -- General desktop use. -- Mixed batch workloads. - -## More details - -### Queues - -Local plus node plus machine plus reject hold tasks across 1042 queues. Each pass drains three PRIQ tiers (local plus node plus machine) plus value ordered reject plus steal for five dispatch tiers total with move capped by slots and 8 visits plus reclaim when empty plus aged past period. Reject stays value ordered outside dispatch with overflow name for wire compat. Direct plus exiting LOCAL_ON stays terminal FIFO outside PRIQ order with no tier rank. Six latency ceilings name burst sizes apart from dispatch tiers. See `src/bpf/intf.h`. - -### Keys - -Each strict key sets queue rank with vruntime pacing via lag bounds. Predictor shapes deadlines with up plus down shifts plus half deviation margin. Virtual deadline adds dynamic slice over weight with one divide. Strict key holds earlier of deadline plus virtual deadline with 2ms clamp still. Remaining feeds slice plus slack only now. See `src/bpf/intf.h`. - -### Admission - -RED checks residual from deadline minus cost plus fixed tolerance of zero for latency-critical else `64us` for hard batch with hard scoped to non-latency via the unified test. Admit plus reclaim share the same fixed path, so both agree. Newcomer victim needs cost past fixed `256us Emax` plus past exceed plus never latency-critical, else admits. Newcomer-pays trades choice for single-check admission and tiers-empty plus aged reclaim caps starvation without dropping. Fixed bounds gate overload plus PRIQ only for tiers with LOCAL_ON terminal. See `src/bpf/edf.bpf.c` and `src/rust/config.rs`. - -### Gates - -A gate runs first so tasks and CPUs wait. Exiting work runs at once without waiting. Fails join the value ordered reject queue without leaking. Drain stays gated with mask wins. Eligibility gates every kick, so hogs pace while lagging tasks still wake. See `src/bpf/cgroup.bpf.c`. - -### Reporting - -Flags `--stats`, `--monitor`, and `--no-webui` show counters as text or page at `50005`. Page keeps local, node, machine, kicks, preempt, plus RED rejects plus reclaims. Snapshots share one moment with times plus topology. Dashboard shows sixteen counters plus uptime with CPU cards plus five key merged JSON intact. See `src/rust/stats.rs`. - -### Fairness - -Strict order holds the earlier of deadline plus virtual deadline in each queue. Vruntime advances by slice over weight with lag clamp. Sleepers gain one slice of boost. Adaptive steps change the slice without changing virtual time. Hierarchy stays flat. See `src/bpf/intf.h`. - -### Weights - -Weight tunes period bands. Shares map to 32ms, 16ms, 8ms, 4ms periods with shares 32, 64, 256, and 1024. Effective share stacks task times hint over 128 with zero mapped to 128. Heavy tasks earn near keys, light tasks earn far keys. Value holds weight with top critical. See `src/bpf/cgroup.bpf.c`. - -### Locality - -Locality stays with per-CPU plus per-node queues. Select takes prev idle, then waker and sibling idle, before the pick, so pairs share cache still. Placement keeps the slowest sufficient CPU with prev tie plus near minimum now. Two-way SMT assumed. Span equals online CPUs with no hotplug use. See `src/bpf/select_cpu.bpf.c`. - -### Contention - -One pass stays capped with 8 visits per pass across five tiers. Each tier moves task by slots. Steal scans 4 to 8 peers node-local first. Reclaim moves reject when tiers hold no work plus aged past period. Twelve peers cover one percent on 1024 CPUs. See `src/bpf/dispatch.bpf.c`. - -### Inversion - -Mask check caps inversion with fail open. Each move checks the CPU mask and picks time first, so heads skip to the next task and tier. Reject stays outside dispatch with reclaim on same key or after. Local on stays terminal FIFO at three sites outside PRIQ order. See `src/bpf/dispatch.bpf.c`. - -### Staleness - -Staleness heals math plus fold. Stop feeds average plus deviation plus credit with no sampling. Average rises with shift `3` plus falls with shift `4`, deviation widens with shift `2` plus narrows with shift `3`, and period adds average plus deviation plus half deviation. Yields carry `10us` plus `1ms` when critical plus wall meets, else shrink `exceed>>3` capped `1ms` plus half then halved per stop on late else grow `slack>>3` capped `1ms` plus half then halved per stop on early with deadband hold. Misses stay lifetime, adapt window. Reclaim shares the fixed `64us tol` plus `256us Emax` with admit and falls back without reserve when tiers hold no work. See `src/bpf/lifecycle.bpf.c`. - -### Latency - -Latency caps slice at `100us` plus key at now plus max `4ms` else slice plus `100us` with RED on deadline. Sleep below `20us` vetoes toward batch with unknown open, decoupled from the `100us` cap. Arrival preempts only when lat meets batch owner else fails closed with the strict key driving kick and margin plus tail still checked while placement tests the deadline plus drain. Kick threads the pre-overwrite sleep, so it agrees with RED plus slice. Resume keeps start plus cur leftover clamped to `10us` plus `100us` else `1ms`. Adapt steps cap at `1ms` then re-clamp here, so one shift never holds past the cap with fixed `256us Emax` past the cap. See `src/bpf/intf.h` plus `src/bpf/preempt.bpf.c` plus `src/bpf/lifecycle.bpf.c`. - -### Tiers - -Tiers pace bursts at `50us` plus `100us` plus `500us` plus `1ms` plus `5ms` with a `20ms` ceiling plus a `10us` floor under an `80ms` period. Predicted burst maps avg plus dev plus half dev margin to the ceiling with critical forced to `50us`, so audio plus UI plus IPC plus desktop plus bulk work hold room without starving. Six latency ceilings name burst sizes apart from five dispatch tiers. Fresh waits cap the dynamic slice by the tier capped at `1ms`, so small bursts pace tightly while bulk still rotates each quantum. Like fair.c, tiers pace service with no fixed hold. See `src/bpf/intf.h` plus `src/rust/config.rs`. - -### Prediction - -Prediction keeps math-only average plus deviation with no model. Average rises fast with shift `3` plus falls slow with shift `4`, deviation widens fast with shift `2` plus narrows slow with shift `3`, and period adds average plus deviation plus half deviation margin with `1ns` to `1s` clamp. Adapt adds proportional deadband at base shift `5` floor `8us` plus half-damp shift `1` capping one step at one quarter base, so timer jitter never hunts and ringing halves each stop. Fixed `64us` tolerance plus `256us Emax` gate overload with task at `72B` plus stats at `136B`. See `src/bpf/intf.h`. - -## Code map - -- Rules live in `src/bpf/intf.h` with RED plus adapt helpers. -- Core lives in cgroup, weight, vtime, edf, placement, select, enqueue, preempt, dispatch, lifecycle, stats, and timer, with select plus enqueue split. -- Init lives in main plus topology still. -- Dashboard lives in snapshot, stats, topology, webui, and ui now even today still. +- Latency sensitive work, such as audio editing. +- Desktop use, such as gaming with browser tabs open. +- Batch work, such as compiling and rendering. ## Limitations - Hotplug needs restart. -- Needs kernel `7.2` or newer. diff --git a/scheds/experimental/scx_flow/build.rs b/scheds/experimental/scx_flow/build.rs index 4a8a6c6f34..cb64c7040a 100644 --- a/scheds/experimental/scx_flow/build.rs +++ b/scheds/experimental/scx_flow/build.rs @@ -33,6 +33,17 @@ fn main() { .unwrap() .enable_intf("src/bpf/intf.h", "bpf_intf.rs") .enable_skel("src/bpf/main.bpf.c", "bpf") - .build() + .add_source("src/bpf/lib/arena.bpf.c") + .add_source("src/bpf/lib/common.bpf.c") + .add_source("src/bpf/lib/atq.bpf.c") + .add_source("src/bpf/lib/edq.bpf.c") + .add_source("src/bpf/lib/bitmap.bpf.c") + .add_source("src/bpf/lib/cpumask.bpf.c") + .add_source("src/bpf/lib/minheap.bpf.c") + .add_source("src/bpf/lib/rbtree.bpf.c") + .add_source("src/bpf/lib/sdt_alloc.bpf.c") + .add_source("src/bpf/lib/sdt_task.bpf.c") + .add_source("src/bpf/lib/topology.bpf.c") + .compile_link_gen() .unwrap(); } diff --git a/scheds/experimental/scx_flow/lib b/scheds/experimental/scx_flow/lib new file mode 120000 index 0000000000..c2c14b9959 --- /dev/null +++ b/scheds/experimental/scx_flow/lib @@ -0,0 +1 @@ +../../../../../lib \ No newline at end of file diff --git a/scheds/experimental/scx_flow/src/bpf/cgroup.bpf.c b/scheds/experimental/scx_flow/src/bpf/cgroup.bpf.c deleted file mode 100644 index c7ab3f7316..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/cgroup.bpf.c +++ /dev/null @@ -1,252 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Admission gate plus flat hierarchy for the core. - * - * The gate runs first in every op, so stale CPUs plus moved tasks plus - * stale queues fail closed with one counter and no charge. The flat - * view holds one period plus weight hint per id with single weighting - * through one shared band helper, and no group or pool shapes order. - * The table holds 8192 rows with no eviction, so a full table misses - * to defaults with no stall. Id zero scopes to defaults with no row. - * A zero cached id is the stale sentinel with miss to the acquire path. - * Moves carry vruntime plus deadline with no hint carry, so the next - * enqueue reads the new hint after the move invalidate clears the id. - * - * Copyright (c) 2026 Galih Tama - */ -/* True when the id is a live CPU below nr and the bound. */ -static __always_inline bool flow_cpu_live(u32 cpu) -{ - if (unlikely((u64)cpu >= nr_cpu_ids)) - return false; - if (unlikely((u64)cpu >= (u64)FLOW_MAX_CPUS)) - return false; - return true; -} -/* True when the CPU is live and inside the task mask. */ -static __always_inline bool flow_cpu_ok( - const struct task_struct *p, s32 cpu) -{ - if (unlikely(cpu < 0)) - return false; - if (unlikely((u64)cpu >= nr_cpu_ids)) - return false; - if (unlikely((u64)cpu >= (u64)FLOW_MAX_CPUS)) - return false; - return bpf_cpumask_test_cpu((u32)cpu, p->cpus_ptr); -} -/* True when one task may enter an op on the given CPU. */ -static __always_inline bool flow_entry_ok(s32 cpu, - const struct task_struct *p, u64 dsq) -{ - if (unlikely(!p)) - return false; - if (unlikely(cpu >= 0 && !flow_cpu_live((u32)cpu))) - return false; - if (unlikely(cpu >= 0 && !bpf_cpumask_test_cpu((u32)cpu, - p->cpus_ptr))) - return false; - if (unlikely(dsq && !flow_dsq_valid(dsq))) - return false; - return true; -} -/* Id of one hierarchy with root at one on missing. */ -static __always_inline u64 flow_cgrp_id(struct cgroup *cgrp) -{ - struct kernfs_node *kn; - u64 id; - if (!cgrp) - return 1; - kn = BPF_CORE_READ(cgrp, kn); - if (!kn) - return 1; - id = BPF_CORE_READ(kn, id); - if (!id) - return 1; - return id; -} -/* Clear one cached hierarchy id for a pid with no fail. */ -static __always_inline void flow_cgrp_cache_invalidate(u32 pid) -{ - if (!pid) - return; - bpf_map_delete_elem(&cgrp_cache_stor, &pid); -} -/* Acquired hierarchy of one task with paired release. */ -static __always_inline struct cgroup *flow_task_cgrp( - struct task_struct *p) -{ - return scx_bpf_task_cgroup(p); -} -/* Release one acquired hierarchy with null tolerance. */ -static __always_inline void flow_cgrp_put(struct cgroup *cgrp) -{ - if (cgrp) - bpf_cgroup_release(cgrp); -} -/* Flat period hint in micros for one id with zero for no hint. */ -static __always_inline u32 flow_hint_us(u64 cgid) -{ - struct flow_hint *h; - if (!cgid) - return 0; - h = bpf_map_lookup_elem(&hint_stor, &cgid); - if (!h) - return 0; - return READ_ONCE(h->period_us); -} -/* Hint plus weight of one task with one cache plus one row read. */ -static __always_inline void flow_task_hint_weight( - struct task_struct *p, u32 *hint_us, u32 *weight) -{ - u32 pid = (u32)p->pid; - u64 *cached; - u64 id; - struct flow_hint *h; - if (hint_us) - *hint_us = 0; - if (weight) - *weight = (u32)FLOW_WEIGHT_BASE; - if (!p) - return; - if (pid) { - cached = bpf_map_lookup_elem(&cgrp_cache_stor, &pid); - if (cached && *cached) { - id = *cached; - h = bpf_map_lookup_elem(&hint_stor, &id); - if (!h) - return; - if (hint_us) - *hint_us = READ_ONCE(h->period_us); - if (weight) { - u32 w = READ_ONCE(h->weight); - *weight = w ? flow_weight_clamp(w) : - (u32)FLOW_WEIGHT_BASE; - } - return; - } - } - { - struct cgroup *cgrp = flow_task_cgrp(p); - if (!cgrp) - return; - id = flow_cgrp_id(cgrp); - flow_cgrp_put(cgrp); - if (pid) - bpf_map_update_elem(&cgrp_cache_stor, - &pid, &id, BPF_ANY); - h = bpf_map_lookup_elem(&hint_stor, &id); - if (!h) - return; - if (hint_us) - *hint_us = READ_ONCE(h->period_us); - if (weight) { - u32 w = READ_ONCE(h->weight); - *weight = w ? flow_weight_clamp(w) : - (u32)FLOW_WEIGHT_BASE; - } - } -} -/* Init one flat hint row with zero period plus neutral weight. */ -/* Zero period means no hint, so the default 80ms period applies with */ -/* no extra fill and a huge hint still clamps via saturation at the */ -/* period caller. A missing row reads the same, so init plus miss */ -/* agree with no stale hint and the count never wraps. */ -s32 BPF_STRUCT_OPS_SLEEPABLE(flow_cgroup_init, struct cgroup *cgrp, - struct scx_cgroup_init_args *args) -{ - u64 id; - struct flow_hint h = {}; - (void)args; - if (!cgrp) - return -EINVAL; - id = flow_cgrp_id(cgrp); - if (!id) - return -EINVAL; - h.weight = (u32)FLOW_WEIGHT_BASE; - bpf_map_update_elem(&hint_stor, &id, &h, BPF_ANY); - return 0; -} -/* Exit one flat hint row. */ -void BPF_STRUCT_OPS(flow_cgroup_exit, struct cgroup *cgrp) -{ - u64 id; - if (!cgrp) - return; - id = flow_cgrp_id(cgrp); - if (!id) - return; - bpf_map_delete_elem(&hint_stor, &id); -} -/* Prepare one flat move with no alloc and no fail. */ -s32 BPF_STRUCT_OPS(flow_cgroup_prep_move, struct task_struct *p, - struct cgroup *from, struct cgroup *to) -{ - (void)p; - (void)from; - (void)to; - return 0; -} -/* Commit one flat move with vruntime plus deadline carry. */ -void BPF_STRUCT_OPS(flow_cgroup_move, struct task_struct *p, - struct cgroup *from, struct cgroup *to) -{ - (void)from; - if (!p) - return; - if (!to) - return; - flow_cgrp_cache_invalidate((u32)p->pid); -} -/* Cancel one flat move with no state change. */ -void BPF_STRUCT_OPS(flow_cgroup_cancel_move, struct task_struct *p, - struct cgroup *from, struct cgroup *to) -{ - (void)p; - (void)from; - (void)to; -} -/* Shared single share band for cgroup plus task paths. */ -static __always_inline void flow_share_band(u32 w, u32 *period_us, - u32 *weight) -{ - u32 p = 8000; - u32 b = 256; - u32 c = flow_weight_clamp(w); - if (c < 64) { - p = 32000; - b = 32; - } else if (c < 128) { - p = 16000; - b = 64; - } else if (c < 512) { - p = 8000; - b = 256; - } else { - p = 4000; - b = 1024; - } - if (period_us) - *period_us = p; - if (weight) - *weight = b; -} -/* Update one flat hint from the share with fixed bands. */ -/* Bands stay at 4ms plus 8ms plus 16ms plus 32ms with shares at 1024 */ -/* plus 256 plus 64 plus 32, so a huge share never fills a huge period */ -/* with no wrap. The period converts with saturation at the caller, so */ -/* a stray row still clamps with no short deadline. */ -void BPF_STRUCT_OPS(flow_cgroup_set_weight, struct cgroup *cgrp, - u32 weight) -{ - u64 id; - struct flow_hint h = {}; - if (!cgrp) - return; - id = flow_cgrp_id(cgrp); - if (!id) - return; - flow_share_band(weight, &h.period_us, &h.weight); - if (bpf_map_update_elem(&hint_stor, &id, &h, BPF_ANY) < 0) - return; -} diff --git a/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.c b/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.c deleted file mode 100644 index cc3b94068d..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.c +++ /dev/null @@ -1,569 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Dispatch with strict PRIQ plus capped steal plus fail open. - * - * Each pass drains local plus node plus machine plus steal in order - * with at most one hint threaded move per tier capped by remaining - * slots and visits capped at eight per pass shared across tiers. Four - * depths read once, so tiers plus steal plus perf share the same - * reads. Three PRIQ tiers (local plus node plus machine) hold strict - * order through the kernel priority queue with insert vtime plus value - * ordered reject plus steal for five total, so the earliest key always - * wins. In-tier keys cap at now plus one period at enqueue, so far keys - * never starve past one period and eight visits per pass cap each tier - * with resume next pass. The reject queue stays value ordered outside - * dispatch, so overload never inverts the PRIQ order. The reject queue - * holds overload and reclaims at most one per pass with tiers-empty - * fallback plus aged cover past one period, so PRIQ tiers never starve - * behind rejects and zero credit never idles queued work. A reject - * rejoins a PRIQ tier only on reclaim with the same key or a strictly - * after key, so an earlier key never waits behind a rejoin. The steal - * tier scans four to eight peers sticky with node-local first plus idle - * affinity plus backoff on gate plus miss pressure, with per peer hints - * threaded into one hint move plus a saturated early out when tiers - * still hold work. A Q1 only fast path drains the single queue pass and - * skips two empty moves plus the steal checks. The shared cursor advances - * by two on a successful steal to match select, so the next pass starts - * past the drained peer without a hotspot. Fail open moves through the - * shared mask gate, so one foreign head never stalls its tier. A stale - * hint only repeats or skips a pass. The level follows after all moves - * through the shared hint check without a kfunc and stays transition - * only. The check covers per CPU local, local on, node, and running, and - * skips machine, reject, and steal, so a busy shared tier never forces - * max on an idle CPU. Local on stays terminal FIFO at three sites - * outside PRIQ order with no tier rank, so tiers stay PRIQ-only. - * - * Copyright (c) 2026 Galih Tama - */ -/* Depth check with saved hints plus running without a kfunc. */ -/* Takes the dispatch depths for own local plus local on plus node, */ -/* so the perf pass reuses the same reads. Shared early exit keeps one */ -/* compare on the busy path and the first queued hint or running pid */ -/* returns busy at once. A stale read with dispatch moves only shifts the */ -/* perf level by one pass without changing order, since the next pass */ -/* reads again. Signed hints keep empty at zero or below, so empty never */ -/* wraps. */ -/** - * flow_perf_busy_hint - test busy from saved queue hints. - * @cpu: CPU to test, negative fails closed. - * @local_q: saved own local depth, non-positive means empty. - * @local_on_q: saved local on depth, non-positive means empty. - * @node_q: saved node depth, non-positive means empty. - * - * Scope covers per CPU local, local on, node, and running, and skips - * machine, overflow, and steal. The caller also gates on live, so an - * idle CPU with only shared backlog still rests at half without changing - * order. - * - * Returns: true when busy, else false without a kfunc. - */ -static __noinline bool flow_perf_busy_hint(s32 cpu, s32 local_q, - s32 local_on_q, s32 node_q) -{ - struct flow_cpu_state *st; - if (cpu < 0) - return false; - if (!flow_cpu_live((u32)cpu)) - return false; - if (local_q > 0) - return true; - if (local_on_q > 0) - return true; - if (node_q > 0) - return true; - st = flow_cpu((u32)cpu); - if (st && READ_ONCE(st->running_pid) != 0) - return true; - return false; -} -/* Core perf set with transition only store. */ -static __noinline void flow_perf_set(s32 cpu, u32 want) -{ - u32 cap; - u32 key; - u32 *last; - if (!bpf_ksym_exists(scx_bpf_cpuperf_set)) - return; - if (cpu < 0) - return; - if (!flow_cpu_live((u32)cpu)) - return; - if ((u64)cpu >= (u64)FLOW_MAX_CPUS) - return; - if (want != (u32)FLOW_CPU_PERF_HALF && - want != (u32)FLOW_CPU_PERF_MAX) - return; - if (bpf_ksym_exists(scx_bpf_cpuperf_cap)) { - cap = scx_bpf_cpuperf_cap(cpu); - if (cap == 0) - return; - if (want > cap) - want = cap; - } - key = (u32)cpu; - last = bpf_map_lookup_elem(&cpu_perf_last, &key); - if (!last) - return; - if (READ_ONCE(*last) == want) - return; - __sync_lock_test_and_set(last, want); - scx_bpf_cpuperf_set(cpu, want); -} -/* Shared perf update with saved hints without a kfunc on the check. */ - /* Scope covers per CPU local, local on, node, and running, and skips */ - /* machine, overflow, and steal, so a busy shared tier never forces max */ - /* on an idle CPU. Transition-only store keeps one level per change */ - /* without flapping, and a stale read only shifts the level by one pass. */ -static __always_inline void flow_perf_update_hint(s32 cpu, s32 local_q, - s32 local_on_q, s32 node_q) -{ - if (flow_perf_busy_hint(cpu, local_q, local_on_q, node_q)) - flow_perf_set(cpu, (u32)FLOW_CPU_PERF_MAX); - else - flow_perf_set(cpu, (u32)FLOW_CPU_PERF_HALF); -} -/** - * struct flow_reclaim_tail - reclaim args for the outlined candidate check. - * @rctx: reject task state with deadline plus predictor plus vruntime. - * @q: reject task for the mask gate. - * @cpu: target CPU for the mask gate. - * @now: current time in nanos. - * @credit: saved global reclaim credit, read once by the caller. - * @tiers_empty: true when local plus node plus machine hold no work. - * - * Bundles the candidate state plus time plus credit plus gate, so the - * outlined check takes one pointer like the scan plus enqueue tails and - * the dispatch loop stays small. - */ -struct flow_reclaim_tail { - struct flow_task_ctx *rctx; - struct task_struct *q; - s32 cpu; - u64 now; - u64 credit; - bool tiers_empty; -}; -/** - * flow_reclaim_is_aged - test one reject wait past one period. - * @wait_at: last wait stamp in nanos, zero means unknown. - * @now: current time in nanos. - * - * Ages past one period with wrap safety, so continuous tier load still - * needs credit past the age bound with no bypass. A zero stamp, a stamp - * at now, or a future stamp never counts as aged with no stall. - * Like fair.c, the bound paces reclaim, unlike rt.c, no fixed priority - * holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so the reclaim check keeps one age with no inline growth. - * - * Returns: true when aged past one period, else false. - */ -static __noinline bool flow_reclaim_is_aged(u64 wait_at, u64 now) -{ - u64 age; - if (wait_at == 0 || wait_at == now) - return false; - if (flow_time_before(now, wait_at)) - return false; - age = now - wait_at; - return age > (u64)FLOW_PERIOD_NS; -} -/** - * flow_reclaim_key_ok - test one reject key still fresh. - * @rctx: reject task state with vruntime plus slice plus weight. - * @rdl: reject absolute deadline in nanos. - * @now: current time in nanos. - * - * Rebuilds the strict key as the earlier of deadline plus virtual - * deadline with the effective share, so a stale key fails closed to - * the next candidate with no move. A key at now stays fresh with no - * stall. Like fair.c, the earliest key wins, unlike rt.c, no fixed - * priority holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so the reclaim check keeps one key with no inline growth. - * - * Returns: true when fresh, else false on stale state. - */ -static __noinline bool flow_reclaim_key_ok(struct flow_task_ctx *rctx, - u64 rdl, u64 now) -{ - u64 rvtime; - u64 vr; - u64 sl; - u32 tw; - u32 hw; - u32 eff; - u64 vd; - if (!rctx) - return false; - vr = READ_ONCE(rctx->vruntime); - sl = (u64)READ_ONCE(rctx->slice_ns); - tw = READ_ONCE(rctx->weight); - hw = READ_ONCE(rctx->hint_w); - eff = flow_task_effective_weight(tw, hw); - vd = flow_virt_deadline(vr, sl, eff); - rvtime = flow_edf_key(rdl, vd); - if (rvtime != now && flow_time_before(rvtime, now)) - return false; - return true; -} -/** - * flow_reclaim_early_skip - test whether the reclaim walk skips early. - * @credit: saved global reclaim credit, read once by the caller. - * @tiers_empty: true when local plus node plus machine hold no work. - * - * Skips the walk when tiers hold work plus credit stays short of the - * fixed 256us Emax, since aged heads still need funding with no - * fallback. Tiers-empty keeps the walk with no reserve, so zero credit - * never idles work. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so the dispatch pass keeps one fixed read with no inline - * growth. - * - * Returns: true when the caller skips the walk, else false. - */ -static __noinline bool flow_reclaim_early_skip(u64 credit, bool tiers_empty) -{ - if (!tiers_empty && credit < (u64)FLOW_RED_EMAX_NS) - return true; - return false; -} -/** - * flow_reclaim_candidate_ok - test one reject for reclaim plus reserve. - * @t: reclaim tail with state plus task plus target plus time plus credit - * plus gate, read once by the caller. - * - * Checks laxity with the fixed 64us tolerance plus tiers-empty plus - * aged cover plus key freshness plus mask plus credit with reserve, - * so the loop keeps one call. Hard takes 64us while latency-critical - * keeps zero, so reclaim agrees with admit. Tiers-empty heads with - * positive laxity fall back without reserve while funded heads reserve - * before the move, so zero credit never idles queued work. Aged heads - * past one period pass even when tiers hold work. A stale key, a - * foreign mask, or a lost reserve fails closed to the next candidate. - * - * Returns: true when the caller may move the candidate. - * - * Outlined with noinline to keep verifier headroom on the dispatch path. - */ -static __noinline bool flow_reclaim_candidate_ok(const struct flow_reclaim_tail *t) -{ - struct flow_task_ctx *rctx = t->rctx; - struct task_struct *q = t->q; - s32 cpu = t->cpu; - u64 now = t->now; - u64 credit = t->credit; - bool tiers_empty = t->tiers_empty; - u64 rdl; - u64 ravg; - u64 rdev; - u64 rcost; - u64 rtol; - s64 rres; - u64 rexc; - u64 rlax; - bool rcrit; - bool funded; - if (!rctx || !q) - return false; - rdl = READ_ONCE(rctx->deadline); - ravg = (u64)READ_ONCE(rctx->avg_ns); - rdev = (u64)READ_ONCE(rctx->dev_ns); - { - u32 rhint = READ_ONCE(rctx->hint_us); - u32 rtw = READ_ONCE(rctx->weight); - u32 rhw = READ_ONCE(rctx->hint_w); - u32 reff; - if (rtw == 0) - rtw = (u32)FLOW_WEIGHT_BASE; - reff = flow_task_effective_weight(rtw, rhw); - /* Queue wait is not sleep, so the reclaim check passes zero */ - /* sleep with probation, while enqueue checks pass the true */ - /* gap read before the wait overwrite. */ - rcrit = flow_is_lat(ravg, rdev, rhint, 0, 0, reff); - } - rcost = flow_red_cost(ravg, READ_ONCE(rctx->slice_ns)); - /* Reclaim shares the fixed 64us tolerance with admit, so hard */ - /* takes 64us while latency-critical keeps zero. */ - rtol = flow_red_tol(rcrit); - rres = flow_red_residual(rdl, now, rcost); - rexc = flow_red_exceed(rres, rtol); - rlax = flow_red_laxity(rdl, now, rcost); - if (rlax == 0) - return false; - /* Aged cover past one period through the shared helper, so PRIQ */ - /* tiers never wait behind rejects past the age bound. */ - if (!tiers_empty && - !flow_reclaim_is_aged(READ_ONCE(rctx->wait_at), now)) - return false; - /* Key freshness through the shared helper, so an earlier key never */ - /* waits behind a rejoin with a stale key failing closed. */ - if (!flow_reclaim_key_ok(rctx, rdl, now)) - return false; - if (!flow_mask_ok(cpu, q)) - return false; - /* Aged heads still need funding, so continuous tier load never */ - /* drains rejects without credit with no overload bypass. */ - /* Tiers-empty heads with positive laxity fall back without reserve, */ - /* so zero credit never idles queued work. */ - funded = flow_red_reclaim_ok(credit, rexc, rlax); - if (!tiers_empty && !funded) - return false; - if (funded) { - if (!flow_credit_consume(rexc)) - return false; - } - return true; -} -/** - * flow_reject_reclaim_one - reclaim one value ordered reject. - * @cpu: target CPU for the mask gate. - * @visits: per pass visit count shared across tiers. - * @now: current time in nanos. - * @queued: saved reject depth, non-positive skips without a walk. - * @tiers_empty: true when local plus node plus machine hold no work. - * - * Scans at most eight value ordered rejects with one RCU walk, so the - * check stays cheap with no overload stall. Funded heads reserve credit - * before the move with a recheck to the next candidate on a lost race, - * while tiers-empty heads with positive laxity fall back without reserve - * so zero credit never idles queued work. Aged heads past one period - * reclaim when funded even while tiers hold work, so continuous tier - * load still needs credit with no bypass. Non reclaimable, stale, and - * foreign entries skip to the next candidate, so one bad head never - * stalls the queue. The credit funds the retry without using head - * state. The greatest value still wins among reclaimable entries. - * Tiers-empty gating plus one move per pass plus the one period age - * bound keep starvation capped and PRIQ tiers never wait behind - * rejects past the age bound. - * - * Returns: one on move else zero. - * - * Outlined with noinline to keep verifier headroom on the dispatch path. - */ -static __noinline u32 flow_reject_reclaim_one(s32 cpu, u32 *visits, u64 now, - s32 queued, bool tiers_empty) -{ - u64 credit; - struct task_struct *q; - u32 moved = 0; - if (unlikely(cpu < 0)) - return 0; - if (unlikely(!visits)) - return 0; - if (unlikely(!flow_cpu_live((u32)cpu))) - return 0; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - return 0; - if (likely(queued <= 0)) - return 0; - credit = flow_credit_peek(); - /* Skip the walk when tiers hold work plus credit stays short of the */ - /* fixed 256us Emax through the shared helper, since aged heads */ - /* still need funding with no fallback. Tiers-empty keeps the walk */ - /* with no reserve, so zero credit never idles work. */ - if (flow_reclaim_early_skip(credit, tiers_empty)) - return 0; - bpf_rcu_read_lock(); - bpf_for_each(scx_dsq, q, flow_overflow_dsq(), 0) { - struct flow_task_ctx *rctx; - struct flow_reclaim_tail tail; - u32 cur; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - break; - if (unlikely(moved)) - break; - (*visits)++; - rctx = flow_lookup(q); - if (!rctx) - continue; - tail.rctx = rctx; - tail.q = q; - tail.cpu = cpu; - tail.now = now; - tail.credit = credit; - tail.tiers_empty = tiers_empty; - if (!flow_reclaim_candidate_ok(&tail)) - continue; - cur = flow_move_candidate(BPF_FOR_EACH_ITER, cpu, q); - if (cur) - moved = cur; - break; - } - bpf_rcu_read_unlock(); - return moved; -} -void BPF_STRUCT_OPS(flow_dispatch, s32 cpu, - struct task_struct *prev) -{ - u32 budget; - u32 left = 0; - u32 visits = 0; - u32 local_moved = 0; - u32 node_moved = 0; - u32 machine_moved = 0; - u32 reclaim_moved = 0; - u64 own_local; - u32 node; - u64 node_dsq; - u64 machine_dsq; - (void)prev; - if (unlikely(cpu < 0)) - return; - if (unlikely(!flow_cpu_live((u32)cpu))) { - flow_gate_reject(); - return; - } - budget = scx_bpf_dispatch_nr_slots(); - own_local = flow_local_dsq((u32)cpu); - node = flow_cpu_node((u32)cpu); - if (node >= (u32)FLOW_MAX_NODES || - (u64)node >= nr_node_ids) - node = 0; - node_dsq = flow_node_dsq(node); - machine_dsq = flow_machine_dsq(); - /* Read four depths once before the budget gate, so the perf check */ - /* at out reuses the same reads even when slots run out. Signed hints */ - /* keep empty at zero or below. The reject queue stays outside here, */ - /* so the pass pays four reads total. */ - { - s32 lq0 = scx_bpf_dsq_nr_queued(own_local); - s32 lo0 = scx_bpf_dsq_nr_queued((u64)SCX_DSQ_LOCAL_ON | - (u64)(u32)cpu); - s32 nq0 = scx_bpf_dsq_nr_queued(node_dsq); - s32 mq0 = scx_bpf_dsq_nr_queued(machine_dsq); - if (unlikely(budget == 0)) - goto out_hint; - left = budget; - /* Queue depths read once. Each tier move threads its hint through */ - /* the shared hint move, so empty tiers skip the RCU scan without a */ - /* visit cost. The same hints feed the steal early exit and the perf */ - /* check, so the pass pays four queue reads total. A stale hint only */ - /* repeats or skips a pass, since the shared hint move rechecks under */ - /* RCU with the same visit cap. Signed hints keep empty at zero or */ - /* below. */ - { - bool q1_only = lq0 > 0 && nq0 <= 0 && mq0 <= 0; - /* Q1 only fast path drains the local tier alone. The common */ - /* single queue pass skips two empty moves plus the steal */ - /* backlog with the same order plus the same counts. Uses */ - /* the saved hint without polling again. */ - if (q1_only && likely(left) && - likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - local_moved = flow_move_one_hint(own_local, cpu, &visits, - lq0); - if (local_moved > left) - local_moved = left; - left -= local_moved; - goto account; - } - if (likely(left) && likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - if (lq0 > 0) { - local_moved = flow_move_one_hint(own_local, cpu, - &visits, lq0); - if (local_moved > left) - local_moved = left; - left -= local_moved; - } - } - if (likely(left) && likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - if (nq0 > 0) { - node_moved = flow_move_one_hint(node_dsq, cpu, - &visits, nq0); - if (node_moved > left) - node_moved = left; - left -= node_moved; - } - } - if (likely(left) && likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - if (mq0 > 0) { - machine_moved = flow_move_one_hint(machine_dsq, cpu, - &visits, mq0); - if (machine_moved > left) - machine_moved = left; - left -= machine_moved; - } - } - /* Reject queue stays outside dispatch. A reject rejoins a PRIQ */ - /* tier only on reclaim with the same key or a strictly after */ - /* key, so strict order holds. Like fair.c, the earliest key */ - /* wins, unlike rt.c, no fixed priority holds. */ - /* Reclaim one value ordered reject with tiers-empty plus aged cover. */ - /* Tiers-empty heads fall back without reserve so zero credit */ - /* never idles queued work, while aged heads past one period */ - /* reclaim even when tiers hold work so the reject queue keeps */ - /* draining. The clock reads only here, and a stale hint only */ - /* repeats or skips a pass. */ - if (likely(left) && likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - bool tiers_empty = (lq0 <= 0 && nq0 <= 0 && mq0 <= 0); - s32 oq = scx_bpf_dsq_nr_queued(flow_overflow_dsq()); - if (oq > 0) { - u64 now = flow_now(); - u32 rec = flow_reject_reclaim_one(cpu, &visits, - now, oq, tiers_empty); - if (rec > left) - rec = left; - left -= rec; - local_moved += rec; - reclaim_moved += rec; - } - } - /* Steal tier last with a capped 4 to 8 peer window with saturation. */ - /* Only steals when tiers drained, so busy passes skip cheap with */ - /* the saved hints. The window caps each pass while miss counts */ - /* pace every tier, so the lowest tier still turns. */ - /* Backlog sums the three queued PRIQ tiers (local plus node */ - /* plus machine) with saturation, so a huge depth clamps instead */ - /* of wrapping to idle. Narrow means empty peers skip without */ - /* RCU through the per peer hint in the shared steal, so the */ - /* effective scan stays small. */ - if (likely(left) && likely(visits < (u32)FLOW_DISPATCH_MAX_VISIT)) { - u32 steal_moved = 0; - struct flow_cpu_state *cst; - u32 cursor; - u64 backlog = 0; - if (lq0 > 0) - backlog = flow_sat_add(backlog, (u64)lq0); - if (nq0 > 0) - backlog = flow_sat_add(backlog, (u64)nq0); - if (mq0 > 0) - backlog = flow_sat_add(backlog, (u64)mq0); - if (backlog == 0) { - u64 nr = nr_cpu_ids; - cst = flow_cpu((u32)cpu); - cursor = cst ? READ_ONCE(cst->cursor) : (u32)cpu; - steal_moved = flow_steal_one(cpu, &visits, cursor); - if (steal_moved > left) - steal_moved = left; - left -= steal_moved; - local_moved += steal_moved; - /* Shared cursor advances by two on success to match */ - /* select, so the next steal starts fresh without a */ - /* hotspot. Races keep no atomic order beyond the */ - /* single store. */ - if (steal_moved && cst && nr > 1 && - nr <= (u64)FLOW_MAX_CPUS) { - u32 n = (u32)nr; - u32 next = flow_wrap_idx((u64)cursor + 2ULL, n); - __sync_lock_test_and_set(&cst->cursor, next); - } - } - } - } -account: - flow_account_local(local_moved); - flow_account_node(node_moved); - flow_account_machine(machine_moved); - flow_count_red_reclaim(reclaim_moved); -out_hint: - /* Perf check reuses the saved local plus local on plus node hints */ - /* without a kfunc, so the pass skips a second check on the busy */ - /* path. A stale read only shifts the level by one pass without */ - /* changing order. */ - flow_perf_update_hint(cpu, lq0, lo0, nq0); - } - return; -} diff --git a/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.h b/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.h new file mode 100644 index 0000000000..fb067c2724 --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/dispatch.bpf.h @@ -0,0 +1,745 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Dispatch and lifecycle for the flow scheduler. + * + * Each CPU drains its own queue first, then queues on the same LLC, + * then the same node, then distant queues, then fallback. Each queue + * drains in deadline order. A head that cannot run here + * sends one wake to its owner and stays queued. Each victim keeps + * its own forward slot with the fallback on the last slot, so one + * victim does not hide another. A dead head is dropped with its count + * and the next queue is tried. The fallback drops its count from the + * task and wakes the owner when the move fails. A dispatch that moved + * nothing but saw such a head wakes the fallback head again without + * the dedup check. Remote moves count on the thief and drop the gauge + * on the source. Running records the task snapshot and mirrors the + * due time beside it for gap checks. Stopping charges burnt time into the + * stored time and mirrors the stored time beside it, and tracks the + * run length for the next due time. A runnable yield with no burnt + * time still moves the stored time forward by one. The tick charges + * the burnt delta and moves the due time with the burst left while + * inside it and the left slice past it and mirrors the due time beside + * it, so stopping charges only the tail past the last tick. When the + * slice is exhausted at the tick, the stored slice stays while the + * running horizon moves out by one slice, so the two views diverge + * until stopping charges the tail. A busy core runs at max and an idle + * core runs at half. The set call never sends zero and never steers + * placement. A mask change on a queued task keeps the queue and wakes + * the new owner, counting the wake when the owner is usable. A task + * with no usable CPU waits in the fallback queue until the mask widens. + * Stopping plus tick reclaim at most one saved delta from burst past + * burnt with room plus live plus allowed and idle only kick, so overload + * drains with no new op. Init creates one embedded queue per CPU bounded at 64 total + * and the fallback queue. Queues + * use the upstream deadline library with always eligible tasks. Liveness comes from + * the upstream tree, so CPUs that arrive late need a restart to be seen. + * Each task carries one arena queue node with its pid for lookup. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_DISPATCH_BPF_H +#define __FLOW_DISPATCH_BPF_H +#include "intf.h" +#include "maps.bpf.h" +#include "stats.bpf.h" +#include "select.bpf.h" +#include "enqueue.bpf.h" +#include "fair.bpf.h" +#include +#include +#include +#include +/* A busy core runs at max and an idle core runs at half. The call + * stays on one live core and never sends zero. */ +static __always_inline void flow_cpuperf_mark(u32 cpu, bool idle) +{ + u32 perf; + if (!flow_cpu_ok(cpu) || !flow_cpu_live(cpu)) + return; + if (!bpf_ksym_exists(scx_bpf_cpuperf_set)) + return; + perf = (u32)SCX_CPUPERF_ONE; + if (idle) + perf = (u32)(SCX_CPUPERF_ONE / 2); + if (!perf) + return; + scx_bpf_cpuperf_set((s32)cpu, perf); +} +static __always_inline void flow_forward_from_peeked(struct task_struct *ph, u32 llc, u32 slot) +{ + s32 owner; + s64 hv; + u64 pid; + if (!ph) + return; + if (slot > (u32)FLOW_MAX_LLCS) + return; + pid = (u64)ph->pid; + hv = (s64)ph->scx.dsq_vtime; + owner = flow_first_allowed(ph); + { + u64 last_p = READ_ONCE(flow_fwd_pid[slot]); + s64 last_v = READ_ONCE(flow_fwd_vtime[slot]); + s32 last_o = READ_ONCE(flow_fwd_owner[slot]); + if (last_p == pid && last_v == hv && last_o == owner) + return; + flow_fwd_pid[slot] = pid; + flow_fwd_vtime[slot] = hv; + flow_fwd_owner[slot] = owner; + } + if (owner < 0) { + flow_kick_idle_only(owner, ph, llc); + return; + } + flow_stat_inc(llc, 12); + flow_kick_idle_only(owner, ph, llc); +} +/* A dispatch that moved nothing but saw an unrunnable head wakes the + * fallback head again without the dedup check, so an owner that + * turned idle is not missed. The kick stays idle only with no pad check. */ +static __always_inline void flow_rekick_unrunnable(struct task_struct *ph, u32 llc) +{ + s32 owner; + if (!ph) + return; + owner = flow_first_allowed(ph); + flow_kick_idle_only(owner, ph, llc); +} +/* Reclaim one fallback head with saved burst. Peeks the fallback queue + * once and kicks the idle owner once when the target holds room with + * live plus allowed, so overload drains with no extra probe and no new + * op. Saved zero skips with no kick. Compare only with no divide. */ +static __always_inline void flow_reclaim_kick(u64 saved, u32 llc) +{ + struct task_struct *ph; + s32 owner; + struct scx_edq __arena *edq; + if (!saved) + return; + if (!flow_llc_ok(llc)) + return; + ph = __COMPAT_scx_bpf_dsq_peek((u64)FLOW_FALLBACK_DSQ); + if (!ph) + return; + owner = flow_first_allowed(ph); + if (owner < 0) + return; + edq = flow_edq_for_cpu(owner); + if (!edq) + return; + if (scx_edq_nr_queued(edq) >= (u64)FLOW_QUEUE_CAP) + return; + flow_kick_idle_only(owner, ph, llc); +} +static __always_inline int flow_try_move_edq(u32 cpu, u32 llc, u32 vllc, + struct scx_edq __arena *edq, + u32 slot, int steal, bool *saw) +{ + u64 peeked_raw; + struct flow_arena_task __arena *peeked_at; + s32 peek_pid; + struct task_struct *ph; + struct task_struct *p; + struct flow_task_ctx *lt; + u64 slice; + u64 popped_raw; + struct flow_arena_task __arena *popped_at; + s32 popped_pid; + if (!edq) + return 0; + if (slot > (u32)FLOW_MAX_LLCS) + return 0; + /* Peek with a hold so the node stays alive across the owner check. */ + peeked_raw = scx_edq_peek_hold(edq); + if (!peeked_raw) + return 0; + /* The pop address is also the wrapper address with the node at + * offset zero. This cast follows the queue API and does not + * launder task storage. */ + peeked_at = (struct flow_arena_task __arena *)peeked_raw; + peek_pid = READ_ONCE(peeked_at->pid); + ph = bpf_task_from_pid(peek_pid); + if (!ph) { + /* Dead head. Remove the exact node with no extra pop so a + * raced pop elsewhere does not lose its count. */ + int r = scx_edq_try_remove(edq, (scx_edq_task_t *)peeked_at); + scx_edq_task_drop((scx_edq_task_t *)peeked_at); + if (!r) + flow_queued_dec(vllc); + return 0; + } + if (!flow_cpu_allowed((s32)cpu, ph)) { + if (saw) + *saw = true; + flow_forward_from_peeked(ph, llc, slot); + bpf_task_release(ph); + scx_edq_task_drop((scx_edq_task_t *)peeked_at); + return 0; + } + bpf_task_release(ph); + scx_edq_task_drop((scx_edq_task_t *)peeked_at); + /* Claim the head with a hold. A raced pop may hand the next task, + * which is checked again below. */ + popped_raw = scx_edq_pop(edq, true); + if (!popped_raw) + return 0; + popped_at = (struct flow_arena_task __arena *)popped_raw; + popped_pid = READ_ONCE(popped_at->pid); + p = bpf_task_from_pid(popped_pid); + if (!p) { + scx_edq_task_drop((scx_edq_task_t *)popped_at); + flow_queued_dec(vllc); + return 0; + } + if (!flow_cpu_allowed((s32)cpu, p)) { + if (saw) + *saw = true; + flow_forward_from_peeked(p, llc, slot); + /* Keep the task alive through the fallback queue. */ + lt = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + slice = (u64)FLOW_SLICE_MIN_NS; + if (lt) { + u64 s = READ_ONCE(lt->slice_rem); + if (s) + slice = s; + } + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, slice, 0); + flow_stat_inc(llc, 2); + bpf_task_release(p); + scx_edq_task_drop((scx_edq_task_t *)popped_at); + return 0; + } + lt = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + slice = (u64)FLOW_SLICE_MIN_NS; + if (lt) { + u64 s = READ_ONCE(lt->slice_rem); + if (s) + slice = s; + } + scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, slice, 0); + flow_cpuperf_mark(cpu, false); + flow_stat_inc(llc, 1); + flow_queued_dec(vllc); + bpf_task_release(p); + scx_edq_task_drop((scx_edq_task_t *)popped_at); + if (steal) { + flow_stat_inc(llc, 3); + flow_stat_inc(llc, 5); + } + return 1; +} +static __always_inline int flow_drain_cpu(u32 cpu, u32 llc, u32 victim, int steal, bool *saw) +{ + struct scx_edq __arena *edq; + int vllc; + u32 vuse; + u32 slot; + if (!flow_cpu_ok(victim) || !flow_cpu_live(victim)) + return 0; + if (!flow_edqs) + return 0; + edq = &flow_edqs[victim]; + vllc = topo_cpu_to_llc_id(victim); + if (vllc < 0 || !flow_llc_ok((u32)vllc)) + return 0; + vuse = (u32)vllc; + /* The bound is a power of two, so a mask keeps the slot in + * range with no division. The fallback keeps the last slot. */ + slot = victim & ((u32)FLOW_MAX_LLCS - 1U); + /* Deadline order drain with insertion ties from the queue. */ + if (flow_try_move_edq(cpu, llc, vuse, edq, slot, steal, saw)) + return 1; + return 0; +} +void BPF_STRUCT_OPS(flow_dispatch, s32 cpu, struct task_struct *prev) +{ + u32 c; + u32 llc = 0; + u32 victim; + int v; + bool saw_unrunnable = false; + struct topo_iter hint_iter; + topo_ptr hint_node = 0; + topo_ptr walk = 0; + (void)prev; + scx_arena_subprog_init(); + if (cpu < 0) + return; + c = (u32)cpu; + if (!flow_cpu_ok(c) || !flow_cpu_live(c)) + return; + v = topo_cpu_to_llc_id(c); + if (v < 0 || !flow_llc_ok((u32)v)) + return; + llc = (u32)v; + if (topo_all && topo_contains(topo_all, c)) { + TOPO_FOR_EACH_NODE(&hint_iter, walk) { + if (topo_contains(walk, c)) { + hint_node = walk; + break; + } + } + } + if (flow_drain_cpu(c, llc, c, 0, &saw_unrunnable)) + return; + bpf_for(victim, 0, FLOW_MAX_CPUS) { + int vl; + if (victim == c) + continue; + if (!flow_cpu_live(victim)) + continue; + vl = topo_cpu_to_llc_id(victim); + if (vl < 0 || (u32)vl != llc) + continue; + if (flow_drain_cpu(c, llc, victim, 1, &saw_unrunnable)) + return; + } + bpf_for(victim, 0, FLOW_MAX_CPUS) { + int vl; + if (victim == c) + continue; + if (!flow_cpu_live(victim)) + continue; + vl = topo_cpu_to_llc_id(victim); + if (vl < 0 || !flow_llc_ok((u32)vl) || (u32)vl == llc) + continue; + /* Node identity comes from the tree with no per-CPU walk here. */ + if (!hint_node || !topo_contains(hint_node, victim)) + continue; + if (flow_drain_cpu(c, llc, victim, 1, &saw_unrunnable)) + return; + } + bpf_for(victim, 0, FLOW_MAX_CPUS) { + int vl; + if (victim == c) + continue; + if (!flow_cpu_live(victim)) + continue; + vl = topo_cpu_to_llc_id(victim); + if (vl < 0 || !flow_llc_ok((u32)vl) || (u32)vl == llc) + continue; + if (hint_node && topo_contains(hint_node, victim)) + continue; + if (flow_drain_cpu(c, llc, victim, 1, &saw_unrunnable)) + return; + } + { + struct task_struct *ph = __COMPAT_scx_bpf_dsq_peek((u64)FLOW_FALLBACK_DSQ); + if (ph) { + if (!flow_cpu_allowed((s32)c, ph)) { + flow_forward_from_peeked(ph, llc, (u32)FLOW_MAX_LLCS); + saw_unrunnable = true; + } else { + struct flow_task_ctx *pt; + u32 vllc = llc; + pt = bpf_task_storage_get(&task_ctx_stor, ph, 0, 0); + if (pt) { + u32 q = READ_ONCE(pt->llc_id); + if (flow_llc_ok(q)) + vllc = q; + } + if (scx_bpf_dsq_move_to_local((u64)FLOW_FALLBACK_DSQ, 0)) { + flow_stat_inc(llc, 1); + flow_cpuperf_mark(c, false); + flow_queued_dec(vllc); + return; + } + /* The head can run here but the move failed. + * Wake the owner so the task is not left idle. */ + flow_forward_from_peeked(ph, llc, (u32)FLOW_MAX_LLCS); + saw_unrunnable = true; + } + } + } + if (saw_unrunnable) { + struct task_struct *rh = __COMPAT_scx_bpf_dsq_peek((u64)FLOW_FALLBACK_DSQ); + if (rh) + flow_rekick_unrunnable(rh, llc); + } + /* No task moved, so the core stays idle at half. */ + flow_cpuperf_mark(c, true); +} +void BPF_STRUCT_OPS(flow_running, struct task_struct *p) +{ + s32 task_cpu = scx_bpf_task_cpu(p); + u32 cpu; + struct flow_task_ctx *t; + u32 llc = 0; + struct flow_running_state *rs; + u64 sl; + u64 ng; + int v; + if (task_cpu < 0) + return; + cpu = (u32)task_cpu; + if (!flow_cpu_ok(cpu)) + return; + scx_arena_subprog_init(); + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + if (!t) + return; + v = topo_cpu_to_llc_id(cpu); + if (v >= 0 && flow_llc_ok((u32)v)) + llc = (u32)v; + else if (flow_llc_ok(t->llc_id)) + llc = t->llc_id; + sl = p->scx.slice; + if (!sl) + sl = (u64)FLOW_SLICE_MIN_NS; + else if (sl > (u64)FLOW_SLICE_MIN_NS) + sl = (u64)FLOW_SLICE_MIN_NS; + rs = &flow_running_state[cpu]; + ng = rs->gen + 1; + if (ng == 0) + ng = 1; + rs->vtime = READ_ONCE(t->vtime); + rs->slice_rem = sl; + rs->gen = ng; + rs->llc_id = llc; + rs->vd = READ_ONCE(t->vd); + t->gen = ng; + t->slice_rem = sl; + t->llc_id = llc; + /* Running keeps the stored time and mirrors the due time beside it for gap checks. */ + scx_bpf_task_set_dsq_vtime(p, READ_ONCE(t->vd)); + /* The gauge was already dropped when the task moved to the local + * queue. Local inserts were never counted. Running only clears + * ownership. The core is busy now, so it runs at max. */ + __sync_fetch_and_and(&t->flags, (u32)~(u32)FLOW_FLAG_QUEUED); + flow_cpuperf_mark(cpu, false); +} +void BPF_STRUCT_OPS(flow_stopping, struct task_struct *p, bool runnable) +{ + s32 task_cpu = scx_bpf_task_cpu(p); + u32 cpu; + struct flow_task_ctx *t; + struct flow_running_state *rs; + u64 cur; + u64 have; + u64 used; + u64 total_used; + u64 old_b; + if (task_cpu < 0) + return; + cpu = (u32)task_cpu; + if (!flow_cpu_ok(cpu)) + return; + scx_arena_subprog_init(); + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + if (!t) + return; + rs = &flow_running_state[cpu]; + cur = p->scx.slice; + have = READ_ONCE(t->slice_rem); + if (!have) + have = (u64)FLOW_SLICE_MIN_NS; + if (cur > have) + cur = have; + if (cur >= have) + used = 0; + else + used = have - cur; + /* Track the run length before the tail charge, so the next due + * time prices what this run actually burnt. */ + if (cur < (u64)FLOW_SLICE_MIN_NS) + total_used = (u64)FLOW_SLICE_MIN_NS - cur; + else + total_used = 0; + old_b = flow_burst_clamp(READ_ONCE(t->burst_ns)); + t->burst_ns = flow_burst_update(READ_ONCE(t->burst_ns), total_used, cur, runnable); + /* Burnt time pays here into the stored time, scaled by the nice + * weight with saturation and mirrored as the stored time beside it. The + * tick already moved the left slice forward, so this charges only + * the tail past the last tick. A runnable yield with no burnt time + * still moves the stored time forward by one, so repeated yields + * cannot hold the queue head. */ + if (used) { + s64 nv = flow_fair_charge(READ_ONCE(t->vtime), used, + flow_nice_weight(p)); + t->vtime = nv; + scx_bpf_task_set_dsq_vtime(p, nv); + if (!cur) + flow_stat_inc(rs->llc_id, 9); + } else if (runnable) { + s64 nv = flow_fair_cap_add(READ_ONCE(t->vtime), 1); + t->vtime = nv; + scx_bpf_task_set_dsq_vtime(p, nv); + } + rs->slice_rem = cur; + t->slice_rem = cur; + /* A sleeping task leaves the core idle at half. A runnable task + * keeps its count with no frequency change. Reclaim at most one + * saved delta from burst past burnt with room plus live plus + * allowed and idle only kick. */ + if (runnable) + flow_stat_inc(rs->llc_id, 10); + else + flow_cpuperf_mark(cpu, true); + { + u64 saved = (old_b > total_used) ? (old_b - total_used) : 0; + flow_reclaim_kick(saved, READ_ONCE(rs->llc_id)); + } +} +void BPF_STRUCT_OPS(flow_tick, struct task_struct *p) +{ + s32 task_cpu = scx_bpf_task_cpu(p); + u32 cpu; + struct flow_task_ctx *t; + struct flow_running_state *rs; + u64 cur; + u64 have; + if (task_cpu < 0) + return; + cpu = (u32)task_cpu; + if (!flow_cpu_ok(cpu)) + return; + scx_arena_subprog_init(); + rs = &flow_running_state[cpu]; + cur = p->scx.slice; + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + if (!t) { + rs->slice_rem = cur; + return; + } + /* Charge the burnt delta, then move the due time with the burst + * left while inside it and the left slice past it in both the + * stored and running views, so the running horizon keeps the + * burst bound. Stopping later charges only the tail past this tick. */ + have = READ_ONCE(t->slice_rem); + if (cur && cur < have) { + u64 delta = have - cur; + u64 burnt = (cur < (u64)FLOW_SLICE_MIN_NS) ? + ((u64)FLOW_SLICE_MIN_NS - cur) : (u64)FLOW_SLICE_MIN_NS; + u64 b = flow_burst_clamp(READ_ONCE(t->burst_ns)); + u64 rem = (burnt < b) ? (b - burnt) : cur; + u32 w = flow_nice_weight(p); + s64 nv = flow_fair_charge(READ_ONCE(t->vtime), delta, w); + s64 nvd = flow_vd_for(nv, rem, w); + u64 saved = (b > burnt) ? (b - burnt) : 0; + u32 rllc = READ_ONCE(t->llc_id); + t->vtime = nv; + t->vd = nvd; + t->slice_rem = cur; + rs->vtime = nv; + rs->vd = nvd; + scx_bpf_task_set_dsq_vtime(p, nvd); + /* Reclaim at most one saved delta with room plus live plus + * allowed and idle only kick. */ + if (!flow_llc_ok(rllc)) + rllc = 0; + flow_reclaim_kick(saved, rllc); + } else if (!cur && have) { + /* The slice ran out at the tick. Keep the stored slice so + * stopping still charges the tail, but move the running horizon + * out by one slice so a wake can preempt at once with the two + * views diverged until stopping. Seed the burst to one slice + * for the next run. */ + u32 w = flow_nice_weight(p); + s64 nv = flow_fair_charge(READ_ONCE(t->vtime), have, w); + s64 nvd = flow_vd_for(nv, (u64)FLOW_SLICE_MIN_NS, w); + rs->vtime = nv; + rs->vd = nvd; + t->burst_ns = (u64)FLOW_SLICE_MIN_NS; + } + rs->slice_rem = cur; +} +void BPF_STRUCT_OPS(flow_set_cpumask, struct task_struct *p, const struct cpumask *mask) +{ + struct flow_task_ctx *t; + (void)mask; + if (!p) + return; + scx_arena_subprog_init(); + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + if (!t) + return; + if (READ_ONCE(t->flags) & (u32)FLOW_FLAG_QUEUED) { + s32 owner = flow_first_allowed(p); + u32 qllc = READ_ONCE(t->llc_id); + if (!flow_llc_ok(qllc)) + qllc = 0; + if (owner < 0) { + /* No usable CPU. The task waits in fallback + * until the mask widens, so count the skip. */ + flow_stat_inc(qllc, 8); + return; + } + if (!flow_cpu_allowed(owner, p) || !flow_cpu_live((u32)owner)) { + flow_stat_inc(qllc, 8); + return; + } + flow_kick_idle_only(owner, p, qllc); + flow_stat_inc(qllc, 11); + return; + } + if (p->flags & PF_EXITING) + t->slice_rem = (u64)FLOW_EXIT_SLICE_NS; + { + s32 tgt = flow_first_allowed(p); + int v; + if (tgt < 0) + return; + if (!flow_cpu_live((u32)tgt)) + return; + v = topo_cpu_to_llc_id((u32)tgt); + if (v < 0 || !flow_llc_ok((u32)v)) + return; + t->llc_id = (u32)v; + } +} +void BPF_STRUCT_OPS(flow_enable, struct task_struct *p) +{ + struct flow_task_ctx *t; + s64 v; + if (!p) + return; + t = bpf_task_storage_get(&task_ctx_stor, p, 0, BPF_LOCAL_STORAGE_GET_F_CREATE); + if (!t) + return; + v = (s64)p->scx.dsq_vtime; + t->vtime = v; + t->vd = v; + t->slice_rem = (u64)FLOW_SLICE_MIN_NS; + t->burst_ns = (u64)FLOW_SLICE_MIN_NS; + t->gen = 0; + t->llc_id = 0; + t->flags = 0; +} +s32 BPF_STRUCT_OPS_SLEEPABLE(flow_init_task, struct task_struct *p, struct scx_init_task_args *args) +{ + struct flow_task_ctx *t; + void __arena *mem; + struct flow_arena_task __arena *at; + (void)args; + if (!p) + return 0; + t = bpf_task_storage_get(&task_ctx_stor, p, 0, BPF_LOCAL_STORAGE_GET_F_CREATE); + if (t) { + t->vtime = 0; + t->vd = 0; + t->slice_rem = (u64)FLOW_SLICE_MIN_NS; + t->burst_ns = (u64)FLOW_SLICE_MIN_NS; + t->gen = 0; + t->llc_id = 0; + t->flags = 0; + scx_bpf_task_set_dsq_vtime(p, 0); + } + /* One arena node per task for the queue. The node sits at offset + * zero of the wrapper, so the queue address is also the wrapper + * address with no storage laundering. */ + mem = __scx_task_data(p); + if (mem) { + at = mem; + scx_edq_task_init((scx_edq_task_t *)at); + WRITE_ONCE(at->pid, p->pid); + WRITE_ONCE(at->pad, 0); + return 0; + } + mem = scx_task_alloc(p); + if (!mem) + return 0; + at = mem; + scx_edq_task_init((scx_edq_task_t *)at); + WRITE_ONCE(at->pid, p->pid); + WRITE_ONCE(at->pad, 0); + return 0; +} +void BPF_STRUCT_OPS(flow_exit_task, struct task_struct *p, struct scx_exit_task_args *args) +{ + struct flow_task_ctx *t; + void __arena *mem; + (void)args; + if (!p) + return; + scx_arena_subprog_init(); + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + mem = __scx_task_data(p); + if (!mem) { + if (t) { + u32 old = __sync_fetch_and_and(&t->flags, (u32)~(u32)FLOW_FLAG_QUEUED); + if (old & (u32)FLOW_FLAG_QUEUED) { + u32 dllc = READ_ONCE(t->llc_id); + if (!flow_llc_ok(dllc)) + dllc = 0; + flow_queued_dec(dllc); + } + } + return; + } + { + struct flow_arena_task __arena *at = mem; + u32 was_queued = 0; + u32 dllc = 0; + if (t) { + dllc = READ_ONCE(t->llc_id); + if (!flow_llc_ok(dllc)) + dllc = 0; + was_queued = __sync_fetch_and_and(&t->flags, + (u32)~(u32)FLOW_FLAG_QUEUED) & + (u32)FLOW_FLAG_QUEUED; + } + /* Drop the queue link when still present. Dequeue already + * dropped the gauge when it ran, so drop here only when + * the flag shows dequeue had not run yet. Detach then + * waits for holds before the free below. */ + scx_edq_task_fini((scx_edq_task_t *)at); + if (was_queued) + flow_queued_dec(dllc); + scx_edq_task_detach((scx_edq_task_t *)at); + scx_task_free(p); + } +} +s32 BPF_STRUCT_OPS_SLEEPABLE(flow_init) +{ + u64 n; + n = scx_bpf_nr_cpu_ids(); + scx_arena_subprog_init(); + if (n == 0) { + scx_bpf_error("no CPUs found"); + return -EINVAL; + } + if (n > (u64)FLOW_MAX_CPUS) { + scx_bpf_error("CPU count over bound"); + return -E2BIG; + } + /* The arena library must be ready before any queue is built. + * Userspace sets up the arena and the topology tree before load, + * so a missing tree fails closed here with no partial queues. */ + if (!topo_all) { + scx_bpf_error("topology tree missing"); + return -ENODEV; + } + /* Thread shape keeps the userspace seed with the source default on miss. */ + flow_ccx_prefer = 1; + if (n > 512ULL) { + scx_bpf_error("CPU count over bound"); + return -E2BIG; + } + /* One embedded queue per live CPU in deadline order bounded at + * 64 total. The table holds one entry per CPU id below the + * observed count, so every live id stays in range while the + * request stays within the static area cap. The array lives in + * arena memory for the queue address space. Fresh pages start + * zeroed, which is the empty queue state. */ + flow_edqs = scx_static_alloc(sizeof(struct scx_edq) * (size_t)n, + __alignof__(struct scx_edq)); + if (!flow_edqs) { + scx_bpf_error("queue alloc failed"); + return -ENOMEM; + } + { + s32 ret = scx_bpf_create_dsq((u64)FLOW_FALLBACK_DSQ, -1); + if (ret < 0 && ret != -EEXIST) { + scx_bpf_error("fallback dsq create failed"); + return ret; + } + } + return 0; +} +void BPF_STRUCT_OPS(flow_exit, struct scx_exit_info *info) +{ + UEI_RECORD(uei, info); + flow_edqs = 0; + scx_bpf_destroy_dsq((u64)FLOW_FALLBACK_DSQ); +} +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/edf.bpf.c b/scheds/experimental/scx_flow/src/bpf/edf.bpf.c deleted file mode 100644 index 2bdad02af4..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/edf.bpf.c +++ /dev/null @@ -1,340 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * EDF deadline plus eligibility plus drain for the core. - * - * Holds the burst predictor, the absolute deadline, the fair - * key, and the eligibility gate. Every task earns a deadline from the - * predictor else the hint period, and queue order uses the earlier of - * deadline plus virtual deadline with a 2ms lag bound. Eligibility - * gates every kick, so hogs pace while lagging tasks wake. Drain sums - * local plus node with saturation, so a busy node keeps the local tier - * without waiting. Depths read once feed the same drain, so enqueue - * bypass and tier escalation share one read. Runs under the caller. - * - * Copyright (c) 2026 Galih Tama - */ -/* True when one task still meets its deadline from the given time. */ -/* A zero deadline means no order yet, so the check passes with no */ -/* miss. A time past the deadline fails, so the caller rejoins a tier. */ -static __always_inline bool flow_deadline_ok(u64 deadline, - u64 now) -{ - if (deadline == 0) - return true; - if (flow_time_before(now, deadline)) - return true; - if (now == deadline) - return true; - return false; -} -/* Drain depth of one CPU as queued slices times the quantum. */ -/* Saturates on wrap, so a huge depth clamps instead of wrapping to */ -/* an idle view. A bad read drops to zero with no boost. */ -static __always_inline u64 flow_drain_ns(u64 dsq) -{ - s32 n = scx_bpf_dsq_nr_queued(dsq); - u64 depth; - if (n <= 0) - return 0; - depth = (u64)n; - if (depth > (u64)~0ULL / (u64)FLOW_QUANTUM_NS) - return (u64)~0ULL; - return depth * (u64)FLOW_QUANTUM_NS; -} -/* Drain nanos from a saved queued hint without a kfunc. */ -/* Non-positive hints read zero with no boost. Saturates on wrap, so a */ -/* huge depth clamps instead of wrapping to an idle view. */ -static __always_inline u64 flow_drain_from_q(s32 n) -{ - u64 depth; - if (n <= 0) - return 0; - depth = (u64)n; - if (depth > (u64)~0ULL / (u64)FLOW_QUANTUM_NS) - return (u64)~0ULL; - return depth * (u64)FLOW_QUANTUM_NS; -} -/** - * flow_cpu_drain_hint - combined drain from saved local plus node. - * @local_q: saved own local depth, non-positive means empty. - * @node_q: saved node depth, non-positive means empty. - * - * Sums both drains with saturation and no kfunc, so a busy node holds - * the local tier with no wait on the same reads as the bypass gate. - * - * Returns: combined drain in nanos. - */ -static __always_inline u64 flow_cpu_drain_hint(s32 local_q, s32 node_q) -{ - return flow_sat_add(flow_drain_from_q(local_q), - flow_drain_from_q(node_q)); -} -/** - * flow_cpu_drain - combined drain of one CPU as local plus node. - * @cpu: CPU id below the 1024 bound. - * - * Sums both depths with saturation, so a busy node holds the local - * tier with no wait. A missing node reads zero with no boost, and - * sparse nodes fold to zero. - * - * Outlined with noinline to keep verifier headroom and callers in meets - * plus fair plus BSF share one copy with no inline growth. - * - * Returns: combined drain in nanos. - */ -static __noinline u64 flow_cpu_drain(u32 cpu) -{ - u64 local = flow_drain_ns(flow_local_dsq(cpu)); - u32 node = flow_cpu_node((u32)cpu); - u64 shared = 0; - if (node < (u32)FLOW_MAX_NODES && - (u64)node < nr_node_ids) - shared = flow_drain_ns(flow_node_dsq(node)); - return flow_sat_add(local, shared); -} -/** - * flow_ready_before - test ready time against deadline with wrap safety. - * @ready: ready time in nanos, max fails closed. - * @deadline: absolute deadline in nanos. - * - * Fails closed on saturated ready, else wrap safe before plus equal, - * so a huge drain never reads as early with no wrap to the front. - * - * Outlined with noinline to share one compare copy across drain plus - * deadline checks with no inline growth and no order change. - * - * Returns: true when @ready falls before or on @deadline. - */ -static __noinline bool flow_ready_before(u64 ready, u64 deadline) -{ - if (ready == (u64)~0ULL) - return false; - if (flow_time_before(ready, deadline)) - return true; - if (ready == deadline) - return true; - return false; -} -/** - * flow_cpu_meets - test deadline against one CPU drain. - * @cpu: CPU id below the 1024 bound. - * @deadline: absolute deadline, zero meets all. - * @now: current time in nanos. - * - * Adds now plus the combined local plus node drain with saturation, - * so a huge drain fails closed with no wrap to an early view. The - * drain poll plus the compare split across two noinline calls, so the - * SSF plus BSF loops share one copy each with no inline growth. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - * - * Returns: true when the drain finishes before @deadline. - */ -static __noinline bool flow_cpu_meets(u32 cpu, - u64 deadline, u64 now) -{ - u64 drain; - u64 ready; - if (deadline == 0) - return true; - drain = flow_cpu_drain(cpu); - ready = flow_sat_add(now, drain); - return flow_ready_before(ready, deadline); -} -/** - * flow_cpu_meets_fair_hint - test fair time against saved drain. - * @local_q: saved own local depth, non-positive means empty. - * @node_q: saved node depth, non-positive means empty. - * @vtime: fair time, zero meets all. - * @now: current time in nanos. - * - * Mirrors the drain check for the fair key without a kfunc, so the bypass - * plus the tier choice share one read with the same order. A zero fair - * time means no fair order yet, so the check passes. - * - * Returns: true when the drain finishes before @vtime. - */ -static __always_inline bool flow_cpu_meets_fair_hint(s32 local_q, - s32 node_q, u64 vtime, u64 now) -{ - u64 drain; - u64 ready; - if (vtime == 0) - return true; - drain = flow_cpu_drain_hint(local_q, node_q); - ready = flow_sat_add(now, drain); - return flow_ready_before(ready, vtime); -} -/* - * RED guarantee core for the flow scheduler. - * - * Holds the residual and exceeding time with fixed tolerance used - * only for the guarantee. The deadline bounds the check without - * shaping vruntime. A newcomer with zero exceed passes at once, else - * the newcomer itself is tested as the O(1) victim with cost past the - * fixed 256us Emax plus cost past the exceed plus never critical, else - * the newcomer admits. A full least value scan stays a noted - * alternative, so the verifier keeps one pass. Newcomer-pays trades - * exact victim choice for a single check with tiers-empty reclaim - * covering starvation below. The reject queue stays value ordered - * outside dispatch, and a global saved credit at or past the fixed - * 256us Emax reclaims one head with positive laxity. Runs under the - * caller without a lock here, so the verifier stays small. - */ -/** - * flow_red_gate - shared victim gate for one newcomer cost. - * @cost: remaining worst cost in nanos from burst else slice. - * @exceed: newcomer exceeding time in nanos, zero admits at once. - * @emax: fixed Emax in nanos at 256us. - * @is_crit: true marks latency-critical that never rejects. - * @deadline: newcomer absolute deadline, zero admits at once. - * - * Checks cost past Emax plus cost past exceed with no critical, so the - * newcomer itself covers the overload as the O(1) victim. A full least - * value scan stays a noted alternative with no verifier growth. - * - * Returns: true when the newcomer should reject, else false. - */ -static __always_inline bool flow_red_gate(u64 cost, u64 exceed, u64 emax, - bool is_crit, u64 deadline) -{ - if (exceed == 0) - return false; - if (is_crit) - return false; - if (deadline == 0) - return false; - if (cost <= emax) - return false; - if (cost <= exceed) - return false; - return true; -} -/** - * flow_red_should_reject - test one newcomer for RED reject. - * @deadline: newcomer absolute deadline in nanos. - * @now: current time in nanos. - * @avg: burst average in nanos, zero for no history. - * @slice: stored slice in nanos, zero for no history. - * @is_crit: true marks latency-critical via the unified latency test - * with zero tolerance, false for hard batch. - * - * Costs burst else slice else quantum once, tolerates the fixed 64us - * for hard batch only, then shares the gate below. Latency-critical - * keeps zero with no slack. Like fair.c, the bound paces order, unlike - * rt.c, no fixed priority holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so miss plus open plus pinned share one read with no inline - * growth. - * - * Returns: true when the newcomer should reject to the value ordered - * queue, else false for admit. - */ -static __noinline bool flow_red_should_reject(u64 deadline, u64 now, - u64 avg, u32 slice, bool is_crit) -{ - u64 cost = flow_red_cost(avg, slice); - u64 tol = flow_red_tol(is_crit); - u64 emax = (u64)FLOW_RED_EMAX_NS; - s64 resid = flow_red_residual(deadline, now, cost); - u64 exceed = flow_red_exceed(resid, tol); - /* Newcomer tests itself, so the deadline order holds with no */ - /* before check past equality. Shares the gate with reclaim, so */ - /* both agree with one copy. */ - return flow_red_gate(cost, exceed, emax, is_crit, deadline); -} -/** - * flow_red_reclaim_ok - test reclaim from one global credit. - * @saved: global completer credit in nanos from completions. - * @exceed: head exceeding time in nanos. - * @laxity: head laxity in nanos, zero means no room. - * - * Reclaims when the global credit passes the fixed 256us Emax and - * covers the head exceed with positive laxity. The global credit funds - * the retry without shaping shares. - * - * Returns: true when the head may rejoin. - */ -static __always_inline bool flow_red_reclaim_ok(u64 saved, u64 exceed, - u64 laxity) -{ - u64 emax = (u64)FLOW_RED_EMAX_NS; - if (saved < emax) - return false; - if (laxity == 0) - return false; - if (saved < exceed) - return false; - return true; -} -/* Global reclaim credit from completer saved deltas. */ -/* Stopping adds the unused cost minus delta on completions with */ -/* saturation at 1s, so one completion funds a later retry without */ -/* keeping a task pointer. Dispatch peeks this credit for the head check */ -/* and reserves the exceed else the fixed 256us Emax before a move, so the */ -/* completer delta funds the retry without using head state. Compare and */ -/* swap retries stop at four, so a lost race only delays one pass. */ -/* Add one saved delta to the global reclaim credit with saturation. */ -static __always_inline void flow_credit_add(u64 delta) -{ - u32 key = 0; - u64 *slot; - s32 i; - if (delta == 0) - return; - slot = bpf_map_lookup_elem(&reclaim_credit_stor, &key); - if (!slot) - return; - bpf_for(i, 0, 4) { - u64 cur = READ_ONCE(*slot); - u64 nxt = flow_sat_add(cur, delta); - u64 old; - if (nxt > (u64)FLOW_PRED_MAX_NS) - nxt = (u64)FLOW_PRED_MAX_NS; - old = __sync_val_compare_and_swap(slot, cur, nxt); - if (old == cur) - break; - } -} -/* Peek the global reclaim credit with zero on miss. */ -static __always_inline u64 flow_credit_peek(void) -{ - u32 key = 0; - u64 *slot = bpf_map_lookup_elem(&reclaim_credit_stor, &key); - if (!slot) - return 0; - return READ_ONCE(*slot); -} -/* Consume one reclaim funding with floor at zero. */ -/* Takes the exceed when past zero else the fixed 256us Emax, so a zero */ -/* exceed still spends the bound. Fails closed when short without */ -/* spending, so a lost compare and swap race retries up to four times */ -/* then delays one pass. The reclaim caller reserves before the move and */ -/* falls back without reserve when tiers hold no work, so the consume */ -/* stays strict while the reclaim keeps one move per pass. */ -static __always_inline bool flow_credit_consume(u64 exceed) -{ - u32 key = 0; - u64 *slot = bpf_map_lookup_elem(&reclaim_credit_stor, &key); - s32 i; - u64 emax = (u64)FLOW_RED_EMAX_NS; - if (!slot) - return false; - bpf_for(i, 0, 4) { - u64 cur = READ_ONCE(*slot); - u64 need = exceed ? exceed : emax; - u64 nxt; - u64 old; - if (cur < need) - return false; - if (cur < emax) - return false; - nxt = cur - need; - old = __sync_val_compare_and_swap(slot, cur, nxt); - if (old == cur) - return true; - } - return false; -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.c deleted file mode 100644 index 3086afb7ac..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.c +++ /dev/null @@ -1,362 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue op with RED admission plus strict PRIQ. - * - * Every wakeup earns one EDF deadline from the burst predictor else - * the hint period plus one virtual deadline from vruntime plus slice - * over weight, then passes the RED check with residual plus exceed - * plus tolerance used only for the guarantee. The deadline bounds the - * check without shaping vruntime. A zero exceed admits at once, a - * critical exceed admits without a swap, else the newcomer itself is - * tested as the O(1) victim with cost past the fixed 256us Emax plus - * cost past the exceed plus never critical, else the newcomer admits and a full least - * value scan stays a noted alternative. Queue order uses the strict EDF - * key of the earlier of the two times in three PRIQ tiers (local plus - * node plus machine) plus value ordered reject plus steal for five total - * with insert vtime, so urgent tasks still win while hogs fall behind - * with lag bounds. Fresh waits earn a dynamic slice from the saturated - * remaining time clamped to 10us plus 1ms, while misses hold else floor - * only and rejoin via the same tier escalation re-derived with a fresh - * deadline plus skip aging. Tasks join direct only when all tiers - * including the reject hold no work or the target still drains before - * the key with an empty machine and an empty reject, so no earlier key - * waits behind this arrival. Missed tasks rejoin a tier queue with a - * fresh deadline plus a miss count and one idle kick without waiting, - * else the reject queue on overload. Pinned tasks wait in a tier queue - * with wait set and one idle kick, else the reject queue on overload. - * Exiting tasks run at once on the task CPU without queueing. The gate - * runs first for all other arrivals, so a stale CPU or a moved task fails - * closed with one counter. The predictor average rises fast with shift 3 - * plus falls slow with shift 4 and the deviation widens fast with shift 2 - * plus narrows slow with shift 3 plus half deviation margin from stopping, - * so short bursts earn tight deadlines without a table walk. Vruntime advances by scaled - * service with one divide, and the CPU minimum folds forward on every - * charge, so fairness tracks service without a table. Every tier join - * counts one admit and every RED overload counts one RED reject without - * double counting the gate. The exiting, bypass, tier idle, and preempt - * paths form the kick points, so every wait meets at most one kick. A - * direct preempt needs unified latency with probation plus an eligible lat - * arrival against a batch owner plus a 100us margin lead with more than - * 100us still left on the owner, so near ties and nearly done owners - * never bounce while one kick per wait stays. The owner paces on start - * plus inherit cur without a fresh quantum, so the tail tracks the stored - * slice. A preempted head resumes via lifecycle only with start plus cur - * clamped to 10us plus 100us for latency else 1ms with inherit on bad - * start plus tail plus history, so the same head resumes with its - * leftover. Latency-critical slice carryover keeps the unused quantum, so - * short bursts earn nearer keys. Strict slice writes run here before the - * key. Fresh waits earn the dynamic remaining clamp, misses hold else - * floor only, and rotations inherit zero. Slice expiry paces the rest - * without stamping here. Local plus node depths read once, so the drain - * gated bypass and the combined drain tier escalation share one read. See - * intf.h for the deadline plus fairness helpers and dispatch.bpf.c for - * the tier scans. - * - * The op holds the target plus insert plus miss plus open plus kick - * helpers in enqueue/ with the fair plus clamp noinline on scalar input - * plus the pinned plus miss plus open plus place plus kick noinline on - * tail pointers, so the verifier stays small. - * - * Copyright (c) 2026 Galih Tama - */ -#include "enqueue/target.bpf.c" -#include "enqueue/insert.bpf.c" -#include "enqueue/miss.bpf.c" -#include "enqueue/open.bpf.c" -#include "enqueue/kick.bpf.c" - -void BPF_STRUCT_OPS(flow_enqueue, struct task_struct *p, - u64 enq_flags) -{ - struct flow_task_ctx *tctx; - s32 sel; - s32 cpu = -1; - bool pinned = false; - u64 now; - u64 deadline; - u64 vtime; - u32 hint; - u32 hint_w = (u32)FLOW_WEIGHT_BASE; - u64 avg = 0; - u64 dev = 0; - bool is_reenq = false; - u64 hoist_vr = 0; - s32 hoist_lag = 0; - u64 hoist_min = 0; - bool hoist_elig = false; - struct flow_open_out open_out = { 0 }; - /* Requeue plus last slice expiry bypass the cgroup hint read plus */ - /* the occupant preempt lookup, so slice rotation stays cheap. The */ - /* stored hint plus hint weight in the task state carry the period */ - /* plus the share, and the owner paces at slice expiry with no */ - /* extra kick. The requeue case is rare beside fresh wakeups, so */ - /* it stays unlikely. */ - if (unlikely(enq_flags & (SCX_ENQ_REENQ | SCX_ENQ_LAST))) - is_reenq = true; - /* Exiting tasks run at once on the task CPU with no queue wait. */ - /* The gate never runs here, so exiting work stays exempt. Exiting */ - /* is rare, so it stays unlikely. */ - if (unlikely(p->flags & PF_EXITING)) { - s32 tgt = scx_bpf_task_cpu(p); - if (flow_cpu_ok(p, tgt)) { - struct flow_cpu_state *tst; - scx_bpf_dsq_insert(p, - (u64)SCX_DSQ_LOCAL_ON | (u64)tgt, - (u64)FLOW_QUANTUM_NS, enq_flags); - tst = flow_cpu((u32)tgt); - if (tst && - READ_ONCE(tst->running_pid) == 0) { - scx_bpf_kick_cpu(tgt, - SCX_KICK_IDLE); - flow_count_kick(); - } - return; - } - } - tctx = NULL; - sel = p->scx.selected_cpu; - pinned = flow_task_pinned(p); - now = flow_now(); - /* The gate runs first without creating state, so stale CPUs or */ - /* moved tasks fail closed. The lookup stays read only here, and the */ - /* create follows only on pass. Rejects are rare, so they stay */ - /* unlikely. Gate misses join the value ordered reject queue without */ - /* waiting, so no path needs a tail queue and no insert touches the */ - /* kernel global queue. */ - if (unlikely(!flow_entry_ok(sel, p, 0) && !flow_entry_ok( - scx_bpf_task_cpu(p), p, 0))) { - struct flow_task_ctx *lctx = flow_lookup(p); - u32 gval; - flow_gate_reject(); - if (lctx) - lctx->wait_at = now; - /* Gate misses thread the stored share plus unified latency when */ - /* state holds, else batch value when absent with probation. */ - if (lctx) { - u32 gw = READ_ONCE(lctx->weight); - u32 ghw = READ_ONCE(lctx->hint_w); - u64 gavg = (u64)READ_ONCE(lctx->avg_ns); - u64 gdev = (u64)READ_ONCE(lctx->dev_ns); - u32 ghint = READ_ONCE(lctx->hint_us); - u32 geff = flow_task_effective_weight(gw, ghw); - bool gcrit = flow_is_lat(gavg, gdev, ghint, 0, 0, - geff); - gval = flow_red_value(geff, gcrit); - } else { - gval = flow_red_value((u32)FLOW_WEIGHT_BASE, false); - } - flow_overflow_insert(p, enq_flags, gval); - flow_kick_idle_allowed(p, sel); - return; - } - tctx = flow_get(p); - /* Tasks without state join a tier queue with a fallback deadline */ - /* as the fair time plus an idle kick. The kick targets one idle */ - /* allowed CPU without preempting, so a waiting task wakes cleanly. */ - /* The gate already passed, so this path adds no gate count. Missing */ - /* state is rare, so it stays unlikely. */ - if (unlikely(!tctx)) { - s32 mc = flow_pick_target(p, sel); - u32 mh = 0; - u32 mhw = (u32)FLOW_WEIGHT_BASE; - u64 mdl; - /* No state means no predictor, so the hint weight threads */ - /* with BASE-only task share and batch value with probation. */ - flow_task_hint_weight(p, &mh, &mhw); - mdl = flow_fallback_deadline(now, mh); - if (flow_cpu_ok(p, mc)) { - flow_tier_insert(p, mc, mdl, now); - flow_count_admit(); - } else { - u32 meff = flow_task_effective_weight( - (u32)FLOW_WEIGHT_BASE, mhw); - flow_gate_reject(); - flow_overflow_insert(p, enq_flags, - flow_red_value(meff, false)); - } - flow_kick_idle_allowed(p, sel); - return; - } - /* Ensure the fairness fields hold sane defaults without a divide. */ - /* A zero weight means no history, so the neutral share applies. */ - /* A zero slice means no history, so the fixed quantum applies. */ - { - u32 w = READ_ONCE(tctx->weight); - u32 s = READ_ONCE(tctx->slice_ns); - if (w == 0) - __sync_lock_test_and_set(&tctx->weight, - (u32)FLOW_WEIGHT_BASE); - if (s == 0) - __sync_lock_test_and_set(&tctx->slice_ns, - (u32)FLOW_QUANTUM_NS); - } - /* Pinned tasks wait in a tier queue with wait set and one idle kick. */ - /* Pinning is rare, so it stays unlikely. The tier keeps mask wins */ - /* on drain, so a pinned task still meets only its allowed CPU. */ - /* The pinned wait runs Outlined on scalars with no tail struct, so */ - /* the open path keeps verifier headroom with the same fair time */ - /* plus miss plus clamp plus kick and no stack spill. */ - if (unlikely(pinned)) { - flow_enqueue_pinned(p, tctx, sel, now, enq_flags); - return; - } - cpu = flow_pick_target(p, sel); - /* No live CPU waits in the value ordered reject queue with an idle */ - /* kick. Homeless work waits there with the stored share plus value */ - /* order and enq flags kept, so no insert touches the kernel global */ - /* queue. */ - if (!flow_cpu_ok(p, cpu)) { - u32 hw = READ_ONCE(tctx->weight); - u32 hw_hint = READ_ONCE(tctx->hint_w); - u32 hhint = READ_ONCE(tctx->hint_us); - u64 h_avg = (u64)READ_ONCE(tctx->avg_ns); - u64 h_dev = (u64)READ_ONCE(tctx->dev_ns); - u64 h_sleep = flow_sleep_ns(READ_ONCE(tctx->wait_at), now, - h_avg); - u32 heff = flow_task_effective_weight(hw, hw_hint); - bool hcrit = flow_is_lat(h_avg, h_dev, hhint, h_sleep, 0, - heff); - flow_gate_reject(); - tctx->wait_at = now; - flow_overflow_insert(p, enq_flags, flow_red_value(heff, hcrit)); - flow_kick_idle_allowed(p, sel); - return; - } - if (READ_ONCE(tctx->deadline) == 0 && READ_ONCE(tctx->wait_at) == 0) - flow_count_insert(); - /* One predictor period plus one EDF deadline plus one fair time. */ - /* A zero average means no history, so the fresh hint period */ - /* applies with the default when the hint is zero. Later wakeups */ - /* add average plus deviation with saturation, so short bursts earn */ - /* tight deadlines with no table walk. The hint stores with no lag, */ - /* while the predictor shapes only the deadline once history exists. */ - /* A miss on the last deadline counts before the new deadline, so */ - /* the miss count tracks wall completion past deadline. Requeues */ - /* reuse the stored hint plus hint weight with no lookup and no */ - /* cgroup acquire, so slice rotation keeps the heavy share with no */ - /* neutral cliff. The reuse may stay stale across one slice when */ - /* the share changed, so the new values show on the next fresh */ - /* wakeup with no order break. A cgroup move shows the same way */ - /* on the next fresh wakeup with no order break. Vruntime clamps within the lag bound of the target */ - /* minimum with a compare and swap, so sleepers gain no more than */ - /* one boost with no storm. The effective share stacks task times */ - /* hint over 128 on the stack, so every task earns a clamped share */ - /* with no special case and the hint weight stored alongside. */ - if (is_reenq) { - hint = READ_ONCE(tctx->hint_us); - hint_w = READ_ONCE(tctx->hint_w); - } else { - /* One cache plus one row read for both values, so the fresh */ - /* path pays no double lookup with no behavior change. The */ - /* task base stays stored, only the hint reads here. */ - flow_task_hint_weight(p, &hint, &hint_w); - } - avg = (u64)READ_ONCE(tctx->avg_ns); - dev = (u64)READ_ONCE(tctx->dev_ns); - tctx->hint_us = hint; - tctx->hint_w = hint_w; - /* Clamp vruntime within the lag bound of the target minimum */ - /* through the shared helper with no order change. */ - flow_clamp_to_min(tctx, (u32)cpu); - /* Miss rejoins self-contained through the outlined helper with the */ - /* same fresh deadline plus held slice plus RED plus tier plus kick, */ - /* so the open path below handles only fresh plus requeue compute */ - /* with no inline growth and the same counts. */ - { - struct flow_miss_tail miss = { - .tctx = tctx, - .cpu = cpu, - .sel = sel, - .now = now, - .enq_flags = enq_flags, - .hint = hint, - .hint_w = hint_w, - .avg = avg, - .dev = dev, - }; - if (flow_enqueue_miss(p, &miss)) - return; - } - deadline = flow_pred_deadline(now, avg, dev, hint); - __sync_lock_test_and_set(&tctx->deadline, deadline); - /* Open fair time runs outlined with out fields for RED plus place */ - /* plus kick, so fresh plus requeue share one divide copy with no */ - /* inline growth and the same order. */ - { - struct flow_open_tail open = { - .tctx = tctx, - .deadline = deadline, - .now = now, - .enq_flags = enq_flags, - .hint = hint, - .hint_w = hint_w, - .avg = avg, - .dev = dev, - .is_reenq = is_reenq, - }; - flow_enqueue_open(&open, &open_out); - vtime = open_out.vtime; - } - /* RED admission through the shared outlined helper. A reject needs */ - /* cost past the fixed 256us Emax plus cost past the exceed with no */ - /* critical, else the newcomer admits to the tier path. The deadline */ - /* bounds the check without shaping vruntime. Critical follows the */ - /* unified latency and cost uses the pre-clamp slice for fresh */ - /* waits, so RED and slice agree. A full O(n) least value scan stays */ - /* a noted alternative, so the verifier keeps one pass. Shares one */ - /* copy with miss plus pinned, so the dispatcher stays thin. */ - { - u32 csl = READ_ONCE(tctx->slice_ns); - bool ccrit = open_out.is_lat; - u32 cost_sl = csl; - struct flow_reject_tail rej; - if (open_out.is_fresh && !(enq_flags & SCX_ENQ_PREEMPT)) - cost_sl = open_out.pre_slice; - rej.tctx = tctx; - rej.deadline = deadline; - rej.now = now; - rej.avg = avg; - rej.slice = cost_sl; - rej.is_lat = ccrit; - rej.hint_w = hint_w; - rej.enq_flags = enq_flags; - rej.sel = sel; - if (flow_enqueue_reject(p, &rej)) - return; - } - /* Every tier plus bypass join counts one admit without double */ - /* counting, so the counters track joins while tier queues hold */ - /* misses plus pins. */ - flow_count_admit(); - /* Eligibility read takes vruntime plus lag plus minimum once per */ - /* wait. The bypass and the kick share this one gate, so hogs pace */ - /* with one minimum read. Dropped reads keep the same order. */ - hoist_vr = READ_ONCE(tctx->vruntime); - hoist_lag = READ_ONCE(tctx->vlag); - hoist_min = flow_cpu_min((u32)cpu); - hoist_elig = flow_eligible(hoist_vr, hoist_min, hoist_lag); - /* Idle direct bypass plus tier join run outlined without changing */ - /* order, so the drain gate and the tier escalation share one read. */ - /* A direct bypass returns at once with one kick, else the tier join */ - /* falls into the single kick tail. The deadline plus admit already */ - /* hold, so order plus counters stay correct without extra waiting. */ - /* Strict fair order gates the bypass with eligibility plus drain, so */ - /* hogs pace through tiers without a direct jump and one kick per wait */ - /* stays. A stale hint only races a concurrent tier join, since */ - /* dispatch still drains in fair order with mask wins on the next pass. */ - /* Arrival sleep threads the pre-overwrite gap, so kick agrees with */ - /* RED plus slice on the same latency with no second wait read. */ - { - struct flow_enqueue_tail tail; - tail.cpu = cpu; - tail.vtime = vtime; - tail.now = now; - tail.enq_flags = enq_flags; - tail.arr_sleep = open_out.sleep_ns; - tail.is_reenq = is_reenq; - tail.hoist_elig = hoist_elig; - if (flow_enqueue_place(p, &tail)) - return; - flow_enqueue_kick(p, &tail); - } -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.h b/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.h new file mode 100644 index 0000000000..eac44cf8c2 --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/enqueue.bpf.h @@ -0,0 +1,479 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Queueing for the flow scheduler. + * + * Shared tasks join the queue of the constrained target in deadline order. + * The upstream queue keeps insertion order for equal deadlines, so the code + * adds no extra tie handling. Pinned tasks join the local queue in order + * with a single slice. Exiting tasks use the local queue when allowed and + * the owner queue otherwise with a short slice. Tasks that have no usable + * CPU join the fallback queue in FIFO order. The queue key is the floored + * virtual deadline saturated to unsigned with negatives at zero. Shared + * inserts move past the per LLC floor and add the burst scaled nice + * step to the floored time through the shared charge path. Tasks with + * no usable CPU skip the floor and stay FIFO. The charge scales with + * the nice weight. Each shared enqueue checks the idle flag first, then the + * running deadline on the target for an earlier deadline win. Idle targets take + * an idle wake and never preempt. Each running instance kicks at most once. + * A deadline win kicks for preempt on a win, else it counts a skip with no wake. A wake goes only to an idle target, else it counts a + * skip with no wake. The kernel idle flag decides the idle wake. + * Preempts stay in the same LLC with an allowed live target. Local + * inserts are not counted in the shared gauge. Shared and fallback + * inserts count the gauge, and fallback inserts also count fallback. + * Dequeue drops the gauge on cancel. Masks + * are checked again before each wake, so a task is never kicked toward + * a CPU outside its current mask. The queue node lives in arena memory + * beside the task with the pid for owner lookup. Rejects fall back to + * the FIFO queue with no extra probe. Overload admits with live plus + * tolerance plus bound plus room plus cap and evicts at most one ready + * task with the latest deadline in the lowest band through a bounded + * scan of at most eight. Queues hold + * bounded at 64 total with eligibility always eligible. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_ENQUEUE_BPF_H +#define __FLOW_ENQUEUE_BPF_H +#include "intf.h" +#include "maps.bpf.h" +#include "stats.bpf.h" +#include "fair.bpf.h" +#include "select.bpf.h" +#include +#include +#include +static __always_inline struct scx_edq __arena *flow_edq_for_cpu(s32 tgt) +{ + if (tgt < 0 || !flow_cpu_ok((u32)tgt)) + return 0; + if (!flow_cpu_live((u32)tgt)) + return 0; + if (!flow_edqs) + return 0; + return &flow_edqs[(u32)tgt]; +} +static __always_inline u64 flow_edq_deadline(s64 vd) +{ + if (vd < 0) + return 0; + return (u64)vd; +} +static __always_inline int flow_llc_for_cpu(s32 tgt, u32 *out) +{ + int v; + if (tgt < 0 || !flow_cpu_ok((u32)tgt)) + return -1; + v = topo_cpu_to_llc_id((u32)tgt); + if (v < 0 || !flow_llc_ok((u32)v)) + return -1; + *out = (u32)v; + return 0; +} +static __always_inline void flow_kick_idle_only(s32 tgt, struct task_struct *p, u32 llc) +{ + if (tgt < 0) { + flow_stat_inc(llc, 8); + return; + } + if (!flow_cpu_allowed(tgt, p)) { + flow_stat_inc(llc, 8); + return; + } + if (!flow_cpu_live((u32)tgt)) { + flow_stat_inc(llc, 8); + return; + } + if (!scx_bpf_test_and_clear_cpu_idle(tgt)) { + flow_stat_inc(llc, 8); + return; + } + scx_bpf_kick_cpu(tgt, SCX_KICK_IDLE); + flow_stat_inc(llc, 7); +} +static __always_inline void flow_kick_vd(s32 tgt, struct task_struct *p, u32 llc, s64 new_vd) +{ + struct flow_running_state *rs; + u64 rgen; + u32 rllc; + u32 last; + s64 run_vd; + u32 c; + if (tgt < 0 || !p || !flow_cpu_ok((u32)tgt) || !flow_cpu_allowed(tgt, p) || + !flow_cpu_live((u32)tgt)) { + flow_stat_inc(llc, 8); + return; + } + if (scx_bpf_test_and_clear_cpu_idle(tgt)) { + scx_bpf_kick_cpu(tgt, SCX_KICK_IDLE); + flow_stat_inc(llc, 7); + return; + } + /* Reassert the bound on the index used below so the verifier + * keeps the range across the calls above. The barrier keeps the + * compiler from folding the check away with the earlier one. */ + c = (u32)tgt; + asm volatile ("" : "+r" (c)); + if (c >= (u32)FLOW_MAX_CPUS) + return; + rs = &flow_running_state[c]; + rgen = READ_ONCE(rs->gen); + rllc = READ_ONCE(rs->llc_id); + if (!rgen || !flow_llc_ok(rllc) || rllc != llc) { + flow_stat_inc(llc, 8); + return; + } + last = READ_ONCE(rs->pad); + if ((u32)rgen == last) { + flow_stat_inc(llc, 8); + return; + } + run_vd = READ_ONCE(rs->vd); + if (!(new_vd < run_vd)) { + flow_stat_inc(llc, 8); + return; + } + if (__sync_val_compare_and_swap(&rs->pad, last, (u32)rgen) != last) { + flow_stat_inc(llc, 8); + return; + } + scx_bpf_kick_cpu(tgt, SCX_KICK_PREEMPT); + flow_stat_inc(llc, 6); +} +/* Bounded evict one for overload. Scans at most eight ready tasks on the + * target queue and keeps the latest deadline in the lowest implicit band. + * The victim moves to the fallback queue in FIFO order and the caller + * admits the newcomer. Ready means still queued. Compare only with no + * divide and a single remove, so one pass never holds across the host. */ +static __always_inline bool flow_try_evict_one(struct scx_edq __arena *edq, + s64 new_vd, u32 new_band, u32 llc) +{ + u64 best_raw = 0; + s32 best_pid = -1; + u32 best_band = 4U; + s64 best_vd = 0; + bool have_best = false; + int i; + if (!edq) + return false; + for (i = 0; i < 8; i++) { + u64 raw = 0; + struct flow_arena_task __arena *at; + s32 pid; + struct task_struct *ph; + struct flow_task_ctx *vt; + u32 vb; + s64 vvd; + int r = scx_edq_try_peek_nth_hold(edq, (u32)i, &raw); + if (r || !raw) + break; + at = (struct flow_arena_task __arena *)raw; + pid = READ_ONCE(at->pid); + ph = bpf_task_from_pid(pid); + if (!ph) { + scx_edq_task_drop((scx_edq_task_t *)at); + continue; + } + vt = bpf_task_storage_get(&task_ctx_stor, ph, 0, 0); + if (!vt) { + bpf_task_release(ph); + scx_edq_task_drop((scx_edq_task_t *)at); + continue; + } + if (!(READ_ONCE(vt->flags) & (u32)FLOW_FLAG_QUEUED)) { + bpf_task_release(ph); + scx_edq_task_drop((scx_edq_task_t *)at); + continue; + } + vb = flow_band_for_weight(flow_nice_weight(ph)); + vvd = READ_ONCE(vt->vd); + bpf_task_release(ph); + if (!have_best || vb < best_band || + (vb == best_band && vvd > best_vd)) { + if (have_best && best_raw) + scx_edq_task_drop((scx_edq_task_t *)best_raw); + best_raw = raw; + best_pid = pid; + best_band = vb; + best_vd = vvd; + have_best = true; + } else { + scx_edq_task_drop((scx_edq_task_t *)at); + } + } + if (!have_best || !best_raw || best_pid < 0) + return false; + if (best_band > new_band) { + scx_edq_task_drop((scx_edq_task_t *)best_raw); + return false; + } + if (best_band == new_band && best_vd < new_vd) { + scx_edq_task_drop((scx_edq_task_t *)best_raw); + return false; + } + { + struct flow_arena_task __arena *best_at = + (struct flow_arena_task __arena *)best_raw; + int r = scx_edq_try_remove(edq, (scx_edq_task_t *)best_at); + scx_edq_task_drop((scx_edq_task_t *)best_at); + if (r) + return false; + } + { + struct task_struct *vp = bpf_task_from_pid(best_pid); + struct flow_task_ctx *lt; + u64 slice = (u64)FLOW_SLICE_MIN_NS; + if (!vp) { + flow_queued_dec(llc); + return true; + } + lt = bpf_task_storage_get(&task_ctx_stor, vp, 0, 0); + if (lt) { + u64 s = READ_ONCE(lt->slice_rem); + if (s) + slice = s; + } + scx_bpf_dsq_insert(vp, (u64)FLOW_FALLBACK_DSQ, slice, 0); + flow_stat_inc(llc, 2); + bpf_task_release(vp); + return true; + } +} +void BPF_STRUCT_OPS(flow_enqueue, struct task_struct *p, u64 enq_flags) +{ + s32 task_cpu; + s32 tgt; + u32 llc = 0; + u32 cpu_ok = 0; + s64 raw_v; + bool pinned = false; + struct flow_task_ctx *t; + u32 old_flags; + bool no_cpu; + if (!p) + return; + scx_arena_subprog_init(); + task_cpu = scx_bpf_task_cpu(p); + if (task_cpu < 0) + task_cpu = (s32)bpf_get_smp_processor_id(); + tgt = flow_constrained_target(task_cpu, p); + if (tgt >= 0 && flow_cpu_live((u32)tgt)) { + u32 tmp = 0; + if (!flow_llc_for_cpu(tgt, &tmp)) + llc = tmp; + cpu_ok = 1; + } + /* The bound is a power of two, so a mask keeps the index in + * range with no division. */ + llc &= ((u32)FLOW_MAX_LLCS - 1U); + no_cpu = !cpu_ok || tgt < 0; + raw_v = (s64)p->scx.dsq_vtime; + pinned = flow_is_pinned(p); + t = bpf_task_storage_get(&task_ctx_stor, p, 0, BPF_LOCAL_STORAGE_GET_F_CREATE); + if (!t) { + if (p->flags & PF_EXITING) { + if (tgt >= 0 && flow_cpu_allowed(tgt, p)) { + u64 ldsq = (u64)SCX_DSQ_LOCAL_ON | (u64)(u32)tgt; + scx_bpf_dsq_insert(p, ldsq, (u64)FLOW_EXIT_SLICE_NS, enq_flags); + flow_kick_idle_only(tgt, p, llc); + return; + } + { + struct scx_edq __arena *edq = no_cpu ? 0 : flow_edq_for_cpu(tgt); + bool fell = true; + if (edq) { + void __arena *mem = __scx_task_data(p); + if (mem) { + struct flow_arena_task __arena *at = mem; + u64 dl = flow_edq_deadline(raw_v); + WRITE_ONCE(at->pid, p->pid); + if (scx_edq_nr_queued(edq) < (u64)FLOW_QUEUE_CAP) { + int ret = scx_edq_insert(edq, + (scx_edq_task_t *)at, + dl, 0, + (u64)FLOW_EXIT_SLICE_NS); + if (!ret) + fell = false; + } + } + } + if (fell) + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, + (u64)FLOW_EXIT_SLICE_NS, enq_flags); + flow_stat_inc(llc, 0); + if (fell) + flow_stat_inc(llc, 2); + flow_kick_idle_only(tgt, p, llc); + return; + } + } + goto insert_only; + } + /* Local placements run before ownership is taken. A task on a + * local queue is not counted in the shared gauge, so it leaves + * without the queued bit. Shared and fallback inserts take the + * bit below and count the gauge together. */ + if (p->flags & PF_EXITING) { + if (tgt >= 0 && flow_cpu_allowed(tgt, p)) { + u64 ldsq = (u64)SCX_DSQ_LOCAL_ON | (u64)(u32)tgt; + scx_bpf_dsq_insert(p, ldsq, (u64)FLOW_EXIT_SLICE_NS, enq_flags); + flow_kick_idle_only(tgt, p, llc); + return; + } + } + if (pinned) { + s32 first = flow_first_allowed(p); + if (first < 0) + first = tgt; + if (first >= 0 && flow_cpu_allowed(first, p)) { + u32 pllc = llc; + u32 tmp = 0; + if (!flow_llc_for_cpu(first, &tmp)) + pllc = tmp; + { + u64 ldsq = (u64)SCX_DSQ_LOCAL_ON | (u64)(u32)first; + scx_bpf_dsq_insert(p, ldsq, (u64)FLOW_SLICE_MIN_NS, enq_flags); + flow_kick_idle_only(first, p, pllc); + return; + } + } + } + old_flags = __sync_fetch_and_or(&t->flags, (u32)FLOW_FLAG_QUEUED); + if (old_flags & (u32)FLOW_FLAG_QUEUED) { + flow_fb_inc(llc, 4); + return; + } + if (p->flags & PF_EXITING) { + struct scx_edq __arena *edq = no_cpu ? 0 : flow_edq_for_cpu(tgt); + bool fell = true; + t->llc_id = llc; + if (edq) { + void __arena *mem = __scx_task_data(p); + if (mem) { + struct flow_arena_task __arena *at = mem; + u64 dl = flow_edq_deadline(raw_v); + WRITE_ONCE(at->pid, p->pid); + if (scx_edq_nr_queued(edq) < (u64)FLOW_QUEUE_CAP) { + int ret = scx_edq_insert(edq, + (scx_edq_task_t *)at, + dl, 0, + (u64)FLOW_EXIT_SLICE_NS); + if (!ret) + fell = false; + } + } + } + if (fell) + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, + (u64)FLOW_EXIT_SLICE_NS, enq_flags); + flow_stat_inc(llc, 0); + if (fell) + flow_stat_inc(llc, 2); + flow_kick_idle_only(tgt, p, llc); + return; + } + if (pinned) { + t->llc_id = llc; + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, (u64)FLOW_SLICE_MIN_NS, enq_flags); + flow_stat_inc(llc, 0); + flow_stat_inc(llc, 2); + /* No owner queue took the task. Kick self when idle so the + * fallback head is peeked again soon. */ + flow_kick_idle_only((s32)bpf_get_smp_processor_id(), p, llc); + return; + } + { + /* Shared inserts join the order past the floor. Tasks with no + * usable CPU skip the floor, and fallback inserts stay FIFO. + * Queues hold bounded at 64 total with pure deadline order + * and a single kick. Overload admits with live plus tolerance + * plus bound plus room plus cap and evicts at most one ready + * task with the latest deadline in the lowest band through a + * bounded scan of at most eight. Rejects fall back to FIFO. */ + s64 base = READ_ONCE(t->vtime); + u32 w = flow_nice_weight(p); + s64 floored = no_cpu ? base : flow_seq_floor(llc, base); + s64 vd = flow_vd_for(floored, READ_ONCE(t->burst_ns), w); + u64 slice_len = (u64)FLOW_SLICE_MIN_NS; + struct scx_edq __arena *edq = no_cpu ? 0 : flow_edq_for_cpu(tgt); + bool fell = true; + bool can_queue = false; + void __arena *mem = 0; + if (edq) { + u64 cost = flow_red_cost(READ_ONCE(t->burst_ns)); + u64 exceed = flow_red_exceed(cost); + u64 nr = scx_edq_nr_queued(edq); + bool over = flow_red_gate(cost, exceed, nr); + mem = __scx_task_data(p); + if (mem && !over && nr < (u64)FLOW_QUEUE_CAP) + can_queue = true; + else if (mem && (over || nr >= (u64)FLOW_QUEUE_CAP)) { + u32 nb = flow_band_for_weight(w); + if (flow_try_evict_one(edq, vd, nb, llc)) { + if (scx_edq_nr_queued(edq) < + (u64)FLOW_QUEUE_CAP) + can_queue = true; + } + } + } + t->vtime = floored; + t->vd = vd; + t->slice_rem = slice_len; + t->llc_id = llc; + /* Mirror the due time beside the stored time so later reads see the same due time for order checks. */ + scx_bpf_task_set_dsq_vtime(p, vd); + /* Rejects fall back to FIFO with no extra probe. */ + if (can_queue) { + struct flow_arena_task __arena *at = mem; + u64 dl = flow_edq_deadline(vd); + WRITE_ONCE(at->pid, p->pid); + { + int ret = scx_edq_insert(edq, + (scx_edq_task_t *)at, + dl, 0, slice_len); + if (!ret) + fell = false; + } + } + if (fell) + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, slice_len, enq_flags); + flow_stat_inc(llc, 0); + if (fell) + flow_stat_inc(llc, 2); + if (no_cpu) { + /* No usable CPU. Kick self when idle so the + * fallback head is peeked again soon. */ + flow_kick_idle_only((s32)bpf_get_smp_processor_id(), p, llc); + return; + } + flow_kick_vd(tgt, p, llc, vd); + return; + } +insert_only: + { + u64 sl = (u64)FLOW_SLICE_MIN_NS; + scx_bpf_dsq_insert(p, (u64)FLOW_FALLBACK_DSQ, sl, enq_flags); + flow_stat_inc(llc, 0); + flow_stat_inc(llc, 2); + flow_kick_idle_only(tgt, p, llc); + return; + } +} +void BPF_STRUCT_OPS(flow_dequeue, struct task_struct *p, u64 deq_flags) +{ + struct flow_task_ctx *t; + u32 old; + (void)deq_flags; + if (!p) + return; + t = bpf_task_storage_get(&task_ctx_stor, p, 0, 0); + if (!t) + return; + old = __sync_fetch_and_and(&t->flags, (u32)~(u32)FLOW_FLAG_QUEUED); + if (old & (u32)FLOW_FLAG_QUEUED) { + u32 dllc = READ_ONCE(t->llc_id); + if (!flow_llc_ok(dllc)) + dllc = 0; + flow_queued_dec(dllc); + } +} +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue/insert.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue/insert.bpf.c deleted file mode 100644 index 2dafd8ff1e..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue/insert.bpf.c +++ /dev/null @@ -1,500 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue tier inserts plus fair time for the flow scheduler. - * - * Holds the local plus node plus machine plus overflow inserts with - * the shared drain escalation plus the shared fair time plus the lag - * clamp plus the pinned wait path. Queue order uses the earlier of the - * deadline plus the virtual deadline, so urgent tasks still win while - * hogs fall behind with lag bounds. Tasks join direct when the target - * can drain before the shared home, so no task waits for a busy CPU - * while shared room stays open. Strict PRIQ holds without favoring batch, - * reusing the tier escalation plus the slowest sufficient pick. Every - * tier join counts one admit, so the counters track joins. Runs under - * the caller. - * - * Copyright (c) 2026 Galih Tama - */ -/* Insert one task into the local tier of one CPU with fair order. */ -static __always_inline void flow_local_insert(struct task_struct *p, s32 cpu, u64 vtime) -{ - scx_bpf_dsq_insert_vtime(p, flow_local_dsq((u32)cpu), (u64)FLOW_QUANTUM_NS, vtime, 0); -} -/* Insert one task into the shared tier of one node with fair order. */ -static __always_inline void flow_node_insert(struct task_struct *p, u32 node, u64 vtime) -{ - scx_bpf_dsq_insert_vtime(p, flow_node_dsq(node), (u64)FLOW_QUANTUM_NS, vtime, 0); -} -/* Insert one task into the machine tier with fair order. */ -static __always_inline void flow_machine_insert(struct task_struct *p, u64 vtime) -{ - scx_bpf_dsq_insert_vtime(p, flow_machine_dsq(), (u64)FLOW_QUANTUM_NS, vtime, 0); -} -/* Insert one task into the reject queue value ordered without FIFO. */ -/* Orders by decreasing value through the kernel priority queue, so the */ -/* greatest value drains first on reclaim. Value picks the order without */ -/* shaping vruntime. Runs outside dispatch with reclaim only, so dispatch */ -/* tiers stay strict. */ -static __always_inline void flow_overflow_insert(struct task_struct *p, u64 enq_flags, u32 value) -{ - u64 key = flow_reject_key(value); - scx_bpf_dsq_insert_vtime(p, flow_overflow_dsq(), (u64)FLOW_QUANTUM_NS, key, enq_flags); -} -/** - * flow_take_sleep - true sleep plus wait stamp in one shared copy. - * @tctx: task state with wait stamp to read plus overwrite. - * @now: current time in nanos. - * @avg: burst average in nanos for the gap minus burst. - * - * Isolates the true gap as now minus wait minus burst with wrap safety, - * then stamps wait to now, so queue plus run never look like sleep and - * later reads see one snapshot. Shares one sleep plus store copy, so - * miss plus open plus pinned keep no inline growth and the same gap. - * - * Outlined with noinline to keep verifier headroom on the enqueue path. - * - * Returns: sleep time in nanos, zero when unknown. - */ -static __noinline u64 flow_take_sleep(struct flow_task_ctx *tctx, u64 now, - u64 avg) -{ - u64 sleep; - if (!tctx) - return 0; - sleep = flow_sleep_ns(READ_ONCE(tctx->wait_at), now, avg); - tctx->wait_at = now; - return sleep; -} -/** - * flow_tier_insert_hint - tier join from saved combined drain. - * @p: task to join, null is ignored by the insert helpers. - * @cpu: target CPU for the drain gate. - * @vtime: fair time used for order plus the drain gate. - * @now: current time in nanos. - * @local_q: saved own local depth, non-positive means empty. - * @node_q: saved node depth, non-positive means empty. - * - * Takes the local tier when the saved combined drain finishes before - * the fair time, else the node tier when live, else the machine tier, so - * a busy node keeps the task local. Escalation follows the combined drain - * with mask wins on dispatch drain. Strict PRIQ holds without favoring - * batch, so the earliest key wins in every tier. Like fair.c, the - * earliest key wins, unlike rt.c, no fixed priority holds. - */ -static __always_inline void flow_tier_insert_hint(struct task_struct *p, - s32 cpu, u64 vtime, u64 now, s32 local_q, s32 node_q) -{ - u32 node; - bool drain_ok = false; - if (cpu >= 0) - drain_ok = flow_cpu_meets_fair_hint(local_q, node_q, vtime, - now); - if (cpu >= 0 && drain_ok) { - flow_local_insert(p, cpu, vtime); - return; - } - if (cpu >= 0) { - node = flow_cpu_node((u32)cpu); - if (node < (u32)FLOW_MAX_NODES && (u64)node < nr_node_ids) { - flow_node_insert(p, node, vtime); - return; - } - } - flow_machine_insert(p, vtime); -} -/* Join one task to the tier its target drains first with fair order. */ -/* Reads local plus node once here, so callers without saved depths pay */ -/* the same reads. The local queue takes the task when the target drains */ -/* local plus node before the fair key, else the node queue when live, */ -/* else the machine queue, so no task waits for a busy CPU while shared */ -/* room stays open. */ -static __always_inline void flow_tier_insert(struct task_struct *p, s32 cpu, u64 vtime, u64 now) -{ - s32 local_q = 0; - s32 node_q = 0; - if (cpu >= 0) { - u32 node; - local_q = scx_bpf_dsq_nr_queued(flow_local_dsq((u32)cpu)); - node = flow_cpu_node((u32)cpu); - if (node < (u32)FLOW_MAX_NODES && (u64)node < nr_node_ids) - node_q = scx_bpf_dsq_nr_queued(flow_node_dsq(node)); - } - flow_tier_insert_hint(p, cpu, vtime, now, local_q, node_q); -} -/** - * flow_make_fair - strict EDF key from task state plus deadline plus hint. - * @tctx: task state with vruntime plus weight plus slice. - * @deadline: absolute EDF deadline in nanos. - * @hint_w: hint share with base for neutral. - * - * Reads vruntime plus weight plus slice once and stacks the effective - * share of task times hint over 128, so pinned, miss, and open paths - * share one divide copy with the same order. The slice holds the dynamic - * remaining clamp on fresh waits else the held charge on misses, so near - * deadlines earn near virtual times without a band jump. RED cost stays - * on the pre-clamp slice, so admit plus order agree. The strict key - * drives tier plus kick while placement tests the deadline. - * - * Returns: strict key as the earlier of deadline plus virtual deadline. - * - * Outlined with noinline to keep verifier headroom and pinned plus miss - * plus open paths share one divide copy. - */ -static __noinline u64 flow_make_fair(struct flow_task_ctx *tctx, - u64 deadline, u32 hint_w) -{ - u64 vr = READ_ONCE(tctx->vruntime); - u32 sl = READ_ONCE(tctx->slice_ns); - u32 task_w = READ_ONCE(tctx->weight); - u32 eff; - u64 vd; - if (task_w == 0) - task_w = (u32)FLOW_WEIGHT_BASE; - eff = flow_task_effective_weight(task_w, hint_w); - if (sl == 0) - sl = (u32)FLOW_QUANTUM_NS; - vd = flow_virt_deadline(vr, (u64)sl, eff); - return flow_edf_key(deadline, vd); -} -/** - * flow_clamp_to_min - clamp vruntime within the lag bound of a CPU. - * @tctx: task state with vruntime to fold forward. - * @cpu: target CPU whose minimum bounds the boost. - * - * Folds a vruntime more than 2ms behind the minimum forward to minimum - * minus 2ms with saturation at zero, so long sleepers wake only slightly - * early. Uses a compare and swap, so a concurrent charge win keeps the - * winner. - * - * Outlined with noinline to keep verifier headroom and pinned plus open - * paths share one clamp copy. - */ -static __noinline void flow_clamp_to_min(struct flow_task_ctx *tctx, - u32 cpu) -{ - u64 min = flow_cpu_min(cpu); - u64 cur = READ_ONCE(tctx->vruntime); - u64 bound = (u64)FLOW_VLAG_MAX_NS; - u64 floor = 0; - if (min > bound) - floor = min - bound; - if (min > bound && cur < floor) - __sync_val_compare_and_swap(&tctx->vruntime, cur, floor); -} -/** - * flow_enqueue_cap_key - cap one fair key at now plus one period. - * @vtime: strict fair time from the EDF key, zero keeps zero. - * @now: current time in nanos. - * - * Caps far keys at now plus one period with saturation, so far keys - * never starve past the bound while placement tests the deadline. - * Like fair.c, the cap paces service, unlike rt.c, no fixed priority - * holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so miss plus open plus pinned share the same bound with no - * inline growth. - * - * Returns: capped key in nanos. - */ -static __noinline u64 flow_enqueue_cap_key(u64 vtime, u64 now) -{ - u64 bound = flow_sat_add(now, (u64)FLOW_PERIOD_NS); - if (vtime != 0 && bound != (u64)~0ULL && - !flow_time_before(vtime, bound) && vtime != bound) - vtime = bound; - return vtime; -} -/** - * flow_enqueue_is_lat - unified latency for one wait from stored fields. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @hint: flat period hint in micros, zero for no hint. - * @sleep_ns: true sleep gap from the caller wrap-safe helper. - * @eff: effective share from task times hint over 128. - * - * Runs the unified base plus ext test with probation, so newcomers - * stay batch with no stored bit and RED plus slice agree on the same - * gap. The caller stacks task times hint over 128, so the shared - * test stays at five args with no stack spill. Like fair.c, the test - * paces service, unlike rt.c, no fixed priority holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so miss plus open plus pinned share the same test with no - * inline growth. - * - * Returns: true when latency holds, else false for batch. - */ -static __noinline bool flow_enqueue_is_lat(u64 avg, u64 dev, u32 hint, - u64 sleep_ns, u32 eff) -{ - return flow_is_lat(avg, dev, hint, sleep_ns, 0, eff); -} -/** - * struct flow_reject_tail - RED reject args for the shared reject path. - * @tctx: task state with weight for the value order. - * @deadline: newcomer absolute deadline in nanos. - * @now: current time in nanos. - * @avg: burst average in nanos, zero for no history. - * @slice: cost slice in nanos for the RED check. - * @is_lat: unified latency for the RED check. - * @hint_w: hint share with base for neutral. - * @enq_flags: enqueue flags threaded to the reject insert. - * @sel: selected CPU hint for the idle kick. - * - * Bundles the RED state plus time plus flags, so the shared reject - * takes one pointer like the miss plus open tails with no stack args - * and the same order. - */ -struct flow_reject_tail { - struct flow_task_ctx *tctx; - u64 deadline; - u64 now; - u64 avg; - u32 slice; - bool is_lat; - u32 hint_w; - u64 enq_flags; - s32 sel; -}; -/** - * flow_enqueue_reject - RED reject one newcomer to the value queue. - * @p: task to reject, passed to the reject insert. - * @t: reject tail with state plus deadline plus time plus flags. - * - * Runs the shared O(1) newcomer check through the outlined helper, so - * a reject needs cost past the fixed 256us Emax plus cost past the - * exceed with no critical. A reject joins the value ordered queue with - * one idle kick, else admits with no insert. Queue order uses value - * without shaping vruntime. Like fair.c, the earliest key wins, - * unlike rt.c, no fixed priority holds. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so miss plus open plus pinned share the same reject with no - * inline growth and the same counts. - * - * Returns: true when rejected with insert plus kick, else false. - */ -static __noinline bool flow_enqueue_reject(struct task_struct *p, - const struct flow_reject_tail *t) -{ - struct flow_task_ctx *tctx; - u64 deadline; - u64 now; - u64 avg; - u32 slice; - bool is_lat; - u32 hint_w; - if (!p || !t) - return false; - tctx = t->tctx; - if (!tctx) - return false; - deadline = t->deadline; - now = t->now; - avg = t->avg; - slice = t->slice; - is_lat = t->is_lat; - hint_w = t->hint_w; - if (!flow_red_should_reject(deadline, now, avg, slice, is_lat)) - return false; - { - u32 tw = READ_ONCE(tctx->weight); - u32 eff = flow_task_effective_weight(tw, hint_w); - flow_count_red_reject(); - flow_overflow_insert(p, t->enq_flags, - flow_red_value(eff, is_lat)); - flow_kick_idle_allowed(p, t->sel); - } - return true; -} -/** - * flow_enqueue_pinned - enqueue one pinned task in tier order. - * @p: task to enqueue, pinned to one CPU without a scan. - * @tctx: task state with vruntime plus deadline plus predictor. - * @sel: selected CPU hint, negative falls back to first allowed. - * @now: current time in nanos. - * @enq_flags: enqueue flags threaded to the reject insert plus requeue - * pace derived from REENQ plus LAST with no extra arg. - * - * Pinned tasks wait in a tier queue with wait set and one idle kick. - * Homeless pins without a live CPU wait in the value ordered reject queue - * like open tasks with the stored share plus value order, so no pin - * parks in the machine tier without a live CPU. Queue order uses the - * effective share of task times hint over 128. Vruntime clamps to the - * target minimum minus 2ms like open tasks, and a past deadline counts - * one miss before the fresh deadline, so pins track lag plus overload - * without stale reuse. The tier keeps mask wins on drain, so a pinned - * task still meets only its allowed CPU. Takes scalars with no tail - * struct, so the verifier tracks registers with no stack spill. - * - * Outlined with noinline to keep verifier headroom and the cold pinned - * path leaves the open path with the same order. - */ -static __noinline void flow_enqueue_pinned(struct task_struct *p, - struct flow_task_ctx *tctx, s32 sel, u64 now, u64 enq_flags) -{ - bool is_reenq = !!(enq_flags & (SCX_ENQ_REENQ | SCX_ENQ_LAST)); - s32 pc = flow_pick_target(p, sel); - u32 ph; - u32 phint_w = (u32)FLOW_WEIGHT_BASE; - u64 pavg; - u64 pdev; - u64 pdl; - u64 pvt; - bool pmiss = false; - bool pin_is_lat = false; - u32 pin_pre = 0; - bool have_pin = false; - u64 pin_sleep_hold = 0; - if (is_reenq) { - ph = READ_ONCE(tctx->hint_us); - phint_w = READ_ONCE(tctx->hint_w); - } else { - /* One cache plus one row read for both values, so the fresh */ - /* pinned path skips a double lookup. The task base stays stored, */ - /* only the hint reads. */ - flow_task_hint_weight(p, &ph, &phint_w); - } - tctx->hint_us = ph; - tctx->hint_w = phint_w; - /* Clamp vruntime within the lag bound of the pinned target through */ - /* the shared helper. */ - if (pc >= 0 && flow_cpu_ok(p, pc)) - flow_clamp_to_min(tctx, (u32)pc); - /* A past deadline counts one miss before the fresh deadline, so */ - /* pinned overload tracks like open tasks. The miss holds the stored */ - /* slice else floors it to 10us via the shared miss helper, and a */ - /* fresh wait earns the dynamic remaining clamp, so the key stays */ - /* strict with skip aging in the miss count. */ - if (READ_ONCE(tctx->deadline) && - flow_missed(READ_ONCE(tctx->deadline), now)) { - flow_count_miss(tctx); - pmiss = true; - } - /* Pinned tasks recompute the deadline from the predictor plus hint */ - /* without stale reuse, so a pinned requeue tracks recent bursts like */ - /* open tasks. A zero average means no history, so the hint period */ - /* applies. */ - pavg = (u64)READ_ONCE(tctx->avg_ns); - pdev = (u64)READ_ONCE(tctx->dev_ns); - pdl = flow_pred_deadline(now, pavg, pdev, ph); - __sync_lock_test_and_set(&tctx->deadline, pdl); - /* Latency recompute per enqueue without a stored bit, so 72B holds. */ - /* A fresh pinned wait clamps the slice to 100us plus caps the key */ - /* to now plus max 4ms else slice plus 100us via the strict key, */ - /* while RED stays on the original deadline. Like fair.c, the cap */ - /* paces service, unlike rt.c, no fixed priority holds. A preempted */ - /* pinned head resumes via lifecycle only without a slice rewrite */ - /* here, so the stored leftover stays. Sleep isolates the true gap as */ - /* now minus wait minus burst, and in-tier keys cap at now plus one */ - /* period for the starvation bound. */ - if (pmiss) { - u64 pm_sleep = flow_take_sleep(tctx, now, pavg); - pin_sleep_hold = pm_sleep; - __sync_lock_test_and_set(&tctx->slice_ns, - flow_slice_miss_hold(READ_ONCE(tctx->slice_ns))); - pvt = flow_make_fair(tctx, pdl, phint_w); - pvt = flow_enqueue_cap_key(pvt, now); - } else if (!is_reenq) { - u64 p_sleep = flow_take_sleep(tctx, now, pavg); - bool p_is_lat; - u32 p_pre; - u32 p_slice; - u64 p_vt; - u32 p_eff; - /* No stable uclamp field in this task view, so fail open to */ - /* zero without an extra map, and probation holds through both */ - /* helpers, so newcomers stay batch. Shares the latency copy */ - /* with miss plus open. */ - p_eff = flow_task_effective_weight(READ_ONCE(tctx->weight), - phint_w); - p_is_lat = flow_enqueue_is_lat(pavg, pdev, ph, p_sleep, - p_eff); - p_pre = flow_slice_for(pdl, now); - p_pre = flow_slice_tier_cap(p_pre, pavg, pdev, p_is_lat); - p_slice = flow_slice_lat_clamp(p_pre, p_is_lat); - pin_is_lat = p_is_lat; - pin_pre = p_pre; - have_pin = true; - pin_sleep_hold = p_sleep; - if (enq_flags & SCX_ENQ_PREEMPT) { - pvt = flow_make_fair(tctx, pdl, phint_w); - } else { - u64 p_dl; - __sync_lock_test_and_set(&tctx->slice_ns, p_slice); - p_vt = flow_make_fair(tctx, pdl, phint_w); - if (p_is_lat) { - p_dl = flow_lat_deadline(now, p_slice); - pvt = flow_edf_key(p_vt, p_dl); - } else { - pvt = p_vt; - } - } - pvt = flow_enqueue_cap_key(pvt, now); - } else { - u64 pr_sleep = flow_take_sleep(tctx, now, pavg); - pin_sleep_hold = pr_sleep; - __sync_lock_test_and_set(&tctx->slice_ns, - flow_slice_inherit(READ_ONCE(tctx->slice_ns))); - pvt = flow_make_fair(tctx, pdl, phint_w); - pvt = flow_enqueue_cap_key(pvt, now); - } - /* RED on the pinned join through the shared outlined helper, so a */ - /* reject needs cost past the fixed 256us Emax plus cost past the */ - /* exceed with no critical. Tolerance aids only the guarantee */ - /* without shaping the key. Critical follows the unified latency */ - /* through the shared test and cost uses the pre-clamp slice for */ - /* fresh waits. */ - { - u32 psl = READ_ONCE(tctx->slice_ns); - bool pcrit; - u32 pcost_sl; - struct flow_reject_tail rej; - if (have_pin) { - pcrit = pin_is_lat; - if (!(enq_flags & SCX_ENQ_PREEMPT)) - pcost_sl = pin_pre; - else - pcost_sl = psl; - } else { - u32 p_eff = flow_task_effective_weight( - READ_ONCE(tctx->weight), phint_w); - pcrit = flow_enqueue_is_lat(pavg, pdev, ph, - pin_sleep_hold, p_eff); - pcost_sl = psl; - } - rej.tctx = tctx; - rej.deadline = pdl; - rej.now = now; - rej.avg = pavg; - rej.slice = pcost_sl; - rej.is_lat = pcrit; - rej.hint_w = phint_w; - rej.enq_flags = enq_flags; - rej.sel = sel; - if (flow_enqueue_reject(p, &rej)) - return; - } - if (flow_cpu_ok(p, pc)) { - flow_tier_insert(p, pc, pvt, now); - flow_count_admit(); - flow_kick_idle_allowed(p, sel); - return; - } - { - u32 ptw = READ_ONCE(tctx->weight); - u32 peff; - bool pcrit; - if (ptw == 0) - ptw = (u32)FLOW_WEIGHT_BASE; - peff = flow_task_effective_weight(ptw, phint_w); - pcrit = flow_enqueue_is_lat(pavg, pdev, ph, pin_sleep_hold, - peff); - flow_gate_reject(); - tctx->wait_at = now; - flow_overflow_insert(p, enq_flags, - flow_red_value(peff, pcrit)); - flow_kick_idle_allowed(p, sel); - } -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue/kick.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue/kick.bpf.c deleted file mode 100644 index 1f4b7e037c..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue/kick.bpf.c +++ /dev/null @@ -1,347 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue direct bypass plus kick for the flow scheduler. - * - * Holds the idle direct bypass with the hoisted drain gate plus the - * strict one kick per wait tail. An idle target takes the task straight - * to its local queue with one idle kick per wait and no preempt, so - * wakeups take a bounded direct jump past the tier plus dispatch hop - * with one insert plus one kick and no zero-cost bypass. The bypass - * runs only when empty plus earliest-only holds incl the reject queue - * and the local plus node plus machine plus reject tiers hold no - * queued work or the target still drains local plus node before the - * strict key with an empty machine plus an empty reject, so an earlier key never waits behind - * this arrival in a tier queue. Rechecks keep the same order with one - * hoist. Strict fair order gates the bypass with eligibility plus - * drain, so hogs pace through tiers with no direct jump and one kick - * per wait stays. A direct preempt needs unified latency with - * probation plus an eligible lat arrival against a batch owner plus a - * 100us margin lead with more than 100us still left on the owner, so - * near ties plus nearly done owners never bounce while one kick per - * wait stays with no storm. Arrival plus occupant latency use unified - * base plus ext with probation and no extra task reads. Exiting tasks stay - * exempt with no queue wait and no gate. Runs under the caller with no - * lock. - * - * Copyright (c) 2026 Galih Tama - */ -/* Tail args for the Outlined place plus kick with one call each. */ -/* Bundles the live target plus the fair time plus the enqueue time */ -/* plus the insert flags plus the requeue pace plus the hoisted */ -/* eligibility plus the arrival sleep read before the wait overwrite, */ -/* so each Outlined tail takes one pointer with no stack args and the */ -/* bypass plus the kick share the same single reads. */ -struct flow_enqueue_tail { - s32 cpu; - u64 vtime; - u64 now; - u64 enq_flags; - u64 arr_sleep; - bool is_reenq; - bool hoist_elig; -}; -/** - * flow_enqueue_place - bypass idle direct or join a tier queue. - * @p: task to place on its live target. - * @t: tail args with target plus fair time plus time plus flags plus - * eligibility, hoisted once by the caller with no second poll. - * - * Idle direct bypass only when tiers hold no earlier strict key. An idle - * target takes the task straight to its local queue with one idle kick - * per wait and no preempt, so wakeups take a bounded direct jump past - * the tier plus dispatch hop with one insert plus one kick. The bypass runs only when the local plus node plus machine plus reject tiers hold - * no queued work or the target still drains local plus node before the - * strict key with an empty machine plus an empty reject, so an earlier key never waits behind this arrival in - * a tier queue. The value ordered reject stays in scope here and a queued - * vetoes the bypass with no jump. Local plus node depths hoist once here, so the empty - * gate plus the drain gate share the same reads with no second poll. - * The bypass inserts straight to local with no tier move count, so - * admits vs moves drift by the bypass count with no loss while dispatch - * moves still count each tier. The TOCTOU between the empty hints and - * the direct insert only races a concurrent tier join with no loss, - * since dispatch still drains in fair order with mask wins on the next - * pass. Tier join through the hoisted combined drain escalation takes - * the local tier when the hoisted drain finishes before the fair key, - * else the node tier when live, else the machine tier, so no task waits - * for a busy CPU while shared room stays open. Queue order plus tier - * choice use the fair time while placement tests the deadline, so the - * slowest sufficient CPU wins. Mask wins on dispatch drain with the - * same order. - * - * Returns: true when the direct bypass took with one kick, else false - * after a tier join with the kick left to the caller. - * - * Outlined with noinline to keep verifier headroom and the bypass plus - * tier join leaves the kick tail with no inline growth and the same - * order plus the same counts. - */ -static __noinline bool flow_enqueue_place(struct task_struct *p, - struct flow_enqueue_tail *t) -{ - s32 cpu = t->cpu; - u64 vtime = t->vtime; - u64 now = t->now; - struct flow_cpu_state *dst = flow_cpu((u32)cpu); - if (dst && READ_ONCE(dst->running_pid) == 0) { - u64 own = flow_local_dsq((u32)cpu); - u32 node = flow_cpu_node((u32)cpu); - bool node_valid = false; - u64 node_dsq = 0; - s32 lq = 0; - s32 nq = 0; - s32 mq = 0; - s32 oq = 0; - bool tiers_empty = false; - bool drain_ok = false; - if (node < (u32)FLOW_MAX_NODES && - (u64)node < nr_node_ids) { - node_dsq = flow_node_dsq(node); - node_valid = true; - } - /* Hoist local plus node plus machine plus reject once with */ - /* signed hints, so the empty gate plus the drain gate plus */ - /* the tier escalation share one read with no repoll. The */ - /* reject queue stays in scope here by design and a queued */ - /* reject vetoes the bypass, so an earlier value never waits */ - /* behind this arrival. Like fair.c, the earliest key wins, */ - /* unlike rt.c, no fixed priority holds. */ - lq = scx_bpf_dsq_nr_queued(own); - mq = scx_bpf_dsq_nr_queued(flow_machine_dsq()); - oq = scx_bpf_dsq_nr_queued(flow_overflow_dsq()); - if (node_valid) - nq = scx_bpf_dsq_nr_queued(node_dsq); - if (lq <= 0 && mq <= 0 && oq <= 0 && (!node_valid || nq <= 0)) - tiers_empty = true; - /* Drain gate uses the same hoisted combined drain with */ - /* no kfunc, so the bypass tests fair order cheap. The machine */ - /* plus reject queues veto here too and the bypass needs an empty */ - /* machine plus an empty reject, so shared plus value order hold */ - /* with no jump. */ - drain_ok = flow_cpu_meets_fair_hint(lq, nq, vtime, now); - if (mq > 0) - drain_ok = false; - if (oq > 0) - drain_ok = false; - if ((tiers_empty || drain_ok) && t->hoist_elig) { - scx_bpf_dsq_insert(p, - (u64)SCX_DSQ_LOCAL_ON | (u64)(u32)cpu, - (u64)FLOW_QUANTUM_NS, t->enq_flags); - scx_bpf_test_and_clear_cpu_idle(cpu); - scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE); - flow_count_kick(); - return true; - } - /* Tier join through the hoisted combined drain escalation */ - /* with no second poll. The local tier takes the task when */ - /* the hoisted drain finishes before the fair key, else the */ - /* node tier when live, else the machine tier, so no task */ - /* waits for a busy CPU while shared room stays open. Queue */ - /* order plus tier choice use the fair time while placement */ - /* tests the deadline, so the slowest sufficient CPU wins. */ - /* Mask wins on dispatch drain with the same order. */ - flow_tier_insert_hint(p, cpu, vtime, now, lq, nq); - return false; - } - /* Tier join through the shared insert with fair order. */ - /* The local queue takes the task when the target drains local plus */ - /* node before the fair key, else the node queue when live, else the */ - /* machine queue, so no task waits for a busy CPU while shared room */ - /* stays open. Queue order plus tier choice use the fair time while */ - /* placement tests the deadline, so the slowest sufficient CPU wins. */ - flow_tier_insert(p, cpu, vtime, now); - return false; -} -/** - * flow_enqueue_kick - kick one idle or preempt one busy target. - * @p: waiting task that just joined a tier queue. - * @t: tail args with target plus arrival fair time plus time plus - * requeue pace plus eligibility, hoisted once by the caller. - * - * Idle targets kick at once with strict one kick per wait and no rate - * window. The idle flag clears first so the kick sticks. The pid read - * uses a relaxed load to match the running stores. Requeues skip the - * occupant lookup with no task_from_pid cost, so slice rotation paces - * at expiry with no extra kick. Busy preempts count in preempt_kicks on - * success and in preempt_skipped on every hold by strict margin plus - * tail plus eligibility with no missing fill, so the two counters track - * urgency with no extra kick. Strict order uses wrap safe time before - * throughout, so equal arrivals pace with no bounce. Idle kicks gate on - * the hoisted eligibility, so hogs pace through tiers with no idle jump - * while lagging tasks still wake at once. The gate stays with one - * minimum read per wait, and the ineligible corner paces in tiers with - * no kick and one skipped preempt with no storm. The running pid names - * the occupant with no curr read. A trusted lookup carries the occupant - * deadline, and a missing occupant fails closed with no kick and no - * skipped count, since no urgency holds to track. The occupant CPU - * validates before the compare, so a migrated occupant never kicks the - * wrong CPU with no count. A zero occupant deadline means no order yet, - * so the arrival paces with no kick and no skipped count. Only predictor - * slack plus margin plus tail plus eligibility plus fair order holds - * count as skipped. An urgent latency-critical arrival leads by 100us - * with more than 100us left on the owner, so near ties plus nearly - * done owners never bounce. The shared preempt helper holds the margin - * plus tail with wrap safe order, so only a truly earlier arrival with - * work left preempts at once with one kick per wait. Equal or later - * arrivals pace at slice expiry with one skipped preempt. The fair time - * leads here, so fairness plus urgency gate the kick. Eligibility - * already passed above, so the helper checks lead plus tail only with - * predictor slack gated before it. - * - * Outlined with noinline to keep verifier headroom and the RCU occupant - * walk leaves the bypass plus tier join with no inline growth and the - * same one kick per wait order. - */ -static __noinline void flow_enqueue_kick(struct task_struct *p, - struct flow_enqueue_tail *t) -{ - s32 cpu = t->cpu; - u64 vtime = t->vtime; - u64 now = t->now; - struct flow_cpu_state *st = flow_cpu((u32)cpu); - u32 occ_pid; - struct task_struct *trusted; - struct flow_task_ctx *octx; - u64 occ_deadline; - u64 occ_run_at; - u32 occ_cur; - u64 o_avg; - u64 o_dev; - bool occ_lat = false; - bool arr_lat = true; - if (!st) - return; - /* Idle kicks gate on the hoisted eligibility, so hogs pace */ - /* through tiers with no idle jump while lagging tasks still */ - /* wake at once. The gate stays with one minimum read per */ - /* wait, and the ineligible corner paces in tiers with no */ - /* kick and one skipped preempt with no storm. */ - if (!t->hoist_elig) { - flow_count_preempt_skip(); - return; - } - if (READ_ONCE(st->running_pid) == 0) { - scx_bpf_test_and_clear_cpu_idle(cpu); - scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE); - flow_count_kick(); - return; - } - /* Requeues pace at slice expiry with no occupant preempt, */ - /* so the task_from_pid plus cgroup plus 16 peer cost stays */ - /* out of the hot rotation path. */ - if (t->is_reenq) - return; - /* The running pid names the occupant with no curr read. */ - /* A trusted lookup carries the occupant deadline, and a */ - /* missing occupant fails closed with no kick and no skipped */ - /* count, since no urgency holds to track. The occupant CPU */ - /* validates before the compare, so a migrated occupant never */ - /* kicks the wrong CPU with no count. A zero occupant deadline */ - /* means no order yet, so the arrival paces with no kick and */ - /* no skipped count. Only margin plus tail plus eligibility */ - /* plus fair order holds count as skipped below. */ - occ_pid = READ_ONCE(st->running_pid); - if (occ_pid == 0 || occ_pid == (u32)p->pid) - return; - bpf_rcu_read_lock(); - trusted = bpf_task_from_pid(occ_pid); - if (!trusted) { - bpf_rcu_read_unlock(); - return; - } - if (scx_bpf_task_cpu(trusted) != cpu) { - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - return; - } - octx = flow_lookup(trusted); - if (!octx) { - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - return; - } - occ_deadline = READ_ONCE(octx->deadline); - occ_run_at = READ_ONCE(octx->run_at); - occ_cur = READ_ONCE(octx->slice_ns); - /* Occupant latency uses the unified base plus ext with the same */ - /* occupant lookup, so RED and preempt agree with probation. The */ - /* occupant runs, so sleep stays unknown with fail open to zero. */ - o_avg = (u64)READ_ONCE(octx->avg_ns); - o_dev = (u64)READ_ONCE(octx->dev_ns); - { - u32 o_hint = READ_ONCE(octx->hint_us); - u32 o_tw = READ_ONCE(octx->weight); - u32 o_hw = READ_ONCE(octx->hint_w); - u32 o_eff; - if (o_tw == 0) - o_tw = (u32)FLOW_WEIGHT_BASE; - o_eff = flow_task_effective_weight(o_tw, o_hw); - occ_lat = flow_is_lat(o_avg, o_dev, o_hint, 0, 0, o_eff); - } - if (occ_deadline == 0) { - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - return; - } - /* Predictor slack gates the busy preempt with no new knob. */ - /* A batch arrival with a long predicted burst paces at slice */ - /* expiry with one skipped preempt, so only latency-critical work */ - /* with slack within one quantum preempts at once. Eligibility */ - /* already passed above, so this plus lead plus tail gate the kick. */ - /* Arrival latency uses the unified base plus ext with the threaded */ - /* sleep read before the wait overwrite, so kick agrees with RED */ - /* plus slice on the same gap with uclamp failed open and newcomers */ - /* staying batch with probation. */ - { - struct flow_task_ctx *actx = flow_lookup(p); - if (actx) { - u64 a_avg = (u64)READ_ONCE(actx->avg_ns); - u64 a_dev = (u64)READ_ONCE(actx->dev_ns); - u32 a_hint = READ_ONCE(actx->hint_us); - u32 a_tw = READ_ONCE(actx->weight); - u32 a_hw = READ_ONCE(actx->hint_w); - u32 a_eff; - if (a_tw == 0) - a_tw = (u32)FLOW_WEIGHT_BASE; - a_eff = flow_task_effective_weight(a_tw, a_hw); - arr_lat = flow_is_lat(a_avg, a_dev, a_hint, - t->arr_sleep, 0, a_eff); - if (!arr_lat) { - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - flow_count_preempt_skip(); - return; - } - } else { - arr_lat = false; - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - flow_count_preempt_skip(); - return; - } - } - /* An urgent latency-critical arrival leads by 100us with more than */ - /* 100us left on the owner under the strict key, so near ties plus */ - /* nearly done owners never bounce. The owner paces on start plus */ - /* inherit cur with no fresh quantum, so the tail tracks the stored */ - /* slice. The shared preempt helper holds the */ - /* margin plus tail with wrap safe order, so only a */ - /* truly earlier arrival with work left preempts at once with one */ - /* kick per wait. Equal or later arrivals pace at slice expiry with */ - /* one skipped preempt. Other pairs fail closed with one */ - /* skipped count. The strict key leads here, so fairness plus */ - /* urgency gate the kick. Eligibility already passed above, so the */ - /* helper checks lead plus tail only with slack gated */ - /* just before it. */ - if (!flow_preempt_ok(vtime, occ_deadline, now, - occ_run_at, occ_cur, arr_lat, occ_lat)) { - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - flow_count_preempt_skip(); - return; - } - bpf_task_release(trusted); - bpf_rcu_read_unlock(); - scx_bpf_kick_cpu(cpu, SCX_KICK_PREEMPT); - flow_count_kick(); - flow_count_preempt_kick(); -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue/miss.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue/miss.bpf.c deleted file mode 100644 index b0d1642ad9..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue/miss.bpf.c +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue miss rejoin for the flow scheduler. - * - * Holds the self-contained miss path with the fresh deadline plus the - * held slice plus the strict fair time plus the shared RED admit plus - * the tier rejoin. A miss on the last deadline counts before the new - * deadline, so the miss count tracks wall completion past deadline with - * skip aging. The miss holds the stored slice else floors it to 10us - * with no dynamic recompute, then rejoins via the same tier escalation - * re-derived with the fresh deadline, so urgency returns at once with - * no starvation. RED uses the same O(1) newcomer check through the - * shared outlined helper, so a reject needs cost past the fixed 256us Emax plus cost past the exceed with no critical. Tolerance aids only - * the guarantee without shaping the key. A full O(n) least value scan - * stays a noted alternative, so the verifier keeps one pass. Critical - * follows the unified latency, so RED and slice agree. Like fair.c, - * the earliest key wins, unlike rt.c, no fixed priority holds. Runs - * under the caller with one kick at most. - * - * Copyright (c) 2026 Galih Tama - */ -/** - * flow_enqueue_miss - rejoin one missed task in tier order. - * @p: task to rejoin, passed to the tier plus reject inserts. - * @t: miss tail with state plus target plus hint plus time plus flags. - * - * Counts one miss before the fresh deadline, holds the stored slice - * else floors it to 10us, then rejoins via the same tier escalation - * re-derived with the fresh deadline plus skip aging. RED on the rejoin - * uses the shared outlined helper with cost past Emax plus cost past - * exceed and never critical. A reject joins the value ordered queue - * with one idle kick, else the tier queue with one admit plus one idle - * kick. Queue order uses the strict fair time capped at now plus one - * period, so far keys never starve past the bound while placement tests - * the deadline. Returns true when the miss took with no further work - * for the caller, else false when no miss holds. - * - * Outlined with noinline to keep verifier headroom and the miss plus - * open paths share no inline growth with the same order plus the same - * counts. - */ -static __noinline bool flow_enqueue_miss(struct task_struct *p, - const struct flow_miss_tail *t) -{ - struct flow_task_ctx *tctx; - s32 cpu; - s32 sel; - u64 now; - u64 enq_flags; - u32 hint; - u32 hint_w; - u64 avg; - u64 dev; - u64 m_sleep; - u64 ndl; - u64 nvt; - u32 msl; - bool mcrit; - if (!p || !t) - return false; - tctx = t->tctx; - if (!tctx) - return false; - cpu = t->cpu; - sel = t->sel; - now = t->now; - enq_flags = t->enq_flags; - hint = t->hint; - hint_w = t->hint_w; - avg = t->avg; - dev = t->dev; - /* No miss without a stored deadline past now, so fresh work falls */ - /* through to the open compute with no count and no deadline move. */ - if (!READ_ONCE(tctx->deadline)) - return false; - if (!flow_missed(READ_ONCE(tctx->deadline), now)) - return false; - /* A miss holds the stored slice else floors it to 10us with no */ - /* dynamic recompute via the shared miss helper, then rejoins via */ - /* the same tier escalation re-derived with the fresh deadline plus */ - /* skip aging in the miss count, so urgency returns at once with no */ - /* starvation. */ - flow_count_miss(tctx); - m_sleep = flow_take_sleep(tctx, now, avg); - ndl = flow_pred_deadline(now, avg, dev, hint); - __sync_lock_test_and_set(&tctx->deadline, ndl); - __sync_lock_test_and_set(&tctx->slice_ns, - flow_slice_miss_hold(READ_ONCE(tctx->slice_ns))); - nvt = flow_make_fair(tctx, ndl, hint_w); - /* In-tier keys cap at now plus one period through the shared */ - /* helper, so far keys never starve past the bound. */ - nvt = flow_enqueue_cap_key(nvt, now); - /* RED on the miss rejoin with the same O(1) newcomer check through */ - /* the shared outlined helper, so a reject needs cost past the */ - /* fixed 256us Emax plus cost past the exceed with no critical. */ - /* Tolerance aids only the guarantee without shaping the key. */ - /* A full O(n) least value scan stays a noted alternative, so */ - /* the verifier keeps one pass. Critical follows the unified */ - /* latency through the shared test, so RED and slice agree. */ - msl = READ_ONCE(tctx->slice_ns); - mcrit = flow_enqueue_is_lat(avg, dev, hint, m_sleep, - flow_task_effective_weight(READ_ONCE(tctx->weight), hint_w)); - { - struct flow_reject_tail rej = { - .tctx = tctx, - .deadline = ndl, - .now = now, - .avg = avg, - .slice = msl, - .is_lat = mcrit, - .hint_w = hint_w, - .enq_flags = enq_flags, - .sel = sel, - }; - if (flow_enqueue_reject(p, &rej)) - return true; - } - flow_tier_insert(p, cpu, nvt, now); - flow_count_admit(); - flow_kick_idle_allowed(p, sel); - return true; -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue/open.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue/open.bpf.c deleted file mode 100644 index 9b7e4e91b8..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue/open.bpf.c +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue open compute for the flow scheduler. - * - * Holds the fresh plus requeue fair time with the dynamic slice plus - * the latency clamp plus the strict key. Fresh waits earn the dynamic - * remaining clamp to 10us plus 1ms with the tier cap plus the 100us - * latency clamp, while requeues hold the stored charge else inherit the - * quantum with no recompute. The slice holds the dynamic remaining - * clamp on fresh waits else the held charge on requeues, so near - * deadlines earn near virtual times without a band jump. Sleep isolates - * the true gap as now minus wait minus burst, so queue plus run never - * look like sleep. In-tier keys cap at now plus one period, so far keys - * never starve past the bound. Like fair.c, the cap paces service, - * unlike rt.c, no fixed priority holds. Runs under the caller with the - * shared RED plus place plus kick left to the dispatcher. - * - * Copyright (c) 2026 Galih Tama - */ -/** - * flow_enqueue_open - compute one open fair time with out fields. - * @t: open tail with state plus deadline plus hint plus time plus flags. - * @out: out fields with fair time plus RED cost plus kick sleep. - * - * A fresh wait clamps the slice to 100us plus caps the key to now plus - * max 4ms else slice plus 100us via the strict key, while RED stays on - * the original deadline. A preempted head resumes without a slice - * rewrite here, so the stored leftover stays with one charge in - * stopping. A requeue holds the stored charge else inherits the quantum - * on zero, so the virtual deadline tracks the same charge the key - * sorts. The effective share stacks task times hint over 128, so - * cgroup plus task weights shape fairness together. Latency recomputes - * per enqueue without a stored bit, so 72B holds. Fills the fair time - * plus the pre-clamp slice plus the sleep plus the latency plus the - * fresh flag, so the dispatcher keeps one shared RED admit plus one - * eligibility plus one place plus kick with no second compute. - * - * Outlined with noinline to keep verifier headroom and the fresh plus - * requeue paths share one divide copy with the same order. - */ -static __noinline void flow_enqueue_open(const struct flow_open_tail *t, - struct flow_open_out *out) -{ - struct flow_task_ctx *tctx; - u64 deadline; - u64 now; - u64 enq_flags; - u32 hint; - u32 hint_w; - u64 avg; - u64 dev; - bool is_reenq; - if (!t || !out) - return; - tctx = t->tctx; - if (!tctx) { - out->vtime = 0; - out->pre_slice = 0; - out->sleep_ns = 0; - out->is_lat = false; - out->is_fresh = !t->is_reenq; - return; - } - deadline = t->deadline; - now = t->now; - enq_flags = t->enq_flags; - hint = t->hint; - hint_w = t->hint_w; - avg = t->avg; - dev = t->dev; - is_reenq = t->is_reenq; - out->vtime = 0; - out->pre_slice = 0; - out->sleep_ns = 0; - out->is_lat = false; - out->is_fresh = !is_reenq; - /* Latency recompute per enqueue without a stored bit, so 72B holds. */ - /* A fresh wait clamps the slice to 100us plus caps the key to now */ - /* plus max 4ms else slice plus 100us via the strict key, while RED */ - /* stays on the original deadline. Like fair.c, the cap paces */ - /* service, unlike rt.c, no fixed priority holds. A preempted head */ - /* resumes via lifecycle only without a slice rewrite here, so the */ - /* stored leftover stays with one charge in stopping. Sleep isolates */ - /* the true gap as now minus wait minus burst, so queue plus run */ - /* never look like sleep. In-tier keys cap at now plus one period, */ - /* so far keys never starve past the bound. */ - if (!is_reenq) { - u64 lat_sleep = flow_take_sleep(tctx, now, avg); - bool is_lat; - u32 pre_slice; - u32 lat_slice; - u64 lat_vt; - u64 vtime; - /* No stable uclamp field in this task view, so fail open to */ - /* zero without an extra map, and the ext helper keeps the veto */ - /* for callers that thread a real clamp. Probation holds through */ - /* both helpers, so newcomers stay batch. Latency shares one */ - /* copy with miss plus pinned, so the open path keeps headroom. */ - is_lat = flow_enqueue_is_lat(avg, dev, hint, lat_sleep, - flow_task_effective_weight(READ_ONCE(tctx->weight), - hint_w)); - pre_slice = flow_slice_for(deadline, now); - pre_slice = flow_slice_tier_cap(pre_slice, avg, dev, is_lat); - lat_slice = flow_slice_lat_clamp(pre_slice, is_lat); - out->is_lat = is_lat; - out->pre_slice = pre_slice; - out->sleep_ns = lat_sleep; - out->is_fresh = true; - if (enq_flags & SCX_ENQ_PREEMPT) { - vtime = flow_make_fair(tctx, deadline, hint_w); - } else { - u64 lat_dl; - __sync_lock_test_and_set(&tctx->slice_ns, lat_slice); - lat_vt = flow_make_fair(tctx, deadline, hint_w); - if (is_lat) { - lat_dl = flow_lat_deadline(now, lat_slice); - vtime = flow_edf_key(lat_vt, lat_dl); - } else { - vtime = lat_vt; - } - } - vtime = flow_enqueue_cap_key(vtime, now); - out->vtime = vtime; - } else { - u64 re_sleep = flow_take_sleep(tctx, now, avg); - u64 vtime; - /* Strict slice before the key without stale reuse. A slice */ - /* rotation holds the stored charge else inherits the quantum */ - /* on zero, so the virtual deadline tracks the same charge the */ - /* key sorts. The remaining time feeds the slice plus slack only */ - /* with the sort staying the earlier of deadline plus virtual */ - /* time. */ - out->sleep_ns = re_sleep; - out->is_fresh = false; - out->pre_slice = 0; - /* RED latency for the requeue uses the same unified test on */ - /* the same gap through the shared helper, so RED and slice */ - /* agree with no second wait read at the caller. */ - out->is_lat = flow_enqueue_is_lat(avg, dev, hint, re_sleep, - flow_task_effective_weight(READ_ONCE(tctx->weight), - hint_w)); - __sync_lock_test_and_set(&tctx->slice_ns, - flow_slice_inherit(READ_ONCE(tctx->slice_ns))); - /* Strict EDF key from the virtual deadline plus the EDF */ - /* deadline. Heavy tasks earn a near virtual time while light */ - /* tasks earn a far one with one divide, so the earlier of the */ - /* two paces order with latency still capped by the deadline. */ - /* The effective share stacks task times hint over 128, so */ - /* cgroup plus task weights shape fairness together. In-tier */ - /* keys cap at now plus one period through the shared helper, */ - /* so far keys never starve past the bound. */ - vtime = flow_make_fair(tctx, deadline, hint_w); - vtime = flow_enqueue_cap_key(vtime, now); - out->vtime = vtime; - } -} diff --git a/scheds/experimental/scx_flow/src/bpf/enqueue/target.bpf.c b/scheds/experimental/scx_flow/src/bpf/enqueue/target.bpf.c deleted file mode 100644 index 32a5b54b5e..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/enqueue/target.bpf.c +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Enqueue target for the flow scheduler. - * - * Holds the pinned test plus the target pick for the enqueue pass. - * Pinned tasks stay where the mask allows with no scan, and every - * other arrival falls back from the selected CPU to the first allowed - * CPU with no topology walk. An empty mask falls through to the - * machine tier at the caller. Runs under the caller with no lock. - * - * Copyright (c) 2026 Galih Tama - */ -/* True when one task cannot migrate from its current CPU. */ -/* Migration disabled plus a single allowed CPU both pin, so the */ -/* caller waits in a tier queue with no scan and no direct jump. */ -static __always_inline bool flow_task_pinned(const struct task_struct *p) -{ - if (is_migration_disabled(p)) - return true; - if (p->nr_cpus_allowed == 1) - return true; - return false; -} -/* Pick the target CPU for one task from the select hint. */ -/* Takes the selected CPU when live plus allowed, else the first */ -/* allowed CPU when live, else negative with no scan, so the caller */ -/* waits in the machine tier with no wait and no gate bypass. */ -static __always_inline s32 flow_pick_target(struct task_struct *p, s32 sel) -{ - s32 first; - if (sel >= 0 && flow_cpu_ok(p, sel)) - return sel; - first = (s32)bpf_cpumask_first(p->cpus_ptr); - if (flow_cpu_ok(p, first)) - return first; - return -1; -} diff --git a/scheds/experimental/scx_flow/src/bpf/fair.bpf.h b/scheds/experimental/scx_flow/src/bpf/fair.bpf.h new file mode 100644 index 0000000000..ffb144b509 --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/fair.bpf.h @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Fair charging for the flow scheduler. + * + * The base charge scales with the nice weight. Values saturate at + * the top. The task nice weight comes from a small table over minus + * twenty to nineteen with zero as one hundred, read from the task + * static priority minus one hundred twenty. Out of range tasks keep + * the default. + * Fresh times move past the per LLC floor through a short + * compare and swap loop, so each stored time stays unique with + * the winner publishing its value at once. When the loop loses + * too often, the last observed value plus one is stored directly + * with no further retry. An invalid LLC skips the floor and keeps + * the input time directly. The floor rises over time and never + * moves backward for a given LLC. When the time runs ahead of the + * floor, the floor moves up by at most one base step per enqueue, + * so one far time cannot pull the floor with it. Virtual deadline adds the burst scaled nice step + * to the floored time through the shared charge path, so a larger + * weight or a shorter run gives an earlier due time with no extra + * divide. Burst holds the last run length between the floor and + * one slice with shift only moves. Overload cost holds the run length + * between the floor and one slice. Exceed holds the cost past tolerance + * else zero. The gate admits with live plus tolerance plus bound plus + * room plus cap and rejects large costs on a full target. Bands map the + * nice weight between one and sixteen thousand three hundred eighty four + * with base one hundred twenty eight through shift only moves with no + * new field, so the lowest band holds the lightest share. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_FAIR_BPF_H +#define __FLOW_FAIR_BPF_H +#include "intf.h" +#include "maps.bpf.h" +/* Nice weight on the weight scale from minus twenty to nineteen. + * Strictly falls from ten thousand to one with one hundred at zero. + * Fits in read only data with direct indexing and no loop. */ +static const u32 flow_nice_table[40] = { + 10000, 7943, 6310, 5012, 3981, 3162, 2512, 1995, + 1585, 1259, 1000, 794, 631, 501, 398, 316, + 251, 200, 158, 126, 100, 78, 62, 48, + 38, 30, 23, 18, 14, 11, 10, 9, + 8, 7, 6, 5, 4, 3, 2, 1, +}; +static __always_inline u32 flow_nice_weight(const struct task_struct *p) +{ + s32 prio; + u32 idx; + if (!p) + return (u32)FLOW_CGROUP_WEIGHT_DFLT; + prio = p->static_prio - 120; + if (prio < -20 || prio > 19) + return (u32)FLOW_CGROUP_WEIGHT_DFLT; + idx = (u32)(prio + 20); + if (idx >= 40U) + return (u32)FLOW_CGROUP_WEIGHT_DFLT; + return flow_nice_table[idx]; +} +static __always_inline u64 flow_fair_step(u32 w) +{ + u32 cw = w; + if (cw == (u32)FLOW_CGROUP_WEIGHT_INVALID || cw < (u32)FLOW_CGROUP_WEIGHT_MIN) + cw = (u32)FLOW_CGROUP_WEIGHT_DFLT; + if (cw > (u32)FLOW_CGROUP_WEIGHT_MAX) + cw = (u32)FLOW_CGROUP_WEIGHT_MAX; + if (!cw) + return (u64)FLOW_FAIR_BASE_NS; + return (u64)FLOW_FAIR_BASE_NS * (u64)FLOW_CGROUP_WEIGHT_DFLT / (u64)cw; +} +static __always_inline s64 flow_fair_cap_add(s64 base, u64 add) +{ + const s64 vmax = (s64)0x7fffffffffffffffLL; + if (add > (u64)vmax) + return vmax; + if (base >= vmax - (s64)add) + return vmax; + return base + (s64)add; +} +static __always_inline s64 flow_fair_charge(s64 base, u64 used, u32 w) +{ + const s64 vmax = (s64)0x7fffffffffffffffLL; + u64 st = flow_fair_step(w); + u64 slice = (u64)FLOW_SLICE_MIN_NS; + u64 hi; + u64 lo; + u64 scaled; + if (!st) + st = (u64)FLOW_FAIR_BASE_NS; + if (!slice) + slice = (u64)FLOW_SLICE_MIN_NS; + hi = used / slice; + lo = used % slice; + if (hi > (u64)vmax / st) + return vmax; + scaled = hi * st + lo * st / slice; + if (scaled > (u64)vmax) + return vmax; + return flow_fair_cap_add(base, scaled); +} +/* Burst stays between the floor and one slice. A zero or past slice + * value snaps to one slice and a short value snaps to the floor. + * Shift moves keep the update without divide. */ +static __always_inline u64 flow_burst_clamp(u64 burst_ns) +{ + if (!burst_ns || burst_ns > (u64)FLOW_SLICE_MIN_NS) + return (u64)FLOW_SLICE_MIN_NS; + if (burst_ns < (u64)FLOW_SLICE_FLOOR_NS) + return (u64)FLOW_SLICE_FLOOR_NS; + return burst_ns; +} +static __always_inline s64 flow_vd_for(s64 floored, u64 burst_ns, u32 w) +{ + u64 b = flow_burst_clamp(burst_ns); + s64 vd = flow_fair_charge(floored, b, w); + if (vd <= floored) + return flow_fair_cap_add(floored, 1); + return vd; +} +/* Track the last run length. An overrun snaps to one slice. A run + * that ends early while still runnable only moves up past the old + * value by half the gap and holds otherwise, since the stop cut the + * run short. A sleep moves by a quarter toward the run length. */ +static __always_inline u64 flow_burst_update(u64 old_burst, u64 total_used, + u64 cur, bool runnable) +{ + u64 b = flow_burst_clamp(old_burst); + u64 u = total_used; + if (u > (u64)FLOW_SLICE_MIN_NS) + u = (u64)FLOW_SLICE_MIN_NS; + if (!cur) + return (u64)FLOW_SLICE_MIN_NS; + if (runnable) { + if (u > b) + b = b - (b >> 1) + (u >> 1); + return flow_burst_clamp(b); + } + b = b - (b >> 2) + (u >> 2); + return flow_burst_clamp(b); +} +/* Overload cost for one burst. Holds the run length between the floor + * and one slice, so a larger burst pays more with saturating clamp only. */ +static __always_inline u64 flow_red_cost(u64 burst_ns) +{ + return flow_burst_clamp(burst_ns); +} +/* Overload exceed past tolerance. Holds zero when the cost sits within + * tolerance else the cost past tolerance, so small costs admit at once + * with saturating math only. */ +static __always_inline u64 flow_red_exceed(u64 cost) +{ + u64 tol = (u64)FLOW_RED_TOL_NS; + if (cost <= tol) + return 0; + return cost - tol; +} +/* Overload gate for one newcomer cost with target room. Rejects when the + * cost sits past the bound and the target holds no room under the cap, + * so small costs plus room admit and overload drains to fallback with + * the caps kept. Compare only with no divide. */ +static __always_inline bool flow_red_gate(u64 cost, u64 exceed, u64 queued) +{ + u64 emax = (u64)FLOW_RED_EMAX_NS; + if (!exceed) + return false; + if (cost <= emax) + return false; + if (queued < (u64)FLOW_QUEUE_CAP) + return false; + return true; +} +/* Implicit band for one nice weight. Maps between one and sixteen + * thousand three hundred eighty four with base one hundred twenty eight + * through shift only moves, so the lightest share sits in the lowest + * band with no new field and no divide. */ +static __always_inline u32 flow_band_for_weight(u32 w) +{ + u32 cw = w; + if (!cw || cw < 1U) + cw = 1U; + if (cw > 16384U) + cw = 16384U; + if (cw >= (128U << 3)) + return 3U; + if (cw >= 128U) + return 2U; + if (cw >= (128U >> 3)) + return 1U; + return 0U; +} +static __always_inline s64 flow_seq_floor(u32 llc, s64 v) +{ + const s64 vmax = (s64)0x7fffffffffffffffLL; + int i; + if (!flow_llc_ok(llc)) + return v; + for (i = 0; i < 4; i++) { + s64 last = READ_ONCE(flow_llc_seq[llc]); + s64 want = v; + s64 next; + if (want <= last) { + if (last == vmax) + want = last; + else + want = last + 1; + next = want; + } else { + s64 cap = flow_fair_cap_add(last, (u64)FLOW_FAIR_BASE_NS); + if (want < cap) + next = want; + else + next = cap; + } + if (__sync_val_compare_and_swap(&flow_llc_seq[llc], last, next) == last) + return want; + } + { + s64 last = READ_ONCE(flow_llc_seq[llc]); + s64 want = v; + if (want <= last) { + if (last == vmax) + want = last; + else + want = last + 1; + flow_llc_seq[llc] = want; + } + return want; + } +} +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/intf.h b/scheds/experimental/scx_flow/src/bpf/intf.h index 37da5955b1..4d9b57aa70 100644 --- a/scheds/experimental/scx_flow/src/bpf/intf.h +++ b/scheds/experimental/scx_flow/src/bpf/intf.h @@ -1,50 +1,37 @@ // SPDX-License-Identifier: GPL-2.0 /* - * Shared constants and helpers for the flow scheduler. - * - * The scheduler keeps one local queue per CPU plus one shared queue - * per node plus one shared queue per machine plus one value ordered - * reject queue. Homeless work without a live CPU and gate misses wait - * in the reject queue by value with mask wins on drain. - * Idle CPUs steal one task from peer locals as the fifth tier with - * a capped window of 4 to 8 peers proportional to remaining visits. - * Every task earns an absolute deadline from now plus a period, and - * each queue orders by the strict EDF key through the kernel priority - * queue. The strict key holds the earlier of deadline plus virtual - * deadline with a 2ms lag bound, so the earliest key always - * runs next. Each fresh wait earns a dynamic slice from the saturated - * remaining time clamped to 10us at the floor plus 1ms at the ceiling, - * so near deadlines pace tightly while far deadlines still rotate each - * millisecond. A miss holds the stored slice else floors it to 10us - * with a fresh deadline plus a tier rejoin rederived through the same - * escalation plus skip aging, and a zero slice inherits the 1ms - * quantum. A global completer credit at or past the fixed 256us Emax - * reclaims one value ordered reject with positive laxity plus the - * same key or a strictly after key with a single move, so overload - * drains without starving the tiers. A miss counts when wall time - * passes the deadline, and the miss rejoins a tier queue with a fresh - * deadline plus a direct kick without waiting. Placement takes the - * slowest sufficient CPU among the allowed set that can meet the - * deadline, so light work never takes a fast CPU that other work - * needs. Hints from the flat view tune the period plus the weight, - * and no group or pool shapes order. Each stop feeds the burst - * predictor average plus deviation with up plus down shifts, so later - * deadlines track recent bursts without a table walk. The average - * rises fast with shift 3 plus falls slow with shift 4, the deviation - * widens fast with shift 2 plus narrows slow with shift 3, and the - * period adds average plus deviation plus half deviation margin, so - * stable bursts keep tight deadlines while ragged bursts hold margin. - * The fair key stays math-only with no nudge, so tier plus kick ride - * the strict key while placement tests the deadline plus drain and - * fixed RED bounds gate overload with PRIQ only for tiers. The - * direct plus exiting LOCAL_ON queue stays terminal FIFO outside - * PRIQ order with no tier rank. Hard means batch non-latency while - * critical means latency-critical via the unified latency test, so - * tolerance aids hard only. See - * select_cpu.bpf.c for placement and enqueue.bpf.c for the - * deadline choice plus dispatch.bpf.c for the tier scans and - * lifecycle.bpf.c for the miss count and timer.bpf.c for the leftover - * charge plus the miss count. + * Shared constants for the flow scheduler. + * + * Each CPU owns one queue ordered by virtual deadline. Ties + * leave in insertion order. One fallback queue holds tasks that have + * no usable CPU in FIFO order as a best effort overflow with no extra + * promise. Pinned tasks run on their local queue. Placement keeps the + * constrained target with no load scan. Draining walks local first + * then same LLC then same node then distant remote last in deadline order + * with idle starts at once. Each per CPU queue holds bounded at 64 + * total with one millis slices. Each enqueue prices the task by its + * nice weight. A task pays for the time it burns, scaled by that weight. Fresh times move past + * a per LLC floor so two tasks never share the same value, with a + * direct store of the last observed value plus one when the loop + * loses too often. Virtual deadline adds a nice based step scaled + * by the burst to the floored time through the shared charge path, + * so a larger weight or a shorter run gives an earlier due time. + * Slices hold one fixed quantum with a small floor. Burst holds the + * last run length. Overload keeps a guaranteed admit with live plus + * tolerance plus bound plus room plus cap. A full target evicts at most + * one ready task with the latest deadline in the lowest implicit band + * through a bounded scan of at most eight. Bands come from the nice + * weight through the fair helper with no new field. Rejects stay in the + * fallback queue in FIFO order. Stopping plus tick reclaim at most one + * saved delta from burst past burnt with room plus live plus allowed + * and idle only kick. A shared enqueue with a due time ahead of the + * running due time kicks for preempt with idle wakes otherwise. Each running instance kicks at most once. + * A runnable yield with no burnt time still moves the stored time forward by one. Each per CPU queue + * holds bounded at 64 total with the fallback holding at most one + * thousand twenty four. Queues come from the upstream deadline + * library with always eligible tasks, and placement follows the upstream + * topology library with liveness from the same tree. Arena holds one + * queue node per task beside the task state. * * Copyright (c) 2026 Galih Tama */ @@ -65,1773 +52,112 @@ typedef int pid_t; #ifndef __always_inline #define __always_inline inline __attribute__((__always_inline__)) #endif -#ifndef __noinline -#define __noinline __attribute__((noinline)) -#endif #ifndef READ_ONCE #define READ_ONCE(x) (*(const volatile typeof(x) *)&(x)) #endif -/* Slice ceiling of 1ms with no knob. Caps the dynamic slice plus the */ -/* preempt tail window plus the carryover, so one slice always spans */ -/* one wakeup with no extra hold. Fresh waits clamp the saturated */ -/* remaining time to this ceiling with a 10us floor. */ enum flow_consts { - FLOW_QUANTUM_NS = 1000000ULL, - /* Dynamic slice floor of 10us with no knob. Holds the smallest */ - /* charge that still outlasts the kick cost, so near deadlines */ - /* pace tightly with no zero slice. Misses hold else floor here, */ - /* and a zero slice inherits the ceiling. */ - FLOW_SLICE_MIN_NS = 10000ULL, - /* Ultra-low latency boundary of 50us with no knob. Caps the T1 tier, */ - /* so audio plus frame pacing bursts pace tightly with no extra hold. */ - /* Like fair.c, the bound paces service, unlike rt.c, no fixed */ - /* priority holds. */ - FLOW_SLICE_ULL_NS = 50000ULL, - /* Low latency boundary of 100us with no knob. Caps the T2 tier, so */ - /* compositor plus UI bursts rotate each tenth quantum with no hold. */ - /* Matches the latency slice cap, so urgent wakeups keep one bound. */ - /* Like fair.c, the bound paces service, unlike rt.c, no fixed */ - /* priority holds. */ - FLOW_SLICE_LL_NS = 100000ULL, - /* Medium-low latency boundary of 500us with no knob. Caps the T3 */ - /* tier, so IPC plus microservice bursts hold margin with no storm. */ - /* Like fair.c, the bound paces service, unlike rt.c, no fixed */ - /* priority holds. */ - FLOW_SLICE_MLL_NS = 500000ULL, - /* Normal latency boundary of 1ms with no knob. Caps the T4 tier at */ - /* one quantum, so desktop plus worker bursts rotate each quantum. */ - /* Like fair.c, the bound paces service, unlike rt.c, no fixed */ - /* priority holds. */ - FLOW_SLICE_NL_NS = 1000000ULL, - /* Extended normal latency boundary of 5ms with no knob. Caps the T5 */ - /* tier, so bulk I/O plus build bursts hold room with no starve. */ - /* Like fair.c, the bound paces service, unlike rt.c, no fixed */ - /* priority holds. */ - FLOW_SLICE_ENL_NS = 5000000ULL, - /* Dynamic slice ceiling of 20ms with no knob. Caps the T6 tier plus */ - /* the multi-tier spectrum, so throughput bursts hold room with an */ - /* 80ms period guarding starvation. Like fair.c, the ceiling paces */ - /* service, unlike rt.c, no fixed priority holds. */ - FLOW_SLICE_MAX_NS = 20000000ULL, - /* Default period of 80ms with no knob. Holds four 20ms slices, */ - /* so a fully used throughput task still leaves room for waits plus */ - /* retries inside the period with no starvation under 20ms holds. */ - FLOW_PERIOD_NS = 80000000ULL, - /* Predictor bounds with no knob. Holds 1ns to 1s, so a huge */ - /* burst clamps instead of wrapping to a short deadline. */ - FLOW_PRED_MIN_NS = 1ULL, - FLOW_PRED_MAX_NS = 1000000000ULL, - FLOW_WEIGHT_MIN = 1ULL, - FLOW_WEIGHT_BASE = 128ULL, - FLOW_WEIGHT_MAX = 16384ULL, - /* CPU bound of 1024 rows with no knob. Covers the largest test */ - /* host with wide margin while keeping array memory small. */ FLOW_MAX_CPUS = 1024ULL, - /* Node bound of 16 rows with no knob. Covers the largest test */ - /* host with wide margin while keeping the node scan small. */ - FLOW_MAX_NODES = 16ULL, - /* Hint bound of 8192 rows with no knob. Keys are hierarchy ids */ - /* with sparse use, so the table holds large hosts with room for */ - /* churn. Full tables fail closed to the default period without */ - /* evicting. */ - FLOW_HINT_MAX = 8192ULL, - /* Local queue region base. Holds 1024 ids, one per CPU. */ - FLOW_LOCAL_BASE = 0x5100ULL, - /* Node queue region base. Holds 16 ids, one per node. */ - FLOW_NODE_BASE = 0x5900ULL, - /* Machine queue id shared by every CPU. */ - FLOW_MACHINE = 0x5A00ULL, - /* Overflow reject id for overload past tier order with value order. */ -/* Named overflow frozen for wire compat only and it holds the value */ -/* ordered reject queue drained only by reclaim, never a tier overflow. */ - FLOW_OVERFLOW = 0x5A01ULL, - /* Queue count of 1042. Holds 1024 local plus 16 node plus one */ - /* machine plus one value ordered reject. */ - FLOW_MAX_DSQS = 1042ULL, - /* Dispatch visit cap of 8 entries per pass with no knob. Caps */ - /* visited entries per pass shared across five tiers regardless of */ - /* moves, so one pass never holds RCU across the whole queue on */ - /* mask misses. Moves take at most one per tier per pass capped by */ - /* remaining dispatch slots, and leftover work resumes next pass, */ - /* so the pass stays work conserving across passes. The steal window */ - /* spans 4 to 8 peers proportional to remaining visits. */ - FLOW_DISPATCH_MAX_VISIT = 8ULL, - /* Steal peer window with no knob. Scans at least 4 peers and at */ - /* most 8 peers per pass, so the steal stays cheap without a hotspot */ - /* while large hosts still find work. */ - FLOW_STEAL_MIN_PEERS = 4ULL, - FLOW_STEAL_MAX_PEERS = 8ULL, - /* BSF fallback bound of 4 peers with no knob. Scans the next four */ - /* past the 8 peer SSF window from cursor plus 9, so select covers */ - /* twelve unique peers per pass without walking topology. Keeps the */ - /* fallback cheap while extending coverage with the same order. */ - FLOW_BSF_MAX_PEERS = 4ULL, - FLOW_OPS_TIMEOUT_MS = 20000ULL, - /* Resume gap of 5s. Deltas past this bound read as an s2idle */ - /* plus long stall, so stopping clamps to zero while userspace */ - /* reseeds the topology view. Monotonic pauses across S3, so S3 */ - /* trips only the userspace boot gap. Stays past one period. */ - FLOW_RESUME_GAP_NS = 5000000000ULL, - /* Base capacity of 1024 units with no knob. Every CPU on a */ - /* symmetric host offers the same units, so the slowest */ - /* sufficient pick falls to the lowest sufficient id. */ - FLOW_CAP_BASE = 1024ULL, - /* CPU performance levels at half plus max with no knob. Any own */ - /* plus local plus running picks max else half with no shared use. */ - FLOW_CPU_PERF_HALF = 512ULL, - FLOW_CPU_PERF_MAX = 1024ULL, - /* Preempt leads by 100us with no knob, so near ties never bounce */ - /* while urgent gaps still preempt at once. The floor stays at */ - /* 100us with one kick per wait. */ - FLOW_PREEMPT_MARGIN_NS = 100000ULL, - /* Preempt waits out a 100us tail with no knob, so a nearly done */ - /* owner finishes instead of taking a kick. The floor stays at */ - /* 100us with one kick per wait. */ - FLOW_PREEMPT_TAIL_NS = 100000ULL, - /* Allowed lag bound of 2ms with no knob. Newly woken tasks clamp */ - /* within this distance of the CPU minimum, so sleepers gain no */ - /* more than one extra slice of boost with no storm. */ - FLOW_VLAG_MAX_NS = 2000000ULL, - /* RED bound of 256us with no knob. Caps the maximum exceeding */ - /* time, so a global credit at or past this bound reclaims one */ - /* reject, and a victim cost at or below this bound keeps the */ - /* newcomer with no swap. A capped latency slice at 100us never */ - /* passes, so latency never pays as victim. The bound caps */ - /* lateness with no share shaping. */ - FLOW_RED_EMAX_NS = 256000ULL, - /* RED tolerance of 64us with no knob. Holds the guarantee slack */ - /* for hard batch only scoped to non-latency, so latency-critical */ - /* keeps zero tolerance with no late run. Tolerance aids the */ - /* guarantee with no order shaping. Reclaim shares the same fixed */ - /* path, so admit plus reclaim agree. */ + FLOW_MAX_LLCS = 64ULL, + FLOW_MAX_NODES = 8ULL, + FLOW_QUEUE_CAP = 64ULL, + FLOW_FALLBACK_CAP = 1024ULL, FLOW_RED_TOL_NS = 64000ULL, - /* Adaptive grow step of 64us frozen for wire compat only. */ - /* Kept with no use after the proportional law, so old headers */ - /* still decode with no behavior change, whitelisted with no use. */ - /* Like fair.c, the step paces service, unlike rt.c, no fixed priority holds. */ - /* Clamps with the slice floor plus ceiling. */ - FLOW_ADAPT_GROW_NS = 64000ULL, - /* Adaptive shrink step of 128us frozen for wire compat only. */ - /* Kept with no use after the proportional law, so old headers */ - /* still decode with no behavior change, whitelisted with no use. */ - /* Like fair.c, the step tracks load, unlike rt.c, no fixed priority holds. */ - /* Clamps with the slice floor plus ceiling. */ - FLOW_ADAPT_SHRINK_NS = 128000ULL, - /* Proportional adapt cap of 1ms with no knob. Caps one shift */ - /* step, so a huge exceed plus slack moves at most one quantum */ - /* with no storm. Exceed shrinks, slack grows, both shift 3. */ - FLOW_ADAPT_PROP_MAX_NS = 1000000ULL, - /* Proportional adapt shift of 3 with no knob. Maps exceed plus */ - /* slack to one eighth with shifts only, so no divide runs in BPF. */ - FLOW_ADAPT_PROP_SHIFT = 3ULL, - /* Proportional deadband shift of 5 with no knob. Holds one */ - /* thirty-second of the base as the quiet band, so timer jitter */ - /* plus one tick never hunts the slice with shifts only. Exceed */ - /* plus slack at or below the band hold the clamped slice. */ - FLOW_ADAPT_DEADBAND_SHIFT = 5ULL, - /* Proportional deadband floor of 8us with no knob. Keeps the */ - /* quiet band above one tick on small slices, so a 10us base still */ - /* holds a real band with no divide. */ - FLOW_ADAPT_DEADBAND_MIN_NS = 8000ULL, - /* Half-damp shift of 1 with no knob. Halves the capped step once, */ - /* so one correction moves at most one quarter base with shifts */ - /* only and ringing halves each stop with no divide. */ - FLOW_ADAPT_DAMP_SHIFT = 1ULL, - /* Predictor rise shift of 3 with no knob. Moves the average one */ - /* eighth toward a larger sample with shifts only, so bursts grow */ - /* fast with no divide. */ - FLOW_PRED_UP_SHIFT = 3ULL, - /* Predictor fall shift of 4 with no knob. Moves the average one */ - /* sixteenth toward a smaller sample with shifts only, so bursts */ - /* decay slow with no cliff. */ - FLOW_PRED_DOWN_SHIFT = 4ULL, - /* Deviation widen shift of 2 with no knob. Moves the deviation one */ - /* quarter toward a larger error with shifts only, so ragged bursts */ - /* gain margin fast with no divide. */ - FLOW_PRED_DEV_UP_SHIFT = 2ULL, - /* Deviation narrow shift of 3 with no knob. Moves the deviation one */ - /* eighth toward a smaller error with shifts only, so stable bursts */ - /* keep margin without a snap. */ - FLOW_PRED_DEV_DOWN_SHIFT = 3ULL, - /* Deviation margin shift of 1 with no knob. Adds half deviation to */ - /* the period with shifts only, so the deadline holds average plus */ - /* one and a half deviation with no divide and no wrap. */ - FLOW_PRED_DEV_MARGIN_SHIFT = 1ULL, - /* Latency slice cap of 100us with no knob. Caps the dynamic slice */ - /* plus the carryover plus the adapt step for latency work, so */ - /* urgent wakeups rotate each tenth quantum with no extra hold. */ - /* Like fair.c, the cap paces service, unlike rt.c, no fixed */ - /* priority holds. Clamps with the slice floor plus ceiling. The */ - /* cap equals the preempt tail, so a latency head at the cap never */ - /* passes the tail gate and floors with no resume. Adapt steps cap */ - /* at 1ms then re-clamp here, so one shift never holds past the */ - /* cap. RED Emax stays at 256us past the cap, so a capped latency */ - /* slice never pays as victim with no swap. */ - FLOW_SLICE_LAT_NS = 100000ULL, - /* Latency sleep floor of 20us with no knob. Vetoes only sleeps */ - /* below this floor toward batch, so the 100us slice cap stays */ - /* decoupled with no extra hold. Like fair.c, the floor paces */ - /* service, unlike rt.c, no fixed priority holds. Unknown sleep */ - /* fails open with no stall. */ - FLOW_LAT_SLEEP_MIN_NS = 20000ULL, - /* Latency deadline bound of 4ms with no knob. Holds one quarter */ - /* period, so latency keys order within one quarter period with no */ - /* extra hold. Like fair.c, the bound paces order, unlike rt.c, no */ - /* fixed priority holds. */ - FLOW_D_LAT_NS = 4000000ULL, + FLOW_RED_EMAX_NS = 256000ULL, + FLOW_RED_EVICT_MAX = 8ULL, + FLOW_SLICE_MIN_NS = 1000000ULL, + FLOW_SLICE_FLOOR_NS = 62500ULL, + FLOW_EXIT_SLICE_NS = 1000ULL, + FLOW_FAIR_BASE_NS = 20000ULL, + FLOW_FAIR_EXTRA_NS = 1000ULL, + FLOW_CGROUP_WEIGHT_MIN = 1ULL, + FLOW_CGROUP_WEIGHT_DFLT = 100ULL, + FLOW_CGROUP_WEIGHT_MAX = 10000ULL, + FLOW_CGROUP_WEIGHT_INVALID = 0ULL, + FLOW_OPS_TIMEOUT_MS = 20000ULL, + FLOW_FALLBACK_DSQ = 0x6100ULL, + FLOW_FLAG_QUEUED = 1ULL, }; -/* Static dispatch tier order. Local plus node plus machine plus overflow */ -/* plus steal drain in fair order through the kernel priority queues with */ -/* the reject value ordered. Every pass follows this order without swapping */ -/* for load, so the verifier sees one fixed path. Dispatch calls the tier */ -/* moves directly with no index switch, so no tier index needs storage. The */ -/* steal tier scans peer locals within the capped window with mask wins. */ -/* Per task state at 72B with vruntime plus deadline plus stamps plus */ -/* predictor plus lag plus weight plus slice plus hint plus hint weight */ -/* plus misses plus adapt miss plus adapt sat plus adapt delta. */ -/* Vruntime holds the scaled service in nanos, zero when no history. */ -/* A zero vruntime means no service yet, so the first virtual deadline */ -/* falls near now without extra boost past the lag bound. Deadline holds */ -/* the absolute EDF deadline for queue order and the miss check. A zero */ -/* deadline means no order yet, so preempt and the miss check skip. Wait */ -/* holds the last enqueue time. A zero wait means the task never queued. */ -/* Every queue join stamps the task, so queued work always carries a stamp. */ -/* Run holds the segment start while on CPU else zero, so a claimed start */ -/* pairs the stopping charge. The on CPU gauge lives in the snapshot. */ -/* Running claims from zero only with a compare and swap, so a second */ -/* running without a stop keeps the first start. Stopping versus disable */ -/* or exit claims once with atomics, so each claimed start meets exactly */ -/* one charge. Hint weight holds the flat hint share clamped to range with */ -/* 128 for neutral, stored alongside the task base so requeues, stopping, */ -/* and leftover keep the heavy share without another cache lookup. A zero */ -/* means no history, so the effective helper maps it to neutral. Avg holds */ -/* the burst average in nanos in 32 bits, zero when no history. Dev holds */ -/* the burst deviation in nanos in 32 bits, zero when no history. Values */ -/* clamp to 1ns to 1s, so a huge burst never wraps. */ -/* Vlag holds the allowed lag in nanos as a signed bound, zero when no */ -/* slack. Weight holds the task base share clamped to range with 128 for */ -/* neutral, and the effective share stacks task times hint over 128 on the */ -/* stack. Slice holds the per task slice in nanos with the dynamic */ -/* remaining clamp on fresh waits. A miss holds the stored slice else floors */ -/* it to 10us, and a zero slice inherits the 1ms quantum with strict */ -/* preempt on a fresh quantum. Hint holds the flat period hint in micros */ -/* for the deadline. A zero hint means no hint, so the default period */ -/* applies. Misses holds the count of deadline misses for the life of the */ -/* task with saturating adds, so a huge miss count clamps instead of */ -/* wrapping. Lifetime means promotion latches once 8 holds with the same */ -/* one-move cap. A windowed decay stays a noted alternative. Adapt miss */ -/* holds the consecutive miss streak for the adaptive slice with saturation */ -/* at 0xffff, so a ragged burst widens step by step. Adapt sat holds the */ -/* clamp streak at the slice floor plus ceiling with saturation, so a stuck */ -/* slice shows its bound. Adapt delta holds the last saved execution in */ -/* nanos per task for debug, while the global completer credit funds */ -/* reclaim, so a completion with delta at or past the fixed 256us Emax */ -/* reclaims one reject. */ -/* Like fair.c, vruntime paces order, unlike rt.c, no fixed priority holds. */ -/* C holds burst else slice else quantum, and V holds weight with zero */ -/* mapped to 128, so the slice adapts while virtual time stays untouched. */ -/* Stamps stay per task owned except the run claim uses atomics, and only */ -/* counters use atomics. Cursor and miss scans stay best effort. */ +/* Per task state. Vtime is charged service. Slice holds the time + * left in the current quantum. Gen identifies the running instance. + * Llc records the last enqueue target. Flags holds the queued bit. + * Vd holds the due time for queue order. Burst holds the run length + * used for the due time. */ struct flow_task_ctx { - u64 vruntime; - u64 deadline; - u64 wait_at; - u64 run_at; - u32 hint_w; - u32 avg_ns; - u32 dev_ns; - s32 vlag; - u32 weight; - u32 slice_ns; - u32 hint_us; - u32 misses; - u16 adapt_miss; - u16 adapt_sat; - u32 adapt_delta; -}; -/* Per CPU state at 16B with running pid plus placement cursor plus */ -/* minimum vruntime. Pid holds the task now on the CPU else zero. */ -/* Owner clears use a compare and swap, so a stale exit never clears a */ -/* new owner. Cursor is shared by select SSF plus BSF and dispatch steal */ -/* with stride two and best effort races. A success advances past the */ -/* picked peer, so the next pass starts fresh without a hotspot. Min */ -/* vruntime tracks the smallest served vruntime on the CPU, zero when no */ -/* history, so newly woken tasks clamp without gaining past the lag bound. */ -/* The minimum folds forward only and holds stale on idle with the lag bound */ -/* capping the boost, so no decay timer runs and rejoins stay capped. */ -struct flow_cpu_state { - u32 running_pid; - u32 cursor; - u64 min_vruntime; + s64 vtime; + u64 slice_rem; + u64 gen; + u32 llc_id; + u32 flags; + s64 vd; + u64 burst_ns; }; -/* Per CPU topology view at 8B with sibling plus node. */ -/* Smt sib holds the thread sibling or all ones when unknown. */ -/* Node holds the node id used by placement and dispatch. */ -struct flow_topo { - u32 smt_sib; - u32 node; +/* Arena per task queue node. Storage holds the upstream queue node + * with the pid beside it for owner lookup. The node sits at offset + * zero so a queue pop address is also this address. Sized for the + * task allocator with spare words for growth. */ +struct flow_arena_task { + u64 storage[16]; + s32 pid; + u32 pad; }; -/* Per CPU capacity view at 4B with one units row. */ -/* Units hold the capacity in base units for the slowest sufficient */ -/* pick. A zero row means unknown, so the base applies. */ -struct flow_cpu_cap { - u32 units; +/* Per CPU running view. Gen counts runs. Pad holds the last kicked + * generation, so each run kicks at most once. Vd mirrors the running + * task due time for gap checks. */ +struct flow_running_state { + s64 vtime; + u64 slice_rem; + u64 gen; + u32 llc_id; + u32 pad; + s64 vd; }; -/* Flat period plus weight hint at 8B with one row per id. */ -/* Period holds the period in micros with zero for no hint, and weight */ -/* holds the scheduling share with 128 for neutral. The flat view tunes */ -/* the period plus the weight only, and no group or pool shapes order. */ -struct flow_hint { - u32 period_us; - u32 weight; +/* Per CPU seed from userspace. Holds the CPU id plus the cluster + * index assigned at startup. Cache and node placement come from the + * upstream topology tree, so no cached copy lives here. The cluster + * index stays here as an interim until it moves into the tree data + * pointer, which needs a non-zero data size at tree build time. */ +struct flow_cpu_ctx { + u32 cpu_id; + u32 ccx_id; + u32 reserved; + u32 pad; }; -/* Scheduler counters with 17 fields. Reject plus reclaim moves count */ -/* RED overload plus reclaim detail without an extra map, so stats stay at */ -/* 136B. Overflow plus steal moves count in the local bucket. Rejects plus */ -/* on CPU stay frozen at zero whitelisted for wire compat only without a BPF writer, */ -/* while real rejects count in gate plus RED rejects. Readers must use */ -/* gate_rejects for drops plus red_rejects for overload, and the snapshot */ -/* counts live pids for the on CPU gauge. Miss plus Term where Term equals */ -/* completions stay counters only without queues, so misses plus completions */ -/* record history. Preempt kicks count busy preempts sent, and preempt */ -/* skipped counts every suppressed hold by margin, tail, and eligibility. */ -/* Counters run without a knob. */ -struct flow_sched_stats { - u64 on_cpu; - u64 total_runtime; - u64 inserts; - u64 requeues; - u64 completions; - u64 local_moves; - u64 node_moves; - u64 machine_moves; - u64 kicks; - u64 admits; - u64 rejects; - u64 misses; - u64 gate_rejects; - u64 preempt_kicks; - u64 preempt_skipped; - u64 red_rejects; - u64 red_reclaims; +/* Per LLC counters. The order matches the userspace reader. + * Queued counts tasks waiting in shared queues. Dispatched counts + * moves to a local queue. Fallback counts fallback inserts. Steal + * counts remote moves, with a split count kept on the thief. + * Duplicate counts requeues dropped while already queued. Kick + * counts preempt plus idle and skipped wakes. Overrun counts full + * slice burns. Blocked counts stops that leave the task runnable. + * Orphan counts mask change kicks. Forward counts heads passed to + * their owner. */ +struct flow_llc_stats { + u64 queued; + u64 dispatched; + u64 fallback; + u64 steal; + u64 fb_duplicate; + u64 steal_llc; + u64 kick_preempt; + u64 kick_idle; + u64 kick_skip; + u64 overrun; + u64 blocked; + u64 orphan_kick; + u64 hol_forward; }; -/* Task state holds vruntime plus deadline plus stamps plus predictor */ -/* plus lag plus weight plus slice plus hint plus misses plus adapt */ -/* miss plus sat plus delta in 72 bytes. */ -_Static_assert(sizeof(struct flow_task_ctx) == 72, - "task state stays at 72B"); -/* CPU state holds pid plus cursor plus minimum vruntime in 16 bytes. */ -_Static_assert(sizeof(struct flow_cpu_state) == 16, - "CPU state stays at 16B"); -/* Topology view holds sibling plus node in 8 bytes. */ -_Static_assert(sizeof(struct flow_topo) == 8, - "topology view stays at 8B"); -/* Stats hold 17 counters in 136 bytes. Rejects plus on CPU stay frozen */ -/* at zero for wire compat only with no BPF writer, whitelisted so old */ -/* readers still decode with no behavior change. */ -_Static_assert(sizeof(struct flow_sched_stats) == 136, - "stats stay at 136B"); -/* Queue count holds local plus node plus machine plus overflow. */ -/* Steal reuses peer locals without a new queue, so the count stays. */ -_Static_assert(FLOW_MAX_DSQS == - FLOW_MAX_CPUS + FLOW_MAX_NODES + 2, - "dsq count stays local plus node plus two"); -/* Period holds four max slices, so a 20ms hold never starves past one */ -/* period with no extra timer. Six latency ceilings name burst sizes, */ -/* while five dispatch tiers name queues, so the counts differ by design. */ -_Static_assert(FLOW_PERIOD_NS == 4 * FLOW_SLICE_MAX_NS, - "period stays four times slice max"); -/* Resume gap stays past one period, so only a real stall trips the */ -/* resume path with no false trip on a long slice. */ -_Static_assert(FLOW_RESUME_GAP_NS > FLOW_PERIOD_NS, - "resume gap stays past one period"); -_Static_assert(FLOW_SLICE_MIN_NS < FLOW_SLICE_ULL_NS && - FLOW_SLICE_ULL_NS < FLOW_SLICE_LL_NS && - FLOW_SLICE_LL_NS < FLOW_SLICE_MLL_NS && - FLOW_SLICE_MLL_NS < FLOW_SLICE_NL_NS && - FLOW_SLICE_NL_NS < FLOW_SLICE_ENL_NS && - FLOW_SLICE_ENL_NS < FLOW_SLICE_MAX_NS, - "tier order stays 50us to 20ms plus 10us floor"); -/** - * flow_time_before - test time order with wrap safety. - * @a: first time in nanos. - * @b: second time in nanos. - * - * The signed diff keeps order across the u64 wrap with no branch. - * - * Outlined with noinline to keep verifier headroom on the select plus - * drain paths with no order change, so SSF plus BSF share one copy. - * - * Returns: true when @a falls before @b, else false. - */ -static __noinline bool flow_time_before(u64 a, - u64 b) -{ - return (s64)(a - b) < 0; -} -/** - * flow_sat_add - add two times with clamp on wrap. - * @a: first addend in nanos. - * @b: second addend in nanos. - * - * A wrap clamps to max, so a huge sum never falls to the front. - * - * Returns: saturated sum of @a plus @b. - */ -static __always_inline u64 flow_sat_add(u64 a, - u64 b) -{ - u64 out = a + b; - if (out < a) - return (u64)~0ULL; - return out; -} -/** - * flow_delta_clamp - clamped service delta from start to now. - * @now: current time in nanos. - * @start: segment start in nanos, zero or future folds to zero. - * - * A zero start means no claimed start while a start after now means - * a backward clock, so both read zero with wrap safety and no charge. - * A start at now reads zero through the subtract with no branch. - * - * Returns: saturated service in nanos, zero on bad stamps. - */ -static __always_inline u64 flow_delta_clamp(u64 now, - u64 start) -{ - if (start == 0) - return 0; - if (flow_time_before(now, start)) - return 0; - return now - start; -} -/** - * flow_gap_is_resume - test one delta for a suspend plus resume gap. - * @delta: raw service in nanos already clamped by flow_delta_clamp. - * - * Deltas past the 5s bound read as an s2idle stall where monotonic - * still advances, so the caller clamps to zero with no predictor - * plus minimum plus credit pollution. S3 pauses monotonic, so S3 - * trips only the userspace boot gap with a reseed. - * - * Returns: true when past the resume bound, else false. - */ -static __always_inline bool flow_gap_is_resume(u64 delta) -{ - return delta > (u64)FLOW_RESUME_GAP_NS; -} -/** - * flow_weight_clamp - clamp one share into range. - * @w: raw share with zero for no history. - * - * Zero maps to 1, so an explicit zero earns the lightest share while - * missing state stays neutral via the effective helper. Oversize - * shares fail closed to the top bound. - * - * Returns: clamped share from 1 to 16384. - */ -static __always_inline u32 flow_weight_clamp(u32 w) -{ - if (w < (u32)FLOW_WEIGHT_MIN) - return (u32)FLOW_WEIGHT_MIN; - if (w > (u32)FLOW_WEIGHT_MAX) - return (u32)FLOW_WEIGHT_MAX; - return w; -} -/** - * flow_share_combine - combine two shares into one effective share. - * @task_w: task base share, clamped to range. - * @hint_w: hint share, clamped to range. - * - * Multiplies the shares then shifts right by 7 for divide by 128, - * so the neutral pair of 128 plus 128 stays neutral with no divide. - * A small product clamps to the floor, and a large product clamps - * to the top with no wrap. - * - * Returns: effective share from 1 to 16384. - */ -static __always_inline u32 flow_share_combine(u32 task_w, - u32 hint_w) -{ - u32 t = flow_weight_clamp(task_w); - u32 h = flow_weight_clamp(hint_w); - u64 prod = (u64)t * (u64)h; - u64 eff = prod >> 7; - if (eff < (u64)FLOW_WEIGHT_MIN) - return (u32)FLOW_WEIGHT_MIN; - if (eff > (u64)FLOW_WEIGHT_MAX) - return (u32)FLOW_WEIGHT_MAX; - return (u32)eff; -} -/** - * flow_task_effective_weight - effective share of one task plus hint. - * @task_w: task base share with zero for neutral. - * @hint_w: hint share with zero for neutral. - * - * Maps each zero input to the neutral share of 128, then combines - * with the shared helper, so missing state stays neutral with no - * special case at the caller. - * - * Returns: effective share from 1 to 16384. - */ -static __always_inline u32 flow_task_effective_weight(u32 task_w, - u32 hint_w) -{ - u32 t = task_w ? task_w : (u32)FLOW_WEIGHT_BASE; - u32 h = hint_w ? hint_w : (u32)FLOW_WEIGHT_BASE; - return flow_share_combine(t, h); -} -/** - * flow_scaled_delta - scaled service for one delta at one weight. - * @delta: raw service in nanos. - * @weight: scheduling share, clamped to range. - * - * Scales inversely with weight through one divide, so the neutral - * weight of 128 keeps the delta unchanged while lighter tasks grow - * and heavier tasks shrink with no band jump. Mirrors the fair - * scaler in weight.bpf.c with saturation and a floor of one. - * - * Returns: scaled service in nanos. - */ -static __always_inline u64 flow_scaled_delta(u64 delta, - u32 weight) -{ - u32 w = flow_weight_clamp(weight); - u64 prod; - u64 out; - if (delta == 0) - return 0; - /* Clamp never returns zero, so no zero guard is needed here. */ - if (delta > (u64)~0ULL / (u64)FLOW_WEIGHT_BASE) - return (u64)~0ULL; - prod = delta * (u64)FLOW_WEIGHT_BASE; - out = prod / (u64)w; - if (out == 0) - return 1; - return out; -} -/** - * flow_vruntime_advance - advance vruntime by one delta at one weight. - * @vruntime: base vruntime in nanos. - * @delta: raw service in nanos. - * @weight: scheduling share, clamped to range. - * - * Adds the scaled service to the base, so heavy tasks advance slowly - * while light tasks advance quickly with one divide. A wrap clamps to - * max, so a huge vruntime never falls to the front. - * - * Returns: advanced vruntime in nanos. - */ -static __always_inline u64 flow_vruntime_advance(u64 vruntime, - u64 delta, u32 weight) -{ - return flow_sat_add(vruntime, flow_scaled_delta(delta, weight)); -} -/** - * flow_lag_clamp - clamp lag within the allowed bound. - * @lag: raw lag in nanos as a signed bound. - * - * Values past plus or minus 2ms fold to the nearer bound with - * saturation, so a stale lag never grants a huge boost with no storm. - * - * Returns: clamped lag from minus 2ms to 2ms. - */ -static __always_inline s32 flow_lag_clamp(s32 lag) -{ - s32 bound = (s32)FLOW_VLAG_MAX_NS; - if (lag > bound) - return bound; - if (lag < -bound) - return -bound; - return lag; -} -/** - * flow_eligible - test vruntime eligibility against the CPU minimum. - * @vruntime: task vruntime in nanos. - * @min_vruntime: CPU minimum vruntime in nanos. - * @vlag: allowed lag in nanos as a signed bound. - * - * Eligible means the vruntime falls no more than the allowed lag past - * the minimum, so lagging tasks wait while leading tasks pace. A negative - * lag clamps to zero with no boost, so a negative bound never grants slack. - * The signed diff keeps order across the u64 wrap with no branch, and a - * saturated minimum plus lag never wraps to the front. - * - * Returns: true when eligible, else false. - */ -static __always_inline bool flow_eligible(u64 vruntime, - u64 min_vruntime, s32 vlag) -{ - s32 lag = flow_lag_clamp(vlag); - u64 limit; - if (lag < 0) - lag = 0; - limit = flow_sat_add(min_vruntime, (u64)lag); - if (limit == (u64)~0ULL) - return true; - if (vruntime == limit) - return true; - return flow_time_before(vruntime, limit); -} -/** - * flow_virt_deadline - virtual deadline from base plus request. - * @ve: eligible base in nanos. - * @request: requested service in nanos. - * @weight: scheduling share, clamped to range. - * - * Adds the scaled request to the eligible base with saturation, so a - * heavy task earns a near deadline while a light task earns a far one - * with one divide. A wrap clamps to max, so a huge sum never jumps to - * the front. - * - * Returns: virtual deadline in nanos. - */ -static __always_inline u64 flow_virt_deadline(u64 ve, - u64 request, u32 weight) -{ - return flow_sat_add(ve, flow_scaled_delta(request, weight)); -} -/** - * flow_edf_key - strict EDF sort key from deadline plus virtual time. - * @deadline: absolute EDF deadline in nanos, zero for no order. - * @vd: virtual deadline in nanos, zero for no order. - * - * The EDF deadline caps latency while the virtual deadline paces - * fairness, so urgent tasks still win while hogs fall behind. A zero - * deadline means no EDF order yet, so the virtual deadline rules. The - * signed diff picks the earlier time with wrap safety, so the closest - * deadline always wins without a band jump. - * - * Returns: earlier of @deadline plus @vd in nanos. - */ -static __always_inline u64 flow_edf_key(u64 deadline, - u64 vd) +#ifdef __BPF__ +static __always_inline bool flow_llc_ok(u32 llc) { - if (deadline == 0) - return vd; - if (vd == 0) - return deadline; - if (flow_time_before(vd, deadline)) - return vd; - return deadline; + return llc < (u32)FLOW_MAX_LLCS; } -/** - * flow_remaining_ns - saturated time left until the deadline. - * @deadline: absolute EDF deadline in nanos, zero for no order. - * @now: current time in nanos. - * - * Feeds the dynamic slice plus slack display only, never the sort key, - * so the order stays the strict earlier of deadline plus virtual time. - * A zero deadline means no order yet, and a past deadline means no - * time left, so both read zero. - * - * Returns: saturated remaining time in nanos. - */ -static __always_inline u64 flow_remaining_ns(u64 deadline, - u64 now) -{ - if (deadline == 0) - return 0; - if (flow_time_before(now, deadline)) - return deadline - now; - return 0; -} -/** - * flow_sleep_ns - true sleep gap as now minus wait minus burst. - * @old_wait: last wait stamp in nanos, zero for unknown. - * @now: current time in nanos. - * @avg: burst average in nanos, zero for no history. - * - * Isolates the true gap as now minus wait minus burst, so queue plus - * run never look like sleep. A zero wait, a wait at or after now, and a - * burst-covered gap all read zero with wrap safety, so newcomers plus - * requeues fail open. - * - * Returns: sleep time in nanos, zero when unknown. - */ -static __always_inline u64 flow_sleep_ns(u64 old_wait, u64 now, - u64 avg) -{ - u64 gap; - if (old_wait == 0) - return 0; - if (!flow_time_before(old_wait, now)) - return 0; - gap = now - old_wait; - if (avg != 0) { - if (gap > avg) - gap -= avg; - else - gap = 0; - } - return gap; -} -/** - * flow_slice_for - dynamic slice from the saturated remaining time. - * @deadline: absolute EDF deadline in nanos. - * @now: current time in nanos. - * - * Clamps the remaining time to the 10us floor plus the 1ms ceiling - * with no knob, so near deadlines pace tightly while far deadlines - * still rotate each millisecond. A zero plus a past deadline floors - * to 10us with no zero slice. - * - * Returns: dynamic slice in nanos from 10us to 1ms. - */ -static __always_inline u32 flow_slice_for(u64 deadline, - u64 now) -{ - u64 rem = flow_remaining_ns(deadline, now); - if (rem < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (rem > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)rem; -} -/** - * flow_slice_inherit - slice default for zero stored state. - * @cur: stored slice in nanos, zero for no history. - * - * A zero slice means no history, so the 1ms quantum applies with no - * extra write at the caller. - * - * Returns: @cur else the 1ms quantum. - */ -static __always_inline u32 flow_slice_inherit(u32 cur) +static __always_inline bool flow_cpu_ok(u32 cpu) { - if (cur == 0) - return (u32)FLOW_QUANTUM_NS; - return cur; + return cpu < (u32)FLOW_MAX_CPUS; } -/** - * flow_slice_miss_hold - miss slice with hold else floor only. - * @cur: stored slice in nanos, zero for no history. - * - * A miss never recomputes the dynamic slice, so the miss path holds - * the stored charge else floors it to 10us with no zero slice and no - * knob. The fresh deadline plus the re-derived tier rejoin carry the - * urgency with skip aging in the miss count. Pinned plus open miss - * paths share this helper, so the two holds never skew. - * - * Returns: held slice else the 10us floor. - */ -static __always_inline u32 flow_slice_miss_hold(u32 cur) -{ - u32 s = flow_slice_inherit(cur); - if (s < (u32)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - return s; -} -/** - * flow_red_cost - worst cost from burst else slice else quantum. - * @avg: burst average in nanos, zero for no history. - * @slice: stored slice in nanos, zero for no history. - * - * The cost bounds the guarantee with no share shaping. A burst average - * wins when present, else the stored slice, else the 1ms quantum, so C - * tracks recent runs with no table walk. Caps at the 20ms slice max, - * so a throughput burst never underestimates past the 1ms quantum - * with no share shaping. - * - * Returns: cost in nanos from 10us to 20ms. - */ -static __always_inline u64 flow_red_cost(u64 avg, u32 slice) -{ - if (avg) { - if (avg < (u64)FLOW_SLICE_MIN_NS) - return (u64)FLOW_SLICE_MIN_NS; - if (avg > (u64)FLOW_SLICE_MAX_NS) - return (u64)FLOW_SLICE_MAX_NS; - return avg; - } - if (slice) { - if ((u64)slice < (u64)FLOW_SLICE_MIN_NS) - return (u64)FLOW_SLICE_MIN_NS; - if ((u64)slice > (u64)FLOW_SLICE_MAX_NS) - return (u64)FLOW_SLICE_MAX_NS; - return (u64)slice; - } - return (u64)FLOW_QUANTUM_NS; -} -/** - * flow_red_tol - guarantee tolerance for one task. - * @is_crit: true when latency-critical via the unified latency test - * with no tolerance, false for hard batch. - * - * Tolerance aids the guarantee only with no order shaping. Hard batch - * keeps 64us while latency-critical keeps zero, so the check stays - * strict for urgent work with no separate class past latency. Admit - * plus reclaim share this fixed path, so both agree. - * - * Returns: tolerance in nanos, zero for latency-critical. - */ -static __always_inline u64 flow_red_tol(bool is_crit) -{ - if (is_crit) - return 0; - return (u64)FLOW_RED_TOL_NS; -} -/** - * flow_red_residual - residual time from deadline plus cost. - * @deadline: absolute deadline in nanos, zero means no order. - * @now: current time in nanos. - * @cost: remaining worst cost in nanos. - * - * The residual tests the guarantee with no vruntime shaping. A zero deadline means no order, so the check - * passes with a large residual. A past deadline yields a negative - * residual with wrap safety. - * - * Returns: signed residual in nanos. - */ -static __always_inline s64 flow_red_residual(u64 deadline, u64 now, - u64 cost) -{ - s64 left; - if (deadline == 0) - return (s64)FLOW_PRED_MAX_NS; - if (flow_time_before(now, deadline)) - left = (s64)(deadline - now); - else if (now == deadline) - left = 0; - else - left = -((s64)(now - deadline)); - left -= (s64)cost; - return left; -} -/** - * flow_red_exceed - exceeding time from residual plus tolerance. - * @resid: signed residual in nanos. - * @tol: guarantee tolerance in nanos, zero for critical. - * - * The exceed marks lateness without shaping shares. A residual plus - * tolerance at or past zero means no exceed, else the negated sum bounds - * the needed reclaim. - * - * Returns: exceeding time in nanos, zero when schedulable. - */ -static __always_inline u64 flow_red_exceed(s64 resid, u64 tol) -{ - s64 sum = resid + (s64)tol; - if (sum >= 0) - return 0; - return (u64)(-sum); -} -/** - * flow_red_value - admission value from weight plus critical. - * @weight: task base share, zero maps to 128. - * @is_crit: true marks latency-critical via the unified latency test - * with maximum value, false for hard batch. - * - * Value orders the reject queue without shaping vruntime. - * Latency-critical holds the top value while hard batch holds the - * clamped base share, so the greatest value reclaims first with no - * separate class past latency. - * - * Returns: value from 1 to 16384, top for latency-critical. - */ -static __always_inline u32 flow_red_value(u32 weight, bool is_crit) -{ - if (is_crit) - return (u32)FLOW_WEIGHT_MAX; - if (weight == 0) - weight = (u32)FLOW_WEIGHT_BASE; - return flow_weight_clamp(weight); -} -/** - * flow_red_laxity - laxity from deadline plus cost. - * @deadline: absolute deadline in nanos, zero means no order. - * @now: current time in nanos. - * @cost: remaining worst cost in nanos. - * - * Laxity gates reclaim with no vruntime shaping. A zero deadline means no order with zero laxity, a past - * deadline means no laxity, else the saturated remainder holds. - * - * Returns: laxity in nanos, zero when none. - */ -static __always_inline u64 flow_red_laxity(u64 deadline, u64 now, - u64 cost) -{ - u64 rem; - if (deadline == 0) - return 0; - if (!flow_time_before(now, deadline) && now != deadline) - return 0; - rem = deadline - now; - if (rem < cost) - return 0; - return rem - cost; -} -/** - * flow_reject_key - reject queue key from value. - * @value: admission value from 1 to 16384. - * - * Orders the reject queue by decreasing value through the kernel - * priority queue, so the greatest value drains first on reclaim. A - * larger value maps to a smaller key with no wrap. - * - * Returns: queue key in nanos. - */ -static __always_inline u64 flow_reject_key(u32 value) -{ - u32 v = flow_weight_clamp(value); - return (u64)((u32)FLOW_WEIGHT_MAX - v); -} -/** - * flow_adapt_up - widen the slice by 64us with clamp. - * @cur: stored slice in nanos, zero inherits the quantum. - * - * Frozen, unused after the proportional law, kept for wire compat only - * with no caller, so old headers still decode with no behavior change. - * Like fair.c, the step paces service, unlike rt.c, no fixed priority - * holds. Adds 64us with saturation, then clamps to 10us plus 1ms, - * so a miss earns room with no wrap. Virtual time stays untouched. - * - * Returns: adapted slice in nanos from 10us to 1ms. - */ -static __always_inline __attribute__((unused)) u32 flow_adapt_up(u32 cur) -{ - u64 s = (u64)flow_slice_inherit(cur); - s = flow_sat_add(s, (u64)FLOW_ADAPT_GROW_NS); - if (s < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (s > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)s; -} -/** - * flow_adapt_down - narrow the slice by 128us with clamp. - * @cur: stored slice in nanos, zero inherits the quantum. - * - * Frozen, unused after the proportional law, kept for wire compat only - * with no caller, so old headers still decode with no behavior change. - * Like fair.c, the step tracks load, unlike rt.c, no fixed priority - * holds. Subtracts 128us with floor at 10us, then clamps to 1ms, so - * a hit returns room with no stall. Virtual time stays untouched. - * - * Returns: adapted slice in nanos from 10us to 1ms. - */ -static __always_inline __attribute__((unused)) u32 flow_adapt_down(u32 cur) -{ - u64 s = (u64)flow_slice_inherit(cur); - if (s <= (u64)FLOW_ADAPT_SHRINK_NS) - return (u32)FLOW_SLICE_MIN_NS; - s -= (u64)FLOW_ADAPT_SHRINK_NS; - if (s < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (s > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)s; -} -/** - * flow_adapt_deadband - quiet band for one base slice. - * @base: clamped base slice in nanos from 10us to 1ms. - * - * Takes the larger of base shifted right by DEADBAND_SHIFT plus the 8us - * floor, so small slices keep a real band while large slices scale with - * shifts only and no divide. - * - * Returns: deadband in nanos. - */ -static __always_inline u64 flow_adapt_deadband(u64 base) +static __always_inline bool flow_node_ok(u32 node) { - u64 band = base >> FLOW_ADAPT_DEADBAND_SHIFT; - if (band < (u64)FLOW_ADAPT_DEADBAND_MIN_NS) - return (u64)FLOW_ADAPT_DEADBAND_MIN_NS; - return band; + return node < (u32)FLOW_MAX_NODES; } -/** - * flow_adapt_prop - proportional slice from exceed plus slack with clamp. - * @cur: stored slice in nanos, zero inherits the quantum. - * @exceed: lateness in nanos, now minus expiring deadline else zero. - * @slack: earliness in nanos, expiring deadline minus now else zero. - * - * Like fair.c, the step paces service, unlike rt.c, no fixed priority - * holds. An exceed shrinks by exceed shifted right by SHIFT, a slack - * grows by slack shifted right by SHIFT, each capped at 1ms plus half - * of base then halved once more by the damp shift, so one step moves - * at most one quarter base with shifts only. Exceed plus slack at or - * below the proportional deadband hold the clamped slice with no hunt, - * so timer jitter never rings. Clamps to 10us plus 1ms, so one step - * never stalls nor holds the CPU. An on-time stop with both zero holds - * the clamped slice. Exceed wins when both hold. Virtual time - * stays untouched, RED never writes the slice, and the caller keeps the - * carry gate first on the same expiring deadline. Latency callers re-clamp - * the result to 100us past the 1ms step, so one shift never holds past - * the cap. - * - * Returns: adapted slice in nanos from 10us to 1ms. - */ -static __always_inline u32 flow_adapt_prop(u32 cur, u64 exceed, - u64 slack) -{ - u64 base = (u64)flow_slice_inherit(cur); - u64 band = flow_adapt_deadband(base); - u64 step; - u64 nxt; - if (exceed) { - if (exceed <= band) { - if (base < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (base > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)base; - } - step = exceed >> FLOW_ADAPT_PROP_SHIFT; - if (step > (u64)FLOW_ADAPT_PROP_MAX_NS) - step = (u64)FLOW_ADAPT_PROP_MAX_NS; - if (step > (base >> 1)) - step = base >> 1; - step >>= FLOW_ADAPT_DAMP_SHIFT; - if (step == 0) { - if (base < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (base > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)base; - } - if (base <= step) - return (u32)FLOW_SLICE_MIN_NS; - nxt = base - step; - if (nxt < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (nxt > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)nxt; - } - if (slack) { - if (slack <= band) { - if (base < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (base > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)base; - } - step = slack >> FLOW_ADAPT_PROP_SHIFT; - if (step > (u64)FLOW_ADAPT_PROP_MAX_NS) - step = (u64)FLOW_ADAPT_PROP_MAX_NS; - if (step > (base >> 1)) - step = base >> 1; - step >>= FLOW_ADAPT_DAMP_SHIFT; - if (step == 0) { - if (base < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (base > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)base; - } - nxt = flow_sat_add(base, step); - if (nxt < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (nxt > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)nxt; - } - if (base < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (base > (u64)FLOW_QUANTUM_NS) - return (u32)FLOW_QUANTUM_NS; - return (u32)base; -} -/** - * flow_carry_for - carryover slice from unused quantum with clamp. - * @delta: raw service in nanos of the yielding slice. - * - * Keeps the unused quantum remainder as quantum minus delta with clamp - * to 10us plus 1ms through the adapt bounds, so a tiny remainder never - * floors below the slice minimum. Uses the fixed 1ms quantum, not the - * stored slice, so short bursts carry the true unused quantum without - * changing virtual time. Callers gate on runnable, short, and - * latency-critical without a wall miss, so only short bursts carry. - * - * Returns: carry slice in nanos from 10us to 1ms. - */ -static __always_inline u32 flow_carry_for(u64 delta) -{ - u64 q = (u64)FLOW_QUANTUM_NS; - u64 c; - if (delta >= q) - return (u32)FLOW_SLICE_MIN_NS; - c = q - delta; - if (c < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (c > q) - return (u32)FLOW_QUANTUM_NS; - return (u32)c; -} -/** - * flow_slice_resume - remaining slice for a preempted head with clamp. - * @occ_start: segment start in nanos, zero or max falls back to inherit. - * @now: current time in nanos. - * @occ_lat: true caps the ceiling at 100us else 1ms. - * @cur: stored slice in nanos, zero inherits the quantum. - * - * Keeps occ_end minus now with occ_end at start plus the stored slice, - * clamped to 10us plus 100us for latency else 1ms, so a preempted head - * resumes with its leftover. A bad start or a saturated end falls back - * to the inherited slice, while a past end floors to the minimum with - * wrap-safe order. The tail check lives in the caller as delta plus 100us - * below cur with history and no wall miss, so this helper keeps no tail - * check and only preempt-like early yields resume without changing - * virtual time. Equality fails closed and floors, so a latency head at - * the 100us cap never resumes past the equal tail. - * - * Returns: remaining slice else inherited slice on bad start plus end. - */ -static __always_inline u32 flow_slice_resume(u64 occ_start, u64 now, - bool occ_lat, u32 cur) -{ - u64 base; - u64 occ_end; - u64 rem; - u64 cap; - if (occ_start == 0 || occ_start == (u64)~0ULL) - return flow_slice_inherit(cur); - base = (u64)flow_slice_inherit(cur); - occ_end = flow_sat_add(occ_start, base); - if (occ_end == (u64)~0ULL) - return flow_slice_inherit(cur); - if (!flow_time_before(now, occ_end) && now != occ_end) - rem = 0; - else if (flow_time_before(now, occ_end)) - rem = occ_end - now; - else - rem = 0; - cap = occ_lat ? (u64)FLOW_SLICE_LAT_NS : (u64)FLOW_QUANTUM_NS; - if (rem < (u64)FLOW_SLICE_MIN_NS) - return (u32)FLOW_SLICE_MIN_NS; - if (rem > cap) - return (u32)cap; - return (u32)rem; -} -/** - * flow_deadline_at - absolute deadline from now plus period. - * @now: current time in nanos. - * @period: relative period in nanos. - * - * The add saturates, so a huge now clamps instead of wrapping to - * the front. - * - * Returns: absolute deadline in nanos. - */ -static __always_inline u64 flow_deadline_at(u64 now, - u64 period) -{ - return flow_sat_add(now, period); -} -/** - * flow_task_period - period for one task from hint else default. - * @hint_us: flat period hint in micros, zero for no hint. - * - * A zero hint means no hint, so the default period of 80ms applies. - * The hint converts from micros to nanos with saturation, so a huge - * hint clamps instead of wrapping to a short period. - * - * Returns: period in nanos. - */ -static __always_inline u64 flow_task_period(u32 hint_us) -{ - u64 hint; - if (!hint_us) - return (u64)FLOW_PERIOD_NS; - hint = (u64)hint_us; - if (hint > 18446744073709551ULL) - return (u64)~0ULL; - return hint * 1000ULL; -} -/** - * flow_pred_clamp - clamp predictor value to 1ns to 1s. - * @v: raw value in nanos. - * - * Values below the floor rise to 1ns and values past the top fall - * to 1s, so a huge burst never wraps to a short deadline. - * - * Returns: clamped value in nanos. - */ -static __always_inline u64 flow_pred_clamp(u64 v) -{ - if (v < (u64)FLOW_PRED_MIN_NS) - return (u64)FLOW_PRED_MIN_NS; - if (v > (u64)FLOW_PRED_MAX_NS) - return (u64)FLOW_PRED_MAX_NS; - return v; -} -/** - * flow_pred_avg - updated burst average with up plus down shifts. - * @avg: old average in nanos, zero for no history. - * @delta: new sample in nanos. - * - * A zero average means no history, so the first sample sets the - * average at once. Rises move one eighth with UP_SHIFT 3 while falls - * move one sixteenth with DOWN_SHIFT 4, so bursts grow fast plus decay - * slow with shifts only and no divide. The result clamps to 1ns to 1s, - * so a spike never wraps. - * - * Returns: updated average in nanos. - */ -static __always_inline u64 flow_pred_avg(u64 avg, - u64 delta) -{ - u64 d; - u64 diff; - d = flow_pred_clamp(delta ? delta : - (u64)FLOW_PRED_MIN_NS); - if (avg == 0) - return d; - if (d > avg) { - diff = (d - avg) >> FLOW_PRED_UP_SHIFT; - return flow_pred_clamp(flow_sat_add(avg, - diff)); - } - diff = (avg - d) >> FLOW_PRED_DOWN_SHIFT; - if (diff > avg) - return (u64)FLOW_PRED_MIN_NS; - return flow_pred_clamp(avg - diff); -} -/** - * flow_pred_dev - updated burst deviation with up plus down shifts. - * @dev: old deviation in nanos, zero for no history. - * @avg: new average in nanos from flow_pred_avg, zero for no history. - * @delta: new sample in nanos. - * - * Tracks the absolute error between delta and the new average with - * widen shift 2 plus narrow shift 3, so a stable burst keeps a small - * margin while a ragged burst widens fast with no jump. Callers pass - * the new average from flow_pred_avg, so the margin tracks the fresh - * mean. A zero deviation means no history, so the first value takes - * the max of error and new average quarter as the floor. The result - * clamps the same way with no divide. - * - * Returns: updated deviation in nanos. - */ -static __always_inline u64 flow_pred_dev(u64 dev, - u64 avg, u64 delta) -{ - u64 d; - u64 a; - u64 err; - u64 diff; - u64 floor; - d = flow_pred_clamp(delta ? delta : - (u64)FLOW_PRED_MIN_NS); - a = avg ? avg : d; - err = d > a ? d - a : a - d; - err = flow_pred_clamp(err ? err : - (u64)FLOW_PRED_MIN_NS); - if (dev == 0) { - floor = avg >> 2; - if (floor > err) - return flow_pred_clamp(floor); - return err; - } - if (err > dev) { - diff = (err - dev) >> FLOW_PRED_DEV_UP_SHIFT; - return flow_pred_clamp(flow_sat_add(dev, - diff)); - } - diff = (dev - err) >> FLOW_PRED_DEV_DOWN_SHIFT; - if (diff > dev) - return (u64)FLOW_PRED_MIN_NS; - return flow_pred_clamp(dev - diff); -} -/** - * flow_pred_period - predicted period from average plus margin dev. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * - * A zero average means no history, so the default period of 80ms - * applies. Later periods add average plus deviation plus half deviation - * with saturation, so a stable burst keeps a tight deadline while a - * ragged burst holds one and a half deviation margin with no wrap past - * 1s and shifts only. - * - * Returns: predicted period in nanos. - */ -static __always_inline u64 flow_pred_period(u64 avg, - u64 dev) -{ - u64 sum; - u64 margin; - if (avg == 0) - return (u64)FLOW_PERIOD_NS; - margin = dev >> FLOW_PRED_DEV_MARGIN_SHIFT; - sum = flow_sat_add(avg, dev); - sum = flow_sat_add(sum, margin); - if (sum == (u64)~0ULL) - return (u64)FLOW_PRED_MAX_NS; - return flow_pred_clamp(sum); -} -/** - * flow_pred_deadline - predicted deadline from now plus predictor. - * @now: current time in nanos. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @hint_us: flat period hint in micros, zero for no hint. - * - * A zero average means no history, so the hint period applies with - * the default of 80ms when the hint is zero. Later wakeups add the - * predicted period with saturation, so a huge now clamps instead of - * wrapping to the front. Fair order via kernel priority queue holds - * the earlier of this deadline plus the virtual deadline, so the - * earliest fair time wins with lag bounds. - * - * Returns: absolute deadline in nanos. - */ -static __always_inline u64 flow_pred_deadline(u64 now, - u64 avg, u64 dev, u32 hint_us) -{ - u64 period; - if (avg == 0) - period = flow_task_period(hint_us); - else - period = flow_pred_period(avg, dev); - return flow_deadline_at(now, period); -} -/** - * flow_lat_crit - test latency-critical from predictor slack. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * - * A zero average means no history, so the task counts as batch with - * probation. Later tasks add average plus deviation plus half deviation - * margin with saturation, so a short predicted burst within one quantum - * stays critical while a long burst paces at slice expiry. Uses the - * quantum without a new map. - * - * Returns: true when latency-critical, else false. - */ -static __always_inline bool flow_lat_crit(u64 avg, - u64 dev) -{ - u64 pred; - u64 margin; - if (avg == 0) - return false; - margin = dev >> FLOW_PRED_DEV_MARGIN_SHIFT; - pred = flow_sat_add(avg, dev); - pred = flow_sat_add(pred, margin); - if (pred == (u64)~0ULL) - return false; - return pred <= (u64)FLOW_QUANTUM_NS; -} -/** - * flow_slice_lat_clamp - clamp one slice to the latency cap. - * @slice: stored slice in nanos. - * @is_lat: true when latency-critical with the 100us cap. - * - * Like fair.c, the cap paces service, unlike rt.c, no fixed priority - * holds. A latency task keeps the smaller of the slice plus the 100us - * cap, so urgent wakeups rotate each tenth quantum. A non latency task - * keeps the slice unchanged. - * - * Returns: capped slice for latency else @slice. - */ -static __always_inline u32 flow_slice_lat_clamp(u32 slice, - bool is_lat) -{ - if (is_lat && slice > (u32)FLOW_SLICE_LAT_NS) - return (u32)FLOW_SLICE_LAT_NS; - return slice; -} -/** - * flow_classify_latency_tier - tier ceiling from predicted burst. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @is_crit: true forces the ULL ceiling for critical work. - * - * Like fair.c, the tier paces service, unlike rt.c, no fixed priority - * holds. Adds average plus deviation plus half deviation margin with - * saturation, so a stable burst keeps a tight tier while a ragged burst - * holds margin. Critical work plus a prediction at or below 50us earns - * the ULL ceiling, then 100us plus 500us plus 1ms plus 5ms bound LL plus - * MLL plus NL plus ENL, else the 20ms ceiling holds throughput. Fresh - * waits cap the dynamic slice by this ceiling capped at 1ms, so audio - * plus UI plus IPC plus desktop pace tightly with no extra hold, while - * bulk still rotates each quantum. Six latency ceilings name burst - * sizes apart from five dispatch tiers. - * - * Returns: tier ceiling in nanos from 50us to 20ms. - */ -static __always_inline u32 flow_classify_latency_tier(u64 avg, u64 dev, - bool is_crit) -{ - u64 margin = dev >> FLOW_PRED_DEV_MARGIN_SHIFT; - u64 pred = flow_sat_add(avg, dev); - pred = flow_sat_add(pred, margin); - if (is_crit || pred <= (u64)FLOW_SLICE_ULL_NS) - return (u32)FLOW_SLICE_ULL_NS; - if (pred <= (u64)FLOW_SLICE_LL_NS) - return (u32)FLOW_SLICE_LL_NS; - if (pred <= (u64)FLOW_SLICE_MLL_NS) - return (u32)FLOW_SLICE_MLL_NS; - if (pred <= (u64)FLOW_SLICE_NL_NS) - return (u32)FLOW_SLICE_NL_NS; - if (pred <= (u64)FLOW_SLICE_ENL_NS) - return (u32)FLOW_SLICE_ENL_NS; - return (u32)FLOW_SLICE_MAX_NS; -} -/** - * flow_slice_tier_cap - cap one dynamic slice by the predicted tier. - * @pre: dynamic slice in nanos from the remaining clamp. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @is_lat: true forces the ULL ceiling for critical work. - * - * Caps the tier at the 1ms quantum, so small bursts pace tightly while - * bulk still rotates each quantum with no extra hold. The 5ms plus - * 20ms ceilings cap here too, so throughput never holds past one - * quantum on fresh waits. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so open plus pinned share the same tier logic with no inline - * growth. - * - * Returns: capped slice in nanos from 10us to 1ms. - */ -static __noinline u32 flow_slice_tier_cap(u32 pre, u64 avg, u64 dev, - bool is_lat) -{ - u32 tier = flow_classify_latency_tier(avg, dev, is_lat); - if (tier > (u32)FLOW_QUANTUM_NS) - tier = (u32)FLOW_QUANTUM_NS; - if (pre > tier) - pre = tier; - return pre; -} -/** - * flow_lat_deadline - latency deadline from now plus slice plus margin. - * @now: current time in nanos. - * @slice: clamped slice in nanos. - * - * Takes the larger of the 4ms bound plus slice plus 100us with - * saturation, then adds now with saturation, so a huge slice never - * wraps to the front and ns accuracy holds. Like fair.c, the bound - * paces order, unlike rt.c, no fixed priority holds. Uses shifts without - * a divide. - * - * Returns: absolute latency deadline in nanos. - */ -static __always_inline u64 flow_lat_deadline(u64 now, - u32 slice) -{ - u64 need = flow_sat_add((u64)slice, - (u64)FLOW_PREEMPT_MARGIN_NS); - u64 bound = need > (u64)FLOW_D_LAT_NS ? need : - (u64)FLOW_D_LAT_NS; - return flow_sat_add(now, bound); -} -/** - * flow_lat_crit_ext - extended latency test with advisory veto. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @hint_us: flat period hint in micros, zero for no hint. - * @sleep_ns: sleep time in nanos, zero for unknown. - * @uclamp_min: uclamp minimum 0 to 1024, zero for unknown. - * @eff_w: effective share, zero for unknown. - * - * Like fair.c, the test paces service, unlike rt.c, no fixed priority - * holds. Newcomers with no history stay batch with probation, so only - * observed bursts earn latency. Each signal vetoes only toward batch with - * quantum-relative bounds using shifts only, so unknown sleep, clamp, and - * share fail open. A predicted burst past one quantum vetoes, a hint - * period past one quantum vetoes, a short sleep below 20us vetoes, an - * explicit low clamp below half vetoes, and a light share below 128 - * vetoes. The sleep floor stays decoupled from the 100us slice cap, so - * the veto needs only a short nap. All pass keeps latency. - * - * Returns: true when latency holds, else false for batch. - */ -static __always_inline bool flow_lat_crit_ext(u64 avg, - u64 dev, u32 hint_us, u64 sleep_ns, u32 uclamp_min, - u32 eff_w) -{ - u64 pred; - u64 margin; - u64 hint_ns; - if (avg == 0) - return false; - margin = dev >> FLOW_PRED_DEV_MARGIN_SHIFT; - pred = flow_sat_add(avg, dev); - pred = flow_sat_add(pred, margin); - if (pred == (u64)~0ULL) - return false; - if (pred > (u64)FLOW_QUANTUM_NS) - return false; - if (hint_us != 0) { - u64 h = (u64)hint_us; - if (h > 18446744073709551ULL) - return false; - hint_ns = h * 1000ULL; - if (hint_ns > (u64)FLOW_QUANTUM_NS) - return false; - } - if (sleep_ns != 0) { - if (sleep_ns < (u64)FLOW_LAT_SLEEP_MIN_NS) - return false; - } - if (uclamp_min != 0) { - if (uclamp_min < (u32)FLOW_CPU_PERF_HALF) - return false; - } - if (eff_w != 0) { - if (eff_w < (u32)FLOW_WEIGHT_BASE) - return false; - } - return true; -} -/** - * flow_is_lat - unified latency test from base plus ext. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @hint_us: flat period hint in micros, zero for no hint. - * @sleep_ns: sleep time in nanos, zero for unknown. - * @uclamp_min: uclamp minimum 0 to 1024, zero for unknown. - * @eff_w: effective share, zero for unknown. - * - * Unifies the base predictor plus the extended veto, so every path - * agrees with RED critical on the same value. Newcomers stay batch - * with probation through both helpers, so no path needs a separate - * fail-open case. Like fair.c, the test paces service, unlike rt.c, no - * fixed priority holds. - * - * Returns: true when latency holds, else false for batch. - */ -static __always_inline bool flow_is_lat(u64 avg, u64 dev, - u32 hint_us, u64 sleep_ns, u32 uclamp_min, u32 eff_w) -{ - if (!flow_lat_crit(avg, dev)) - return false; - return flow_lat_crit_ext(avg, dev, hint_us, sleep_ns, - uclamp_min, eff_w); -} -/** - * flow_fallback_deadline - fallback deadline from now plus hint. - * @now: current time in nanos. - * @hint_us: flat period hint in micros, zero for no hint. - * - * Tasks with no state or no history join a tier queue at once with - * this deadline, so no path needs a tail queue. - * - * Returns: absolute deadline in nanos. - */ -static __always_inline u64 flow_fallback_deadline(u64 now, - u32 hint_us) -{ - return flow_deadline_at(now, flow_task_period(hint_us)); -} -/** - * flow_missed - test deadline miss at the given time. - * @deadline: absolute deadline in nanos, zero for no order. - * @now: current time in nanos. - * - * A zero deadline means no order yet, so the check skips. A time that - * falls before or on the deadline passes, so only a strictly later time - * counts a miss with wrap safety. Miss counts stay lifetime with - * saturation, so promotion latches. - * - * Returns: true when missed, else false. - */ -static __always_inline bool flow_missed(u64 deadline, - u64 now) -{ - if (deadline == 0) - return false; - if (flow_time_before(now, deadline)) - return false; - if (now == deadline) - return false; - return true; -} -/** - * flow_local_dsq - local queue id of one CPU. - * @cpu: CPU id below the 1024 bound. - * - * One ordered queue per CPU keeps fair order local. - * - * Returns: local queue id. - */ -static __always_inline u64 flow_local_dsq(u32 cpu) -{ - return (u64)FLOW_LOCAL_BASE + (u64)cpu; -} -/** - * flow_node_dsq - shared queue id of one node. - * @node: node id below the 16 bound. - * - * One ordered queue per node shares work inside the node. - * - * Returns: node queue id. - */ -static __always_inline u64 flow_node_dsq(u32 node) -{ - return (u64)FLOW_NODE_BASE + (u64)node; -} -/** - * flow_machine_dsq - id of the machine queue. - * - * Work with no node home rests here with mask wins on drain. - * - * Returns: machine queue id shared by every CPU. - */ -static __always_inline u64 flow_machine_dsq(void) -{ - return (u64)FLOW_MACHINE; -} -/** - * flow_overflow_dsq - id of the value ordered reject queue. - * - * Bursts past tier order wait here by value with mask wins. - * - * Returns: overflow queue id shared by every CPU. - */ -static __always_inline u64 flow_overflow_dsq(void) -{ - return (u64)FLOW_OVERFLOW; -} -/** - * flow_dsq_valid - test live scheduler queue id. - * @dsq: queue id to test. - * - * Local plus node plus machine plus overflow pass, and all other ids - * fail, so a stale id never moves work. Sparse nodes fold to machine - * at the caller, so holes in the node view stay safe. The kernel global - * queue never passes for wire compat with homeless work in machine. - * - * Returns: true when live, else false. - */ -static __always_inline bool flow_dsq_valid(u64 dsq) -{ - if (dsq >= (u64)FLOW_LOCAL_BASE && - dsq < (u64)FLOW_LOCAL_BASE + (u64)FLOW_MAX_CPUS) - return true; - if (dsq >= (u64)FLOW_NODE_BASE && - dsq < (u64)FLOW_NODE_BASE + (u64)FLOW_MAX_NODES) - return true; - if (dsq == (u64)FLOW_MACHINE) - return true; - if (dsq == (u64)FLOW_OVERFLOW) - return true; - return false; -} -/** - * flow_is_pow2 - test power of two with no divide. - * @n: value to test. - * - * Zero never counts as a power of two, so the mask path never - * runs on an empty host with no divide by zero. - * - * Returns: true when @n holds exactly one bit, else false. - */ -static __always_inline bool flow_is_pow2(u64 n) -{ - return n != 0 && (n & (n - 1ULL)) == 0; -} -/** - * flow_wrap_idx - wrap base into 0 to n minus 1 with pow2 fast path. - * @base: unwrapped index stock plus offset. - * @n: host count above one and within the 1024 bound. - * - * Powers of two mask with base and n minus 1, so the hot - * 16 CPU path skips the modulo divide with the same order. - * Other hosts fall back to modulo with the same result and - * no extra branch past the power check. Callers guard n above - * one, so a zero or one host never divides by zero here. - * - * Returns: wrapped index below @n. - */ -static __always_inline u32 flow_wrap_idx(u64 base, u32 n) -{ - if (n == 0) - return 0; - if (flow_is_pow2((u64)n)) - return (u32)(base & ((u64)n - 1ULL)); - return (u32)(base % (u64)n); -} -/* Forward task type for the enqueue tails without pulling kernel headers. */ -/* The BPF build already holds the full task view through common, while */ -/* the host bindings keep this opaque, so the dispatcher still calls with */ -/* no extra include. */ -struct task_struct; -/** - * struct flow_miss_tail - miss-rejoin args for the outlined miss path. - * @tctx: task state with vruntime plus deadline plus predictor. - * @cpu: live target CPU for the tier rejoin. - * @sel: selected CPU hint for the idle kick. - * @now: current time in nanos. - * @enq_flags: enqueue flags threaded to the reject insert. - * @hint: flat period hint in micros, zero for no hint. - * @hint_w: hint share with base for neutral. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * - * Bundles the miss state plus hint plus time plus flags, so the outlined - * miss path takes one pointer like the pinned plus place plus kick tails - * with no stack args and no order change. - */ -struct flow_miss_tail { - struct flow_task_ctx *tctx; - s32 cpu; - s32 sel; - u64 now; - u64 enq_flags; - u32 hint; - u32 hint_w; - u64 avg; - u64 dev; -}; -/** - * struct flow_open_tail - open compute args for the outlined open path. - * @tctx: task state with vruntime plus weight plus slice. - * @deadline: fresh predicted deadline already stored by the caller. - * @now: current time in nanos. - * @enq_flags: enqueue flags with preempt keeping the stored slice. - * @hint: flat period hint in micros, zero for no hint. - * @hint_w: hint share with base for neutral. - * @avg: burst average in nanos, zero for no history. - * @dev: burst deviation in nanos. - * @is_reenq: true reuses the stored slice with inherit else recomputes. - * - * Bundles the open state plus deadline plus time plus flags, so the - * outlined fresh plus requeue compute takes one pointer with no stack - * args and the same order. - */ -struct flow_open_tail { - struct flow_task_ctx *tctx; - u64 deadline; - u64 now; - u64 enq_flags; - u32 hint; - u32 hint_w; - u64 avg; - u64 dev; - bool is_reenq; -}; -/** - * struct flow_open_out - open compute out fields for RED plus place plus kick. - * @vtime: strict fair time capped at now plus one period. - * @pre_slice: dynamic slice before the latency clamp, zero on requeue. - * @sleep_ns: true sleep gap read before the wait overwrite. - * @is_lat: unified latency for RED plus slice agreement. - * @is_fresh: true for fresh waits else false for requeues. - * - * Carries the fair time plus the RED cost plus the kick sleep in one - * struct, so the dispatcher keeps one shared RED admit plus one - * eligibility plus one place plus kick with no second compute. - */ -struct flow_open_out { - u64 vtime; - u32 pre_slice; - u64 sleep_ns; - bool is_lat; - bool is_fresh; -}; -/* Outlined miss-rejoin plus open compute shared by the enqueue dispatcher. */ -/* The miss path rejoins self-contained with RED plus tier plus kick, while */ -/* the open path computes fresh plus requeue into out fields for the shared */ -/* RED plus place plus kick, so the verifier keeps one copy each with no */ -/* inline growth and the same order plus the same counts. */ -static __noinline bool flow_enqueue_miss(struct task_struct *p, - const struct flow_miss_tail *t); -static __noinline void flow_enqueue_open(const struct flow_open_tail *t, - struct flow_open_out *out); +#endif #endif diff --git a/scheds/experimental/scx_flow/src/bpf/lib b/scheds/experimental/scx_flow/src/bpf/lib new file mode 120000 index 0000000000..c2c14b9959 --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/lib @@ -0,0 +1 @@ +../../../../../lib \ No newline at end of file diff --git a/scheds/experimental/scx_flow/src/bpf/lifecycle.bpf.c b/scheds/experimental/scx_flow/src/bpf/lifecycle.bpf.c deleted file mode 100644 index c8f4bd24f9..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/lifecycle.bpf.c +++ /dev/null @@ -1,524 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Task lifecycle ops with adaptive slice plus reclaim. - * - * Running claims the segment start from zero with an unconditional - * pid store. Only stopping charges. A stall past 5s clamps the - * stopping delta to zero, so suspend plus resume never poisons the - * predictor plus the minimum plus the credit. The snapshot counts - * live pids for the on CPU gauge. Stopping claims the start once, - * charges the raw segment to total runtime, advances vruntime by the - * scaled delta, folds - * the CPU minimum forward, then feeds the burst predictor average plus - * deviation from the same delta with up plus down shifts plus half - * deviation margin, then resumes a preempt-like head with start plus cur - * minus now clamped to 10us plus 100us for latency else 1ms with inherit - * on bad start plus end else carries the latency-critical slice up to one - * quantum clamped to 10us plus 1ms else adapts proportionally by exceed - * SHIFT capped 1ms plus half then halved shrink on late else slack SHIFT - * capped 1ms plus half then halved grow on early with deadband hold plus - * clamp to 10us plus 1ms and latency grow to 100us without changing - * virtual time, then counts one requeue per runnable stop else one - * completion. Like fair.c, vruntime paces order, unlike rt.c, no fixed - * priority holds. C holds burst else slice else quantum, and V holds - * weight with zero mapped to 128, so the slice adapts while virtual time - * stays untouched. A global saved credit at or past the fixed 256us Emax - * reclaims one value ordered reject with positive laxity plus same - * key or strictly after with a single move. A runnable preempt-like yield - * with history plus tail left and no wall miss keeps start plus cur minus - * now, else a yield before one quantum keeps the unused remainder only - * when wall time still meets the deadline plus unified latency holds, else - * the proportional step runs on the same expiring deadline. A wall - * completion past the deadline counts one miss without a kick, since the - * task already left the CPU. Miss plus Term where Term equals completions - * stay counters only, so misses plus completions record history. Frozen - * rejects plus on CPU plus overflow hold wire compat without a BPF writer, - * whitelisted with readers using gate plus RED plus live pids. - * Enable clears vruntime plus deadline plus stamps plus predictor plus lag - * plus weight plus slice plus hint plus hint weight plus misses plus adapt - * miss plus sat plus delta, and Disable plus exit clear without charging, - * so each segment meets exactly one charge in stopping without double - * counting. Disable clears the cached hierarchy id like move plus enable - * plus exit, so a reused pid never reads stale. A closed gate still counts - * one reject without charging. Release clears a stale running view without - * charging. The gate runs first in every op except the exiting paths, so a - * stale CPU fails closed with one counter. See intf.h for the shared - * helpers and enqueue.bpf.c for the fair time choice. - * - * Copyright (c) 2026 Galih Tama - */ -void BPF_STRUCT_OPS(flow_running, struct task_struct *p) -{ - struct flow_task_ctx *tctx; - struct flow_cpu_state *st; - s32 cpu; - u64 now; - u64 stamp; - cpu = scx_bpf_task_cpu(p); - /* The gate runs first with fail closed and no count on pass. */ - /* Exiting tasks never reach here through the running path. */ - if (unlikely(!flow_entry_ok(cpu, p, 0))) { - flow_gate_reject(); - return; - } - tctx = flow_lookup(p); - now = flow_now(); - /* Fold a bad clock, so a zero or saturated read never stamps zero */ - /* or max into the segment start. */ - if (now == 0 || now == (u64)~0ULL) - now = 1; - if (likely(tctx)) { - /* The stamp never reads zero or max after the fold above, */ - /* so the claim swaps from zero only while a second running */ - /* without a stop keeps the first start with no second use. */ - /* The on CPU gauge lives in the snapshot with no BPF count, */ - /* so this path holds no gauge add. */ - stamp = now; - __sync_val_compare_and_swap(&tctx->run_at, - 0, stamp); - } - if (unlikely(cpu < 0)) - return; - if (unlikely(!flow_cpu_live((u32)cpu))) - return; - st = flow_cpu((u32)cpu); - if (likely(st)) { - /* Claim the pid with an unconditional store, so a concurrent */ - /* clear plus run keeps the running task with no lost update. */ - /* The clear only clears when it still owns the pid, so the */ - /* store always wins over a stale clear with no torn write. A */ - /* compare and swap from the observed owner loses here, when */ - /* the clear wins the race to zero first, the swap fails and */ - /* leaves zero while this task still runs. The next running */ - /* would fold again, but the live view stays wrong until then. */ - __sync_lock_test_and_set(&st->running_pid, - (u32)p->pid); - } -} -void BPF_STRUCT_OPS(flow_dequeue, struct task_struct *p, - u64 deq_flags) -{ - (void)p; - (void)deq_flags; -} -/** - * struct flow_stop_tail - stopping commit args for the outlined commit. - * @tctx: task state with slice plus adapt miss plus sat plus delta. - * @slice: new slice in nanos to store. - * @miss: true counts one adapt miss else clears the streak. - * @sat_hi: saturation ceiling with 100us for latency else 1ms. - * @cost_avg: burst average for the RED cost, zero for no history. - * @cost_slice: stored slice for the RED cost. - * @delta: raw service in nanos of the stopping segment. - * - * Bundles the adapt plus carry commit, so the four stopping paths share - * one store with no inline growth and the same order. - */ -struct flow_stop_tail { - struct flow_task_ctx *tctx; - u32 slice; - bool miss; - u32 sat_hi; - u64 cost_avg; - u32 cost_slice; - u64 delta; -}; -/** - * flow_stop_commit - commit one stopping slice plus adapt plus delta. - * @t: stop tail with state plus slice plus miss plus ceiling plus cost - * plus delta, read once by the caller. - * - * Stores the slice, folds the adapt miss streak with saturation at - * 0xffff, folds the clamp streak at the floor plus ceiling, then saves - * the unused cost minus delta for the global credit with no wrap. Like - * fair.c, the step paces service, unlike rt.c, no fixed priority - * holds. Virtual time stays untouched. - * - * Outlined with noinline to keep verifier headroom with one shared - * copy, so resume plus carry plus adapt share the same commit with no - * inline growth. - */ -static __noinline void flow_stop_commit(const struct flow_stop_tail *t) -{ - struct flow_task_ctx *tctx; - u32 slice; - bool miss; - u32 sat_hi; - u64 ccost; - u64 csaved; - u32 cs; - if (!t) - return; - tctx = t->tctx; - if (!tctx) - return; - slice = t->slice; - miss = t->miss; - sat_hi = t->sat_hi; - __sync_lock_test_and_set(&tctx->slice_ns, slice); - if (miss) { - u16 mm = READ_ONCE(tctx->adapt_miss); - if (mm < 0xffffU) - tctx->adapt_miss = mm + 1; - } else { - tctx->adapt_miss = 0; - } - { - u16 sat = READ_ONCE(tctx->adapt_sat); - if (slice == (u32)FLOW_SLICE_MIN_NS || slice == sat_hi) { - if (sat < 0xffffU) - tctx->adapt_sat = sat + 1; - } else { - tctx->adapt_sat = 0; - } - } - ccost = flow_red_cost(t->cost_avg, t->cost_slice); - csaved = ccost > t->delta ? ccost - t->delta : 0; - cs = csaved > 0xffffffffULL ? 0xffffffffU : (u32)csaved; - tctx->adapt_delta = cs; -} -void BPF_STRUCT_OPS(flow_stopping, struct task_struct *p, - bool runnable) -{ - struct flow_task_ctx *tctx; - s32 cpu; - u64 now; - u64 delta; - u64 start; - u64 n_avg_keep = 0; - u64 n_dev_keep = 0; - bool have_pred = false; - bool stop_is_lat = false; - cpu = scx_bpf_task_cpu(p); - if (!flow_entry_ok(cpu, p, 0)) { - flow_gate_reject(); - return; - } - tctx = flow_lookup(p); - now = flow_now(); - /* Tasks without state hold no claim, so they hold no count. */ - /* The pid view still clears when owned. */ - if (!tctx) { - flow_clear_running_if_owner(cpu, (u32)p->pid); - return; - } - /* The start claims with an exchange, so only stopping charges. */ - /* A zero claim means no counted start, */ - /* so this pass drops with no charge. The on CPU gauge lives in */ - /* the snapshot with no BPF drop, so every pass ends here with no */ - /* gauge use. */ - start = __sync_lock_test_and_set(&tctx->run_at, 0); - if (start == 0) { - flow_clear_running_if_owner(cpu, (u32)p->pid); - return; - } - /* Clamp the segment delta with a fold on bad stamps, then clamp an */ - /* s2idle stall past 5s to zero, so a stale start never pollutes */ - /* the predictor plus the minimum plus the credit below. S3 pauses */ - /* monotonic with no BPF gap, so the boot gap reseeds instead. */ - /* The zero delta skips the predictor plus the minimum fold through */ - /* the gated charge, and the credit through its own delta gate. */ - delta = flow_delta_clamp(now, start); - if (flow_gap_is_resume(delta)) - delta = 0; - /* Every segment counts raw time while vruntime counts scaled time. */ - /* The predictor average rises fast with shift 3 plus falls slow */ - /* with shift 4, and the deviation widens fast with shift 2 plus */ - /* narrows slow with shift 3, plus a first deviation floor at */ - /* average quarter, so later deadlines track recent bursts with no */ - /* extra walk. A zero delta keeps the predictor, so a backward clock */ - /* never pulls the average to 1ns. The vruntime advance uses the */ - /* effective share of task times stored hint over 128 with no divide */ - /* and no lookup, so heavy tasks move slowly while light tasks move */ - /* quickly with no neutral cliff. The CPU minimum folds forward best */ - /* effort with no regression past a concurrent win. */ - flow_count_runtime(delta); - if (delta) { - u64 avg = (u64)READ_ONCE(tctx->avg_ns); - u64 dev = (u64)READ_ONCE(tctx->dev_ns); - u32 task_w = READ_ONCE(tctx->weight); - u32 hint_w = READ_ONCE(tctx->hint_w); - u32 eff_w; - u64 n_avg = flow_pred_avg(avg, delta); - /* Deviation updates from the observed delta with the new average, */ - /* so a fresh mean shapes the margin at once with no lagging bound. */ - u64 n_dev = flow_pred_dev(dev, n_avg, delta); - u64 vrun = READ_ONCE(tctx->vruntime); - u64 n_vrun; - if (task_w == 0) - task_w = (u32)FLOW_WEIGHT_BASE; - eff_w = flow_task_effective_weight(task_w, hint_w); - n_vrun = flow_ledger_advance(vrun, delta, eff_w); - __sync_lock_test_and_set(&tctx->avg_ns, (u32)n_avg); - __sync_lock_test_and_set(&tctx->dev_ns, (u32)n_dev); - __sync_lock_test_and_set(&tctx->vruntime, n_vrun); - flow_min_advance(cpu, n_vrun); - n_avg_keep = n_avg; - n_dev_keep = n_dev; - have_pred = true; - } - /* Latency-critical slice carryover from the fixed quantum with no knob. */ - /* A runnable task that yields before one quantum keeps quantum */ - /* minus delta as the next slice when wall time still meets the */ - /* deadline plus predictor slack still holds critical, so short */ - /* bursts earn a nearer virtual deadline without an extra slice. All */ - /* other stops adapt proportionally with exceed right 3 capped 1ms */ - /* plus half of base then halved grow on late else slack right 3 */ - /* capped 1ms plus half of base then halved grow on early with */ - /* deadband hold plus clamp to 10us plus 1ms without changing virtual */ - /* time, so the slice tracks recent runs with shifts only. The same */ - /* expiring deadline feeds exceed plus slack, and the carry gate runs */ - /* first. */ - /* Like fair.c, the step paces service, unlike rt.c, no fixed priority holds. */ - /* C holds burst else slice else quantum, and V holds weight with */ - /* zero mapped to 128. Exiting plus completion paths skip the carry */ - /* with adapt only, so only runnable waits carry with one kick per */ - /* wait at enqueue. Misses count lifetime with saturation, adapt */ - /* miss counts the consecutive wall miss streak with saturation, so */ - /* promotion latches on lifetime while adapt tracks the window. */ - /* Latency recompute per stop without a stored bit, so 72B holds. */ - /* Sleep stays unknown with fail open, while hint plus effective */ - /* share veto toward batch with quantum-relative bounds and */ - /* probation, so newcomers stay batch. Like fair.c, the test paces */ - /* service, unlike rt.c, no fixed priority holds. Carry caps at */ - /* 100us plus adapt re-clamps at 100us past the 1ms step with */ - /* slack grow allowed to the cap, so urgent bursts rotate each tenth quantum. */ - stop_is_lat = false; - { - u64 s_avg = have_pred ? n_avg_keep : - (u64)READ_ONCE(tctx->avg_ns); - u64 s_dev = have_pred ? n_dev_keep : - (u64)READ_ONCE(tctx->dev_ns); - u32 s_hint = READ_ONCE(tctx->hint_us); - u32 s_task_w = READ_ONCE(tctx->weight); - u32 s_hint_w = READ_ONCE(tctx->hint_w); - u32 s_eff; - if (s_task_w == 0) - s_task_w = (u32)FLOW_WEIGHT_BASE; - s_eff = flow_task_effective_weight(s_task_w, s_hint_w); - /* No stable uclamp field in this task view, so fail open to */ - /* zero without an extra map, and probation holds through both */ - /* helpers. */ - stop_is_lat = flow_is_lat(s_avg, s_dev, s_hint, 0, 0, s_eff); - } - if (runnable) { - u64 exp_dl = READ_ONCE(tctx->deadline); - bool wmiss = !flow_deadline_ok(exp_dl, now); - u32 pre_cur = READ_ONCE(tctx->slice_ns); - /* Preempt-like resume keeps the start plus cur leftover when */ - /* runnable yields early with history plus tail left and no wall */ - /* miss, so only preempt heads with more than 100us left resume */ - /* with occ start plus cur clamped to 10us plus 100us for latency */ - /* else 1ms with inherit on bad start plus end. The tail check is */ - /* delta plus 100us below cur here, so the helper keeps no tail */ - /* check. Equality fails closed and floors, so a latency head at */ - /* the 100us cap never resumes: cap equals tail, so delta plus */ - /* tail never falls below cap with delta past zero. This path */ - /* never runs and keeps latency rotating via carry plus adapt */ - /* without changing virtual time. Voluntary short yields fall */ - /* through to carry plus adapt, so resume never shadows. */ - if (!wmiss && have_pred && delta > 0 && - flow_sat_add(delta, (u64)FLOW_PREEMPT_TAIL_NS) < - (u64)pre_cur) { - u32 rem = flow_slice_resume(start, now, stop_is_lat, - pre_cur); - u32 rem_cap = stop_is_lat ? - (u32)FLOW_SLICE_LAT_NS : (u32)FLOW_QUANTUM_NS; - /* Resume plus carry plus adapt commit through the */ - /* shared helper, so the four stores share one copy */ - /* with no behavior change. */ - struct flow_stop_tail commit = { - .tctx = tctx, - .slice = rem, - .miss = false, - .sat_hi = rem_cap, - .cost_avg = have_pred ? n_avg_keep : 0, - .cost_slice = pre_cur, - .delta = delta, - }; - flow_stop_commit(&commit); - } else if (!wmiss && have_pred && delta > 0 && - delta < (u64)FLOW_QUANTUM_NS && stop_is_lat) { - u32 carry = flow_carry_for(delta); - u32 lat_cap = stop_is_lat ? - (u32)FLOW_SLICE_LAT_NS : (u32)FLOW_QUANTUM_NS; - struct flow_stop_tail commit; - carry = flow_slice_lat_clamp(carry, stop_is_lat); - commit.tctx = tctx; - commit.slice = carry; - commit.miss = false; - commit.sat_hi = lat_cap; - commit.cost_avg = n_avg_keep; - commit.cost_slice = pre_cur; - commit.delta = delta; - flow_stop_commit(&commit); - } else { - u32 cur = READ_ONCE(tctx->slice_ns); - u64 exceed = 0; - u64 slack = 0; - u32 nxt; - bool m = wmiss; - u32 sat_hi; - struct flow_stop_tail commit; - if (exp_dl != 0) { - if (m) - exceed = now - exp_dl; - else if (now != exp_dl) - slack = exp_dl - now; - } - nxt = flow_adapt_prop(cur, exceed, slack); - if (stop_is_lat) - nxt = flow_slice_lat_clamp(nxt, true); - sat_hi = stop_is_lat ? - (u32)FLOW_SLICE_LAT_NS : (u32)FLOW_QUANTUM_NS; - commit.tctx = tctx; - commit.slice = nxt; - commit.miss = m; - commit.sat_hi = sat_hi; - commit.cost_avg = have_pred ? n_avg_keep : 0; - commit.cost_slice = cur; - commit.delta = delta; - flow_stop_commit(&commit); - } - } else { - /* Completion adapt without carry and without a kick. An exceed */ - /* shrinks by exceed right 3 capped 1ms plus half of base, a slack */ - /* grows by slack right 3 capped 1ms plus half of base, both clamped */ - /* without changing virtual time. The */ - /* global credit funds reclaim below. */ - u64 exp_dl = READ_ONCE(tctx->deadline); - u32 cur = READ_ONCE(tctx->slice_ns); - bool cmiss = !flow_deadline_ok(exp_dl, now); - u64 exceed = 0; - u64 slack = 0; - u32 nxt; - if (exp_dl != 0) { - if (cmiss) - exceed = now - exp_dl; - else if (now != exp_dl) - slack = exp_dl - now; - } - nxt = flow_adapt_prop(cur, exceed, slack); - if (stop_is_lat) - nxt = flow_slice_lat_clamp(nxt, true); - { - u32 sat_hi = stop_is_lat ? - (u32)FLOW_SLICE_LAT_NS : (u32)FLOW_QUANTUM_NS; - struct flow_stop_tail commit = { - .tctx = tctx, - .slice = nxt, - .miss = cmiss, - .sat_hi = sat_hi, - .cost_avg = have_pred ? n_avg_keep : 0, - .cost_slice = cur, - .delta = delta, - }; - flow_stop_commit(&commit); - /* Reclaim runs in dispatch from the global credit at or past */ - /* the fixed 256us Emax with tiers-empty fallback plus aged */ - /* cover past one period, so this path records only without */ - /* walking. The global credit funds the retry without shaping */ - /* shares. Dispatch scans at most eight value ordered rejects */ - /* with positive laxity plus same key or strictly after plus */ - /* mask wins, so strict order holds with a single move. Zero */ - /* service completions fund nothing, so only a real delta with */ - /* a fresh predictor adds credit. Credit reuses the committed */ - /* delta, so funding agrees with the stored value with no */ - /* second cost pass. */ - if (delta > 0 && have_pred) - flow_credit_add((u64)READ_ONCE(tctx->adapt_delta)); - } - } - /* The pid view clears when owned. The snapshot counts live pids for */ - /* the on CPU gauge. */ - flow_clear_running_if_owner(cpu, (u32)p->pid); - /* A wall completion past the deadline counts one miss without a kick, */ - /* since the task already left the CPU. The miss count stays lifetime */ - /* without a reset here, so stopping records only. The miss count */ - /* tracks the proportional shrink. */ - if (!runnable && !flow_deadline_ok(READ_ONCE(tctx->deadline), now)) - flow_count_miss(tctx); - if (runnable) { - flow_count_requeue(true); - return; - } - flow_count_requeue(false); -} -void BPF_STRUCT_OPS(flow_enable, struct task_struct *p) -{ - struct flow_task_ctx *tctx; - s32 cpu = scx_bpf_task_cpu(p); - if (!flow_entry_ok(cpu, p, 0)) { - flow_gate_reject(); - return; - } - tctx = flow_get(p); - if (!tctx) - return; - /* Fresh tasks hold no vruntime, no deadline, no stamps, no */ - /* predictor, no lag, neutral weight, fixed slice, no hint, neutral */ - /* hint weight, no misses, no adapt miss, no adapt sat, and no adapt */ - /* delta. The first enqueue clamps vruntime to the CPU minimum */ - /* minus the lag bound with a fallback deadline plus a virtual */ - /* deadline, so sleepers gain no more than one boost. The cached */ - /* hierarchy id clears too, so a reused pid never reads a stale */ - /* hierarchy. */ - flow_cgrp_cache_invalidate((u32)p->pid); - tctx->vruntime = 0; - tctx->deadline = 0; - tctx->wait_at = 0; - tctx->run_at = 0; - tctx->hint_w = (u32)FLOW_WEIGHT_BASE; - tctx->avg_ns = 0; - tctx->dev_ns = 0; - tctx->vlag = 0; - tctx->weight = (u32)FLOW_WEIGHT_BASE; - tctx->slice_ns = (u32)FLOW_QUANTUM_NS; - tctx->hint_us = 0; - tctx->misses = 0; - tctx->adapt_miss = 0; - tctx->adapt_sat = 0; - tctx->adapt_delta = 0; -} -void BPF_STRUCT_OPS(flow_disable, struct task_struct *p) -{ - s32 cpu = scx_bpf_task_cpu(p); - if (!flow_entry_ok(cpu, p, 0)) { - flow_gate_reject(); - return; - } - /* Clear the cached hierarchy id for ABA safety, so a later pid */ - /* reuse never reads a stale hierarchy like move plus enable plus */ - /* exit. A zero pid needs no clear with the zero sentinel. */ - flow_cgrp_cache_invalidate((u32)p->pid); - /* Charge lives only in stopping with no leftover, so disable */ - /* clears the pid view with no advance and no minimum fold. */ - flow_clear_running_if_owner(cpu, (u32)p->pid); -} -void BPF_STRUCT_OPS(flow_exit_task, struct task_struct *p, - struct scx_exit_task_args *args) -{ - s32 cpu = scx_bpf_task_cpu(p); - (void)args; - /* Exiting tasks stay exempt from the gate with no count. The */ - /* cached hierarchy id clears too, so a later pid reuse never */ - /* reads a stale hierarchy. */ - flow_cgrp_cache_invalidate((u32)p->pid); - /* Charge lives only in stopping with no leftover, so exit clears */ - /* the pid view with no advance and no minimum fold. */ - flow_clear_running_if_owner(cpu, (u32)p->pid); -} -void BPF_STRUCT_OPS(flow_cpu_release, s32 cpu, - struct scx_cpu_release_args *args) -{ - (void)args; - /* The gate runs with no task here, so only the CPU checks. */ - /* A stale CPU counts one reject with no clear. */ - if (cpu >= 0 && !flow_cpu_live((u32)cpu)) { - flow_gate_reject(); - return; - } - /* Clear the stale running view with no charge. */ - /* The segment still ends through stopping or disable. */ - flow_clear_running(cpu); -} diff --git a/scheds/experimental/scx_flow/src/bpf/main.bpf.c b/scheds/experimental/scx_flow/src/bpf/main.bpf.c index 7b59d917dc..2270218df4 100644 --- a/scheds/experimental/scx_flow/src/bpf/main.bpf.c +++ b/scheds/experimental/scx_flow/src/bpf/main.bpf.c @@ -1,267 +1,35 @@ // SPDX-License-Identifier: GPL-2.0 /* - * Flow scheduler BPF core. + * Flow scheduler entry. * - * Maps hold task state, CPU pid plus cursor plus minimum rows, the - * topology view, the capacity view, the flat hint rows, the per CPU - * stats rows, the perf level rows, and the reclaim credit row. Init - * creates one local queue per CPU plus one shared queue per node plus - * one machine queue plus one value ordered reject queue, and it fails - * loudly on over bound counts. Ops split across per logic files with - * maps plus init plus exit plus the ops table only here. Hotplug needs - * a restart, and the watchdog stays at 20 seconds. + * Thin glue that pulls in area headers in order and declares + * the ops table. Each CPU owns one upstream queue in deadline order + * and there is one fallback + * queue in FIFO order. Queues hold bounded at 64 total. + * Ties leave in insertion order. Deadline order sets the queue with + * preempts for shared tasks with an earlier deadline. Queues come from + * the upstream deadline library and placement follows the + * upstream topology library. Tables are written once, so a CPU that + * arrives late needs a restart to be seen. Settings live in the + * shared header. * * Copyright (c) 2026 Galih Tama */ #include #include #include +#include +#include +#include #include "intf.h" -#include "topology.h" char _license[] SEC("license") = "GPL"; UEI_DEFINE(uei); -/* Per task state for the life of the task. */ -struct { - __uint(type, BPF_MAP_TYPE_TASK_STORAGE); - __uint(map_flags, BPF_F_NO_PREALLOC); - __type(key, int); - __type(value, struct flow_task_ctx); -} task_ctx_stor SEC(".maps"); -/* Per CPU pid with placement cursor plus minimum. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, FLOW_MAX_CPUS); - __type(key, u32); - __type(value, struct flow_cpu_state); -} cpu_state_stor SEC(".maps"); -/* Per CPU topology view with sibling plus node. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, FLOW_MAX_CPUS); - __type(key, u32); - __type(value, struct flow_topo); -} topo_stor SEC(".maps"); -/* Per CPU capacity view with one units row. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, FLOW_MAX_CPUS); - __type(key, u32); - __type(value, struct flow_cpu_cap); -} cap_stor SEC(".maps"); -/* Flat period hint by id with miss default. */ -struct { - __uint(type, BPF_MAP_TYPE_HASH); - __uint(max_entries, FLOW_HINT_MAX); - __type(key, u64); - __type(value, struct flow_hint); -} hint_stor SEC(".maps"); -/* Task to hierarchy cache with pid key plus id value. */ -struct { - __uint(type, BPF_MAP_TYPE_HASH); - __uint(max_entries, 2048); - __type(key, u32); - __type(value, u64); -} cgrp_cache_stor SEC(".maps"); -/* Per CPU stats rows with no shared read modify write. Each CPU owns */ -/* one row keyed by its id, so updates touch only the local row. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, FLOW_MAX_CPUS); - __type(key, u32); - __type(value, struct flow_sched_stats); -} cpu_stats_stor SEC(".maps"); -/* Last perf level per CPU with no call on steady. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, FLOW_MAX_CPUS); - __type(key, u32); - __type(value, u32); -} cpu_perf_last SEC(".maps"); -/* Global reclaim credit from completer saved deltas with no knob. */ -/* One u64 row holds the unused cost funding for dispatch reclaim with */ -/* saturation at 1s, so completions fund retries with no task pointer. */ -struct { - __uint(type, BPF_MAP_TYPE_ARRAY); - __uint(max_entries, 1); - __type(key, u32); - __type(value, u64); -} reclaim_credit_stor SEC(".maps"); -volatile u64 nr_cpu_ids; -volatile u64 nr_node_ids; -/* Includes run in dependency order with maps plus helpers before */ -/* callers, so stats plus cgroup plus vtime plus weight plus edf come */ -/* first, then placement plus timer plus preempt plus select, then */ -/* enqueue plus dispatch plus lifecycle. Enqueue splits into target plus */ -/* insert plus miss plus open plus kick before the dispatcher, so the */ -/* miss plus open tails share one copy each with no forward use. */ -#include "stats.bpf.c" -#include "cgroup.bpf.c" -#include "vtime.bpf.c" -#include "weight.bpf.c" -#include "edf.bpf.c" -#include "task_placement.bpf.c" -#include "timer.bpf.c" -#include "preempt.bpf.c" -#include "select_cpu.bpf.c" -#include "enqueue.bpf.c" -#include "dispatch.bpf.c" -#include "lifecycle.bpf.c" -/** - * flow_init - create queues plus seed CPU state. - * - * Creates one local queue per CPU plus one node queue per node plus - * one machine queue plus one value ordered reject queue. Seeds per CPU - * state plus capacity rows, then derives the node count from the seeded - * view. Topology rows seed once from userspace at attach with the - * resume refresh in the userspace loop, so init keeps no topo reseed. - * Fails loudly on over bound counts with no partial attach. - * - * Returns: 0 on success, negative errno on failure. - */ -s32 BPF_STRUCT_OPS_SLEEPABLE(flow_init) -{ - s32 ret; - u64 n; - s32 cpu; - u64 want = 1; - n = scx_bpf_nr_cpu_ids(); - if (n > (u64)FLOW_MAX_CPUS) { - scx_bpf_error("CPU count over bound"); - return -E2BIG; - } - if (n == 0) { - scx_bpf_error("no CPUs found"); - return -EINVAL; - } - nr_cpu_ids = n; - { - s32 c; - u32 hi = 0; - bool seen = false; - bpf_for(c, 0, FLOW_MAX_CPUS) { - u32 key; - struct flow_topo *tp; - u32 nd; - if (c < 0) - continue; - if ((u64)c >= n) - break; - key = (u32)c; - tp = bpf_map_lookup_elem(&topo_stor, - &key); - if (!tp) - continue; - nd = READ_ONCE(tp->node); - if (!flow_topo_node_ok(nd)) - continue; - if (!seen || nd > hi) { - hi = nd; - seen = true; - } - } - if (seen) - want = (u64)hi + 1; - if (want < 1) - want = 1; - if (want > (u64)FLOW_MAX_NODES) - want = (u64)FLOW_MAX_NODES; - nr_node_ids = want; - /* Bound the queue count at init, so local plus node plus */ - /* machine plus reject never passes 1042 with no wrap. */ - if (n + want + 2 > (u64)FLOW_MAX_DSQS) { - scx_bpf_error("dsq count over bound"); - return -E2BIG; - } - } - bpf_for(cpu, 0, FLOW_MAX_CPUS) { - struct flow_cpu_state *st; - struct flow_cpu_cap *cp; - u32 key; - if (cpu < 0) - continue; - if ((u64)cpu >= n) - break; - if ((u64)cpu >= (u64)FLOW_MAX_CPUS) - break; - key = (u32)cpu; - st = bpf_map_lookup_elem(&cpu_state_stor, &key); - if (st) { - st->running_pid = 0; - st->cursor = (u32)cpu; - st->min_vruntime = 0; - } - cp = bpf_map_lookup_elem(&cap_stor, &key); - if (cp) - cp->units = (u32)FLOW_CAP_BASE; - } - bpf_for(cpu, 0, FLOW_MAX_CPUS) { - u64 local; - if (cpu < 0) - continue; - if ((u64)cpu >= n) - break; - local = flow_local_dsq((u32)cpu); - if (!flow_dsq_valid(local)) { - scx_bpf_error("dsq id over bound"); - return -EINVAL; - } - ret = scx_bpf_create_dsq(local, -1); - if (ret < 0 && ret != -EEXIST) { - scx_bpf_error("dsq create failed"); - return ret; - } - } - { - u32 node; - u64 nn = nr_node_ids; - if (nn > (u64)FLOW_MAX_NODES) - nn = (u64)FLOW_MAX_NODES; - bpf_for(node, 0, FLOW_MAX_NODES) { - u64 nd; - if ((u64)node >= nn) - break; - nd = flow_node_dsq(node); - if (!flow_dsq_valid(nd)) { - scx_bpf_error("dsq id over bound"); - return -EINVAL; - } - ret = scx_bpf_create_dsq(nd, -1); - if (ret < 0 && ret != -EEXIST) { - scx_bpf_error("dsq create failed"); - return ret; - } - } - } - if (!flow_dsq_valid(flow_machine_dsq())) { - scx_bpf_error("dsq id over bound"); - return -EINVAL; - } - ret = scx_bpf_create_dsq(flow_machine_dsq(), -1); - if (ret < 0 && ret != -EEXIST) { - scx_bpf_error("dsq create failed"); - return ret; - } - if (!flow_dsq_valid(flow_overflow_dsq())) { - scx_bpf_error("dsq id over bound"); - return -EINVAL; - } - ret = scx_bpf_create_dsq(flow_overflow_dsq(), -1); - if (ret < 0 && ret != -EEXIST) { - scx_bpf_error("dsq create failed"); - return ret; - } - return 0; -} -/** - * flow_exit - record exit info on teardown. - * @info: exit info from the kernel. - * - * Records the exit reason with no extra work. - */ -void BPF_STRUCT_OPS(flow_exit, struct scx_exit_info *info) -{ - UEI_RECORD(uei, info); -} +#include "maps.bpf.h" +#include "stats.bpf.h" +#include "fair.bpf.h" +#include "select.bpf.h" +#include "enqueue.bpf.h" +#include "dispatch.bpf.h" SCX_OPS_DEFINE(flow_ops, .select_cpu = (void *)flow_select_cpu, .enqueue = (void *)flow_enqueue, @@ -269,17 +37,11 @@ SCX_OPS_DEFINE(flow_ops, .dispatch = (void *)flow_dispatch, .running = (void *)flow_running, .stopping = (void *)flow_stopping, + .tick = (void *)flow_tick, + .set_cpumask = (void *)flow_set_cpumask, .enable = (void *)flow_enable, - .disable = (void *)flow_disable, + .init_task = (void *)flow_init_task, .exit_task = (void *)flow_exit_task, - .cpu_release = (void *)flow_cpu_release, - .cgroup_init = (void *)flow_cgroup_init, - .cgroup_exit = (void *)flow_cgroup_exit, - .cgroup_prep_move = (void *)flow_cgroup_prep_move, - .cgroup_move = (void *)flow_cgroup_move, - .cgroup_cancel_move = (void *)flow_cgroup_cancel_move, - .cgroup_set_weight = (void *)flow_cgroup_set_weight, - .set_weight = (void *)flow_set_weight, .init = (void *)flow_init, .exit = (void *)flow_exit, .flags = SCX_OPS_ENQ_LAST | diff --git a/scheds/experimental/scx_flow/src/bpf/maps.bpf.h b/scheds/experimental/scx_flow/src/bpf/maps.bpf.h new file mode 100644 index 0000000000..31e7cfc11a --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/maps.bpf.h @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Tables for the flow scheduler. + * + * Task storage holds one entry per task. CPU storage holds the seed + * view written at startup with the cluster index only; cache and node + * placement come from the upstream topology tree. LLC storage holds + * per LLC counters. Globals hold the running view, + * the per LLC floor, the per CPU queues as one embedded queue per CPU + * in arena memory, the forward coalescing state, and two + * switches for cluster choice plus thread shape. Each CPU owns one + * queue in deadline order bounded at 64 total. A null queue means the CPU + * is offline or its queue was never built. Thread shape defaults on so a + * missed seed stays conservative. The CPU plus LLC tables are written once, so a + * CPU that arrives late needs a restart to be seen. Liveness comes + * from the topology tree, so no separate live table is kept. The + * arena task map from the task allocator is infra and not counted + * in the three maps here. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_MAPS_BPF_H +#define __FLOW_MAPS_BPF_H +#include "intf.h" +#include +struct { + __uint(type, BPF_MAP_TYPE_TASK_STORAGE); + __uint(map_flags, BPF_F_NO_PREALLOC); + __type(key, int); + __type(value, struct flow_task_ctx); +} task_ctx_stor SEC(".maps"); +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, FLOW_MAX_CPUS); + __type(key, u32); + __type(value, struct flow_cpu_ctx); +} cpu_ctx_stor SEC(".maps"); +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, FLOW_MAX_LLCS); + __type(key, u32); + __type(value, struct flow_llc_stats); +} llc_stats_stor SEC(".maps"); +volatile u64 flow_ccx_prefer; +volatile u64 flow_smt_enabled = 1; +struct flow_running_state flow_running_state[FLOW_MAX_CPUS]; +s64 flow_llc_seq[FLOW_MAX_LLCS]; +struct scx_edq __arena *flow_edqs; +u64 flow_fwd_pid[FLOW_MAX_LLCS + 1]; +s64 flow_fwd_vtime[FLOW_MAX_LLCS + 1]; +s32 flow_fwd_owner[FLOW_MAX_LLCS + 1]; +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/preempt.bpf.c b/scheds/experimental/scx_flow/src/bpf/preempt.bpf.c deleted file mode 100644 index dac28c7c02..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/preempt.bpf.c +++ /dev/null @@ -1,129 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Preempt plus idle kick for the enqueue pass. - * - * Holds the strict one kick per wait rule with unified latency plus - * lead plus tail plus eligibility. Only a latency arrival against a - * batch occupant with margin lead and tail left on the owner kicks, - * so near ties and nearly done owners never bounce while one kick per - * wait stays. Lat to lat, batch to batch, and batch to lat fail closed - * with one skipped count. Every hold counts in preempt skipped. The - * exiting, bypass, tier idle, and preempt paths share this gate. Runs - * under the caller. - * - * Copyright (c) 2026 Galih Tama - */ -/* True when one arrival preempts with margin, tail, and latency. */ -/* The arrival key must lead the occupant key by more than the margin, */ -/* so near ties never bounce. The owner must hold more than the tail */ -/* past now from start plus inherit cur, so nearly done owners finish */ -/* instead of taking a kick. Equality fails closed and floors, so a head */ -/* with exactly the tail left never kicks. Only a latency arrival */ -/* against a batch occupant preempts, so lat to batch wins while lat */ -/* to lat, batch to batch, and batch to lat fail closed with one */ -/* skipped count. The enqueue path calls this helper after the */ -/* eligibility check, so eligibility stays outside here with one minimum */ -/* read per wait. Equal arrivals pace without an extra kick, so no tie */ -/* assert runs. RED cost covers the newcomer on burst else pre-clamp */ -/* slice else quantum, while this tail covers the occupant on start */ -/* plus stored slice. The inputs differ by task on purpose with no */ -/* shared write, and both clamp to 10us plus 1ms, so admission plus */ -/* preempt agree on the same bounds. */ -/* Mirrored in config.rs preempt_ok for host tests, so the kernel and */ -/* the host agree. */ -static __always_inline bool flow_preempt_ok(u64 arr_key, - u64 occ_key, u64 now, u64 occ_run_at, u32 occ_cur, bool arr_lat, - bool occ_lat) -{ - u64 margin; - u64 occ_end; - u64 tail; - u64 base; - if (!arr_lat || occ_lat) - return false; - if (arr_key == 0 || arr_key == (u64)~0ULL) - return false; - if (occ_key == 0 || occ_key == (u64)~0ULL) - return false; - if (!flow_time_before(arr_key, occ_key)) - return false; - margin = flow_sat_add(arr_key, (u64)FLOW_PREEMPT_MARGIN_NS); - if (margin == (u64)~0ULL) - return false; - if (!flow_time_before(margin, occ_key)) - return false; - if (occ_run_at == 0 || occ_run_at == (u64)~0ULL) - return false; - base = (u64)flow_slice_inherit(occ_cur); - occ_end = flow_sat_add(occ_run_at, base); - if (occ_end == (u64)~0ULL) - return false; - tail = flow_sat_add(now, (u64)FLOW_PREEMPT_TAIL_NS); - if (tail == (u64)~0ULL) - return false; - if (!flow_time_before(tail, occ_end)) - return false; - return true; -} -/* Kick one idle allowed CPU for tier waits with strict one kick at most. */ -/* Tries the selected CPU first, then the kernel idle pick, then the */ -/* first allowed live CPU. Kicks only when the target runs nothing, with */ -/* the idle flag cleared first so the kick sticks. Never sends a preempt */ -/* kick, so tier waits stay idle only. */ -/* Factored per target probe keeps one copy. */ -/** - * flow_kick_one_if_idle - kick one CPU when idle plus eligible. - * @p: task waiting for the kick. - * @cpu: candidate CPU, negative fails closed. - * @vr: arrival vruntime for the eligibility gate. - * @lag: arrival lag bound for the eligibility gate. - * @has_ctx: true when @vr plus @lag hold valid state. - * - * Outlined with noinline to keep verifier headroom and the three probes - * share one eligibility plus kick copy. - * - * Returns: true when the kick took or an ineligible hold counted, so - * the caller stops, else false to try the next candidate. - */ -static __noinline bool flow_kick_one_if_idle( - const struct task_struct *p, s32 cpu, u64 vr, s32 lag, bool has_ctx) -{ - struct flow_cpu_state *st; - if (!flow_cpu_ok(p, cpu)) - return false; - st = flow_cpu((u32)cpu); - if (!st || READ_ONCE(st->running_pid) != 0) - return false; - if (has_ctx && - !flow_eligible(vr, READ_ONCE(st->min_vruntime), lag)) { - flow_count_preempt_skip(); - return true; - } - scx_bpf_test_and_clear_cpu_idle(cpu); - scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE); - flow_count_kick(); - return true; -} -static __noinline void flow_kick_idle_allowed( - const struct task_struct *p, s32 sel) -{ - s32 idle; - s32 first; - struct flow_task_ctx *tctx; - u64 vr = 0; - s32 lag = 0; - bool has_ctx = false; - tctx = flow_lookup((struct task_struct *)p); - if (tctx) { - vr = READ_ONCE(tctx->vruntime); - lag = READ_ONCE(tctx->vlag); - has_ctx = true; - } - if (flow_kick_one_if_idle(p, sel, vr, lag, has_ctx)) - return; - idle = scx_bpf_pick_idle_cpu(p->cpus_ptr, 0); - if (flow_kick_one_if_idle(p, idle, vr, lag, has_ctx)) - return; - first = (s32)bpf_cpumask_first(p->cpus_ptr); - flow_kick_one_if_idle(p, first, vr, lag, has_ctx); -} diff --git a/scheds/experimental/scx_flow/src/bpf/select.bpf.h b/scheds/experimental/scx_flow/src/bpf/select.bpf.h new file mode 100644 index 0000000000..4a9f582f4b --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/select.bpf.h @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Placement for the flow scheduler. + * + * The pick first tries the previous CPU when it is allowed and + * online. Otherwise it scans once and prefers the same LLC, then + * the same node, then a distant CPU. Cache and node identity come + * from the upstream topology tree with cluster hints from the seed + * view. Ties keep the first CPU in fixed order. Within the same LLC + * the scan favors the same cluster, with the tie favor kept even + * when threads share cores and only the fast pick gated on single + * threads. No sibling probe runs and each CPU stands single with + * fail closed choice. Every check returns minus one on failure. + * Masks are tested again before each wake, so a task is never kicked + * toward a CPU outside its current mask. Frequency follows core + * busyness and never steers placement. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_SELECT_BPF_H +#define __FLOW_SELECT_BPF_H +#include "intf.h" +#include "maps.bpf.h" +#include "stats.bpf.h" +#include +static __always_inline bool flow_is_pinned(struct task_struct *p) +{ + if (!p) + return false; + if (p->nr_cpus_allowed == 1) + return true; + return is_migration_disabled(p); +} +static __always_inline bool flow_cpu_allowed(s32 cpu, struct task_struct *p) +{ + u32 c; + if (!p || !p->cpus_ptr) + return false; + if (cpu < 0) + return false; + c = (u32)cpu; + if (!flow_cpu_ok(c)) + return false; + return bpf_cpumask_test_cpu(c, p->cpus_ptr); +} +static __always_inline bool flow_cpu_live(u32 cpu) +{ + if (!flow_cpu_ok(cpu)) + return false; + if (!topo_all) + return false; + return topo_contains(topo_all, cpu) ? true : false; +} +static __always_inline s32 flow_first_allowed(struct task_struct *p) +{ + u32 first; + if (!p || !p->cpus_ptr) + return -1; + first = bpf_cpumask_first(p->cpus_ptr); + if (!flow_cpu_live(first)) + return -1; + if (!flow_cpu_allowed((s32)first, p)) + return -1; + return (s32)first; +} +static __always_inline s32 flow_constrained_target(s32 hint, struct task_struct *p) +{ + if (!p || !p->cpus_ptr) + return -1; + if (hint >= 0 && flow_cpu_allowed(hint, p) && flow_cpu_live((u32)hint)) + return hint; + return flow_first_allowed(p); +} +static __always_inline bool flow_is_primary(u32 node) +{ + return node == 0; +} +static __always_inline int flow_hint_llc(s32 hint) +{ + int v; + if (hint < 0 || !flow_cpu_ok((u32)hint)) + return -1; + if (!topo_all) + return -1; + v = topo_cpu_to_llc_id((u32)hint); + if (v < 0 || !flow_llc_ok((u32)v)) + return -1; + return v; +} +static __always_inline u32 flow_cpu_ccx(u32 cpu) +{ + u32 key = cpu; + struct flow_cpu_ctx *cc; + if (!flow_cpu_ok(cpu)) + return 0; + cc = bpf_map_lookup_elem(&cpu_ctx_stor, &key); + if (!cc) + return 0; + return READ_ONCE(cc->ccx_id); +} +s32 BPF_STRUCT_OPS(flow_select_cpu, struct task_struct *p, s32 prev_cpu, u64 wake_flags) +{ + s32 hint = prev_cpu; + s32 tgt; + int hint_llc = -1; + u32 hint_ccx = 0; + bool have_hint_topo = false; + s32 best = -1; + int best_score = 99; + bool best_same = false; + bool use_ccx; + bool smt_on; + u32 c; + struct topo_iter hint_iter; + topo_ptr hint_node = 0; + topo_ptr walk = 0; + (void)wake_flags; + if (!p) + return hint; + scx_arena_subprog_init(); + use_ccx = READ_ONCE(flow_ccx_prefer) ? true : false; + smt_on = READ_ONCE(flow_smt_enabled) ? true : false; + tgt = flow_constrained_target(hint, p); + if (tgt >= 0) + return tgt; + if (hint >= 0 && flow_cpu_ok((u32)hint) && topo_all && + topo_contains(topo_all, (u32)hint)) { + hint_llc = flow_hint_llc(hint); + hint_ccx = flow_cpu_ccx((u32)hint); + TOPO_FOR_EACH_NODE(&hint_iter, walk) { + if (topo_contains(walk, (u32)hint)) { + hint_node = walk; + break; + } + } + if (hint_llc >= 0 || hint_node) + have_hint_topo = true; + } + bpf_for(c, 0, FLOW_MAX_CPUS) { + u32 l; + u32 cx; + int score; + int vllc; + bool same_node = false; + if (!flow_cpu_live(c)) + continue; + if (!flow_cpu_allowed((s32)c, p)) + continue; + vllc = topo_cpu_to_llc_id(c); + if (vllc < 0 || !flow_llc_ok((u32)vllc)) + continue; + l = (u32)vllc; + cx = flow_cpu_ccx(c); + if (hint_node && topo_contains(hint_node, c)) + same_node = true; + score = 3; + if (have_hint_topo) { + if (hint_llc >= 0 && l == (u32)hint_llc) + score = 0; + else if (same_node) + score = 1; + else + score = 2; + if (!smt_on && use_ccx && hint_llc >= 0 && + l == (u32)hint_llc && cx == hint_ccx) + score = -1; + } else if (flow_is_primary(0)) { + score = 2; + } + if (score < best_score) { + best_score = score; + best = (s32)c; + best_same = have_hint_topo && use_ccx && cx == hint_ccx; + if (score == -1) + break; + if (score == 0 && (!use_ccx || best_same)) + break; + } else if (score == best_score) { + /* Tie favor stays even with threads on; only the fast pick is gated. */ + bool cur_same = have_hint_topo && use_ccx && cx == hint_ccx; + if (cur_same && !best_same) { + best = (s32)c; + best_same = true; + if (score == 0) + break; + } + } + } + /* The mask can change while scanning, check the pick again. */ + if (best >= 0 && flow_cpu_allowed(best, p)) + return best; + return flow_first_allowed(p); +} +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/select/idle.bpf.c b/scheds/experimental/scx_flow/src/bpf/select/idle.bpf.c deleted file mode 100644 index 5f1879f20d..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/select/idle.bpf.c +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Select idle plus pinned probes for the flow scheduler. - * - * Holds the pinned pick plus the idle-first probe for the select pass. - * Pinned tasks stay where the mask allows with no scan, and every - * other arrival tries the waker when idle else the kernel idle pick - * with no state cost. An empty mask falls through to the machine tier - * at the caller. Runs under the caller with no lock. - * - * Copyright (c) 2026 Galih Tama - */ -/** - * flow_select_pinned_cpu - pick one CPU for a pinned task. - * @p: pinned task, stays where the mask allows with no scan. - * @prev_cpu: previous CPU for the fallback when live plus allowed. - * - * Takes the task CPU when live plus allowed, else the previous CPU - * when live plus allowed, else the first allowed CPU when live, else - * counts one gate reject and falls back to the previous CPU. Covers - * both migration disabled plus single allowed with the same order. - * - * Returns: picked CPU or @prev_cpu on fallback with gate count. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - */ -static __noinline s32 flow_select_pinned_cpu(struct task_struct *p, - s32 prev_cpu) -{ - s32 here = scx_bpf_task_cpu(p); - s32 first; - if (flow_cpu_ok(p, here)) - return here; - if (flow_cpu_ok(p, prev_cpu)) - return prev_cpu; - first = (s32)bpf_cpumask_first(p->cpus_ptr); - if (flow_cpu_ok(p, first)) - return first; - flow_gate_reject(); - return prev_cpu; -} -/** - * flow_select_idle_probe - probe the idle-first CPUs for one task. - * @p: task to place. - * @this_cpu: waker CPU tried first when idle plus allowed. - * - * Takes the waker when live plus allowed plus idle with no state cost, - * else the kernel idle pick when live plus allowed, else negative with - * no scan, so the caller falls through to the deadline plus scan pass. - * - * Returns: picked CPU or negative when no idle CPU meets. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - */ -static __noinline s32 flow_select_idle_probe(struct task_struct *p, - s32 this_cpu) -{ - struct flow_cpu_state *wst; - s32 picked; - if (likely(flow_cpu_ok(p, this_cpu))) { - wst = flow_cpu((u32)this_cpu); - if (wst && READ_ONCE(wst->running_pid) == 0) - return this_cpu; - } - picked = scx_bpf_pick_idle_cpu(p->cpus_ptr, 0); - if (picked >= 0 && flow_cpu_ok(p, picked)) - return picked; - return -1; -} diff --git a/scheds/experimental/scx_flow/src/bpf/select/scan.bpf.c b/scheds/experimental/scx_flow/src/bpf/select/scan.bpf.c deleted file mode 100644 index 8aac3dd6e3..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/select/scan.bpf.c +++ /dev/null @@ -1,482 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Select scan with slowest plus best sufficient fit for the core. - * - * Holds the SSF scan plus the BSF fallback plus the combined best pick - * plus the single ktime scan tail. The SSF scan takes the slowest - * sufficient CPU in two node-local phases with a near minimum tiebreak - * on the CPU minima through a single best plus a locality flag, so - * light work never takes a fast CPU and close peers win ties with no - * extra scan. Tied minima on the previous CPU win even past the lower - * id with no extra scan, so cache stays warm sticky. The BSF fallback - * takes the best sufficient CPU with the smallest combined drain plus - * minimum plus prev plus id tiebreak over the next four peers past the - * SSF window from cursor plus 9, so the two scans - * cover twelve unique peers with no overlap when the host holds at - * least twelve CPUs, else the windows wrap and overlap, and symmetric - * hosts still spread work with no topology walk. Twelve peers cover - * about one percent on a 1024 CPU host, so large hosts need many passes - * with the cursor spreading the load and no single pass stall. SSF runs in O(VISIT) - * with VISIT at most eight peers from the cursor with no hotspot, and - * BSF adds at most four more from the disjoint window. The shared - * cursor with dispatch steal advances by two with best effort races - * and no atomic order. One ktime read serves the previous plus SSF - * plus BSF checks, and pow2 hosts mask with no divide. Loops run via - * bpf_loop callbacks with gated pow2 plus node-local paths, so the - * verifier checks each body once with no unrolled depth. Runs under the - * caller with no lock. - * - * Copyright (c) 2026 Galih Tama - */ -/** - * struct flow_ssf_iter - SSF loop state for the bpf_loop callback. - * @p: task to place, typed for the mask gate. - * @deadline: absolute deadline, zero meets all. - * @now: current time in nanos. - * @this_cpu: waker CPU skipped as the busy waker. - * @this_node: waker node for the locality gate. - * @prev_cpu: previous CPU for the sticky tie preference. - * @start: scan start below the host count. - * @n: host count above one and within the bound. - * @best: best peer id or 0xffffffffU when none meets. - * @best_units: best capacity in base units. - * @best_min: best minimum vruntime in nanos. - * @pow2: true when @n holds exactly one bit, hoisted once. - * @best_local: true when @best shares the waker node. - */ -struct flow_ssf_iter { - const struct task_struct *p; - u64 deadline; - u64 now; - u32 this_cpu; - u32 this_node; - s32 prev_cpu; - u32 start; - u32 n; - u32 best; - u32 best_units; - u64 best_min; - bool pow2; - bool best_local; -}; -/** - * struct flow_bsf_iter - BSF loop state for the bpf_loop callback. - * @p: task to place, typed for the mask gate. - * @deadline: absolute deadline, zero meets all. - * @now: current time in nanos. - * @this_cpu: waker CPU skipped as the busy waker. - * @prev_cpu: previous CPU for the sticky tie preference. - * @start: disjoint start past the SSF window. - * @n: host count above one and within the bound. - * @best: best peer id or 0xffffffffU when none meets. - * @best_drain: best combined drain in nanos. - * @best_min: best minimum vruntime in nanos. - * @pow2: true when @n holds exactly one bit, hoisted once. - */ -struct flow_bsf_iter { - const struct task_struct *p; - u64 deadline; - u64 now; - u32 this_cpu; - s32 prev_cpu; - u32 start; - u32 n; - u32 best; - u64 best_drain; - u64 best_min; - bool pow2; -}; -/** - * flow_ssf_step - test one SSF peer via the bpf_loop callback. - * @idx: offset from the scan start within the eight peer window. - * @ctx_: pointer to struct flow_ssf_iter with the window plus best. - * - * Gates pow2 wrap plus window plus node-local paths with no unrolled - * depth, so the verifier checks the body once with the same order. - * - * Returns: 1 to stop on bound, else 0 to continue. - */ -static int flow_ssf_step(u32 idx, void *ctx_) -{ - struct flow_ssf_iter *c = ctx_; - u32 peer; - u32 units; - u64 pmin; - bool same; - if (!c) - return 1; - if ((u64)idx >= (u64)c->n) - return 1; - if (c->pow2) - peer = (u32)(((u64)c->start + (u64)idx) & ((u64)c->n - 1ULL)); - else - peer = (u32)(((u64)c->start + (u64)idx) % (u64)c->n); - if (peer == c->this_cpu) - return 0; - if (!flow_cpu_ok(c->p, (s32)peer)) - return 0; - if (!flow_cpu_meets(peer, c->deadline, c->now)) - return 0; - units = flow_cpu_units(peer); - if (c->best != 0xffffffffU) { - if ((u64)units + 64ULL < (u64)c->best_units) { - pmin = flow_cpu_min(peer); - same = flow_cpu_node(peer) == c->this_node; - c->best_units = units; - c->best_min = pmin; - c->best = peer; - c->best_local = same; - return 0; - } - if ((u64)units > (u64)c->best_units + 64ULL) - return 0; - pmin = flow_cpu_min(peer); - same = flow_cpu_node(peer) == c->this_node; - if (same && !c->best_local) { - c->best_units = units < c->best_units ? units : c->best_units; - c->best_min = pmin; - c->best = peer; - c->best_local = true; - return 0; - } - if (!same && c->best_local) - return 0; - if (!flow_time_before(pmin, c->best_min) && pmin != c->best_min) - return 0; - /* Sticky prev-CPU tie preference with no extra scan. */ - /* A tied minimum on the previous CPU wins even past the */ - /* lower id, so cache stays warm with no hotspot. */ - if (pmin == c->best_min) { - bool peer_prev = ((s32)peer == c->prev_cpu); - bool best_prev = ((s32)c->best == c->prev_cpu); - if (peer_prev && !best_prev) { - } else if (!peer_prev && best_prev) { - return 0; - } else if (peer >= c->best) { - return 0; - } - } - c->best_units = units < c->best_units ? units : c->best_units; - c->best_min = pmin; - c->best = peer; - c->best_local = same; - return 0; - } - pmin = flow_cpu_min(peer); - same = flow_cpu_node(peer) == c->this_node; - c->best_units = units; - c->best_min = pmin; - c->best = peer; - c->best_local = same; - return 0; -} -/** - * flow_bsf_step - test one BSF peer via the bpf_loop callback. - * @idx: offset from the disjoint start within the four peer window. - * @ctx_: pointer to struct flow_bsf_iter with the window plus best. - * - * Gates pow2 wrap plus drain plus minimum paths with no unrolled - * depth, so the verifier checks the body once with the same order. - * - * Returns: 1 to stop on bound, else 0 to continue. - */ -static int flow_bsf_step(u32 idx, void *ctx_) -{ - struct flow_bsf_iter *c = ctx_; - u32 peer; - u64 drain; - u64 pmin; - if (!c) - return 1; - if ((u64)idx >= (u64)c->n) - return 1; - if (c->pow2) - peer = (u32)(((u64)c->start + (u64)idx) & ((u64)c->n - 1ULL)); - else - peer = (u32)(((u64)c->start + (u64)idx) % (u64)c->n); - if (peer == c->this_cpu) - return 0; - if (!flow_cpu_ok(c->p, (s32)peer)) - return 0; - if (!flow_cpu_meets(peer, c->deadline, c->now)) - return 0; - drain = flow_cpu_drain(peer); - if (c->best == 0xffffffffU) { - pmin = flow_cpu_min(peer); - c->best_drain = drain; - c->best_min = pmin; - c->best = peer; - return 0; - } - if (drain < c->best_drain) { - pmin = flow_cpu_min(peer); - c->best_drain = drain; - c->best_min = pmin; - c->best = peer; - return 0; - } - if (drain != c->best_drain) - return 0; - pmin = flow_cpu_min(peer); - if (pmin != c->best_min && !flow_time_before(pmin, c->best_min)) - return 0; - /* Sticky prev-CPU tie preference with no extra scan. */ - /* A tied drain plus minimum on the previous CPU wins even past */ - /* the lower id, so cache stays warm with no hotspot. */ - if (pmin == c->best_min) { - bool peer_prev = ((s32)peer == c->prev_cpu); - bool best_prev = ((s32)c->best == c->prev_cpu); - if (peer_prev && !best_prev) { - } else if (!peer_prev && best_prev) { - return 0; - } else if (peer >= c->best) { - return 0; - } - } - c->best_min = pmin; - c->best = peer; - return 0; -} - -/** - * struct flow_scan_tail - scan args for the Outlined SSF plus BSF picks. - * @p: task to place, typed for the mask gate. - * @deadline: absolute deadline, zero meets all. - * @now: current time in nanos. - * @this_cpu: waker CPU skipped as the busy waker. - * @prev_cpu: previous CPU for the sticky tie preference. - * @cursor: shared cursor for the scan start. - * - * Bundles the live task plus the deadline plus the poll time plus the - * waker plus the previous CPU plus the shared cursor, so each Outlined - * pick takes one pointer with no stack args and the two scans share - * the same single reads. - */ -struct flow_scan_tail { - const struct task_struct *p; - u64 deadline; - u64 now; - u32 this_cpu; - s32 prev_cpu; - u32 cursor; -}; -/** - * flow_ssf_pick - slowest sufficient pick among allowed peers. - * @t: scan tail with task plus deadline plus time plus waker plus - * previous plus cursor, hoisted once by the caller with no second poll. - * - * Scans at most eight peers from the cursor via a bpf_loop callback - * with no unrolled depth, so the verifier checks the body once with - * gated pow2 plus node-local paths. Node-local peers win in the - * 64-unit window with the same slowest plus near minimum rule, so - * cache stays close with no extra scan. A tied minimum on the previous - * CPU wins even past the lower id, so cache stays warm with no extra - * scan. A local candidate beats a remote best in the window, while a - * clearly slower peer still wins across phases with wrap safe adds. - * Peers within 64 units count as near minimum with wrap safe order, - * so lagging CPUs win ties. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - * - * Returns: peer id or 0xffffffffU when no peer meets. - */ -static __noinline u32 flow_ssf_pick(const struct flow_scan_tail *t) -{ - struct flow_ssf_iter it = { - .p = t->p, - .deadline = t->deadline, - .now = t->now, - .this_cpu = t->this_cpu, - .this_node = 0, - .prev_cpu = 0, - .start = 0, - .n = 0, - .best = 0xffffffffU, - .best_units = 0xffffffffU, - .best_min = (u64)~0ULL, - .pow2 = false, - .best_local = false, - }; - u64 nr = nr_cpu_ids; - u32 n; - if (nr <= 1 || nr > (u64)FLOW_MAX_CPUS) - return it.best; - n = (u32)nr; - it.n = n; - it.this_node = flow_cpu_node(t->this_cpu); - it.prev_cpu = t->prev_cpu; - it.pow2 = flow_is_pow2((u64)n); - if (it.pow2) - it.start = (u32)(((u64)t->cursor + 1ULL) & ((u64)n - 1ULL)); - else - it.start = (u32)(((u64)t->cursor + 1ULL) % (u64)n); - bpf_loop((u32)FLOW_DISPATCH_MAX_VISIT, flow_ssf_step, &it, 0); - return it.best; -} -/** - * flow_bsf_pick - best sufficient fallback over the disjoint window. - * @t: scan tail with task plus deadline plus time plus waker plus - * previous plus cursor, hoisted once by the caller with no second poll. - * - * Scans the next four peers past the SSF window from cursor plus 9 via - * a bpf_loop callback with no unrolled depth, so the verifier checks - * the body once with gated pow2 plus minimum paths. Equal drains break - * toward the smallest minimum with wrap safe order, then the previous - * CPU on ties, then the smallest peer id, so ties stay sticky with no - * hotspot. Covers twelve unique peers with SSF on large hosts, so - * select pays at most 12 checks per pass. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - * - * Returns: peer id or 0xffffffffU when no peer meets. - */ -static __noinline u32 flow_bsf_pick(const struct flow_scan_tail *t) -{ - struct flow_bsf_iter it = { - .p = t->p, - .deadline = t->deadline, - .now = t->now, - .this_cpu = t->this_cpu, - .prev_cpu = 0, - .start = 0, - .n = 0, - .best = 0xffffffffU, - .best_drain = (u64)~0ULL, - .best_min = (u64)~0ULL, - .pow2 = false, - }; - u64 nr = nr_cpu_ids; - u32 n; - u32 start; - if (nr <= 1 || nr > (u64)FLOW_MAX_CPUS) - return it.best; - n = (u32)nr; - it.n = n; - it.prev_cpu = t->prev_cpu; - it.pow2 = flow_is_pow2((u64)n); - if (it.pow2) { - start = (u32)(((u64)t->cursor + 1ULL) & ((u64)n - 1ULL)); - it.start = (u32)(((u64)start + - (u64)FLOW_DISPATCH_MAX_VISIT) & ((u64)n - 1ULL)); - } else { - start = (u32)(((u64)t->cursor + 1ULL) % (u64)n); - it.start = (u32)(((u64)start + - (u64)FLOW_DISPATCH_MAX_VISIT) % (u64)n); - } - bpf_loop((u32)FLOW_BSF_MAX_PEERS, flow_bsf_step, &it, 0); - return it.best; -} -/** - * flow_select_best - slowest plus best sufficient pick in one call. - * @p: task to place. - * @deadline: absolute deadline, zero meets all. - * @now: current time in nanos. - * @this_cpu: waker CPU for the cursor plus the self skip. - * @prev_cpu: previous CPU for the sticky tie preference. - * - * Runs the SSF scan over eight peers from the cursor plus the disjoint - * BSF fallback over the next four past the SSF window from cursor plus - * 9, so twelve unique peers hold with no overlap on large hosts. Tied - * minima on the previous CPU win in both scans with no extra walk, so - * cache stays warm. The shared cursor with steal advances by two on - * success with best effort races, so passes spread with no hotspot. - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - * - * Returns: peer id or 0xffffffffU when no peer meets. - */ -static __noinline u32 flow_select_best(const struct task_struct *p, - u64 deadline, u64 now, u32 this_cpu, s32 prev_cpu) -{ - u64 nr = nr_cpu_ids; - struct flow_cpu_state *wst = flow_cpu(this_cpu); - u32 cursor = wst ? READ_ONCE(wst->cursor) : 0; - struct flow_scan_tail tail = { - .p = p, - .deadline = deadline, - .now = now, - .this_cpu = this_cpu, - .prev_cpu = prev_cpu, - .cursor = cursor, - }; - u32 best; - u32 bsf; - u32 n; - bool pow2; - u32 start; - u32 next; - if (nr <= 1 || nr > (u64)FLOW_MAX_CPUS) - return 0xffffffffU; - n = (u32)nr; - pow2 = flow_is_pow2((u64)n); - if (pow2) { - start = (u32)(((u64)cursor + 1ULL) & ((u64)n - 1ULL)); - next = (u32)(((u64)start + 1ULL) & ((u64)n - 1ULL)); - } else { - start = (u32)(((u64)cursor + 1ULL) % (u64)n); - next = (u32)(((u64)start + 1ULL) % (u64)n); - } - (void)start; - best = flow_ssf_pick(&tail); - if (best != 0xffffffffU) { - if (wst) - __sync_lock_test_and_set(&wst->cursor, next); - return best; - } - bsf = flow_bsf_pick(&tail); - if (bsf != 0xffffffffU) { - if (wst) - __sync_lock_test_and_set(&wst->cursor, next); - return bsf; - } - return 0xffffffffU; -} -/** - * flow_select_scan - run previous plus SSF plus BSF plus fallback. - * @p: task to place. - * @prev_cpu: previous CPU for the meet check plus the fallback. - * @deadline: absolute deadline, zero meets all. - * @this_cpu: waker CPU for the cursor plus the self skip. - * - * One ktime serves the previous plus SSF plus BSF with no second read. - * Early exit on the previous CPU avoids both scans when it meets, so - * the common stay keeps one drain check with no peer walk. Shared SSF - * plus disjoint BSF run in one Outlined call with no topology signal, - * so select keeps twelve peer coverage. An empty mask falls through to - * the machine tier at enqueue. - * - * Outlined with noinline to keep verifier headroom on the select path - * with no order change. - * - * Returns: picked CPU or @prev_cpu on fallback with gate count. - */ -static __noinline s32 flow_select_scan(const struct task_struct *p, - s32 prev_cpu, u64 deadline, u32 this_cpu) -{ - u64 now; - u32 best; - s32 first; - /* One ktime serves previous plus SSF plus BSF with no second read. */ - now = flow_now(); - /* Early exit on the previous CPU avoids both scans when it meets, */ - /* so the common stay keeps one drain check with no peer walk. */ - if (flow_cpu_ok(p, prev_cpu)) { - if (flow_cpu_meets((u32)prev_cpu, deadline, now)) - return prev_cpu; - } - /* Shared SSF plus disjoint BSF in one Outlined call with sticky */ - /* prev-CPU ties, so select keeps twelve peer coverage with warm */ - /* cache. */ - best = flow_select_best(p, deadline, now, this_cpu, prev_cpu); - if (best != 0xffffffffU) - return (s32)best; - if (flow_cpu_ok(p, prev_cpu)) - return prev_cpu; - first = (s32)bpf_cpumask_first(p->cpus_ptr); - if (flow_cpu_ok(p, first)) - return first; - flow_gate_reject(); - return prev_cpu; -} diff --git a/scheds/experimental/scx_flow/src/bpf/select_cpu.bpf.c b/scheds/experimental/scx_flow/src/bpf/select_cpu.bpf.c deleted file mode 100644 index 33eeee70e3..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/select_cpu.bpf.c +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Select CPU thin wrapper over the SSF placement. - * - * Takes idle first with no state cost, then the previous CPU when it - * meets the deadline, then the slowest sufficient fit in O(VISIT) with - * VISIT at most eight peers in two node-local phases, then the best - * sufficient fallback over the next four peers past the SSF window from - * cursor plus 9 with drain plus minimum plus prev plus id tiebreak. The - * two scans cover twelve unique peers with no overlap when the host holds at - * least twelve CPUs, else the windows wrap, so the fallback extends - * coverage instead of rescanning. The shared cursor with dispatch steal - * advances by two with best effort races and no atomic order. Pinned - * tasks stay where the mask allows with no scan. An empty mask falls - * through to the machine tier at enqueue. One ktime read serves the - * previous plus SSF plus BSF checks, and pow2 hosts mask with no divide. - * - * The op holds the idle plus scan helpers in select/ with the pinned - * plus idle plus SSF plus BSF plus best plus scan noinline on scalar - * input, so the verifier stays small. - * - * Copyright (c) 2026 Galih Tama - */ -#include "select/idle.bpf.c" -#include "select/scan.bpf.c" -s32 BPF_STRUCT_OPS(flow_select_cpu, struct task_struct *p, - s32 prev_cpu, u64 wake_flags) -{ - s32 this_cpu; - s32 idle; - u64 deadline = 0; - struct flow_task_ctx *tctx; - (void)wake_flags; - this_cpu = (s32)bpf_get_smp_processor_id(); - if (unlikely(is_migration_disabled(p))) - return flow_select_pinned_cpu(p, prev_cpu); - if (unlikely(p->nr_cpus_allowed == 1)) - return flow_select_pinned_cpu(p, prev_cpu); - idle = flow_select_idle_probe(p, this_cpu); - if (idle >= 0) - return idle; - tctx = flow_lookup(p); - if (likely(tctx)) - deadline = READ_ONCE(tctx->deadline); - if (unlikely(deadline == 0) && likely(flow_cpu_ok(p, prev_cpu))) - return prev_cpu; - return flow_select_scan(p, prev_cpu, deadline, (u32)this_cpu); -} diff --git a/scheds/experimental/scx_flow/src/bpf/stats.bpf.c b/scheds/experimental/scx_flow/src/bpf/stats.bpf.c deleted file mode 100644 index 882877ebcb..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/stats.bpf.c +++ /dev/null @@ -1,194 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Per CPU stats with no shared read modify write. - * - * Each CPU owns one stats row keyed by its id, so updates touch only - * the local row with no cross CPU atomic. Aggregation sums all rows - * in userspace with saturation, so the hot paths pay no contention. - * A zero row means idle with no history. Runs under the caller with - * no lock and no shared modify. - * - * Copyright (c) 2026 Galih Tama - */ -/* Resolve the local row pointer for direct field adds. */ -/* Returns null on an out of bound id with no fold to row zero, so a */ -/* stale CPU never attributes to CPU zero. Callers skip on null. */ -static __always_inline struct flow_sched_stats *flow_stat_row(void) -{ - u32 cpu = bpf_get_smp_processor_id(); - if ((u64)cpu >= (u64)FLOW_MAX_CPUS) - return NULL; - if ((u64)cpu >= nr_cpu_ids) - return NULL; - return bpf_map_lookup_elem(&cpu_stats_stor, &cpu); -} -/* Count one closed gate rejection with saturation. */ -static __always_inline void flow_gate_reject(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - u64 cur; - if (!row) - return; - cur = READ_ONCE(row->gate_rejects); - if (cur == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->gate_rejects, 1); -} -/* Count one tier move batch with saturation on the local row. */ -static __always_inline void flow_account_local(u32 n) -{ - struct flow_sched_stats *row; - if (!n) - return; - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->local_moves) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->local_moves, (u64)n); -} -/* Count one node tier move batch with saturation on the local row. */ -static __always_inline void flow_account_node(u32 n) -{ - struct flow_sched_stats *row; - if (!n) - return; - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->node_moves) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->node_moves, (u64)n); -} -/* Count one machine tier move batch with saturation on the local row. */ -static __always_inline void flow_account_machine(u32 n) -{ - struct flow_sched_stats *row; - if (!n) - return; - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->machine_moves) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->machine_moves, (u64)n); -} -/* Count one deadline miss with saturation on the local row plus task. */ -static __noinline void flow_count_miss(struct flow_task_ctx *tctx) -{ - struct flow_sched_stats *row; - u32 m; - if (!tctx) - return; - m = READ_ONCE(tctx->misses); - if (m != 0xffffffffU) - __sync_fetch_and_add(&tctx->misses, 1); - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->misses) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->misses, 1); -} -/* Count one admit with saturation on the local row. */ -static __always_inline void flow_count_admit(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->admits) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->admits, 1); -} -/* Count one insert with saturation on the local row. */ -static __always_inline void flow_count_insert(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->inserts) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->inserts, 1); -} -/* Count one kick with saturation on the local row. */ -static __always_inline void flow_count_kick(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->kicks) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->kicks, 1); -} -/* Count one runtime delta with saturation on the local row. */ -static __always_inline void flow_count_runtime(u64 delta) -{ - struct flow_sched_stats *row; - if (delta == 0) - return; - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->total_runtime) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->total_runtime, delta); -} -/* Count one requeue or completion with saturation on the local row. */ -static __always_inline void flow_count_requeue(bool runnable) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (runnable) { - if (READ_ONCE(row->requeues) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->requeues, 1); - } else { - if (READ_ONCE(row->completions) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->completions, 1); - } -} -/* Count one preempt kick with saturation on the local row. */ -static __always_inline void flow_count_preempt_kick(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->preempt_kicks) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->preempt_kicks, 1); -} -/* Count one held preempt with saturation on the local row. */ -static __always_inline void flow_count_preempt_skip(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->preempt_skipped) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->preempt_skipped, 1); -} -/* Count one RED overload reject with saturation on the local row. */ -static __always_inline void flow_count_red_reject(void) -{ - struct flow_sched_stats *row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->red_rejects) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->red_rejects, 1); -} -/* Count one RED reclaim move with saturation on the local row. */ -static __always_inline void flow_count_red_reclaim(u32 n) -{ - struct flow_sched_stats *row; - if (!n) - return; - row = flow_stat_row(); - if (!row) - return; - if (READ_ONCE(row->red_reclaims) == (u64)~0ULL) - return; - __sync_fetch_and_add(&row->red_reclaims, (u64)n); -} diff --git a/scheds/experimental/scx_flow/src/bpf/stats.bpf.h b/scheds/experimental/scx_flow/src/bpf/stats.bpf.h new file mode 100644 index 0000000000..4069cf64e8 --- /dev/null +++ b/scheds/experimental/scx_flow/src/bpf/stats.bpf.h @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Counters for the flow scheduler. + * + * Each helper updates the counters of one LLC. The queued gauge + * never drops below zero. It uses a short compare and swap loop. + * When the loop loses, a saturating atomic step keeps the floor + * with no plain store, so a decrement is not lost under contention. + * An unknown offset does nothing. + * + * Copyright (c) 2026 Galih Tama + */ +#ifndef __FLOW_STATS_BPF_H +#define __FLOW_STATS_BPF_H +#include "intf.h" +#include "maps.bpf.h" +static __always_inline struct flow_llc_stats *flow_stats_for(u32 llc) +{ + return bpf_map_lookup_elem(&llc_stats_stor, &llc); +} +static __always_inline void flow_stat_inc(u32 llc, u64 off) +{ + struct flow_llc_stats *st = flow_stats_for(llc); + u64 *cell; + if (!st) + return; + if (off == 0) + cell = &st->queued; + else if (off == 1) + cell = &st->dispatched; + else if (off == 2) + cell = &st->fallback; + else if (off == 3) + cell = &st->steal; + else if (off == 4) + cell = &st->fb_duplicate; + else if (off == 5) + cell = &st->steal_llc; + else if (off == 6) + cell = &st->kick_preempt; + else if (off == 7) + cell = &st->kick_idle; + else if (off == 8) + cell = &st->kick_skip; + else if (off == 9) + cell = &st->overrun; + else if (off == 10) + cell = &st->blocked; + else if (off == 11) + cell = &st->orphan_kick; + else if (off == 12) + cell = &st->hol_forward; + else + return; + __sync_fetch_and_add(cell, 1ULL); +} +static __always_inline void flow_fb_inc(u32 llc, u64 tail_off) +{ + flow_stat_inc(llc, 2); + flow_stat_inc(llc, tail_off); +} +static __always_inline void flow_queued_dec(u32 llc) +{ + struct flow_llc_stats *st = flow_stats_for(llc); + int i; + if (!st) + return; + for (i = 0; i < 4; i++) { + u64 old = READ_ONCE(st->queued); + u64 next; + if (old == 0) + return; + next = old - 1; + if (__sync_val_compare_and_swap(&st->queued, old, next) == old) + return; + } + { + u64 old = __sync_fetch_and_sub(&st->queued, 1ULL); + if (!old) + __sync_fetch_and_add(&st->queued, 1ULL); + } +} +#endif diff --git a/scheds/experimental/scx_flow/src/bpf/task_placement.bpf.c b/scheds/experimental/scx_flow/src/bpf/task_placement.bpf.c deleted file mode 100644 index 68bba88b51..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/task_placement.bpf.c +++ /dev/null @@ -1,219 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Task placement steal plus hint moves for the core. - * - * Holds the sticky bounded steal plus the hint threaded moves. The - * steal window spans four to eight peers proportional to remaining - * visits from the same shared cursor with stride two and mask wins - * on drain. Sticky node-local peers win first within the window with - * idle affinity on the thief, so cache stays warm with no hotspot. - * Contention backs off on gate plus miss pressure through the overflow - * backlog gate at the caller plus a busy thief hold at four peers, - * so loaded passes keep the minimum scan with no loss. Hint threaded - * moves thread hoisted depths with no second poll, and queue runnable - * hints gate every RCU walk with a benign TOCTOU that only delays work - * to the next pass with no loss. The SSF scan plus the BSF fallback - * live in select/scan.bpf.c with the same order plus prev-CPU ties, so - * select keeps twelve unique peers with no overlap on large hosts. - * Eight peers cover under one percent on a 1024 CPU host, so large - * hosts steal across many passes with no single pass stall. Runs under the caller with no lock. - * - * Copyright (c) 2026 Galih Tama - */ -/* True when one CPU may run one task through its mask. */ -/* Live proven at entry, so mask alone gates here with no live branch. */ -static __always_inline bool flow_mask_ok(s32 cpu, - const struct task_struct *p) -{ - if (unlikely(cpu < 0)) - return false; - if (unlikely(!p)) - return false; - return bpf_cpumask_test_cpu((u32)cpu, p->cpus_ptr); -} -/* One candidate with the shared mask gate plus move in one place. */ -/* Gives one on move else zero with no state and one mask test. */ -static __always_inline u32 flow_move_candidate( - struct bpf_iter_scx_dsq *it, s32 cpu, struct task_struct *p) -{ - if (unlikely(cpu < 0)) - return 0; - if (unlikely(!p)) - return 0; - if (unlikely(!flow_mask_ok(cpu, p))) - return 0; - return (u32)scx_bpf_dsq_move(it, p, - (u64)SCX_DSQ_LOCAL_ON | (u64)(u32)cpu, 0); -} -/* Move one queued task with a hoisted hint plus a BPF mask gate. */ -/* Takes a queue id plus a CPU scalar plus the per pass visit count plus */ -/* the hoisted queued hint with no extra queue poll, so dispatch tiers */ -/* plus steal peers skip the second kfunc with the same visit cap. Visits */ -/* cap per pass shared across tiers with resume next pass at eight, so */ -/* the loop never holds RCU across the whole queue. The TOCTOU between */ -/* the hoisted hint and the iterator recheck only repeats or skips a pass */ -/* with no loss, since the next pass re-reads the hint with no stall. */ -/** - * flow_move_one_hint - move one task using a hoisted queue hint. - * @dsq: tier queue id to drain. - * @cpu: target CPU for the mask gate. - * @visits: per pass visit count shared across tiers. - * @queued: hoisted queued depth, non-positive skips with no kfunc. - * - * Returns: one on move else zero with no state. - */ -static __noinline u32 flow_move_one_hint(u64 dsq, s32 cpu, u32 *visits, - s32 queued) -{ - struct task_struct *p; - u32 moved = 0; - if (unlikely(cpu < 0)) - return 0; - if (unlikely(!visits)) - return 0; - if (unlikely(!flow_cpu_live((u32)cpu))) - return 0; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - return 0; - if (likely(queued <= 0)) - return 0; - bpf_rcu_read_lock(); - bpf_for_each(scx_dsq, p, dsq, 0) { - if (unlikely(moved)) - break; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - break; - (*visits)++; - moved += flow_move_candidate(BPF_FOR_EACH_ITER, cpu, p); - } - bpf_rcu_read_unlock(); - return moved; -} -/* Sticky bounded steal with idle affinity plus node-local first. */ -/* Scans four to eight peers proportional to remaining visits, so the */ -/* steal stays bounded with no hotspot. A busy thief holds four peers */ -/* while an idle thief scans the full proportional window, so */ -/* contention backs off with no extra counter. Node-local peers win */ -/* first within the window with one pass tracking the first local plus */ -/* the first remote, then a single hint move from the local peer else */ -/* the remote peer, so cache stays warm with one RCU walk. Each move */ -/* shares the per pass visit cap at eight, so a miss heavy peer never */ -/* holds RCU across the whole queue. Stolen work counts in the local */ -/* bucket with no new counter, so stats stay at 136B. The start hoists */ -/* once outside the loop with pow2 masking, so peers step from start */ -/* plus offset with no per peer add chain. The TOCTOU between the per */ -/* peer empty hint and the shared move only delays the steal to the */ -/* next pass with no loss. The cursor is shared with select at stride */ -/* two with best effort races and no atomic order. Gate plus miss */ -/* pressure backs off through the overflow backlog gate at the caller, */ -/* so tier waits skip the steal with no second poll. */ -static __noinline u32 flow_steal_one(s32 cpu, u32 *visits, u32 cursor) -{ - u32 window; - u32 off; - u64 nr; - u32 my_node; - u32 local_peer = 0xffffffffU; - u32 remote_peer = 0xffffffffU; - u64 local_dsq = 0; - u64 remote_dsq = 0; - s32 local_q = 0; - s32 remote_q = 0; - if (unlikely(cpu < 0)) - return 0; - if (unlikely(!visits)) - return 0; - if (unlikely(!flow_cpu_live((u32)cpu))) - return 0; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - return 0; - nr = nr_cpu_ids; - if (nr <= 1 || nr > (u64)FLOW_MAX_CPUS) - return 0; - /* Proportional window spans 4 to 8 peers from remaining visits with */ - /* saturation, so overspent visits hold four with no wrap. A fresh */ - /* pass with full visits scans eight peers, while a spent pass with */ - /* few visits left scans four peers. Bounds use the shared steal plus */ - /* visit constants with no literal and no mirror. */ - { - u32 remain = *visits >= (u32)FLOW_DISPATCH_MAX_VISIT ? 0 : - (u32)FLOW_DISPATCH_MAX_VISIT - *visits; - window = (u32)FLOW_STEAL_MIN_PEERS + (remain >> 1); - } - if (window < (u32)FLOW_STEAL_MIN_PEERS) - window = (u32)FLOW_STEAL_MIN_PEERS; - if (window > (u32)FLOW_STEAL_MAX_PEERS) - window = (u32)FLOW_STEAL_MAX_PEERS; - /* Idle affinity holds the full window for an idle thief plus four */ - /* peers for a busy thief, so contention backs off with no counter. */ - /* A busy thief still steals node-local work when tiers drain, but */ - /* pays the minimum scan with no hotspot. */ - { - struct flow_cpu_state *self = flow_cpu((u32)cpu); - if (!self || READ_ONCE(self->running_pid) != 0) - window = (u32)FLOW_STEAL_MIN_PEERS; - } - my_node = flow_cpu_node((u32)cpu); - { - u32 n = (u32)nr; - bool pow2 = flow_is_pow2((u64)n); - u32 start; - /* Hoist the pow2 check once per steal, so peers step with */ - /* one mask or modulo each with no per peer power test. */ - if (pow2) - start = (u32)(((u64)cursor + 1ULL) & ((u64)n - 1ULL)); - else - start = (u32)(((u64)cursor + 1ULL) % (u64)n); - bpf_for(off, 0, FLOW_STEAL_MAX_PEERS) { - u32 peer; - u64 peer_dsq; - u32 pnode; - /* Start hoists once with pow2 masking, so peers step */ - /* from start plus offset with no per peer add chain. */ - if ((u64)off >= (u64)window) - break; - if (unlikely(*visits >= (u32)FLOW_DISPATCH_MAX_VISIT)) - break; - if (local_peer != 0xffffffffU && remote_peer != 0xffffffffU) - break; - if (pow2) - peer = (u32)(((u64)start + (u64)off) & - ((u64)n - 1ULL)); - else - peer = (u32)(((u64)start + (u64)off) % (u64)n); - if (peer == (u32)cpu) - continue; - if (unlikely(!flow_cpu_live(peer))) - continue; - peer_dsq = flow_local_dsq(peer); - /* Queue runnable hint threads once per peer with no */ - /* second poll, so each peer pays one queue read total. */ - /* A race only delays the steal to the next pass. */ - { - s32 pq = scx_bpf_dsq_nr_queued(peer_dsq); - if (pq <= 0) - continue; - pnode = flow_cpu_node(peer); - if (pnode == my_node) { - if (local_peer == 0xffffffffU) { - local_peer = peer; - local_dsq = peer_dsq; - local_q = pq; - } - } else if (remote_peer == 0xffffffffU) { - remote_peer = peer; - remote_dsq = peer_dsq; - remote_q = pq; - } - } - } - } - /* Node-local first moves from the first local peer else the first */ - /* remote peer with one hint move total, so the pass pays one RCU */ - /* walk with the same visit cap and mask wins on drain. */ - if (local_peer != 0xffffffffU) - return flow_move_one_hint(local_dsq, cpu, visits, local_q); - if (remote_peer != 0xffffffffU) - return flow_move_one_hint(remote_dsq, cpu, visits, remote_q); - return 0; -} diff --git a/scheds/experimental/scx_flow/src/bpf/timer.bpf.c b/scheds/experimental/scx_flow/src/bpf/timer.bpf.c deleted file mode 100644 index cecc9078d8..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/timer.bpf.c +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Optional decay timer for the core. - * - * Holds the stale minimum decay with no timer wait by default. Tier - * waits wake by direct kick on insert with no timer, so no timer - * callback runs in the default shape. A stale minimum on an idle CPU - * holds until the next charge and stays bounded by the 2ms lag clamp - * plus eligibility, so rejoins keep at most one slice of boost with no - * storm and no decay is needed. The decay helper folds a stale CPU - * minimum toward the observed vruntime with one bounded step when the - * operator enables it, so a long idle CPU rejoins without dragging a - * stale minimum with no storm. Disabled stays a no-op with no cost. - * Runs under the caller with no lock. - * - * Copyright (c) 2026 Galih Tama - */ -/* Decay one CPU minimum toward the given vruntime by one step. */ -/* Disabled by default with no call from any op, so the helper costs */ -/* nothing unless the operator wires it. When enabled, moves the */ -/* minimum forward by at most one lag bound toward the sample with */ -/* saturation, so a stale minimum rejoins without a jump. Kept */ -/* intentionally as the optional decay point with no Rust mirror, */ -/* so the kernel stays the single truth with one decay symbol. */ -static __always_inline void flow_timer_decay(u32 cpu, u64 sample) -{ - (void)cpu; - (void)sample; - /* Optional decay stays disabled with no state cost. Tier waits */ - /* wake by direct kick with no timer wait. */ -} diff --git a/scheds/experimental/scx_flow/src/bpf/topology.h b/scheds/experimental/scx_flow/src/bpf/topology.h deleted file mode 100644 index f6158037d4..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/topology.h +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Topology init helpers for the flow scheduler. - * - * Holds only the node bound check used by flow_init to derive the - * node count from the seeded view. Hot paths never include this - * header, so enqueue plus select plus dispatch keep their order. - * - * Copyright (c) 2026 Galih Tama - */ -#ifndef __FLOW_TOPOLOGY_H -#define __FLOW_TOPOLOGY_H - -#include "intf.h" - -/* True when the seeded node id fits the node bound. */ -/* Out of bound rows never shape the node count, so large hosts fold */ -/* to the machine queue with no trap. Init only with no hot-path use. */ -static __always_inline bool flow_topo_node_ok(u32 node) -{ - return node < (u32)FLOW_MAX_NODES; -} - -#endif /* __FLOW_TOPOLOGY_H */ diff --git a/scheds/experimental/scx_flow/src/bpf/vtime.bpf.c b/scheds/experimental/scx_flow/src/bpf/vtime.bpf.c deleted file mode 100644 index a2fb66441d..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/vtime.bpf.c +++ /dev/null @@ -1,183 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Virtual time ledger plus CPU minimum for the core. - * - * Holds the clock plus task plus CPU lookups shared by every op plus - * the vruntime ledger plus the CPU minimum fold. The ledger advances - * by the fair delta with saturation, so heavy tasks move slowly while - * light tasks move quickly with no divide beyond the scaler. The CPU - * minimum folds forward best effort with bounded retry, so newly woken - * tasks clamp without gaining past the lag bound. A stale minimum on - * an idle CPU holds until the next charge and stays bounded by the 2ms - * lag clamp plus eligibility, so no decay timer runs and rejoins keep - * at most one slice of boost with no storm. Runs inline with no walk, - * so the verifier stays small. - * - * Copyright (c) 2026 Galih Tama - */ -/* Monotonic clock in nanos for deadlines plus fair times. Pauses */ -/* across S3, so BPF heals s2idle stalls here while userspace boot */ -/* time trips S3 with a reseed. */ -static __always_inline u64 flow_now(void) -{ - return bpf_ktime_get_ns(); -} -/* Task state without create for fast read paths. */ -static struct flow_task_ctx *flow_lookup(struct task_struct *p) -{ - return bpf_task_storage_get(&task_ctx_stor, - (struct task_struct *)p, 0, 0); -} -/* Task state with create for enqueue and enable paths. */ -static struct flow_task_ctx *flow_get(struct task_struct *p) -{ - return bpf_task_storage_get(&task_ctx_stor, - (struct task_struct *)p, 0, - BPF_LOCAL_STORAGE_GET_F_CREATE); -} -/* CPU state or null when the id is past the bound. */ -static struct flow_cpu_state *flow_cpu(u32 cpu) -{ - u32 key = cpu; - if (cpu >= (u32)FLOW_MAX_CPUS) - return NULL; - return bpf_map_lookup_elem(&cpu_state_stor, &key); -} -/* Topology view or null when the id is past the bound. */ -static struct flow_topo *flow_topo(u32 cpu) -{ - u32 key = cpu; - if (cpu >= (u32)FLOW_MAX_CPUS) - return NULL; - return bpf_map_lookup_elem(&topo_stor, &key); -} -/* Capacity units of one CPU with base on miss. */ -/* A zero row means unknown, so the base applies. */ -static __always_inline u32 flow_cpu_units(u32 cpu) -{ - u32 key = cpu; - u32 *v; - if (cpu >= (u32)FLOW_MAX_CPUS) - return (u32)FLOW_CAP_BASE; - v = bpf_map_lookup_elem(&cap_stor, &key); - if (!v || *v == 0) - return (u32)FLOW_CAP_BASE; - return READ_ONCE(*v); -} -/* Node of one CPU with zero on miss. */ -static __always_inline u32 flow_cpu_node(u32 cpu) -{ - struct flow_topo *tp = flow_topo(cpu); - if (!tp) - return 0; - if (tp->node >= (u32)FLOW_MAX_NODES) - return 0; - return READ_ONCE(tp->node); -} -/** - * flow_ledger_advance - advance vruntime by one delta at one weight. - * @vruntime: base vruntime in nanos. - * @delta: raw service in nanos. - * @weight: scheduling share, clamped to range. - * - * Adds the fair scaled service to the base through the shared scaler, - * so heavy tasks advance slowly while light tasks advance quickly. - * - * Returns: advanced vruntime in nanos. - */ -static __always_inline u64 flow_ledger_advance(u64 vruntime, - u64 delta, u32 weight) -{ - return flow_sat_add(vruntime, flow_scaled_delta(delta, weight)); -} -/* Minimum vruntime of one CPU with zero on miss. */ -/* A missing row means no history, so zero keeps new tasks eligible. */ -/* A stale minimum on an idle CPU holds until the next charge, but the */ -/* 2ms lag clamp plus eligibility bound the sleeper boost to one slice */ -/* with no storm, so no decay is needed. */ -static __always_inline u64 flow_cpu_min(u32 cpu) -{ - struct flow_cpu_state *st = flow_cpu(cpu); - if (!st) - return 0; - return READ_ONCE(st->min_vruntime); -} -/* Fold one CPU minimum forward to at least the given vruntime. */ -/* Takes the max best effort with a bounded compare and swap retry, so a */ -/* lost race retries with no torn write and the next charge folds again */ -/* with no stall. A zero vruntime never moves the minimum, so no history */ -/* holds zero. A vruntime at max clamps with no wrap. A stale minimum */ -/* never moves backward here, so idle CPUs rejoin through the lag clamp */ -/* with at most one slice of boost and no timer. */ -static __always_inline void flow_min_advance(s32 cpu, - u64 vruntime) -{ - struct flow_cpu_state *st; - s32 i; - if (cpu < 0) - return; - if (vruntime == 0) - return; - if (!flow_cpu_live((u32)cpu)) - return; - st = flow_cpu((u32)cpu); - if (!st) - return; - bpf_for(i, 0, 4) { - u64 cur = READ_ONCE(st->min_vruntime); - u64 old; - if (cur == vruntime) - break; - if (!flow_time_before(cur, vruntime)) - break; - old = __sync_val_compare_and_swap(&st->min_vruntime, - cur, vruntime); - if (old == cur) - break; - } -} -/* Clear the running pid with a compare and swap loop. */ -/* Retries the swap so a concurrent run pairs, and a lost race keeps */ -/* the winner with no torn zero. Release carries no pid, so the loop */ -/* claims whatever owner it finds. The segment still ends through */ -/* stopping with no charge here. */ -static __always_inline void flow_clear_running(s32 cpu) -{ - struct flow_cpu_state *st; - s32 i; - if (cpu < 0) - return; - if (!flow_cpu_live((u32)cpu)) - return; - st = flow_cpu((u32)cpu); - if (!st) - return; - bpf_for(i, 0, 4) { - u32 cur = READ_ONCE(st->running_pid); - u32 old; - if (cur == 0) - break; - old = __sync_val_compare_and_swap( - &st->running_pid, cur, 0); - if (old == cur) - break; - } -} -/* Clear the running pid only when the pid owns it. */ -/* Uses one compare and swap, so a stale exit never clears a new */ -/* owner after a switch. A zero pid never owns, so it passes. */ -static __always_inline void flow_clear_running_if_owner( - s32 cpu, u32 pid) -{ - struct flow_cpu_state *st; - if (cpu < 0) - return; - if (pid == 0) - return; - if (!flow_cpu_live((u32)cpu)) - return; - st = flow_cpu((u32)cpu); - if (!st) - return; - __sync_val_compare_and_swap(&st->running_pid, pid, 0); -} diff --git a/scheds/experimental/scx_flow/src/bpf/weight.bpf.c b/scheds/experimental/scx_flow/src/bpf/weight.bpf.c deleted file mode 100644 index 9e98676c58..0000000000 --- a/scheds/experimental/scx_flow/src/bpf/weight.bpf.c +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Task weight for the core. - * - * Holds the per task base share plus the nice table plus the fair - * delta scaler. The nice table maps nice minus 20 to 19 into weights - * centred at 128 for nice zero with powers near two, so light nices - * earn small shares while heavy nices earn large shares with no walk. - * The fair delta scales service inversely with weight through one - * divide, so heavy tasks advance slowly while light tasks advance - * quickly with no band jump. A zero input maps to the lightest share - * while missing state stays neutral via the effective helper. - * - * Copyright (c) 2026 Galih Tama - */ -/* Nice weight table for nice minus 20 to 19. Index 20 holds nice zero */ -/* at 128 with kernel ratios scaled by eight, so the full span covers */ -/* 1 to 11095 within the 1 to 16384 bound with no divide at lookup. */ -static const u32 flow_nice_weight[40] = { - 11095U, 8969U, 7060U, 5784U, 4536U, 3644U, 2906U, 2338U, - 1868U, 1489U, 1193U, 952U, 762U, 613U, 488U, 390U, - 312U, 248U, 198U, 159U, 128U, 102U, 81U, 65U, - 52U, 41U, 34U, 26U, 21U, 17U, 13U, 10U, - 8U, 7U, 5U, 4U, 3U, 2U, 2U, 1U -}; -/** - * flow_nice_to_weight - weight for one nice value. - * @nice: nice from minus 20 to 19, clamped into range. - * - * Returns: weight from the table with no divide. - */ -static __always_inline u32 flow_nice_to_weight(s32 nice) -{ - u32 idx; - if (nice < -20) - nice = -20; - if (nice > 19) - nice = 19; - idx = (u32)(nice + 20); - if (idx >= 40U) - idx = 20U; - return flow_nice_weight[idx]; -} -/** - * flow_calc_delta_fair - scaled service for one delta at one weight. - * @delta: raw service in nanos. - * @weight: scheduling share, clamped to range. - * - * Scales inversely with weight through one divide, so the neutral - * weight of 128 keeps the delta unchanged while lighter tasks grow - * and heavier tasks shrink with no band jump. A zero weight maps to - * the floor, so an explicit zero earns the lightest share. A zero - * delta stays zero with no floor, so idle charges nothing. A nonzero - * delta that scales to zero rises to one, so every service step moves - * the ledger forward with no stall. A huge product saturates instead - * of wrapping to a short charge. - * - * Returns: scaled service in nanos. - */ -static __always_inline u64 flow_calc_delta_fair(u64 delta, u32 weight) -{ - return flow_scaled_delta(delta, weight); -} -/** - * flow_set_weight - store one task base share with clamp. - * @p: task to reweight, null fails closed. - * @weight: raw share, clamped to range with zero mapping to 1. - * - * Stores the clamped base in task state with no hint use, so later - * enqueues stack the effective share with the stored flat hint. A - * zero input stores 1 for the lightest share with no neutral. A - * missing task state fails closed with no create and no stall. - */ -void BPF_STRUCT_OPS(flow_set_weight, struct task_struct *p, - u32 weight) -{ - struct flow_task_ctx *tctx; - u32 w; - if (!p) - return; - tctx = flow_lookup(p); - if (!tctx) - return; - w = flow_weight_clamp(weight); - __sync_lock_test_and_set(&tctx->weight, w); -} diff --git a/scheds/experimental/scx_flow/src/cli.rs b/scheds/experimental/scx_flow/src/cli.rs new file mode 100644 index 0000000000..8853c59137 --- /dev/null +++ b/scheds/experimental/scx_flow/src/cli.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Command line options for the flow scheduler. +//! +//! Copyright (c) 2026 Galih Tama + +//! Poll interval handling and scheduler flags. + +use std::time::Duration; + +use anyhow::Result; +use clap::Parser; +use clap_complete::Shell; +use scx_utils::libbpf_clap_opts::LibbpfOpts; + +/* Binary name used in logs and stats. */ +pub const SCHEDULER_NAME: &str = "scx_flow"; + +pub fn full_version() -> String { + scx_utils::build_id::full_version(env!("CARGO_PKG_VERSION")) +} + +/// Init stderr logging with local time offset. +/// Verbose selects debug output. Other levels stay fixed. +pub fn init_logging(verbose: bool) -> Result<()> { + let loglevel = if verbose { + simplelog::LevelFilter::Debug + } else { + simplelog::LevelFilter::Info + }; + let mut lcfg = simplelog::ConfigBuilder::new(); + lcfg.set_time_offset_to_local() + .expect("Failed to set local time offset") + .set_time_level(simplelog::LevelFilter::Error) + .set_location_level(simplelog::LevelFilter::Off) + .set_target_level(simplelog::LevelFilter::Off) + .set_thread_level(simplelog::LevelFilter::Off); + simplelog::TermLogger::init( + loglevel, + lcfg.build(), + simplelog::TerminalMode::Stderr, + simplelog::ColorChoice::Auto, + )?; + Ok(()) +} + +/// Validated poll interval from float seconds. +/// Rejects NaN, infinite, non-positive, and values over one hour. +/// A bad value returns an error before any timer starts. +pub fn poll_interval_secs(v: f64) -> Result { + if !v.is_finite() || v <= 0.0 || v > 3600.0 { + anyhow::bail!("interval bad {v}"); + } + Ok(Duration::from_secs_f64(v)) +} + +#[derive(Debug, Parser)] +#[command(name = SCHEDULER_NAME, version, disable_version_flag = true)] +pub struct Opts { + /* Poll interval for the stats printer. */ + #[clap(long)] + pub stats: Option, + /* Run the stats printer only. */ + #[clap(long)] + pub monitor: Option, + /* Verbose output with libbpf detail. */ + #[clap(short = 'v', long, action = clap::ArgAction::SetTrue)] + pub verbose: bool, + /* Exit dump buffer length in bytes. Zero keeps the default size. */ + /* Values pass to the kernel as given. The operator owns this path. */ + #[clap(long, default_value = "0")] + pub exit_dump_len: u32, + /* Print version and exit. */ + #[clap(short = 'V', long, action = clap::ArgAction::SetTrue)] + pub version: bool, + /* Show stat descriptions. */ + #[clap(long)] + pub help_stats: bool, + /* Generate shell completions and exit. */ + #[clap(long, value_name = "SHELL", hide = true)] + pub completions: Option, + #[clap(flatten, next_help_heading = "Libbpf Options")] + pub libbpf: LibbpfOpts, +} diff --git a/scheds/experimental/scx_flow/src/main.rs b/scheds/experimental/scx_flow/src/main.rs index 93b3265d03..3ff759ca97 100644 --- a/scheds/experimental/scx_flow/src/main.rs +++ b/scheds/experimental/scx_flow/src/main.rs @@ -1,542 +1,40 @@ // SPDX-License-Identifier: GPL-2.0 //! Flow scheduler front end. -//! //! Copyright (c) 2026 Galih Tama - -//! Loads the BPF object, seeds the topology view, then drives the loop. -//! Observability is counters through the stats server plus the loopback -//! dashboard with per CPU cards plus a JSON snapshot for debugging. - mod bpf_skel; pub use bpf_skel::*; pub mod bpf_intf; pub use bpf_intf::*; -#[path = "rust/config.rs"] -mod config; -#[path = "rust/snapshot.rs"] -mod snapshot; -#[path = "rust/stats.rs"] +pub mod cli; +pub mod metrics; +pub mod run; +#[path = "stats.rs"] mod stats; -#[path = "rust/topology.rs"] -mod topology; -#[path = "rust/webui.rs"] -mod webui; - -use std::mem::MaybeUninit; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::time::Duration; - +pub mod topology; use anyhow::Result; -use clap::CommandFactory; -use clap::Parser; -use clap_complete::Shell; +use clap::{CommandFactory, Parser}; use clap_complete::generate; -use crossbeam::channel::RecvTimeoutError; use log::info; -use scx_stats::prelude::*; -use scx_utils::UserExitInfo; -use scx_utils::build_id; -use scx_utils::libbpf_clap_opts::LibbpfOpts; -use scx_utils::scx_ops_attach; -use scx_utils::scx_ops_load; -use scx_utils::scx_ops_open; -use scx_utils::try_set_rlimit_infinity; -use scx_utils::uei_exited; -use scx_utils::uei_report; - -use config::Config; -use stats::Metrics; - -/* Binary name used in logs and stats. */ -const SCHEDULER_NAME: &str = "scx_flow"; -/* Resume gap in seconds shared with FLOW_RESUME_GAP_NS in intf.h. A loop */ -/* stall past this bound reads as a suspend plus resume gap, so the run */ -/* loop refreshes the topology view once while BPF clamps stale deltas. */ -/* Monotonic pauses across S3, so the boot gap trips S3 here. */ -const RESUME_GAP_SECS: u64 = 5; -/* Boot clock id for suspend-aware gaps. Value 7 on Linux. */ -const CLOCK_BOOTTIME: i32 = 7; - -/// Boot time including suspend, else None on fault. -/// Uses clock_gettime with no extra dep, so S3 trips the gap where -/// Instant plus monotonic pause with no false trip on bad reads. -fn boot_now() -> Option { - #[repr(C)] - struct Timespec { - tv_sec: i64, - tv_nsec: i64, - } - unsafe extern "C" { - fn clock_gettime(clk_id: i32, tp: *mut Timespec) -> i32; - } - let mut ts = Timespec { - tv_sec: 0, - tv_nsec: 0, - }; - // SAFETY: clock_gettime writes a valid timespec on success. - let rc = unsafe { clock_gettime(CLOCK_BOOTTIME, &mut ts) }; - if rc != 0 { - return None; - } - if ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1_000_000_000 { - return None; - } - Some(Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)) -} - -/// True when the boot gap passes the 5s resume bound. -/// Pure for host injection with no clock use, so start at now minus -/// 6s trips while a short stall stays quiet with wrap safety. -fn boot_gap_exceeded(last: Duration, now: Duration) -> bool { - match now.checked_sub(last) { - Some(d) => d > Duration::from_secs(RESUME_GAP_SECS), - None => false, - } -} -/* CPU bound shared with the BPF header. */ -#[cfg(test)] -const MAX_CPUS: usize = crate::bpf_intf::flow_consts_FLOW_MAX_CPUS as usize; - -fn full_version() -> String { - build_id::full_version(env!("CARGO_PKG_VERSION")) -} - -/// Validated poll interval from float seconds. -/// Rejects NaN plus infinite plus non-positive plus over one hour, so -/// a bad flag fails closed before any timer starts with no panic. -fn poll_interval_secs(v: f64) -> Result { - if !v.is_finite() || v <= 0.0 || v > 3600.0 { - anyhow::bail!("interval bad {v}"); - } - Ok(Duration::from_secs_f64(v)) -} - -#[derive(Debug, Parser)] -#[command(name = SCHEDULER_NAME, version, disable_version_flag = true)] -struct Opts { - /* Poll interval for the stats printer. */ - #[clap(long)] - stats: Option, - /* Run the stats printer only. */ - #[clap(long)] - monitor: Option, - /* Verbose BPF logging. */ - #[clap(short = 'd', long, action = clap::ArgAction::SetTrue)] - debug: bool, - /* Verbose output with libbpf detail. */ - #[clap(short = 'v', long, action = clap::ArgAction::SetTrue)] - verbose: bool, - /* Exit dump buffer length in bytes. */ - #[clap(long, default_value = "1048576")] - exit_dump_len: u32, - /* Print version and exit. */ - #[clap(short = 'V', long, action = clap::ArgAction::SetTrue)] - version: bool, - /* Show stat descriptions. */ - #[clap(long)] - help_stats: bool, - /* Generate shell completions and exit. */ - #[clap(long, value_name = "SHELL", hide = true)] - completions: Option, - /* Disable the loopback dashboard thread. */ - #[clap(long = "no-webui", action = clap::ArgAction::SetTrue)] - no_webui: bool, - #[clap(flatten, next_help_heading = "Libbpf Options")] - libbpf: LibbpfOpts, -} - -/* - * Scheduler owns the skeleton, the link, the stats - * server plus the dashboard channel. It drives the run - * loop until shutdown or exit. - */ -pub(crate) struct Scheduler<'a> { - skel: BpfSkel<'a>, - struct_ops: Option, - stats_server: StatsServer<(), Metrics>, - started_at: std::time::Instant, - /* Dashboard sender with None when disabled. */ - webui_tx: Option>, - /* Online ids once at init in rank order. */ - online_cpus: Vec, - /* SMT flag per online CPU in rank order for the cards. */ - smt: Vec, - /* One line topology summary for the page. */ - topology: String, - /* Seeded rows in rank order for the resume watch. */ - seeded: Vec<(u32, u32, u32)>, -} - -impl<'a> Scheduler<'a> { - fn init( - opts: &'a Opts, - open_object: &'a mut MaybeUninit, - shutdown: Arc, - ) -> Result { - try_set_rlimit_infinity(); - let mut bld = BpfSkelBuilder::default(); - bld.obj_builder.debug(opts.debug || opts.verbose); - let open_opts = opts.libbpf.clone().into_bpf_open_opts(); - let mut skel = scx_ops_open!(bld, open_object, flow_ops, open_opts)?; - /* Validate the constants before load. */ - let cfg = Config::default(); - cfg.validate()?; - info!("Config: {}", cfg.describe()); - /* Ops flags live in the BPF object for kernel 7.2 and up. */ - skel.struct_ops.flow_ops_mut().exit_dump_len = opts.exit_dump_len; - let mut skel = scx_ops_load!(skel, flow_ops, uei)?; - let _ = &mut skel; - /* Seed the BPF topology view with sibling plus node rows. */ - /* Failures keep the BPF defaults with node zero. */ - let rows = topology::topo_rows(); - Self::seed_topo_with(&mut skel, &rows); - let struct_ops = scx_ops_attach!(skel, flow_ops)?; - let stats_server = StatsServer::new(stats::server_data()).launch()?; - /* Bounded dashboard channel drops a frame when full. */ - let webui_tx = if opts.no_webui { - None - } else { - let (tx, rx) = crossbeam::channel::bounded::(16); - let sd = shutdown.clone(); - std::thread::spawn(move || { - webui::start(rx, sd); - }); - Some(tx) - }; - let online_cpus: Vec = rows.iter().map(|(cpu, _, _)| *cpu).collect(); - /* SMT flags cache the sibling view with no sysfs use on poll. */ - let smt: Vec = rows - .iter() - .map(|(cpu, sib, _)| topology::is_smt_thread(*cpu, *sib)) - .collect(); - let topology = topology::describe_topology(&rows); - info!("Topology: {topology}"); - Ok(Self { - skel, - struct_ops: Some(struct_ops), - stats_server, - started_at: std::time::Instant::now(), - webui_tx, - online_cpus, - smt, - topology, - seeded: rows, - }) - } - - fn exited(&self) -> bool { - uei_exited!(&self.skel, uei) - } - - /* Seed one topology row per CPU into the BPF view. */ - /* Each row carries the thread sibling and the node id. */ - /* A failed update keeps the BPF default with no trap. */ - fn seed_topo_with(skel: &mut BpfSkel<'_>, rows: &[(u32, u32, u32)]) { - use libbpf_rs::MapCore; - for (cpu, sib, node) in rows { - let key = cpu.to_ne_bytes(); - let mut val = [0u8; 8]; - val[0..4].copy_from_slice(&sib.to_ne_bytes()); - val[4..8].copy_from_slice(&node.to_ne_bytes()); - if let Err(e) = skel - .maps - .topo_stor - .update(&key, &val, libbpf_rs::MapFlags::ANY) - { - log::warn!("topo seed failed for cpu {cpu}: {e}"); - } - } - } - - fn run(&mut self, shutdown: Arc) -> Result { - let (res_ch, req_ch) = self.stats_server.channels(); - /* Short tick keeps stats polls prompt while the page polls */ - /* once per second, so most ticks only refresh the bound */ - /* channel when the dashboard is on plus the queue has room. */ - /* Resume watch on the loop tick: a stall past 5s reads as a */ - /* suspend plus resume gap, so the topology view reseeds once */ - /* with no hotplug use. BPF monotonic heals s2idle stalls via */ - /* the 5s delta clamp, while boot time trips S3 where monotonic */ - /* pauses plus long stalls reseed here. Manual check: run then */ - /* echo mem > /sys/power/state, resume, expect one refresh. */ - let mut last_tick = std::time::Instant::now(); - let mut last_boot = boot_now(); - /* One BPF read serves both the stats reply plus the page. */ - while !shutdown.load(Ordering::Relaxed) && !self.exited() { - match req_ch.recv_timeout(Duration::from_millis(100)) { - Ok(()) => { - if let Some(ref tx) = self.webui_tx { - if !tx.is_full() { - let web = self.get_web_metrics(); - let stats = web.stats.clone(); - let _ = tx.try_send(web); - res_ch.send(stats)? - } else { - res_ch.send(self.get_metrics())? - } - } else { - res_ch.send(self.get_metrics())? - } - } - Err(RecvTimeoutError::Timeout) => { - if let Some(ref tx) = self.webui_tx - && !tx.is_full() - { - let web = self.get_web_metrics(); - let _ = tx.try_send(web); - } - } - Err(e) => Err(e)?, - } - /* One resume check per tick keeps the reseed to one refresh */ - /* per stall with no extra poll. */ - let now = std::time::Instant::now(); - let stalled = now.duration_since(last_tick); - last_tick = now; - let boot = boot_now(); - let boot_stalled = match (last_boot, boot) { - (Some(l), Some(n)) => boot_gap_exceeded(l, n), - _ => false, - }; - if boot.is_some() { - last_boot = boot; - } - if stalled > Duration::from_secs(RESUME_GAP_SECS) || boot_stalled { - if boot_stalled { - info!("resume suspected on boot gap, refreshing topology"); - } else { - info!("resume suspected after {stalled:?}, refreshing topology"); - } - if let Some(rows) = topology::reseed_if_changed(&mut self.seeded) { - Self::seed_topo_with(&mut self.skel, &rows); - self.online_cpus = rows.iter().map(|(cpu, _, _)| *cpu).collect(); - self.smt = rows - .iter() - .map(|(cpu, sib, _)| topology::is_smt_thread(*cpu, *sib)) - .collect(); - self.topology = topology::describe_topology(&rows); - info!("Topology: {}", self.topology); - } - } - } - let m = self.get_metrics(); - info!( - "exit ins={} req={} done={} local={} node={} machine={} kick={} adm={} rej={} miss={} gate={} pkick={} pskip={} redrej={} redrec={} runtime={} oncpu={}", - m.inserts, - m.requeues, - m.completions, - m.local_moves, - m.node_moves, - m.machine_moves, - m.kicks, - m.admits, - m.rejects, - m.misses, - m.gate_rejects, - m.preempt_kicks, - m.preempt_skipped, - m.red_rejects, - m.red_reclaims, - m.total_runtime, - m.on_cpu, - ); - let _ = self.struct_ops.take(); - uei_report!(&self.skel, uei) - } -} - fn main() -> Result<()> { - let opts = Opts::parse(); + let opts = cli::Opts::parse(); if let Some(shell) = opts.completions { generate( shell, - &mut Opts::command(), - SCHEDULER_NAME, + &mut cli::Opts::command(), + cli::SCHEDULER_NAME, &mut std::io::stdout(), ); return Ok(()); } - let only = opts.monitor.is_some(); if opts.version { - println!("{} {}", SCHEDULER_NAME, full_version()); + println!("{} {}", cli::SCHEDULER_NAME, cli::full_version()); return Ok(()); } if opts.help_stats { - println!("stats: top"); + stats::server_data().describe_meta(&mut std::io::stdout(), Some(&["Metrics"]))?; return Ok(()); } - if !only { - simplelog::SimpleLogger::init( - if opts.debug { - simplelog::LevelFilter::Debug - } else { - simplelog::LevelFilter::Info - }, - simplelog::Config::default(), - )?; - info!("{} {}", SCHEDULER_NAME, full_version()); - info!("Starting {} scheduler", SCHEDULER_NAME); - } - let shutdown = Arc::new(AtomicBool::new(false)); - let sd = shutdown.clone(); - ctrlc::set_handler(move || { - sd.store(true, Ordering::Relaxed); - })?; - if let Some(intv) = opts.monitor.or(opts.stats) { - let dur = poll_interval_secs(intv)?; - let sd = shutdown.clone(); - let jh = std::thread::spawn(move || { - if let Err(e) = stats::monitor(dur, sd) { - log::warn!("monitor failed: {e}"); - } - }); - if only { - let _ = jh.join(); - return Ok(()); - } - } - let mut open_object = MaybeUninit::::uninit(); - let mut sched = Scheduler::init(&opts, &mut open_object, shutdown.clone())?; - sched.run(shutdown)?; - info!("Scheduler exited"); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn scheduler_name_is_flow() { - assert_eq!(SCHEDULER_NAME, "scx_flow"); - assert!(poll_interval_secs(1.0).is_ok()); - assert!(poll_interval_secs(0.0).is_err()); - assert!(poll_interval_secs(-1.0).is_err()); - assert!(poll_interval_secs(f64::NAN).is_err()); - assert!(poll_interval_secs(f64::INFINITY).is_err()); - assert!(poll_interval_secs(3601.0).is_err()); - } - - #[test] - fn max_cpus_matches_header() { - assert_eq!( - MAX_CPUS, - crate::bpf_intf::flow_consts_FLOW_MAX_CPUS as usize - ); - } - - #[test] - fn quantum_matches_header() { - assert_eq!( - crate::config::QUANTUM_NS, - crate::bpf_intf::flow_consts_FLOW_QUANTUM_NS - ); - assert_eq!(crate::config::QUANTUM_NS, 1_000_000); - assert_eq!(crate::config::WEIGHT_BASE, 128); - assert_eq!(crate::config::WEIGHT_MIN, 1); - assert_eq!(crate::config::WEIGHT_MAX, 16_384); - } - - #[test] - fn slot_matches_header() { - assert_eq!(crate::bpf_intf::flow_consts_FLOW_MACHINE, 0x5A00); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_OVERFLOW, 0x5A01); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_MAX_DSQS, 1042); - } - - #[test] - fn period_matches_header() { - assert_eq!( - crate::config::PERIOD_NS, - crate::bpf_intf::flow_consts_FLOW_PERIOD_NS - ); - assert_eq!(crate::config::PERIOD_NS, 80_000_000); - } - - #[test] - fn task_size_is_72() { - assert_eq!(std::mem::size_of::(), 72); - } - - #[test] - fn cpu_size_is_16() { - assert_eq!(std::mem::size_of::(), 16); - } - - #[test] - fn topo_size_is_8() { - assert_eq!(std::mem::size_of::(), 8); - } - - #[test] - fn sched_stats_size_is_136() { - assert_eq!( - std::mem::size_of::(), - 136 - ); - } - - #[test] - fn fixed_red_matches_header() { - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_RED_TOL_NS, - crate::config::RED_TOL_NS - ); - assert_eq!(crate::config::RED_TOL_NS, 64_000); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_RED_EMAX_NS, - crate::config::RED_EMAX_NS - ); - assert_eq!(crate::config::RED_EMAX_NS, 256_000); - } - - #[test] - fn kick_rule_matches_header() { - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PREEMPT_MARGIN_NS, - crate::config::PREEMPT_MARGIN_NS - ); - assert_eq!(crate::config::PREEMPT_MARGIN_NS, 100_000); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PREEMPT_TAIL_NS, - crate::config::PREEMPT_TAIL_NS - ); - assert_eq!(crate::config::PREEMPT_TAIL_NS, 100_000); - } - - #[test] - fn hint_matches_header() { - assert_eq!( - crate::config::HINT_MAX, - crate::bpf_intf::flow_consts_FLOW_HINT_MAX - ); - assert_eq!(crate::config::HINT_MAX, 8192); - } - - #[test] - fn resume_gap_matches_header() { - assert_eq!(RESUME_GAP_SECS, 5); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_RESUME_GAP_NS, - RESUME_GAP_SECS * 1_000_000_000 - ); - } - - #[test] - fn boot_gap_trips_on_6s_stall() { - // Injected boot gap of 6s trips S3 where monotonic pauses. - let last = Duration::from_secs(100); - let now = last + Duration::from_secs(6); - assert!(boot_gap_exceeded(last, now)); - // Short 1s stall stays quiet with no reseed. - assert!(!boot_gap_exceeded(last, last + Duration::from_secs(1))); - // Exact 5s bound stays quiet, past trips with no wrap trip. - assert!(!boot_gap_exceeded(last, last + Duration::from_secs(5))); - assert!(!boot_gap_exceeded(now, last)); - if let Some(t) = boot_now() { - assert!(t.as_secs() > 0); - } - } + cli::init_logging(opts.verbose)?; + info!("{} {}", cli::SCHEDULER_NAME, cli::full_version()); + run::drive(&opts) } diff --git a/scheds/experimental/scx_flow/src/metrics.rs b/scheds/experimental/scx_flow/src/metrics.rs new file mode 100644 index 0000000000..72049794e8 --- /dev/null +++ b/scheds/experimental/scx_flow/src/metrics.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Per LLC metric collection for the flow scheduler. +//! +//! Copyright (c) 2026 Galih Tama + +//! Sums counters in struct order with wrapping add. + +use log::warn; + +use crate::BpfSkel; +use crate::stats::Metrics; + +/// Fold one LLC value into the aggregate. +/// Counters use wrapping add. Short reads keep prior state. +/// Thirteen counters cover queueing plus kicks plus forward. +pub fn fold_llc_val(out: &mut Metrics, val: &[u8]) { + if val.len() < 32 { + return; + } + let q = u64::from_ne_bytes(val[0..8].try_into().unwrap_or([0u8; 8])); + let d = u64::from_ne_bytes(val[8..16].try_into().unwrap_or([0u8; 8])); + let f = u64::from_ne_bytes(val[16..24].try_into().unwrap_or([0u8; 8])); + let s = u64::from_ne_bytes(val[24..32].try_into().unwrap_or([0u8; 8])); + out.queued = out.queued.wrapping_add(q); + out.dispatched = out.dispatched.wrapping_add(d); + out.fallback = out.fallback.wrapping_add(f); + out.steal = out.steal.wrapping_add(s); + if val.len() >= 40 { + let v = u64::from_ne_bytes(val[32..40].try_into().unwrap_or([0u8; 8])); + out.fb_duplicate = out.fb_duplicate.wrapping_add(v); + } + if val.len() >= 48 { + let v = u64::from_ne_bytes(val[40..48].try_into().unwrap_or([0u8; 8])); + out.steal_llc = out.steal_llc.wrapping_add(v); + } + if val.len() >= 56 { + let v = u64::from_ne_bytes(val[48..56].try_into().unwrap_or([0u8; 8])); + out.kick_preempt = out.kick_preempt.wrapping_add(v); + } + if val.len() >= 64 { + let v = u64::from_ne_bytes(val[56..64].try_into().unwrap_or([0u8; 8])); + out.kick_idle = out.kick_idle.wrapping_add(v); + } + if val.len() >= 72 { + let v = u64::from_ne_bytes(val[64..72].try_into().unwrap_or([0u8; 8])); + out.kick_skip = out.kick_skip.wrapping_add(v); + } + if val.len() >= 80 { + let v = u64::from_ne_bytes(val[72..80].try_into().unwrap_or([0u8; 8])); + out.overrun = out.overrun.wrapping_add(v); + } + if val.len() >= 88 { + let v = u64::from_ne_bytes(val[80..88].try_into().unwrap_or([0u8; 8])); + out.blocked = out.blocked.wrapping_add(v); + } + if val.len() >= 96 { + let v = u64::from_ne_bytes(val[88..96].try_into().unwrap_or([0u8; 8])); + out.orphan_kick = out.orphan_kick.wrapping_add(v); + } + if val.len() >= 104 { + let v = u64::from_ne_bytes(val[96..104].try_into().unwrap_or([0u8; 8])); + out.hol_forward = out.hol_forward.wrapping_add(v); + } +} + +/// Sum per LLC counters into one view. +/// A failed map read warns and keeps zeros for that LLC. +pub fn collect(skel: &BpfSkel<'_>) -> Metrics { + use libbpf_rs::MapCore; + let mut out = Metrics::default(); + for llc in 0..crate::bpf_intf::flow_consts_FLOW_MAX_LLCS { + let key = llc.to_ne_bytes(); + let val = match skel + .maps + .llc_stats_stor + .lookup(&key, libbpf_rs::MapFlags::ANY) + { + Ok(Some(v)) => v, + Ok(None) => continue, + Err(e) => { + warn!("stats read failed for llc {llc}: {e:#}"); + continue; + } + }; + fold_llc_val(&mut out, &val); + if llc + 1 >= 64 { + break; + } + } + out +} + +/// Collect each LLC row on its own. +/// Short reads keep zeros for that LLC through the same fold guards. +/// Order follows the LLC index. +pub fn collect_per_llc(skel: &BpfSkel<'_>) -> Vec<(u32, Metrics)> { + use libbpf_rs::MapCore; + let mut out: Vec<(u32, Metrics)> = Vec::new(); + for llc in 0..crate::bpf_intf::flow_consts_FLOW_MAX_LLCS { + let key = llc.to_ne_bytes(); + let val = match skel + .maps + .llc_stats_stor + .lookup(&key, libbpf_rs::MapFlags::ANY) + { + Ok(Some(v)) => v, + Ok(None) => continue, + Err(e) => { + warn!("stats read failed for llc {llc}: {e:#}"); + continue; + } + }; + let mut row = Metrics::default(); + fold_llc_val(&mut row, &val); + out.push((llc, row)); + if llc + 1 >= 64 { + break; + } + } + out +} diff --git a/scheds/experimental/scx_flow/src/run.rs b/scheds/experimental/scx_flow/src/run.rs new file mode 100644 index 0000000000..77577d4f04 --- /dev/null +++ b/scheds/experimental/scx_flow/src/run.rs @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Scheduler run loop for the flow scheduler. +//! +//! Copyright (c) 2026 Galih Tama + +//! Holds the skeleton, the link, and the stats server. + +use std::mem::MaybeUninit; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use anyhow::Context; +use anyhow::Result; +use crossbeam::channel::RecvTimeoutError; +use libbpf_rs::skel::Skel; +use log::info; +use log::warn; +use scx_arena::ArenaLib; +use scx_stats::prelude::*; +use scx_utils::NR_CPU_IDS; +use scx_utils::UserExitInfo; +use scx_utils::scx_ops_attach; +use scx_utils::scx_ops_load; +use scx_utils::scx_ops_open; +use scx_utils::try_set_rlimit_infinity; +use scx_utils::uei_exited; +use scx_utils::uei_report; + +use crate::BpfSkel; +use crate::BpfSkelBuilder; +use crate::cli::Opts; +use crate::cli::SCHEDULER_NAME; +use crate::stats::Metrics; + +/* + * Scheduler holds the skeleton, the link, and the stats server. + * It drives the run loop until shutdown or exit. The arena library + * stays alive for the whole run so queue and topology memory stays + * valid while the scheduler is attached. + */ +pub(crate) struct Scheduler<'a> { + skel: BpfSkel<'a>, + struct_ops: Option, + stats_server: StatsServer<(), Metrics>, + _arenalib: ArenaLib, +} + +impl<'a> Scheduler<'a> { + pub fn init( + opts: &'a Opts, + open_object: &'a mut MaybeUninit, + ) -> Result { + try_set_rlimit_infinity(); + let mut skel_builder = BpfSkelBuilder::default(); + skel_builder.obj_builder.debug(opts.verbose); + let open_opts = opts.libbpf.clone().into_bpf_open_opts(); + let mut skel = scx_ops_open!(skel_builder, open_object, flow_ops, open_opts) + .context("failed to open BPF object (check dmesg)")?; + skel.struct_ops.flow_ops_mut().exit_dump_len = opts.exit_dump_len; + { + // Thread shape defaults on in BPF so a missed seed stays conservative. + let smt_on = crate::topology::detect_smt().unwrap_or(true); + match skel.maps.data_data.as_mut() { + Some(data) => data.flow_smt_enabled = if smt_on { 1 } else { 0 }, + None => warn!("smt seed missed, using kernel default"), + } + // Arena sizing needs the host CPU count before load so the bitmap + // init sees a valid value and the topology tree can build. + match skel.maps.rodata_data.as_mut() { + Some(rodata) => rodata.nr_cpu_ids = *NR_CPU_IDS as u32, + None => warn!("nr_cpu_ids seed missed, arena init will fail"), + } + } + let mut skel = scx_ops_load!(skel, flow_ops, uei)?; + // Build the arena and the topology tree before any queue exists. + // The BPF init fails closed when the tree is missing, so a setup + // failure here never reaches attach. + let task_size = std::mem::size_of::(); + let arenalib = ArenaLib::setup(skel.object_mut(), task_size, 0, *NR_CPU_IDS) + .context("arena setup failed")?; + match crate::topology::seed_topology(&mut skel) { + Ok(text) => info!("Topology: {text}"), + Err(e) => warn!("topology seed failed, using BPF defaults: {e:#}"), + } + let struct_ops = scx_ops_attach!(skel, flow_ops)?; + let stats_server = StatsServer::new(crate::stats::server_data()).launch()?; + Ok(Self { + skel, + struct_ops: Some(struct_ops), + stats_server, + _arenalib: arenalib, + }) + } + + fn exited(&mut self) -> bool { + uei_exited!(&self.skel, uei) + } + + /// Sum per LLC counters into one view. + /// A failed map read warns and keeps zeros for that entry. + fn get_metrics(&self) -> Metrics { + crate::metrics::collect(&self.skel) + } + + /// One row per LLC for debug logs. Reuses the same fold guards. + fn log_per_llc(&self) { + if !log::log_enabled!(log::Level::Debug) { + return; + } + for (llc, row) in crate::metrics::collect_per_llc(&self.skel) { + let mut buf: Vec = Vec::new(); + if row.format_llc(&mut buf, llc).is_ok() { + log::debug!("{}", String::from_utf8_lossy(&buf).trim_end()); + } + } + } + + pub fn run(&mut self, shutdown: Arc) -> Result { + let (res_ch, req_ch) = self.stats_server.channels(); + while !shutdown.load(Ordering::Relaxed) && !self.exited() { + match req_ch.recv_timeout(Duration::from_secs(1)) { + Ok(()) => { + res_ch.send(self.get_metrics())?; + self.log_per_llc(); + } + Err(RecvTimeoutError::Timeout) => {} + Err(e) => Err(e)?, + } + } + let _ = self.struct_ops.take(); + uei_report!(&self.skel, uei) + } +} + +impl Drop for Scheduler<'_> { + fn drop(&mut self) { + info!("Unregister {SCHEDULER_NAME} scheduler"); + } +} + +/// Drive the restart loop until shutdown or a non-restart exit. +/// Holds shutdown, the monitor thread, and the open object. +/// Restart follows the exit info. A restart starts a new instance. +pub fn drive(opts: &Opts) -> Result<()> { + use anyhow::Context as _; + let shutdown = Arc::new(AtomicBool::new(false)); + let sd = shutdown.clone(); + ctrlc::set_handler(move || sd.store(true, Ordering::Relaxed)) + .context("Error setting Ctrl-C handler")?; + if let Some(intv) = opts.monitor.or(opts.stats) { + let dur = crate::cli::poll_interval_secs(intv)?; + let sd = shutdown.clone(); + let jh = std::thread::spawn(move || { + if let Err(e) = crate::stats::monitor(dur, sd) { + warn!("monitor failed: {e:#}"); + } + }); + if opts.monitor.is_some() { + let _ = jh.join(); + return Ok(()); + } + } + let mut open_object = MaybeUninit::::uninit(); + loop { + let mut sched = Scheduler::init(opts, &mut open_object)?; + if !sched.run(shutdown.clone())?.should_restart() { + break; + } + } + info!("Scheduler exited"); + Ok(()) +} diff --git a/scheds/experimental/scx_flow/src/rust/config.rs b/scheds/experimental/scx_flow/src/rust/config.rs deleted file mode 100644 index 9536510e9c..0000000000 --- a/scheds/experimental/scx_flow/src/rust/config.rs +++ /dev/null @@ -1,1408 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -//! Validated scheduling constants for the flow scheduler. -//! -//! Copyright (c) 2026 Galih Tama - -//! Holds the validated constants with defaults that match intf.h. - -use anyhow::Result; -use anyhow::bail; - -/// Fixed slice in nanos at 1ms. Every insert uses this slice. -pub const QUANTUM_NS: u64 = 1_000_000; -/// Dynamic slice floor in nanos at 10us. Fresh waits clamp the -/// saturated remaining time to this floor with the quantum ceiling. -pub const SLICE_MIN_NS: u64 = 10_000; -/// Ultra-low latency boundary in nanos at 50us. Caps the T1 tier, -/// so audio plus frame pacing bursts pace tightly with no extra hold. -pub const SLICE_ULL_NS: u64 = 50_000; -/// Low latency boundary in nanos at 100us. Caps the T2 tier, so -/// compositor plus UI bursts rotate each tenth quantum with no hold. -/// Matches the latency slice cap, so urgent wakeups keep one bound. -pub const SLICE_LL_NS: u64 = 100_000; -/// Medium-low latency boundary in nanos at 500us. Caps the T3 tier, -/// so IPC plus microservice bursts hold margin with no storm. -pub const SLICE_MLL_NS: u64 = 500_000; -/// Normal latency boundary in nanos at 1ms. Caps the T4 tier at one -/// quantum, so desktop plus worker bursts rotate each quantum. -pub const SLICE_NL_NS: u64 = 1_000_000; -/// Extended normal latency boundary in nanos at 5ms. Caps the T5 -/// tier, so bulk I/O plus build bursts hold room with no starve. -pub const SLICE_ENL_NS: u64 = 5_000_000; -/// Dynamic slice ceiling in nanos at 20ms. Caps the T6 tier plus the -/// multi-tier spectrum, so throughput bursts hold room with an 80ms -/// period guarding starvation. -pub const SLICE_MAX_NS: u64 = 20_000_000; -/// Default period in nanos at 80ms. Holds four 20ms slices, so a -/// fully used throughput task still leaves room for waits plus -/// retries inside the period with no starvation under 20ms holds. -pub const PERIOD_NS: u64 = 80_000_000; -/// Least predictor value in nanos at 1. Clamps short bursts. -pub const PRED_MIN_NS: u64 = 1; -/// Largest predictor value in nanos at 1s. Clamps long bursts. -pub const PRED_MAX_NS: u64 = 1_000_000_000; -/// Base capacity in units at 1024. Symmetric hosts share the base. -pub const CAP_BASE: u32 = 1024; -/// Base weight with a neutral share. -pub const WEIGHT_BASE: u32 = 128; -/// Least weight admitted. -pub const WEIGHT_MIN: u32 = 1; -/// Largest weight admitted. -pub const WEIGHT_MAX: u32 = 16_384; -/// Max hint rows bound shared with the BPF header. -pub const HINT_MAX: u64 = 8192; -/// RED bound in nanos at 256us. Caps the maximum exceeding time with -/// the fixed bound shared by admit plus reclaim plus credit. -pub const RED_EMAX_NS: u64 = 256_000; -/// RED tolerance in nanos at 64us. Holds hard task slack only with the -/// fixed value shared by admit plus reclaim. -pub const RED_TOL_NS: u64 = 64_000; -/// Adaptive grow step in nanos at 64us frozen for wire compat only. -/// Whitelisted with no use after the proportional law. -pub const ADAPT_GROW_NS: u64 = 64_000; -/// Adaptive shrink step in nanos at 128us frozen for wire compat only. -/// Whitelisted with no use after the proportional law. -pub const ADAPT_SHRINK_NS: u64 = 128_000; -/// Proportional adapt cap in nanos at 1ms. Caps one shift step. -pub const ADAPT_PROP_MAX_NS: u64 = 1_000_000; -/// Proportional adapt shift at 3. Maps exceed plus slack to one eighth. -pub const ADAPT_PROP_SHIFT: u32 = 3; -/// Proportional deadband shift at 5. Holds one thirty-second of the base -/// as the quiet band with shifts only. -pub const ADAPT_DEADBAND_SHIFT: u32 = 5; -/// Proportional deadband floor in nanos at 8us. Keeps the quiet band -/// above one tick on small slices. -pub const ADAPT_DEADBAND_MIN_NS: u64 = 8_000; -/// Half-damp shift at 1. Halves the capped step once, so one correction -/// moves at most one quarter base. -pub const ADAPT_DAMP_SHIFT: u32 = 1; -/// Predictor rise shift at 3. Moves the average one eighth toward a -/// larger sample, so bursts grow fast. -pub const PRED_UP_SHIFT: u32 = 3; -/// Predictor fall shift at 4. Moves the average one sixteenth toward a -/// smaller sample, so bursts decay slow. -pub const PRED_DOWN_SHIFT: u32 = 4; -/// Deviation widen shift at 2. Moves the deviation one quarter toward a -/// larger error, so ragged bursts gain margin fast. -pub const PRED_DEV_UP_SHIFT: u32 = 2; -/// Deviation narrow shift at 3. Moves the deviation one eighth toward a -/// smaller error, so stable bursts keep margin. -pub const PRED_DEV_DOWN_SHIFT: u32 = 3; -/// Deviation margin shift at 1. Adds half deviation to the period, so -/// the deadline holds average plus one and a half deviation. -pub const PRED_DEV_MARGIN_SHIFT: u32 = 1; -/// Latency slice cap in nanos at 100us. Caps the dynamic slice plus -/// the carryover plus the adapt step for latency work, so urgent -/// wakeups rotate each tenth quantum with no extra hold. The cap -/// equals the preempt tail, so a latency head at the cap never passes -/// the tail gate and floors with no resume. Adapt steps cap at 1ms -/// then re-clamp here, so one shift never holds past the cap. RED Emax -/// stays at 256us past the cap, so a capped latency slice never pays -/// as victim with no swap. -pub const SLICE_LAT_NS: u64 = 100_000; -/// Latency sleep floor in nanos at 20us. Vetoes only sleeps below this -/// floor toward batch with no knob, so the 100us slice cap stays -/// decoupled with no extra hold. Like fair.c, the floor paces service -/// with no fixed priority hold. Unknown sleep fails open with no stall. -pub const LAT_SLEEP_MIN_NS: u64 = 20_000; -/// Latency deadline bound in nanos at 4ms. Holds one twentieth period. -pub const D_LAT_NS: u64 = 4_000_000; -/// Preempt margin in nanos at 100us. Leads the occupant key, so near -/// ties never bounce with no knob. -pub const PREEMPT_MARGIN_NS: u64 = 100_000; -/// Preempt tail in nanos at 100us. Holds the owner leftover, so nearly -/// done owners finish with no knob. -pub const PREEMPT_TAIL_NS: u64 = 100_000; - -/// Default fixed slice in nanos. -const DEF_QUANTUM_NS: u64 = QUANTUM_NS; - -/// Mirror of flow_adapt_deadband in intf.h for host tests. -/// Holds the larger of base shift 5 plus the 8us floor. -#[cfg(test)] -pub fn adapt_deadband(base: u64) -> u64 { - let band = base >> ADAPT_DEADBAND_SHIFT; - if band < ADAPT_DEADBAND_MIN_NS { - return ADAPT_DEADBAND_MIN_NS; - } - band -} - -/// Mirror of flow_adapt_prop in intf.h for host tests. -/// Shifts only without a divide, capped at 1ms plus half of base then -/// halved once more, clamped 10us to 1ms with proportional deadband. -/// An exceed shrinks, a slack grows, both zero holds, exceed wins. -#[cfg(test)] -pub fn adapt_prop(cur: u32, exceed: u64, slack: u64) -> u32 { - let base = if cur == 0 { QUANTUM_NS } else { cur as u64 }; - let band = adapt_deadband(base); - // Clamp helper keeps the same 10us plus 1ms bounds as BPF. - let clamp = |v: u64| -> u32 { - if v < SLICE_MIN_NS { - return SLICE_MIN_NS as u32; - } - if v > QUANTUM_NS { - return QUANTUM_NS as u32; - } - v as u32 - }; - if exceed != 0 { - if exceed <= band { - return clamp(base); - } - let mut step = exceed >> ADAPT_PROP_SHIFT; - if step > ADAPT_PROP_MAX_NS { - step = ADAPT_PROP_MAX_NS; - } - if step > (base >> 1) { - step = base >> 1; - } - step >>= ADAPT_DAMP_SHIFT; - if step == 0 { - return clamp(base); - } - if base <= step { - return SLICE_MIN_NS as u32; - } - return clamp(base - step); - } - if slack != 0 { - if slack <= band { - return clamp(base); - } - let mut step = slack >> ADAPT_PROP_SHIFT; - if step > ADAPT_PROP_MAX_NS { - step = ADAPT_PROP_MAX_NS; - } - if step > (base >> 1) { - step = base >> 1; - } - step >>= ADAPT_DAMP_SHIFT; - if step == 0 { - return clamp(base); - } - return clamp(base.saturating_add(step)); - } - clamp(base) -} - -/// Mirror of flow_slice_lat_clamp in intf.h for host tests. -/// Caps the slice at 100us for latency with no knob. -#[cfg(test)] -pub fn slice_lat_clamp(slice: u32, is_lat: bool) -> u32 { - if is_lat && (slice as u64) > SLICE_LAT_NS { - return SLICE_LAT_NS as u32; - } - slice -} - -/// Mirror of flow_pred_avg in intf.h for host tests. -/// Rise shift 3 plus fall shift 4 with 1ns to 1s clamp. -#[cfg(test)] -pub fn pred_avg(avg: u64, delta: u64) -> u64 { - let d = if delta == 0 { PRED_MIN_NS } else { delta }.clamp(PRED_MIN_NS, PRED_MAX_NS); - if avg == 0 { - return d; - } - if d > avg { - let diff = (d - avg) >> PRED_UP_SHIFT; - return avg.saturating_add(diff).clamp(PRED_MIN_NS, PRED_MAX_NS); - } - let diff = (avg - d) >> PRED_DOWN_SHIFT; - if diff > avg { - return PRED_MIN_NS; - } - (avg - diff).clamp(PRED_MIN_NS, PRED_MAX_NS) -} - -/// Mirror of flow_pred_dev in intf.h for host tests. -/// Widen shift 2 plus narrow shift 3 with first floor at average quarter. -#[cfg(test)] -pub fn pred_dev(dev: u64, avg: u64, delta: u64) -> u64 { - let d = if delta == 0 { PRED_MIN_NS } else { delta }.clamp(PRED_MIN_NS, PRED_MAX_NS); - let a = if avg == 0 { d } else { avg }; - let mut err = d.abs_diff(a); - if err == 0 { - err = PRED_MIN_NS; - } - err = err.clamp(PRED_MIN_NS, PRED_MAX_NS); - if dev == 0 { - let floor = avg >> 2; - if floor > err { - return floor.clamp(PRED_MIN_NS, PRED_MAX_NS); - } - return err; - } - if err > dev { - let diff = (err - dev) >> PRED_DEV_UP_SHIFT; - return dev.saturating_add(diff).clamp(PRED_MIN_NS, PRED_MAX_NS); - } - let diff = (dev - err) >> PRED_DEV_DOWN_SHIFT; - if diff > dev { - return PRED_MIN_NS; - } - (dev - diff).clamp(PRED_MIN_NS, PRED_MAX_NS) -} - -/// Mirror of flow_pred_period in intf.h for host tests. -/// Adds average plus deviation plus half deviation margin. -#[cfg(test)] -pub fn pred_period(avg: u64, dev: u64) -> u64 { - if avg == 0 { - return PERIOD_NS; - } - let margin = dev >> PRED_DEV_MARGIN_SHIFT; - let sum = avg.saturating_add(dev).saturating_add(margin); - if sum == u64::MAX { - return PRED_MAX_NS; - } - sum.clamp(PRED_MIN_NS, PRED_MAX_NS) -} - -/// Mirror of flow_classify_latency_tier in intf.h for host tests. -/// Adds avg plus dev plus half dev margin with saturation, so stable -/// bursts keep a tight tier while ragged bursts hold margin with no -/// wrap. Critical forces ULL, then 50us plus 100us plus 500us plus 1ms -/// plus 5ms bound ULL plus LL plus MLL plus NL plus ENL, else 20ms holds -/// throughput. Host-test mirror with no BPF slice caller. -#[cfg(test)] -pub fn classify_tier(avg: u64, dev: u64, is_crit: bool) -> u32 { - let margin = dev >> PRED_DEV_MARGIN_SHIFT; - let pred = avg.saturating_add(dev).saturating_add(margin); - if is_crit || pred <= SLICE_ULL_NS { - return SLICE_ULL_NS as u32; - } - if pred <= SLICE_LL_NS { - return SLICE_LL_NS as u32; - } - if pred <= SLICE_MLL_NS { - return SLICE_MLL_NS as u32; - } - if pred <= SLICE_NL_NS { - return SLICE_NL_NS as u32; - } - if pred <= SLICE_ENL_NS { - return SLICE_ENL_NS as u32; - } - SLICE_MAX_NS as u32 -} - -/// Mirror of flow_red_cost in intf.h for host tests. -/// Costs burst else slice else quantum clamped to 10us plus 20ms, so the -/// guarantee holds without shaping shares plus throughput never -/// underestimates past the quantum. -#[cfg(test)] -pub fn red_cost(avg: u64, slice: u32) -> u64 { - if avg != 0 { - if avg < SLICE_MIN_NS { - return SLICE_MIN_NS; - } - if avg > SLICE_MAX_NS { - return SLICE_MAX_NS; - } - return avg; - } - if slice != 0 { - let s = slice as u64; - if s < SLICE_MIN_NS { - return SLICE_MIN_NS; - } - if s > SLICE_MAX_NS { - return SLICE_MAX_NS; - } - return s; - } - QUANTUM_NS -} - -/// Mirror of flow_lat_deadline in intf.h for host tests. -/// Takes max 4ms else slice plus margin with saturation, then adds now -/// with saturation for ns accuracy without a divide. -#[cfg(test)] -pub fn lat_deadline(now: u64, slice: u32) -> u64 { - let need = (slice as u64).saturating_add(PREEMPT_MARGIN_NS); - let bound = if need > D_LAT_NS { need } else { D_LAT_NS }; - now.saturating_add(bound) -} - -/// Mirror of flow_lat_crit_ext in intf.h for host tests. -/// Advisory veto toward batch with 20us sleep floor plus quantum-relative -/// bounds using shifts only, so unknown sleep, clamp, and share fail open. -/// The sleep floor stays decoupled from the 100us slice cap. Newcomers with -/// no history stay batch with probation. The burst test adds average plus -/// deviation plus half deviation margin, so RED plus slice agree. -#[cfg(test)] -pub fn lat_crit_ext( - avg: u64, - dev: u64, - hint_us: u32, - sleep_ns: u64, - uclamp_min: u32, - eff_w: u32, -) -> bool { - if avg == 0 { - return false; - } - { - let margin = dev >> PRED_DEV_MARGIN_SHIFT; - let pred = avg.saturating_add(dev).saturating_add(margin); - if pred == u64::MAX { - return false; - } - if pred > QUANTUM_NS { - return false; - } - } - if hint_us != 0 { - let h = hint_us as u64; - if h > 18_446_744_073_709_551 { - return false; - } - if h * 1000 > QUANTUM_NS { - return false; - } - } - if sleep_ns != 0 && sleep_ns < LAT_SLEEP_MIN_NS { - return false; - } - if uclamp_min != 0 && uclamp_min < 512 { - return false; - } - if eff_w != 0 && eff_w < WEIGHT_BASE { - return false; - } - true -} - -/// Mirror of flow_lat_crit in intf.h for host tests. -/// Newcomers with no history stay batch with probation. Tests average -/// plus deviation plus half deviation margin against the quantum. -#[cfg(test)] -pub fn lat_crit(avg: u64, dev: u64) -> bool { - if avg == 0 { - return false; - } - let margin = dev >> PRED_DEV_MARGIN_SHIFT; - let pred = avg.saturating_add(dev).saturating_add(margin); - if pred == u64::MAX { - return false; - } - pred <= QUANTUM_NS -} - -/// Mirror of flow_is_lat in intf.h for host tests. -/// Unifies base plus ext, so RED and slice agree. -#[cfg(test)] -pub fn is_lat( - avg: u64, - dev: u64, - hint_us: u32, - sleep_ns: u64, - uclamp_min: u32, - eff_w: u32, -) -> bool { - if !lat_crit(avg, dev) { - return false; - } - lat_crit_ext(avg, dev, hint_us, sleep_ns, uclamp_min, eff_w) -} - -/// Wrap-safe order for host tests mirroring flow_time_before. -/// Uses the signed diff, so the u64 wrap keeps order with no branch. -#[cfg(test)] -fn time_before(a: u64, b: u64) -> bool { - (a.wrapping_sub(b) as i64) < 0 -} - -/// Mirror of flow_sleep_ns in intf.h for host tests. -/// Isolates now minus wait minus burst, so queue plus run never count -/// as sleep with wrap safety and probation. -#[cfg(test)] -pub fn sleep_ns(old_wait: u64, now: u64, avg: u64) -> u64 { - if old_wait == 0 { - return 0; - } - if !time_before(old_wait, now) { - return 0; - } - let mut gap = now.wrapping_sub(old_wait); - if avg != 0 { - if gap > avg { - gap -= avg; - } else { - gap = 0; - } - } - gap -} - -/// Mirror of flow_preempt_ok in preempt.bpf.c for host tests. -/// Needs lat arrival against batch owner with 100us margin lead plus -/// 100us tail left on start plus inherit cur, so near ties plus nearly -/// done owners never bounce with wrap safety. -#[cfg(test)] -pub fn preempt_ok( - arr_key: u64, - occ_key: u64, - now: u64, - occ_run_at: u64, - occ_cur: u32, - arr_lat: bool, - occ_lat: bool, -) -> bool { - if !arr_lat || occ_lat { - return false; - } - if arr_key == 0 || arr_key == u64::MAX { - return false; - } - if occ_key == 0 || occ_key == u64::MAX { - return false; - } - if !time_before(arr_key, occ_key) { - return false; - } - let margin = arr_key.saturating_add(PREEMPT_MARGIN_NS); - if margin == u64::MAX { - return false; - } - if !time_before(margin, occ_key) { - return false; - } - if occ_run_at == 0 || occ_run_at == u64::MAX { - return false; - } - let base = if occ_cur == 0 { - QUANTUM_NS - } else { - occ_cur as u64 - }; - let occ_end = occ_run_at.saturating_add(base); - if occ_end == u64::MAX { - return false; - } - let tail = now.saturating_add(PREEMPT_TAIL_NS); - if tail == u64::MAX { - return false; - } - if !time_before(tail, occ_end) { - return false; - } - true -} - -/// Mirror of flow_slice_resume in intf.h for host tests. -/// Keeps start plus cur leftover clamped to 10us plus 100us else 1ms -/// with wrap-safe order, so a wrapped clock never reads as leftover. -/// Equality fails closed and floors, so a head at the 100us cap never -/// resumes past the equal tail. -#[cfg(test)] -pub fn slice_resume(start: u64, now: u64, is_lat: bool, cur: u32) -> u32 { - let base = if cur == 0 { QUANTUM_NS } else { cur as u64 }; - if start == 0 || start == u64::MAX { - return base as u32; - } - let end = start.saturating_add(base); - if end == u64::MAX { - return base as u32; - } - let rem = if !time_before(now, end) && now != end { - 0 - } else if time_before(now, end) { - end.wrapping_sub(now) - } else { - 0 - }; - let cap = if is_lat { SLICE_LAT_NS } else { QUANTUM_NS }; - if rem < SLICE_MIN_NS { - return SLICE_MIN_NS as u32; - } - if rem > cap { - return cap as u32; - } - rem as u32 -} - -/// Resume gap in nanos at 5s shared with the BPF header. -/// Past one period, so only a real stall trips with no false trip. -#[cfg(test)] -pub const RESUME_GAP_NS: u64 = 5_000_000_000; - -/// Mirror of flow_delta_clamp in intf.h for host tests. -/// Zero or future start folds to zero with wrap safety and no charge. -#[cfg(test)] -pub fn delta_clamp(now: u64, start: u64) -> u64 { - if start == 0 { - return 0; - } - if time_before(now, start) { - return 0; - } - now.wrapping_sub(start) -} - -/// Mirror of flow_gap_is_resume in intf.h for host tests. -/// Past 5s reads as an s2idle stall where monotonic still advances. -/// S3 pauses monotonic, so S3 trips only the boot gap with a reseed. -#[cfg(test)] -pub fn gap_is_resume(delta: u64) -> bool { - delta > RESUME_GAP_NS -} - -/// Validated scheduling constants. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Config { - /// Fixed slice in nanos. Always 1ms with no knob. - pub quantum_ns: u64, -} - -impl Default for Config { - /// Compile time defaults from the shared header. - fn default() -> Self { - Self { - quantum_ns: DEF_QUANTUM_NS, - } - } -} - -impl Config { - /// Validate the constants against the bounds the BPF side relies on. - /// An invalid value is a programming fault, not a runtime state. - /// The slice stays fixed at 1ms with base weight 128 in range - /// 1 to 16384. The period stays at 80ms with predictor 1ns to 1s. - /// Fresh waits clamp remaining time to the 10us floor plus the 1ms - /// ceiling with misses holding else flooring only. Tiers pace at - /// 50us plus 100us plus 500us plus 1ms plus 5ms with a 20ms - /// ceiling plus a 10us floor, so throughput holds room with no starvation. - /// Dispatch moves at most one hint threaded move per tier capped - /// by remaining slots with visits capped at 8 per pass shared across - /// five tiers with steal window 4 to 8 plus BSF - /// four disjoint past SSF eight for twelve unique peers on hosts - /// with at least twelve CPUs with node-local phases plus drain plus - /// minimum plus id tiebreak, and RED admits with residual plus - /// exceed plus fixed 64us tolerance plus fixed 256us Emax used only - /// for the guarantee with base capacity 1024. Queues hold 1024 local plus - /// 16 node plus machine plus reject with ids in the 0x5100 region. - /// Hints hold 8192 flat rows with period plus weight and no timer - /// wait. Preempt needs 100us margin plus 100us tail strictly with a - /// floor at 100us and one kick per wait gated on eligibility. Fairness - /// bounds lag at 2ms with vruntime plus virtual deadline pacing queue - /// order. Stats hold 17 counters at 136B with preempt kicks plus - /// skipped plus RED rejects plus reclaims. Adaptive shrinks by exceed - /// right 3 capped 1ms plus half then halved on late else grows by slack - /// right 3 capped 1ms plus half then halved on early with deadband hold - /// plus clamp to 10us plus 1ms without changing virtual time. Latency - /// caps the slice at 100us plus the key at now plus max 4ms else slice - /// plus 100us with RED on the original deadline. Latency vetoes sleeps - /// below 20us toward batch with unknown open, so the sleep floor stays - /// decoupled from the slice cap. The predictor rises fast with shift 3 - /// plus falls slow with shift 4, widens fast with shift 2 plus narrows - /// slow with shift 3, and adds half deviation margin, so the deadline - /// holds average plus one and a half deviation. Fixed RED keeps 64us - /// tolerance plus 256us Emax with task at 72B. - pub fn validate(&self) -> Result<()> { - if self.quantum_ns != QUANTUM_NS { - bail!("quantum bad {}", self.quantum_ns); - } - if SLICE_MIN_NS != 10_000 { - bail!("slice floor bad"); - } - if SLICE_MIN_NS >= QUANTUM_NS { - bail!("slice floor over ceiling bad"); - } - if WEIGHT_MIN != 1 || WEIGHT_BASE != 128 || WEIGHT_MAX != 16_384 { - bail!("weight bounds bad"); - } - if PERIOD_NS != 80_000_000 { - bail!("period bounds bad"); - } - if PRED_MIN_NS != 1 || PRED_MAX_NS != 1_000_000_000 { - bail!("predictor bounds bad"); - } - if CAP_BASE != 1024 { - bail!("capacity base bad"); - } - if HINT_MAX != 8192 { - bail!("hint bound bad"); - } - if crate::bpf_intf::flow_consts_FLOW_QUANTUM_NS != QUANTUM_NS { - bail!("quantum header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_MIN_NS != SLICE_MIN_NS { - bail!("slice floor header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PERIOD_NS != PERIOD_NS { - bail!("period header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_MIN_NS != PRED_MIN_NS { - bail!("pred floor bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_MAX_NS != PRED_MAX_NS { - bail!("pred ceiling bad"); - } - if crate::bpf_intf::flow_consts_FLOW_WEIGHT_MIN != WEIGHT_MIN as u64 { - bail!("weight floor bad"); - } - if crate::bpf_intf::flow_consts_FLOW_WEIGHT_BASE != WEIGHT_BASE as u64 { - bail!("weight base bad"); - } - if crate::bpf_intf::flow_consts_FLOW_WEIGHT_MAX != WEIGHT_MAX as u64 { - bail!("weight top bad"); - } - if crate::bpf_intf::flow_consts_FLOW_CAP_BASE != CAP_BASE as u64 { - bail!("cap base bad"); - } - if crate::bpf_intf::flow_consts_FLOW_HINT_MAX != HINT_MAX { - bail!("hint header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PREEMPT_MARGIN_NS != PREEMPT_MARGIN_NS { - bail!("margin bad"); - } - if PREEMPT_MARGIN_NS != 100_000 { - bail!("margin bounds bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PREEMPT_TAIL_NS != PREEMPT_TAIL_NS { - bail!("tail bad"); - } - if PREEMPT_TAIL_NS != 100_000 { - bail!("tail bounds bad"); - } - if crate::bpf_intf::flow_consts_FLOW_VLAG_MAX_NS != 2_000_000 { - bail!("lag bound bad"); - } - if crate::bpf_intf::flow_consts_FLOW_MAX_DSQS != 1042 { - bail!("dsq count bad"); - } - if crate::bpf_intf::flow_consts_FLOW_DISPATCH_MAX_VISIT != 8 { - bail!("visit bound bad"); - } - if crate::bpf_intf::flow_consts_FLOW_STEAL_MIN_PEERS != 4 - || crate::bpf_intf::flow_consts_FLOW_STEAL_MAX_PEERS != 8 - { - bail!("steal window bad"); - } - if crate::bpf_intf::flow_consts_FLOW_BSF_MAX_PEERS != 4 { - bail!("bsf bound bad"); - } - if crate::bpf_intf::flow_consts_FLOW_BSF_MAX_PEERS - > crate::bpf_intf::flow_consts_FLOW_DISPATCH_MAX_VISIT - { - bail!("bsf over visit bad"); - } - if crate::bpf_intf::flow_consts_FLOW_OVERFLOW != 0x5A01 { - bail!("overflow id bad"); - } - if crate::bpf_intf::flow_consts_FLOW_RED_EMAX_NS != RED_EMAX_NS { - bail!("red emax bad"); - } - if crate::bpf_intf::flow_consts_FLOW_RED_TOL_NS != RED_TOL_NS { - bail!("red tol bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_GROW_NS != ADAPT_GROW_NS { - bail!("adapt grow bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_SHRINK_NS != ADAPT_SHRINK_NS { - bail!("adapt shrink bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_PROP_MAX_NS != ADAPT_PROP_MAX_NS { - bail!("adapt prop max bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_PROP_SHIFT != ADAPT_PROP_SHIFT as u64 { - bail!("adapt prop shift bad"); - } - if ADAPT_PROP_MAX_NS != 1_000_000 { - bail!("prop max bounds bad"); - } - if ADAPT_PROP_SHIFT != 3 { - bail!("prop shift bounds bad"); - } - if ADAPT_PROP_MAX_NS > QUANTUM_NS { - bail!("prop max over ceiling bad"); - } - if SLICE_LAT_NS != 100_000 { - bail!("slice lat bad"); - } - if D_LAT_NS != 4_000_000 { - bail!("d lat bad"); - } - if SLICE_LAT_NS <= SLICE_MIN_NS { - bail!("slice lat floor bad"); - } - if SLICE_LAT_NS >= QUANTUM_NS { - bail!("slice lat over ceiling bad"); - } - if D_LAT_NS >= PERIOD_NS { - bail!("d lat over period bad"); - } - if SLICE_ULL_NS != 50_000 { - bail!("slice ull bad"); - } - if SLICE_LL_NS != 100_000 { - bail!("slice ll bad"); - } - if SLICE_MLL_NS != 500_000 { - bail!("slice mll bad"); - } - if SLICE_NL_NS != 1_000_000 { - bail!("slice nl bad"); - } - if SLICE_ENL_NS != 5_000_000 { - bail!("slice enl bad"); - } - if SLICE_MAX_NS != 20_000_000 { - bail!("slice max bad"); - } - if !(SLICE_MIN_NS < SLICE_ULL_NS - && SLICE_ULL_NS < SLICE_LL_NS - && SLICE_LL_NS < SLICE_MLL_NS - && SLICE_MLL_NS < SLICE_NL_NS - && SLICE_NL_NS < SLICE_ENL_NS - && SLICE_ENL_NS < SLICE_MAX_NS) - { - bail!("tier order bad"); - } - if SLICE_LL_NS != SLICE_LAT_NS { - bail!("tier ll lat bad"); - } - if SLICE_NL_NS != QUANTUM_NS { - bail!("tier nl quantum bad"); - } - if PERIOD_NS != 4 * SLICE_MAX_NS { - bail!("period slice max bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_ULL_NS != SLICE_ULL_NS { - bail!("slice ull header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_LL_NS != SLICE_LL_NS { - bail!("slice ll header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_MLL_NS != SLICE_MLL_NS { - bail!("slice mll header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_NL_NS != SLICE_NL_NS { - bail!("slice nl header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_ENL_NS != SLICE_ENL_NS { - bail!("slice enl header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_MAX_NS != SLICE_MAX_NS { - bail!("slice max header bad"); - } - if PRED_UP_SHIFT != 3 { - bail!("pred up bad"); - } - if PRED_DOWN_SHIFT != 4 { - bail!("pred down bad"); - } - if PRED_DEV_UP_SHIFT != 2 { - bail!("pred dev up bad"); - } - if PRED_DEV_DOWN_SHIFT != 3 { - bail!("pred dev down bad"); - } - if PRED_DEV_MARGIN_SHIFT != 1 { - bail!("pred margin bad"); - } - if ADAPT_DEADBAND_SHIFT != 5 { - bail!("deadband shift bad"); - } - if ADAPT_DEADBAND_MIN_NS != 8_000 { - bail!("deadband floor bad"); - } - if ADAPT_DAMP_SHIFT != 1 { - bail!("damp bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_UP_SHIFT != PRED_UP_SHIFT as u64 { - bail!("pred up header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_DOWN_SHIFT != PRED_DOWN_SHIFT as u64 { - bail!("pred down header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_DEV_UP_SHIFT != PRED_DEV_UP_SHIFT as u64 { - bail!("pred dev up header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_DEV_DOWN_SHIFT != PRED_DEV_DOWN_SHIFT as u64 { - bail!("pred dev down header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_PRED_DEV_MARGIN_SHIFT != PRED_DEV_MARGIN_SHIFT as u64 { - bail!("pred margin header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_DEADBAND_SHIFT != ADAPT_DEADBAND_SHIFT as u64 { - bail!("deadband shift header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_DEADBAND_MIN_NS != ADAPT_DEADBAND_MIN_NS { - bail!("deadband floor header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_ADAPT_DAMP_SHIFT != ADAPT_DAMP_SHIFT as u64 { - bail!("damp header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_SLICE_LAT_NS != SLICE_LAT_NS { - bail!("slice lat header bad"); - } - if LAT_SLEEP_MIN_NS != 20_000 { - bail!("lat sleep bad"); - } - if LAT_SLEEP_MIN_NS < PRED_MIN_NS { - bail!("lat sleep floor bad"); - } - if LAT_SLEEP_MIN_NS >= SLICE_LAT_NS { - bail!("lat sleep over slice bad"); - } - if crate::bpf_intf::flow_consts_FLOW_LAT_SLEEP_MIN_NS != LAT_SLEEP_MIN_NS { - bail!("lat sleep header bad"); - } - if crate::bpf_intf::flow_consts_FLOW_D_LAT_NS != D_LAT_NS { - bail!("d lat header bad"); - } - if RED_TOL_NS != 64_000 { - bail!("red tol bad"); - } - if RED_EMAX_NS != 256_000 { - bail!("red emax bad"); - } - if std::mem::size_of::() != 136 { - bail!("stats size bad"); - } - if std::mem::size_of::() != 72 { - bail!("task size bad"); - } - Ok(()) - } - - /// One line summary of the constants for the start log. - /// Values print in microseconds for brevity. - pub fn describe(&self) -> String { - format!("quantum={}us", self.quantum_ns / 1000,) - } -} - -/// Builder for Config used only by tests. -/// Production uses Config default directly. -#[cfg(test)] -#[derive(Debug, Clone, Default)] -pub struct ConfigBuilder { - quantum_ns: Option, -} - -#[cfg(test)] -impl ConfigBuilder { - /// Set the fixed slice. - pub fn quantum_ns(mut self, v: u64) -> Self { - self.quantum_ns = Some(v); - self - } - /// Assemble and validate the result. - pub fn build(self) -> Result { - let d = Config::default(); - let cfg = Config { - quantum_ns: self.quantum_ns.unwrap_or(d.quantum_ns), - }; - cfg.validate()?; - Ok(cfg) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn defaults_are_valid() { - Config::default().validate().unwrap(); - } - - #[test] - fn builder_defaults_match_config() { - let cfg = ConfigBuilder::default().build().unwrap(); - assert_eq!(cfg, Config::default()); - } - - #[test] - fn rejects_bad_quantum() { - let a = ConfigBuilder::default().quantum_ns(1).build(); - assert!(a.is_err()); - let b = ConfigBuilder::default().quantum_ns(2_000_000).build(); - assert!(b.is_err()); - } - - #[test] - /// Summary holds the fixed slice with no knob. - fn describe_is_stable() { - let s = Config::default().describe(); - assert!(s.contains("quantum=1000us")); - assert!(!s.contains("batch")); - } - - #[test] - /// Dynamic slice spans the 10us floor to the 1ms ceiling. - fn slice_bounds_match_intf_h() { - assert_eq!(SLICE_MIN_NS, 10_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_MIN_NS, SLICE_MIN_NS); - const _: () = assert!(SLICE_MIN_NS < QUANTUM_NS); - } - - #[test] - /// Defaults match the shared header with local plus shared queues. - fn defaults_match_intf_h() { - assert_eq!( - Config::default().quantum_ns, - crate::bpf_intf::flow_consts_FLOW_QUANTUM_NS - ); - assert_eq!(QUANTUM_NS, 1_000_000); - assert_eq!(PERIOD_NS, 80_000_000); - assert_eq!(SLICE_ULL_NS, 50_000); - assert_eq!(SLICE_LL_NS, 100_000); - assert_eq!(SLICE_MLL_NS, 500_000); - assert_eq!(SLICE_NL_NS, 1_000_000); - assert_eq!(SLICE_ENL_NS, 5_000_000); - assert_eq!(SLICE_MAX_NS, 20_000_000); - assert_eq!(PERIOD_NS, 4 * SLICE_MAX_NS); - assert_eq!(PRED_MIN_NS, 1); - assert_eq!(PRED_MAX_NS, 1_000_000_000); - assert_eq!(CAP_BASE, 1024); - assert_eq!(WEIGHT_MIN, 1); - assert_eq!(WEIGHT_BASE, 128); - assert_eq!(WEIGHT_MAX, 16_384); - assert_eq!(HINT_MAX, 8192); - assert_eq!(RED_EMAX_NS, 256_000); - assert_eq!(RED_TOL_NS, 64_000); - assert_eq!(ADAPT_GROW_NS, 64_000); - assert_eq!(ADAPT_SHRINK_NS, 128_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_MAX_DSQS, 1042); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_VLAG_MAX_NS, 2_000_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_MACHINE, 0x5A00); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_OVERFLOW, 0x5A01); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_DISPATCH_MAX_VISIT, 8); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_BSF_MAX_PEERS, 4); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_LOCAL_BASE, 0x5100); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_NODE_BASE, 0x5900); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_HINT_MAX, HINT_MAX); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_PRED_MIN_NS, PRED_MIN_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_PRED_MAX_NS, PRED_MAX_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_CAP_BASE, CAP_BASE as u64); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_WEIGHT_BASE, - WEIGHT_BASE as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_WEIGHT_MAX, - WEIGHT_MAX as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PREEMPT_MARGIN_NS, - PREEMPT_MARGIN_NS - ); - assert_eq!(PREEMPT_MARGIN_NS, 100_000); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PREEMPT_TAIL_NS, - PREEMPT_TAIL_NS - ); - assert_eq!(PREEMPT_TAIL_NS, 100_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_RED_EMAX_NS, RED_EMAX_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_RED_TOL_NS, RED_TOL_NS); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_GROW_NS, - ADAPT_GROW_NS - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_SHRINK_NS, - ADAPT_SHRINK_NS - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_PROP_MAX_NS, - ADAPT_PROP_MAX_NS - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_PROP_SHIFT, - ADAPT_PROP_SHIFT as u64 - ); - assert_eq!(ADAPT_PROP_MAX_NS, 1_000_000); - assert_eq!(ADAPT_PROP_SHIFT, 3); - assert_eq!(ADAPT_DEADBAND_SHIFT, 5); - assert_eq!(ADAPT_DEADBAND_MIN_NS, 8_000); - assert_eq!(ADAPT_DAMP_SHIFT, 1); - assert_eq!(PRED_UP_SHIFT, 3); - assert_eq!(PRED_DOWN_SHIFT, 4); - assert_eq!(PRED_DEV_UP_SHIFT, 2); - assert_eq!(PRED_DEV_DOWN_SHIFT, 3); - assert_eq!(PRED_DEV_MARGIN_SHIFT, 1); - assert_eq!(SLICE_LAT_NS, 100_000); - assert_eq!(LAT_SLEEP_MIN_NS, 20_000); - assert_eq!(D_LAT_NS, 4_000_000); - const _: () = assert!(D_LAT_NS < PERIOD_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_ULL_NS, SLICE_ULL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_LL_NS, SLICE_LL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_MLL_NS, SLICE_MLL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_NL_NS, SLICE_NL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_ENL_NS, SLICE_ENL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_MAX_NS, SLICE_MAX_NS); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_UP_SHIFT, - PRED_UP_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_DOWN_SHIFT, - PRED_DOWN_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_DEV_UP_SHIFT, - PRED_DEV_UP_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_DEV_DOWN_SHIFT, - PRED_DEV_DOWN_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_DEV_MARGIN_SHIFT, - PRED_DEV_MARGIN_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_DEADBAND_SHIFT, - ADAPT_DEADBAND_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_DEADBAND_MIN_NS, - ADAPT_DEADBAND_MIN_NS - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_DAMP_SHIFT, - ADAPT_DAMP_SHIFT as u64 - ); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_LAT_NS, SLICE_LAT_NS); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_LAT_SLEEP_MIN_NS, - LAT_SLEEP_MIN_NS - ); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_D_LAT_NS, D_LAT_NS); - assert_eq!( - std::mem::size_of::(), - 136 - ); - assert_eq!(std::mem::size_of::(), 72); - } - - #[test] - /// Proportional adapt shrinks on exceed plus grows on slack. - fn prop_shrink_grow_matches_intf_h() { - // Deadband holds tiny exceed plus slack with no hunt. - assert_eq!(adapt_deadband(1_000_000), 31_250); - assert_eq!(adapt_deadband(10_000), 8_000); - assert_eq!(adapt_prop(1_000_000, 8_000, 0), 1_000_000); - assert_eq!(adapt_prop(500_000, 0, 1_600), 500_000); - // Exceed 64us shrinks 4us with shift 3 plus half-damp. - assert_eq!(adapt_prop(1_000_000, 64_000, 0), 996_000); - // Slack 64us grows 4us with shift 3 plus half-damp. - assert_eq!(adapt_prop(500_000, 0, 64_000), 504_000); - // Huge exceed caps at half of base then halved to 750k. - assert_eq!(adapt_prop(1_000_000, 10_000_000, 0), 750_000); - // Mid exceed 2ms shrinks 125us with shift 3 plus half-damp. - assert_eq!(adapt_prop(1_000_000, 2_000_000, 0), 875_000); - // Huge slack caps at 1ms grow then halved clamped to 1ms. - assert_eq!(adapt_prop(900_000, 0, 10_000_000), 1_000_000); - // Small base shrinks to the 10us floor. - assert_eq!(adapt_prop(10_000, 80_000, 0), 10_000); - // On-time hold keeps the clamped slice. - assert_eq!(adapt_prop(500_000, 0, 0), 500_000); - // Zero slice inherits the quantum then holds in deadband. - assert_eq!(adapt_prop(0, 8_000, 0), 1_000_000); - // Tiny exceed below 8ns holds without a divide. - assert_eq!(adapt_prop(500_000, 7, 0), 500_000); - // Early slack inside deadband holds with no hunt. - assert_eq!(adapt_prop(500_000, 0, 200), 500_000); - // Exceed wins when both hold. - assert_eq!( - adapt_prop(500_000, 64_000, 1_600), - adapt_prop(500_000, 64_000, 0) - ); - } - - #[test] - /// Predictor rises fast plus falls slow with margin. - fn pred_up_down_margin_matches_intf_h() { - // First sample sets the average at once. - assert_eq!(pred_avg(0, 100_000), 100_000); - // Rise 80k over 100k moves 10k with shift 3. - assert_eq!(pred_avg(100_000, 180_000), 110_000); - // Fall 80k under 100k moves 5k with shift 4. - assert_eq!(pred_avg(100_000, 20_000), 95_000); - // Deviation widens fast with shift 2. - assert_eq!(pred_dev(10_000, 110_000, 180_000), 25_000); - // Period adds half deviation margin. - assert_eq!(pred_period(100_000, 10_000), 115_000); - assert_eq!(pred_period(0, 0), PERIOD_NS); - // Headers agree on every shift. - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_UP_SHIFT, - PRED_UP_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_PRED_DOWN_SHIFT, - PRED_DOWN_SHIFT as u64 - ); - assert_eq!( - crate::bpf_intf::flow_consts_FLOW_ADAPT_DEADBAND_MIN_NS, - ADAPT_DEADBAND_MIN_NS - ); - } - - #[test] - /// RED costs the pre-clamp slice without a post-clamp underestimate. - fn red_uses_pre_clamp_not_post() { - // Fresh 1ms pre-clamp caps to 100us for latency slice. - let pre = 1_000_000; - let post = slice_lat_clamp(pre, true); - assert_eq!(post, 100_000); - // RED still costs the 1ms pre-clamp without an underestimate. - assert_eq!(red_cost(0, pre), 1_000_000); - assert_eq!(red_cost(0, post), 100_000); - assert!(red_cost(0, pre) > red_cost(0, post)); - // Burst wins over slice with the same 10us plus 20ms clamp. - assert_eq!(red_cost(900_000, 1_000_000), 900_000); - assert_eq!(red_cost(0, 0), QUANTUM_NS); - assert_eq!(red_cost(1, 1_000_000), SLICE_MIN_NS); - // Throughput bursts past 1ms keep room to 20ms with no cap. - assert_eq!(red_cost(5_000_000, 0), 5_000_000); - assert_eq!(red_cost(0, 5_000_000), 5_000_000); - assert_eq!(red_cost(30_000_000, 0), SLICE_MAX_NS); - assert_eq!(red_cost(0, 30_000_000), SLICE_MAX_NS); - } - - #[test] - /// Latency slice clamps at 100us plus deadline at max 4ms. - fn lat_bounds_match_intf_h() { - const _: () = assert!(SLICE_LAT_NS > SLICE_MIN_NS); - const _: () = assert!(SLICE_LAT_NS < QUANTUM_NS); - const _: () = assert!(LAT_SLEEP_MIN_NS < SLICE_LAT_NS); - const _: () = assert!(LAT_SLEEP_MIN_NS >= PRED_MIN_NS); - assert_eq!(SLICE_LAT_NS, 100_000); - assert_eq!(LAT_SLEEP_MIN_NS, 20_000); - assert_eq!(D_LAT_NS, 4_000_000); - const _: () = assert!(D_LAT_NS < PERIOD_NS); - assert_eq!(PERIOD_NS, 80_000_000); - // Non latency keeps the slice. - assert_eq!(slice_lat_clamp(1_000_000, false), 1_000_000); - // Latency caps at 100us. - assert_eq!(slice_lat_clamp(1_000_000, true), 100_000); - assert_eq!(slice_lat_clamp(100_000, true), 100_000); - // Deadline floors at 4ms plus adds slice plus 100us. - assert_eq!(lat_deadline(0, 100_000), 4_000_000); - assert_eq!(lat_deadline(1_000, 1_000_000), 1_000 + 4_000_000); - assert_eq!(lat_deadline(0, 5_000_000), 5_100_000); - // Saturates on wrap with ns accuracy. - assert_eq!(lat_deadline(u64::MAX - 1_000, 100_000), u64::MAX); - } - - #[test] - /// Extended latency vetoes batch hints with probation. - fn lat_ext_veto_matches_intf_h() { - // Newcomers with no history stay batch with probation. - assert!(!lat_crit_ext(0, 0, 0, 0, 0, 0)); - assert!(!lat_crit(0, 0)); - assert!(!is_lat(0, 0, 0, 0, 0, 0)); - // Short burst with neutral signals keeps latency. - assert!(lat_crit_ext(100_000, 10_000, 0, 1_000_000, 0, 128)); - assert!(lat_crit(100_000, 10_000)); - assert!(is_lat(100_000, 10_000, 0, 1_000_000, 0, 128)); - // Unified latency matches base plus ext, so RED agrees. - assert!(!is_lat(900_000, 200_000, 0, 1_000_000, 0, 128)); - assert!(!is_lat(100_000, 10_000, 2000, 1_000_000, 0, 128)); - assert!(!is_lat(100_000, 10_000, 0, 10_000, 0, 128)); - assert!(is_lat(100_000, 10_000, 0, 30_000, 0, 128)); - assert!(is_lat(100_000, 10_000, 0, 50_000, 0, 128)); - assert!(is_lat(100_000, 10_000, 0, 150_000, 0, 128)); - assert!(is_lat(100_000, 10_000, 0, 0, 0, 128)); - // Long burst past quantum vetoes. - assert!(!lat_crit_ext(900_000, 200_000, 0, 1_000_000, 0, 128)); - // Large hint past quantum vetoes. - assert!(!lat_crit_ext(100_000, 10_000, 2000, 1_000_000, 0, 128)); - // Small hint keeps latency. - assert!(lat_crit_ext(100_000, 10_000, 500, 1_000_000, 0, 128)); - // Short sleep below 20us vetoes, 30us plus 50us plus 150us keep, - // unknown sleep fails open with no stall. - assert!(!lat_crit_ext(100_000, 10_000, 0, 10_000, 0, 128)); - assert!(lat_crit_ext(100_000, 10_000, 0, 30_000, 0, 128)); - assert!(lat_crit_ext(100_000, 10_000, 0, 50_000, 0, 128)); - assert!(lat_crit_ext(100_000, 10_000, 0, 150_000, 0, 128)); - assert!(lat_crit_ext(100_000, 10_000, 0, 0, 0, 128)); - // Explicit low clamp vetoes, unknown passes. - assert!(!lat_crit_ext(100_000, 10_000, 0, 1_000_000, 100, 128)); - assert!(lat_crit_ext(100_000, 10_000, 0, 1_000_000, 1024, 128)); - // Light share vetoes, heavy keeps. - assert!(!lat_crit_ext(100_000, 10_000, 0, 1_000_000, 0, 32)); - assert!(lat_crit_ext(100_000, 10_000, 0, 1_000_000, 0, 1024)); - } - - #[test] - /// Sleep isolates now minus wait minus burst with probation. - fn sleep_isolates_gap_minus_burst() { - // Gap 1ms minus 200us burst leaves 800us sleep. - assert_eq!(sleep_ns(1_000, 1_001_000, 200_000), 800_000); - // Burst-covered gap reads zero with no underflow. - assert_eq!(sleep_ns(1_000, 1_001_000, 2_000_000), 0); - // No history keeps the full gap. - assert_eq!(sleep_ns(1_000, 1_001_000, 0), 1_000_000); - // Unknown wait plus wait at now both read zero. - assert_eq!(sleep_ns(0, 1_000, 100_000), 0); - assert_eq!(sleep_ns(1_000, 1_000, 100_000), 0); - // Wrap keeps order: wait near max to small now reads 1501ns. - assert_eq!(sleep_ns(u64::MAX - 1_000, 500, 0), 1_501); - // Wrapped gap minus burst keeps the remainder with no underflow. - assert_eq!(sleep_ns(u64::MAX - 1_000, 500, 1_000), 501); - assert_eq!(sleep_ns(u64::MAX - 1_000, 500, 5_000), 0); - } - - #[test] - /// Resume keeps start plus cur leftover with clamp. - fn resume_uses_cur_not_quantum() { - // Start plus 500us cur with 400us left keeps 400us batch. - assert_eq!( - slice_resume(1_000, 1_000 + 100_000, false, 500_000), - 400_000 - ); - // Latency caps the same leftover at 100us. - assert_eq!(slice_resume(1_000, 1_000 + 100_000, true, 500_000), 100_000); - // Start plus 250us cur keeps 150us rem capped to 100us for latency. - assert_eq!(slice_resume(1_000, 1_000 + 100_000, true, 250_000), 100_000); - // Bad start inherits the stored slice. - assert_eq!(slice_resume(0, 1_000, false, 500_000), 500_000); - assert_eq!(slice_resume(0, 1_000, true, 500_000), 500_000); - // Past end floors to the minimum with no zero slice. - assert_eq!(slice_resume(1_000, 1_000 + 600_000, false, 500_000), 10_000); - // Saturated end near wrap inherits with no wrap to front. - assert_eq!(slice_resume(u64::MAX - 10, 100, false, 500_000), 500_000); - } - - #[test] - /// Suspend gap past 5s clamps with a reseed trip. - fn suspend_gap_clamps_with_reseed_trip() { - // Injected start 6s back trips the resume bound for a clamp. - let now = 10_000_000_000u64; - let start = now - 6_000_000_000u64; - let delta = delta_clamp(now, start); - assert_eq!(delta, 6_000_000_000); - assert!(gap_is_resume(delta)); - assert_eq!(RESUME_GAP_NS, 5_000_000_000); - assert_eq!( - RESUME_GAP_NS, - crate::bpf_intf::flow_consts_FLOW_RESUME_GAP_NS - ); - // Short 1s stall stays quiet with no trip. - assert!(!gap_is_resume(delta_clamp(now, now - 1_000_000_000))); - // Zero plus future start fold to zero with no trip. - assert_eq!(delta_clamp(now, 0), 0); - assert!(!gap_is_resume(delta_clamp(now, 0))); - assert_eq!(delta_clamp(now, now + 1_000), 0); - assert!(!gap_is_resume(delta_clamp(now, now + 1_000))); - } - - #[test] - /// Preempt needs lat arrival against batch owner only. - fn preempt_needs_lat_to_batch_only() { - // Arrival 1ms leads occupant 2ms with margin plus tail held. - assert!(preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 1_000_000, true, false - )); - // Lat to lat plus batch to batch plus batch to lat fail closed. - assert!(!preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 1_000_000, true, true - )); - assert!(!preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 1_000_000, false, false - )); - assert!(!preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 1_000_000, false, true - )); - // Near tie within 100us margin never bounces. - assert!(!preempt_ok( - 1_950_000, 2_000_000, 500_000, 500_000, 1_000_000, true, false - )); - // Nearly done owner with tail left fails closed. - assert!(!preempt_ok( - 1_000_000, 2_000_000, 1_450_000, 500_000, 1_000_000, true, false - )); - // Zero cur inherits quantum, so the same lead still wins. - assert!(preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 0, true, false - )); - // Short 50us cur leaves no tail, so the kick fails closed. - assert!(!preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 50_000, true, false - )); - } - - #[test] - /// Miss plus skip plus period stay fixed without drift. - fn miss_skip_period_are_intentional() { - // Misses stay lifetime: newcomers with no history stay batch. - assert!(!is_lat(0, 0, 0, 0, 0, 0)); - // Skips count every hold: lat to lat fails closed. - assert!(!preempt_ok( - 1_000_000, 2_000_000, 500_000, 500_000, 1_000_000, true, true - )); - // Period caps in-tier keys at now plus one period. - assert_eq!(PERIOD_NS, 80_000_000); - assert_eq!(PERIOD_NS, 4 * SLICE_MAX_NS); - const _: () = assert!(D_LAT_NS < PERIOD_NS); - } - - #[test] - /// Tier ceilings map predicted bursts without a divide. - fn classify_tier_matches_intf_h() { - const _: () = assert!(SLICE_ULL_NS < SLICE_MLL_NS); - const _: () = assert!(SLICE_MLL_NS < SLICE_NL_NS); - const _: () = assert!(SLICE_NL_NS < SLICE_ENL_NS); - const _: () = assert!(SLICE_ENL_NS < SLICE_MAX_NS); - assert_eq!(SLICE_ULL_NS, 50_000); - assert_eq!(SLICE_LL_NS, 100_000); - assert_eq!(SLICE_MLL_NS, 500_000); - assert_eq!(SLICE_NL_NS, 1_000_000); - assert_eq!(SLICE_ENL_NS, 5_000_000); - assert_eq!(SLICE_MAX_NS, 20_000_000); - // Critical forces ULL even past the ceiling. - assert_eq!(classify_tier(20_000_000, 0, true), 50_000); - // Prediction at or below 50us earns ULL with half dev margin. - assert_eq!(classify_tier(30_000, 10_000, false), 50_000); - assert_eq!(classify_tier(50_000, 0, false), 50_000); - // 100us plus 500us plus 1ms plus 5ms bound LL plus MLL plus NL plus ENL. - assert_eq!(classify_tier(60_000, 10_000, false), 100_000); - assert_eq!(classify_tier(300_000, 100_000, false), 500_000); - assert_eq!(classify_tier(600_000, 100_000, false), 1_000_000); - assert_eq!(classify_tier(3_000_000, 1_000_000, false), 5_000_000); - // Past 5ms holds the 20ms ceiling with saturation. - assert_eq!(classify_tier(6_000_000, 0, false), 20_000_000); - assert_eq!(classify_tier(u64::MAX - 10, 20, false), 20_000_000); - // Headers agree on every bound. - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_ULL_NS, SLICE_ULL_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_SLICE_MAX_NS, SLICE_MAX_NS); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_PERIOD_NS, PERIOD_NS); - // Fresh waits cap the tier at 1ms, so bulk still rotates. - let bulk = classify_tier(6_000_000, 0, false); - assert_eq!(bulk, SLICE_MAX_NS as u32); - assert_eq!(bulk.min(QUANTUM_NS as u32), QUANTUM_NS as u32); - let audio = classify_tier(30_000, 10_000, false); - assert_eq!(audio, SLICE_ULL_NS as u32); - assert!(audio < QUANTUM_NS as u32); - } - - #[test] - /// Task stays at 72B with stats at 136B plus fixed RED. - fn abi_sizes_stay_pinned() { - assert_eq!(std::mem::size_of::(), 72); - assert_eq!( - std::mem::size_of::(), - 136 - ); - assert_eq!(RED_EMAX_NS, 256_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_RED_EMAX_NS, RED_EMAX_NS); - assert_eq!(RED_TOL_NS, 64_000); - assert_eq!(crate::bpf_intf::flow_consts_FLOW_RED_TOL_NS, RED_TOL_NS); - } - - #[test] - /// Fixed RED keeps 64us tolerance plus 256us Emax. - #[allow(clippy::assertions_on_constants)] - fn fixed_red_matches_intf_h() { - assert_eq!(RED_TOL_NS, 64_000); - assert_eq!(RED_EMAX_NS, 256_000); - } -} diff --git a/scheds/experimental/scx_flow/src/rust/snapshot.rs b/scheds/experimental/scx_flow/src/rust/snapshot.rs deleted file mode 100644 index f95a81e590..0000000000 --- a/scheds/experimental/scx_flow/src/rust/snapshot.rs +++ /dev/null @@ -1,220 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -//! Snapshot reads for the flow scheduler. -//! -//! Copyright (c) 2026 Galih Tama - -//! Builds the counters view plus the dashboard view from the BPF maps. -//! Each poll reads the per CPU stats rows plus the per CPU pid view -//! with no extra sysfs use, so the page stays cheap beside the slice. -//! A dashboard poll costs 3N BPF map reads for N online CPUs: N for -//! the stats sum plus N for the on CPU gauge plus N for the per CPU -//! cards, with one alloc and no sysfs on poll. - -use std::mem::MaybeUninit; -use std::os::fd::AsFd; -use std::os::fd::AsRawFd; - -use crate::Scheduler; -use crate::stats; - -impl<'a> Scheduler<'a> { - /// Count live pids for the on CPU gauge with no BPF counter. - /// Walks the cached online list with one map read per CPU, so the - /// gauge costs N reads with no atomic cost on the hot paths. The - /// BPF on CPU field stays zero for wire compat and never drives - /// this count. - pub(crate) fn count_on_cpu(&self) -> u64 { - let mut live = 0u64; - for &id in self.online_cpus.iter() { - let st = self.read_cpu(id as usize); - if st.running_pid != 0 { - live = live.saturating_add(1); - } - } - live - } - - pub(crate) fn get_metrics(&self) -> stats::Metrics { - let mut total_runtime = 0u64; - let mut inserts = 0u64; - let mut requeues = 0u64; - let mut completions = 0u64; - let mut local_moves = 0u64; - let mut node_moves = 0u64; - let mut machine_moves = 0u64; - let mut kicks = 0u64; - let mut admits = 0u64; - let mut misses = 0u64; - let mut gate_rejects = 0u64; - let mut preempt_kicks = 0u64; - let mut preempt_skipped = 0u64; - let mut red_rejects = 0u64; - let mut red_reclaims = 0u64; - for &id in self.online_cpus.iter() { - let s = self.read_stats(id as usize); - total_runtime = total_runtime.saturating_add(s.total_runtime); - inserts = inserts.saturating_add(s.inserts); - requeues = requeues.saturating_add(s.requeues); - completions = completions.saturating_add(s.completions); - local_moves = local_moves.saturating_add(s.local_moves); - node_moves = node_moves.saturating_add(s.node_moves); - machine_moves = machine_moves.saturating_add(s.machine_moves); - kicks = kicks.saturating_add(s.kicks); - admits = admits.saturating_add(s.admits); - misses = misses.saturating_add(s.misses); - gate_rejects = gate_rejects.saturating_add(s.gate_rejects); - preempt_kicks = preempt_kicks.saturating_add(s.preempt_kicks); - preempt_skipped = preempt_skipped.saturating_add(s.preempt_skipped); - red_rejects = red_rejects.saturating_add(s.red_rejects); - red_reclaims = red_reclaims.saturating_add(s.red_reclaims); - } - stats::Metrics { - on_cpu: self.count_on_cpu(), - total_runtime, - uptime_ns: self.started_at.elapsed().as_nanos().min(u64::MAX as u128) as u64, - inserts, - requeues, - completions, - local_moves, - node_moves, - machine_moves, - kicks, - admits, - // Dead compat: rejects stays zero with no BPF writer for wire - // compat only; readers must use gate_rejects for drops. - rejects: 0, - misses, - gate_rejects, - preempt_kicks, - preempt_skipped, - red_rejects, - red_reclaims, - } - } - - /// Read one per CPU stats row without heap use. - /// Failed lookups yield a zero row with no trap. - pub(crate) fn read_stats(&self, cpu: usize) -> crate::bpf_intf::flow_sched_stats { - let zero = crate::bpf_intf::flow_sched_stats { - on_cpu: 0, - total_runtime: 0, - inserts: 0, - requeues: 0, - completions: 0, - local_moves: 0, - node_moves: 0, - machine_moves: 0, - kicks: 0, - admits: 0, - rejects: 0, - misses: 0, - gate_rejects: 0, - preempt_kicks: 0, - preempt_skipped: 0, - red_rejects: 0, - red_reclaims: 0, - }; - if cpu >= crate::bpf_intf::flow_consts_FLOW_MAX_CPUS as usize { - return zero; - } - let fd = self.skel.maps.cpu_stats_stor.as_fd().as_raw_fd(); - let key = cpu as u32; - let mut out = MaybeUninit::::zeroed(); - let ret = unsafe { - libbpf_rs::libbpf_sys::bpf_map_lookup_elem( - fd, - &key as *const _ as *const std::ffi::c_void, - out.as_mut_ptr() as *mut std::ffi::c_void, - ) - }; - if ret == 0 { - unsafe { out.assume_init() } - } else { - zero - } - } - - /// Read one CPU pid view without heap use. - /// Failed lookups yield an idle view with zero pid. - pub(crate) fn read_cpu(&self, cpu: usize) -> crate::bpf_intf::flow_cpu_state { - let idle = crate::bpf_intf::flow_cpu_state { - running_pid: 0, - cursor: 0, - min_vruntime: 0, - }; - if cpu >= crate::bpf_intf::flow_consts_FLOW_MAX_CPUS as usize { - return idle; - } - let fd = self.skel.maps.cpu_state_stor.as_fd().as_raw_fd(); - let key = cpu as u32; - let mut out = MaybeUninit::::zeroed(); - let ret = unsafe { - libbpf_rs::libbpf_sys::bpf_map_lookup_elem( - fd, - &key as *const _ as *const std::ffi::c_void, - out.as_mut_ptr() as *mut std::ffi::c_void, - ) - }; - if ret == 0 { - unsafe { out.assume_init() } - } else { - idle - } - } - - /// Dashboard snapshot with raw counters plus live pid cards. - /// Counters stay raw with no deltas and the on CPU gauge counts live - /// pids with the pid view. Costs 3N map reads for N online CPUs: N - /// for the stats sum via get_metrics plus N for the gauge plus N for - /// the cards, with one alloc sized to the online count. SMT comes - /// from the cached init flags with no sysfs use on poll and stays - /// display only. Offline stays out, so per CPU count matches the - /// cached online count. Version plus timestamp plus topology join the - /// counters for the page plus the log. - pub(crate) fn get_web_metrics(&self) -> stats::WebMetrics { - let mut per_cpu = Vec::with_capacity(self.online_cpus.len()); - for (rank, &id) in self.online_cpus.iter().enumerate() { - let st = self.read_cpu(id as usize); - let smt = self.smt.get(rank).copied().unwrap_or(false); - per_cpu.push(stats::PerCpuMetrics { - id, - smt, - running_pid: st.running_pid, - slice_ns: crate::config::QUANTUM_NS, - }); - } - let timestamp_ns = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|v| v.as_nanos().min(u64::MAX as u128) as u64) - .unwrap_or(0); - let metrics = self.get_metrics(); - stats::WebMetrics { - stats: metrics, - per_cpu, - version: env!("CARGO_PKG_VERSION").to_string(), - timestamp_ns, - topology: self.topology.clone(), - } - } -} - -#[cfg(test)] -mod tests { - /// Poll cost in BPF map reads for N online CPUs. - /// Dashboard polls read N for the stats sum via get_metrics plus N - /// for the on CPU gauge plus N for the per CPU cards, so the total - /// stays 3N with one alloc and no sysfs on poll. - fn snapshot_reads(n: usize) -> usize { - n.saturating_mul(3) - } - - #[test] - fn poll_cost_is_three_n() { - assert_eq!(snapshot_reads(0), 0); - assert_eq!(snapshot_reads(1), 3); - assert_eq!(snapshot_reads(4), 12); - // One alloc holds N cards with no extra walk. - let per_cpu = Vec::::with_capacity(4); - assert!(per_cpu.capacity() >= 4); - } -} diff --git a/scheds/experimental/scx_flow/src/rust/stats.rs b/scheds/experimental/scx_flow/src/rust/stats.rs deleted file mode 100644 index f159828ae3..0000000000 --- a/scheds/experimental/scx_flow/src/rust/stats.rs +++ /dev/null @@ -1,218 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -//! Stats server for the flow scheduler. -//! -//! Copyright (c) 2026 Galih Tama - -//! Exports the counters view plus the dashboard view from the BPF maps. -//! The stats server carries deltas while the dashboard carries raw -//! counters plus per CPU cards for the loopback page. - -use std::io::Write; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::time::Duration; - -use anyhow::Result; -use scx_stats::prelude::*; -use scx_stats_derive::Stats; -use scx_stats_derive::stat_doc; -use serde::Deserialize; -use serde::Serialize; - -#[stat_doc] -#[derive(Clone, Debug, Default, Serialize, Deserialize, Stats)] -#[stat(top)] -/// Counters with placement, admission, and miss detail. -/// BPF holds 17 counters, Rust adds display-only uptime for eighteen. -pub struct Metrics { - #[stat(desc = "Tasks now on a CPU")] - #[serde(default)] - pub on_cpu: u64, - #[stat(desc = "Total runtime in nanoseconds")] - #[serde(default)] - pub total_runtime: u64, - /// Display-only uptime since attach in nanos with no BPF use. - /// Filled from the start instant, never from the BPF counters. - #[stat(desc = "Uptime since attach in nanoseconds")] - #[serde(default)] - pub uptime_ns: u64, - #[stat(desc = "Fresh deadline joins")] - #[serde(default)] - pub inserts: u64, - #[stat(desc = "Runnable slice ends with requeue")] - #[serde(default)] - pub requeues: u64, - #[stat(desc = "Blocks and exits")] - #[serde(default)] - pub completions: u64, - #[stat(desc = "Moves from the local tier")] - #[serde(default)] - pub local_moves: u64, - #[stat(desc = "Moves from the node tier")] - #[serde(default)] - pub node_moves: u64, - #[stat(desc = "Moves from the machine tier")] - #[serde(default)] - pub machine_moves: u64, - #[stat(desc = "Idle wakeup kicks sent after insert")] - #[serde(default)] - pub kicks: u64, - #[stat(desc = "Tasks admitted with no bound")] - #[serde(default)] - pub admits: u64, - #[stat( - desc = "Rejects dead at zero whitelisted for wire compat with no writer; real rejects count in gate_rejects" - )] - #[serde(default)] - pub rejects: u64, - #[stat(desc = "Wall completions past deadline")] - #[serde(default)] - pub misses: u64, - #[stat(desc = "Closed gate rejects on stale CPUs plus tasks")] - #[serde(default)] - pub gate_rejects: u64, - #[stat(desc = "Busy preempts sent with margin plus tail")] - #[serde(default)] - pub preempt_kicks: u64, - #[stat(desc = "Preempts held by margin plus tail plus eligibility")] - #[serde(default)] - pub preempt_skipped: u64, - #[stat(desc = "RED overload rejects to the value ordered queue")] - #[serde(default)] - pub red_rejects: u64, - #[stat(desc = "RED reclaims from the value ordered queue")] - #[serde(default)] - pub red_reclaims: u64, -} - -/// One card of the per CPU grid. -/// Id plus SMT stay fixed while pid plus slice refresh on each poll. -/// Pid holds zero when idle and slice holds the shared quantum. -/// SMT marks the second thread of one core for display only with -/// no placement use and false on old JSON. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub struct PerCpuMetrics { - /// CPU id. - #[serde(default)] - pub id: u32, - /// True for the second thread of one core with false on single thread. - /// Display only with no placement use plus false on old JSON. - #[serde(default)] - pub smt: bool, - /// Pid now on the CPU with zero when idle. - #[serde(default)] - pub running_pid: u32, - /// Fixed slice in nanos with the shared quantum. - #[serde(default)] - pub slice_ns: u64, -} - -/// Snapshot for the web dashboard. -/// Counters stay raw with the on CPU gauge plus the live pid view. -/// The run loop pushes one per poll and the web thread keeps the -/// newest behind a lock for the page plus the JSON routes. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub struct WebMetrics { - /// Scheduler wide counters with raw values. - pub stats: Metrics, - /// One entry per online CPU in rank order. - #[serde(default)] - pub per_cpu: Vec, - /// Scheduler version for the page plus the log. - #[serde(default)] - pub version: String, - /// Wall time in nanos since epoch for the log. - #[serde(default)] - pub timestamp_ns: u64, - /// One line topology summary for the page. - #[serde(default)] - pub topology: String, -} - -/// Stats printer loop for the monitor flag. -/// Polls the stats server on the interval with plain text lines. -pub fn monitor(intv: Duration, shutdown: Arc) -> Result<()> { - scx_utils::monitor_stats::( - &[], - intv, - || shutdown.load(Ordering::Relaxed), - |metrics| metrics.format(&mut std::io::stdout()), - ) -} - -/// Server data for the stats server. -/// A single top op reports interval deltas of the counters. -pub fn server_data() -> StatsServerData<(), Metrics> { - let open: Box> = Box::new(move |(req_ch, res_ch)| { - req_ch.send(())?; - let mut prev = res_ch.recv()?; - let read: Box> = Box::new(move |_args, (req_ch, res_ch)| { - req_ch.send(())?; - let cur = res_ch.recv()?; - let delta = cur.delta(&prev); - prev = cur; - delta.to_json() - }); - Ok(read) - }); - StatsServerData::new() - .add_meta(Metrics::meta()) - .add_ops("top", StatsOps { open, close: None }) -} - -impl Metrics { - fn format(&self, w: &mut W) -> Result<()> { - writeln!( - w, - "[{}] run={} runtime_ns={} uptime_ns={} ins={} req={} done={} \ - local={} node={} machine={} kick={} adm={} rej={} \ - miss={} gate={} pkick={} pskip={} redrej={} redrec={}", - crate::SCHEDULER_NAME, - self.on_cpu, - self.total_runtime, - self.uptime_ns, - self.inserts, - self.requeues, - self.completions, - self.local_moves, - self.node_moves, - self.machine_moves, - self.kicks, - self.admits, - self.rejects, - self.misses, - self.gate_rejects, - self.preempt_kicks, - self.preempt_skipped, - self.red_rejects, - self.red_reclaims, - )?; - Ok(()) - } - - /// Interval delta of the counters over the poll interval. - /// Gauges like on_cpu plus uptime_ns pass through as live values. - pub fn delta(&self, rhs: &Self) -> Self { - Self { - on_cpu: self.on_cpu, - total_runtime: self.total_runtime.wrapping_sub(rhs.total_runtime), - uptime_ns: self.uptime_ns, - inserts: self.inserts.wrapping_sub(rhs.inserts), - requeues: self.requeues.wrapping_sub(rhs.requeues), - completions: self.completions.wrapping_sub(rhs.completions), - local_moves: self.local_moves.wrapping_sub(rhs.local_moves), - node_moves: self.node_moves.wrapping_sub(rhs.node_moves), - machine_moves: self.machine_moves.wrapping_sub(rhs.machine_moves), - kicks: self.kicks.wrapping_sub(rhs.kicks), - admits: self.admits.wrapping_sub(rhs.admits), - rejects: self.rejects.wrapping_sub(rhs.rejects), - misses: self.misses.wrapping_sub(rhs.misses), - gate_rejects: self.gate_rejects.wrapping_sub(rhs.gate_rejects), - preempt_kicks: self.preempt_kicks.wrapping_sub(rhs.preempt_kicks), - preempt_skipped: self.preempt_skipped.wrapping_sub(rhs.preempt_skipped), - red_rejects: self.red_rejects.wrapping_sub(rhs.red_rejects), - red_reclaims: self.red_reclaims.wrapping_sub(rhs.red_reclaims), - } - } -} diff --git a/scheds/experimental/scx_flow/src/rust/topology.rs b/scheds/experimental/scx_flow/src/rust/topology.rs deleted file mode 100644 index 37e9f45780..0000000000 --- a/scheds/experimental/scx_flow/src/rust/topology.rs +++ /dev/null @@ -1,334 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -//! Topology view for the flow scheduler. -//! -//! Copyright (c) 2026 Galih Tama - -//! Delegates host discovery to scx_utils::Topology with a sysfs -//! fallback, then seeds the BPF view in two best-effort phases. -//! Phase one writes the primary rows with sibling plus node, and phase -//! two refreshes the LLC bitmaps for the start log. Either phase keeps -//! the BPF defaults on fault with no trap and no hot-path use. -//! Sibling assumes two-way SMT as in sibling_cpus, so a third thread -//! stays single with all ones. Span holds online CPUs at init, so the -//! seed matches the sysfs online list with no hotplug use. - -use scx_utils::Topology; - -/// CPU ids past this bound never seed, mirroring FLOW_MAX_CPUS. -const CPU_BOUND: u32 = 1024; - -/// Node ids past this bound fold to zero, mirroring FLOW_MAX_NODES. -const NODE_BOUND: u32 = 16; - -/// One topology row per CPU with sibling plus node. -/// Sibling comes from the core view with all ones on fault, and node -/// folds to zero on fault with a cap at sixteen. A Topology failure -/// falls back to the sysfs lists with the same shape and no panic. -pub fn topo_rows() -> Vec<(u32, u32, u32)> { - init_topology() -} - -/// Build the seeded rows from the shared Topology view. -/// Uses scx_utils::Topology as the source of truth with a sysfs -/// fallback on fault, so large hosts fold to the machine queue with -/// no panic and no extra scan on the hot paths. Span equals the online -/// list at construction, sorted in rank order with the CPU plus node -/// bounds, so the seed matches sysfs online with no extra view. Sibling -/// follows sibling_cpus with two-way assumed, so extra threads on wider -/// cores stay single with no extra scan. -pub fn init_topology() -> Vec<(u32, u32, u32)> { - if let Ok(topo) = Topology::new() { - let sibs = topo.sibling_cpus(); - let mut rows = Vec::new(); - let mut online: Vec = topo.span.iter().map(|c| c as u32).collect(); - online.sort_unstable(); - for cpu in online { - if cpu >= CPU_BOUND { - continue; - } - let sib = sibs - .get(cpu as usize) - .copied() - .filter(|s| *s >= 0) - .map(|s| s as u32) - .filter(|s| *s != cpu) - .unwrap_or(u32::MAX); - let node = topo - .all_cpus - .get(&(cpu as usize)) - .map(|c| c.node_id as u32) - .unwrap_or(0); - let node = if node < NODE_BOUND { node } else { 0 }; - rows.push((cpu, sib, node)); - } - if !rows.is_empty() { - return rows; - } - } - fallback_rows() -} - -/// True when two topology snapshots hold the same rows. -/// Compares in rank order with no sort, so the caller keeps the seeded -/// order while a reorder still counts as changed with one reseed. -pub fn topo_rows_equal(a: &[(u32, u32, u32)], b: &[(u32, u32, u32)]) -> bool { - a == b -} - -/// Fresh rows when the host view changed since the seed, else None. -/// Refreshes through the shared discovery path with the same bounds, -/// so a resume that offlines CPUs reseeds with no hotplug use. -/// Updates the held snapshot on change, so the caller seeds the BPF -/// view once per change with no extra poll. -pub fn reseed_if_changed(prev: &mut Vec<(u32, u32, u32)>) -> Option> { - let next = topo_rows(); - if topo_rows_equal(prev, &next) { - return None; - } - *prev = next.clone(); - Some(next) -} - -/// Primary bitmap text for the start log in rank order. -/// Best effort with empty on fault, so a failed read never traps. -pub fn write_primary_bitmap(rows: &[(u32, u32, u32)]) -> String { - let mut ids: Vec = rows.iter().map(|(cpu, _, _)| *cpu).collect(); - ids.sort_unstable(); - ids.iter() - .map(|c| c.to_string()) - .collect::>() - .join(",") -} - -/// LLC bitmap texts for the start log, one entry per LLC. -/// Best effort with empty on fault, so hosts without an LLC view log -/// no bitmap with no trap and no hot-path use. -pub fn write_llc_bitmaps() -> Vec { - let topo = match Topology::new() { - Ok(t) => t, - Err(_) => return Vec::new(), - }; - let mut out = Vec::new(); - for llc in topo.all_llcs.values() { - let mut ids: Vec = llc.all_cpus.keys().copied().collect(); - ids.sort_unstable(); - let text = ids - .iter() - .map(|c| c.to_string()) - .collect::>() - .join(","); - out.push(text); - } - out.sort(); - out -} - -/// Short topology line for the start log. -/// Shows cpus seeded with primary plus llcs counts with no hot-path use. -pub fn describe_topology(rows: &[(u32, u32, u32)]) -> String { - let primary = write_primary_bitmap(rows); - let llcs = write_llc_bitmaps(); - if llcs.is_empty() { - format!("cpus={} seeded", rows.len()) - } else { - format!( - "cpus={} seeded primary=[{}] llcs={}", - rows.len(), - primary, - llcs.len() - ) - } -} - -/// True when the CPU is the second thread of one core. -/// Sibling holds all ones on single thread, so single thread stays -/// false with no panic. A lower sibling marks the second thread, so -/// only one card per core shows SMT with no extra sysfs use. Two-way -/// assumed as in sibling_cpus, so a third thread on wider cores stays -/// single by design with no extra kick and no non-x86 walk. -pub fn is_smt_thread(cpu: u32, sib: u32) -> bool { - sib != u32::MAX && sib < cpu -} - -/// Parse a kernel CPU list like 0-3 plus 5 into ids. -/// Ranges clamp to the CPU bound before the walk, so a faulty list -/// never loops the full u32 range. Ids past the bound never seed. -pub fn parse_cpu_list(s: &str) -> Vec { - let mut out = Vec::new(); - for part in s.split(',') { - let part = part.trim(); - if part.is_empty() { - continue; - } - if let Some((a, b)) = part.split_once('-') - && let (Ok(lo), Ok(hi)) = (a.trim().parse::(), b.trim().parse::()) - { - let hi = hi.min(CPU_BOUND - 1); - if lo <= hi { - for cpu in lo..=hi { - out.push(cpu); - } - } - continue; - } - if let Ok(cpu) = part.parse::() - && cpu < CPU_BOUND - { - out.push(cpu); - } - } - out.sort_unstable(); - out.dedup(); - out -} - -/// Read one kernel CPU list file into ids with empty on fault. -pub fn read_cpu_list_file(path: &str) -> Vec { - std::fs::read_to_string(path) - .map(|s| parse_cpu_list(&s)) - .unwrap_or_default() -} - -/// Fallback rows from the sysfs lists with the same shape. -/// Sibling reads the thread list with all ones on fault, and node -/// reads the NUMA view with zero on fault and a cap at sixteen. -fn fallback_rows() -> Vec<(u32, u32, u32)> { - let online = read_cpu_list_file("/sys/devices/system/cpu/online"); - let mut rows = Vec::new(); - for cpu in online { - let sib = thread_sibling(cpu).unwrap_or(u32::MAX); - let node = cpu_node(cpu).unwrap_or(0); - let node = if node < NODE_BOUND { node } else { 0 }; - rows.push((cpu, sib, node)); - } - rows -} - -/// Thread sibling of one CPU with None on fault. -fn thread_sibling(cpu: u32) -> Option { - let path = format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list"); - let ids = read_cpu_list_file(&path); - ids.into_iter().find(|id| *id != cpu) -} - -/// Node of one CPU with None on fault. -/// Reads the NUMA view through the per CPU node links with a fallback -/// to the node cpulists, so package ids never shape placement. -/// A missing link plus a missing cpulist means unknown, so the caller -/// folds to zero with no panic. -fn cpu_node(cpu: u32) -> Option { - let dir = format!("/sys/devices/system/cpu/cpu{cpu}"); - if let Ok(entries) = std::fs::read_dir(&dir) { - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if let Some(suffix) = name.strip_prefix("node") - && !suffix.is_empty() - && let Ok(node) = suffix.parse::() - { - return Some(node); - } - } - } - node_from_cpulists(cpu) -} - -/// Node of one CPU from the node cpulists with None on fault. -/// Scans the online nodes and returns the first node whose cpulist -/// holds the CPU, so hosts without per CPU links still seed. -fn node_from_cpulists(cpu: u32) -> Option { - let ids = read_cpu_list_file("/sys/devices/system/node/online"); - for node in ids { - let path = format!("/sys/devices/system/node/node{node}/cpulist"); - let cpus = read_cpu_list_file(&path); - if cpus.contains(&cpu) { - return Some(node); - } - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_ranges_and_singles() { - assert_eq!(parse_cpu_list("0-3"), vec![0, 1, 2, 3]); - assert_eq!(parse_cpu_list("0-1,3"), vec![0, 1, 3]); - assert_eq!(parse_cpu_list(""), Vec::::new()); - } - - #[test] - fn rows_cap_large_nodes() { - let node = 20u32; - let capped = if node < NODE_BOUND { node } else { 0 }; - assert_eq!(capped, 0); - } - - #[test] - fn clamps_ranges_and_ids_to_cpu_bound() { - let wide = parse_cpu_list("0-1100"); - assert_eq!(wide.len(), 1024); - assert!(wide.iter().all(|c| *c < 1024)); - assert_eq!(parse_cpu_list("1023-1100"), vec![1023]); - assert_eq!(parse_cpu_list("1100"), Vec::::new()); - assert_eq!(parse_cpu_list("1100-1200"), Vec::::new()); - } - - #[test] - fn smt_marks_only_second_thread() { - assert!(!is_smt_thread(0, u32::MAX)); - assert!(!is_smt_thread(0, 1)); - assert!(is_smt_thread(1, 0)); - assert!(!is_smt_thread(4, 5)); - assert!(is_smt_thread(5, 4)); - assert!(!is_smt_thread(7, u32::MAX)); - } - - #[test] - fn primary_bitmap_joins_rank_order() { - let rows = vec![(2, u32::MAX, 0), (0, u32::MAX, 0), (1, 0, 0)]; - assert_eq!(write_primary_bitmap(&rows), "0,1,2"); - assert_eq!(write_primary_bitmap(&[]), ""); - } - - #[test] - fn init_topology_rows_stay_in_bounds() { - let rows = init_topology(); - assert_eq!(topo_rows(), rows); - assert!( - rows.iter() - .all(|(c, _, n)| *c < CPU_BOUND && *n < NODE_BOUND) - ); - let mut ids: Vec = rows.iter().map(|(c, _, _)| *c).collect(); - ids.sort_unstable(); - ids.dedup(); - assert_eq!(ids.len(), rows.len()); - } - - #[test] - fn equal_rows_match_in_rank_order() { - let a = vec![(0, u32::MAX, 0), (1, 0, 0)]; - assert!(topo_rows_equal(&a, &a.clone())); - assert!(topo_rows_equal(&[], &[])); - assert!(!topo_rows_equal(&a, &[(0, u32::MAX, 0)])); - assert!(!topo_rows_equal(&a, &[(1, 0, 0), (0, u32::MAX, 0)])); - assert!(!topo_rows_equal(&a, &[(0, u32::MAX, 1), (1, 0, 0)])); - } - - #[test] - fn reseed_reports_change_once() { - let live = topo_rows(); - let mut prev = live.clone(); - assert!(reseed_if_changed(&mut prev).is_none()); - assert!(topo_rows_equal(&prev, &live)); - let mut empty = Vec::new(); - match reseed_if_changed(&mut empty) { - Some(next) => { - assert_eq!(next, live); - assert_eq!(empty, live); - } - None => assert!(live.is_empty()), - } - } -} diff --git a/scheds/experimental/scx_flow/src/rust/webui.rs b/scheds/experimental/scx_flow/src/rust/webui.rs deleted file mode 100644 index cb3d04ca10..0000000000 --- a/scheds/experimental/scx_flow/src/rust/webui.rs +++ /dev/null @@ -1,473 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -//! Loopback dashboard for the flow scheduler. -//! -//! Copyright (c) 2026 Galih Tama - -//! Serves the embedded page plus the live snapshot as JSON on loopback. -//! Uses tiny_http 0.12 pinned in Cargo.toml with loopback only plus no -//! TLS plus no store. Binds IPv6 loopback first with IPv4 fallback and -//! serves no WAN route, so the page plus JSON never leave the host. - -use std::sync::Arc; -use std::sync::Mutex; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering; -use std::time::Duration; - -use crossbeam::channel::Receiver; -use serde::Serialize; -use serde_json::Value; -use serde_json::json; -use tiny_http::Header; -use tiny_http::Response; -use tiny_http::Server; - -use crate::stats::WebMetrics; - -/* Loopback TCP port of the dashboard. */ -const PORT: u16 = 50005; -/* Poll bound of the snapshot channel. */ -const POLL: Duration = Duration::from_millis(200); -/* JSON content type value. */ -const JSON: &str = "application/json"; -/* HTML content type value. */ -const HTML: &str = "text/html"; - -/* Newest snapshot behind a lock for the handlers. */ -struct WebState { - metrics: WebMetrics, -} - -/* JSON value of a serializable item. */ -fn jv(v: &T) -> Value { - serde_json::to_value(v).unwrap_or_default() -} - -/* JSON text of a value with an empty object on failure. */ -fn jt(v: &Value) -> String { - serde_json::to_string(v).unwrap_or("{}".into()) -} - -/* Merged dashboard object for one snapshot. */ -/* Full log with version plus timestamp plus topology plus stats plus */ -/* per CPU. Same object serves stats polling plus snapshot download on */ -/* loopback with no new exposure. */ -fn merged(snap: &WebMetrics) -> Value { - json!({ - "version": snap.version.clone(), - "timestamp_ns": snap.timestamp_ns, - "topology": snap.topology.clone(), - "stats": jv(&snap.stats), - "per_cpu": jv(&snap.per_cpu), - }) -} - -/* Start the dashboard thread. */ -/* Consumes snapshots plus exits when the shutdown flag is set */ -/* or the channel closes. Serves the page on the root plus the */ -/* same JSON on the stats plus snapshot paths with loopback only */ -/* plus no store plus unknown paths get not found. Binds one */ -/* loopback only with IPv6 first plus IPv4 fallback plus no */ -/* serve when both fail. One thread plus one lock per poll */ -/* stays cheap beside the page poll with no backlog. */ -pub fn start(rx: Receiver, shutdown: Arc) { - log::info!("web thread started"); - let html = include_str!("../../ui/index.html").to_string(); - let state = Arc::new(Mutex::new(WebState { - metrics: WebMetrics::default(), - })); - let keep = state.clone(); - let done = shutdown.clone(); - std::thread::spawn(move || { - while !done.load(Ordering::Relaxed) { - match rx.recv_timeout(POLL) { - Ok(m) => { - if let Ok(mut s) = keep.lock() { - s.metrics = m; - } - } - Err(crossbeam::channel::RecvTimeoutError::Timeout) => {} - Err(_) => break, - } - } - }); - let mut server: Option = None; - let mut addr = String::new(); - if let Ok(s) = Server::http(format!("[::1]:{PORT}")) { - addr = format!("[::1]:{PORT}"); - server = Some(s); - } - if server.is_none() - && let Ok(s) = Server::http(format!("127.0.0.1:{PORT}")) - { - addr = format!("127.0.0.1:{PORT}"); - server = Some(s); - } - let Some(server) = server else { - log::warn!("web TCP blocked with no serve"); - return; - }; - log::info!("web on port {addr}"); - let nocache = Header::from_bytes("Cache-Control", "no-store").unwrap(); - let nosniff = Header::from_bytes("X-Content-Type-Options", "nosniff").unwrap(); - let frame = Header::from_bytes("X-Frame-Options", "DENY").unwrap(); - let htype = Header::from_bytes("Content-Type", HTML).unwrap(); - let jtype = Header::from_bytes("Content-Type", JSON).unwrap(); - while !shutdown.load(Ordering::Relaxed) { - let got = server.recv_timeout(Duration::from_millis(200)); - let req = match got { - Ok(Some(v)) => v, - _ => continue, - }; - let snap = match state.lock() { - Ok(v) => v.metrics.clone(), - Err(_) => continue, - }; - match req.url() { - "/" => { - let resp = Response::from_string(&html); - let resp = resp.with_header(htype.clone()); - let resp = resp.with_header(nocache.clone()); - let resp = resp.with_header(nosniff.clone()); - let resp = resp.with_header(frame.clone()); - let _ = req.respond(resp); - } - "/api/stats" | "/api/snapshot" => { - let txt = jt(&merged(&snap)); - let resp = Response::from_string(txt); - let resp = resp.with_header(jtype.clone()); - let resp = resp.with_header(nocache.clone()); - let resp = resp.with_header(nosniff.clone()); - let resp = resp.with_header(frame.clone()); - let _ = req.respond(resp); - } - _ => { - let resp = Response::empty(404) - .with_header(nocache.clone()) - .with_header(nosniff.clone()) - .with_header(frame.clone()); - let _ = req.respond(resp); - } - } - } - log::info!("web stopped"); -} - -#[cfg(test)] -mod tests { - use super::*; - - /* Merged keeps the five live keys with no stale keys. */ - #[test] - fn merged_keeps_live_keys() { - let snap = WebMetrics::default(); - let v = merged(&snap); - assert!(v.get("stats").is_some()); - assert!(v.get("per_cpu").is_some()); - assert!(v.get("version").is_some()); - assert!(v.get("timestamp_ns").is_some()); - assert!(v.get("topology").is_some()); - assert_eq!(v.as_object().map(|o| o.len()), Some(5)); - assert!(v.get("governor").is_none()); - assert!(v.get("energy").is_none()); - assert!(v.get("ml_accuracy").is_none()); - assert!(v.get("ml_hits").is_none()); - } - - /* Old snapshots without new fields still decode. */ - #[test] - fn web_metrics_missing_fields_default() { - let txt = "{\"stats\":{\"on_cpu\":1},\"version\":\"4.7.0\"}"; - let m: WebMetrics = serde_json::from_str(txt).unwrap(); - assert_eq!(m.stats.on_cpu, 1); - assert_eq!(m.stats.local_moves, 0); - assert_eq!(m.stats.gate_rejects, 0); - assert_eq!(m.stats.preempt_kicks, 0); - assert_eq!(m.stats.preempt_skipped, 0); - assert_eq!(m.stats.red_rejects, 0); - assert_eq!(m.stats.red_reclaims, 0); - assert!(m.per_cpu.is_empty()); - assert_eq!(m.version, "4.7.0"); - assert_eq!(m.timestamp_ns, 0); - assert_eq!(m.topology, ""); - let old = "{\"id\":1,\"running_pid\":5,\"slice_ns\":2000000}"; - let card: crate::stats::PerCpuMetrics = serde_json::from_str(old).unwrap(); - assert_eq!(card.id, 1); - assert!(!card.smt); - assert_eq!(card.running_pid, 5); - let v = merged(&m); - assert_eq!(v.as_object().map(|o| o.len()), Some(5)); - let back: WebMetrics = serde_json::from_value(v).unwrap(); - assert_eq!(back.stats.on_cpu, 1); - assert_eq!(back.version, "4.7.0"); - } - - /* Full snapshot round trips through JSON with live counters. */ - #[test] - fn web_metrics_round_trip() { - let snap = WebMetrics { - stats: crate::stats::Metrics { - on_cpu: 2, - total_runtime: 1_000_000, - uptime_ns: 2_000_000, - inserts: 3, - requeues: 1, - completions: 2, - local_moves: 10, - node_moves: 4, - machine_moves: 2, - kicks: 5, - admits: 3, - rejects: 1, - misses: 2, - gate_rejects: 0, - preempt_kicks: 1, - preempt_skipped: 2, - red_rejects: 1, - red_reclaims: 1, - }, - per_cpu: vec![ - crate::stats::PerCpuMetrics { - id: 0, - smt: false, - running_pid: 7, - slice_ns: 1_000_000, - }, - crate::stats::PerCpuMetrics { - id: 1, - smt: true, - running_pid: 0, - slice_ns: 1_000_000, - }, - ], - version: "4.7.0".to_string(), - timestamp_ns: 1_700_000_000_000_000_000, - topology: "cpus=4 seeded".to_string(), - }; - let txt = serde_json::to_string(&snap).unwrap(); - assert!(txt.contains("local_moves")); - assert!(txt.contains("node_moves")); - assert!(txt.contains("machine_moves")); - assert!(!txt.contains("over_moves")); - assert!(txt.contains("admits")); - assert!(txt.contains("rejects")); - assert!(txt.contains("misses")); - assert!(!txt.contains("\"parks\"")); - assert!(txt.contains("gate_rejects")); - assert!(txt.contains("preempt_kicks")); - assert!(txt.contains("preempt_skipped")); - assert!(txt.contains("red_rejects")); - assert!(txt.contains("red_reclaims")); - assert!(!txt.contains("ml_hits")); - assert!(!txt.contains("ml_accuracy")); - assert!(txt.contains("slice_ns")); - assert!(txt.contains("running_pid")); - assert!(txt.contains("\"smt\":false")); - assert!(txt.contains("\"smt\":true")); - assert!(txt.contains("version")); - assert!(txt.contains("topology")); - assert!(txt.contains("timestamp_ns")); - assert!(!txt.contains("steal_moves")); - assert!(!txt.contains("slot_moves")); - assert!(!txt.contains("throttled_ns")); - assert!(!txt.contains("nr_throttled")); - assert!(!txt.contains("bw_moves")); - assert!(!txt.contains("park_moves")); - assert!(!txt.contains("enq_no_tctx")); - assert!(!txt.contains("freq_khz")); - assert!(!txt.contains("cur_freq")); - assert!(!txt.contains("llc_id")); - assert!(!txt.contains("governor")); - assert!(!txt.contains("energy")); - let back: WebMetrics = serde_json::from_str(&txt).unwrap(); - assert_eq!(back.stats.local_moves, 10); - assert_eq!(back.stats.node_moves, 4); - assert_eq!(back.stats.machine_moves, 2); - assert_eq!(back.stats.admits, 3); - assert_eq!(back.stats.rejects, 1); - assert_eq!(back.stats.misses, 2); - assert_eq!(back.stats.gate_rejects, 0); - assert_eq!(back.stats.preempt_kicks, 1); - assert_eq!(back.stats.preempt_skipped, 2); - assert_eq!(back.stats.red_rejects, 1); - assert_eq!(back.stats.red_reclaims, 1); - assert_eq!(back.per_cpu.len(), 2); - assert!(!back.per_cpu[0].smt); - assert!(back.per_cpu[1].smt); - assert_eq!(back.per_cpu[0].running_pid, 7); - assert_eq!(back.per_cpu[0].slice_ns, 1_000_000); - assert_eq!(back.per_cpu[1].id, 1); - assert_eq!(back.version, "4.7.0"); - assert_eq!(back.topology, "cpus=4 seeded"); - let v = merged(&snap); - assert_eq!(v.as_object().map(|o| o.len()), Some(5)); - assert!(v.get("ml_accuracy").is_none()); - assert!(v.get("governor").is_none()); - assert!(v.get("energy").is_none()); - } - - /* Dashboard keeps live ids without stale cards. */ - #[test] - fn dashboard_keeps_live_layout() { - let html = include_str!("../../ui/index.html"); - assert!(!html.contains("stale-pill")); - assert!(!html.contains("core-stale")); - assert!(html.contains("text-overflow: ellipsis")); - assert!(html.contains("tabular-nums")); - } - - /* Download keeps version plus timestamp in the file name. */ - #[test] - fn dashboard_download_names_versioned_file() { - let html = include_str!("../../ui/index.html"); - assert!(html.contains("downloadSnapshot")); - assert!(html.contains("JSON.stringify(data, null, 2)")); - assert!(html.contains("data.version")); - assert!(html.contains("data.timestamp_ns")); - assert!(html.contains("scx_flow_")); - assert!(html.contains("/api/snapshot")); - } - - /* Dashboard shows the sixteen live counters plus uptime. */ - #[test] - fn dashboard_shows_live_counters() { - let html = include_str!("../../ui/index.html"); - assert!(html.contains("id=\"on-cpu\"")); - assert!(html.contains("id=\"runtime\"")); - assert!(html.contains("id=\"uptime\"")); - assert!(html.contains("id=\"inserts\"")); - assert!(html.contains("id=\"requeues\"")); - assert!(html.contains("id=\"completions\"")); - assert!(html.contains("id=\"local-moves\"")); - assert!(html.contains("id=\"node-moves\"")); - assert!(html.contains("id=\"machine-moves\"")); - assert!(html.contains("id=\"kicks\"")); - assert!(html.contains("id=\"admits\"")); - assert!(html.contains("id=\"rejects\"")); - assert!(html.contains("id=\"misses\"")); - assert!(html.contains("id=\"gate-rejects\"")); - assert!(html.contains("id=\"preempt-kicks\"")); - assert!(html.contains("id=\"preempt-skipped\"")); - assert!(html.contains("id=\"red-rejects\"")); - assert!(html.contains("id=\"red-reclaims\"")); - assert!(!html.contains("id=\"ml-hits\"")); - assert!(!html.contains("id=\"ml-accuracy\"")); - assert!(html.contains("on_cpu")); - assert!(html.contains("total_runtime")); - assert!(html.contains("uptime_ns")); - assert!(html.contains("local_moves")); - assert!(html.contains("node_moves")); - assert!(html.contains("machine_moves")); - assert!(html.contains("gate_rejects")); - assert!(html.contains("preempt_kicks")); - assert!(html.contains("preempt_skipped")); - assert!(html.contains("red_rejects")); - assert!(html.contains("red_reclaims")); - assert!(!html.contains("ml_hits")); - assert!(!html.contains("ml_accuracy")); - assert!(!html.contains("over_moves")); - assert!(!html.contains("over-moves")); - assert!(!html.contains("\"parks\"")); - assert!(!html.contains("id=\"parks\"")); - assert!(!html.contains("global_moves")); - assert!(!html.contains("global-moves")); - } - - /* Dashboard hides stale wire fields plus heavy sections. */ - #[test] - fn dashboard_hides_stale_fields() { - let html = include_str!("../../ui/index.html"); - assert!(!html.contains("steal_moves")); - assert!(!html.contains("slot_moves")); - assert!(!html.contains("throttled_ns")); - assert!(!html.contains("nr_throttled")); - assert!(!html.contains("bw_moves")); - assert!(!html.contains("park_moves")); - assert!(!html.contains("over_moves")); - assert!(!html.contains("over-moves")); - assert!(!html.contains("\"parks\"")); - assert!(!html.contains("id=\"parks\"")); - assert!(!html.contains("enq_no_tctx")); - assert!(!html.contains("freq_khz")); - assert!(!html.contains("cur_freq")); - assert!(!html.contains("llc_id")); - assert!(!html.contains("core-freq")); - assert!(!html.contains("core-llc")); - assert!(!html.contains("governor")); - assert!(!html.contains("energy")); - assert!(!html.contains("id=\"energy-since\"")); - assert!(!html.contains("id=\"mode-badge\"")); - assert!(!html.contains("no-tctx")); - assert!(!html.contains("id=\"steal\"")); - assert!(!html.contains("id=\"throttled-ns\"")); - assert!(!html.contains("ml_hits")); - assert!(!html.contains("ml_accuracy")); - assert!(!html.contains("ml-total")); - } - - /* Dashboard marks the second thread cards with SMT. */ - #[test] - fn dashboard_shows_smt_badge() { - let html = include_str!("../../ui/index.html"); - assert!(html.contains("core-smt")); - assert!(html.contains("smtLabel")); - assert!(html.contains("cpu.smt")); - assert!(html.contains(">SMT<")); - assert!(html.contains("var(--warning)")); - } - - /* Dashboard clamps on CPU plus shows the live pid count. */ - #[test] - fn dashboard_shows_live_pids_cell() { - let html = include_str!("../../ui/index.html"); - assert!(html.contains("id=\"on-cpu\"")); - assert!(html.contains("id=\"running-pids\"")); - assert!(html.contains("livePids")); - assert!(html.contains("shownOnCpu")); - assert!(html.contains("running_pid")); - } - - /* Header capsules plus the per CPU pill center text by height plus width. */ - #[test] - fn dashboard_centers_header_capsules() { - let html = include_str!("../../ui/index.html"); - assert!(html.contains("#status-badge")); - assert!(html.contains("#download")); - assert!(html.contains(".run-badge")); - assert!(html.contains("display: inline-flex")); - assert!(html.contains("align-items: center")); - assert!(html.contains("justify-content: center")); - assert!(html.contains("line-height: 1.4")); - assert!(!html.contains("#mode-badge")); - } - - /* Dashboard polls once per second with no stored history. */ - #[test] - fn dashboard_polls_once_per_second() { - let html = include_str!("../../ui/index.html"); - assert_eq!(html.matches("setInterval").count(), 1); - assert!(!html.contains("localStorage")); - assert!(html.contains("/api/stats")); - assert!(html.contains("slice_ns")); - } - - /* Dashboard shows fixed RED bounds with no ML. */ - #[test] - fn dashboard_shows_fixed_red() { - let html = include_str!("../../ui/index.html"); - assert!(!html.contains("id=\"ml-accuracy\"")); - assert!(!html.contains("ml_accuracy")); - assert!(html.contains("id=\"red-rejects\"")); - assert!(html.contains("id=\"red-reclaims\"")); - assert!(html.contains("RED rejects")); - } - - /* Summary names RED plus tiers in the running line. */ - #[test] - fn dashboard_summary_names_red() { - let html = include_str!("../../ui/index.html"); - assert!(!html.contains("ML accuracy")); - assert!(html.contains("Flow is running")); - assert!(html.contains("RED rejects")); - } -} diff --git a/scheds/experimental/scx_flow/src/stats.rs b/scheds/experimental/scx_flow/src/stats.rs new file mode 100644 index 0000000000..4e4a360110 --- /dev/null +++ b/scheds/experimental/scx_flow/src/stats.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Stats server for the flow scheduler. +//! +//! Copyright (c) 2026 Galih Tama + +//! Exports per LLC counters summed across LLCs. + +use std::io::Write; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use anyhow::Result; +use scx_stats::prelude::*; +use scx_stats_derive::Stats; +use scx_stats_derive::stat_doc; +use serde::Deserialize; +use serde::Serialize; + +#[stat_doc] +#[derive(Clone, Debug, Default, Serialize, Deserialize, Stats)] +#[stat(top)] +/// Per LLC counters for queueing and kicks. +pub struct Metrics { + #[stat(desc = "Tasks now queued in DSQ")] + #[serde(default)] + pub queued: u64, + #[stat(desc = "Tasks moved to local in dispatch")] + #[serde(default)] + pub dispatched: u64, + #[stat(desc = "Fallback inserts and duplicate drops")] + #[serde(default)] + pub fallback: u64, + #[stat(desc = "Remote LLC queue moves in dispatch")] + #[serde(default)] + pub steal: u64, + #[stat(desc = "Duplicate requeues dropped while queued")] + #[serde(default)] + pub fb_duplicate: u64, + #[stat(desc = "Remote moves counted on the thief")] + #[serde(default)] + pub steal_llc: u64, + #[stat(desc = "Preempt kicks on enqueue")] + #[serde(default)] + pub kick_preempt: u64, + #[stat(desc = "Idle kicks on enqueue")] + #[serde(default)] + pub kick_idle: u64, + #[stat(desc = "Skipped enqueue kicks")] + #[serde(default)] + pub kick_skip: u64, + #[stat(desc = "Tasks that burnt the full slice")] + #[serde(default)] + pub overrun: u64, + #[stat(desc = "Stops that leave the task still runnable")] + #[serde(default)] + pub blocked: u64, + #[stat(desc = "Mask change kicks for queued tasks")] + #[serde(default)] + pub orphan_kick: u64, + #[stat(desc = "Forwards where the head cannot run here")] + #[serde(default)] + pub hol_forward: u64, +} + +impl Metrics { + fn format(&self, w: &mut W) -> Result<()> { + writeln!( + w, + "[{}] queued={} dispatched={} fallback={} steal={} fb_duplicate={} steal_llc={} kick_preempt={} kick_idle={} kick_skip={} overrun={} blocked={} orphan_kick={} hol_forward={}", + crate::cli::SCHEDULER_NAME, + self.queued, + self.dispatched, + self.fallback, + self.steal, + self.fb_duplicate, + self.steal_llc, + self.kick_preempt, + self.kick_idle, + self.kick_skip, + self.overrun, + self.blocked, + self.orphan_kick, + self.hol_forward, + )?; + Ok(()) + } + + /// Single LLC row with the same fields plus the LLC index. + /// Keeps struct order with no reorder. + pub fn format_llc(&self, w: &mut W, llc: u32) -> Result<()> { + write!(w, "[{}:llc{}] ", crate::cli::SCHEDULER_NAME, llc)?; + self.format(w) + } + + /// Interval delta. Queued passes through as a live gauge. + pub fn delta(&self, rhs: &Self) -> Self { + Self { + queued: self.queued, + dispatched: self.dispatched.wrapping_sub(rhs.dispatched), + fallback: self.fallback.wrapping_sub(rhs.fallback), + steal: self.steal.wrapping_sub(rhs.steal), + fb_duplicate: self.fb_duplicate.wrapping_sub(rhs.fb_duplicate), + steal_llc: self.steal_llc.wrapping_sub(rhs.steal_llc), + kick_preempt: self.kick_preempt.wrapping_sub(rhs.kick_preempt), + kick_idle: self.kick_idle.wrapping_sub(rhs.kick_idle), + kick_skip: self.kick_skip.wrapping_sub(rhs.kick_skip), + overrun: self.overrun.wrapping_sub(rhs.overrun), + blocked: self.blocked.wrapping_sub(rhs.blocked), + orphan_kick: self.orphan_kick.wrapping_sub(rhs.orphan_kick), + hol_forward: self.hol_forward.wrapping_sub(rhs.hol_forward), + } + } +} + +/// Stats printer loop for the monitor flag. +pub fn monitor(intv: Duration, shutdown: Arc) -> Result<()> { + scx_utils::monitor_stats::( + &[], + intv, + || shutdown.load(Ordering::Relaxed), + |metrics| metrics.format(&mut std::io::stdout()), + ) +} + +/// Server data for the stats server. +pub fn server_data() -> StatsServerData<(), Metrics> { + let open_top: Box> = Box::new(move |(req_ch, res_ch)| { + req_ch.send(())?; + let cur: Metrics = res_ch.recv()?; + let mut prev: Metrics = cur.clone(); + let read: Box> = Box::new(move |_args, (req_ch, res_ch)| { + req_ch.send(())?; + let cur: Metrics = res_ch.recv()?; + let delta = cur.delta(&prev); + prev = cur.clone(); + delta.to_json() + }); + Ok(read) + }); + StatsServerData::new().add_meta(Metrics::meta()).add_ops( + "top", + StatsOps { + open: open_top, + close: None, + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::metrics::fold_llc_val; + + #[test] + fn delta_keeps_gauge_and_wraps() { + let mut cur = Metrics::default(); + let mut prev = Metrics::default(); + cur.queued = 3; + prev.queued = 7; + cur.dispatched = 5; + prev.dispatched = 3; + cur.hol_forward = 1; + prev.hol_forward = 2; + let d = cur.delta(&prev); + assert_eq!(d.queued, 3); + assert_eq!(d.dispatched, 2); + assert_eq!(d.hol_forward, 1u64.wrapping_sub(2)); + } + + #[test] + fn fold_len_guards_keep_tails() { + let mut short = Metrics::default(); + let tiny = [0u8; 16]; + fold_llc_val(&mut short, &tiny); + assert_eq!(short.queued, 0); + assert_eq!(short.hol_forward, 0); + + let mut half = Metrics::default(); + let mut buf48 = [0u8; 48]; + buf48[40..48].copy_from_slice(&7u64.to_ne_bytes()); + fold_llc_val(&mut half, &buf48); + assert_eq!(half.steal_llc, 7); + assert_eq!(half.hol_forward, 0); + + let mut full = Metrics::default(); + let mut buf104 = [0u8; 104]; + buf104[0..8].copy_from_slice(&1u64.to_ne_bytes()); + buf104[96..104].copy_from_slice(&9u64.to_ne_bytes()); + fold_llc_val(&mut full, &buf104); + assert_eq!(full.queued, 1); + assert_eq!(full.hol_forward, 9); + + let mut over = Metrics::default(); + let mut buf112 = [0u8; 112]; + buf112[96..104].copy_from_slice(&4u64.to_ne_bytes()); + fold_llc_val(&mut over, &buf112); + assert_eq!(over.hol_forward, 4); + } +} diff --git a/scheds/experimental/scx_flow/src/topology.rs b/scheds/experimental/scx_flow/src/topology.rs new file mode 100644 index 0000000000..3b37b03b1f --- /dev/null +++ b/scheds/experimental/scx_flow/src/topology.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Topology seeding for the flow scheduler. +//! +//! Copyright (c) 2026 Galih Tama + +//! Seeds cluster hints for the BPF view. Cache and node identity +//! come from the upstream topology tree built by the arena library. + +use std::collections::BTreeMap; +use std::collections::BTreeSet; + +use anyhow::Context; +use anyhow::Result; +use scx_utils::Topology; + +use crate::BpfSkel; + +/// Cores grouped per cluster. Fixed width keeps the seed stable. +/// Width four is a heuristic: real clusters of eight split in two, +/// which keeps locality without ever merging distant cores. The +/// topology view has no cluster id, so the seed sorts cores by id +/// within each LLC and splits every four for a stable map. +const GROUP_WIDTH: usize = 4; + +/// True when any core holds more than one CPU. +pub fn smt_on(topo: &Topology) -> bool { + topo.all_cores.values().any(|c| c.cpus.len() > 1) +} + +/// Detect SMT from a fresh discovery. Errors return to the caller. +pub fn detect_smt() -> Result { + let topo = Topology::new().context("topology discovery")?; + Ok(smt_on(&topo)) +} + +/// Index of a core position inside its LLC group. +fn chunk_index(pos: usize) -> usize { + pos / GROUP_WIDTH +} + +/// Map each CPU to a cluster id inside its LLC. +/// Cores sort by id within each LLC and split every four. +/// Ids count up across LLCs in LLC order. Splits stay safe: a +/// larger cluster becomes two neighbors, never a distant merge. +fn cpu_ccx(topo: &Topology, llc_ids: &[usize]) -> BTreeMap { + let mut cores_per_llc: BTreeMap> = BTreeMap::new(); + for cpu in topo.all_cpus.values() { + let idx = llc_ids.iter().position(|v| *v == cpu.llc_id).unwrap_or(0); + cores_per_llc.entry(idx).or_default().insert(cpu.core_id); + } + let mut core_ccx: BTreeMap<(usize, usize), u32> = BTreeMap::new(); + let mut next: u32 = 0; + let mut ordered: Vec = cores_per_llc.keys().copied().collect(); + ordered.sort_unstable(); + for idx in ordered { + let cores: Vec = cores_per_llc + .get(&idx) + .map(|s| s.iter().copied().collect()) + .unwrap_or_default(); + let mut sorted = cores; + sorted.sort_unstable(); + let mut last_chunk: Option = None; + for (pos, core) in sorted.into_iter().enumerate() { + let chunk = chunk_index(pos); + if last_chunk != Some(chunk) { + if pos != 0 { + next = next.wrapping_add(1); + } + last_chunk = Some(chunk); + } + core_ccx.insert((idx, core), next); + } + next = next.wrapping_add(1); + } + let mut out: BTreeMap = BTreeMap::new(); + for (id, cpu) in topo.all_cpus.iter() { + let idx = llc_ids.iter().position(|v| *v == cpu.llc_id).unwrap_or(0); + if let Some(ccx) = core_ccx.get(&(idx, cpu.core_id)) { + out.insert(*id, *ccx); + } + } + out +} + +/// Seed one CPU row per online CPU into the BPF view. +/// Writes the CPU id plus the cluster hint; cache and node come +/// from the upstream tree. The cluster stays here as an interim +/// until it moves into the tree data pointer. +/// Failures return an error. +pub fn seed_topology(skel: &mut BpfSkel<'_>) -> Result { + use libbpf_rs::MapCore; + let topo = Topology::new().context("topology discovery")?; + let mut llc_ids: Vec = topo.all_llcs.keys().copied().collect(); + llc_ids.sort_unstable(); + let mut node_ids: Vec = topo.nodes.keys().copied().collect(); + node_ids.sort_unstable(); + if llc_ids.len() > crate::bpf_intf::flow_consts_FLOW_MAX_LLCS as usize { + anyhow::bail!("LLC count over bound"); + } + if node_ids.len() > crate::bpf_intf::flow_consts_FLOW_MAX_NODES as usize { + anyhow::bail!("node count over bound"); + } + let ccx_map = cpu_ccx(&topo, &llc_ids); + let mut groups: BTreeSet = BTreeSet::new(); + for v in ccx_map.values() { + groups.insert(*v); + } + let mut seeded = 0u32; + let mut cpus: Vec = topo.all_cpus.keys().copied().collect(); + cpus.sort_unstable(); + for cpu in cpus { + if cpu >= crate::bpf_intf::flow_consts_FLOW_MAX_CPUS as usize { + continue; + } + if !topo.all_cpus.contains_key(&cpu) { + continue; + } + let ccx = ccx_map.get(&cpu).copied().unwrap_or(0); + let key = (cpu as u32).to_ne_bytes(); + let mut val = [0u8; 16]; + val[0..4].copy_from_slice(&(cpu as u32).to_ne_bytes()); + val[4..8].copy_from_slice(&ccx.to_ne_bytes()); + val[8..12].copy_from_slice(&0u32.to_ne_bytes()); + val[12..16].copy_from_slice(&0u32.to_ne_bytes()); + skel.maps + .cpu_ctx_stor + .update(&key, &val, libbpf_rs::MapFlags::ANY) + .with_context(|| format!("cpu seed failed for cpu {cpu}"))?; + seeded += 1; + } + Ok(format!( + "{} cpus {} llcs {} nodes {} groups", + seeded, + llc_ids.len(), + node_ids.len(), + groups.len().max(1), + )) +} + +#[cfg(test)] +mod tests { + use super::chunk_index; + + #[test] + fn chunks_split_every_four() { + assert_eq!(chunk_index(0), 0); + assert_eq!(chunk_index(3), 0); + assert_eq!(chunk_index(4), 1); + assert_eq!(chunk_index(7), 1); + assert_eq!(chunk_index(8), 2); + } +} diff --git a/scheds/experimental/scx_flow/ui/index.html b/scheds/experimental/scx_flow/ui/index.html deleted file mode 100644 index b251e033b8..0000000000 --- a/scheds/experimental/scx_flow/ui/index.html +++ /dev/null @@ -1,694 +0,0 @@ - - - - - - - scx_flow stats - - - -
- - -
-
-

- scx_flow stats -

-

- per-CPU fair queues, fixed quantum and placement -

-

Loading...

-
-
- -
- ● running -
-
-
- - -
- - -
- -

TL;DR

-

- Loading... -

-

Explanation

-

-
- - -
- -
-
- On-CPU: - 0 -
-
- Live pids: - 0 -
-
- Uptime: - 0 -
-
- Runtime: - 0 -
-
- Inserts: - 0 -
-
- Requeues: - 0 -
-
- Completions: - 0 -
-
- Local moves: - 0 -
-
- Node moves: - 0 -
-
- Machine moves: - 0 -
-
- Kicks: - 0 -
-
- Admits: - 0 -
-
- Rejects: - 0 -
-
- Misses: - 0 -
-
- Gate rejects: - 0 -
-
- Preempt kicks: - 0 -
-
- Preempt skipped: - 0 -
-
- RED rejects: - 0 -
-
- RED reclaims: - 0 -
- -
-
- - -
-

Loading...

-
-
- - - -