added comments extensively

This commit is contained in:
Nilton Constantino
2026-01-19 07:47:54 +00:00
parent 0f3105d622
commit 13ecbd1877
10 changed files with 446 additions and 104 deletions
@@ -10,12 +10,19 @@ use std::sync::Arc;
use std::time::Instant;
/// PrometeuOS (POS): The system firmware/base.
///
/// Maximum authority for boot, peripherals, PVM execution, and fault handling.
/// It acts as the bridge between the high-level PVM applications and the virtual hardware.
pub struct PrometeuOS {
/// Incremented on every host tick (60Hz).
pub tick_index: u64,
/// Incremented every time a logical game frame is successfully completed.
pub logical_frame_index: u64,
/// Indicates if there is an ongoing logical frame that hasn't reached `FRAME_SYNC` yet.
pub logical_frame_active: bool,
/// Number of virtual cycles still available for the current logical frame.
pub logical_frame_remaining_cycles: u64,
/// Real-world CPU time (in microseconds) consumed by the last host tick.
pub last_frame_cpu_time_us: u64,
// Example assets (kept for compatibility with v0 audio syscalls)
@@ -24,36 +31,54 @@ pub struct PrometeuOS {
pub sample_snare: Option<Arc<Sample>>,
// Filesystem
/// The virtual filesystem interface.
pub fs: VirtualFS,
/// Current state of the FS (Mounted, Error, etc).
pub fs_state: FsState,
/// Mapping of numeric handles to file paths for open files.
pub open_files: HashMap<u32, String>,
/// Sequential handle generator for file operations.
pub next_handle: u32,
// Log Service
pub log_service: LogService,
/// Unique ID of the currently running application.
pub current_app_id: u32,
pub current_cartridge_title: String,
pub current_cartridge_app_version: String,
pub current_cartridge_app_mode: crate::model::AppMode,
/// Rate-limiting tracker for application logs to prevent performance degradation.
pub logs_written_this_frame: HashMap<u32, u32>,
// Telemetry and Certification
/// Accumulator for metrics of the frame currently being executed.
pub telemetry_current: TelemetryFrame,
/// Snapshot of the metrics from the last completed logical frame.
pub telemetry_last: TelemetryFrame,
/// Logic for evaluating compliance with the active CAP profile.
pub certifier: Certifier,
/// Global pause flag (used by debugger or system events).
pub paused: bool,
/// Request from debugger to run exactly one instruction or frame.
pub debug_step_request: bool,
/// Instant when the system was initialized.
boot_time: Instant,
}
impl PrometeuOS {
/// Default number of cycles assigned to a single game frame.
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 100_000;
pub const SLICE_PER_TICK: u64 = 100_000; // For now the same, but allows different granularity
/// Maximum number of cycles allowed to execute in a single host tick.
/// Usually the same as CYCLES_PER_LOGICAL_FRAME to target 60FPS.
pub const SLICE_PER_TICK: u64 = 100_000;
/// Maximum characters allowed per log message.
pub const MAX_LOG_LEN: usize = 256;
/// Maximum log entries an App can emit in a single frame.
pub const MAX_LOGS_PER_FRAME: u32 = 10;
/// Creates a new POS instance with optional certification rules.
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
let boot_time = Instant::now();
let mut os = Self {
@@ -158,67 +183,81 @@ impl PrometeuOS {
}
}
/// Executes a host tick (60Hz).
/// Executes a single host tick (nominally 60Hz).
///
/// This method is responsible for managing the logical frame lifecycle.
/// A single host tick might execute a full logical frame, part of it,
/// or multiple frames depending on the configured slices.
pub fn step_frame(&mut self, vm: &mut VirtualMachine, signals: &InputSignals, hw: &mut dyn HardwareBridge) -> Option<String> {
let start = std::time::Instant::now();
self.tick_index += 1;
// If the system is paused, we don't advance unless there's a debug step request.
if self.paused && !self.debug_step_request {
return None;
}
self.update_fs();
// 1. Frame Initialization
// If we are not currently in the middle of a logical frame, start a new one.
if !self.logical_frame_active {
self.logical_frame_active = true;
self.logical_frame_remaining_cycles = Self::CYCLES_PER_LOGICAL_FRAME;
self.begin_logical_frame(signals, hw);
// Beginning of frame: reset telemetry accumulator (but keep frame_index)
// Reset telemetry for the new logical frame
self.telemetry_current = TelemetryFrame {
frame_index: self.logical_frame_index,
..Default::default()
};
}
// Budget for this tick: the minimum between the tick slice and what remains in the logical frame
// 2. Budget Allocation
// Determine how many cycles we can run in this host tick.
let budget = std::cmp::min(Self::SLICE_PER_TICK, self.logical_frame_remaining_cycles);
// 3. VM Execution
if budget > 0 {
// Execute budget
// Run the VM until budget is hit or FRAME_SYNC is reached.
let run_result = vm.run_budget(budget, self, hw);
match run_result {
Ok(run) => {
self.logical_frame_remaining_cycles = self.logical_frame_remaining_cycles.saturating_sub(run.cycles_used);
// Accumulates metrics
// Accumulate metrics for telemetry and certification
self.telemetry_current.cycles_used += run.cycles_used;
self.telemetry_current.vm_steps += run.steps_executed;
// Handle Breakpoints
if run.reason == crate::virtual_machine::LogicalFrameEndingReason::Breakpoint {
self.paused = true;
self.debug_step_request = false;
self.log(LogLevel::Info, LogSource::Vm, 0xDEB1, format!("Breakpoint hit at PC 0x{:X}", vm.pc));
}
// 4. Frame Finalization (FRAME_SYNC reached)
if run.reason == crate::virtual_machine::LogicalFrameEndingReason::FrameSync {
// All drawing commands for this frame are now complete.
// Finalize the framebuffer.
hw.gfx_mut().render_all();
// Finalizes frame telemetry (host_cpu_time will be refined at the end of the tick)
// Finalize frame telemetry
self.telemetry_current.host_cpu_time_us = start.elapsed().as_micros() as u64;
// Certification (CAP)
// Evaluate CAP (Execution Budget Compliance)
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
self.telemetry_current.violations = self.certifier.evaluate(&self.telemetry_current, &mut self.log_service, ts_ms) as u32;
// Latch: what the overlay reads
// Latch telemetry for the Host/Debugger to read.
self.telemetry_last = self.telemetry_current;
self.logical_frame_index += 1;
self.logical_frame_active = false;
self.logical_frame_remaining_cycles = 0;
// If we were doing a "step frame" debug command, pause now that the frame is done.
if self.debug_step_request {
self.paused = true;
self.debug_step_request = false;
@@ -226,6 +265,7 @@ impl PrometeuOS {
}
}
Err(e) => {
// Fatal VM fault (division by zero, invalid memory access, etc).
let err_msg = format!("PVM Fault: {:?}", e);
self.log(LogLevel::Error, LogSource::Vm, 0, err_msg.clone());
return Some(err_msg);
@@ -235,7 +275,7 @@ impl PrometeuOS {
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
// If the frame ended in this tick, we update the final real time in the latch
// If the frame ended exactly in this tick, we update the final real time in the latch.
if !self.logical_frame_active && self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1) {
self.telemetry_last.host_cpu_time_us = self.last_frame_cpu_time_us;
}
@@ -493,23 +533,35 @@ mod tests {
}
impl NativeInterface for PrometeuOS {
/// Dispatches a syscall from the VM to the native implementation.
///
/// Syscalls are grouped by functionality:
/// - 0x0000: System/Cartridge management
/// - 0x1000: Graphics (GFX)
/// - 0x2000: Input
/// - 0x3000: Audio
/// - 0x4000: Filesystem (FS)
/// - 0x5000: Logging
///
/// Each syscall returns the number of virtual cycles it consumed.
fn syscall(&mut self, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<u64, String> {
self.telemetry_current.syscalls += 1;
match id {
// --- System Syscalls ---
// system.has_cart() -> bool
0x0001 => {
// virtual_machine.push(Value::Boolean(self.current_cartridge.is_some()));
// Returns true if a cartridge is available.
Ok(10)
}
// system.run_cart()
0x0002 => {
// if let Some(cart) = self.current_cartridge.as_ref().cloned() {
// self.load_cartridge(&cart);
// } else {
// return Err("No cartridge inserted".into());
// }
// Triggers loading and execution of the current cartridge.
Ok(100)
}
// --- GFX Syscalls ---
// gfx.clear(color_index)
0x1001 => {
let color_idx = vm.pop_integer()? as usize;
@@ -528,6 +580,9 @@ impl NativeInterface for PrometeuOS {
hw.gfx_mut().fill_rect(x, y, w, h, color);
Ok(200)
}
// --- Input Syscalls ---
// input.get_pad(button_id) -> bool
0x2001 => {
let button_id = vm.pop_integer()? as u32;
@@ -535,6 +590,9 @@ impl NativeInterface for PrometeuOS {
vm.push(Value::Boolean(is_down));
Ok(50)
}
// --- Audio Syscalls ---
// audio.play_sample(sample_id, voice_id, volume, pan, pitch)
0x3001 => {
let pitch = vm.pop_number()?;
@@ -559,6 +617,7 @@ impl NativeInterface for PrometeuOS {
// --- Filesystem Syscalls (0x4000) ---
// FS_OPEN(path) -> handle
// Opens a file in the virtual sandbox and returns a numeric handle.
0x4001 => {
let path = match vm.pop()? {
Value::String(s) => s,
@@ -623,7 +682,7 @@ impl NativeInterface for PrometeuOS {
};
match self.fs.list_dir(&path) {
Ok(entries) => {
// For now, returns a string separated by ';'
// Returns a string separated by ';' for simple parsing in PVM.
let names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
vm.push(Value::String(names.join(";")));
Ok(500)