// SPDX-License-Identifier: MIT //! A cart's serial EEPROM (93C46 family), wired to the cart port, saved under the user's //! data directory (never beside a ROM) (`cart/eeprom.py`). //! //! Wiring: DOC, the BLL kit's `includes/eeprom.inc` (Bastian Schick, Apache-2.0) and //! cc65's `libsrc/lynx/eeprom.s` (zlib; the same author's routine): "CS = A7 (18), CLK = //! A1 (11), DI/DO = AUDIN (32)". A1 and A7 are bits of the cart address counter (so a //! program clocks the chip by accessing RCART, and drops CS and CLK together by pulsing //! the address strobe, which clears the counter); DI and DO share the AUDIN pin, driven by //! Mikey when IODIR bit 4 makes it an output, read through IODAT bit 4 when it is an input. //! (This is a community convention, not an Atari document: U8.) //! //! Protocol: the 93Cxx serial EEPROM as its data sheets describe it and as those drivers //! drive it (DOC): with CS high, DI is taken on each rising CLK; a 1 is the start bit, //! then two opcode bits and the address (6 bits for a 93C46 in 16-bit words, one more in //! 8-bit organisation; 8 for 93C56/66, 10 for 93C76/86), then for WRITE the data, MSB //! first. READ: DO gives a dummy 0 after the last address bit, then the word MSB first on //! each following rising CLK (and the next word after it). EWEN/EWDS (opcode 00, address //! 11xxxx/00xxxx) set and clear the write enable, which is clear at power-on; ERASE (11), //! WRITE (01), ERAL (00 10xxxx) and WRAL (00 01xxxx) need it. A write or erase is done //! when CS falls after its last bit; then, with CS high again, DO reads 1 for ready. //! HYPOTHESIS: programming takes no time (the chips take milliseconds; the drivers poll //! DO until ready, so a program sees no difference unless it times the wait). DO floats //! (AUDIN reads its pull-up, 1) when the chip is not driving it. Erased cells read 1. //! //! The save file holds the chip's cells in order, 16-bit words high byte first (8-bit //! organisation: bytes in order). //! //! Differences forced by Rust: `do` is a keyword, so the field is `do_`; the string modes //! and pending kinds are enums. The save path is not part of a save state (it is kept from //! the console a state is loaded into). use std::path::PathBuf; use serde::{Deserialize, Serialize}; /// Header EEPROM type -> (address bits in 16-bit organisation, size in bits) (cartridge.md /// byte 60: 1 = 93C46 ... 5 = 93C86). pub const CHIPS: [(&str, u32, usize); 5] = [ ("93C46", 6, 1024), ("93C56", 8, 2048), ("93C66", 8, 4096), ("93C76", 10, 8192), ("93C86", 10, 16384), ]; fn chip(name: &str) -> Option<(u32, usize)> { CHIPS.iter().find(|c| c.0 == name).map(|c| (c.1, c.2)) } /// `$XDG_DATA_HOME/lynx-python/eeprom` (default `~/.local/share/...`). The directory is /// the reference's, so the specification and its transcription share saves. pub fn save_dir() -> PathBuf { let base = match std::env::var("XDG_DATA_HOME") { Ok(v) if !v.is_empty() => PathBuf::from(v), _ => home().join(".local").join("share"), }; base.join("lynx-python").join("eeprom") } pub(crate) fn home() -> PathBuf { PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/".into())) } pub fn save_path(payload_sha1: &str, chip: &str) -> PathBuf { save_dir().join(format!("{payload_sha1}.{}.eep", chip.to_lowercase())) } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Mode { Idle, Command, Write, Read, Done, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Pending { Write, Erase, Eral, } #[derive(Clone, Serialize, Deserialize)] pub struct Eeprom { pub address_bits: u32, pub bits: i64, pub cells: Vec, pub clk: u8, pub count: i64, pub cs: u8, pub do_: u8, pub driving: bool, pub enabled: bool, pub mode: Mode, pub opcode: i64, pub out: i64, #[serde(skip)] pub path: Option, pub pending: Option<(Pending, i64, i64)>, // a write or erase waiting for CS to fall pub reads: u64, // READ commands received pub word_bits: u32, pub writes: u64, // completed writes and erases (for tools and tests) } impl Eeprom { pub fn new(chip_name: &str, eight_bit: bool, path: Option) -> Eeprom { let (address_bits, size) = chip(chip_name).expect("a 93Cxx chip name"); let word_bits = if eight_bit { 8 } else { 16 }; let mut eeprom = Eeprom { address_bits: address_bits + if eight_bit { 1 } else { 0 }, bits: 0, cells: vec![(1u32 << word_bits) - 1; size / word_bits as usize], // erased = 1s clk: 0, count: 0, cs: 0, do_: 1, driving: false, enabled: false, // DOC: write enable is clear at power-on mode: Mode::Idle, opcode: 0, out: 0, path, pending: None, reads: 0, word_bits, writes: 0, }; if let Some(p) = eeprom.path.clone() { if p.exists() { if let Ok(data) = std::fs::read(&p) { eeprom.load(&data); } } } eeprom } // -- the save file ---------------------------------------------------------------- pub fn image(&self) -> Vec { if self.word_bits == 8 { return self.cells.iter().map(|&c| c as u8).collect(); } self.cells .iter() .flat_map(|&w| [(w >> 8) as u8, w as u8]) .collect() } pub fn load(&mut self, data: &[u8]) { if self.word_bits == 8 { for (i, &b) in data.iter().take(self.cells.len()).enumerate() { self.cells[i] = b as u32; } } else { for i in 0..self.cells.len().min(data.len() / 2) { self.cells[i] = ((data[2 * i] as u32) << 8) | data[2 * i + 1] as u32; } } } fn save(&self) { if let Some(path) = &self.path { if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } let _ = std::fs::write(path, self.image()); } } // -- the pins --------------------------------------------------------------------- /// New levels on CS, CLK and DI (called whenever the counter or AUDIN changes). pub fn pins(&mut self, cs: u8, clk: u8, di: u8) { if cs != 0 && self.cs == 0 { self.mode = Mode::Idle; self.driving = false; if self.pending.is_none() { self.do_ = 1; // ready (HYPOTHESIS: programming takes no time) } } else if cs == 0 && self.cs != 0 { if self.pending.is_some() { self.program(); } self.mode = Mode::Idle; self.driving = false; self.do_ = 1; } if cs != 0 && clk != 0 && self.clk == 0 { self.rise(di); } self.cs = cs; self.clk = clk; } fn rise(&mut self, di: u8) { let mode = self.mode; if mode == Mode::Idle { if di != 0 { self.mode = Mode::Command; self.bits = 0; self.count = 0; } return; } if mode == Mode::Command { self.bits = (self.bits << 1) | di as i64; self.count += 1; if self.count == 2 + self.address_bits as i64 { self.command(); } return; } if mode == Mode::Write { self.out = (self.out << 1) | di as i64; self.count += 1; if self.count == self.word_bits as i64 { self.pending = Some((Pending::Write, self.opcode, self.out)); self.mode = Mode::Done; } return; } if mode == Mode::Read { self.shift_out(); } } fn command(&mut self) { let opcode = self.bits >> self.address_bits; let address = self.bits & ((1 << self.address_bits) - 1); let top = address >> (self.address_bits - 2); self.opcode = address; self.count = 0; self.out = 0; if opcode == 0b10 { // READ: a dummy 0, then the word self.reads += 1; self.mode = Mode::Read; self.out = address; self.count = -1; self.driving = true; self.do_ = 0; } else if opcode == 0b01 { self.mode = Mode::Write; } else if opcode == 0b11 { self.pending = Some((Pending::Erase, address, 0)); self.mode = Mode::Done; } else if top == 0b11 { self.enabled = true; // EWEN self.mode = Mode::Done; } else if top == 0b00 { self.enabled = false; // EWDS self.mode = Mode::Done; } else if top == 0b10 { self.pending = Some((Pending::Eral, 0, 0)); self.mode = Mode::Done; } else { self.mode = Mode::Write; // WRAL: data follows self.opcode = -1; } } /// The next data bit on DO (rising CLK during READ). fn shift_out(&mut self) { self.count += 1; if self.count == self.word_bits as i64 { // sequential read: the next word self.out = (self.out + 1).rem_euclid(self.cells.len() as i64); self.count = 0; } let word = self.cells[self.out as usize]; self.do_ = ((word >> (self.word_bits as i64 - 1 - self.count)) & 1) as u8; } fn program(&mut self) { let (kind, address, value) = self.pending.take().expect("pending"); if !self.enabled { return; } let full = (1u32 << self.word_bits) - 1; let n = self.cells.len() as i64; match kind { Pending::Write if address >= 0 => { self.cells[address.rem_euclid(n) as usize] = value as u32; } Pending::Write => { // WRAL self.cells = vec![value as u32; self.cells.len()]; } Pending::Erase => { self.cells[address.rem_euclid(n) as usize] = full; } Pending::Eral => { self.cells = vec![full; self.cells.len()]; } } self.writes += 1; self.save(); } } /// The cart's EEPROM from its description (`eeprom` = (type, organisation bits)). pub fn for_cart(description: &crate::cart::loader::CartDescription) -> Option { let (chip_name, organisation) = description.eeprom.as_ref()?; Some(Eeprom::new( chip_name, *organisation == 8, Some(save_path(&description.sha1, chip_name)), )) }