diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 3cba2313..58e9f6da 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,7 +1,6 @@ { "recommendations": [ "llvm-vs-code-extensions.vscode-clangd", - "charliermarsh.ruff", - "eamodio.gitlens" + "charliermarsh.ruff" ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 52540406..ffc0c2d3 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,6 +9,13 @@ "**/linux/config.*": "makefile", }, "search.exclude": { - "kmod/build": true, + "build": true, }, + "python.analysis.exclude": [ + "**/node_modules", + "**/.*", + "**/.venv", + "**/__pycache__", + "**/build" + ], } diff --git a/crates/core/src/qemu.rs b/crates/core/src/qemu.rs index f7c211ed..4ceb5c4f 100644 --- a/crates/core/src/qemu.rs +++ b/crates/core/src/qemu.rs @@ -167,6 +167,13 @@ impl Boot { ] .map(String::from), ); + // Under TCG a virtqueue kick on virt's MMIO transport is cheaper handled on the vCPU than + // hopped through an eventfd and the main loop (native tick -17%; in the browser, where an + // eventfd is a JS pipe on the page's thread, -25%). KVM keeps it, and x86's PCI transport + // is unmeasured. + if !kvm_available() && self.arch.virtio_serial == "virtio-serial-device" { + argv.extend(["-global".into(), "virtio-mmio.ioeventfd=off".into()]); + } // A snapshot restores RAM, so the kernel, initrd and command line it was booted with are // not loaded again; the machine and devices must match what it was taken on. match &self.snapshot { @@ -322,9 +329,12 @@ mod tests { // the accelerator is the host's: KVM where /dev/kvm is usable assert!(a.starts_with("-machine virt -accel "), "{a}"); assert!( - a.contains("-smp 3 -m 64M -kernel /kernel -initrd /rootfs.cpio -append rw nokaslr"), + a.contains("-smp 3 -m 64M -kernel /kernel -initrd /rootfs.cpio -append rw nokaslr") + || a.contains("-smp 3 -m 64M -global virtio-mmio.ioeventfd=off -kernel /kernel -initrd /rootfs.cpio -append rw nokaslr"), "{a}" ); + // and TCG, always the browser's, handles a virtqueue kick on the vCPU + assert_eq!(a.contains("ioeventfd=off"), !kvm_available(), "{a}"); // the browser's two-way channels are the wasm32 build's (served()); run.mjs --check boots them assert!(a.contains("-device virtio-serial-device,id=vs0 -device virtconsole,bus=vs0.0,nr=0,chardev=port -chardev file,id=console,path=/kernel.log -chardev "), "{a}"); } @@ -355,6 +365,7 @@ mod tests { || a.contains("-accel tcg,tb-size=64,thread=multi -cpu "), "{a}" ); + assert!(!a.contains("ioeventfd"), "{a}"); // x86's PCI transport keeps it assert!(a.ends_with("-chardev file,id=console,path=/r/kernel.log -chardev socket,path=/r/kstep.sock,server=on,wait=off,logfile=/r/kstep.jsonl,id=port -chardev socket,path=/r/monitor.sock,server=on,wait=off,id=monitor -monitor chardev:monitor"), "{a}"); assert!(!a.contains("memory-backend")); boot.ram_file = Some("/dev/shm/x".into()); diff --git a/crates/core/src/shm.rs b/crates/core/src/shm.rs index 220a65b3..4a793c9d 100644 --- a/crates/core/src/shm.rs +++ b/crates/core/src/shm.rs @@ -118,7 +118,6 @@ pub struct Cgroup { #[derive(Debug, Clone, Serialize, PartialEq)] pub struct Cfs { pub cpu: u32, - pub min_vruntime: i64, pub util_avg: u64, pub load_avg: u64, pub runnable_avg: u64, @@ -138,8 +137,6 @@ pub struct Entity { pub on_rq: bool, pub curr: bool, pub pick: bool, - /// Of the CPU, 1.0 being all of it - pub share: f64, pub weight: u64, pub sum_exec_runtime: u64, pub vruntime: i64, @@ -189,7 +186,9 @@ pub struct Domain { pub busy_factor: u32, pub cache_nice_tries: u32, pub nr_balance_failed: u32, - pub last_balance_ago: u32, + /// Ticks until this CPU's group is balanced at this level, and the CPU that will do it + pub next_balance_in: u32, + pub balancer: u32, pub groups: Vec, } @@ -268,7 +267,6 @@ pub fn decode(b: &[u8]) -> Result { })?; let cfs = table(&r.cfs, h.ncpus, |q| Cfs { cpu: q.cpu, - min_vruntime: q.min_vruntime, util_avg: q.util_avg, load_avg: q.load_avg, runnable_avg: q.runnable_avg, @@ -283,7 +281,6 @@ pub fn decode(b: &[u8]) -> Result { on_rq: e.se.flags & KSTEP_SE_ON_RQ != 0, curr: e.se.flags & KSTEP_SE_CURR != 0, pick: e.se.flags & KSTEP_SE_PICK != 0, - share: e.se.share as f64 / 1024.0, weight: e.se.weight, sum_exec_runtime: e.se.sum_exec_runtime, vruntime: e.se.vruntime, @@ -334,7 +331,8 @@ pub fn decode(b: &[u8]) -> Result { busy_factor: d.busy_factor, cache_nice_tries: d.cache_nice_tries, nr_balance_failed: d.nr_balance_failed, - last_balance_ago: d.last_balance_ago, + next_balance_in: d.next_balance_in, + balancer: d.balancer, groups: all_groups .get(d.group as usize..(d.group + d.ngroups) as usize) .map(<[Group]>::to_vec) @@ -402,7 +400,7 @@ mod tests { r.cgroup[0].weight = 100; r.cfs[0] = kstep_shm_cfs { cpu: 1, - min_vruntime: 1000, + util_avg: 1000, ..Default::default() }; r.entity[0] = kstep_shm_entity { @@ -410,7 +408,6 @@ mod tests { cpu: 1, se: kstep_shm_se { flags: KSTEP_SE_ELIGIBLE | KSTEP_SE_CURR, - share: 512, lag: -8, ..Default::default() }, @@ -476,19 +473,11 @@ mod tests { (st.groups[0].path.as_str(), st.groups[0].weight), ("/a", 100) ); - assert_eq!(st.cfs[0].min_vruntime, 1000); + assert_eq!(st.cfs[0].util_avg, 1000); let e = &st.entities[0]; assert_eq!( - ( - e.task, - e.cgroup.as_str(), - e.eligible, - e.curr, - e.pick, - e.share, - e.lag - ), - (1, "/a", true, true, false, 0.5, -8) + (e.task, e.cgroup.as_str(), e.eligible, e.curr, e.pick, e.lag), + (1, "/a", true, true, false, -8) ); assert_eq!( ( diff --git a/crates/kstep/src/cli/run.rs b/crates/kstep/src/cli/run.rs index 35676473..86d7bab2 100644 --- a/crates/kstep/src/cli/run.rs +++ b/crates/kstep/src/cli/run.rs @@ -175,10 +175,7 @@ fn summary(st: &State) -> String { } s += &format!(" exec={:.1}ms", t.sum_exec_runtime as f64 / 1e6); if let Some(e) = st.entities.iter().find(|e| e.task == t.task) { - s += &format!( - " vruntime={} lag={} weight={} share={:.2}", - e.vruntime, e.lag, e.weight, e.share - ); + s += &format!(" vruntime={} lag={} weight={}", e.vruntime, e.lag, e.weight); for (flag, on) in [ ("eligible", e.eligible), ("pick", e.pick), diff --git a/crates/kstep/src/cli/viz.rs b/crates/kstep/src/cli/viz.rs index 69a1a84c..07a157fe 100644 --- a/crates/kstep/src/cli/viz.rs +++ b/crates/kstep/src/cli/viz.rs @@ -42,6 +42,9 @@ const RESULTS_URL: &str = "https://raw.githubusercontent.com/kstep-dev/results/m /// The playground images: every supported LTS kernel for arm64, shared with the repro builds; /// the page boots this one unless the URL says otherwise const DEFAULT_IMAGE: &str = "v6.18"; +/// The snapshot's machine: the page's default four test CPUs plus CPU 0 for the driver. A layout +/// of up to that many CPUs resumes it, the driver keeping the CPUs beyond the layout idle. +const SNAPSHOT_SMP: u32 = 5; fn website() -> PathBuf { kstep::proj_dir().join("website") @@ -148,11 +151,12 @@ fn build() -> Result { } build_decoder()?; - // data.json: a cache-busting version and the bug catalog + // data.json: a cache-busting version and the bug catalog. Every URL the page fetches carries the + // version, so two builds must never share one: the stamp goes to the second let rev = output(cmd("git", ["rev-parse", "--short", "HEAD"]).current_dir(website()))? .trim() .to_string(); - let version = format!("{rev}-{}", chrono::Utc::now().format("%Y%m%d%H%M")); + let version = format!("{rev}-{}", chrono::Utc::now().format("%Y%m%d%H%M%S")); let all = bugs::load()?; let mut sorted: Vec<&Bug> = all.values().collect(); sorted.sort_by_key(|b| b.extra); // the paper's table first, in file order @@ -162,6 +166,7 @@ fn build() -> Result { serde_json::to_string_pretty(&json!({ "version": version, "bugs": bugs, "kernels": kstep::checkout::LTS, "kernel": DEFAULT_IMAGE, + "snapshot_cpus": SNAPSHOT_SMP - 1, }))?, )?; @@ -170,18 +175,21 @@ fn build() -> Result { // a kernel build each (~10 min). The machine at the driver's ready line for the page's // default CPU count goes next to each, so the page resumes it instead of booting (~0.3 s // instead of ~4 s); the stream fits this QEMU build and image only, so it is taken again - // exactly when the image changed. Needs site/qemu (website/setup.sh). + // when the image changed or QEMU was rebuilt since (a stale stream hangs the resume + // silently). Needs site/qemu (website/setup.sh). let node = node()?; + let qemu_built = fs::metadata(site().join("qemu/qemu-system-aarch64.wasm"))?.modified()?; for kernel in kstep::checkout::LTS { let b = Build::new(Some(kernel))?; b.build_kstep()?; let images = site().join("images").join(kernel); fs::create_dir_all(&images)?; let same = |src: PathBuf, dst: &str| fs::read(&src).ok() == fs::read(images.join(dst)).ok(); - if same(b.kernel(), "kernel") - && same(b.rootfs(), "rootfs.cpio") - && images.join("snap-5.json").is_file() - { + let snap = images.join(format!("snap-{SNAPSHOT_SMP}.json")); + let snap_fresh = fs::metadata(&snap) + .and_then(|m| m.modified()) + .is_ok_and(|t| t > qemu_built); + if same(b.kernel(), "kernel") && same(b.rootfs(), "rootfs.cpio") && snap_fresh { continue; } fs::copy(b.kernel(), images.join("kernel"))?; @@ -190,7 +198,13 @@ fn build() -> Result { &mut mjs( &node, "run.mjs", - &["--snapshot", "--image", images.to_str().unwrap()], + &[ + "--snapshot", + "--smp", + &SNAPSHOT_SMP.to_string(), + "--image", + images.to_str().unwrap(), + ], ), None, ) diff --git a/kmod/cli.c b/kmod/cli.c index fcaedca5..d2b8e244 100644 --- a/kmod/cli.c +++ b/kmod/cli.c @@ -17,6 +17,7 @@ // block like pause, in a freezable sleep (nanosleep), which the freezer takes // chan-read sleep in the channel until there is a byte, and take it // chan-write put a byte in, which sync-wakes one reader from this task’s CPU +// yield sched_yield(): the task gives the CPU up but stays runnable // kill exit when the task next runs // cgroup-create /a the parent must exist; / is the root // cgroup-weight /a cpu.weight, 1..10000 (default 100) @@ -330,6 +331,7 @@ static const struct { {"wake", kstep_task_wakeup}, {"kill", kstep_task_exit}, {"chan-read", kstep_task_chan_read}, {"chan-write", kstep_task_chan_write}, {"freeze", kstep_freeze_task}, {"thaw", kstep_thaw_task}, + {"yield", kstep_task_yield}, }; /* Returns false when the session should end. */ diff --git a/kmod/driver.h b/kmod/driver.h index 6d9dc449..4f7195b3 100644 --- a/kmod/driver.h +++ b/kmod/driver.h @@ -69,6 +69,7 @@ int kstep_task_set_affinity(struct task_struct *p, const char *cpulist); // "1", void kstep_task_set_fair(struct task_struct *p, int policy, int nice); // normal/batch/idle with its nice void kstep_task_set_rt(struct task_struct *p, int policy, int prio); // fifo/rr with its priority, 1..99 void kstep_task_pause(struct task_struct *p); +void kstep_task_yield(struct task_struct *p); // sched_yield(): gives the CPU up while staying runnable void kstep_task_wakeup(struct task_struct *p); void kstep_task_block(struct task_struct *p); void kstep_task_chan_read(struct task_struct *p); @@ -76,7 +77,6 @@ void kstep_task_chan_write(struct task_struct *p); // kernel.c int kstep_write(const char *path, const char *buf, size_t size); -int kstep_read(const char *path, char *buf, size_t size); int kstep_mkdir(const char *dir); void kstep_sysctl_write(const char *name, const char *fmt, ...); void kstep_sched_feat_write(const char *fmt, ...); @@ -84,7 +84,6 @@ void kstep_sched_feat_enable(const char *name); void kstep_sched_feat_disable(const char *name); int kstep_cgroup_write(const char *name, const char *filename, const char *fmt, ...); -int kstep_cgroup_read(const char *name, const char *filename, char *buf, size_t size); bool kstep_cgroup_exists(const char *name); int kstep_cgroup_create(const char *name); void kstep_cgroup_destroy(const char *name); diff --git a/kmod/kernel.c b/kmod/kernel.c index 02a12017..1434bfca 100644 --- a/kmod/kernel.c +++ b/kmod/kernel.c @@ -29,37 +29,18 @@ int kstep_write(const char *path, const char *buf, size_t size) { loff_t pos = 0; ssize_t ret = kernel_write(file, buf, size, &pos); filp_close(file, NULL); - if (ret < 0) { - TRACE_INFO("write %s failed: %ld", path, ret); - return ret; - } - return 0; -} - -// The counterpart of kstep_write, for the cgroup files kSTEP reports back (shm.c). Returns the -// bytes read, with the trailing newline cgroupfs writes stripped, or a negative errno. -int kstep_read(const char *path, char *buf, size_t size) { - struct file *file = filp_open(path, O_RDONLY, 0); - loff_t pos = 0; - ssize_t ret; - - if (IS_ERR(file)) - return PTR_ERR(file); - ret = kernel_read(file, buf, size - 1, &pos); - filp_close(file, NULL); // filp_close() only queues the release: fput() adds it to this task's task_work, which the // kernel runs on the way back to user mode. kSTEP's controller never goes back -- it is the - // module init, looping inside finit_module for the whole session -- so without this every read - // leaks its struct file and the seq_file buffer under it, about 4.6 KB a time. + // module init, looping inside finit_module for the whole session -- so without this every + // write leaks its struct file. KSYM_IMPORT(task_work_run); if (KSYM_task_work_run) KSYM_task_work_run(); - if (ret < 0) + if (ret < 0) { + TRACE_INFO("write %s failed: %ld", path, ret); return ret; - while (ret > 0 && buf[ret - 1] == '\n') - ret--; - buf[ret] = '\0'; - return ret; + } + return 0; } int kstep_mkdir(const char *dir) { @@ -286,14 +267,6 @@ void kstep_cgroup_init(void) { KSYM_rcu_sync_enter(&cpuset_rwsem->rss); } -int kstep_cgroup_read(const char *name, const char *filename, char *buf, size_t size) { - char path[MAX_PATH_LENGTH]; - - if (scnprintf(path, sizeof(path), CGROUP_ROOT "%s/%s", name, filename) >= sizeof(path)) - return -ENAMETOOLONG; - return kstep_read(path, buf, size); -} - bool kstep_cgroup_exists(const char *name) { char path[MAX_PATH_LENGTH]; struct path p; diff --git a/kmod/reset.c b/kmod/reset.c index fd4f2800..2f338465 100644 --- a/kmod/reset.c +++ b/kmod/reset.c @@ -185,7 +185,10 @@ void kstep_reset_cpumask(void) { KSYM_IMPORT_TYPED(int, distribute_cpu_mask_prev); // https://github.com/torvalds/linux/commit/46a87b3851f0d6eb05e6d83d5c5a30df0eca8f76 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0) - for_each_test_cpu(cpu) { + // Every CPU, the controller's included: a new task's first CPU is picked from CPU 0, where + // kstep_task_create sets its affinity, by cpumask_any_and_distribute rotating from this + // counter. Left at whatever the boot made of it, the task's first CPU varied from boot to boot. + for (int cpu = 0; cpu < num_online_cpus(); cpu++) { int *ptr = per_cpu_ptr(KSYM_distribute_cpu_mask_prev, cpu); *ptr = 0; } diff --git a/kmod/shm.c b/kmod/shm.c index 2d61819d..df69a3d6 100644 --- a/kmod/shm.c +++ b/kmod/shm.c @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -38,12 +37,6 @@ phys_addr_t kstep_shm_init(void) { // and curr are the kernel's own answers -- entity_eligible, pick_eevdf, cfs_rq->curr -- so the // page shows what the scheduler would do rather than a re-derivation of it. pick_eevdf is inlined // into __pick_eevdf(cfs_rq, protect) from 6.16, where protect is RUN_TO_PARITY's guard of curr. -#ifdef CONFIG_FAIR_GROUP_SCHED -#define parent_entity(se) ((se)->parent) -#else -#define parent_entity(se) ((struct sched_entity *)NULL) -#endif - #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 6, 0) // EEVDF's pick: __pick_eevdf(cfs_rq, protect) from 6.13, pick_eevdf(cfs_rq) before it. static struct sched_entity *shm_pick(struct cfs_rq *cfs_rq) { @@ -90,17 +83,6 @@ static struct kstep_shm_se shm_se(struct sched_entity *se) { if (se->on_rq && shm_pick(cfs_rq) == se) out.flags |= KSTEP_SE_PICK; #endif - // the share of the CPU: at each level this entity's weight over everything queued there, - // multiplied up to the root; 0 when not queued, since a queue's total counts only what is on it - if (se->on_rq) { - u64 share = 1024; - - for (struct sched_entity *s = se; s; s = parent_entity(s)) { - struct cfs_rq *q = cfs_rq_of(s); - share = q->load.weight ? div64_u64(share * s->load.weight, q->load.weight) : 0; - } - out.share = share; - } return out; } @@ -160,26 +142,51 @@ static struct kstep_shm_rt_entity shm_rt_entity(struct task_struct *p, u32 task, return out; } -// The cgroup's group entities, one record per test CPU, appended to `ents` -- the level the pick -// happens at, which nothing else reports: a task's own counters are kept in its group's queue, so -// four equal tasks split two cgroups' halves without anything in the task table saying why. The -// cpu controller's css is taken from the cgroup rather than the walk's, which is cgroup->self. -// Called under RCU; the entities are stable because the isolated CPUs are held for the whole -// command. -static void shm_group_entities(u32 cgroup, struct cgroup *cgrp, struct kstep_shm_entity *ents, u32 *nents) { -#ifdef CONFIG_FAIR_GROUP_SCHED +// The cgroup's task group, the cpu controller's state; NULL where the controller is off. The css +// is taken from the cgroup rather than the walk's, which is cgroup->self. Under RCU. +static struct task_group *shm_tg(struct cgroup *cgrp) { +#ifdef CONFIG_CGROUP_SCHED struct cgroup_subsys_state *css = rcu_dereference(cgrp->subsys[cpu_cgrp_id]); - struct task_group *tg; if (!css) - return; + return NULL; // css_tg() is private to core.c before 6.12, when sched_ext moved it into sched.h #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 12, 0) - tg = css_tg(css); + return css_tg(css); #else - tg = container_of(css, struct task_group, css); + return container_of(css, struct task_group, css); +#endif +#else + return NULL; +#endif +} + +#ifdef CONFIG_CPUSETS +// The head of struct cpuset, private to kernel/cgroup/cpuset.c (cpuset-internal.h on newer +// kernels) and the same on every kernel kSTEP builds: enough to read the mask that +// cpuset.cpus.effective shows without opening the file, which under emulation costs more than +// the rest of an update together. +struct kstep_cpuset_head { + struct cgroup_subsys_state css; + unsigned long flags; + cpumask_var_t cpus_allowed; + nodemask_t mems_allowed; + cpumask_var_t effective_cpus; +}; +#if __has_include() +#include +static_assert(offsetof(struct kstep_cpuset_head, effective_cpus) == offsetof(struct cpuset, effective_cpus)); +#endif #endif - if (!tg->parent) // the root task group owns no entity: its cfs_rq is the runqueue's own + +// The cgroup's group entities, one record per test CPU, appended to `ents` -- the level the pick +// happens at, which nothing else reports: a task's own counters are kept in its group's queue, so +// four equal tasks split two cgroups' halves without anything in the task table saying why. +// Called under RCU; the entities are stable because the isolated CPUs are held for the whole +// command. +static void shm_group_entities(u32 cgroup, struct task_group *tg, struct kstep_shm_entity *ents, u32 *nents) { +#ifdef CONFIG_FAIR_GROUP_SCHED + if (!tg || !tg->parent) // the root task group owns no entity: its cfs_rq is the runqueue's own return; for_each_test_cpu(cpu) { struct sched_entity *se = tg->se[cpu]; @@ -198,12 +205,9 @@ static void shm_group_entities(u32 cgroup, struct cgroup *cgrp, struct kstep_shm #endif } -// The cgroups: the root and every live cgroup under it, in tree order, collected into `out`. -// The tree walk needs RCU and the two control files sleep, so the walk takes the paths first and -// the files are read after it. Reading the files is how the kernel's own interface reports these -// values -- the cpu controller's weight could come from the task_group, but a cpuset's effective -// mask lives in struct cpuset, which is private to kernel/cgroup/cpuset.c. A cgroup with no cpu -// controller (the root among them, which has no cpu.weight) keeps weight 0. +// The cgroups: the root and every live cgroup under it, in tree order, collected into `out` with +// what their cpu.weight and cpuset.cpus.effective files show, read off the controllers' state. A +// cgroup without the controller (the root among them, which has no cpu.weight) keeps 0. static u32 shm_collect_cgroups(struct kstep_shm_cgroup *out, struct kstep_shm_entity *ents, u32 *nents) { struct cgroup_subsys_state *pos; struct cgroup *root; @@ -215,6 +219,8 @@ static u32 shm_collect_cgroups(struct kstep_shm_cgroup *out, struct kstep_shm_en return 0; rcu_read_lock(); css_for_each_descendant_pre(pos, &root->self) { + struct task_group *tg = shm_tg(pos->cgroup); + if (n == KSTEP_SHM_CGROUPS) break; if (!(pos->flags & CSS_ONLINE)) @@ -222,30 +228,34 @@ static u32 shm_collect_cgroups(struct kstep_shm_cgroup *out, struct kstep_shm_en memset(&out[n], 0, sizeof(out[n])); if (cgroup_path(pos->cgroup, out[n].path, sizeof(out[n].path)) < 0) continue; // a path that does not fit is one no kSTEP driver made - shm_group_entities(n, pos->cgroup, ents, nents); +#ifdef CONFIG_FAIR_GROUP_SCHED + if (tg && tg->parent) // cpu.weight's own conversion of the shares + out[n].weight = clamp_t(u64, DIV_ROUND_CLOSEST_ULL(scale_load_down(tg->shares) * CGROUP_WEIGHT_DFL, 1024), + CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX); +#endif +#ifdef CONFIG_CPUSETS + { + struct cgroup_subsys_state *cs = rcu_dereference(pos->cgroup->subsys[cpuset_cgrp_id]); + + if (cs) + out[n].cpus = cpumask_bits(container_of(cs, struct kstep_cpuset_head, css)->effective_cpus)[0]; + } +#endif + shm_group_entities(n, tg, ents, nents); n++; } rcu_read_unlock(); cgroup_put(root); - - for (u32 i = 0; i < n; i++) { - const char *name = out[i].path[1] ? out[i].path : ""; // the root's files live at CGROUP_ROOT - char buf[64]; - cpumask_var_t mask; - - if (kstep_cgroup_read(name, "cpu.weight", buf, sizeof(buf)) > 0 && - kstrtouint(buf, 10, &out[i].weight)) - out[i].weight = 0; // a value that does not parse is one this kernel does not report - if (kstep_cgroup_read(name, "cpuset.cpus.effective", buf, sizeof(buf)) > 0 && - zalloc_cpumask_var(&mask, GFP_KERNEL)) { - if (!cpulist_parse(buf, mask)) - out[i].cpus = cpumask_bits(mask)[0]; - free_cpumask_var(mask); - } - } return n; } +// idle_cpu(), which not every kernel exports: nothing runs, nothing is queued, no wakeup pending +static bool shm_idle_cpu(int cpu) { + struct rq *rq = cpu_rq(cpu); + + return rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending; +} + // The sched domains the kernel actually built, per CPU and innermost first, and their groups into // the flat group table. Read under RCU, like any other walk of rq->sd. A group's span comes from // sched_group_span (the CPUs it covers), not its balance mask; sd->groups starts at the CPU's own @@ -274,8 +284,47 @@ static u32 shm_collect_domains(struct kstep_shm_domain *out, struct kstep_shm_gr d->nr_balance_failed = sd->nr_balance_failed; d->busy_factor = sd->busy_factor; d->cache_nice_tries = sd->cache_nice_tries; - // jiffies is the mocked clock plus a fixed offset (tick_jiffies.c), so this is logical ticks - d->last_balance_ago = jiffies - sd->last_balance; + // the level's next balance for this CPU, as sched_balance_domains will compute it: the + // interval in ms, busy_factor times longer on a busy CPU (and one less, to unlock the levels' + // periods from each other), in jiffies, clamped to HZ/10 -- max_load_balance_interval + { + struct rq *rq = cpu_rq(cpu); + bool busy = rq->curr != rq->idle; + unsigned long interval = sd->balance_interval; + + if (busy) + interval *= sd->busy_factor; + interval = msecs_to_jiffies(interval); + if (busy) + interval -= 1; + interval = clamp(interval, 1UL, (unsigned long)HZ / 10); + d->next_balance_in = time_after(sd->last_balance + interval, jiffies) ? sd->last_balance + interval - jiffies : 0; + } + // who runs it for this CPU's group (should_we_balance): the first idle CPU of the group, + // preferring one on a wholly idle core above the SMT level, else the group's first CPU + { + const struct cpumask *bal = group_balance_mask(sd->groups); + int first_idle = -1, idle_core = -1, pick, c, s; + + for_each_cpu(c, bal) { + bool core_idle = true; + + if (!shm_idle_cpu(c)) + continue; + if (first_idle < 0) + first_idle = c; + for_each_cpu(s, cpu_smt_mask(c)) + core_idle &= shm_idle_cpu(s); + if (core_idle) { + idle_core = c; + break; + } + } + pick = sd->flags & SD_SHARE_CPUCAPACITY ? first_idle // within a core, any idle thread + : idle_core >= 0 ? idle_core // above it, an idle core first + : first_idle; // else an idle thread of a busy core + d->balancer = pick >= 0 ? pick : cpumask_first(bal); // nobody idle: the group's first CPU + } d->group = *ngroups; first = sd->groups; sg = first; @@ -331,9 +380,6 @@ void kstep_shm_update(struct task_struct **tasks, int ntasks) { }; shm->cfs[cpu - 1] = (struct kstep_shm_cfs){ .cpu = cpu, -#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 19, 0) - .min_vruntime = rq->cfs.min_vruntime, -#endif #ifdef CONFIG_SMP .util_avg = rq->cfs.avg.util_avg, .load_avg = rq->cfs.avg.load_avg, diff --git a/kmod/shm.h b/kmod/shm.h index 79420bc2..b85ae468 100644 --- a/kmod/shm.h +++ b/kmod/shm.h @@ -11,7 +11,7 @@ // Bump whenever a struct below changes, in size or in meaning: a decoder built from another // revision of this header refuses the region instead of misreading it. -#define KSTEP_SHM_LAYOUT 10 +#define KSTEP_SHM_LAYOUT 14 // hdr.features: what this kernel's scheduler has, so a reader shows what exists rather than // knowing kernel versions. EEVDF (6.6+): the fair entities' lag, deadline, eligibility and pick. @@ -82,7 +82,6 @@ struct kstep_shm_se { // se->vlag, which place_entity will restore, while not. s64 lag; u32 flags; - u32 share; // of the CPU, in 1/1024: this weight over its queue's, times the parent entity's share, up to the root -- the walk update_cfs_rq_h_load makes over load averages, made over weights }; // A task's identity and its scheduling attributes -- the sched_attr fields every class reads or @@ -111,7 +110,6 @@ struct kstep_shm_cgroup { // nr_running counts everything queued, h_nr_runnable only what the fair class will run, and a // real-time task, or one left behind by delayed dequeue, is in one and not the other. struct kstep_shm_cfs { - s64 min_vruntime; // signed, as an entity's vruntime u64 util_avg, load_avg, runnable_avg; u64 h_nr_runnable; // cfs_rq->h_nr_runnable: runnable tasks as the balancer counts them u32 cpu; @@ -174,7 +172,11 @@ struct kstep_shm_domain { u32 group, ngroups; // this domain's balancing groups: the group table from `group`, `ngroups` of them, the CPU's own group first as sd->groups has it u32 imbalance_pct, balance_interval, busy_factor, cache_nice_tries; u32 nr_balance_failed; // per CPU: consecutive failures here, which escalate to active balancing - u32 last_balance_ago; // ticks since this CPU last balanced at this level + // When and by whom this CPU's group is next balanced at this level: ticks until last_balance plus + // the interval (busy_factor times longer while the CPU is busy, get_sd_balance_interval) falls + // due, and the CPU that will run it -- should_we_balance's pick for the group: its first idle CPU, + // on an idle core where the level is above SMT, else the group's first CPU. + u32 next_balance_in, balancer; char name[8]; // the topology level: SMT, CLS, MC, PKG, NODE }; diff --git a/kmod/task.c b/kmod/task.c index f9830c6e..86bbf40a 100644 --- a/kmod/task.c +++ b/kmod/task.c @@ -225,6 +225,11 @@ void kstep_task_exit(struct task_struct *p) { TRACE_INFO("Exiting task %d", p->pid); } +void kstep_task_yield(struct task_struct *p) { + kstep_task_ctrl(p, KSTEP_CTRL_YIELD); + TRACE_INFO("Task %d yields", p->pid); +} + void kstep_task_chan_read(struct task_struct *p) { kstep_task_ctrl(p, KSTEP_CTRL_CHAN_READ); TRACE_INFO("Task %d waits", p->pid); diff --git a/kmod/user.h b/kmod/user.h index 45417397..9b5ef326 100644 --- a/kmod/user.h +++ b/kmod/user.h @@ -12,6 +12,7 @@ enum kstep_ctrl { KSTEP_CTRL_BLOCK, // nanosleep(): do_nanosleep() adds TASK_FREEZABLE, which is the difference KSTEP_CTRL_CHAN_READ, // read the channel: sleeps in pipe_read() until there is a byte KSTEP_CTRL_CHAN_WRITE, // write it: pipe_write() sync-wakes one reader from this CPU + KSTEP_CTRL_YIELD, // sched_yield(): give the CPU up, staying runnable -- rr goes to the tail of its list, fair skips the entity once KSTEP_CTRL_PARK, // a new task's first read: sleeps in the read itself (kmod-side only) }; diff --git a/user/user.c b/user/user.c index b1f27be2..d1a11992 100644 --- a/user/user.c +++ b/user/user.c @@ -129,6 +129,9 @@ __attribute__((noreturn)) static int task_main(void) { case KSTEP_CTRL_CHAN_WRITE: write(chan_fd(), "w", 1); // pipe_write() sync-wakes one reader, from this CPU break; + case KSTEP_CTRL_YIELD: + sched_yield(); // stays runnable: the class decides who runs instead, if anyone + break; default: panic("Unknown control action: %d", c); } diff --git a/website b/website index aa6966e7..7e2b313e 160000 --- a/website +++ b/website @@ -1 +1 @@ -Subproject commit aa6966e7898b6f7669e33b88b287a0d7f140b2be +Subproject commit 7e2b313eeda59952820a2419669ad2708860f4db