diff --git a/Cargo.lock b/Cargo.lock index ae3aff84d83..47908e1d40d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -657,6 +657,7 @@ name = "celox-heap" version = "0.11.0" dependencies = [ "fxhash", + "serde", ] [[package]] diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 3f34f2b61fc..a85be9c3be6 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1105,6 +1105,11 @@ pub struct RuntimeSchema { /// most one per module instance. Before each round a timed scheduler /// stores the current time into each, as [`TIME_SLOT_WIDTH`] bits. pub time_slots: Vec, + /// Variables of `$sampled` operands and their copies, which hold the + /// value of the variable in the Preponed region (IEEE 1800-2023 + /// 16.5.1): a host copies each variable into its copy when a time slot + /// is over, and once before the first. + pub sample_shadows: Vec<(A, A)>, /// The state a compiled scheduler exchanges with the runtime, and the /// scheduler itself once one is generated. Present when the design has /// process kernels. @@ -1359,6 +1364,7 @@ impl Default for RuntimeSchema { host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), scheduler: None, derived_edges: Vec::new(), settle_partitions: None, diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index bbe9a4a74fe..a8b28da4739 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -46,6 +46,9 @@ pub struct ScheduleModel { /// Objects the scheduler stores the current time into /// ([`RuntimeSchema::time_slots`]). pub time_slots: Vec, + /// Sampled variables and their copies + /// ([`RuntimeSchema::sample_shadows`]). + pub sample_shadows: Vec<(A, A)>, /// The compiled scheduler, if one was generated /// ([`RuntimeSchema::scheduler`]). pub scheduler: Option>, @@ -152,6 +155,7 @@ impl ScheduleModel { .any(|site| matches!(site.kind, RuntimeEventKind::Finish)), active_commits: schema.active_commits.clone(), time_slots: schema.time_slots.clone(), + sample_shadows: schema.sample_shadows.clone(), scheduler: schema.scheduler.clone(), } } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 978966f9d2f..b17909e54cd 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1972,6 +1972,7 @@ pub fn lower_frontend_artifact( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }; let symbolic = SymbolicRtl { modules: [(module_id, sim_module.clone())].into_iter().collect(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 13d9d614ced..6f6acef4356 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -159,6 +159,9 @@ pub struct SimModule { /// The variable through which the module's code reads the simulation /// time; see `RuntimeSchema::time_slots`. pub time_slot: Option, + /// Variables and their sampled copies; see + /// `RuntimeSchema::sample_shadows`. + pub sample_shadows: Vec<(SourceVarId, SourceVarId)>, } /// A nonblocking site whose kernel has two paths, as diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 288fda6029b..766715c6749 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2135,6 +2135,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( nba_sites, host_request_sites, time_slots, + sample_shadows, .. } = timing; let source_sir = SirProgram { @@ -2386,6 +2387,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); + let sample_shadows: Vec<(StateAddr, StateAddr)> = sample_shadows + .into_iter() + .map(|(variable, copy)| (project(variable), project(copy))) + .collect(); let root_instance = expanded[&InstancePath(Vec::new())]; let settle_partitions = settle_flags.map(|settle| { let mut marks: HashMap> = HashMap::default(); @@ -2509,6 +2514,12 @@ pub fn schedule_symbolic_rtl_reporting_loops( .flat_map(|(source, counter)| [source.id, *counter]), ); } + // The host copies each sampled variable into its copy. + timing_read_roots.extend( + sample_shadows + .iter() + .flat_map(|&(variable, copy)| [variable, copy]), + ); // A package variable's state object maps back to the package's own // variable, not to one of its aliases. let state_to_source = source_to_state @@ -2561,6 +2572,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, active_commits, time_slots, + sample_shadows, scheduler, derived_edges: Vec::new(), settle_partitions, @@ -4113,6 +4125,7 @@ struct TimingMetadata { nba_sites: Vec>, host_request_sites: Vec>, time_slots: Vec, + sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, nba_switches: Vec>, } @@ -4435,6 +4448,7 @@ fn relocate_timing( nba_sites: Vec::new(), host_request_sites: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), nba_switches: Vec::new(), }; for (&instance, module) in instances { @@ -4470,6 +4484,12 @@ fn relocate_timing( }), ); metadata.time_slots.extend(module.time_slot.map(locate)); + metadata.sample_shadows.extend( + module + .sample_shadows + .iter() + .map(|&(variable, copy)| (locate(variable), locate(copy))), + ); metadata.nba_switches.extend( module .nba_switches diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 763987247b7..98a11f435f2 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -87,6 +87,9 @@ struct SvVariable { hidden: bool, /// Compiler-generated external override slot: (target, is_enable). force_control: Option<(SourceVarId, bool)>, + /// The variable whose sampled value this hidden copy holds + /// (`SimModule::sample_shadows`). + sampled_from: Option, } /// Whether `expr` reads a string variable: after its calls are hoisted, a @@ -126,13 +129,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes, and an - /// event expression's variables are state its process and its - /// continuous assignment share. + /// code computes. The time slot and the sampled copies are state the + /// scheduler writes, and an event expression's variables are state its + /// process and its continuous assignment share. fn is_scratch(&self) -> bool { self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + && self.sampled_from.is_none() && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -2198,6 +2202,7 @@ fn prepare_external_hierarchy_collecting( source: variable.source.clone(), hidden: !variable.module_affiliated, force_control: None, + sampled_from: None, }, ) }) @@ -3629,6 +3634,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -3713,6 +3719,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object, or the other instance's, has its own @@ -3793,6 +3800,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }, ); } @@ -4005,6 +4013,7 @@ fn lower_module_with_overrides( nba_switches, host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), + sample_shadows: Vec::new(), }, variables, port_order, @@ -4793,6 +4802,12 @@ pub(crate) fn attach_instance_glue( } // Combinational processes may read the time too. module.time_slot = signal_names.get(TIME_SLOT).copied(); + let mut sample_shadows: Vec<_> = parent_variables + .iter() + .filter_map(|(©, variable)| variable.sampled_from.map(|variable| (variable, copy))) + .collect(); + sample_shadows.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); + module.sample_shadows = sample_shadows; for (instance, child_id, child, connections) in resolved_instances { let glue = build_instance_glue( &parent_variables, @@ -5187,6 +5202,7 @@ fn lower_initial_processes( // Control slots are not signals of the design. hidden: true, force_control: None, + sampled_from: None, }, ); id @@ -5831,6 +5847,7 @@ fn ensure_parent_output_signals( source: None, hidden: false, force_control: None, + sampled_from: None, }; parent .variables @@ -7713,6 +7730,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::Isunbounded | SystemFunction::Signed | SystemFunction::Unsigned + | SystemFunction::Sampled | SystemFunction::Bits | SystemFunction::Size | SystemFunction::Dimensions @@ -9077,6 +9095,15 @@ fn runtime_select_as_shift( } fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { + expr_from_const_expr_with_calls(expr, false) +} + +/// Reconstruct a select operand, optionally retaining nested runtime calls. +fn expr_from_const_expr_with_calls( + expr: &sv::ir::ConstExpr, + allow_calls: bool, +) -> Option { + let convert = |expr| expr_from_const_expr_with_calls(expr, allow_calls); Some(match expr { sv::ir::ConstExpr::Literal(value) => sv::ir::Expr::Literal(value.clone()), sv::ir::ConstExpr::Ident(name) => sv::ir::Expr::Ident(name.clone()), @@ -9086,13 +9113,13 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { lsb, signed, } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**msb).clone(), lsb: (**lsb).clone(), signed: *signed, }, sv::ir::ConstExpr::Select { expr, bit } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**bit).clone(), lsb: (**bit).clone(), signed: false, @@ -9102,28 +9129,36 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { width, signed, } => sv::ir::Expr::Resize { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), width: *width, signed: *signed, }, + sv::ir::ConstExpr::Function { callee, args, .. } if allow_calls => sv::ir::Expr::Call { + callee: callee.clone(), + arg_order: Vec::new(), + args: args + .iter() + .map(|arg| convert(arg).map(Some)) + .collect::>()?, + }, sv::ir::ConstExpr::Function { .. } => return None, sv::ir::ConstExpr::Unary { op, expr } => sv::ir::Expr::Unary { op: *op, - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), }, sv::ir::ConstExpr::Binary { left, op, right } => sv::ir::Expr::Binary { - left: Box::new(expr_from_const_expr(left)?), + left: Box::new(convert(left)?), op: *op, - right: Box::new(expr_from_const_expr(right)?), + right: Box::new(convert(right)?), }, sv::ir::ConstExpr::Mux { condition, then_expr, else_expr, } => sv::ir::Expr::Mux { - condition: Box::new(expr_from_const_expr(condition)?), - then_expr: Box::new(expr_from_const_expr(then_expr)?), - else_expr: Box::new(expr_from_const_expr(else_expr)?), + condition: Box::new(convert(condition)?), + then_expr: Box::new(convert(then_expr)?), + else_expr: Box::new(convert(else_expr)?), }, }) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 26ef54d8fb1..7a1bbbff731 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -102,6 +102,8 @@ pub(super) struct Ff<'p, 'a> { /// The flush-point site of a process with deferred assertions, whose /// queue their actions wait in. flush_site: Option, + /// A combinational process is being lowered. + combinational: bool, } fn stable(var_id: SourceVarId) -> Addr { @@ -161,9 +163,44 @@ impl<'p, 'a> Ff<'p, 'a> { host_request_sites: Vec::new(), nba_switches: Vec::new(), flush_site: None, + combinational: false, } } + /// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static + /// variable read through its sampled copy. Automatic variables and the + /// lowering's own temporaries keep their current value (16.5.1). A + /// combinational process reruns when its inputs change, not when their + /// sampled values do, so it cannot read them. + fn sampled( + &mut self, + args: &[Option], + ) -> Result { + if self.combinational { + return Err(unsupported("$sampled in combinational logic")); + } + let [Some(operand)] = args else { + return Err(unsupported("operand of `$sampled`")); + }; + let operand = self.propagate(operand); + let mut names = HashSet::default(); + expr_idents(&operand, &mut names); + let mut renames = HashMap::default(); + for name in names { + let Some(id) = self.m.id(&name) else { + continue; + }; + if self.m.is_hidden(id) { + continue; + } + if self.m.var(id).value_kind.is_handle() { + return Err(unsupported("$sampled of a string or class handle")); + } + renames.insert(name, self.m.sampled_copy(id)); + } + Ok(rename_idents(&operand, &renames)) + } + /// Whether `stmts`, or a subroutine they call, including in timing /// controls and the defaults of omitted arguments, hold a deferred /// assertion. @@ -779,8 +816,18 @@ impl<'p, 'a> Ff<'p, 'a> { } let mut lowered = Vec::with_capacity(args.len()); for arg in args { - let arg = self.hoist_const(arg, calls)?; - lowered.push(expr_from_const_expr(&arg).ok_or_else(|| { + // $sampled must rewrite its operand before any nested + // call reads it. Hoisting first hides the original inputs + // behind a temporary holding their current-slot value. + let arg = if matches!( + callee, + sv::ir::Callee::System(sv::ir::SystemFunction::Sampled) + ) { + arg.clone() + } else { + self.hoist_const(arg, calls)? + }; + lowered.push(expr_from_const_expr_with_calls(&arg, true).ok_or_else(|| { unsupported(format!("argument of `{callee}` in a select")) })?); } @@ -789,8 +836,19 @@ impl<'p, 'a> Ff<'p, 'a> { callee: callee.clone(), args: lowered.into_iter().map(Some).collect(), }; - let sv::ir::Expr::Ident(result) = self.hoist(&call)? else { - return Err(unsupported(format!("call of `{callee}` in a select"))); + let result = match self.hoist(&call)? { + sv::ir::Expr::Ident(result) => result, + // A sampled operand, as `$sampled(i + 1)`: its value at + // this point is the select's. + hoisted @ sv::ir::Expr::Binary { .. } + | hoisted @ sv::ir::Expr::Unary { .. } => { + let value = self.eval(&hoisted, None)?; + let width = self.b.register(&value).width(); + let (temp, name) = self.m.temp("select", width, false, true); + self.store(temp, SIROffset::Static(0), width, value); + name + } + _ => return Err(unsupported(format!("call of `{callee}` in a select"))), }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); @@ -1074,6 +1132,14 @@ impl<'p, 'a> Ff<'p, 'a> { self.assign(&sv::ir::LValue::Ident(name.clone()), value)?; Expr::Ident(name) } + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Sampled), + args, + .. + } => { + let operand = self.sampled(args)?; + self.hoist(&operand)? + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), args, @@ -4064,6 +4130,7 @@ impl<'p, 'a> Ff<'p, 'a> { // `initial` blocks, like `always_comb`, as Verilator settles them. let runs_at_time_zero = always_comb || !self.m.four_state; self.direct = true; + self.combinational = true; let mut reads = self.m.implicit_reads(body, always_comb); reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); for stmt in body { @@ -6076,6 +6143,7 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, + sampled_from: None, value_kind: Default::default(), }, ); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 37095d43ae5..404fb18d038 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -974,6 +974,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }, ); self.name_to_id.insert(name, id); @@ -982,6 +983,24 @@ impl<'a> ProcModule<'a> { } /// A hidden variable with the shape of `id`, two-state when `two_state`. + /// The hidden copy that holds the sampled value of variable `id` + /// (IEEE 1800-2023 16.5.1), created on first use. + pub fn sampled_copy(&mut self, id: SourceVarId) -> String { + if let Some((name, _)) = self + .name_to_id + .iter() + .find(|(_, copy)| self.variables[copy].sampled_from == Some(id)) + { + return name.clone(); + } + let (copy, name) = self.shadow(id, "sampled", false); + self.variables + .get_mut(©) + .expect("a new copy") + .sampled_from = Some(id); + name + } + pub fn shadow( &mut self, id: SourceVarId, @@ -1040,6 +1059,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1070,6 +1090,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, ..variable }, ); @@ -1597,6 +1618,7 @@ pub(super) fn register_locals( source: None, hidden: true, force_control: None, + sampled_from: None, }, ); name_to_id.insert(local.name.clone(), id); diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 49fdb07fc6b..526b5b7dbf0 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -682,6 +682,7 @@ pub(crate) fn project_module_with_ids( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }, ids, inferred_latch_diagnostics, diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml index 477e1d8a232..0ab148bba27 100644 --- a/crates/celox-heap/Cargo.toml +++ b/crates/celox-heap/Cargo.toml @@ -10,6 +10,7 @@ edition.workspace = true rust-version.workspace = true [dependencies] +serde = { workspace = true, features = ["rc"] } fxhash = { workspace = true } [lints] diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 9d708fe87c1..e280424d429 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -35,7 +35,7 @@ pub const EMPTY_STRING: Handle = 0; const MIN_COLLECTION_INTERVAL: usize = 1024; /// What a handle refers to. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum HandleKind { String, Object, @@ -65,7 +65,7 @@ impl Root { } /// Dynamic strings and class objects referenced by [`Handle`]. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct Heap { strings: HashMap>, lookup: HashMap, Handle>, diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 2683ca747b9..097a345e198 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -11,7 +11,7 @@ use crate::{Handle, HandleKind, Heap}; /// The handle of `null`, the value of zero-initialized memory. pub const NULL: Handle = 0; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) struct Object { class: u32, random_state: u64, @@ -24,7 +24,7 @@ pub(crate) struct Object { pub(crate) handles: Vec<(u32, HandleKind)>, } -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] struct RandomModes { overrides: fxhash::FxHashMap, /// Non-rand properties temporarily made random by an argument list. @@ -47,7 +47,7 @@ impl Object { /// An error that compiled code made in a heap operation, which the runtime /// reports once control returns to it. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Fault { /// A property access or method call through `null` or a handle of no /// live object (IEEE 1800-2023 8.4). diff --git a/crates/celox-runtime/src/file_io.rs b/crates/celox-runtime/src/file_io.rs index 43829b1e38d..24c6b95517c 100644 --- a/crates/celox-runtime/src/file_io.rs +++ b/crates/celox-runtime/src/file_io.rs @@ -1,10 +1,12 @@ //! SystemVerilog file descriptors and multichannel descriptors (IEEE 1800-2023 21.3). //! //! A manager belongs to one simulation. No process-global descriptor table is used. +use crate::file_io_backend::{FileMode, FileSystem, HostFileSystem}; use std::collections::BTreeMap; -use std::fs::{File, OpenOptions}; +use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::Path; +use std::sync::{Arc, Mutex}; use celox_testbench::{DisplayFormatArg, FieldSpec, format_sv_display_arg}; @@ -12,7 +14,8 @@ const FD_FLAG: u32 = 0x8000_0000; #[derive(Debug)] pub struct FileIo { - channels: BTreeMap, + backend: Arc>>, + channels: BTreeMap, descriptors: BTreeMap, stdin_input: InputState, stdin_open: bool, @@ -20,7 +23,7 @@ pub struct FileIo { stderr_open: bool, } -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] struct InputState { eof: bool, pushed: Option, @@ -28,14 +31,21 @@ struct InputState { #[derive(Debug)] struct InputFile { - file: File, + file: BackendFile, readable: bool, input: InputState, } impl Default for FileIo { fn default() -> Self { + Self::new(Box::::default()) + } +} + +impl FileIo { + pub fn new(backend: Box) -> Self { Self { + backend: Arc::new(Mutex::new(backend)), channels: BTreeMap::new(), descriptors: BTreeMap::new(), stdin_input: InputState::default(), @@ -44,34 +54,105 @@ impl Default for FileIo { stderr_open: true, } } -} -impl FileIo { + /// Capture Celox's bookkeeping and the backend's opaque state. Unsupported + /// backend capture is retained as a restore error, allowing inspection. + pub fn snapshot(&self) -> FileIoSnapshot { + let backend = self.backend.lock().unwrap(); + let state = backend + .snapshot() + .and_then(|bytes| { + if backend.snapshot_format().is_empty() { + return Err(io::Error::other( + "snapshot backend must declare a format identity", + )); + } + Ok((backend.snapshot_format().to_owned(), bytes)) + }) + .map_err(|error| error.to_string()); + FileIoSnapshot { + state, + channels: self + .channels + .iter() + .map(|(&key, file)| (key, file.id)) + .collect(), + descriptors: self + .descriptors + .iter() + .map(|(&key, file)| (key, file.file.id, file.readable, file.input.clone())) + .collect(), + stdin_input: self.stdin_input.clone(), + standard_open: [self.stdin_open, self.stdout_open, self.stderr_open], + } + } + + /// Capture a resumable handler state, reporting backend capture failures. + /// System-level checkpoint writers use this rather than publishing a + /// diagnostic snapshot containing an error. + pub fn try_snapshot(&self) -> io::Result { + let snapshot = self.snapshot(); + snapshot + .state + .as_ref() + .map_err(|error| io::Error::other(error.clone()))?; + Ok(snapshot) + } + + /// Prepare a replacement without changing this manager or its backend. + pub fn prepare_restore(&self, snapshot: &FileIoSnapshot) -> io::Result { + let (format, bytes) = snapshot + .state + .as_ref() + .map_err(|error| io::Error::other(error.clone()))?; + let backend = self.backend.lock().unwrap(); + if backend.snapshot_format() != format { + return Err(io::Error::other( + "file I/O snapshot backend format mismatch", + )); + } + let restored = backend.restore(bytes)?; + if restored.snapshot_format() != format { + return Err(io::Error::other( + "restored file I/O backend format mismatch", + )); + } + let mut manager = Self::new(restored); + for &(key, id) in &snapshot.channels { + manager.channels.insert( + key, + BackendFile { + id, + closed: false, + backend: manager.backend.clone(), + }, + ); + } + for (key, id, readable, input) in &snapshot.descriptors { + manager.descriptors.insert( + *key, + InputFile { + file: BackendFile { + id: *id, + closed: false, + backend: manager.backend.clone(), + }, + readable: *readable, + input: input.clone(), + }, + ); + } + manager.stdin_input = snapshot.stdin_input.clone(); + [manager.stdin_open, manager.stdout_open, manager.stderr_open] = snapshot.standard_open; + Ok(manager) + } + /// Open an MCD when mode is absent, otherwise an FD. Failure returns zero, /// as specified by 21.3.1. Closed channel numbers are reused. pub fn open(&mut self, path: impl AsRef, mode: Option<&str>) -> u32 { - let mut options = OpenOptions::new(); - match mode.unwrap_or("w") { - "r" | "rb" => { - options.read(true); - } - "w" | "wb" => { - options.write(true).create(true).truncate(true); - } - "a" | "ab" => { - options.append(true).create(true); - } - "r+" | "r+b" | "rb+" => { - options.read(true).write(true); - } - "w+" | "w+b" | "wb+" => { - options.read(true).write(true).create(true).truncate(true); - } - "a+" | "a+b" | "ab+" => { - options.read(true).append(true).create(true); - } - _ => return 0, - } + let Some(options) = FileMode::parse(mode.unwrap_or("w")) else { + return 0; + }; let key = if mode.is_some() { let Some(key) = (3..FD_FLAG).find(|key| !self.descriptors.contains_key(key)) else { return 0; @@ -86,9 +167,14 @@ impl FileIo { }; key }; - let Ok(mut file) = options.open(path) else { + let Ok(id) = self.backend.lock().unwrap().open(path.as_ref(), options) else { return 0; }; + let mut file = BackendFile { + id, + closed: false, + backend: self.backend.clone(), + }; if let Some(mode) = mode { // Table 21-6 places the initial position at EOF for append modes, // including the read position of update streams (a+). @@ -131,10 +217,10 @@ impl FileIo { Err(invalid_descriptor()) }; } - let Some(mut file) = self.descriptors.remove(&key) else { + let Some(file) = self.descriptors.remove(&key) else { return Err(invalid_descriptor()); }; - return file.file.flush(); + return file.file.close(); } let mut error = None; if descriptor & 1 != 0 && !std::mem::replace(&mut self.stdout_open, false) { @@ -144,8 +230,8 @@ impl FileIo { let key = 1u32 << bit; if descriptor & key != 0 { match self.channels.remove(&key) { - Some(mut file) => { - if let Err(err) = file.flush() { + Some(file) => { + if let Err(err) = file.close() { error = Some(err); } } @@ -171,7 +257,7 @@ impl FileIo { )), 1 if self.stdout_open => Ok(true), 2 if self.stderr_open => { - io::stderr().lock().write_all(bytes)?; + self.backend.lock().unwrap().write_stderr(bytes)?; Ok(false) } key => { @@ -217,7 +303,7 @@ impl FileIo { /// a pushed-back byte is returned before the underlying file is read. pub fn read_byte(&mut self, descriptor: u32) -> io::Result> { if descriptor == FD_FLAG && self.stdin_open { - return read_input_byte(&mut io::stdin().lock(), &mut self.stdin_input); + return read_input_byte(&mut BackendStdin(&self.backend), &mut self.stdin_input); } let file = self.readable_file(descriptor)?; read_input_byte(&mut file.file, &mut file.input) @@ -316,8 +402,8 @@ impl FileIo { if descriptor & FD_FLAG != 0 { return match descriptor & !FD_FLAG { 0 if self.stdin_open => Ok(()), - 1 if self.stdout_open => io::stdout().lock().flush(), - 2 if self.stderr_open => io::stderr().lock().flush(), + 1 if self.stdout_open => self.backend.lock().unwrap().flush_stdout(), + 2 if self.stderr_open => self.backend.lock().unwrap().flush_stderr(), _ => self.positioned_file(descriptor)?.file.flush(), }; } @@ -330,13 +416,13 @@ impl FileIo { }; if descriptor.is_none() || descriptor.is_some_and(|bits| bits & 1 != 0) { if self.stdout_open { - attempt(io::stdout().lock().flush()); + attempt(self.backend.lock().unwrap().flush_stdout()); } else if descriptor.is_some() { attempt(Err(invalid_descriptor())); } } if descriptor.is_none() && self.stderr_open { - attempt(io::stderr().lock().flush()); + attempt(self.backend.lock().unwrap().flush_stderr()); } for bit in 1..31 { let key = 1u32 << bit; @@ -376,6 +462,27 @@ impl FileIo { Ok(file) } + /// Write memory through the injected backend, including its snapshot policy. + pub fn write_memory_with_backend<'a>( + &mut self, + path: impl AsRef, + binary: bool, + words: impl IntoIterator>, + ) -> io::Result<()> { + let id = self + .backend + .lock() + .unwrap() + .open(path.as_ref(), FileMode::parse("w").unwrap())?; + let mut file = BackendFile { + id, + closed: false, + backend: self.backend.clone(), + }; + write_memory_words(&mut file, binary, words)?; + file.close() + } + /// Write a static unpacked memory snapshot, without address specifiers /// (21.5.3). The caller supplies elements in the requested address order. pub fn write_memory<'a>( @@ -384,15 +491,83 @@ impl FileIo { words: impl IntoIterator>, ) -> io::Result<()> { let mut file = File::create(path)?; - for word in words { - file.write_all(&format_sv_display_arg( - &word, - if binary { 'b' } else { 'h' }, - FieldSpec::default(), - ))?; - file.write_all(b"\n")?; + write_memory_words(&mut file, binary, words) + } +} + +fn write_memory_words<'a>( + file: &mut impl Write, + binary: bool, + words: impl IntoIterator>, +) -> io::Result<()> { + for word in words { + file.write_all(&format_sv_display_arg( + &word, + if binary { 'b' } else { 'h' }, + FieldSpec::default(), + ))?; + file.write_all(b"\n")?; + } + file.flush() +} + +/// Host-owned I/O snapshot, separate from core checkpoints. Backend bytes are opaque; descriptor +/// bookkeeping cannot be edited independently of them. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct FileIoSnapshot { + state: Result<(String, Vec), String>, + channels: Vec<(u32, u64)>, + descriptors: Vec<(u32, u64, bool, InputState)>, + stdin_input: InputState, + standard_open: [bool; 3], +} + +#[derive(Debug)] +struct BackendFile { + id: u64, + closed: bool, + backend: Arc>>, +} +impl BackendFile { + fn close(mut self) -> io::Result<()> { + self.closed = true; + self.backend.lock().unwrap().close(self.id) + } +} +impl Read for BackendFile { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.backend.lock().unwrap().read(self.id, buffer) + } +} +impl Write for BackendFile { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.backend.lock().unwrap().write(self.id, buffer) + } + fn flush(&mut self) -> io::Result<()> { + self.backend.lock().unwrap().flush(self.id) + } +} +impl Seek for BackendFile { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.backend.lock().unwrap().seek(self.id, position) + } +} +impl Drop for BackendFile { + fn drop(&mut self) { + if self.closed { + return; } - file.flush() + let _ = self + .backend + .lock() + .unwrap_or_else(|e| e.into_inner()) + .close(self.id); + } +} +struct BackendStdin<'a>(&'a Arc>>); +impl Read for BackendStdin<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.0.lock().unwrap().read_stdin(buffer) } } diff --git a/crates/celox-runtime/src/file_io_backend.rs b/crates/celox-runtime/src/file_io_backend.rs new file mode 100644 index 00000000000..4e1c44ec5aa --- /dev/null +++ b/crates/celox-runtime/src/file_io_backend.rs @@ -0,0 +1,188 @@ +//! Host-supplied file I/O. Handles here are private to a backend; HDL descriptor +//! allocation and input bookkeeping remain in `FileIo`. +use std::{ + collections::BTreeMap, + fmt::Debug, + fs::{File, OpenOptions}, + io::{self, Read, Seek, SeekFrom, Write}, + path::Path, + sync::Arc, +}; + +/// Validated access mode passed to a host filesystem. +#[derive(Debug, Clone, Copy)] +pub struct FileMode { + pub read: bool, + pub write: bool, + pub append: bool, + pub create: bool, + pub truncate: bool, +} + +impl FileMode { + pub(crate) fn parse(mode: &str) -> Option { + let (read, write, append, create, truncate) = match mode { + "r" | "rb" => (true, false, false, false, false), + "w" | "wb" => (false, true, false, true, true), + "a" | "ab" => (false, true, true, true, false), + "r+" | "r+b" | "rb+" => (true, true, false, false, false), + "w+" | "w+b" | "wb+" => (true, true, false, true, true), + "a+" | "a+b" | "ab+" => (true, true, true, true, false), + _ => return None, + }; + Some(Self { + read, + write, + append, + create, + truncate, + }) + } +} + +/// I/O boundary implemented by an embedding host. +/// +/// Each instance owns its handle namespace. `snapshot` records all backend +/// state needed to resume, including open handles, positions and shared-file +/// relationships. The host defines how contents and external effects are +/// retained (for example by versioning, recording, or filesystem snapshots). +/// Celox neither selects nor assumes a storage strategy. +/// +/// `restore` must prepare an independent instance without changing the current +/// instance or externally visible state, including on failure. Returned handles +/// must have the same identities as in the snapshot. Dropping/closing the old +/// instance must not invalidate the new one. This permits Celox to validate and +/// prepare every resource before committing the restored simulation state. +/// Hosts may leave the snapshot methods at their defaults. This places no +/// restriction on core checkpoints: only a request to snapshot this handler +/// itself requires these methods. +/// Stdout bytes remain Celox runtime events; they are not withdrawn on restore. +pub trait FileSystem: Debug + Send { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result; + /// Flush and release a handle, including when flushing reports an error. + fn close(&mut self, handle: u64) -> io::Result<()>; + fn read(&mut self, handle: u64, buffer: &mut [u8]) -> io::Result; + fn write(&mut self, handle: u64, buffer: &[u8]) -> io::Result; + fn seek(&mut self, handle: u64, position: SeekFrom) -> io::Result; + fn flush(&mut self, handle: u64) -> io::Result<()>; + fn read_stdin(&mut self, _buffer: &mut [u8]) -> io::Result { + Err(unsupported()) + } + fn write_stderr(&mut self, _buffer: &[u8]) -> io::Result<()> { + Err(unsupported()) + } + fn flush_stdout(&mut self) -> io::Result<()> { + Ok(()) + } + fn flush_stderr(&mut self) -> io::Result<()> { + Ok(()) + } + /// Stable, host-defined format identity, including a version. A restore + /// rejects a different identity before calling the backend. + fn snapshot_format(&self) -> &str { + "" + } + /// Capture without consuming input, advancing positions or changing contents. + fn snapshot(&self) -> io::Result> { + Err(unsupported()) + } + fn restore(&self, _state: &[u8]) -> io::Result> { + Err(unsupported()) + } +} + +fn unsupported() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "file I/O backend does not support this operation", + ) +} + +/// Creates a fresh I/O namespace for each simulator, including compiler-created +/// shadow instances. Factories must not share mutable stream positions. +#[derive(Clone)] +pub struct FileSystemFactory(Arc Box + Send + Sync>); +impl FileSystemFactory { + pub fn new(factory: impl Fn() -> Box + Send + Sync + 'static) -> Self { + Self(Arc::new(factory)) + } + pub fn create(&self) -> Box { + (self.0)() + } +} +impl Default for FileSystemFactory { + fn default() -> Self { + Self::new(|| Box::::default()) + } +} +impl std::fmt::Debug for FileSystemFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("FileSystemFactory(..)") + } +} + +/// Default host OS implementation. It deliberately cannot promise rollback of +/// arbitrary files, pipes or standard input and does not implement snapshots. +#[derive(Debug, Default)] +pub struct HostFileSystem { + files: BTreeMap, + next: u64, +} +impl HostFileSystem { + fn file(&mut self, handle: u64) -> io::Result<&mut File> { + self.files.get_mut(&handle).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "unknown backend file handle") + }) + } +} +impl FileSystem for HostFileSystem { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result { + let file = OpenOptions::new() + .read(mode.read) + .write(mode.write) + .append(mode.append) + .create(mode.create) + .truncate(mode.truncate) + .open(path)?; + let next = self + .next + .checked_add(1) + .ok_or_else(|| io::Error::other("file handle space exhausted"))?; + let id = self.next; + self.next = next; + self.files.insert(id, file); + Ok(id) + } + fn close(&mut self, handle: u64) -> io::Result<()> { + self.files + .remove(&handle) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "unknown backend file handle") + })? + .flush() + } + fn read(&mut self, handle: u64, buffer: &mut [u8]) -> io::Result { + self.file(handle)?.read(buffer) + } + fn write(&mut self, handle: u64, buffer: &[u8]) -> io::Result { + self.file(handle)?.write(buffer) + } + fn seek(&mut self, handle: u64, position: SeekFrom) -> io::Result { + self.file(handle)?.seek(position) + } + fn flush(&mut self, handle: u64) -> io::Result<()> { + self.file(handle)?.flush() + } + fn read_stdin(&mut self, buffer: &mut [u8]) -> io::Result { + io::stdin().lock().read(buffer) + } + fn write_stderr(&mut self, buffer: &[u8]) -> io::Result<()> { + io::stderr().lock().write_all(buffer) + } + fn flush_stdout(&mut self) -> io::Result<()> { + io::stdout().lock().flush() + } + fn flush_stderr(&mut self) -> io::Result<()> { + io::stderr().lock().flush() + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2a07d54399b..9a72fb0f9e5 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -7,6 +7,7 @@ mod edge; mod error; mod event_buffer; pub mod file_io; +pub mod file_io_backend; pub mod parallel; pub mod plusargs; mod reflection; @@ -35,9 +36,9 @@ pub use reflection::{ }; pub use schedule::{ResolvedSchedule, host_watch}; pub use simulation::{ - CompiledSlots, EventInfo, HostBoundary, KernelSchedule, ScheduleKey, ScheduleParts, - SchedulerMode, SchedulerStats, SimulationExecutor, SimulationSnapshot, SimulationState, - StepObserver, UnitExecutor, + CompiledSlots, EventInfo, HostBoundary, KernelSchedule, PersistedSimulationSnapshot, + ScheduleKey, ScheduleParts, SchedulerMode, SchedulerStats, SimulationExecutor, + SimulationSnapshot, SimulationState, StepObserver, UnitExecutor, }; pub use state_file::{ BaselineRecord, NbaRecord, ProcessRecord, ScheduleRecord, ScheduledEvent, StateDifference, @@ -142,6 +143,29 @@ pub struct SignalRef { pub array_layout: Option, } +/// Copy the value of `from`, with its unknown bits, into `to`, a signal of +/// the same width and state form. +pub fn copy_signal(backend: &mut B, from: SignalRef, to: SignalRef) { + if from.array_layout.is_some() || to.array_layout.is_some() { + // Each array has its own layout, packed or with strided elements: + // the backend gathers and scatters the elements. + let (value, mask) = backend.get_four_state(from); + backend.set_four_state(to, value, mask); + return; + } + let planes = if backend.layout().four_state && from.is_4state { + 2 + } else { + 1 + }; + let bytes = celox_state_layout::get_byte_size(from.width) * planes; + let (memory, size) = backend.memory_as_mut_ptr(); + assert!(from.offset + bytes <= size && to.offset + bytes <= size); + // SAFETY: both ranges are in the backend's memory. Signal views can + // alias, so use the copy operation that permits overlapping ranges. + unsafe { std::ptr::copy(memory.add(from.offset), memory.add(to.offset), bytes) }; +} + #[cfg(test)] mod array_layout_tests { use super::SignalArrayLayout; diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 436f3c1fc08..7ec03666d06 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -43,6 +43,8 @@ pub struct ResolvedSchedule { pub(crate) active_commits: bit_set::BitSet, /// Signals the current time is stored into before each round. pub(crate) time_slots: Vec, + /// Sampled variables and their copies, captured before entering a later timestamp. + pub(crate) sample_shadows: Vec<(SignalRef, SignalRef)>, /// The compiled scheduler, when one was generated. pub(crate) scheduler: Option, /// Per process kernel, why the compiled scheduler does not run it, or @@ -336,6 +338,11 @@ impl ResolvedSchedule { timed: model.timed, active_commits, time_slots: model.time_slots.iter().map(resolve).collect(), + sample_shadows: model + .sample_shadows + .iter() + .map(|(variable, copy)| (resolve(variable), resolve(copy))) + .collect(), scheduler: model.scheduler.as_ref().and_then(|scheduler| { let slots = &scheduler.slots; let mut refs = SchedulerRefs { diff --git a/crates/celox-runtime/src/scheduler.rs b/crates/celox-runtime/src/scheduler.rs index c328336c445..da0cd6409ca 100644 --- a/crates/celox-runtime/src/scheduler.rs +++ b/crates/celox-runtime/src/scheduler.rs @@ -4,7 +4,7 @@ use crate::{ }; use std::collections::BinaryHeap; -#[derive(Debug, Clone)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ClockDef { pub period: u64, } diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index dcdcaeea1b7..036144465e9 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -8,7 +8,7 @@ use crate::{ }; use celox_design::ForkJoin; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Activation { pub kernel: usize, pub parent: Option, diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 449175c28cc..6b6eeea398b 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -119,8 +119,6 @@ impl SimulationState { where E: SimulationExecutor, { - self.scheduler.time = current_time; - let num_events = executor.backend().num_events(); let counted = !self.model.counted.is_empty(); for event in &events_to_process { diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index df6c6b04732..0b3133476a8 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -124,7 +124,7 @@ impl SimulationState { let one_slot = match executor.compiled_slots() { CompiledSlots::None => return None, CompiledSlots::One => true, - CompiledSlots::Any => one_slot, + CompiledSlots::Any => one_slot || self.one_slot_runs(), }; Some(if one_slot { first @@ -176,6 +176,11 @@ impl SimulationState { where E: SimulationExecutor, { + // Designs with sampled values are limited to one slot, so `limit` + // is that slot's timestamp. Keep its baseline on same-time reentry. + if self.one_slot_runs() && limit > self.scheduler.time { + self.sample_values(executor.backend_mut()); + } let scheduler = self .model .scheduler @@ -418,6 +423,19 @@ impl SimulationState { if executor.take_slot_writes() { self.host_pending = true; } + // A run of one slot ends it unless work is left at its time. + if (self.one_slot_runs() || executor.compiled_slots() == CompiledSlots::One) + && !self.host_pending + && self.next_work_time() != Some(now) + { + self.end_time_slot(executor, now)?; + } Ok(now) } + + /// Whether every run of the compiled scheduler takes one slot: the + /// sampled copies are made before entering each later timestamp. + fn one_slot_runs(&self) -> bool { + !self.model.sample_shadows.is_empty() + } } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 0a57c8a08b0..3c983b732f3 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -24,7 +24,7 @@ use celox_design::CounterKind; pub(crate) use batch::{edge_level, event_level}; pub use host::{CompiledSlots, HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; -pub use persist::{ScheduleKey, ScheduleParts, SimulationSnapshot}; +pub use persist::{PersistedSimulationSnapshot, ScheduleKey, ScheduleParts, SimulationSnapshot}; pub use stats::{KernelSchedule, SchedulerMode, SchedulerStats}; pub use wait::{Baseline, Waiter, Waiters}; @@ -552,9 +552,23 @@ impl SimulationState { /// Move to `time` without running anything there, as the end of a run /// to a time without work does. Design code reads the new time. pub fn advance_time(&mut self, backend: &mut B, time: u64) { + if time > self.scheduler.time { + self.sample_values(backend); + } self.set_time(backend, time); } + /// Copy each sampled variable into its copy, which then holds the value + /// the variable has in the Preponed region of the next time slot (IEEE + /// 1800-2023 4.4.2.1, 16.5.1). A timed simulation does it before + /// advancing to a later timestamp and once before the first slot. + /// Returning to the host at the same timestamp must retain the copy. + pub fn sample_values(&self, backend: &mut B) { + for &(variable, copy) in &self.model.sample_shadows { + crate::copy_signal(backend, variable, copy); + } + } + /// Store `time` where design code reads the simulation time (`$time`). fn publish_time(&self, backend: &mut B, time: u64) { for &slot in &self.model.time_slots { diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index 00b493f1180..42ab82d7f11 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -279,7 +279,7 @@ pub(super) fn restore_working_image(backend: &mut B, image: &[u8] } /// A nonblocking assignment waiting for the NBA region. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NbaUpdate { pub target: SignalRef, /// Bit position of the assigned range in the target. diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 5da0c2a960b..813a2bfb652 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -341,3 +341,100 @@ pub struct ScheduleKey { pub stopped: bool, pub suspended: bool, } + +/// Pointer-free encoding of a checkpoint's scheduler. Unlike a portable state +/// file this includes live fork activations and lexical cells. Its schema is +/// private to the checkpoint container version. +#[doc(hidden)] +#[derive(serde::Serialize, serde::Deserialize)] +pub struct PersistedSimulationSnapshot { + time: u64, + clocks: Vec>, + events: Vec<(u64, usize, crate::SignalRef, u8, bool)>, + high: Vec, + unknown: Vec, + wakeups: Vec, + processes: ProcessState, + declarations_pending: bool, + host_pending: bool, + finished: bool, + finalizing: Option, +} + +impl SimulationSnapshot { + #[doc(hidden)] + pub fn persisted(&self) -> PersistedSimulationSnapshot { + PersistedSimulationSnapshot { + time: self.time, + clocks: self.clocks.clone(), + events: self + .event_queue + .iter() + .map(|event| { + ( + event.time, + event.event_ref.id(), + event.signal, + event.next_val, + event.periodic, + ) + }) + .collect(), + high: self.last_clock_values.iter().collect(), + unknown: self.last_clock_unknown.iter().collect(), + wakeups: self.process_wakeups.iter().copied().collect(), + processes: self.process_state.clone(), + declarations_pending: self.declarations_pending, + host_pending: self.host_pending, + finished: self.finished, + finalizing: self.finalizing, + } + } +} + +impl PersistedSimulationSnapshot { + /// Bind event IDs to the receiving compiled instance; machine-code addresses + /// never occur in the file. + /// + /// # Safety + /// This record must have been produced from a valid snapshot for the same + /// design. Its process state contains raw state-memory offsets. + #[doc(hidden)] + pub unsafe fn bind(self, events: &[B::Event]) -> Option> { + if self.clocks.len() > events.len() + || self + .high + .iter() + .chain(&self.unknown) + .any(|&id| id >= events.len()) + { + return None; + } + let event_queue = self + .events + .into_iter() + .map(|(time, id, signal, next_val, periodic)| { + Some(SimEvent { + time, + event_ref: *events.get(id)?, + signal, + next_val, + periodic, + }) + }) + .collect::>()?; + Some(SimulationSnapshot { + time: self.time, + clocks: self.clocks, + event_queue, + last_clock_values: self.high.into_iter().collect(), + last_clock_unknown: self.unknown.into_iter().collect(), + process_wakeups: self.wakeups.into_iter().collect(), + process_state: self.processes, + declarations_pending: self.declarations_pending, + host_pending: self.host_pending, + finished: self.finished, + finalizing: self.finalizing, + }) + } +} diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 881f1d146e6..5ab9a9d3a57 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -441,12 +441,10 @@ impl SimulationState { where E: SimulationExecutor, { - self.publish_time(executor.backend_mut(), current_time); + self.advance_time(executor.backend_mut(), current_time); if !self.model.timed { return self.batch_round(executor, current_time, events_to_process); } - self.scheduler.time = current_time; - // Host writes the waits must see one at a time. for (signal, value) in executor.take_host_writes() { self.observe_host_write(signal, &value); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index a48ba7bd963..cad499b6469 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -214,7 +214,7 @@ impl SimulationState { // The slot is over when nothing more is due at its time, host // writes included. if !self.host_pending && self.next_work_time() != Some(current_time) { - executor.try_end_time_slot(current_time)?; + self.end_time_slot(executor, current_time)?; } Ok(()) } @@ -228,6 +228,19 @@ impl SimulationState { || !state.re_nba_queue.is_empty() } + /// Run the host's Observed and Postponed work after quiescence. + /// The host may resume this timestamp, so sampling waits for time advance. + pub(super) fn end_time_slot( + &mut self, + executor: &mut E, + current_time: u64, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + executor.try_end_time_slot(current_time) + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 7c23f974f2e..8d5058d2b0f 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -311,7 +311,7 @@ pub(super) fn wake_in_region( } /// What one term of a waiting process compares against. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Baseline { /// The counter's value when the wait began, and the signal's value at /// the last check. Only kernels and combinational process units count a @@ -330,7 +330,7 @@ pub enum Baseline { } /// A process suspended at a wait. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Waiter { pub site: usize, pub baselines: Vec, @@ -338,7 +338,7 @@ pub struct Waiter { /// The processes suspended at a wait, by process index. A slot keeps its /// storage while its process runs, so suspending again reuses it. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Waiters { slots: Vec, waiting: Vec, diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 63478460d29..ecc042d1f8c 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -330,7 +330,7 @@ pub fn planes_occur(kind: CounterKind, old: &[u8], new: &[u8], width: usize) -> /// Mutable process scheduling state beyond the delay queue: who waits for /// what, the inactive and post-NBA queues, and the queued nonblocking /// assignments. All of it is empty in a design without process kernels. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ProcessState { pub activations: Vec, pub cells: Vec, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 41d24194d86..d769b5e4a65 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1787,6 +1787,12 @@ pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> .functions .get(name) .is_some_and(|function| function.return_real), + // A sampled value has the type of its operand. + Expr::Call { + callee: Callee::System(SystemFunction::Sampled), + args, + .. + } => matches!(args.first(), Some(Some(operand)) if real_value(operand, dimensions)), Expr::Unary { op: UnaryOp::Plus | UnaryOp::Minus | UnaryOp::ToTwoState, expr, diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index c19568558e4..8b451cf93d7 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -139,6 +139,34 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } + // The sampled value has the type of its operand; the frontend reads + // it from the operand's sampled copy (IEEE 1800-2023 16.9.3). + SystemFunction::Sampled => { + let argument = arguments.pop().ok_or_else(operand_error)?; + // A real operand keeps its type: an integral resize would + // round it. + if expression_binding::real_value(&argument, dimensions) { + return Ok(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }); + } + let width = + expr_static_width(state, &argument, dimensions).ok_or_else(operand_error)?; + let signed = + dimensions::expression_signedness(&argument, dimensions, &dimensions.const_env) + .ok_or_else(operand_error)?; + Ok(Expr::Resize { + expr: Box::new(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }), + width, + signed, + }) + } SystemFunction::Ln | SystemFunction::Log10 | SystemFunction::Exp diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f6e85cb53f9..3b541bf184e 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -60,6 +60,9 @@ pub enum SystemFunction { Signed, /// `$unsigned` (11.7). Unsigned, + /// `$sampled` (IEEE 1800-2023 16.9.3): the value of its operand in the + /// Preponed region of the time slot. + Sampled, /// `$bits` (20.6.2). Bits, /// `$isunbounded` (20.6.3). @@ -253,6 +256,7 @@ impl SystemFunction { Self::Timeprecision => "$timeprecision", Self::Signed => "$signed", Self::Unsigned => "$unsigned", + Self::Sampled => "$sampled", Self::Bits => "$bits", Self::Isunbounded => "$isunbounded", Self::Dimensions => "$dimensions", @@ -354,7 +358,11 @@ impl SystemFunction { /// or it returns the simulation time. Such a call is not a constant /// expression, and a process evaluates it where it runs. pub fn reads_simulation_state(self) -> bool { - self.is_effectful() || matches!(self, Self::Time | Self::Stime | Self::Realtime) + self.is_effectful() + || matches!( + self, + Self::Time | Self::Stime | Self::Realtime | Self::Sampled + ) } /// Whether the call writes argument `position` back, as `$random(seed)` @@ -440,6 +448,7 @@ impl SystemFunction { Self::Time => Some((64, false)), Self::Signed | Self::Unsigned + | Self::Sampled | Self::Bits | Self::Dimensions | Self::UnpackedDimensions @@ -1141,7 +1150,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$assertvacuousoff", Task), unsupported("$assertcontrol", Task), // 20.12 Sampled value system functions - unsupported("$sampled", Function), + function(SystemFunction::Sampled, 1, Some(1)), unsupported("$rose", Function), unsupported("$fell", Function), unsupported("$stable", Function), diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index c830e6a18ce..b2d98151a65 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -389,6 +389,17 @@ pub struct VpiSession { } impl VpiSession { + /// Capture the last evaluated HDL values without dispatching callbacks. + /// + /// VPI callbacks, pending writes, forces and plugin memory are not saved. + /// The returned file is for inspection/diff or HDL-only initialization; + /// it cannot resume a VPI session. Call between dispatch runs or from a + /// read-only synchronization callback for settled values. Other callback + /// phases capture exactly the values currently visible to VPI reads. + pub fn save_state(&self) -> Result { + capture_host_state(&self.host) + } + // The C loader has no Rust caller to retain a guard. Transfer its lifetime // to the explicit celox_vpi_clear_runtime/clear_runtime boundary instead. fn detach(mut self) { @@ -657,6 +668,45 @@ fn install(runtime: Runtime) -> Result { }) } +fn capture_host_state(host: &VpiHost) -> Result { + let runtime = host + .runtime + .try_borrow() + .map_err(|_| "VPI runtime is executing; capture at a callback boundary")?; + runtime + .as_ref() + .ok_or("VPI runtime is unavailable")? + .save_state() + .map_err(|error| error.to_string()) +} + +/// Write a diagnostic HDL state file for the active VPI session. +/// +/// Returns 1 on success, 0 for an unavailable/busy runtime, invalid UTF-8 path, +/// unsupported state value, or I/O failure. Uses the capture contract of +/// [`VpiSession::save_state`]. Existing files at `path` are overwritten. +/// +/// # Safety +/// `path` must be null or point to a readable NUL-terminated UTF-8 string +/// for the duration of this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn celox_vpi_save_state(path: *const c_char) -> i32 { + if path.is_null() { + return 0; + } + // Safety: the caller supplies a readable C string. + let Ok(path) = unsafe { CStr::from_ptr(path) }.to_str() else { + return 0; + }; + let Ok(state) = with_host(capture_host_state) else { + return 0; + }; + let Ok(file) = std::fs::File::create(path) else { + return 0; + }; + i32::from(state.write_to(file).is_ok()) +} + /// Unregister the current thread's host. During callback dispatch this requests /// finish and defers unregistration until the callback run returns. pub fn clear_runtime() { diff --git a/crates/celox-vpi/src/state.rs b/crates/celox-vpi/src/state.rs index 76248f8cb2b..e0d02f2d2e2 100644 --- a/crates/celox-vpi/src/state.rs +++ b/crates/celox-vpi/src/state.rs @@ -29,6 +29,8 @@ pub(crate) trait VpiState { self.image().signal_identity(id) } + fn save_state(&self) -> Result; + /// The stored value, without settling the design. fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint); @@ -46,6 +48,10 @@ pub(crate) trait VpiState { } impl VpiState for NativeProgramInstance { + fn save_state(&self) -> Result { + NativeProgramInstance::save_state(self).map_err(|error| error.to_string()) + } + fn image(&self) -> &NativeProgramImage { self.program_image() } @@ -77,6 +83,7 @@ impl VpiState for NativeProgramInstance { /// entry points that its slot observer's callbacks call reach the state /// through `slot`, which the observer sets for the duration of a dispatch. pub(crate) struct TimedRuntime { + schema: std::sync::Arc, image: NativeProgramImage, pub(crate) simulation: Option>, slot: Option<*mut SlotIo<'static, NativeBackend>>, @@ -87,6 +94,7 @@ pub(crate) struct TimedRuntime { impl TimedRuntime { pub(crate) fn new(image: NativeProgramImage, simulation: Simulation) -> Self { Self { + schema: simulation.state_schema(), image, simulation: Some(simulation), slot: None, @@ -141,6 +149,19 @@ impl TimedRuntime { } impl VpiState for TimedRuntime { + fn save_state(&self) -> Result { + if let Some(slot) = self.slot() { + slot.capture_state(&self.schema) + .map_err(|error| error.to_string()) + } else if let Some(simulation) = &self.simulation { + simulation + .capture_state() + .map_err(|error| error.to_string()) + } else { + Err("VPI runtime is executing; capture at a callback boundary".into()) + } + } + fn image(&self) -> &NativeProgramImage { &self.image } @@ -201,6 +222,10 @@ pub(crate) enum Runtime { } impl Runtime { + pub(crate) fn save_state(&self) -> Result { + self.state().save_state() + } + pub(crate) fn state(&self) -> &dyn VpiState { match self { Runtime::Untimed(instance) => instance, diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 151bb450beb..8f2971e3266 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -157,6 +157,55 @@ fn trusted_instance(image: celox::NativeProgramImage) -> NativeProgramInstance { unsafe { NativeProgramInstance::from_image(image) }.unwrap() } +#[test] +fn vpi_state_capture_matches_simulator_and_preserves_visible_values() { + let _serial = lock_vpi(); + let mut simulator = Simulator::builder(DESIGN, "Top") + .four_state(true) + .build() + .unwrap(); + let expected = simulator.save_state().unwrap(); + let instance = trusted_instance(simulator.shared_code().program_image().clone()); + assert_eq!(instance.save_state().unwrap(), expected); + let session = install_runtime(instance).unwrap(); + let before = session.save_state().unwrap(); + unsafe { + let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); + assert!(!a.is_null()); + let value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 42 }, + }; + vpi_put_value(a, &value, ptr::null(), VPI_NO_DELAY); + let saved = session.save_state().unwrap(); + assert_ne!(saved, before); + assert!(saved.schedule.is_none()); + let a = saved + .objects + .iter() + .find(|object| object.path == "a") + .unwrap(); + assert_eq!(a.value, [42]); + let mut bytes = Vec::new(); + saved.write_to(&mut bytes).unwrap(); + assert_eq!( + celox::StateFile::read_from(bytes.as_slice()).unwrap(), + saved + ); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("vpi.state"); + let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + assert_eq!(celox_vpi_save_state(c_path.as_ptr()), 1); + assert_eq!( + celox::StateFile::read_from(std::fs::File::open(path).unwrap()).unwrap(), + saved + ); + assert_eq!(celox_vpi_save_state(ptr::null()), 0); + // Capturing neither consumes events nor changes HDL values. + assert_eq!(session.save_state().unwrap(), saved); + } +} + const DESIGN: &str = r#" module Child ( i: input logic<8>, @@ -3899,3 +3948,76 @@ fn a_plain_input_settle_reports_fatal_errors() { let error = settle_plain_data_input("$fatal(1, \"fallback failure\");").unwrap_err(); assert!(error.contains("fallback failure"), "{error}"); } + +#[cfg(feature = "systemverilog")] +static TIMED_CAPTURE_STATUS: AtomicI32 = AtomicI32::new(0); + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn capture_timed_read_only(data: *mut VpiCbData) -> i32 { + // Safety: the test keeps its CString alive until callback dispatch returns. + let result = unsafe { celox_vpi_save_state((*data).user_data) }; + TIMED_CAPTURE_STATUS.store(result, Ordering::SeqCst); + 0 +} + +#[cfg(feature = "systemverilog")] +#[test] +fn timed_vpi_capture_reads_the_active_slot_without_advancing_it() { + let _serial = lock_vpi(); + let source = "module Top(output int count); initial begin count=7; #1 count=9; #1 $finish; end endmodule"; + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("capture.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let session = install_timed_runtime(image, simulation).unwrap(); + assert!(session.save_state().unwrap().schedule.is_none()); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("timed.state"); + let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap(); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + ..VpiTime::default() + }; + let callback = VpiCbData { + reason: CB_READ_ONLY_SYNCH, + cb_rtn: Some(capture_timed_read_only), + obj: ptr::null_mut(), + time: &mut time, + value: ptr::null_mut(), + index: 0, + user_data: c_path.as_ptr().cast_mut(), + }; + TIMED_CAPTURE_STATUS.store(0, Ordering::SeqCst); + unsafe { + assert!(!vpi_register_cb(&callback).is_null()); + } + assert!(run_callbacks_result().unwrap()); + assert_eq!(TIMED_CAPTURE_STATUS.load(Ordering::SeqCst), 1); + let saved = celox::StateFile::read_from(std::fs::File::open(path).unwrap()).unwrap(); + assert!(saved.schedule.is_none()); + assert_eq!( + saved + .objects + .iter() + .find(|o| o.path == "count") + .unwrap() + .value, + [7, 0, 0, 0] + ); + let final_state = session.save_state().unwrap(); + assert_eq!( + final_state + .objects + .iter() + .find(|o| o.path == "count") + .unwrap() + .value, + [9, 0, 0, 0] + ); +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b605d44113b..c859ebdaebb 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -418,6 +418,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) host_request_sites: Vec>, pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, + #[serde(default)] + pub(crate) sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, pub(crate) scheduler: Option>, pub(crate) derived_edges: Vec>, } @@ -491,6 +493,11 @@ impl NativeProgramImage { &self.reflection } + /// Design metadata used to name saved state objects. + pub(crate) fn state_design(&self) -> &crate::ir::RuntimeDesign { + &self.design + } + /// Source-independent runtime diagnostics and combinational observers. pub(crate) fn runtime_schema(&self) -> &NativeRuntimeSchema { &self.runtime_schema @@ -591,6 +598,7 @@ impl NativeProgramImage { host_request_sites: self.runtime_schema.host_request_sites.clone(), active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), + sample_shadows: self.runtime_schema.sample_shadows.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), settle_partitions: None, @@ -2640,6 +2648,7 @@ fn compile_program( declaration_startup: sir.runtime().runtime_schema.declaration_startup.clone(), active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), + sample_shadows: sir.runtime().runtime_schema.sample_shadows.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a697a472d00..1b329072c48 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 41; +const CONTAINER_VERSION: u16 = 42; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index c13435839e2..ba5433e1228 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -126,6 +126,27 @@ impl NativeProgramInstance { unsafe { Self::from_image(appended.image) } } + /// Capture HDL values as last evaluated, without executing code or callbacks. + /// + /// This diagnostic state file excludes VPI callbacks, pending writes, force + /// registrations, plugin memory and time scheduling. It has no schedule and + /// is not a resumable VPI session. Signal values include currently applied + /// forces; output already emitted is not withdrawn. + pub fn save_state(&self) -> Result { + let image = self.shared.program_image(); + let schema = image.runtime_schema(); + crate::StateSchema::from_design( + &self.backend, + image.state_design(), + |address| schema.comb_writes.contains(address), + schema + .time_slots + .iter() + .chain(schema.scheduler.iter().flat_map(|s| s.slots.iter())), + ) + .capture(&self.backend) + } + /// Physical duration of one tick in the attached design. pub fn time_precision(&self) -> celox_design::TimePrecision { self.shared.program_image().time_precision() diff --git a/crates/celox/src/comb_activation.rs b/crates/celox/src/comb_activation.rs index 293f2e5eecf..060e674f50c 100644 --- a/crates/celox/src/comb_activation.rs +++ b/crates/celox/src/comb_activation.rs @@ -39,7 +39,7 @@ pub(crate) struct ObserverReads { } /// The values one observer's reads returned. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) struct ObserverSnapshot { words: Vec, wide: Vec<(BigUint, BigUint)>, diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index b7dc82d5a5f..7055ed180c1 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -118,7 +118,9 @@ mod host_api { }; pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; - pub use crate::simulation::{Simulation, SimulationCheckpoint, SlotObserver}; + pub use crate::simulation::{ + CheckpointFileError, Simulation, SimulationCheckpoint, SlotObserver, + }; #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -197,6 +199,16 @@ mod host_api { } } + /// Capture current HDL values without running any simulation regions. + /// Use the schema obtained from this simulation before entering the slot. + /// This diagnostic file has no schedule and is not a resumable checkpoint. + pub fn capture_state( + &self, + schema: &crate::StateSchema, + ) -> Result { + schema.capture(self.io.backend) + } + /// End the simulation when this observer callback returns, before /// any further scheduled work runs. Earlier host writes remain in state. pub fn request_finish(&mut self) { @@ -318,3 +330,6 @@ pub use signal_access::SignalAccessOptions; mod timescale; pub use timescale::SvTimescale; + +/// Host-injected file I/O and snapshot contracts. +pub use celox_runtime::file_io_backend::{FileMode, FileSystem, FileSystemFactory, HostFileSystem}; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index dfc7e05abd1..842dafc65e4 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -11,6 +11,8 @@ use celox_runtime::{ UnitExecutor, host_watch, }; +mod checkpoint_file; +pub use checkpoint_file::CheckpointFileError; mod differential; mod vcd_tasks; @@ -271,19 +273,14 @@ impl HostBoundary for Simulator { fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; - // Deferred assertions mature when a slot is over, which the - // runtime's loop tells apart from the end of a step. - if self.frozen - || !self.components.is_empty() - || self.deferred_assertions - || !self.backend.runs_compiled_scheduler() - { + if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { return CompiledSlots::None; } - // Waveforms record, the heap collects and a slot observer looks at - // every slot boundary. + // Waveforms record, the heap collects, deferred assertions mature + // and a slot observer looks at every slot boundary. let vcd = &self.sv_vcd; - if self.slot_observer.is_some() + if self.deferred_assertions + || self.slot_observer.is_some() || self.vcd_writer.is_some() || vcd.path.is_some() || vcd.started.is_some() @@ -458,6 +455,9 @@ impl Simulation { simulator.timed = true; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; + // Before the first slot, a sampled value is the declared or default + // value (IEEE 1800-2023 16.5.1). + state.sample_values(&mut simulator.backend); Ok(Self { simulator, state, @@ -479,6 +479,8 @@ impl Simulation { } /// Save the design state, simulation time, clocks and pending events. + /// Effect-handler state (including file I/O and VPI) is excluded. The host + /// system coordinates its own handler snapshots with this core checkpoint. pub fn checkpoint(&self) -> Result, CheckpointError> { if self.state.is_suspended() { return Err(CheckpointError::Stopped); @@ -490,6 +492,27 @@ impl Simulation { }) } + /// File-I/O effect state owned by the embedding system, outside core checkpoints. + pub fn file_io(&self) -> &celox_runtime::file_io::FileIo { + self.simulator.file_io() + } + + /// Install a host-prepared file-I/O handler at an execution boundary. + pub fn replace_file_io(&mut self, file_io: celox_runtime::file_io::FileIo) { + self.simulator.replace_file_io(file_io); + } + + /// The schema used for diagnostic HDL captures, including observer callbacks. + pub fn state_schema(&self) -> std::sync::Arc { + self.simulator.state_schema() + } + + /// Capture current HDL values without settling or advancing time. The file + /// has no schedule and cannot resume a timed simulation or a VPI session. + pub fn capture_state(&self) -> Result { + self.state_schema().capture(&self.simulator.backend) + } + /// Save the value of every state object by path, together with the /// simulation time, clocks and pending events by name. pub fn save_state(&mut self) -> Result { @@ -563,7 +586,8 @@ impl Simulation { .filter(|local| local.addr() == event.addr()) }) .map_err(|_| CheckpointError::DesignMismatch)?; - self.simulator.restore(&checkpoint.simulator)?; + self.simulator + .restore_checkpoint_prepared(&checkpoint.simulator)?; self.state.retain_activation_roots(&mut self.simulator); self.simulator.declaration_phase = false; self.simulator @@ -761,7 +785,7 @@ impl Simulation { /// run at that time. #[inline] fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if !self.simulator.deferred_assertions + if !self.simulator.host_slot_work || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { diff --git a/crates/celox/src/simulation/checkpoint_file.rs b/crates/celox/src/simulation/checkpoint_file.rs new file mode 100644 index 00000000000..7ce107a4170 --- /dev/null +++ b/crates/celox/src/simulation/checkpoint_file.rs @@ -0,0 +1,105 @@ +//! Persistence of core execution state. Effect-handler state belongs to the host. +use super::{Simulation, SimulationCheckpoint}; +use crate::{CheckpointError, SimBackend, simulator::checkpoint::PersistedCheckpoint}; +use celox_runtime::PersistedSimulationSnapshot; +use serde::{Deserialize, Serialize}; + +const MAGIC: &[u8; 8] = b"CELOXCP1"; +// Bump whenever a serialized core-state schema or its interpretation changes. +const VERSION: u32 = 1; + +#[derive(Debug, thiserror::Error)] +pub enum CheckpointFileError { + #[error("invalid or incompatible checkpoint container")] + InvalidContainer, + #[error("checkpoint encoding failed: {0}")] + Encoding(#[from] postcard::Error), + #[error(transparent)] + Checkpoint(#[from] CheckpointError), +} + +#[derive(Serialize, Deserialize)] +struct CoreState { + version: u32, + release: String, + architecture: String, + little_endian: bool, + simulator: PersistedCheckpoint, + schedule: PersistedSimulationSnapshot, + host_writes: Vec<(crate::ir::SignalRef, celox_runtime::timing::Value)>, +} + +fn checksum(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf29ce484222325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3) + }) +} + +impl SimulationCheckpoint { + /// Encode core execution state, including live fork activations and heap + /// objects. No effect-handler state or machine-code addresses are included. + /// This is a versioned implementation format, not a portable StateFile. + pub fn to_bytes(&self) -> Result, CheckpointFileError> { + let payload = postcard::to_allocvec(&CoreState { + version: VERSION, + release: env!("CARGO_PKG_VERSION").into(), + architecture: std::env::consts::ARCH.into(), + little_endian: cfg!(target_endian = "little"), + simulator: self.simulator.persisted(), + schedule: self.schedule.persisted(), + host_writes: self.host_writes.clone(), + })?; + let mut bytes = Vec::with_capacity(24 + payload.len()); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&(payload.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&checksum(&payload).to_le_bytes()); + bytes.extend(payload); + Ok(bytes) + } +} + +impl Simulation { + /// Decode a checkpoint and bind its event IDs to this compiled instance. + /// This does not change the simulation or any effect handler. + /// + /// # Safety + /// `bytes` must be an unmodified result of `SimulationCheckpoint::to_bytes` + /// from a compatible Celox build. The container checks version, layout and + /// accidental corruption; it does not authenticate arbitrary memory offsets + /// or process state supplied by an attacker. Never load untrusted checkpoints. + pub unsafe fn checkpoint_from_bytes( + &self, + bytes: &[u8], + ) -> Result, CheckpointFileError> { + if bytes.len() < 24 || &bytes[..8] != MAGIC { + return Err(CheckpointFileError::InvalidContainer); + } + let size = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); + let hash = u64::from_le_bytes(bytes[16..24].try_into().unwrap()); + let payload = &bytes[24..]; + if size != payload.len() as u64 || hash != checksum(payload) { + return Err(CheckpointFileError::InvalidContainer); + } + let (state, remainder): (CoreState, _) = postcard::take_from_bytes(payload)?; + if !remainder.is_empty() + || state.version != VERSION + || state.release != env!("CARGO_PKG_VERSION") + || state.architecture != std::env::consts::ARCH + || state.little_endian != cfg!(target_endian = "little") + { + return Err(CheckpointFileError::InvalidContainer); + } + Ok(SimulationCheckpoint { + simulator: state.simulator.bind(&self.simulator)?, + // SAFETY: the caller guarantees a trusted checkpoint and bind above + // checked that its core layout belongs to this design. + schedule: unsafe { + state + .schedule + .bind::(self.simulator.backend.id_to_event_slice()) + } + .ok_or(CheckpointError::DesignMismatch)?, + host_writes: state.host_writes, + }) + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d0e1e8c7398..9e2fe8c1d99 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1,6 +1,6 @@ mod builder; #[cfg(feature = "host-runtime")] -mod checkpoint; +pub(crate) mod checkpoint; mod error; #[cfg(feature = "host-runtime")] mod heap; @@ -130,7 +130,7 @@ mod host { /// may run: between the polls of concurrent testbench processes. pub(crate) heap_safepoints_blocked: bool, pub(crate) process_heap_roots: Vec, - file_io: celox_runtime::file_io::FileIo, + pub(super) file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, /// The program's scheduling facts. @@ -161,6 +161,12 @@ mod host { /// A timed simulation owns this simulator: a time slot ends when its /// scheduler says so, not when combinational logic settles. pub(crate) timed: bool, + /// Sampled variables and their copies + /// (`RuntimeSchema::sample_shadows`). + sample_shadows: Vec<(SignalRef, SignalRef)>, + /// Deferred assertions or sampled copies have work when a host + /// call's time slot is over. + pub(crate) host_slot_work: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -1030,6 +1036,17 @@ mod host { } else { Vec::new() }; + let sample_shadows: Vec<(SignalRef, SignalRef)> = program + .runtime_schema + .sample_shadows + .iter() + .map(|(variable, copy)| { + ( + backend.resolve_signal(variable), + backend.resolve_signal(copy), + ) + }) + .collect(); let mut comb_deferred_groups: Vec<(u32, usize)> = Vec::new(); for observer in &program.runtime_schema.comb_observers { if matches!( @@ -1066,6 +1083,8 @@ mod host { deferred_assertions: !deferred_sites.is_empty(), comb_deferred_groups, timed: false, + host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + sample_shadows, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1321,13 +1340,12 @@ mod host { } } - /// Without a scheduler, a host call is a time slot: mature the - /// deferred assertions it ran. + /// Without a scheduler, a host call is a time slot: end it. fn end_untimed_slot(&mut self) -> Result<(), RuntimeErrorCode> { if self.timed { return Ok(()); } - self.mature_deferred_assertions() + self.end_host_slot() } pub(crate) fn drain_runtime_events_deferred_with_context( @@ -1469,6 +1487,53 @@ mod host { self.host_watch.set_log(other.host_watch.log().to_vec()); } + /// A host call without a scheduler is a time slot, which is over: + /// deferred assertions mature, then the sampled copies are made. + #[inline] + fn end_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work { + return Ok(()); + } + self.finish_host_slot() + } + + /// A host call without a scheduler begins a time slot. Logic that + /// host writes since the previous call left dirty settles first, in + /// the previous slot, which then ends: the call's domains sample the + /// values it settled to, and settles within the call do not change + /// them. + #[inline] + fn begin_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work || !self.dirty || self.timed { + return Ok(()); + } + self.settle_host_slot() + } + + #[cold] + #[inline(never)] + fn settle_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.eval_comb_checked()?; + self.dirty = false; + self.finish_host_slot() + } + + #[cold] + #[inline(never)] + fn finish_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.mature_deferred_assertions()?; + self.sample_values(); + Ok(()) + } + + /// Copy each sampled variable into its copy (IEEE 1800-2023 + /// 16.5.1). + pub(crate) fn sample_values(&mut self) { + for &(variable, copy) in &self.sample_shadows { + celox_runtime::copy_signal(&mut self.backend, variable, copy); + } + } + /// The time slot ends: the actions of deferred assertions that their /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. @@ -2054,8 +2119,10 @@ mod host { // Nothing the domain runs reads the level, which is the // inactive one before and after the period: both stores are // unobservable, and the period is one run of the domain. - return self.fire(event); + // The call begins its slot in the domain's run. + return self.fire_from::(event); } + self.begin_host_slot()?; let moved = celox_runtime::move_signal( &mut self.backend, &info, @@ -2099,13 +2166,27 @@ mod host { /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - let result = self.fire_unit(event); + self.fire_from::(event) + } + + /// [`Self::fire`]; with `BEGIN`, also the start of the host call, + /// whose slot [`Self::begin_host_slot`] begins in the domain's run, + /// where the clock that nothing reads has already moved. + #[inline] + fn fire_from( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { + let result = self.fire_unit::(event); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions() + self.end_host_slot() } - fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + fn fire_unit( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -2113,7 +2194,10 @@ mod host { let mut eval_comb_ns = 0u64; let mut eval_apply_ns = 0u64; if self.dirty { - if timing_enabled { + if BEGIN && self.host_slot_work && !self.timed { + self.settle_host_slot()?; + self.eval_apply_ff_at_checked(event)?; + } else if timing_enabled { let start = crate::timing::now(); self.eval_comb_checked()?; eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64); @@ -2180,7 +2264,12 @@ mod host { return Ok(()); } // No derived domains: move the signal, then run the event's - // domain. + // domain. Logic that reads the signal settles before it + // moves; otherwise the call begins its slot in the domain's + // run. + if info.comb_read { + self.begin_host_slot()?; + } let write = watched_write(&mut self.host_watch); let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) else { @@ -2190,13 +2279,18 @@ mod host { self.dirty = true; } if info.fires(old, edge) { - return self.fire(event); + return if info.comb_read { + self.fire(event) + } else { + self.fire_from::(event) + }; } if !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; } return Ok(()); } + self.begin_host_slot()?; if let Some(Some(unit)) = self.derived_units.get(event.id()).copied() && !self.finish_sites && self.backend.runs_derived_edge_units() @@ -2264,8 +2358,7 @@ mod host { } /// Settle the outcome of [`celox_runtime::run_edge`] or - /// [`celox_runtime::run_edges`], and mature the deferred assertions - /// they ran. + /// [`celox_runtime::run_edges`], and end the time slot they ran. fn note_edge( &mut self, outcome: Result, @@ -2288,7 +2381,7 @@ mod host { Err(celox_runtime::Halt::Error(error)) => return Err(error), } // The edges are a time slot, as a tick is. - self.mature_deferred_assertions() + self.end_host_slot() } /// A rising edge of `event`'s signal; see [`Self::edge`]. @@ -2328,6 +2421,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; let plans = std::sync::Arc::clone(&self.derived_ticks); let edges = std::sync::Arc::clone(&self.event_edges); let mut scratch = self.derived_scratch.take().unwrap_or_default(); @@ -2432,6 +2526,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; if let [event] = events { return self.tick(*event); } @@ -2492,7 +2587,7 @@ mod host { let result = self.tick_events_unit(&fired); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions()?; + self.end_host_slot()?; for &event in events { let info = self.event_edges[event.id()]; self.backend @@ -2594,8 +2689,11 @@ mod host { ) -> Result<(), RuntimeErrorCode> { if !self.program.runtime_schema.comb_observers.is_empty() || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { - // Derived domains need the settled state to see their edges. + // Derived domains need the settled state to see their edges, + // and each tick of a design with slot work is a host call. + self.begin_host_slot()?; return self.fire(event); } if self.dirty { @@ -2634,6 +2732,7 @@ mod host { if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { return (1, self.tick_deferred_comb(event)); } @@ -3380,6 +3479,46 @@ mod host { } } + #[test] + fn signal_copy_accepts_an_aliased_four_state_view() { + let mut sim = Simulator::builder("module Top (data: input logic<32>) {}", "Top") + .four_state(true) + .build_interpreter() + .unwrap(); + let signal = sim.try_child_signal(&[], "data").unwrap(); + let value = BigUint::from(0x1234u32); + let mask = BigUint::from(0x00ffu32); + sim.backend + .set_four_state(signal, value.clone(), mask.clone()); + celox_runtime::copy_signal(&mut sim.backend, signal, signal); + assert_eq!(sim.backend.get_four_state(signal), (value, mask)); + } + + /// Batched testbench ticks end each tick's slot in a design with + /// sampled values: a register capturing `$sampled(count)` follows + /// the preceding tick. + #[cfg(feature = "systemverilog")] + #[test] + fn batched_testbench_ticks_end_each_slot() { + let source = "module Top(input bit clk, output bit [7:0] count, output bit [7:0] seen);\n \ + always_ff @(posedge clk) begin count <= count + 1; seen <= $sampled(count); end\n\ + endmodule"; + let mut sim = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("t.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.dirty = true; + let mut done = 0; + while done < 3 { + let (ran, result) = sim.tick_deferred_comb_many(clk, 3 - done); + result.unwrap(); + done += ran; + } + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), BigUint::from(2u8)); + } + #[test] fn edges_leave_a_finished_simulation_unchanged() { let mut sim = Simulator::builder(GATED_COUNTER, "Top").build().unwrap(); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index c1d98a11ac8..701aa5286ed 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1704,6 +1704,8 @@ mod host { pub dpi: crate::DpiSymbols, /// Ordered command-line arguments for SystemVerilog plusargs queries. pub plusargs: Vec, + /// Host I/O factory; each simulator receives an independent instance. + pub file_system: celox_runtime::file_io_backend::FileSystemFactory, /// The loop that runs the time slots of a [`crate::Simulation`]. #[doc(hidden)] pub scheduler: crate::SchedulerMode, @@ -1798,6 +1800,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); } @@ -2003,6 +2006,7 @@ mod host { allow_inferred_latches: false, dpi: crate::DpiSymbols::default(), plusargs: Vec::new(), + file_system: Default::default(), scheduler: crate::SchedulerMode::default(), } } @@ -2162,6 +2166,21 @@ mod host { self } + /// Supply the host filesystem for runtime file tasks. The factory is + /// invoked before declaration initialization for each simulator. + /// Snapshot behavior is defined by the returned [`crate::FileSystem`]. + pub fn file_system( + mut self, + factory: impl Fn() -> Box + + Send + + Sync + + 'static, + ) -> Self { + self.options.file_system = + celox_runtime::file_io_backend::FileSystemFactory::new(factory); + self + } + /// Set the ordered arguments queried by `$test$plusargs` and /// `$value$plusargs`. A leading `+` is optional on each argument. /// Queries currently require a timed procedural process, such as an @@ -3049,6 +3068,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3103,6 +3123,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3160,6 +3181,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3231,6 +3253,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3445,6 +3468,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3663,6 +3687,8 @@ mod host { .set_injected(self.injected_components.clone()); sim.diagnostics = self.options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(self.options.plusargs.clone()); + sim.file_io = + celox_runtime::file_io::FileIo::new(self.options.file_system.create()); sim.apply_initial_values(); sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) @@ -3989,12 +4015,10 @@ mod host { )?; // Host state outside the memory image, such as open files, // cannot be shared with a shadow. - Ok(Some( - match shadow.simulator.check_host_checkpoint_support() { - Ok(()) => Ok(Box::new(shadow)), - Err(_) => Err("the design keeps host state outside its memory image"), - }, - )) + Ok(Some(match shadow.simulator.check_host_restore_support() { + Ok(()) => Ok(Box::new(shadow)), + Err(_) => Err("the design keeps host state outside its memory image"), + })) } /// Load `image` into executable memory and start a timed simulation @@ -4087,6 +4111,7 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 29d48e87623..ecbd56e5388 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -121,17 +121,13 @@ impl std::fmt::Debug for Checkpoint { /// Reasons a checkpoint cannot be taken or restored. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum CheckpointError { - /// External component instances hold opaque state. They currently exist - /// only while a testbench runs, when no checkpoint can be taken. - #[error( - "checkpoints are not supported for designs with external components, whose state Celox cannot capture" - )] + /// Portable state-file APIs exclude opaque external component instances. + /// Core checkpoint capture and restore do not depend on their state. + #[error("portable state files do not capture opaque external component state")] ExternalComponents, /// Source-driven files and waveform controls have host state that is /// not represented in the saved HDL memory image. - #[error( - "checkpoints and state files are not supported for designs with SystemVerilog file I/O or VCD control tasks" - )] + #[error("the saved state does not include restorable external file I/O or VCD control state")] ExternalSystemTasks, #[error("the checkpoint was taken from a different design")] DesignMismatch, @@ -154,13 +150,13 @@ pub enum CheckpointError { impl Simulator { /// Save the current design state. /// + /// This captures only core execution state. Effect handlers, including file + /// I/O and VPI, retain their own state. The embedding system coordinates + /// their checkpoints with this one at a quiescent execution boundary. + /// /// Inputs written since the last evaluation are part of the saved state; /// combinational logic is settled again after a restore. pub fn checkpoint(&self) -> Result { - self.check_host_checkpoint_support()?; - if !self.components.is_empty() { - return Err(CheckpointError::ExternalComponents); - } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), comb_observer_snapshots: self.comb_observer_snapshots.clone(), @@ -177,6 +173,13 @@ impl Simulator { /// simulation, continue in a new file with [`Self::switch_vcd`]. pub fn restore(&mut self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { self.validate_restore(checkpoint)?; + self.restore_checkpoint_prepared(checkpoint) + } + + pub(crate) fn restore_checkpoint_prepared( + &mut self, + checkpoint: &Checkpoint, + ) -> Result<(), CheckpointError> { let fingerprint = self.state_fingerprint(); self.frozen = checkpoint.frozen; checkpoint @@ -195,17 +198,24 @@ impl Simulator { /// Check every precondition of [`Self::restore`] without changing state. pub(crate) fn validate_restore(&self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { - self.check_host_checkpoint_support()?; - if !self.components.is_empty() { - return Err(CheckpointError::ExternalComponents); - } if !checkpoint.image.matches(self.state_fingerprint()) { return Err(CheckpointError::DesignMismatch); } Ok(()) } - pub(crate) fn check_host_checkpoint_support(&self) -> Result<(), CheckpointError> { + /// The file-I/O effect handler. Its state is deliberately outside core + /// checkpoints; an embedding system may snapshot it separately. + pub fn file_io(&self) -> &celox_runtime::file_io::FileIo { + &self.file_io + } + + /// Replace the file-I/O effect handler at a host execution boundary. + pub fn replace_file_io(&mut self, file_io: celox_runtime::file_io::FileIo) { + self.file_io = file_io; + } + + pub(crate) fn check_host_restore_support(&self) -> Result<(), CheckpointError> { if self .program .runtime_schema @@ -231,3 +241,50 @@ impl Simulator { .get_or_init(|| crate::ir::state_fingerprint(self.backend.layout(), &self.program)) } } + +// Only this private wire type implements Deserialize: a safe API must not be +// able to construct a Checkpoint containing arbitrary memory offsets. +#[derive(serde::Serialize, serde::Deserialize)] +pub(crate) struct PersistedCheckpoint { + fingerprint: u64, + bytes: Box<[u8]>, + heap: celox_heap::Heap, + observers: Vec, + initial_eval: bool, + frozen: bool, +} +impl Checkpoint { + pub(crate) fn persisted(&self) -> PersistedCheckpoint { + PersistedCheckpoint { + fingerprint: self.image.fingerprint, + bytes: self.image.bytes.clone(), + heap: self.image.heap.clone(), + observers: self.comb_observer_snapshots.clone(), + initial_eval: self.comb_observer_initial_eval, + frozen: self.frozen, + } + } +} +impl PersistedCheckpoint { + pub(crate) fn bind( + self, + simulator: &Simulator, + ) -> Result { + if self.fingerprint != simulator.state_fingerprint() + || self.bytes.len() != state_range(&simulator.backend).len() + || self.observers.len() != simulator.comb_observer_snapshots.len() + { + return Err(CheckpointError::DesignMismatch); + } + Ok(Checkpoint { + image: StateImage { + fingerprint: self.fingerprint, + bytes: self.bytes, + heap: self.heap, + }, + comb_observer_snapshots: self.observers, + comb_observer_initial_eval: self.initial_eval, + frozen: self.frozen, + }) + } +} diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 1420c5d1975..913589e4aea 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -253,19 +253,20 @@ impl Simulator { ) }) .collect(); - celox_runtime::file_io::FileIo::write_memory( - path, - site.operation == 5, - words.iter().map(|(value, mask)| DisplayFormatArg { - value, - mask: Some(mask), - width, - signed: false, - is_string: false, - float_precision: None, - }), - ) - .map_err(|err| error(format!("$writemem: {err}")))?; + self.file_io + .write_memory_with_backend( + path, + site.operation == 5, + words.iter().map(|(value, mask)| DisplayFormatArg { + value, + mask: Some(mask), + width, + signed: false, + is_string: false, + float_precision: None, + }), + ) + .map_err(|err| error(format!("$writemem: {err}")))?; } _ => return Err(error("unknown file I/O request".into())), } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 3ef0f4727cf..c65ea6a9156 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -129,6 +129,65 @@ pub struct StateSchema { } impl StateSchema { + pub(crate) fn from_design<'a, B: SimBackend>( + backend: &B, + design: &crate::ir::RuntimeDesign, + is_comb: impl Fn(&crate::AbsoluteAddr) -> bool, + time_slots: impl Iterator, + ) -> Self { + let time_slots: crate::HashSet<_> = time_slots.collect(); + // Build-specific partitioned-settle flags are recomputed on load. + let settle_flags = backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags_offset); + let mut objects: Vec<_> = backend + .layout() + .offsets + .keys() + .filter(|address| !time_slots.contains(address)) + .filter(|address| Some(backend.layout().offsets[*address]) != settle_flags) + .map(|&address| (design.get_path(&address), address)) + .collect(); + objects.sort_unstable(); + let mut named = Vec::with_capacity(objects.len()); + let mut index = 0; + while index < objects.len() { + let path = &objects[index].0; + let end = objects[index..] + .iter() + .position(|(other, _)| other != path) + .map_or(objects.len(), |offset| index + offset); + for (ordinal, (path, address)) in objects[index..end].iter().enumerate() { + named.push(NamedObject { + path: if end - index == 1 { + path.clone() + } else { + format!("{path}#{ordinal}") + }, + signal: backend.resolve_signal(address), + role: if is_comb(address) { + StateRole::Comb + } else { + StateRole::State + }, + strings: design.state_objects.get(address).is_some_and(|metadata| { + metadata.value_kind == celox_design::ValueKind::StrRef + }), + objects: design.state_objects.get(address).is_some_and(|metadata| { + metadata.value_kind == celox_design::ValueKind::ObjRef + }), + }); + } + index = end; + } + StateSchema { + four_state: backend.layout().four_state, + objects: named, + } + } + /// Save the value of every state object of `backend` as last evaluated. /// /// Fails if a variable holds a class object. @@ -300,7 +359,9 @@ impl Simulator { /// Save the value of every state object, by path. /// /// Combinational values are settled first, so the file shows the values - /// a read would return. + /// a read would return. Unlike [`Self::checkpoint`], this portable format + /// does not include a host filesystem snapshot. File/VCD designs can be + /// saved for inspection, but loading them is rejected. pub fn save_state(&mut self) -> Result { self.prepare_save_state()?; self.state_schema().capture(&self.backend) @@ -309,7 +370,6 @@ impl Simulator { /// Validate support and settle before a timed owner synchronizes termination. /// Capture must follow that synchronization, since final procedures can write state. pub(crate) fn prepare_save_state(&mut self) -> Result<(), StateError> { - self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -343,6 +403,7 @@ impl Simulator { if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } + self.check_host_restore_support()?; // Evaluating the loaded state can still fail (an oscillating // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; @@ -379,76 +440,16 @@ impl Simulator { /// Name the state objects: the hierarchical path, followed by `#n` when /// several objects share it. fn build_state_schema(&self) -> StateSchema { - let comb_writes = &self.program.runtime_schema.comb_writes; - // A timed simulation stores its time into the time slots, and a state - // file keeps the time in its schedule; an untimed one reads zero. - // A compiled scheduler's slots hold nothing between runs, and the - // flags of a partitioned settle describe how this build settles, - // not the design: loading state sets them. - let time_slots: crate::HashSet<_> = self - .program - .runtime_schema - .time_slots - .iter() - .chain( - self.program - .runtime_schema - .scheduler - .iter() - .flat_map(|scheduler| scheduler.slots.iter()), - ) - .collect(); - let settle_flags = self - .backend - .layout() - .settle - .as_ref() - .map(|settle| settle.flags_offset); - let mut objects: Vec<_> = self - .backend - .layout() - .offsets - .keys() - .filter(|address| !time_slots.contains(address)) - .filter(|address| Some(self.backend.layout().offsets[*address]) != settle_flags) - .map(|&address| (self.program.get_path(&address), address)) - .collect(); - objects.sort_unstable(); - let mut named = Vec::with_capacity(objects.len()); - let mut index = 0; - while index < objects.len() { - let path = &objects[index].0; - let end = objects[index..] + let schema = &self.program.runtime_schema; + StateSchema::from_design( + &self.backend, + &self.program.design, + |address| schema.comb_writes.contains(address), + schema + .time_slots .iter() - .position(|(other, _)| other != path) - .map_or(objects.len(), |offset| index + offset); - for (ordinal, (path, address)) in objects[index..end].iter().enumerate() { - named.push(NamedObject { - path: if end - index == 1 { - path.clone() - } else { - format!("{path}#{ordinal}") - }, - signal: self.backend.resolve_signal(address), - role: if comb_writes.contains(address) { - StateRole::Comb - } else { - StateRole::State - }, - strings: self.program.design.state_objects.get(address).is_some_and( - |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, - ), - objects: self.program.design.state_objects.get(address).is_some_and( - |metadata| metadata.value_kind == celox_design::ValueKind::ObjRef, - ), - }); - } - index = end; - } - StateSchema { - four_state: self.backend.layout().four_state, - objects: named, - } + .chain(schema.scheduler.iter().flat_map(|s| s.slots.iter())), + ) } /// Express a schedule by event and signal names. diff --git a/crates/celox/tests/checkpoint.rs b/crates/celox/tests/checkpoint.rs index 1735334528f..978a023f83f 100644 --- a/crates/celox/tests/checkpoint.rs +++ b/crates/celox/tests/checkpoint.rs @@ -314,6 +314,9 @@ fn simulation_restore_rewinds_time_and_clocks() { sim.add_clock("clk", 10, 5); timed_trace(&mut sim, 100); let checkpoint = sim.checkpoint().unwrap(); + let bytes = checkpoint.to_bytes().unwrap(); + // SAFETY: this is the unchanged encoding of this simulation's checkpoint. + let checkpoint = unsafe { sim.checkpoint_from_bytes(&bytes) }.unwrap(); assert_eq!(checkpoint.time(), sim.time()); let expected = timed_trace(&mut sim, 400); sim.restore(&checkpoint).unwrap(); @@ -365,3 +368,63 @@ fn simulation_restore_refuses_to_rewind_vcd_until_switched() { sim.flush_vcd().unwrap(); assert_eq!(std::fs::read_to_string(&second).unwrap(), vcd); } + +#[cfg(feature = "systemverilog")] +mod persisted_core { + use std::path::Path; + const SOURCE: &str = r#" +module Top(output int value, output string text); + timeunit 1ns; timeprecision 1ns; + initial begin + text = "checkpoint"; + fork + begin #2; value += 3; text = {text, "-child"}; end + begin #4; value += 7; end + join + #1; value += 10; + end +endmodule +"#; + macro_rules! case { + ($name:ident, $build:ident) => { + #[test] + fn $name() { + let build = || { + celox::Simulation::from_sv_sources( + vec![(SOURCE, Path::new("persisted.sv"))], + "Top", + ) + .$build() + .unwrap() + }; + let mut source = build(); + source.run_until(1).unwrap(); + let bytes = source.checkpoint().unwrap().to_bytes().unwrap(); + source.run_until(6).unwrap(); + let expected = source.capture_state().unwrap(); + let mut restored = build(); + // SAFETY: unchanged bytes from the same build's checkpoint encoder. + let checkpoint = unsafe { restored.checkpoint_from_bytes(&bytes) }.unwrap(); + restored.restore(&checkpoint).unwrap(); + assert_eq!(restored.time(), 1); + restored.run_until(6).unwrap(); + assert_eq!(restored.capture_state().unwrap(), expected); + for length in [0, 8, 23, bytes.len() - 1] { + assert!(unsafe { restored.checkpoint_from_bytes(&bytes[..length]) }.is_err()); + } + let mut corrupt = bytes.clone(); + *corrupt.last_mut().unwrap() ^= 1; + assert!(unsafe { restored.checkpoint_from_bytes(&corrupt) }.is_err()); + } + }; + } + case!(interpreter, build_interpreter); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + case!(native, build_native); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + case!(tiered, build_tiered); + #[cfg(feature = "cranelift")] + case!(cranelift, build_cranelift); + #[cfg(feature = "wasm-runtime")] + case!(wasm, build_wasm); +} diff --git a/crates/celox/tests/sv_host_requests.rs b/crates/celox/tests/sv_host_requests.rs index 9c0263d47b7..031b3eecb89 100644 --- a/crates/celox/tests/sv_host_requests.rs +++ b/crates/celox/tests/sv_host_requests.rs @@ -83,7 +83,7 @@ mixed_requests!(wasm, build_wasm); mixed_requests!(native, build_native); #[test] -fn external_host_state_rejects_checkpoints_and_state_files() { +fn core_checkpoint_does_not_own_external_host_state() { for statement in ["$fwrite(1, \"output\");", "$dumpvars;"] { let source = format!("module Top(output bit q); initial begin {statement} q = 1; end endmodule"); @@ -93,16 +93,175 @@ fn external_host_state_rejects_checkpoints_and_state_files() { ) .build_interpreter() .unwrap(); - assert!(matches!( - simulation.checkpoint(), - Err(celox::CheckpointError::ExternalSystemTasks) - )); - assert!( - simulation - .save_state() - .unwrap_err() - .to_string() - .contains("SystemVerilog file I/O or VCD") - ); + let checkpoint = simulation.checkpoint().unwrap(); + let file = simulation.save_state().unwrap(); + simulation.restore(&checkpoint).unwrap(); + assert!(simulation.load_state(&file).is_err()); } } + +#[path = "test_utils/file_system.rs"] +mod file_system; + +const IO_SNAPSHOT_SOURCE: &str = r#" +module Top(output int value, count); + timeunit 1ps; timeprecision 1ps; + int fd = $fopen("input", "r"); + int n; + initial begin + n = $fscanf(fd, "%d", value); + #1; + value = $fgetc(fd); + count++; + $fclose(fd); + fd = $fopen("output", "w"); + $fwrite(fd, "%c", value); + $fclose(fd); + #1; + end +endmodule +"#; + +macro_rules! io_snapshot { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let build = || { + celox::Simulation::from_sv_sources( + vec![(IO_SNAPSHOT_SOURCE, Path::new("io_snapshot.sv"))], + "Top", + ) + .file_system(|| Box::::default()) + }; + let mut sim = build().$backend().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 12u32.into()); + let checkpoint = sim.checkpoint().unwrap(); + let effects = sim.file_io().snapshot(); + for _ in 0..2 { + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 81u32.into()); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); + // The old input descriptor was closed and its HDL number reused + // for output. Both the mapping and fscanf lookahead must return. + let restored = sim.file_io().prepare_restore(&effects).unwrap(); + sim.replace_file_io(restored); + sim.restore(&checkpoint).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(sim.signal("value")), 12u32.into()); + } + let mut fork = build().$backend().unwrap(); + let restored = fork.file_io().prepare_restore(&effects).unwrap(); + fork.replace_file_io(restored); + fork.restore(&checkpoint).unwrap(); + fork.run_until(1).unwrap(); + assert_eq!(fork.get(fork.signal("value")), 81u32.into()); + let mut rejected = celox::Simulation::from_sv_sources( + vec![(IO_SNAPSHOT_SOURCE, Path::new("io_snapshot.sv"))], + "Top", + ) + .file_system(|| { + let mut host = file_system::TestIo::default(); + host.reject_restore = true; + Box::new(host) + }) + .$backend() + .unwrap(); + rejected.run_until(1).unwrap(); + let before = rejected.save_state().unwrap(); + assert!( + rejected + .file_io() + .prepare_restore(&effects) + .unwrap_err() + .to_string() + .contains("host rejected restore") + ); + assert_eq!(before, rejected.save_state().unwrap()); + assert_eq!(rejected.time(), 1); + } + }; +} +io_snapshot!(io_snapshot_interpreter, build_interpreter); +io_snapshot!(io_snapshot_cranelift, build_cranelift); +io_snapshot!(io_snapshot_wasm, build_wasm); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +io_snapshot!(io_snapshot_native, build_native); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +io_snapshot!(io_snapshot_tiered, build_tiered); + +#[test] +fn io_manager_restores_eof_pushback_channels_and_standard_streams() { + use celox_runtime::file_io::FileIo; + let mut io = FileIo::new(Box::::default()); + let fd = io.open("input", Some("r")); + while io.read_byte(fd).unwrap().is_some() {} + assert!(io.eof(fd).unwrap()); + let eof = io.snapshot(); + io.rewind(fd).unwrap(); + io = io.prepare_restore(&eof).unwrap(); + assert!(io.eof(fd).unwrap()); + io.unread_byte(fd, b'X').unwrap(); + assert_eq!(io.read_byte(0x8000_0000).unwrap(), Some(b's')); + let channel = io.open("output", None); + io.write(channel, b"before").unwrap(); + let saved = io.snapshot(); + io.write(channel, b"after").unwrap(); + io.close(fd).unwrap(); + io.close(channel).unwrap(); + io.close(0x8000_0000).unwrap(); + io = io.prepare_restore(&saved).unwrap(); + assert!(!io.eof(fd).unwrap()); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'X')); + assert_eq!(io.read_byte(0x8000_0000).unwrap(), Some(b't')); + io.write(channel, b"!").unwrap(); + let output = io.open("output", Some("r")); + let mut bytes = Vec::new(); + while let Some(byte) = io.read_byte(output).unwrap() { + bytes.push(byte); + } + assert_eq!(bytes, b"before!"); + let mut incompatible = file_system::TestIo::default(); + incompatible.format = "other-host/v2".into(); + let incompatible = FileIo::new(Box::new(incompatible)); + assert!( + incompatible + .prepare_restore(&saved) + .unwrap_err() + .to_string() + .contains("format mismatch") + ); +} + +#[test] +fn rejected_io_restore_preserves_live_stream_position() { + use celox_runtime::file_io::FileIo; + let mut host = file_system::TestIo::default(); + host.reject_restore = true; + let mut io = FileIo::new(Box::new(host)); + let fd = io.open("input", Some("r")); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'1')); + let saved = io.snapshot(); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'2')); + assert!(io.prepare_restore(&saved).is_err()); + assert_eq!(io.read_byte(fd).unwrap(), Some(b'Q')); +} + +#[test] +fn writemem_uses_injected_io() { + let source = r#"module Top(output int value); + logic [7:0] words [0:1]; int fd; + initial begin + words[0]=8'h41; words[1]=8'h42; + $writememh("output", words); + fd=$fopen("output", "r"); + value=$fgetc(fd); + end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources(vec![(source, Path::new("write.sv"))], "Top") + .file_system(|| Box::::default()) + .build_interpreter() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("value")), u32::from(b'4').into()); +} diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs new file mode 100644 index 00000000000..756fb132c5f --- /dev/null +++ b/crates/celox/tests/sv_sampled.rs @@ -0,0 +1,264 @@ +#![cfg(feature = "systemverilog")] +//! `$sampled(e)` is the value of `e` in the Preponed region of the time +//! slot, the value at the end of the previous slot, and before the first +//! slot the declared or default value (IEEE 1800-2023 4.4.2.1, 16.5.1, +//! 16.9.3). +use std::path::Path; + +macro_rules! sampled { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit clk, a, b, r, s, x, y, z;\n int v;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + /// A clock edge and a blocking write in one slot: the register + /// sees the new value, `$sampled` the value from before the slot. + #[test] + fn a_flip_flop_samples_the_value_before_the_slot() { + let mut sim = simulation( + " always @(posedge clk) begin r <= $sampled(a); s <= a; end\n \ + initial begin #1 a = 1; clk = 1; #1 clk = 0; #1 clk = 1; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (0, 1)); + sim.run_until(3).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (1, 1)); + } + + /// Returning to the host does not advance the Preponed baseline: + /// the host may schedule more work at the same timestamp. + #[test] + fn host_resumptions_keep_the_current_timestamp_sample() { + for mode in [celox::SchedulerMode::Reference, celox::SchedulerMode::Compiled] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk, input bit [7:0] host); + bit [7:0] a, r; + always @(posedge clk) r <= $sampled(a + host); + initial #1 a = 1; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("sampled.sv"))], "Top", + ).scheduler_mode(mode).$backend().unwrap(); + if watch { sim.set_fail_on(Some(celox::Severity::Error)); } + sim.run_until(0).unwrap(); + match entry { + 0 => sim.run_until(1).unwrap(), + 1 => { sim.run_until_bounded(1, 10).unwrap(); } + 2 => { assert_eq!(sim.step().unwrap(), Some(1)); } + _ => { sim.advance_to(1).unwrap(); sim.run_until(1).unwrap(); } + } + assert_eq!(value(&mut sim, "a"), 1); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0, "{mode:?}, watch={watch}, entry={entry}"); + + // Host writes also belong to time 1, not a new slot. + let host = sim.signal("host"); + sim.modify(|io| io.set(host, 2u8)).unwrap(); + sim.schedule("clk", 1, 0).unwrap(); + sim.run_until(1).unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0); + + // Once time advances, the updated values are sampled. + sim.schedule("clk", 2, 0).unwrap(); + sim.schedule("clk", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "r"), 3); + if matches!(mode, celox::SchedulerMode::Compiled) + && !watch && entry == 0 + && matches!(stringify!($backend), "build" | "build_cranelift") { + assert!(sim.scheduler_stats().compiled_slots > 0); + } + } + } + } + } + + /// In the first slot the sampled value is the declared value, + /// in a later slot the value at the end of the previous one. + #[test] + fn time_zero_samples_the_declared_value() { + let mut sim = simulation( + " bit d = 1;\n \ + initial begin\n \ + x = $sampled(b) ^ $sampled(d); b = 1; d = 0; #0 y = $sampled(b) ^ $sampled(d);\n \ + #1 z = $sampled(b) ^ $sampled(d);\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!( + (value(&mut sim, "x"), value(&mut sim, "y"), value(&mut sim, "z")), + (1, 1, 1) + ); + } + + /// A real operand keeps its type. + #[test] + fn real_operands_keep_their_type() { + let mut sim = simulation( + " real d = 1.25;\n real rr;\n initial begin rr = $sampled(d); $display(\"%0.2f\", rr); end", + ); + sim.run_until(0).unwrap(); + assert!(matches!( + sim.drain_runtime_events().as_slice(), + [celox::RuntimeEvent::Display { message }] if message == b"1.25" + )); + } + + /// A sampled expression selects, as `$sampled(i + 1)`. + #[test] + fn sampled_expressions_select() { + let mut sim = simulation( + " bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 1;\n bit [7:0] q;\n \ + always @(posedge clk) q <= data[$sampled(i + 1)];\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 12); + } + + /// A call in a sampled select index reads the sampled values too. + #[test] + fn sampled_calls_select() { + let mut sim = simulation( + " int calls; function automatic bit [1:0] f(bit [1:0] k); calls++; return k; endfunction\n \ + bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 2;\n bit [7:0] q;\n bit [3:0] w;\n \ + always @(posedge clk) begin q <= data[$sampled(f(i))]; w[$sampled(f(i))] <= 1; end\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "q"), value(&mut sim, "w")), (12, 4)); + } + + /// Automatic variables keep their current value; the operand may + /// be any expression. + #[test] + fn automatic_variables_and_expressions() { + let mut sim = simulation( + " initial begin\n \ + automatic int k = 5;\n \ + #1 a = 1; b = 1;\n \ + v = $sampled(k + a + {31'b0, b});\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "v"), 5); + } + + #[test] + fn combinational_logic_cannot_read_sampled_values() { + for item in [ + "always_comb y = $sampled(a);", + "always @(a) y = $sampled(a);", + "assign y = $sampled(a);", + ] { + let source = format!("module Top; bit a, y; {item} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .err() + .expect("rejected"); + assert!( + error.to_string().contains("$sampled in combinational logic"), + "{item}: {error}" + ); + } + } + } + }; +} + +sampled!(interpreter, build_interpreter); +#[cfg(feature = "cranelift")] +sampled!(cranelift, build_cranelift); +#[cfg(target_arch = "x86_64")] +sampled!(native, build_native); +#[cfg(feature = "wasm-runtime")] +sampled!(wasm, build_wasm); + +/// A `Simulator` call is a time slot: a domain reads the values its +/// inputs had when the previous call ended. +#[test] +fn a_tick_samples_the_value_of_the_previous_call() { + let source = "module Top(input bit clk, input bit a, output bit r, output bit s);\n \ + always_ff @(posedge clk) begin r <= $sampled(a); s <= a; end\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + let (a, r, s, clk) = ( + sim.signal("a"), + sim.signal("r"), + sim.signal("s"), + sim.event("clk"), + ); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!((sim.get_as::(r), sim.get_as::(s)), (1, 1)); +} + +/// A domain of a derived clock samples the values from before the call, not +/// those the source domain committed in it. +#[test] +fn derived_domains_sample_the_values_from_before_the_call() { + let source = "module Top(input bit clk, output bit [7:0] r);\n \ + bit div;\n bit [7:0] a;\n \ + always_ff @(posedge clk) begin div <= !div; a <= a + 1; end\n \ + always_ff @(posedge div) r <= $sampled(a);\n\ + endmodule"; + // With the edges in generated units and through the plan walk. + for units in [true, false] { + let mut builder = + celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top"); + if !units { + builder = builder.disable_pass(celox::SirPass::DerivedEdgeUnits); + } + let mut sim = builder.build().unwrap(); + let (r, clk) = (sim.signal("r"), sim.event("clk")); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 0, "units: {units}"); + sim.tick(clk).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 2, "units: {units}"); + } +} + +/// A host write in a slot with nothing to run is what the next slot +/// samples. +#[test] +fn host_writes_of_idle_slots_are_sampled() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $sampled(a);\nendmodule"; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + sim.add_clock("clk", 2, 1); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(1).unwrap(); + let r = sim.signal("r"); + assert_eq!(sim.get(r), 1u8.into()); +} diff --git a/crates/celox/tests/sv_scan.rs b/crates/celox/tests/sv_scan.rs index 53728da9e57..d1b6a7b14ef 100644 --- a/crates/celox/tests/sv_scan.rs +++ b/crates/celox/tests/sv_scan.rs @@ -73,7 +73,7 @@ backend!(wasm, build_wasm); backend!(native, build_native); #[test] -fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { +fn fscanf_preserves_mismatch_lookahead_and_allows_checkpoint() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("input.txt"); std::fs::write(&path, b"12 34Q 7").unwrap(); @@ -99,9 +99,8 @@ fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { let signal = simulation.signal(name); assert_eq!(simulation.get(signal), value.into(), "{name}"); } - assert!( - format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks") - ); + simulation.checkpoint().unwrap(); + simulation.save_state().unwrap(); } let build = || Simulation::from_sv_sources(vec![(&source, Path::new("scan.sv"))], "Top"); check(build().build_interpreter().unwrap()); @@ -151,7 +150,7 @@ fn rejected_formats_are_explicit() { } #[test] -fn fscanf_on_standard_input_rejects_snapshots_before_execution() { +fn fscanf_on_standard_input_allows_snapshots_before_execution() { let source = r#"module Top; int n, value; initial begin #1; n = $fscanf(32'h80000000, "%d", value); end endmodule"#; @@ -159,6 +158,6 @@ fn fscanf_on_standard_input_rejects_snapshots_before_execution() { Simulation::from_sv_sources(vec![(source, Path::new("scan_stdin.sv"))], "Top") .build_interpreter() .unwrap(); - assert!(format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks")); - assert!(simulation.save_state().is_err()); + simulation.checkpoint().unwrap(); + simulation.save_state().unwrap(); } diff --git a/crates/celox/tests/test_utils/file_system.rs b/crates/celox/tests/test_utils/file_system.rs new file mode 100644 index 00000000000..6690e6d7ba6 --- /dev/null +++ b/crates/celox/tests/test_utils/file_system.rs @@ -0,0 +1,146 @@ +//! An embedding-host fixture, not a production filesystem. Its private JSON +//! snapshot format demonstrates that Celox does not interpret backend state. +use celox::{FileMode, FileSystem}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + io::{self, Read, Seek, SeekFrom, Write}, + path::Path, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Stream { + path: String, + position: u64, + read: bool, + write: bool, + append: bool, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TestIo { + files: BTreeMap>, + streams: BTreeMap, + next: u64, + stdin: u64, + stderr: Vec, + pub reject_restore: bool, + pub format: String, +} +impl Default for TestIo { + fn default() -> Self { + Self { + files: BTreeMap::from([("input".into(), b"12Q34".to_vec())]), + streams: BTreeMap::new(), + next: 0, + stdin: 0, + stderr: Vec::new(), + reject_restore: false, + format: "celox-test-host/v1".into(), + } + } +} +impl TestIo { + fn stream(&mut self, id: u64) -> io::Result<&mut Stream> { + self.streams + .get_mut(&id) + .ok_or_else(|| io::Error::other("closed handle")) + } +} +impl FileSystem for TestIo { + fn open(&mut self, path: &Path, mode: FileMode) -> io::Result { + let path = path.to_str().unwrap().to_owned(); + if mode.create { + self.files.entry(path.clone()).or_default(); + } + let bytes = self + .files + .get_mut(&path) + .ok_or_else(|| io::Error::from(io::ErrorKind::NotFound))?; + if mode.truncate { + bytes.clear(); + } + let id = self.next; + self.next += 1; + self.streams.insert( + id, + Stream { + path, + position: 0, + read: mode.read, + write: mode.write, + append: mode.append, + }, + ); + Ok(id) + } + fn close(&mut self, id: u64) -> io::Result<()> { + self.streams + .remove(&id) + .ok_or_else(|| io::Error::other("closed handle"))?; + Ok(()) + } + fn read(&mut self, id: u64, bytes: &mut [u8]) -> io::Result { + let stream = self.stream(id)?.clone(); + if !stream.read { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let mut cursor = io::Cursor::new(&self.files[&stream.path]); + cursor.set_position(stream.position); + let count = cursor.read(bytes)?; + self.stream(id)?.position += count as u64; + Ok(count) + } + fn write(&mut self, id: u64, bytes: &[u8]) -> io::Result { + let stream = self.stream(id)?.clone(); + if !stream.write { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let data = self.files.get_mut(&stream.path).unwrap(); + let position = if stream.append { + data.len() as u64 + } else { + stream.position + }; + let mut cursor = io::Cursor::new(data); + cursor.set_position(position); + let count = cursor.write(bytes)?; + self.stream(id)?.position = position + count as u64; + Ok(count) + } + fn seek(&mut self, id: u64, position: SeekFrom) -> io::Result { + let stream = self.stream(id)?.clone(); + let mut cursor = io::Cursor::new(&self.files[&stream.path]); + cursor.set_position(stream.position); + let result = cursor.seek(position)?; + self.stream(id)?.position = result; + Ok(result) + } + fn flush(&mut self, id: u64) -> io::Result<()> { + self.stream(id)?; + Ok(()) + } + fn read_stdin(&mut self, bytes: &mut [u8]) -> io::Result { + let mut cursor = io::Cursor::new(b"stdin"); + cursor.set_position(self.stdin); + let count = cursor.read(bytes)?; + self.stdin += count as u64; + Ok(count) + } + fn write_stderr(&mut self, bytes: &[u8]) -> io::Result<()> { + self.stderr.extend_from_slice(bytes); + Ok(()) + } + fn snapshot_format(&self) -> &str { + &self.format + } + fn snapshot(&self) -> io::Result> { + serde_json::to_vec(self).map_err(io::Error::other) + } + fn restore(&self, state: &[u8]) -> io::Result> { + if self.reject_restore { + return Err(io::Error::other("host rejected restore")); + } + let state: Self = serde_json::from_slice(state).map_err(io::Error::other)?; + Ok(Box::new(state)) + } +} diff --git a/docs/guide/checkpoints.md b/docs/guide/checkpoints.md index 36a22fb532d..d43775c30e8 100644 --- a/docs/guide/checkpoints.md +++ b/docs/guide/checkpoints.md @@ -57,6 +57,93 @@ sim.time(); // 100 - Checkpoints live in memory. To keep state across processes, use a state file. +## External resources: file I/O and VPI {#external-resources} + +A design containing file I/O, `$fscanf` (including stdin), or VCD tasks can +be captured at the normal API boundary. `checkpoint()` copies state without +executing HDL; `save_state()` / `saveState()` retain their usual combinational +settling behavior. A simulation suspended mid-slot by `$stop` must still be +continued before capture. + +Rust hosts can supply runtime I/O through `FileSystem`, keeping the OS-backed +`HostFileSystem` as the default: + +```rust +let mut sim = Simulation::from_sv_sources(sources, "Top") + .file_system(|| Box::new(MyHostIo::new())) + .build()?; +let saved = sim.checkpoint()?; +// Advance the simulation, then restore both HDL and host I/O state. +sim.restore(&saved)?; +``` + +`MyHostIo` implements `celox::FileSystem`. The factory runs before declaration +initialization and creates an independent backend for each simulator. It handles +open/read/write/seek/close/flush, stdin and stderr; runtime `$writemem*` operations +also use it. This boundary covers runtime file tasks, not compiler source-file +loading, compile-time memory initialization, or VCD writers. It does not require +any particular filesystem or storage strategy. + +Core checkpoints contain HDL memory, heap values, process state and scheduling +state. They do **not** contain effect-handler state. A design using file I/O or +VPI can take and restore a core checkpoint without asking its handlers to save +anything. Restoring only the core leaves those handlers attached and unchanged; +subsequent SV calls are interpreted by their current state. + +The file-I/O handler owns HDL descriptor allocation, FD/MCD mappings, readability, +EOF flags, scan lookahead and standard-stream flags. Its injected `FileSystem` +owns the backing resources and defines their effect semantics. Rust hosts can +compose these independently at a quiescent execution boundary: + +```rust,ignore +let core = simulation.checkpoint()?; +let io = simulation.file_io().snapshot(); +// ... execute a scenario ... +let restored_io = simulation.file_io().prepare_restore(&io)?; +simulation.replace_file_io(restored_io); +simulation.restore(&core)?; +``` + +The host chooses which handlers to include, how external effects are retained, +and the persistence format of its **system checkpoint**. Core does not require +a memory filesystem, a disk overlay, or handler persistence. The default Rust +`HostFileSystem` continues to use the OS directly. Its lack of an independent +resource snapshot does not prevent core checkpoint capture or restore. + +`FileSystem::restore()` prepares a replacement handler with the saved private +handle identities. This helper's contract leaves the existing handler and +external resources untouched during preparation. A host with a different effect +commit protocol can coordinate its own replacement instead. Validation and +commit order belong to that host system, not to the core checkpoint. + +`SimulationCheckpoint::to_bytes()` encodes the core, including live fork +activations and heap objects, without event-code pointers. An instance built +from the same design binds saved event IDs through +`unsafe Simulation::checkpoint_from_bytes()`. This implementation format is +versioned and checks layout and accidental corruption; load only trusted, +unmodified artifacts from a compatible build. It is separate from portable +`StateFile`, which contains named HDL values and an optional schedule. + +Portable state-file restore retains its existing host-resource restrictions. +System hosts can compose core and effect-handler snapshots into their own +resumable checkpoint format. + +For native VPI hosts, Rust `VpiSession::save_state()` and +`NativeProgramInstance::save_state()` return the same `StateFile` format, +without evaluating HDL or dispatching callbacks. Capture between dispatch runs +or in a read-only synchronization callback for settled values. In other callback +phases, the file contains the values currently visible to VPI reads, which may +not yet be settled. The file has no simulation schedule: pending VPI writes, +callback registrations, force registrations, plugin memory, and cocotb/Python +coroutines are excluded. Applied force values are visible in the HDL data. +These files support inspection, comparison, and HDL-only initialization; they +are not resumable VPI sessions. C plugins can call +`int celox_vpi_save_state(const char *path)` under the same contract (1 for +success, 0 for failure). The path is UTF-8; an existing file is overwritten. + +Opaque external component state also remains with its host. Core checkpoints +do not capture it; portable state-file APIs retain their component restrictions. + ## Waveforms VCD output keeps recording across a restore: the next `dump()` writes the diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index b1446e6d85f..f1d1a67a29b 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -93,7 +93,9 @@ To compare two runs or two simulators, `celox run` can save | `--save-state-dir DIR` | Write the files to `DIR` (default: the current directory). | A cycle that the run never reaches is an error. These options are available for -SystemVerilog testbenches on every backend. +SystemVerilog testbenches on every backend, including designs with file I/O or +VCD tasks. The saved file contains HDL state; external resources are excluded +under the [snapshot contract](checkpoints.md#external-resources). ```sh celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index b74b6f5a4b7..ae258e91cbb 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -210,6 +210,7 @@ waits zero. | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | +| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | @@ -709,6 +710,21 @@ host does at each callback, or the time step of the report while and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. +### Sampled values {#sampled-values} + +`$sampled(e)` is the value `e` has in the Preponed region of the time slot: +the value at the end of the previous slot, and in the first slot the declared +or default value (IEEE 1800-2023 4.4.2.1, 16.5.1). Each static variable the +operand reads, the indices of its selects and the arguments of its calls +included, is read from a copy that the timed simulation updates before advancing +to a later timestamp. Returning to the host and resuming at the same timestamp +retains that copy, including across host writes. Automatic variables keep their current value. A `Simulator` call is a +time slot. `$sampled` in combinational logic (`always_comb`, `always_latch`, +an `always` lowered as combinational logic, a continuous assignment) is +rejected: such a process reruns when its inputs change, not when their sampled +values do. A design that uses `$sampled` runs the compiled scheduler one slot +at a time. + ### Deferred assertions The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index ff7e7377ff9..2839b045e40 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -154,6 +154,7 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time`、`$stime`、`$realtime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | +| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。[サンプル値](#sampled-values) を参照 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | @@ -408,6 +409,18 @@ drain のコンテキストが与える時刻で、VPI ホストはコールバ VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 +### サンプル値 {#sampled-values} + +`$sampled(e)` は、タイムスロットの Preponed region での `e` の値です。前のスロットの終わりの値で、 +最初のスロットでは宣言の初期値か既定値です(IEEE 1800-2023 4.4.2.1、16.5.1)。被演算子が読む +静的変数は、選択のインデックスや呼び出しの引数の中のものも含めて、時刻を先へ進める直前に +更新するコピーから読みます。同じ時刻にホストへ戻って再開しても、ホストからの書き込みを含め、 +コピーは更新しません。automatic 変数は現在の値のままです。`Simulator` では呼び出し 1 回が +タイムスロットです。組み合わせ回路(`always_comb`、`always_latch`、組み合わせ回路として扱う +`always`、継続代入)の中の `$sampled` は拒否します。こうしたプロセスは入力が変わったときに +再実行するもので、入力のサンプル値が変わったときではないためです。`$sampled` を使う設計では、 +コンパイル済みスケジューラを 1 スロットずつ実行します。 + ### 遅延付きアサーション `assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延