merge fork/062-input-latency into fork/062-intel-test3

This commit is contained in:
Garvit Surana committed 2026-11-26 09:16:41 +00:00
commit bb44df447e
5 files changed
+672 -83

No files matched your search

+238
View File
@@ -0,0 +1,238 @@
//! When `stela-boot`'s input service polls each host keyboard and pointer
//! (`engine::input`), how a due poll meets the host drivers' lock another
//! processor holds, and the spread of the polls' lateness and of the gaps
//! between the inputs they deliver.
//!
//! Every poll runs under the host drivers' lock, which the GPUs' pump holds
//! while Linux runs, a step at a time, and lets go after its step once a
//! core spins for it. A device is due once its interval has passed since
//! its last poll. A due poll that finds the lock taken tries again at the
//! next service turn; once it is [`LATE_WAIT_MICROS`] late it spins for
//! the lock instead, as a waiter the pump lets in after its step, for the
//! turn's [`wait_micros`] at most, once a turn. A wait the holder outlasted
//! (one Linux step can take tens of milliseconds) is not tried again for
//! [`WAIT_BACKOFF_MICROS`], so a poll never spins through a long step.
//!
//! A device's interval is its looks' cost: a poll that delivered nothing
//! costs the boot PE what it took, and polls are spaced [`COST_SHARE`] times
//! that recent cost apart, between [`IDLE_MILLIS`] and [`SLOW_MILLIS`] when
//! idle and at most [`ACTIVE_MILLIS`] for [`ACTIVE_SECONDS`] after its last
//! input. A poll that delivered input is not counted: its time is the
//! input's own transfer, which an I2C touchpad behind an interrupt pin pays
//! only when its pin says a report is ready (about 0.75 ms for a report at
//! 400 kHz), so counting it held a moving finger to one read every 32 ms.
/// A device that gave no input for [`ACTIVE_SECONDS`] is polled this often
/// at most. A poll can be a port or register access a hypervisor takes to
/// its device model; USB low-speed keyboards and mice are polled as rarely.
pub const IDLE_MILLIS: u64 = 8;
/// How long a device is polled at every service turn after it last gave
/// input, so a pointer's motion keeps its full rate.
pub const ACTIVE_SECONDS: u64 = 5;
/// A device's looks may take at most one part in this of the boot PE: a
/// look costing more is spaced this many times its cost apart. A port read
/// that costs a microsecond on hardware can wait milliseconds for a
/// hypervisor's device-model lock; the boot PE's time is the guest's.
pub const COST_SHARE: u64 = 32;
/// The longest an idle device waits for its next poll however costly its
/// looks are, which its first input can wait.
pub const SLOW_MILLIS: u64 = 250;
/// The longest an active device waits for its next poll.
pub const ACTIVE_MILLIS: u64 = 32;
/// How late a due poll may run before it waits for a taken lock.
pub const LATE_WAIT_MICROS: u64 = 2000;
/// How long no poll waits for the lock after a wait the holder outlasted.
pub const WAIT_BACKOFF_MICROS: u64 = 8000;
/// The longest wait of a turn on a PE whose guest code waits for it (the
/// boot PE's step, which holds every PE's time), and of any other turn: a
/// waiting PE's or the host core's, whose guest is idle. The GPUs' pump's
/// Linux steps take about 0.2 ms on average.
pub const STEP_WAIT_MICROS: u64 = 250;
pub const WAIT_MICROS: u64 = 1000;
/// Gaps between a device's deliveries longer than this are pauses between
/// motions, not the rate of one, and are left out of its gap spread.
pub const GAP_MILLIS: u64 = 250;
/// The longest wait for the lock in a turn ([`STEP_WAIT_MICROS`]).
pub const fn wait_micros(step: bool) -> u64 {
if step { STEP_WAIT_MICROS } else { WAIT_MICROS }
}
/// One device's pace, in counter ticks of `per_micro` a microsecond.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Device {
/// The counter at its last poll.
looked: u64,
/// The counter at its last poll that delivered input.
active: u64,
/// Its looks' recent cost: an eighth of each poll that delivered
/// nothing joins seven eighths of the last.
cost: u64,
/// The counter at its last delivery, for the gap spread.
delivered: Option<u64>,
}
/// What a turn does with a device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Plan {
/// Not due yet.
Later,
/// Due, `late` ticks past its interval: take the lock if it is free,
/// else spin for it for `wait_micros` at most (none when zero).
Poll { late: u64, wait_micros: u64 },
}
/// One turn's waits: at most one, of at most `wait_micros`.
#[derive(Clone, Copy, Debug)]
pub struct Turn {
wait_micros: u64,
waited: bool,
}
impl Turn {
pub const fn new(wait_micros: u64) -> Self {
Self {
wait_micros,
waited: false,
}
}
}
/// The waits across turns: after one the holder outlasted, none until the
/// counter passes `quiet_until`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Waits {
quiet_until: Option<u64>,
}
impl Waits {
fn allowed(&self, now: u64) -> bool {
// The counter may wrap: the quiet time is over once `now` is no
// more than half the counter's range past it.
self.quiet_until
.is_none_or(|until| now.wrapping_sub(until) < u64::MAX / 2)
}
/// A wait that began at `now` found the lock still held at its end.
pub fn outlasted(&mut self, now: u64, per_micro: u64) {
self.quiet_until = Some(now.wrapping_add(per_micro * WAIT_BACKOFF_MICROS));
}
}
impl Device {
/// Whether it delivered input within [`ACTIVE_SECONDS`] of `now`.
pub fn active(&self, now: u64, per_micro: u64) -> bool {
now.wrapping_sub(self.active) < per_micro * 1_000_000 * ACTIVE_SECONDS
}
/// The ticks between its polls at `now`.
pub fn interval(&self, now: u64, per_micro: u64) -> u64 {
let millis = per_micro * 1000;
let spaced = self.cost.saturating_mul(COST_SHARE);
if self.active(now, per_micro) {
spaced.min(millis * ACTIVE_MILLIS)
} else {
spaced.clamp(millis * IDLE_MILLIS, millis * SLOW_MILLIS)
}
}
/// What `turn` does with this device at `now`.
pub fn plan(&self, now: u64, per_micro: u64, turn: &mut Turn, waits: &Waits) -> Plan {
let since = now.wrapping_sub(self.looked);
let interval = self.interval(now, per_micro);
if since < interval {
return Plan::Later;
}
let late = since - interval;
let wait = late >= per_micro * LATE_WAIT_MICROS
&& !turn.waited
&& turn.wait_micros != 0
&& waits.allowed(now);
if wait {
turn.waited = true;
}
Plan::Poll {
late,
wait_micros: if wait { turn.wait_micros } else { 0 },
}
}
/// A poll at `now` took `took` ticks inside the lock and `delivered`
/// input or not: the gap since its last delivery, when it delivered
/// within [`GAP_MILLIS`] of it.
pub fn polled(&mut self, now: u64, took: u64, delivered: bool, per_micro: u64) -> Option<u64> {
self.looked = now;
if !delivered {
self.cost = self.cost - self.cost / 8 + took / 8;
return None;
}
self.active = now;
let gap = self
.delivered
.map(|at| now.wrapping_sub(at))
.filter(|gap| *gap < per_micro * 1000 * GAP_MILLIS);
self.delivered = Some(now);
gap
}
}
/// The upper bounds of [`Spread`]'s buckets, in microseconds; the last
/// bucket is open.
const BOUNDS_US: [u64; 11] = [
125, 250, 500, 1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000,
];
/// How a set of times spread, kept as counts in doubling buckets.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Spread {
counts: [u32; BOUNDS_US.len() + 1],
max_us: u64,
}
impl Spread {
pub fn add(&mut self, us: u64) {
let bucket = BOUNDS_US
.iter()
.position(|bound| us <= *bound)
.unwrap_or(BOUNDS_US.len());
self.counts[bucket] = self.counts[bucket].saturating_add(1);
self.max_us = self.max_us.max(us);
}
pub fn count(&self) -> u64 {
self.counts.iter().map(|count| u64::from(*count)).sum()
}
/// The time at or below which `percent` of the times lie: the upper
/// bound of the bucket that holds that rank, or the largest time when
/// that is smaller or the bucket is the open one. `None` when empty.
pub fn percentile(&self, percent: u64) -> Option<u64> {
let count = self.count();
if count == 0 {
return None;
}
let rank = (count * percent.min(100)).div_ceil(100).max(1);
let mut seen = 0;
for (bucket, n) in self.counts.iter().enumerate() {
seen += u64::from(*n);
if seen >= rank {
let bound = BOUNDS_US.get(bucket).copied().unwrap_or(u64::MAX);
return Some(bound.min(self.max_us));
}
}
Some(self.max_us)
}
}
/// `p50+p95+max` in microseconds, `-` when empty.
impl core::fmt::Display for Spread {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match (self.percentile(50), self.percentile(95)) {
(Some(median), Some(high)) => write!(f, "{median}+{high}+{}", self.max_us),
_ => f.write_str("-"),
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,372 @@
extern crate std;
use super::*;
use std::string::ToString;
/// A 24 MHz counter, as `stela-boot`'s corrected count.
const PER_MICRO: u64 = 24;
const fn us(micros: u64) -> u64 {
micros * PER_MICRO
}
const fn ms(millis: u64) -> u64 {
us(millis * 1000)
}
/// A device last polled at `looked` that last delivered at `active`, with
/// looks costing `cost` ticks.
fn device(looked: u64, active: u64, cost: u64) -> Device {
Device {
looked,
active,
cost,
delivered: None,
}
}
/// A time long after any delivery: the device is idle there.
const IDLE: u64 = ms(60_000);
#[test]
fn an_idle_device_is_polled_at_most_every_idle_millis() {
let idle = device(IDLE, 0, us(2));
assert_eq!(idle.interval(IDLE, PER_MICRO), ms(IDLE_MILLIS));
let mut turn = Turn::new(WAIT_MICROS);
let waits = Waits::default();
assert_eq!(
idle.plan(IDLE + ms(IDLE_MILLIS) - 1, PER_MICRO, &mut turn, &waits),
Plan::Later
);
assert_eq!(
idle.plan(IDLE + ms(IDLE_MILLIS), PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: 0,
wait_micros: 0
}
);
}
#[test]
fn costly_looks_space_polls_within_their_bounds() {
// An empty look that costs a millisecond (a hypervisor's port read).
let costly = device(IDLE, 0, ms(1));
assert_eq!(costly.interval(IDLE, PER_MICRO), ms(COST_SHARE));
let ruinous = device(IDLE, 0, ms(100));
assert_eq!(ruinous.interval(IDLE, PER_MICRO), ms(SLOW_MILLIS));
// Active, the same looks are spaced no more than ACTIVE_MILLIS apart,
// and cheap ones not at all.
let active = device(IDLE, IDLE, ms(100));
assert_eq!(active.interval(IDLE, PER_MICRO), ms(ACTIVE_MILLIS));
let cheap = device(IDLE, IDLE, us(2));
assert_eq!(cheap.interval(IDLE, PER_MICRO), us(64));
}
#[test]
fn the_reads_that_delivered_input_do_not_slow_the_device() {
// A touchpad behind an interrupt pin: a pin read costs 2 us, a report's
// read 750 us. Counting the reports held it to one read every 24 ms.
let mut pad = Device::default();
let mut now = IDLE;
for _ in 0..16 {
pad.polled(now, us(2), false, PER_MICRO);
now += ms(1);
}
for _ in 0..64 {
pad.polled(now, us(750), true, PER_MICRO);
now += ms(8);
}
assert!(pad.active(now, PER_MICRO));
assert!(
pad.interval(now, PER_MICRO) <= us(64),
"{}",
pad.interval(now, PER_MICRO)
);
// Empty looks that cost as much do slow it, as before.
for _ in 0..64 {
pad.polled(now, us(750), false, PER_MICRO);
now += ms(1);
}
assert!(pad.interval(now, PER_MICRO) >= ms(20));
}
#[test]
fn a_due_poll_waits_only_once_late_and_once_a_turn() {
let waits = Waits::default();
let looked = ms(1000);
let pad = device(looked, looked, 0);
let other = device(looked, looked, 0);
// Due but not yet late enough: only a try.
let mut turn = Turn::new(WAIT_MICROS);
let early = looked + us(LATE_WAIT_MICROS) - 1;
assert_eq!(
pad.plan(early, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: early - looked,
wait_micros: 0
}
);
// Late: the first device of the turn waits, the next only tries.
let late = looked + us(LATE_WAIT_MICROS);
let mut turn = Turn::new(WAIT_MICROS);
assert_eq!(
pad.plan(late, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: WAIT_MICROS
}
);
assert_eq!(
other.plan(late, PER_MICRO, &mut turn, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: 0
}
);
// A step's turn waits less.
let mut step = Turn::new(wait_micros(true));
assert_eq!(
pad.plan(late, PER_MICRO, &mut step, &waits),
Plan::Poll {
late: us(LATE_WAIT_MICROS),
wait_micros: STEP_WAIT_MICROS
}
);
}
#[test]
fn a_wait_the_holder_outlasted_is_not_tried_again_for_the_backoff() {
let looked = ms(1000);
let pad = device(looked, looked, 0);
let mut waits = Waits::default();
let late = looked + ms(3);
waits.outlasted(late, PER_MICRO);
let mut turn = Turn::new(WAIT_MICROS);
let within = late + us(WAIT_BACKOFF_MICROS) - 1;
assert!(matches!(
pad.plan(within, PER_MICRO, &mut turn, &waits),
Plan::Poll { wait_micros: 0, .. }
));
let after = late + us(WAIT_BACKOFF_MICROS);
assert!(matches!(
pad.plan(after, PER_MICRO, &mut turn, &waits),
Plan::Poll {
wait_micros: WAIT_MICROS,
..
}
));
}
#[test]
fn the_backoff_holds_across_the_counters_wrap() {
let mut waits = Waits::default();
let at = u64::MAX - us(100);
waits.outlasted(at, PER_MICRO);
assert!(!waits.allowed(at.wrapping_add(us(WAIT_BACKOFF_MICROS) - 1)));
assert!(waits.allowed(at.wrapping_add(us(WAIT_BACKOFF_MICROS))));
}
#[test]
fn gaps_count_only_within_a_motion() {
let mut pad = Device::default();
let start = ms(10_000);
assert_eq!(pad.polled(start, 0, true, PER_MICRO), None);
assert_eq!(pad.polled(start + ms(8), 0, true, PER_MICRO), Some(ms(8)));
// An empty poll between keeps the gap from the last delivery.
assert_eq!(pad.polled(start + ms(12), 0, false, PER_MICRO), None);
assert_eq!(pad.polled(start + ms(16), 0, true, PER_MICRO), Some(ms(8)));
// A pause between two motions is no gap.
assert_eq!(
pad.polled(start + ms(16 + GAP_MILLIS), 0, true, PER_MICRO),
None
);
}
#[test]
fn a_spread_reports_bucket_bounds_and_its_largest_time() {
let mut spread = Spread::default();
assert_eq!(spread.percentile(50), None);
assert_eq!(spread.to_string(), "-");
for _ in 0..90 {
spread.add(700);
}
for _ in 0..9 {
spread.add(3000);
}
spread.add(31_000);
assert_eq!(spread.count(), 100);
assert_eq!(spread.percentile(50), Some(1000));
assert_eq!(spread.percentile(95), Some(4000));
assert_eq!(spread.percentile(100), Some(31_000));
assert_eq!(spread.to_string(), "1000+4000+31000");
// A bound above every time is the largest time; the open bucket too.
let mut one = Spread::default();
one.add(9);
assert_eq!(one.to_string(), "9+9+9");
let mut huge = Spread::default();
huge.add(500_000);
assert_eq!(huge.percentile(50), Some(500_000));
}
/// A fake host-drivers lock: the GPUs' pump runs Linux in steps of
/// `step_us`, `steps` of them every `period_us`, and one step of `long_us`
/// at the start of every second. A waiter spinning for the lock is let in
/// at the end of the step in progress. `None` while free, else the end of
/// the step that holds it.
#[derive(Clone, Copy)]
struct Pump {
period_us: u64,
steps: u64,
step_us: u64,
long_us: u64,
}
impl Pump {
fn holds(&self, now: u64) -> Option<u64> {
let second = now - now % ms(1000);
if now - second < us(self.long_us) {
return Some(second + us(self.long_us));
}
let start = now - now % us(self.period_us);
let into = now - start;
(into < us(self.steps * self.step_us))
.then(|| start + (into / us(self.step_us) + 1) * us(self.step_us))
}
}
/// What a touchpad behind an interrupt pin gave the guest over a run.
struct Outcome {
reports: u64,
read: u64,
/// From a report's readiness to its read.
latency: Spread,
gaps: Spread,
spun_us: u64,
}
/// Run service turns every `turn_us` for `seconds` against `pump`, with a
/// touchpad that has a report ready every `report_us`: its pin read costs
/// 2 us and a report's read 750 us.
fn run(pump: Pump, turn_us: u64, report_us: u64, seconds: u64) -> Outcome {
let mut pad = Device::default();
let mut waits = Waits::default();
let mut outcome = Outcome {
reports: 0,
read: 0,
latency: Spread::default(),
gaps: Spread::default(),
spun_us: 0,
};
// The next report not yet read.
let mut next_report = us(report_us);
let end = ms(seconds * 1000);
let mut now = us(turn_us);
while now < end {
let mut turn = Turn::new(WAIT_MICROS);
if let Plan::Poll { wait_micros, .. } = pad.plan(now, PER_MICRO, &mut turn, &waits) {
let entered = match pump.holds(now) {
None => Some(now),
Some(step_end) if wait_micros != 0 => {
if step_end - now <= us(wait_micros) {
outcome.spun_us += (step_end - now) / PER_MICRO;
Some(step_end)
} else {
outcome.spun_us += wait_micros;
waits.outlasted(now, PER_MICRO);
None
}
}
Some(_) => None,
};
if let Some(at) = entered {
let mut delivered = false;
while next_report <= at {
outcome.latency.add((at - next_report) / PER_MICRO);
outcome.read += 1;
next_report += us(report_us);
delivered = true;
}
let took = if delivered { us(750) } else { us(2) };
if let Some(gap) = pad.polled(now, took, delivered, PER_MICRO) {
outcome.gaps.add(gap / PER_MICRO);
}
}
}
now += us(turn_us);
}
outcome.reports = end / us(report_us);
outcome
}
const FREE: Pump = Pump {
period_us: 1000,
steps: 0,
step_us: 1,
long_us: 0,
};
#[test]
fn a_free_lock_reads_every_report_within_a_turn() {
let outcome = run(FREE, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(95).unwrap() <= 500);
assert_eq!(outcome.gaps.percentile(50), Some(8000));
assert_eq!(outcome.spun_us, 0);
}
#[test]
fn a_busy_pump_in_short_steps_leaves_reads_at_the_reports_rate() {
// Half the time held, in Linux steps of 250 us, the pump's own mean.
let pump = Pump {
period_us: 2000,
steps: 4,
step_us: 250,
long_us: 0,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(95).unwrap() <= 2000);
assert!(outcome.gaps.percentile(95).unwrap() <= 16000);
// Rate: at least 120 reads a second over the run.
assert!(outcome.read >= 1200, "{}", outcome.read);
}
#[test]
fn a_long_linux_step_is_waited_for_a_few_times_not_spun_through() {
// The pump held three fifths of the time in 250 us steps, as in the
// busiest tenth of the logs' windows, and one 25 ms Linux step a second,
// which nothing can shorten.
let pump = Pump {
period_us: 2500,
steps: 6,
step_us: 250,
long_us: 25_000,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(50).unwrap() <= 1000);
assert!(outcome.latency.percentile(95).unwrap() <= 2000);
let short = run(Pump { long_us: 0, ..pump }, 500, 8000, 10);
// The short steps cost the turns' waits little, and each long step
// at most four outlasted waits of WAIT_MICROS, one per backoff.
assert!(short.spun_us <= 10 * 20_000, "{}", short.spun_us);
let long = outcome.spun_us - short.spun_us;
assert!(long <= 10 * 4 * WAIT_MICROS, "{long}");
}
#[test]
fn a_lock_held_nine_tenths_still_gives_every_report_at_a_bounded_spin() {
// 900 us steps with 100 us free between: tries mostly fail, and a late
// poll waits out about half a step. Every report is still read within
// a few milliseconds, at about a quarter of an idle PE's time.
let pump = Pump {
period_us: 1000,
steps: 1,
step_us: 900,
long_us: 0,
};
let outcome = run(pump, 500, 8000, 10);
assert!(outcome.read + 1 >= outcome.reports);
assert!(outcome.latency.percentile(50).unwrap() <= 2000);
assert!(outcome.latency.percentile(95).unwrap() <= 4000);
assert!(outcome.spun_us <= 10 * 300_000, "{}", outcome.spun_us);
}
+1
View File
@@ -80,6 +80,7 @@ pub mod host_resources;
pub mod host_samples;
pub mod host_speed;
pub mod hpet;
pub mod input_pace;
pub mod install_caution;
pub mod install_mode;
pub mod install_progress;
+60 -83
View File
@@ -5,23 +5,24 @@
//! Their drivers reach registers and DMA pages through the loader's
//! identity root, as the storage services do, so each poll runs in that
//! root (`storage::RestoreRoot`). The guest sees an input change at
//! its peripheral's next interrupt poll after the slice it arrived in. A
//! device that gave no input for a few seconds is polled every
//! [`IDLE_MILLIS`], so its first input waits that long. A device whose
//! polls cost more than a [`COST_SHARE`]th of that is polled as much less
//! often, but at most [`SLOW_MILLIS`] apart when idle and [`ACTIVE_MILLIS`]
//! when active, which bound its first input's wait while the host drivers'
//! lock is free. A posted GPU call is pumped between devices
//! its peripheral's next interrupt poll after the slice it arrived in.
//! When each device is polled is `stela_boot_core::input_pace`'s: at every
//! turn while it gives input, at most every `IDLE_MILLIS` after a few
//! seconds without, and further apart when its empty looks are costly
//! (`COST_SHARE`). A posted GPU call is pumped between devices
//! (`gpu::pump_posted`).
//!
//! No call waits for the host drivers' lock for longer than
//! [`STARVED_WAIT_MICROS`]: the turn may be a step of a PE that runs guest
//! code, and another processor can hold the lock for longer than one exit
//! may take. A poll, an LED change or a stopped device's removal that finds
//! the lock busy stays due for the next turn. A device holds its input
//! meanwhile as far as its hardware does: a USB device one report in its
//! queued transfer and what it keeps itself behind the endpoint's NAKs, a
//! PS/2 device its own buffer behind the controller's.
//! A poll that finds the host drivers' lock taken tries again at the next
//! turn, and once it is `LATE_WAIT_MICROS` late spins for it as a waiter
//! the GPUs' pump lets in after its Linux step, for the turn's
//! `input_pace::wait_micros` at most: the turn may be a step of a PE that
//! runs guest code, and another processor can hold the lock for longer than
//! one exit may take. An LED change or a stopped device's removal that
//! finds the lock busy stays due for the next turn. A device holds its
//! input meanwhile as far as its hardware does: a USB device one report in
//! its queued transfer and what it keeps itself behind the endpoint's NAKs,
//! a PS/2 device its own buffer behind the controller's, an I2C device its
//! report behind its asserted interrupt pin.
//!
//! Each device's first polling and LED failure is reported once. A device
//! that stops is reported and dropped, so re-plugged keyboards do not pile
@@ -38,6 +39,7 @@
use super::storage::{Inputs, RestoreRoot};
use crate::output;
use alloc::vec::Vec;
use stela_boot_core::input_pace::{self, Plan, Spread};
use stela_boot_core::options::GuestTrackpad;
use stela_drivers::input::{HeldInputs, Input, InputDevice, multitouch::Surface};
use stela_soc::machine::AppleDevices;
@@ -70,13 +72,8 @@ struct Reported {
last_failure: Option<alloc::string::String>,
/// The keyboard LEDs last wanted have not reached the device yet.
leds_due: bool,
/// The counter when the device was last polled, and when a poll last
/// found input.
looked: u64,
active: u64,
/// Its polls' recent cost in counter ticks, without lock waits: an
/// eighth of each poll joins seven eighths of the last.
cost: u64,
/// When it is polled ([`input_pace::Device`]).
pace: input_pace::Device,
/// Its polls since the last [`TIMES_SECONDS`] report.
times: Times,
/// For an i8042: its bytes read and dropped at the last report, and
@@ -105,44 +102,15 @@ struct Times {
skipped: u64,
/// The inputs its polls gave the guest.
delivered: u64,
/// How late each poll ran after it was due, its lock wait included, in
/// microseconds, and the gaps between its deliveries within a motion.
late: Spread,
gap: Spread,
}
/// How often the input devices' poll times are reported.
const TIMES_SECONDS: u64 = 10;
/// How often an idle device is polled. A poll can be a port or register
/// access a hypervisor takes to its device model, which waits there for
/// the model's lock, and the boot PE serves the host between slices of
/// guest code, holding back its guest, the devices' deadlines and the GPUs'
/// work. A device holds what arrives meanwhile: a USB device in its
/// transfer, a PS/2 device in its own buffer while the controller's is
/// full. USB low-speed keyboards and mice are polled as rarely.
const IDLE_MILLIS: u64 = 8;
/// How long a busy host-drivers lock may leave a due device unpolled before
/// a poll waits for the lock, for [`STARVED_WAIT_MICROS`] at most. A disk
/// command can hold it for tens of milliseconds; below this a due device is
/// polled at the next turn the lock is free.
const STARVED_MILLIS: u64 = 32;
/// How long a turn waits for the host drivers' lock for a device unpolled
/// past [`STARVED_MILLIS`], once for all its devices: about a service
/// step's length. The wait shows a holder that works in steps (the GPUs'
/// pump) that the lock is wanted, so it lets go at its next step; a holder
/// that keeps it longer leaves the poll due for the next turn.
const STARVED_WAIT_MICROS: u64 = 1000;
/// How long a device is polled at every service turn after it last gave
/// input, so a pointer's motion keeps its full rate.
const ACTIVE_SECONDS: u64 = 5;
/// A device's polls may take at most one part in this of the boot PE: a
/// poll costing more is spaced this many times its cost apart. A port read
/// that costs a microsecond on hardware can wait milliseconds for a
/// hypervisor's device-model lock; the boot PE's time is the guest's.
const COST_SHARE: u64 = 32;
/// The longest an idle device waits for its next poll however costly its
/// polls are, which its first input can wait.
const SLOW_MILLIS: u64 = 250;
/// The longest an active device waits for its next poll.
const ACTIVE_MILLIS: u64 = 32;
pub struct HostInput {
inputs: Inputs,
/// What was reported of each of `inputs.devices`, in the same order.
@@ -155,6 +123,8 @@ pub struct HostInput {
wanted_leds: Option<u8>,
/// The counter at the last poll-time report.
reported_times: u64,
/// The polls' waits for the host drivers' lock across turns.
waits: input_pace::Waits,
/// What each device holds down, released when it stops.
held: HeldInputs,
/// The next device's identity.
@@ -197,6 +167,7 @@ impl HostInput {
leds: None,
wanted_leds: None,
reported_times: 0,
waits: input_pace::Waits::default(),
held: HeldInputs::new(),
touch_frames: false,
trackpad_surface: false,
@@ -334,9 +305,11 @@ impl HostInput {
/// Read the host's input devices, without the guest's devices, in the
/// order probe found them. The guest's lock-key LEDs reach each host
/// keyboard first, as Linux `hidinput_led_worker` sends an input
/// device's LED changes.
/// device's LED changes. `step` when the turn is a step of a PE that
/// runs guest code, which waits for the lock least.
pub fn read(
&mut self,
step: bool,
#[cfg(feature = "diagnostics")] turn: &mut super::service::InputTurn,
) -> Vec<Input> {
if let Some(leds) = self.wanted_leds
@@ -380,27 +353,20 @@ impl HostInput {
let mut pending = Vec::new();
let mut stopped = false;
let now = super::host::fresh_counter();
let millis = super::host::COUNTER_HZ / 1000;
let starved = millis * STARVED_MILLIS;
// Whether this turn may still wait for the lock.
let mut may_wait = true;
let per_micro = super::host::COUNTER_HZ / 1_000_000;
// This turn's one wait for the lock.
let mut turn = input_pace::Turn::new(input_pace::wait_micros(step));
for (device, reported) in self.inputs.devices.iter_mut().zip(&mut self.reported) {
// A stopped device a busy lock kept from being dropped.
if device.stopped() {
stopped = true;
continue;
}
let active =
now.wrapping_sub(reported.active) < super::host::COUNTER_HZ * ACTIVE_SECONDS;
let interval = if active {
(reported.cost * COST_SHARE).min(millis * ACTIVE_MILLIS)
} else {
(reported.cost * COST_SHARE).clamp(millis * IDLE_MILLIS, millis * SLOW_MILLIS)
};
let since = now.wrapping_sub(reported.looked);
if since < interval {
let Plan::Poll { late, wait_micros } =
reported.pace.plan(now, per_micro, &mut turn, &self.waits)
else {
continue;
}
};
let before = pending.len();
let entering = super::host::fresh_counter();
let entered;
@@ -408,13 +374,17 @@ impl HostInput {
// SAFETY: the loader root `storage::open` captured, which
// maps this device.
let root = unsafe {
if since >= interval + starved && core::mem::take(&mut may_wait) {
RestoreRoot::enter_within(self.inputs.root, STARVED_WAIT_MICROS)
if wait_micros != 0 {
RestoreRoot::enter_within(self.inputs.root, wait_micros)
} else {
RestoreRoot::try_enter(self.inputs.root)
}
};
let Some(_root) = root else {
if wait_micros != 0 {
self.waits
.outlasted(super::host::fresh_counter(), per_micro);
}
reported.times.skipped += 1;
continue;
};
@@ -432,11 +402,13 @@ impl HostInput {
times.longest_wait = times.longest_wait.max(waited);
times.polled += took;
times.longest_poll = times.longest_poll.max(took);
reported.cost = reported.cost - reported.cost / 8 + took / 8;
reported.looked = now;
reported.times.delivered += pending.len().saturating_sub(before) as u64;
if pending.len() != before {
reported.active = now;
times.late.add((late + waited) / per_micro);
let delivered = pending.len() != before;
if let Some(gap) = reported.pace.polled(now, took, delivered, per_micro) {
times.gap.add(gap / per_micro);
}
times.delivered += pending.len().saturating_sub(before) as u64;
if delivered {
// A laptop's own keyboard or touchpad lights a panel the
// lid darkened, whatever its `_LID` reads (`--lid method`).
if built_in(device) && super::lid::built_in_input() == Some(false) {
@@ -473,11 +445,14 @@ impl HostInput {
}
/// `INPUT TIMES name:polls/waited_us/longest_wait_us/polled_us/
/// longest_poll_us/skipped/delivered[/read=K+M/dropped=D] …`: each
/// device's polls since the last report, the host-drivers lock waits
/// before them, their own time, the inputs they gave the guest, and for
/// an i8042 the bytes read from its keyboard and mouse ports and the
/// bytes dropped since the last report.
/// longest_poll_us/skipped/delivered/late=P50+P95+MAX/gap=P50+P95+MAX
/// [/read=K+M/dropped=D] …`: each device's polls since the last report,
/// the host-drivers lock waits before them, their own time, the turns a
/// busy lock skipped it, the inputs they gave the guest, how late its
/// polls ran after they were due and the gaps between its deliveries
/// within a motion (in microseconds; a percentile is its bucket's upper
/// bound, `-` for none), and for an i8042 the bytes read from its
/// keyboard and mouse ports and the bytes dropped since the last report.
fn report_times(&mut self) {
let micros = |ticks: u64| ticks / (super::host::COUNTER_HZ / 1_000_000);
let mut line = alloc::string::String::from("INPUT TIMES");
@@ -486,7 +461,7 @@ impl HostInput {
let _ = core::fmt::Write::write_fmt(
&mut line,
format_args!(
" {}:{}/{}/{}/{}/{}/{}/{}",
" {}:{}/{}/{}/{}/{}/{}/{}/late={}/gap={}",
device.name().replace(' ', "_"),
t.polls,
micros(t.waited),
@@ -495,6 +470,8 @@ impl HostInput {
micros(t.longest_poll),
t.skipped,
t.delivered,
t.late,
t.gap,
),
);
if let Some(counters) = device.ps2_counters() {
+1
View File
@@ -333,6 +333,7 @@ impl Service {
input_turn.usb_done = host::rdtsc();
}
let inputs = input.read(
step,
#[cfg(feature = "diagnostics")]
&mut input_turn,
);