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
4 changes: 4 additions & 0 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ pub struct SchedulerSchema<A> {
/// The event signals a host periodic clock may drive inside the
/// scheduler's slots, in the order of its clock slots.
pub clocks: Vec<A>,
/// Per process kernel, the event signals it writes, as indices into
/// [`Self::events`]; empty for a kernel the scheduler does not run.
pub kernel_events: Vec<Vec<usize>>,
}

impl<A> SchedulerSchema<A> {
Expand All @@ -1069,6 +1072,7 @@ impl<A> SchedulerSchema<A> {
fallback: self.fallback,
events: self.events.into_iter().map(&mut map).collect(),
clocks: self.clocks.into_iter().map(map).collect(),
kernel_events: self.kernel_events,
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2072,6 +2072,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
fallback: Vec::new(),
events: Vec::new(),
clocks: Vec::new(),
kernel_events: Vec::new(),
});
// The runtime reads counters, the signals waits watch and staged
// nonblocking values directly; no unit loads a wait's signal.
Expand Down
22 changes: 22 additions & 0 deletions crates/celox-runtime/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ pub(crate) struct SchedulerRefs {
/// The event id and signal of each host clock the scheduler may run,
/// in the order of its clock slots.
pub(crate) clocks: Vec<(usize, SignalRef)>,
/// Per process kernel, the bits of `levels` of the events it writes.
pub(crate) kernel_events: Vec<u64>,
/// Per clock slot, the bit of `levels` of its event.
pub(crate) clock_events: Vec<u64>,
pub(crate) clock_next: SignalRef,
pub(crate) clock_period: SignalRef,
pub(crate) clock_value: SignalRef,
Expand Down Expand Up @@ -365,6 +369,24 @@ impl<B: SimBackend> ResolvedSchedule<B> {
.iter()
.map(|event| backend.resolve_event_opt(event).map(|event| event.id()))
.collect::<Option<_>>()?,
kernel_events: (0..scheduler.fallback.len())
.map(|index| {
scheduler
.kernel_events
.get(index)
.into_iter()
.flatten()
.fold(0, |mask, &bit| mask | 1 << bit)
})
.collect(),
clock_events: scheduler
.clocks
.iter()
.map(|clock| {
let bit = scheduler.events.iter().position(|event| event == clock)?;
Some(1 << bit)
})
.collect::<Option<_>>()?,
clocks: scheduler
.clocks
.iter()
Expand Down
31 changes: 24 additions & 7 deletions crates/celox-runtime/src/simulation/compiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,19 @@ impl<B: SimBackend> SimulationState<B> {
|| !pending.ready.is_empty()
|| !pending.inactive.is_empty()
|| !pending.nba_queue.is_empty()
|| pending
.waiters
.iter()
.any(|(process, _)| scheduler.waits.get(process).is_none_or(Option::is_none))
|| pending.waiters.iter().any(|(process, _)| {
scheduler.waits.get(process).is_none_or(Option::is_none)
|| self.writes_observed(scheduler, process)
})
{
return None;
}
let mut first = u64::MAX;
let mut other = u64::MAX;
for &Reverse((time, process)) in self.process_wakeups.iter() {
if scheduler.wake.get(process).is_some_and(Option::is_some) {
if scheduler.wake.get(process).is_some_and(Option::is_some)
&& !self.writes_observed(scheduler, process)
{
first = first.min(time);
} else {
other = other.min(time);
Expand All @@ -100,8 +102,10 @@ impl<B: SimBackend> SimulationState<B> {
let clocks = &self.scheduler.clocks;
let compiled = compiled_clocks(scheduler, queue, clocks);
for event in queue {
if clock_slot(scheduler, event, clocks).is_some_and(|bit| compiled >> bit & 1 != 0)
{
if clock_slot(scheduler, event, clocks).is_some_and(|bit| {
compiled >> bit & 1 != 0
&& scheduler.clock_events[bit] & self.observed_events == 0
}) {
first = first.min(event.time);
} else {
other = other.min(event.time);
Expand All @@ -126,6 +130,15 @@ impl<B: SimBackend> SimulationState<B> {
})
}

/// Whether `process` may change an event the host observes, so that
/// its slots run in the reference loop.
fn writes_observed(&self, scheduler: &SchedulerRefs, process: usize) -> bool {
scheduler
.kernel_events
.get(process)
.is_some_and(|&events| events & self.observed_events != 0)
}

/// Run the compiled scheduler for the slots up to `limit`. Returns, like
/// [`Self::step_until`], the time of the last slot run.
pub(super) fn run_compiled<E>(
Expand Down Expand Up @@ -393,6 +406,10 @@ impl<B: SimBackend> SimulationState<B> {
}
}
executor.try_finish_timed_step(now)?;
// What the host writes after the slot is an update of its time.
if executor.take_slot_writes() {
self.host_pending = true;
}
Ok(now)
}
}
17 changes: 17 additions & 0 deletions crates/celox-runtime/src/simulation/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,23 @@ pub trait HostBoundary: UnitExecutor {
output
}

/// Called in every round when its processes and scheduled values have
/// run and its flip-flop domains are about to evaluate: the round's
/// edges are in state, and no domain has committed. Returns whether the
/// host wrote state; the round then settles it before the domains read
/// it. Writes to signals a wait watches are logged as in
/// [`Self::take_host_writes`].
fn before_domains(&mut self, _timestamp: u64) -> Result<bool, Halt> {
Ok(false)
}

/// Whether the host wrote state in [`Self::try_finish_timed_step`]
/// since the last call. The writes are updates of that slot's time: the
/// next step settles them there.
fn take_slot_writes(&mut self) -> bool {
false
}

/// Snapshot external-component inputs immediately before an event domain
/// evaluates its sequential logic.
fn stage_external_event(
Expand Down
23 changes: 22 additions & 1 deletion crates/celox-runtime/src/simulation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub use wait::{Baseline, Waiter, Waiters};

use self::round::Round;
use crate::{
SimulatorErrorCode,
SignalRef, SimulatorErrorCode,
backend::SimBackend,
schedule::ResolvedSchedule,
scheduler::{Scheduler, SimEvent},
Expand Down Expand Up @@ -161,6 +161,10 @@ pub struct SimulationState<B: SimBackend> {
slot_passes: u64,
/// The loop that runs time slots, and the slots each loop ran.
stats: SchedulerStats,
/// The bits of the compiled scheduler's events whose changes the host
/// observes inside a slot: the kernels and host clocks that write them
/// run in the reference loop.
observed_events: u64,
}

impl<B: SimBackend> SimulationState<B> {
Expand Down Expand Up @@ -213,6 +217,7 @@ impl<B: SimBackend> SimulationState<B> {
return_budget: SLOT_RETURN_BUDGET,
slot_passes: 0,
stats: SchedulerStats::default(),
observed_events: 0,
};
state.stats.kernels = (0..state.model.processes.len())
.map(|index| match state.model.kernel_fallback.get(index) {
Expand Down Expand Up @@ -341,6 +346,22 @@ impl<B: SimBackend> SimulationState<B> {
&self.stats
}

/// The signals whose changes the host observes inside a time slot (see
/// [`HostBoundary::before_domains`]). The slots in which a kernel or
/// host clock of the compiled scheduler may change an observed event
/// signal run in the reference loop, where the host sees the change
/// before any domain commits; the other kernels' slots stay compiled.
pub fn set_observed_signals(&mut self, signals: impl IntoIterator<Item = SignalRef>) {
let Some(scheduler) = &self.model.scheduler else {
return;
};
self.observed_events = signals
.into_iter()
.filter_map(|signal| self.model.signal_to_id.get(&signal))
.filter_map(|event| scheduler.events.iter().position(|id| id == event))
.fold(0, |mask, bit| mask | 1 << bit);
}

/// [`Self::step_until`], showing the step to `observer`. An error of
/// the observer replaces the step's result.
pub fn step_until_observed<E, O>(
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-runtime/src/simulation/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,15 @@ impl<B: SimBackend> SimulationState<B> {
loop {
let mut any_new_outer_loop_trigger = false;
let mut newly_triggered = Vec::new();
// The host sees the wave's edges before its domains commit, and
// its writes are in state before they evaluate.
if executor.before_domains(current_time)? {
for (signal, value) in executor.take_host_writes() {
self.observe_host_write(signal, &value);
}
executor.eval_comb()?;
self.observe_driven(executor.backend());
}

loop {
let mut any_new_sequential_trigger = false;
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-runtime/src/simulation/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ impl<B: SimBackend> SimulationState<B> {
self.step_round(executor, current_time, Vec::new(), ready, false)?;
}
executor.try_finish_timed_step(current_time)?;
// What the host writes after the slot is an update of its time.
if executor.take_slot_writes() {
self.host_pending = true;
}
Ok(())
}

Expand Down
54 changes: 48 additions & 6 deletions crates/celox/examples/sched_bench.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Timed-scheduler overhead benchmark for instruction-count comparisons.
//!
//! Usage: `sched_bench <a|ac|b1|b5|bh|d|dr> <cycles> [default|reference|compiled] [native|interp]`
//! Usage: `sched_bench <a|ac|b1|b5|bh|d|dr> <cycles> [default|reference|compiled] [native|interp] [observe=<signal>]`
//!
//! Every variant clocks the same 64 registers `rK <= rK + (seed ^ K)`:
//!
Expand All @@ -17,7 +17,9 @@
//!
//! The optional third argument selects the timed scheduler (hidden builder
//! option), by default the library's; the fourth the backend, by default the
//! host's native one.
//! host's native one. With a fifth, `observe=<signal>`, a timed variant runs
//! with a slot observer that counts the changes of `<signal>` at the end of
//! every slot, as a VPI value-change callback does.
//!
//! The scheduler's cost per cycle is the difference of the whole-program
//! instruction counts of two runs, which cancels compilation:
Expand Down Expand Up @@ -138,10 +140,18 @@ fn main() {
Some(other) => panic!("unknown scheduler {other}: expected reference or compiled"),
};
let builder = celox::Simulation::from_sv_sources(sources, "Top").scheduler_mode(mode);
let observed = args
.get(5)
.map(|arg| arg.strip_prefix("observe=").expect("observe=<signal>"));
if interpreter {
run(builder.build_interpreter().unwrap(), variant, cycles)
run(
builder.build_interpreter().unwrap(),
variant,
cycles,
observed,
)
} else {
run(builder.build().unwrap(), variant, cycles)
run(builder.build().unwrap(), variant, cycles, observed)
}
};
println!("{variant} {cycles} out={out:?}");
Expand All @@ -159,12 +169,42 @@ fn tick<B: celox::SimBackend>(mut sim: celox::Simulator<B>, cycles: u64) -> celo
sim.get(out)
}

/// Counts the changes of one signal at the end of every slot.
struct Changes {
signal: celox::SignalRef,
last: Option<celox::BigUint>,
count: std::rc::Rc<std::cell::Cell<u64>>,
}

impl<B: celox::SimBackend> celox::SlotObserver<B> for Changes {
fn before_domains(&mut self, _: &mut celox::SlotIo<'_, B>, _: u64) {}

fn end_of_slot(&mut self, io: &mut celox::SlotIo<'_, B>, _: u64) {
let value = io.get(self.signal);
if self.last.as_ref() != Some(&value) {
self.count.set(self.count.get() + 1);
self.last = Some(value);
}
}
}

/// The timed variants: run `cycles` clock periods.
fn run<B: celox::SimBackend>(
mut sim: celox::Simulation<B>,
variant: &str,
cycles: u64,
observed: Option<&str>,
) -> celox::BigUint {
let changes = std::rc::Rc::new(std::cell::Cell::new(0));
if let Some(path) = observed {
let signal = sim.signal(path);
let observer = Changes {
signal,
last: None,
count: std::rc::Rc::clone(&changes),
};
sim.observe_slots(Box::new(observer), &[signal]);
}
if variant == "ac" {
let seed = sim.signal("seed");
sim.modify(|io| io.set(seed, 7u32)).unwrap();
Expand All @@ -179,8 +219,10 @@ fn run<B: celox::SimBackend>(
sim.run_until(cycles * 10).unwrap();
let stats = sim.scheduler_stats();
println!(
"compiled slots {}, kernels {:?}",
stats.compiled_slots, stats.kernels
"compiled slots {}, kernels {:?}, observed changes {}",
stats.compiled_slots,
stats.kernels,
changes.get()
);
let out = sim.signal("out");
sim.get(out)
Expand Down
2 changes: 1 addition & 1 deletion crates/celox/src/backend/native/image_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{fmt, path::Path};
use super::backend::NativeProgramImage;

const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI";
const CONTAINER_VERSION: u16 = 34;
const CONTAINER_VERSION: u16 = 35;
const TRAILER_SIZE: usize = 32;
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
Expand Down
50 changes: 49 additions & 1 deletion crates/celox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ mod host_api {
};
pub use crate::debug::CompilationTraceResult;
pub use crate::diagnostics::DiagnosticsOptions;
pub use crate::simulation::{Simulation, SimulationCheckpoint};
pub use crate::simulation::{Simulation, SimulationCheckpoint, SlotObserver};
#[cfg(any(
target_arch = "x86_64",
feature = "arm64-codegen",
Expand Down Expand Up @@ -169,6 +169,54 @@ mod host_api {
}
}

/// State access of a [`SlotObserver`] inside a time slot: reads see
/// the slot's state so far, writes are blocking writes of the host at
/// the slot's time.
pub struct SlotIo<'a, B: SimBackend = DefaultBackend> {
io: IOContext<'a, B>,
wrote: bool,
}

impl<'a, B: SimBackend> SlotIo<'a, B> {
pub(crate) fn new(io: IOContext<'a, B>) -> Self {
Self { io, wrote: false }
}

pub(crate) fn wrote(&self) -> bool {
self.wrote
}

/// The stored value, with X/Z bits as their payload.
pub fn get(&self, signal: crate::SignalRef) -> crate::BigUint {
self.io.backend.get(signal)
}

/// The stored payload and X/Z mask.
pub fn get_four_state(&self, signal: crate::SignalRef) -> (crate::BigUint, crate::BigUint) {
self.io.get_four_state(signal)
}

pub fn set<T: Copy>(&mut self, signal: crate::SignalRef, val: T) {
self.wrote = true;
self.io.set(signal, val);
}

pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) {
self.wrote = true;
self.io.set_wide(signal, val);
}

pub fn set_four_state(
&mut self,
signal: crate::SignalRef,
val: crate::BigUint,
mask: crate::BigUint,
) {
self.wrote = true;
self.io.set_four_state(signal, val, mask);
}
}

#[cfg(any(
target_arch = "x86_64",
feature = "arm64-codegen",
Expand Down
Loading
Loading