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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions crates/celox-runtime/src/vcd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::path::Path;
/// Self-contained — does not reference any IR types. Can be cached
/// alongside a shared backend artifact so that VCD
/// works even on cache-hit paths.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct VcdSignalDesc {
/// VCD scope name (e.g. instance path).
pub scope: String,
Expand All @@ -29,7 +29,7 @@ pub struct VcdSignalDesc {

/// Describes a signal whose value is supplied by an external runtime rather
/// than stored in Celox's flat simulation memory.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct VcdExternalSignalDesc {
pub scope: String,
pub name: String,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-vpi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ thiserror.workspace = true
tempfile.workspace = true
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "env-filter"] }
celox-design.workspace = true
celox-runtime.workspace = true
celox-sv-analyzer = { workspace = true, optional = true }
clap.workspace = true
fxhash.workspace = true
Expand Down
196 changes: 182 additions & 14 deletions crates/celox-vpi/src/bin/celox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,20 @@ use celox::{
};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand};

#[cfg(feature = "systemverilog")]
#[path = "celox/checkpoint_fs.rs"]
mod checkpoint_fs;
#[path = "celox/project.rs"]
mod project;
#[path = "celox/runner.rs"]
mod runner;
#[cfg(feature = "systemverilog")]
#[path = "celox/state_signal.rs"]
mod state_signal;
#[cfg(feature = "systemverilog")]
#[path = "celox/system_checkpoint.rs"]
mod system_checkpoint;

use project::{Design, DesignArgs};

#[derive(Parser)]
Expand Down Expand Up @@ -88,15 +98,23 @@ struct SaveStateArgs {
/// the design's global time precision.
#[arg(long, value_name = "T", value_delimiter = ',')]
save_state_at_time: Vec<u64>,
/// Disable the default SIGUSR1 checkpoint handler (Unix, SystemVerilog).
#[arg(long)]
no_checkpoint_on_signal: bool,
/// Resume a trusted CLI checkpoint with the same design and options.
#[arg(long, value_name = "FILE")]
restore_checkpoint: Option<PathBuf>,
/// The directory of the saved files, `<signal>-<N>.state` and
/// `time-<T>.state` (default: the current directory).
/// `time-<T>.state` or `signal-<PID>-<N>.checkpoint` (default: the current directory).
#[arg(long, value_name = "DIR")]
save_state_dir: Option<PathBuf>,
}

impl SaveStateArgs {
fn is_empty(&self) -> bool {
self.save_state_on.is_none() && self.save_state_at_time.is_empty()
self.save_state_on.is_none()
&& self.save_state_at_time.is_empty()
&& self.restore_checkpoint.is_none()
}
}

