Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
{
"recommendations": [
"llvm-vs-code-extensions.vscode-clangd",
"charliermarsh.ruff",
"eamodio.gitlens"
"charliermarsh.ruff"
]
}
9 changes: 8 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
"**/linux/config.*": "makefile",
},
"search.exclude": {
"kmod/build": true,
"build": true,
},
"python.analysis.exclude": [
"**/node_modules",
"**/.*",
"**/.venv",
"**/__pycache__",
"**/build"
],
}
13 changes: 12 additions & 1 deletion crates/core/src/qemu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}");
}
Expand Down Expand Up @@ -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());
Expand Down
29 changes: 9 additions & 20 deletions crates/core/src/shm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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<Group>,
}

Expand Down Expand Up @@ -268,7 +267,6 @@ pub fn decode(b: &[u8]) -> Result<State, Error> {
})?;
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,
Expand All @@ -283,7 +281,6 @@ pub fn decode(b: &[u8]) -> Result<State, Error> {
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,
Expand Down Expand Up @@ -334,7 +331,8 @@ pub fn decode(b: &[u8]) -> Result<State, Error> {
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)
Expand Down Expand Up @@ -402,15 +400,14 @@ 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 {
task: 1,
cpu: 1,
se: kstep_shm_se {
flags: KSTEP_SE_ELIGIBLE | KSTEP_SE_CURR,
share: 512,
lag: -8,
..Default::default()
},
Expand Down Expand Up @@ -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!(
(
Expand Down
5 changes: 1 addition & 4 deletions crates/kstep/src/cli/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
30 changes: 22 additions & 8 deletions crates/kstep/src/cli/viz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -148,11 +151,12 @@ fn build() -> Result<String> {
}
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
Expand All @@ -162,6 +166,7 @@ fn build() -> Result<String> {
serde_json::to_string_pretty(&json!({
"version": version, "bugs": bugs,
"kernels": kstep::checkout::LTS, "kernel": DEFAULT_IMAGE,
"snapshot_cpus": SNAPSHOT_SMP - 1,
}))?,
)?;

Expand All @@ -170,18 +175,21 @@ fn build() -> Result<String> {
// 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"))?;
Expand All @@ -190,7 +198,13 @@ fn build() -> Result<String> {
&mut mjs(
&node,
"run.mjs",
&["--snapshot", "--image", images.to_str().unwrap()],
&[
"--snapshot",
"--smp",
&SNAPSHOT_SMP.to_string(),
"--image",
images.to_str().unwrap(),
],
),
None,
)
Expand Down
2 changes: 2 additions & 0 deletions kmod/cli.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
// block <n> like pause, in a freezable sleep (nanosleep), which the freezer takes
// chan-read <n> sleep in the channel until there is a byte, and take it
// chan-write <n> put a byte in, which sync-wakes one reader from this task’s CPU
// yield <n> sched_yield(): the task gives the CPU up but stays runnable
// kill <n> exit when the task next runs
// cgroup-create /a the parent must exist; / is the root
// cgroup-weight /a <w> cpu.weight, 1..10000 (default 100)
Expand Down Expand Up @@ -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. */
Expand Down
3 changes: 1 addition & 2 deletions kmod/driver.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,21 @@ 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);
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, ...);
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);
Expand Down
39 changes: 6 additions & 33 deletions kmod/kernel.c
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down
5 changes: 4 additions & 1 deletion kmod/reset.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading