From 4cd3526e4d22d5eab4b15d75af7f840203df3ac7 Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:28:35 -0700 Subject: [PATCH 1/6] iris-ci: boot to any hostname's login prompt, menu or not `iris-ci boot` ran a fixed script: wait for "Option?", press 1, wait for the literal text "IRIS console login". Both steps assumed too much. The getty prompt carries the machine's hostname, and "IRIS" is only the default of a fresh install, so a disk with any other hostname (indy-6522 console login:, ip30-6530 console login:) never matched. And a PROM with AutoLoad set boots without printing the menu, so the first wait ran out the whole timeout. Neither case could boot, and the failure was a bare timeout that gave no hint why. Poll the serial console instead, as `boot-test` already does. Press 1 once if "Option?" appears, and finish when the prompt text appears, whether or not the menu did. The prompt defaults to "login:" and --prompt overrides it. This is client-side only, nothing on the emulator's hot paths. Two tests drive a fake CI socket: a menu followed by a non-IRIS login, and an autoloading PROM that prints no menu. Both failed before. Production lines: +22 -9 --- STORAGE.md | 2 +- src/iris_ci_main.rs | 88 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/STORAGE.md b/STORAGE.md index 0b6ff133b..2575837b2 100644 --- a/STORAGE.md +++ b/STORAGE.md @@ -309,7 +309,7 @@ debugging the wrapper itself. # In another terminal: drive it ./target/release/iris-ci status --wait-ready 60 # guest state + monitor readiness -./target/release/iris-ci boot # PROM menu → IRIS console login (one cmd) +./target/release/iris-ci boot # PROM menu (if shown) → login prompt (one cmd) ./target/release/iris-ci login # send root + dismiss vt100 prompt + wait # ./target/release/iris-ci run 'ls /' # send shell command, get stdout + exit code ./target/release/iris-ci save base/multiuser diff --git a/src/iris_ci_main.rs b/src/iris_ci_main.rs index 614ed58fb..790a82331 100644 --- a/src/iris_ci_main.rs +++ b/src/iris_ci_main.rs @@ -172,11 +172,14 @@ enum Cmd { timeout: u64, }, - /// Boot from PROM menu through to the IRIS console login prompt. + /// Boot through the PROM menu, if it appears, to the login prompt. Boot { /// Total timeout in seconds for boot to reach the login prompt. #[arg(long, default_value_t = 240)] timeout: u64, + /// Console text that means the login prompt is up. + #[arg(long, default_value = "login:")] + prompt: String, }, /// Send root login + dismiss the vt100 prompt + wait for the shell. Login { @@ -378,7 +381,7 @@ fn dispatch(opts: &Opts, cmd: Cmd) -> Result<()> { Cmd::SerialRead => cmd_serial_read(opts), Cmd::SerialWait { pattern, timeout } => cmd_serial_wait(opts, &pattern, timeout * 1000), - Cmd::Boot { timeout } => cmd_boot(opts, timeout), + Cmd::Boot { timeout, prompt } => cmd_boot(opts, timeout, &prompt), Cmd::Login { user, password } => cmd_login(opts, &user, password.as_deref()), Cmd::Run { command, shell, timeout } => cmd_run(opts, &command, &shell, timeout * 1000), Cmd::WaitPrompt { timeout } => cmd_wait_prompt(opts, timeout * 1000), @@ -944,16 +947,26 @@ fn screen_wait( // ---- boot/login/run macros -------------------------------------------------- -fn cmd_boot(opts: &Opts, timeout_s: u64) -> Result<()> { +fn cmd_boot(opts: &Opts, timeout_s: u64, prompt: &str) -> Result<()> { let deadline = Instant::now() + Duration::from_secs(timeout_s); if !opts.quiet { eprintln!("boot: starting CPU"); } send(opts, "start", json!({}))?; - if !opts.quiet { eprintln!("boot: waiting for PROM menu"); } - wait_with_deadline(opts, "Option?", deadline)?; - if !opts.quiet { eprintln!("boot: PROM reached, selecting 1) Start System"); } - send(opts, "serial-send", json!({"data": "1\r"}))?; - if !opts.quiet { eprintln!("boot: waiting for kernel boot to login prompt"); } - wait_with_deadline(opts, "IRIS console login", deadline)?; + // An autoloading PROM never shows the menu, so watch for both together. + let (mut seen, mut menu) = (String::new(), false); + loop { + let read = send(opts, "serial-read", json!({}))?; + seen.push_str(read.as_str().unwrap_or("")); + if seen.contains(prompt) { break; } + if !menu && seen.contains("Option?") { + menu = true; + if !opts.quiet { eprintln!("boot: PROM reached, selecting 1) Start System"); } + send(opts, "serial-send", json!({"data": "1\r"}))?; + } + if Instant::now() >= deadline { + return Err(Error::Timeout(format!("boot: no {prompt:?} within {timeout_s}s"))); + } + std::thread::sleep(Duration::from_millis(250)); + } if !opts.quiet { eprintln!("boot: ready at login"); } Ok(()) } @@ -1642,4 +1655,61 @@ mod tests { assert_eq!(count_differing(&golden, &no_root, 32), Some(156)); assert!(100 <= SCREEN_MAX_PIXELS && SCREEN_MAX_PIXELS < 156); } + /// Serves `start`, `serial-send` and `serial-read` for `cmd_boot`; the + /// console shows `before` until `1\r` arrives (or always, when `after` + /// is None) and `after` from then on. Returns the address and a handle + /// that yields the data sent. + fn fake_console(before: &'static str, after: Option<&'static str>) + -> (String, std::sync::Arc>>) + { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap().to_string(); + let sent = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = sent.clone(); + std::thread::spawn(move || { + for s in l.incoming() { + let s = s.unwrap(); + let mut line = String::new(); + BufReader::new(s.try_clone().unwrap()).read_line(&mut line).unwrap(); + let req: Value = serde_json::from_str(&line).unwrap(); + let data = match req["cmd"].as_str().unwrap() { + "serial-send" => { + log.lock().unwrap().push(req["args"]["data"].as_str().unwrap().into()); + Value::Null + } + "serial-read" => { + let sent = !log.lock().unwrap().is_empty(); + json!(if sent { after.unwrap_or(before) } else { before }) + } + // The fixed waits the old script used never match a real console. + "wait-serial" => { + writeln!(&s, "{}", json!({"ok": false, "error": "timeout", "timeout": true})).unwrap(); + continue; + } + _ => Value::Null, + }; + writeln!(&s, "{}", json!({"ok": true, "data": data})).unwrap(); + } + }); + (addr, sent) + } + + fn boot_opts(addr: &str) -> Opts { + Opts { socket: addr.into(), json: false, quiet: true } + } + + #[test] + fn boot_presses_the_menu_and_stops_at_any_hostnames_login() { + let (addr, sent) = fake_console("Option? ", Some("ip30-6530 console login: ")); + cmd_boot(&boot_opts(&addr), 5, "login:").unwrap(); + assert_eq!(*sent.lock().unwrap(), ["1\r"]); + } + + #[test] + fn boot_of_an_autoloading_prom_needs_no_menu() { + let (addr, sent) = fake_console("Starting up the system...\r\nindy-6522 console login: ", None); + cmd_boot(&boot_opts(&addr), 5, "login:").unwrap(); + assert!(sent.lock().unwrap().is_empty()); + } + } From 927d2c10be2a58e7f465a9b1434dbce46ba4564d Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:33:11 -0700 Subject: [PATCH 2/6] validate: check the board listeners for port clashes --validate only compared serial A/B, the monitor and the gdb port. A Fuel whose L1 port equals serial A, or a Tezro whose serial C equals B, printed "ok" and then exited at startup with "must be distinct". Other clashes (the O2 control port, virtio-serial and TCP forwards against the monitor or a console) started the machine but lost a listener with one line on stderr. Add the L1 port, Tezro serial C/D, the O2 control port, virtio-serial TCP ports and TCP port forwards to the same check, with the machines' defaults. Runs only under --validate. Production lines: +20 -0 --- src/validate_config.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/validate_config.rs b/src/validate_config.rs index 593fa31c9..2c2bf7ce8 100644 --- a/src/validate_config.rs +++ b/src/validate_config.rs @@ -112,6 +112,26 @@ pub fn problems(cfg: &MachineConfig) -> Vec { if let Some(gdb) = cfg.gdb_port { ports.push(("gdb_port", gdb)); } + // The listeners a board adds. Defaults match the machines' own. + let l1 = |p: Option| ("machine.l1_port", p.unwrap_or(8882)); + match cfg.machine.profile { + MachineProfile::FuelIp34 => ports.push(l1(cfg.fuel.l1_port)), + MachineProfile::TezroIp53 => ports.extend([ + l1(cfg.tezro.l1_port), + ("machine.serial_port_c", cfg.tezro.serial_port_c.unwrap_or(8883)), + ("machine.serial_port_d", cfg.tezro.serial_port_d.unwrap_or(8884)), + ]), + MachineProfile::Origin3200Ip35 | MachineProfile::Onyx3000Ip35 => ports.push(l1(cfg.ip35_section().l1_port)), + MachineProfile::O2Ip32 => ports.extend(cfg.o2.control_port.map(|p| ("machine.control_port", p))), + _ => {} + } + let virtio = &cfg.virtio_serial; + if virtio.enabled { + let default = [crate::dev::virtio::console::DEFAULT_TCP_PORT]; + let tcp = virtio.ports.iter().filter_map(|p| p.tcp_port); + ports.extend(if virtio.ports.is_empty() { default.to_vec() } else { tcp.collect() }.into_iter().map(|p| ("virtio_serial tcp_port", p))); + } + ports.extend(cfg.port_forward.iter().filter(|f| f.proto == crate::config::ForwardProto::Tcp).map(|f| ("port_forward host_port", f.host_port))); let mut seen: BTreeMap = BTreeMap::new(); for (setting, port) in ports { if port == 0 { @@ -236,6 +256,29 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A board's L1 port and a Tezro's extra serial ports are listeners too. + #[test] + fn the_board_ports_join_the_clash_check() { + let mut cfg = MachineConfig::default(); + cfg.scsi.clear(); + cfg.machine.profile = MachineProfile::FuelIp34; + cfg.fuel.l1_port = Some(8880); + assert!(problems(&cfg).iter().any(|p| p == "machine.l1_port and serial_port_a both use port 8880"), "{:?}", problems(&cfg)); + cfg.machine.profile = MachineProfile::TezroIp53; + cfg.tezro.l1_port = None; + cfg.tezro.serial_port_c = Some(8881); + assert!(problems(&cfg).iter().any(|p| p == "machine.serial_port_c and serial_port_b both use port 8881"), "{:?}", problems(&cfg)); + cfg.tezro.serial_port_c = None; + assert!(!problems(&cfg).iter().any(|p| p.contains("both use port")), "{:?}", problems(&cfg)); + cfg.machine.profile = MachineProfile::O2Ip32; + cfg.o2.control_port = Some(8888); + assert!(problems(&cfg).iter().any(|p| p == "machine.control_port and monitor_port both use port 8888"), "{:?}", problems(&cfg)); + cfg.o2.control_port = None; + cfg.virtio_serial.enabled = true; + cfg.serial_port_a = Some(8890); + assert!(problems(&cfg).iter().any(|p| p == "virtio_serial tcp_port and serial_port_a both use port 8890"), "{:?}", problems(&cfg)); + } + /// A `prom` the user names must be there, on every machine; "(embedded)" and the /// default ask for the built-in PROM. #[test] From ddbf58d093cb735ebb0f76cfca9eaf9f1cbcb131 Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:31:10 -0700 Subject: [PATCH 3/6] workstation: route disc changes to every SCSI controller Disc changes from the CI socket, the window's RCtrl+F12 and iris-gui went through a changer that each machine built from its first SCSI controller only. A CD-ROM on the Indigo2's second controller, the Octane's second bus, the O2's external bus or an Origin's extra controllers was visible to the guest but not listed, loaded or ejected: "No device at SCSI ID 20". Add DiscChangers, which holds every controller's changer and takes the same id the config uses for the drive, `[scsi.N]` = 16 * controller + id. A bare id below 16 still means controller 0, so existing commands keep their meaning. Each machine now hands it all of its controllers. It runs only when a disc change is requested, not on any guest path. Production lines: +39 -7 --- src/ip27.rs | 2 +- src/ip30_machine.rs | 3 +-- src/ip32_machine.rs | 5 ++--- src/machine.rs | 27 ++++++++++++++++++++++++++- src/workstation.rs | 33 +++++++++++++++++++++++++++++++++ 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/ip27.rs b/src/ip27.rs index d81b93cad..88cecba6a 100644 --- a/src/ip27.rs +++ b/src/ip27.rs @@ -462,7 +462,7 @@ pub(crate) fn pci_devices( let ps2 = ioc3.ps2(); let reset_scsi = scsi.clone(); let disk_scsi = scsi.clone(); - let disc_changer = scsi.first().map(|c| c.clone() as Arc); + let disc_changer = Some(Arc::new(crate::workstation::DiscChangers(scsi.iter().map(|c| c.clone() as _).collect())) as Arc); let reset_clock = timekeeper.clone(); let flush = timekeeper.clone(); let reset: Box = Box::new(move || { diff --git a/src/ip30_machine.rs b/src/ip30_machine.rs index 0c5c534b6..34a6f6cbf 100644 --- a/src/ip30_machine.rs +++ b/src/ip30_machine.rs @@ -1515,9 +1515,8 @@ impl Workstation for OctaneMachine { fn scratch_path(&self) -> Option<&std::path::Path> { self.scratch_path.as_deref() } - /// Disc changes on the internal bus. fn disc_changer(&self) -> Option> { - Some(self.scsi[0].clone() as Arc) + Some(Arc::new(crate::workstation::DiscChangers(self.scsi.iter().map(|c| c.clone() as _).collect()))) } fn pending_chd_sync_count(&self) -> usize { self.disk_buses().iter().map(|b| b.pending_chd_sync_count()).sum() diff --git a/src/ip32_machine.rs b/src/ip32_machine.rs index 7b780584a..a98e234f1 100644 --- a/src/ip32_machine.rs +++ b/src/ip32_machine.rs @@ -906,10 +906,9 @@ impl Workstation for O2Machine { fn ci_rollback(&mut self) -> Result<(), String> { O2Machine::ci_rollback(self) } fn scratch_path(&self) -> Option<&std::path::Path> { self.scratch_path.as_deref() } - /// Disc changes on the internal bus (controller 0), as the Indigo2 offers - /// its first controller. fn disc_changer(&self) -> Option> { - self.bus.scsi.lock().unwrap().first().map(|c| c.clone() as Arc) + let ctls = self.bus.scsi.lock().unwrap().iter().map(|c| c.clone() as _).collect(); + Some(Arc::new(crate::workstation::DiscChangers(ctls))) } /// The same `/CDROM` remount the Indy types: controller 0 is `dks0` to /// IRIX on the O2 as well. diff --git a/src/machine.rs b/src/machine.rs index 1b1c1c175..ce26a844b 100644 --- a/src/machine.rs +++ b/src/machine.rs @@ -2618,7 +2618,8 @@ impl Workstation for Machine { } fn scratch_path(&self) -> Option<&std::path::Path> { Machine::scratch_path(self) } fn disc_changer(&self) -> Option> { - Some(self.hpc3.scsi().clone()) + let ctls = std::iter::once(self.hpc3.scsi()).chain(self.hpc3.scsi1()); + Some(Arc::new(crate::workstation::DiscChangers(ctls.map(|c| c.clone() as _).collect()))) } fn remount_cdrom_guest(&self, scsi_id: u8) { Machine::remount_cdrom_guest(self, scsi_id) } fn pending_chd_sync_count(&self) -> usize { Machine::pending_chd_sync_count(self) } @@ -3043,6 +3044,30 @@ mod stop_order_tests { assert!(probe.stopped.load(SeqCst), "the display thread released its renderer"); assert!(!overlap.load(SeqCst), "HPC3 was still running when the graphics stopped"); } + + /// A CD-ROM on the Indigo2's second controller is `[scsi.20]`; disc + /// changes must reach it by that key. + #[test] + fn second_controller_cdrom_takes_disc_changes() { + use crate::config::{MachineProfile, ScsiDeviceConfig}; + use crate::workstation::Workstation; + let dir = crate::display_stop_tests::scratch("indigo2-disc"); + let nv = dir.to_path_buf(); + let machine = big_stack(move || { + let mut cfg = crate::bench_runner::bench_config([16, 0, 0, 0], &parts::R4400_150); + crate::test_temp::nvram_in(&mut cfg, &nv); + cfg.machine.profile = MachineProfile::Indigo2Ip22; + cfg.scsi.insert(20, ScsiDeviceConfig { cdrom: true, controller: 1, ..Default::default() }); + Box::new(Machine::new(cfg)) + }); + let changer = Workstation::disc_changer(&*machine).expect("a disc changer"); + assert_eq!(changer.disc_status().iter().map(|d| d.0).collect::>(), [20]); + let iso = dir.join("a.iso"); + std::fs::write(&iso, vec![0u8; 2048]).unwrap(); + let path = iso.to_string_lossy().into_owned(); + assert_eq!(changer.load_disc(20, path.clone()), Ok(path)); + assert!(changer.load_disc(4, "x.iso".into()).is_err(), "controller 0 has no id 4"); + } } #[cfg(test)] diff --git a/src/workstation.rs b/src/workstation.rs index a53acf89d..677b434bd 100644 --- a/src/workstation.rs +++ b/src/workstation.rs @@ -437,6 +437,39 @@ pub trait DiscChanger: Send + Sync { fn eject_to_empty(&self, id: usize) -> Result<(), String>; } +/// Every controller's drives behind one changer, each named by its `[scsi.N]` +/// key, `16 * controller + id`. A bare id below 16 is controller 0. +pub struct DiscChangers(pub Vec>); + +impl DiscChangers { + fn split(&self, slot: usize) -> Result<(&dyn DiscChanger, usize), String> { + let ctl = self.0.get(slot / 16).ok_or_else(|| format!("No SCSI controller for ID {slot}"))?; + Ok((&**ctl, slot % 16)) + } +} + +impl DiscChanger for DiscChangers { + fn disc_status(&self) -> Vec<(usize, String, Vec, u64, u64)> { + let each = self.0.iter().enumerate(); + each.flat_map(|(c, d)| { + d.disc_status().into_iter().map(move |(id, cur, discs, p, n)| (16 * c + id, cur, discs, p, n)) + }) + .collect() + } + fn load_disc(&self, id: usize, path: String) -> Result { + let (ctl, id) = self.split(id)?; + ctl.load_disc(id, path) + } + fn eject_disc(&self, id: usize) -> Result { + let (ctl, id) = self.split(id)?; + ctl.eject_disc(id) + } + fn eject_to_empty(&self, id: usize) -> Result<(), String> { + let (ctl, id) = self.split(id)?; + ctl.eject_to_empty(id) + } +} + /// Every controller that lends its targets (the WD33C93A, the Adaptec 7880) /// takes disc changes the same way; the operations are `scsi_monitor`'s. impl DiscChanger for T { From 9de0a28cc94ab0e6d22ec9a38abea383cee019b6 Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:30:53 -0700 Subject: [PATCH 4/6] config: refuse --test-device next to the Ultra64 board or a second head The test device, the Ultra64 dev board and the second Newport head all decode GIO expansion slot 0. validate() already refuses virtio devices in exp0 beside them, but not these pairings, so a config such as --test-device with [ultra64] enabled passed validation and then aborted in the machine constructor with a panic (exit 134), leaving the Ultra64 bridge shared-memory object behind in /dev/shm. Reject both combinations in validate() on the Indy, Indigo2 and Indigo2 IMPACT, so the user gets a configuration error and nothing is created. The constructor check stays as a backstop for in-process callers. The check runs once at config time, so no hot path is touched. Production lines: +9 -0 --- src/config.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/config.rs b/src/config.rs index a84b87471..1111b2b13 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4072,6 +4072,15 @@ impl MachineConfig { } } self.validate_serial_sockets()?; + // The test device decodes GIO expansion slot 0, as do the Ultra64 board and the second Newport head. + if self.test_device && matches!(self.machine.profile, MachineProfile::IndyIp24 | MachineProfile::Indigo2Ip22 | MachineProfile::Indigo2Ip28) { + if self.ultra64.enabled { + return Err("test_device and [ultra64] both claim GIO expansion slot 0; enable one".into()); + } + if self.graphics.heads == 2 && !self.headless { + return Err("test_device and the second graphics head (graphics.heads = 2) both claim GIO expansion slot 0".into()); + } + } if self.test_device_run_config.is_some() { if !self.test_device { return Err("test_device_run_config needs test_device".into()); @@ -5375,6 +5384,17 @@ mod export_tests { assert!(alone.contains("needs test_device"), "{alone}"); } + #[test] + fn the_test_device_refuses_another_card_in_gio_slot_0() { + let cli = |a: &[&str]| Cli::parse_from(["iris"].iter().chain(a)).apply(MachineConfig::default()); + let mut cfg = cli(&["--test-device"]); + cfg.ultra64.enabled = true; + assert!(cfg.validate().unwrap_err().contains("[ultra64]")); + let mut cfg = cli(&["--test-device"]); + cfg.graphics.heads = 2; + assert!(cfg.validate().unwrap_err().contains("second graphics head")); + } + #[test] fn parse_mac_accepts_both_separators_and_rejects_junk() { assert_eq!(parse_mac("00:80:19:12:34:56").unwrap(), [0, 0x80, 0x19, 0x12, 0x34, 0x56]); From 5e16792d4c99898d780940364e05a4fc553ba77e Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:32:32 -0700 Subject: [PATCH 5/6] ds1685: stop the writer thread keeping its part alive The NVRAM writer upgraded a Weak and held the strong Arc for its whole condvar wait. If the owner dropped the last reference to a started part without calling stop, the count never reached zero, Drop (which stops and flushes) never ran, and the thread waited forever with any dirty image unwritten. The self-join guard in stop existed only because of this shape. No shipped machine hits it today: the IOC3 and the machine both stop the part before dropping it. It is a trap for any new owner. Move the job slot, condvar and running flag into an Arc that the writer holds instead of the part. Dropping the part's last reference now runs Drop, which stops and joins the writer, so the Weak, new_cyclic and the self-join guard go away. Nothing on a hot path changes; hand_over, which runs from the debounce timer, takes one extra pointer hop. The new test drops a started part with the writer parked and checks the part is freed; it fails before this change and passes after. Production lines: +29 -30 --- src/dev/ds1685.rs | 77 +++++++++++++++++++++++++++++------------------ 1 file changed, 47 insertions(+), 30 deletions(-) diff --git a/src/dev/ds1685.rs b/src/dev/ds1685.rs index ec0e4a02b..f55184bbd 100644 --- a/src/dev/ds1685.rs +++ b/src/dev/ds1685.rs @@ -19,7 +19,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::SyncSender; -use std::sync::{Arc, Weak}; +use std::sync::Arc; use std::time::{Duration, Instant}; use parking_lot::{Condvar, Mutex}; @@ -201,6 +201,16 @@ fn save_nvram((path, image, clock): &NvramJob) -> std::io::Result<()> { /// A rewrite of the NVRAM file waiting for the writer thread. type NvramJob = (std::path::PathBuf, Vec, Option>); +/// What the writer thread shares with the part. It holds only this, so +/// dropping the part's last reference runs its `Drop`, which joins the writer. +#[derive(Default)] +struct WriterSlot { + /// The NVRAM image the writer thread has yet to put in the file. + job: Mutex>, + ready: Condvar, + running: AtomicBool, +} + /// The clock part: its registers and RAM, the file they persist in, and the /// thread that writes it. pub struct Ds1685 { @@ -210,25 +220,18 @@ pub struct Ds1685 { /// Where the guest's power-off goes: one `PowerOff` event when it writes /// the bit. events: Option>, - /// The NVRAM image the writer thread has yet to put in the file. - job: Mutex>, - ready: Condvar, - running: AtomicBool, + slot: Arc, thread: Mutex>>, - me: Weak, } impl Ds1685 { pub fn new(events: Option>) -> Arc { - Arc::new_cyclic(|me| Ds1685 { + Arc::new(Ds1685 { st: Mutex::new(Rtc::new()), dirty: AtomicU64::new(0), events, - job: Mutex::new(None), - ready: Condvar::new(), - running: AtomicBool::new(false), + slot: Arc::default(), thread: Mutex::new(None), - me: me.clone(), }) } @@ -312,8 +315,8 @@ impl Ds1685 { /// The debounce ran out: hand the image to the writer thread. pub fn hand_over(&self) { if let Some(job) = self.take_dirty(NVRAM_QUIET) { - *self.job.lock() = Some(job); - self.ready.notify_all(); + *self.slot.job.lock() = Some(job); + self.slot.ready.notify_all(); } } @@ -340,13 +343,12 @@ impl Ds1685 { } /// Write the NVRAM file when the timer hands over an image. - fn writer(me: Weak) { + fn writer(s: Arc) { loop { let job = { - let Some(d) = me.upgrade() else { return }; - let mut slot = d.job.lock(); - while slot.is_none() && d.running.load(Ordering::SeqCst) { - d.ready.wait(&mut slot); + let mut slot = s.job.lock(); + while slot.is_none() && s.running.load(Ordering::SeqCst) { + s.ready.wait(&mut slot); } match slot.take() { Some(j) => j, @@ -405,39 +407,35 @@ impl Device for Ds1685 { /// Start the writer thread. fn start(&self) { - if self.running.swap(true, Ordering::SeqCst) { + if self.slot.running.swap(true, Ordering::SeqCst) { return; } - let me = self.me.clone(); + let slot = self.slot.clone(); *self.thread.lock() = Some( std::thread::Builder::new() .name("IOC3-NVRAM".into()) - .spawn(move || Ds1685::writer(me)) + .spawn(move || Ds1685::writer(slot)) .expect("spawn ds1685 nvram thread"), ); } /// Join the writer and flush the file. fn stop(&self) { - if !self.running.swap(false, Ordering::SeqCst) { + if !self.slot.running.swap(false, Ordering::SeqCst) { return; } // The writer waits on the job slot's lock: take it so the wake-up // cannot fall between its check of `running` and its wait. - drop(self.job.lock()); - self.ready.notify_all(); - // The writer can hold the last reference for a moment, and then this - // runs on it; it cannot join itself. + drop(self.slot.job.lock()); + self.slot.ready.notify_all(); if let Some(t) = self.thread.lock().take() { - if t.thread().id() != std::thread::current().id() { - let _ = t.join(); - } + let _ = t.join(); } self.flush(); } fn is_running(&self) -> bool { - self.running.load(Ordering::SeqCst) + self.slot.running.load(Ordering::SeqCst) } fn get_clock(&self) -> u64 { @@ -451,3 +449,22 @@ impl Drop for Ds1685 { self.flush(); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dropping_a_started_part_without_stop_ends_its_writer() { + let d = Ds1685::new(None); + d.start(); + // Wait for the writer to park holding its reference. + let t = Instant::now(); + while Arc::strong_count(&d) < 2 && t.elapsed() < Duration::from_millis(500) { + std::thread::yield_now(); + } + let part = Arc::downgrade(&d); + drop(d); + assert!(part.upgrade().is_none(), "the writer kept the part alive"); + } +} From 9341cf0d89ebe0be280e5fd66490c8797f11dddb Mon Sep 17 00:00:00 2001 From: James Braid Date: Sun, 22 Nov 2026 13:14:59 -0700 Subject: [PATCH 6/6] docs: say Tezro IOC4 console needs the PROM's console setting The Tezro console option reads as if it moves the guest console. It only picks the host connection. The PROM defaults to the L1 and writes nothing to the IOC4 ports, so choosing ioc4_a on a fresh flash leaves the port and serial_log empty and looks like a model bug. Running console ioc4 in the Command Monitor and resetting moves the PROM console to IOC4 UART A (port B stays silent). The PROM stores that in the flash, so it survives only with a flash file. Document both in the Tezro page and the feature table. Production lines: +0 -0 --- FEATURES.md | 2 +- docs/tezro-ip53.md | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index da72dd9c4..9581cb5fd 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -324,7 +324,7 @@ Tezro-specific settings apply when `machine.profile = "tezro_ip53"`. | Key | Default | Values and behavior | |---|---|---| | `flash` | unset | Persistent 16 MiB boot-flash file. Unset, the flash is volatile. | -| `console` | `l1` | `l1`, `ioc4_a`, `ioc4_b`, `ioc4_c` or `ioc4_d`. Selects the guest console connection. | +| `console` | `l1` | `l1`, `ioc4_a`, `ioc4_b`, `ioc4_c` or `ioc4_d`. Selects the host connection only. The PROM uses the L1 until `console ioc4` is run in its Command Monitor and the machine is reset; it then uses UART A (`ioc4_a`) only, and keeps the choice in the `flash` file. | | `l1_port` | `8882` | Host TCP port for the L1 console. | | `l1_log` | unset | Optional serial log path for L1 output when an IOC4 port is selected as console. | | `serial_port_c`, `serial_port_d` | `8883`, `8884` | Host TCP ports of IOC4 ports 2 and 3; ports 0 and 1 use `serial_port_a` and `serial_port_b`. | diff --git a/docs/tezro-ip53.md b/docs/tezro-ip53.md index 855cf05ab..71b052d1f 100644 --- a/docs/tezro-ip53.md +++ b/docs/tezro-ip53.md @@ -119,7 +119,11 @@ matches a captured Tezro. One processor needs at least 512 MiB, two or four at l the L1 port and log. The console options are `l1` (the default) and `ioc4_a` to `ioc4_d`, the IOC4's ports 0 to 3. IOC4 ports 0 and 1 listen on `serial_port_a` and `serial_port_b`, ports 2 and 3 on `tezro.serial_port_c` -and `tezro.serial_port_d`. `nvram` names the 32 KiB DS1744 store; its clock +and `tezro.serial_port_d`. The setting only picks the host connection: the +PROM writes to the L1 until `console ioc4` is run in its Command Monitor and +the machine is reset, after which the menu appears on UART A (`ioc4_a`) only. +The PROM keeps that choice in the flash, so set `flash` or it is lost on the +next start. `nvram` names the 32 KiB DS1744 store; its clock reference is kept beside it with a `.clock` suffix. ## Firmware inputs