use serde::Serialize;
use sew_noise::probe::{self as raw, ProbeHandle, Quantiles};
use super::{
CaptureDspSched, CaptureDspSchedFallback, CaptureDspSchedMode, NoiseRemovalControl,
NoiseRemovalState,
};
pub type CoreNumber = fn() -> Option<u32>;
pub const SCHEMA: &str = "sew-noise-probe/2";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NoiseProbePhase {
Default,
TimeConstraint,
Unscheduled,
ShortDeadline,
}
impl NoiseProbePhase {
pub const ALL: [Self; 4] = [
Self::Default,
Self::TimeConstraint,
Self::Unscheduled,
Self::ShortDeadline,
];
pub const fn letter(self) -> &'static str {
match self {
Self::Default => "a",
Self::TimeConstraint => "b",
Self::Unscheduled => "c",
Self::ShortDeadline => "d",
}
}
pub const fn available(self) -> bool {
matches!(self, Self::Default) || super::hook::DSP_SCHED
}
pub const fn sched(self) -> CaptureDspSched {
CaptureDspSched::new(match self {
Self::Default => CaptureDspSchedMode::Workgroup,
Self::TimeConstraint => CaptureDspSchedMode::TimeConstraintOnly,
Self::Unscheduled => CaptureDspSchedMode::None,
Self::ShortDeadline => CaptureDspSchedMode::OwnWorkgroup,
})
}
pub const fn of_mode(mode: CaptureDspSchedMode) -> NoiseProbePhase {
match mode {
CaptureDspSchedMode::TimeConstraintOnly => Self::TimeConstraint,
CaptureDspSchedMode::None => Self::Unscheduled,
CaptureDspSchedMode::OwnWorkgroup => Self::ShortDeadline,
_ => Self::Default,
}
}
const fn id(self) -> u8 {
match self {
Self::Default => 0,
Self::TimeConstraint => 1,
Self::Unscheduled => 2,
Self::ShortDeadline => 3,
}
}
fn from_id(id: u8) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.id() == id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum NoiseProbeError {
#[error("no probed call is running")]
NotProbing,
#[error("probe phase {} is not available in this build", .0.letter())]
PhaseUnavailable(NoiseProbePhase),
}
pub(super) struct Run {
call: u64,
handle: ProbeHandle,
current: NoiseProbePhase,
ended: Vec<(NoiseProbePhase, NoiseRemovalState)>,
deadlines: Vec<(NoiseProbePhase, u64)>,
call_ended: bool,
}
#[derive(Default)]
pub(super) struct Slot {
armed: Option<CoreNumber>,
run: Option<Run>,
}
impl Slot {
pub(super) fn take_armed(&mut self) -> Option<CoreNumber> {
self.armed.take()
}
pub(super) fn started(&mut self, call: u64, handle: ProbeHandle) {
self.run = Some(Run {
call,
handle,
current: NoiseProbePhase::Default,
ended: Vec::new(),
deadlines: Vec::new(),
call_ended: false,
});
}
pub(super) fn runs(&self, call: u64) -> bool {
self.run
.as_ref()
.is_some_and(|r| r.call == call && !r.call_ended)
}
pub(super) fn ended(&mut self, call: u64, state: NoiseRemovalState) {
if let Some(run) = self
.run
.as_mut()
.filter(|r| r.call == call && !r.call_ended)
{
run.ended.push((run.current, state));
run.call_ended = true;
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeSched {
pub requested: CaptureDspSchedMode,
pub effective: CaptureDspSchedMode,
pub fallback: Option<CaptureDspSchedFallback>,
pub period_us: Option<u32>,
pub computation_us: Option<u32>,
pub constraint_us: Option<u32>,
pub interval_deadline_us: Option<u32>,
pub intervals: u64,
}
impl NoiseProbeSched {
fn of(state: &NoiseRemovalState) -> Option<NoiseProbeSched> {
Some(NoiseProbeSched {
requested: state.capture_stage_dsp_sched_requested?,
effective: state.capture_stage_dsp_sched_effective?,
fallback: state.capture_stage_dsp_sched_fallback,
period_us: state.capture_stage_dsp_period_us,
computation_us: state.capture_stage_dsp_computation_us,
constraint_us: state.capture_stage_dsp_constraint_us,
interval_deadline_us: state.capture_stage_dsp_interval_deadline_us,
intervals: state.capture_stage_dsp_intervals,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeTimes {
pub n: u64,
pub p50_ns: u64,
pub p99_ns: u64,
pub max_ns: u64,
}
impl From<Quantiles> for NoiseProbeTimes {
fn from(q: Quantiles) -> Self {
Self {
n: q.n,
p50_ns: q.p50_ns,
p99_ns: q.p99_ns,
max_ns: q.max_ns,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeCore {
pub core: u32,
pub blocks: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbePhaseReport {
pub phase: NoiseProbePhase,
pub letter: &'static str,
pub deadline_us: Option<u64>,
pub blocks: u64,
pub left_out: u64,
pub model_blocks: u64,
pub erb_blocks: u64,
pub df_blocks: u64,
pub strong_out_blocks: u64,
pub stage_wall: NoiseProbeTimes,
pub stage_cpu: Option<NoiseProbeTimes>,
pub full_wall: NoiseProbeTimes,
pub full_cpu: Option<NoiseProbeTimes>,
pub k1_wall: NoiseProbeTimes,
pub k1_cpu: Option<NoiseProbeTimes>,
pub k2_wall: NoiseProbeTimes,
pub k2_cpu: Option<NoiseProbeTimes>,
pub cores: Vec<NoiseProbeCore>,
pub core_unknown: u64,
pub state: Option<NoiseRemovalState>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeBlock {
pub phase: Option<&'static str>,
pub wall_ns: u32,
pub cpu_ns: Option<u32>,
pub core: Option<u32>,
pub model: bool,
pub erb: bool,
pub df: bool,
pub strong_out: bool,
pub left_out: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeLoops {
pub k1_passes: usize,
pub k1_floats: usize,
pub k1_every_blocks: u64,
pub k2_floats: usize,
pub k2_every_blocks: u64,
}
impl NoiseProbeLoops {
const NOW: Self = Self {
k1_passes: raw::CACHE_LOOP_PASSES,
k1_floats: raw::CACHE_LOOP_FLOATS,
k1_every_blocks: raw::CACHE_LOOP_EVERY,
k2_floats: raw::MEMORY_LOOP_FLOATS,
k2_every_blocks: raw::MEMORY_LOOP_EVERY,
};
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeReport {
pub schema: &'static str,
pub os: &'static str,
pub arch: &'static str,
pub call_ended: bool,
pub phase: NoiseProbePhase,
pub letter: &'static str,
pub dsp_sched: Option<NoiseProbeSched>,
pub loops: NoiseProbeLoops,
pub blocks: u64,
pub dropped: u64,
pub cpu_clock: bool,
pub phases: Vec<NoiseProbePhaseReport>,
pub first_blocks: Vec<NoiseProbeBlock>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct NoiseProbeReference {
pub schema: &'static str,
pub loops: NoiseProbeLoops,
pub spin_ms: u64,
pub core_start: Option<u32>,
pub core_end: Option<u32>,
pub k1_wall: NoiseProbeTimes,
pub k1_cpu: Option<NoiseProbeTimes>,
pub k2_wall: NoiseProbeTimes,
pub k2_cpu: Option<NoiseProbeTimes>,
}
pub fn reference(core: Option<CoreNumber>) -> NoiseProbeReference {
let r = raw::reference(core.unwrap_or(default_core_number));
NoiseProbeReference {
schema: SCHEMA,
loops: NoiseProbeLoops::NOW,
spin_ms: u64::try_from(raw::REFERENCE_SPIN.as_millis()).unwrap_or(u64::MAX),
core_start: r.core_start,
core_end: r.core_end,
k1_wall: r.k1_wall.into(),
k1_cpu: r.k1_cpu.map(Into::into),
k2_wall: r.k2_wall.into(),
k2_cpu: r.k2_cpu.map(Into::into),
}
}
pub fn default_core_number() -> Option<u32> {
raw::core_number()
}
impl NoiseRemovalControl {
pub fn arm_probe(&self, core: Option<CoreNumber>) {
self.probe_slot().armed = Some(core.unwrap_or(default_core_number));
}
pub fn disarm_probe(&self) {
self.probe_slot().armed = None;
}
pub fn probe_armed(&self) -> bool {
self.probe_slot().armed.is_some()
}
pub fn probe_phase(&self) -> Option<NoiseProbePhase> {
let slot = self.probe_slot();
slot.run
.as_ref()
.filter(|r| !r.call_ended)
.map(|r| r.current)
}
#[deprecated(
note = "a call is one phase: set the scheduling before the call with set_dsp_sched; the report names the phase from the mode in effect"
)]
pub fn set_probe_phase(
&self,
phase: NoiseProbePhase,
deadline: Option<std::time::Duration>,
) -> Result<(), NoiseProbeError> {
if !phase.available() {
return Err(NoiseProbeError::PhaseUnavailable(phase));
}
let state = self.state();
let mut slot = self.probe_slot();
let run = slot
.run
.as_mut()
.filter(|r| !r.call_ended)
.ok_or(NoiseProbeError::NotProbing)?;
if run.current != phase {
run.ended.push((run.current, state));
run.current = phase;
run.handle.set_phase(phase.id());
}
let deadline = deadline
.filter(|_| phase == NoiseProbePhase::ShortDeadline)
.map(|d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX));
run.deadlines.retain(|(p, _)| *p != phase);
if let Some(us) = deadline {
run.deadlines.push((phase, us));
}
Ok(())
}
pub fn probe_report(&self) -> Option<NoiseProbeReport> {
let state = self.state();
let slot = self.probe_slot();
let run = slot.run.as_ref()?;
let r = run.handle.report();
let last = run.ended.last().map(|(_, s)| *s);
let sched = NoiseProbeSched::of(&if run.call_ended {
last.unwrap_or(state)
} else {
state
});
let call_phase = sched.map(|s| NoiseProbePhase::of_mode(s.effective));
let phases = r
.phases
.iter()
.map(|p| {
let marked = NoiseProbePhase::from_id(p.phase).unwrap_or(NoiseProbePhase::Default);
let running = !run.call_ended && run.current == marked;
let at_end = run
.ended
.iter()
.rev()
.find(|(ended, _)| *ended == marked)
.map(|(_, s)| *s);
let phase = call_phase.unwrap_or(marked);
NoiseProbePhaseReport {
phase,
letter: phase.letter(),
deadline_us: run
.deadlines
.iter()
.find(|(d, _)| *d == marked)
.map(|(_, us)| *us)
.or(sched.and_then(|s| s.interval_deadline_us.map(u64::from))),
blocks: p.blocks,
left_out: p.left_out,
model_blocks: p.model_blocks,
erb_blocks: p.erb_blocks,
df_blocks: p.df_blocks,
strong_out_blocks: p.strong_out_blocks,
stage_wall: p.stage_wall.into(),
stage_cpu: p.stage_cpu.map(Into::into),
full_wall: p.full_wall.into(),
full_cpu: p.full_cpu.map(Into::into),
k1_wall: p.k1_wall.into(),
k1_cpu: p.k1_cpu.map(Into::into),
k2_wall: p.k2_wall.into(),
k2_cpu: p.k2_cpu.map(Into::into),
cores: p
.cores
.iter()
.map(|c| NoiseProbeCore {
core: c.core,
blocks: c.blocks,
})
.collect(),
core_unknown: p.core_unknown,
state: if running { Some(state) } else { at_end },
}
})
.collect();
Some(NoiseProbeReport {
schema: SCHEMA,
os: std::env::consts::OS,
arch: std::env::consts::ARCH,
call_ended: run.call_ended,
phase: call_phase.unwrap_or(run.current),
letter: call_phase.unwrap_or(run.current).letter(),
dsp_sched: sched,
loops: NoiseProbeLoops::NOW,
blocks: r.blocks,
dropped: r.dropped,
cpu_clock: r.cpu_clock,
phases,
first_blocks: r
.first_blocks
.iter()
.map(|b| NoiseProbeBlock {
phase: call_phase
.or(NoiseProbePhase::from_id(b.phase))
.map(NoiseProbePhase::letter),
wall_ns: b.wall_ns,
cpu_ns: b.cpu_ns,
core: b.core,
model: b.model,
erb: b.erb,
df: b.df,
strong_out: b.strong_out,
left_out: b.left_out,
})
.collect(),
})
}
}