Make a host in Rust, step 2: frames and the budget

A Terse32 program runs at the same speed on every host. Time comes in frames, 60 a second, and in each frame a program can do a fixed amount of work: 125,000 units. This step adds the module frames to the crate of step 1: the frame loop and the System device's first calls.

The frame loop

pub const FRAME_BUDGET: i64 = 125_000;

pub enum Status {
    Running,
    Exited(u8),
    Faulted(Fault),
}

pub struct Machine {
    pub cpu: Cpu,
    pub budget: i64,
    pub frame: u32,
    pub status: Status,
}

Machine is the processor of step 1 with what the frame loop keeps: the budget, the frame counter, and whether and how the machine stopped.

Slot 1 is the System device. BASE_CHARGE is the charge of its calls and of a call the machine does not have; BAD_BUFFER, the result when a call's buffer is not where it must be. Its calls are numbered by function:

pub const SYSTEM: u32 = 1;
pub const BASE_CHARGE: i64 = 4;
pub const BAD_BUFFER: u32 = 0xffff_fffe;
const EVENT_SIZE: u32 = 4;

const WAIT_FRAME: u32 = 0;
const NEXT_EVENT: u32 = 1;
const FRAME_COUNT: u32 = 2;
const EXIT: u32 = 6;
const COPY: u32 = 10;
const MAX_COPY: u32 = 65_536;
    pub fn run_frame<D>(&mut self, mut devices: D)
    where
        D: FnMut(&mut Cpu, i64, u32, u32) -> (u32, i64),
    {
        self.budget += FRAME_BUDGET;
        while self.budget > 0 && self.running() {
            let (cost, ecall) = match self.cpu.step() {
                Ok(step) => step,
                Err(fault) => {
                    self.status = Status::Faulted(fault);
                    break;
                }
            };
            self.budget -= cost;
            if !ecall {
                continue;
            }
            let a7 = self.cpu.x[A7];
            let (slot, function) = (a7 >> 8, a7 & 0xff);
            let budget = self.budget;
            let (result, charge) = if slot == SYSTEM {
                self.system(function)
            } else {
                devices(&mut self.cpu, budget, slot, function)
            };
            self.cpu.x[A0] = result;
            self.budget -= charge;
            if slot == SYSTEM && function == WAIT_FRAME {
                break;
            }
        }
        self.budget = self.budget.min(0);
        self.frame += 1;
    }

In order:

Five calls

    fn system(&mut self, function: u32) -> (u32, i64) {
        let a0 = self.cpu.x[A0];
        let event = self.cpu.memory(a0, EVENT_SIZE, true);
        let result = match function {
            WAIT_FRAME => self.frame + 1,
            NEXT_EVENT if event.is_none() => BAD_BUFFER,
            NEXT_EVENT => 0,
            FRAME_COUNT => self.frame,
            EXIT => {
                self.status = Status::Exited(a0 as u8);
                0
            }
            COPY => {
                // No clipboard: check, charge, drop.
                let n = self.cpu.x[A1];
                let text = self.cpu.memory(a0, n, false);
                if n > MAX_COPY || (n > 0 && text.is_none()) {
                    return (BAD_BUFFER, BASE_CHARGE);
                }
                return (0, BASE_CHARGE + (n as i64 + 3) / 4);
            }
            _ => UNKNOWN_CALL,
        };
        (result, BASE_CHARGE)
    }

The program

use host::cpu::UNKNOWN_CALL;
use host::frames::{BASE_CHARGE, Machine, Status};
use host::image::load;
use std::error::Error;
use std::process::exit;

fn main() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = std::env::args().collect();
    let file = std::fs::read(&args[1])?;
    let frames: u32 = args[2].parse()?;
    let (cpu, _) = load(&file)?;
    let mut m = Machine::new(cpu);
    while m.running() && m.frame < frames {
        m.run_frame(|_, _, _, _| (UNKNOWN_CALL, BASE_CHARGE));
    }
    match m.status {
        Status::Faulted(fault) => {
            eprintln!("{fault}");
            exit(1)
        }
        Status::Exited(code) => exit(code as i32),
        Status::Running => Ok(()),
    }
}

It takes the program and the most frames to run; |_, _, _, _| (u32::MAX, 4) answers a call to any device but the System device: FFFF_FFFFh, charge 4.

Run it

This program calls frame_count 100,000 times, then waits for the next frame and exits with what wait_frame returned:

_start: li   t0, 100000
        li   a7, 0x102      # frame_count
1:      ecall
        addi t0, t0, -1
        bnez t0, 1b
        li   a7, 0x100      # wait_frame
        ecall
        li   a7, 0x106      # exit with its result
        ecall

From examples/host/rust, after cargo build --release:

xxd -r -p > frames.terse <<EOF
544552530001240000010000000000006672616d657300
000000000000000000e1629382026a9308201073000000
fd12e39d02fe93080010730000009308601073000000
EOF
target/release/step2 frames.terse 10
echo $?

prints 6, as terse run frames.terse --frames 10 does. Each pass of the loop costs 7 units: the ecall 1 + 4, the other two instructions 1 each. 100,000 passes are 700,000 units, so the loop ends in frame 5 (frames 0 to 4 give 625,000), wait_frame returns 6, and the program exits in frame 6. A host that says 3 does not charge calls; 5, its wait_frame returns the counter instead of one more; 1, it has no budget at all.

What you have now

A machine that runs programs at exactly the reference's speed: frames.rs, 104 lines, and bin/step2.rs, 24. Next, give it a screen: Make a host in Rust, step 3: a driver shows hello.