ktstr/vmm/
wprof.rs

1//! wprof tracer configuration shipped into auto-repro VMs.
2//!
3//! [wprof](https://github.com/anakryiko/wprof) is a BSD-3-Clause
4//! BPF-based system-wide tracer/profiler that emits Perfetto-format
5//! `.pb` traces. ktstr ships the binary at `/bin/wprof` in the guest
6//! initramfs when a test enables wprof capture, and the guest init
7//! invokes it during auto-repro to produce a trace alongside the
8//! standard failure-dump output.
9//!
10//! The wprof bytes live in the `cargo-ktstr` binary (built by
11//! `build.rs`, embedded via `include_bytes!` in
12//! `src/bin/cargo_ktstr/blobs.rs`). At cargo-ktstr startup the
13//! `install_env` hook extracts the bytes to a tempfile and exports
14//! `KTSTR_WPROF_PATH=<path>`; [`WprofConfig::from_env`] reads that
15//! env var and loads the file for the builder.
16
17use anyhow::Result;
18
19/// Minimum guest memory (MiB) for test entries that enable wprof.
20///
21/// Derivation: `WprofConfig::default_args` requests a single 16 MiB
22/// BPF ring buffer (`--ringbuf-size=16384 --ringbuf-cnt=1`). wprof
23/// faults the whole arena in on capture, so guest RAM must cover it.
24/// The floor is computed from the default ringbuf constants at
25/// `crate::test_support::runtime::WPROF_MIN_MEMORY_MIB` (16 MiB), so
26/// editing `--ringbuf-size`/`--ringbuf-cnt` moves the floor with them.
27///
28/// Applied as a floor by
29/// `crate::test_support::runtime::derive_test_memory_mib` —
30/// the single derivation site shared by the entry-derived
31/// topology path AND every dispatch site that constructs a
32/// `crate::test_support::topo::TopoOverride` from CLI / preset
33/// topology (so e.g. `cargo ktstr test --ktstr-topo NnNlNcNt` and
34/// gauntlet preset runs honor the floor identically). Both
35/// primary and auto-repro VMs route through the same derivation
36/// so the floor propagates to both; identical topology between
37/// the two VMs is also required for stall reproducibility.
38///
39/// The floor applies when the derived memory
40/// `max(cpus*64, 256, entry.memory_mib)` falls below it AND
41/// `entry.wprof` is true. At the minimal default the 16 MiB arena
42/// sits below the universal 256 MiB memory floor, so this floor is
43/// subsumed and never bumps a real VM — the point is that the
44/// default no longer oversizes; it re-engages only if the default
45/// ringbuf sizing grows the arena past the universal floor. A test
46/// that overrides to a larger arena via
47/// `#[ktstr_test(wprof_args = "...")]` must raise its own
48/// `memory_mib` if that arena exceeds the guest's normal memory. An
49/// operator-supplied `crate::test_support::topo::TopoOverride` with
50/// explicit `memory_mib` is honored verbatim per the
51/// override-is-verbatim contract. Shell-mode VMs
52/// (`cargo ktstr shell --kernel ...`) bypass this floor entirely;
53/// the operator sets memory size via shell-mode CLI args.
54pub const WPROF_MIN_MEMORY_MIB: u32 = crate::test_support::runtime::WPROF_MIN_MEMORY_MIB;
55
56/// Apply the wprof memory floor to a raw memory size.
57///
58/// Returns `WPROF_MIN_MEMORY_MIB` when `wprof` is true and `raw_mib`
59/// falls below the floor; otherwise returns `raw_mib` unchanged.
60/// Pure function — no logging, no side effects — so it can be
61/// called from multiple resolution paths without duplicating the
62/// floor formula.
63///
64/// Single source of truth shared by
65/// `crate::test_support::runtime::derive_test_memory_mib` (the
66/// test-launch path used by `cargo ktstr test`) AND by
67/// `cargo ktstr shell --test <NAME>`'s router (which constructs a
68/// shell VM matching the named test's topology). A future change
69/// to the floor formula updates here once; both call sites pick
70/// it up. Inline copies of the `raw < WPROF_MIN_MEMORY_MIB`
71/// conditional are a regression per the
72/// derive_test_memory_mib/attach_wprof_if_requested precedent.
73pub fn apply_wprof_memory_floor(raw_mib: u32, wprof: bool) -> u32 {
74    crate::test_support::runtime::apply_wprof_memory_floor(raw_mib, wprof)
75}
76
77/// wprof invocation args + binary path. Passed to
78/// [`crate::vmm::KtstrVmBuilder::wprof`] when a test (or
79/// `cargo ktstr shell`) wants the wprof tracer available inside
80/// the guest VM.
81///
82/// The binary is sourced from a host path (typically the tempfile
83/// path that `cargo-ktstr` exports via `KTSTR_WPROF_PATH`). The
84/// library packs it at `bin/wprof` in the initramfs using the
85/// existing include_files mechanism, which performs `DT_NEEDED`
86/// resolution and pulls every shared library wprof links against
87/// (libelf, libz, etc.) so the binary actually runs inside the
88/// guest.
89///
90/// The args render to the kernel cmdline as
91/// `KTSTR_WPROF_ARGS=<args joined with ASCII Unit Separator `\x1F`>`
92/// (see [`WprofConfig::args_cmdline`]); guest init parses them and
93/// invokes `/bin/wprof` with those args during auto-repro.
94#[derive(Debug, Clone)]
95pub struct WprofConfig {
96    /// Host filesystem path to the wprof binary. The library opens
97    /// this path to read the ELF (for `DT_NEEDED` resolution) and
98    /// to copy the bytes into the initramfs. Usually populated from
99    /// [`WprofConfig::from_env`] which reads `KTSTR_WPROF_PATH`.
100    pub host_path: std::path::PathBuf,
101    /// CLI args appended after `/bin/wprof` when guest init spawns
102    /// the tracer. Defaults to [`WprofConfig::default_args`].
103    pub args: Vec<String>,
104}
105
106impl WprofConfig {
107    /// Construct a [`WprofConfig`] using the env-var-published
108    /// wprof binary (set by `cargo-ktstr` at startup) and the
109    /// project default args. Returns an error if `KTSTR_WPROF_PATH`
110    /// is unset.
111    pub fn from_env() -> Result<Self> {
112        Ok(Self {
113            host_path: crate::vmm::blobs::load_wprof_path()?,
114            args: Self::default_args(),
115        })
116    }
117
118    /// Default wprof args used by the auto-repro pipeline:
119    /// `-d 500 -e sched --ringbuf-size=16384 --ringbuf-cnt=1`.
120    ///
121    /// Capture window: 500 ms of sched-event tracing into a single
122    /// 16 MiB BPF ring buffer — wprof's own per-buffer default
123    /// (`DEFAULT_RINGBUF_SZ`), the minimal arena that still captures
124    /// ktstr's short sched traces without dropping. The ringbuf
125    /// sizing comes from
126    /// [`crate::test_support::runtime::WPROF_DEFAULT_RINGBUF_SIZE_KB`]
127    /// and [`crate::test_support::runtime::WPROF_DEFAULT_RINGBUF_CNT`]
128    /// so the flags and the derived [`WPROF_MIN_MEMORY_MIB`] floor
129    /// stay in lockstep. Override per-test by constructing a
130    /// [`WprofConfig`] with a custom `args` vec (or, from a test,
131    /// `#[ktstr_test(wprof_args = "...")]`).
132    pub fn default_args() -> Vec<String> {
133        use crate::test_support::runtime::{
134            WPROF_DEFAULT_RINGBUF_CNT, WPROF_DEFAULT_RINGBUF_SIZE_KB,
135        };
136        vec![
137            "-d".to_string(),
138            "500".to_string(),
139            "-e".to_string(),
140            "sched".to_string(),
141            format!("--ringbuf-size={WPROF_DEFAULT_RINGBUF_SIZE_KB}"),
142            format!("--ringbuf-cnt={WPROF_DEFAULT_RINGBUF_CNT}"),
143        ]
144    }
145
146    /// Render the args as a delimited string suitable for passing on
147    /// the kernel cmdline (`KTSTR_WPROF_ARGS=...`). The kernel
148    /// cmdline tokenizer splits on whitespace and `/proc/cmdline`
149    /// parsers (including the guest's `cmdline_val` via
150    /// `split_whitespace`) cannot recover spaces inside a value, so
151    /// joining args with a literal space would truncate everything
152    /// after the first arg. Use ASCII Unit Separator (`\x1F`, the
153    /// delimiter character codepoint reserved by ANSI X3.4 for this
154    /// exact purpose) — non-whitespace, won't appear in real wprof
155    /// args (which are flags, paths, integers, comma-separated
156    /// feature lists), and the kernel passes it through to
157    /// `/proc/cmdline` byte-for-byte.
158    pub fn args_cmdline(&self) -> String {
159        self.args.join("\x1f")
160    }
161}