Expand Down Expand Up @@ -202,7 +220,7 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> {
}
if !arguments.save_state.is_empty() {
return Err(
"--save-state-on and --save-state-at-time currently require a SystemVerilog testbench"
"--save-state-on, --save-state-at-time and --restore-checkpoint currently require a SystemVerilog testbench"
.into(),
);
}
Expand All @@ -219,6 +237,11 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
arguments.execution.validate_sv().unwrap_or_else(|message| {
clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, message).exit()
});
// Install before compiling so requests received during compilation are
// deferred until the first safe simulation boundary.
let signal = (cfg!(unix) && !arguments.save_state.no_checkpoint_on_signal)
.then(state_signal::StateSignal::install)
.transpose()?;
let sources = arguments.design.sv_sources()?;
let source_refs = sources
.iter()
Expand All @@ -231,7 +254,13 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
.diagnostic_policy(arguments.design.diagnostics.clone())
.sv_timescale(arguments.design.timescale)
.signal_access(arguments.design.signal_access.clone())
.plusargs(arguments.plusargs.iter().cloned());
.plusargs(arguments.plusargs.iter().cloned())
.defer_initialization(arguments.save_state.restore_checkpoint.is_some());
let builder = if signal.is_some() || arguments.save_state.restore_checkpoint.is_some() {
builder.file_system(|| Box::<checkpoint_fs::CheckpointFs>::default())
} else {
builder
};
let builder = arguments.design.apply_parameters(builder);
let max_steps = if arguments.execution.unlimited {
u64::MAX
Expand All @@ -240,11 +269,24 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
};
macro_rules! execute {
($build:ident) => {{
let simulation = builder
let mut simulation = builder
.$build()
.map_err(|error| format!("compilation failed:\n{error}"))?;
report_warnings(simulation.warnings())?;
let saves = StateSaves::new(&simulation, &arguments.design.top, &arguments.save_state)?;
let progress = if let Some(path) = &arguments.save_state.restore_checkpoint {
Some(system_checkpoint::restore(&mut simulation, path)?)
} else {
None
};
let mut saves = StateSaves::new(
&simulation,
&arguments.design.top,
&arguments.save_state,
signal,
Comment on lines +281 to +285

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore scheduled-save bookkeeping with the simulation

When resuming with the same scheduled-save options, constructing a fresh StateSaves resets the cycle count and repopulates already-consumed save requests. For example, restoring a checkpoint at time 10 with --save-state-at-time 5 makes StateSaves::before save the restored time-10 state as time-5.state; StateSaves::save uses std::fs::write, so this silently overwrites the correct artifact from the original run. Cycle-based saves likewise restart their numbering, producing states at the wrong cycles or reporting that a previously reached cycle was never reached. Persist and restore the consumed requests and cycle-counting state rather than restoring only the accumulated failure flag.

Useful? React with 👍 / 👎.

)?;
if let Some(progress) = progress {
saves.restore_progress(&simulation, &arguments.design.top, progress)?;
}
simulate_sv(simulation, max_steps, saves, &mut std::io::stdout().lock())
}};
}
Expand All @@ -266,11 +308,11 @@ fn simulate_sv<B: celox::SimBackend>(
mut saves: StateSaves,
output: &mut impl Write,
) -> Result<(), String> {
let mut failed = false;
let initial = simulation.eval_comb();
drain_sv_output(&mut simulation, output, &mut failed)?;
drain_sv_output(&mut simulation, output, &mut saves.failed)?;
initial.map_err(|error| error.to_string())?;
saves.start(&mut simulation);
saves.service_signal(&mut simulation);
let mut steps = 0;
while !simulation.is_finished()
&& let Some(next) = simulation.next_event_time()
Expand All @@ -280,18 +322,18 @@ fn simulate_sv<B: celox::SimBackend>(
}
saves.before(&mut simulation, next)?;
let step = simulation.step();
drain_sv_output(&mut simulation, output, &mut failed)?;
drain_sv_output(&mut simulation, output, &mut saves.failed)?;
if step.map_err(|error| error.to_string())?.is_none() {
break;
}
saves.after_step(&mut simulation)?;
steps += 1;
}
let finished = simulation.finish();
drain_sv_output(&mut simulation, output, &mut failed)?;
drain_sv_output(&mut simulation, output, &mut saves.failed)?;
finished.map_err(|error| error.to_string())?;
saves.finish(&mut simulation)?;
if failed {
if saves.failed {
return Err("SystemVerilog testbench reported an assertion failure or $error".to_string());
}
Ok(())
Expand All @@ -315,14 +357,66 @@ struct StateSaves {
/// The times still to save, in descending order.
times: Vec<u64>,
directory: PathBuf,
signal: Option<state_signal::StateSignal>,
signal_sequence: u64,
failed: bool,
started: bool,
}

/// Persistent CLI bookkeeping; signal registration and output directory are local.
#[cfg(feature = "systemverilog")]
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct SavedStateSaves {
counted: Option<String>,
cycles: Vec<u64>,
count: u64,
high: bool,
times: Vec<u64>,
signal_sequence: u64,
failed: bool,
started: bool,
}

#[cfg(feature = "systemverilog")]
impl StateSaves {
fn progress(&self) -> SavedStateSaves {
SavedStateSaves {
counted: self.counted.as_ref().map(|(name, _)| name.clone()),
cycles: self.cycles.clone(),
count: self.count,
high: self.high,
times: self.times.clone(),
signal_sequence: self.signal_sequence,
failed: self.failed,
started: self.started,
}
}

fn restore_progress<B: celox::SimBackend>(
&mut self,
simulation: &celox::Simulation<B>,
top: &str,
saved: SavedStateSaves,
) -> Result<(), String> {
self.counted = saved
.counted
.map(|name| resolve_signal_path(simulation, top, &name).map(|signal| (name, signal)))
.transpose()?;
self.cycles = saved.cycles;
self.count = saved.count;
self.high = saved.high;
self.times = saved.times;
self.signal_sequence = saved.signal_sequence;
self.failed = saved.failed;
self.started = saved.started;
Ok(())
}

fn new<B: celox::SimBackend>(
simulation: &celox::Simulation<B>,
top: &str,
arguments: &SaveStateArgs,
signal: Option<state_signal::StateSignal>,
) -> Result<Self, String> {
let counted = match &arguments.save_state_on {
Some(path) => Some((path.clone(), resolve_signal_path(simulation, top, path)?)),
Expand All @@ -338,11 +432,23 @@ impl StateSaves {
.save_state_dir
.clone()
.unwrap_or_else(|| PathBuf::from("."));
if !arguments.is_empty() {
if !arguments.is_empty() || signal.is_some() {
std::fs::create_dir_all(&directory)
.map_err(|error| format!("cannot create {}: {error}", directory.display()))?;
}
if signal.is_some() {
let _ = writeln!(
std::io::stderr().lock(),
"SIGUSR1 checkpoint ready (pid {}): {}",
std::process::id(),
directory.display()
);
}
Ok(Self {
signal,
signal_sequence: 0,
failed: false,
started: false,
counted,
cycles: descending(&arguments.save_state_at),
count: 0,
Expand All @@ -361,8 +467,11 @@ impl StateSaves {
}

fn start<B: celox::SimBackend>(&mut self, simulation: &mut celox::Simulation<B>) {
if let Some((_, signal)) = self.counted {
self.high = Self::level(simulation, signal);
if !self.started {
if let Some((_, signal)) = self.counted {
self.high = Self::level(simulation, signal);
}
self.started = true;
}
}

Expand All @@ -372,6 +481,7 @@ impl StateSaves {
simulation: &mut celox::Simulation<B>,
next: u64,
) -> Result<(), String> {
self.service_signal(simulation);
while let Some(&time) = self.times.last()
&& time < next
{
Expand All @@ -386,6 +496,7 @@ impl StateSaves {
simulation: &mut celox::Simulation<B>,
) -> Result<(), String> {
let Some((name, signal)) = &self.counted else {
self.service_signal(simulation);
return Ok(());
};
let (name, signal) = (name.clone(), *signal);
Expand All @@ -399,6 +510,7 @@ impl StateSaves {
self.save(simulation, format!("{name}-{}.state", self.count))?;
}
}
self.service_signal(simulation);
Ok(())
}

Expand All @@ -419,6 +531,62 @@ impl StateSaves {
Ok(())
}

/// A signal request must never turn a diagnostic failure into loss of the
/// ongoing run. Keep requests pending across `$stop` suspensions.
fn service_signal<B: celox::SimBackend>(&mut self, simulation: &mut celox::Simulation<B>) {
if simulation.is_stopped()
|| !self
.signal
.as_ref()
.is_some_and(|signal| signal.take_request())
{
return;
}
let Some(sequence) = self.signal_sequence.checked_add(1) else {
let _ = writeln!(
std::io::stderr().lock(),
"cannot save SIGUSR1 checkpoint: request sequence exhausted"
);
return;
};
self.signal_sequence = sequence;
let path = self.directory.join(format!(
"signal-{}-{sequence}.checkpoint",
std::process::id()
));
let result = (|| -> Result<(), String> {
let state = system_checkpoint::capture(simulation, self)?;
// Publish only complete files, without overwriting earlier captures.
let mut temporary = tempfile::NamedTempFile::new_in(&self.directory)
.map_err(|error| error.to_string())?;
temporary
.as_file_mut()
.write_all(&state)
.map_err(|error| error.to_string())?;
temporary
.as_file_mut()
.sync_all()
.map_err(|error| error.to_string())?;
temporary
.persist_noclobber(&path)
.map_err(|error| error.to_string())?;
Ok(())
})();
let _ = match result {
Ok(()) => writeln!(
std::io::stderr().lock(),
"saved SIGUSR1 checkpoint: {} (time {})",
path.display(),
simulation.time()
),
Err(error) => writeln!(
std::io::stderr().lock(),
"cannot save SIGUSR1 checkpoint {}: {error}; continuing simulation",
path.display()
),
};
}

fn save<B: celox::SimBackend>(
&self,
simulation: &mut celox::Simulation<B>,
Expand Down
Loading
Loading