// SPDX-License-Identifier: MIT //! The chip's core machinery: stepping, delay slots, exceptions, and every memory access. //! //! sh2-python's `_core.py`. ``step()`` runs one instruction, or one exception sequence, //! and returns its states. The rules it encodes, with their sources: //! //! - **PC.** ``self.pc`` is the address of the next instruction to run. While a handler //! runs, ``self.pc`` is its address + 2, so the PC that PC-relative forms and branch //! displacements use (the instruction's address + 4, PM 6.x) is ``self.pc + 2``. //! - **Delay slots.** A delayed branch (``BRA``, ``BSR``, ``BRAF``, ``BSRF``, ``JMP``, //! ``JSR``, ``RTS``, ``RTE``, and ``BT/S``/``BF/S`` when taken) leaves ``pc`` on its //! slot and stores the target in ``delay_target``; the next ``step()`` runs the slot //! with ``self.pc`` set to the target, so a PC-relative slot instruction sees the //! target + 2 (U1, PM 6.x: "the PC must point to ... the branch destination + 2"), //! then continues at the target. Branch registers are read before the slot runs (PM //! 4.1.5). No interrupt or address error is accepted between a branch and its slot //! (HM 4.6.1); a slot holding undefined code or a PC-changing instruction is the //! illegal slot exception, saving the branch target (HM 4.5.3, U3). A not-taken //! ``BT/S``/``BF/S`` makes no slot (U2: the three emulators; unverified). //! - **Interrupts** are accepted between instructions when their level exceeds //! SR.I3-I0 (HM 4.4, 5.4), but not right after a delayed branch nor after ``LDC``, //! ``LDC.L``, ``STC``, ``STC.L``, ``LDS``, ``LDS.L``, ``STS``, ``STS.L`` (HM 4.6, table //! 4.10). IRL is sampled each boundary with no noise-canceller latency (U4's build //! choice). //! - **Exceptions** push SR then PC on R15's stack and read the vector at VBR + 4n (HM //! 4.4-4.5; PM 7.7.7: two MAs push, the third reads the vector). //! - **Memory.** Each CPU access is routed by A31-A29 (HM table 8.2): the cache area, //! the cache-through area, the associative purge space, the address array, the data //! array, and the on-chip modules at H'FFFFFE00-H'FFFFFFFF. External cycles go to the //! board's callbacks through the BSC, split into port-width cycles (HM 7.4.1). //! - **The write buffer** (HM 7.11.2: "the bus state controller has one level of write //! buffer"). A CPU write to external memory is taken by the buffer as soon as it is //! empty and the CPU goes on one state later, while the BSC makes the write's cycles; //! a second write waits until the first's cycles end, and every external read (a //! cache-through read, a line fill, a fetch that misses, a DMA read) waits for them //! too ("During reads, the CPU always has to wait"). Cache hits and on-chip module //! accesses do not wait. A CCR write that arrives while a write is buffered takes //! effect when that write's cycles end, and cache hits use the old lines meanwhile //! (U9: DN's hardware values; C20). DMA writes are not buffered here (rung 5). //! - **Synchronous DRAM and refresh** (HM 7.5; bsc.rs has the shapes). A read of an //! SDRAM area is one burst, a write a single write, with the states the BSC gives by //! row and bank; a line fill is one burst, still one callback per port cycle. Refresh //! requests are made between external accesses, never inside one (HM 7.5.7: "after //! the access cycle is completed"), and at step boundaries when the bus is idle; an //! access that finds one under way waits for it. //! - **Address errors** (HM table 4.6): a misaligned word or longword access, an odd //! instruction address, a fetch from on-chip module space, a byte access to //! H'FFFFFF00-, a longword access to H'FFFFFE00-H'FFFFFEFF. The faulting access is not //! made (a read gives 0: U15 leaves the access itself open) and the exception (vector //! 9) is taken after the instruction completes (HM 4.3.2), saving the next //! instruction's address; one pending after a delayed branch waits for the slot (HM //! 4.6.1). use crate::bus::{Bus, DATA, FETCH, FILL, FIRST, HIT, REFRESH, THROUGH, VECTOR, WRITE}; use crate::cache::{CCR_ID, CCR_OD}; use crate::cpu::{Sh7604, M32}; use crate::module::ModuleId; pub const NEVER: i64 = 1 << 62; pub const VECTOR_ILLEGAL: u32 = 4; // general illegal instruction (HM table 4.3) pub const VECTOR_SLOT_ILLEGAL: u32 = 6; pub const VECTOR_ADDRESS_ERROR: u32 = 9; pub const VECTOR_DMA_ADDRESS_ERROR: u32 = 10; // HM table 4.3 pub const VECTOR_NMI: u32 = 11; pub const IRL_VECTOR_BASE: u32 = 64; // IRL1 -> 64, IRL2-3 -> 65, ... IRL14-15 -> 71 (HM table 5.3) // The exception sequences' plans, by ``exception_plans`` index. const INTERRUPT: usize = 0; const ADDRESS_ERROR: usize = 1; const ILLEGAL: usize = 2; fn width_mask(width: u32) -> u32 { match width { 8 => 0xFF, 16 => 0xFFFF, _ => M32, } } impl Sh7604 { // -- stepping ----------------------------------------------------------------- /// Run one instruction or one exception sequence; return the states it took. /// /// The states are those the pipeline's cursor moved (pipeline.rs): over a run they /// add up to PM 7.3's count, the intervals between EX stages. pub fn step(&mut self) -> i64 { let start = self.clock; if self.pc != self.p_pc { // The host moved the PC (a test, a replay's resync): the pipeline's fetches // were for the old stream. self.pipeline_restart(); } if start >= self.next_event { self.service_events(); } if self.dmac.active && !self.dmac_run_disabled { self.dmac_run(); if self.clock != start { // The DMAC's cycles held the bus: the CPU's slots wait for them. self.p_start += self.clock - start; } } let target = self.delay_target; let tables = self.tables; if target < 0 { if self.address_error { self.address_error = false; let pc = self.pc; self.exception(VECTOR_ADDRESS_ERROR, pc, -1, ADDRESS_ERROR, -1); self.p_pc = self.pc; return self.clock - start; } if self.dma_address_error { // DOC: HM 4.1 (table 4.1: below the CPU's address error, above every // interrupt; table 4.2: taken when the instruction under way ends, so not // between a delayed branch and its slot, HM 4.6.1), HM 4.3.2 (the saved PC // is the next instruction's), HM 14.3.2 (it ends SLEEP). Entry as for the // CPU's address error (PM figure 7.95). self.dma_address_error = false; self.sleeping = false; let pc = self.pc; self.exception(VECTOR_DMA_ADDRESS_ERROR, pc, -1, ADDRESS_ERROR, -1); self.p_pc = self.pc; return self.clock - start; } if self.nmi != self.nmi_seen { self.nmi_edge(); } if !self.no_interrupt && self.interrupt_due() { self.take_interrupt(); self.p_pc = self.pc; return self.clock - start; } self.no_interrupt = false; if self.sleeping { // SLEEP: the CPU waits for an interrupt (HM 14.3.1). Idle in short // slices so the board can raise IRL between them; the pipeline waits. let idle = (self.next_event - self.clock).max(1).min(16); self.p_start += idle; self.clock = self.p_start; return self.clock - start; } let pc = self.pc; if pc & 1 != 0 || pc >= 0xFFFFFE00 { // An odd address, or a fetch from on-chip module space (HM table 4.6): // nothing is executed; the saved PC is that address (HM 4.3.2). self.exception(VECTOR_ADDRESS_ERROR, pc, -1, ADDRESS_ERROR, -1); self.p_pc = self.pc; return self.clock - start; } self.advance(self.p_next_ex - 1); // through this instruction's IF let op = self.opcode(pc); self.pc = pc + 2; let o = tables.ops[op as usize]; self.issue(o.plan, o.load_dest, o.uses, pc); self.dispatch(o.handler, op); self.retire(o.plan, pc as i64 + 2); self.no_interrupt = o.blocks; } else { // The delay slot (HM 4.6.1: no interrupt or address error between it and // its branch). let pc = self.pc; self.advance(self.p_next_ex - 1); let op = self.opcode(pc); self.delay_target = -1; let o = tables.ops[op as usize]; if o.slot_illegal { // HM 4.5.3: decoded in the slot; the saved PC is the branch target. self.exception(VECTOR_SLOT_ILLEGAL, target as u32, -1, ILLEGAL, -1); self.p_pc = self.pc; return self.clock - start; } self.pc = target as u32; self.issue(o.plan, o.load_dest, o.uses, pc); self.dispatch(o.handler, op); self.retire(o.plan, target); self.no_interrupt = o.blocks; } self.p_pc = self.pc; self.clock - start } fn service_events(&mut self) { let clock = self.clock; self.frt_run_until(clock); self.wdt_run_until(clock); self.bsc_run_until(clock); if self.bsc.refresh_at <= clock { self.refresh_idle(); } self.reschedule(); } pub(crate) fn reschedule(&mut self) { self.next_event = self.frt.next_event().min(self.wdt.next_event()).min(self.bsc.next_event()); } /// A module extends the current access by ``states`` (the DIVU, HM 10.4.1). /// /// The access's MA lasts until the clock it leaves (pipeline.rs ``ma_close``). pub(crate) fn stall(&mut self, states: i64) { self.clock += states; } // -- interrupts ----------------------------------------------------------------- /// NMI is edge-triggered; ICR.NMIE picks the edge (HM 5.2.1, 5.3.3). fn nmi_edge(&mut self) { let level = self.nmi; self.nmi_seen = level; if (level != 0) == self.intc.nmi_rising() { self.nmi_pending = true; } } fn interrupt_due(&self) -> bool { if self.nmi_pending { return true; } if self.replay_interrupts { return self.injected.is_some(); } let mask = (self.sr >> 4) & 15; self.irl > mask || self.onchip_level > mask } /// Accept the highest request (HM 5.4): NMI, then IRL vs on-chip by level. fn take_interrupt(&mut self) { self.sleeping = false; let pc = self.pc; if self.nmi_pending { self.nmi_pending = false; // NMI: level 16, I3-I0 set to 15 (HM 4.4.3). self.exception(VECTOR_NMI, pc, 15, INTERRUPT, -1); return; } if self.replay_interrupts { let (level, vector) = self.injected.take().unwrap(); if vector < 0 { self.irl_exception(level); } else { self.exception(vector as u32, pc, level as i64, INTERRUPT, -1); } return; } let irl = self.irl; if irl >= self.onchip_level { // IRL ranks above an on-chip source at the same level (HM table 5.4). self.irl_exception(irl); } else { let (vector, level) = (self.onchip_vector, self.onchip_level); self.exception(vector, pc, level as i64, INTERRUPT, -1); } } /// An IRL interrupt: its auto-vector (HM table 5.3), or the bus's (ICR.VECMD = 1). fn irl_exception(&mut self, level: u32) { let pc = self.pc; if self.intc.vecmd() { self.exception(0, pc, level as i64, INTERRUPT, level as i64); } else { self.exception(IRL_VECTOR_BASE + (level >> 1), pc, level as i64, INTERRUPT, -1); } } /// Replay only: make the next boundary accept this interrupt. /// /// A host that replays another emulator's trace (rung 2) sets /// ``chip.replay_interrupts = true``, which stops IRL and the on-chip modules from /// raising interrupts by themselves, and calls this where the trace took one. /// ``vector`` -1 means an IRL auto-vector (or external vector) for ``level``. The /// acceptance rules of HM 4.6 still apply: the interrupt waits for a boundary where /// one may be taken. pub fn inject_interrupt(&mut self, level: u32, vector: i64) { self.injected = Some((level, vector)); } /// An exception sequence in place of the next instruction (PM 7.7.7). /// /// It takes the slots of PM figures 7.95-7.97 (``exception_plans[sequence]``): its /// two pushes and the vector read are its MAs, and the handler's fetch is in the /// slot of its last stage. fn exception(&mut self, vector: u32, saved_pc: u32, level: i64, sequence: usize, external: i64) { let plan = self.exception_plans[sequence]; self.advance(self.p_next_ex - 1); let pc = self.pc; self.issue(plan, 0, 0, pc); self.enter(vector, saved_pc, level, external); self.retire(plan, -1); } /// Exception entry (HM 4.3.2-4.5): push SR, push PC, fetch the vector, jump. /// /// ``level`` >= 0 is written to SR.I3-I0 (interrupts; HM 4.4.3), -1 leaves it. /// ``external`` >= 0 is an IRL level whose vector number comes from the bus /// (ICR.VECMD = 1, HM 5.2.3): that read is made in the vector-read MA, before the /// table read. The jump is not a delayed branch. pub(crate) fn enter(&mut self, vector: u32, saved_pc: u32, level: i64, external: i64) { let sr = self.sr; self.r[15] = self.r[15].wrapping_sub(4); self.write32(self.r[15], sr); self.r[15] = self.r[15].wrapping_sub(4); self.write32(self.r[15], saved_pc); if level >= 0 { self.sr = (sr & !0xF0) | ((level as u32) << 4); } let mut vector = vector; if external >= 0 { if self.p_ma_left != 0 { self.ma_next(); } // External vector mode: A3-A0 carry the level, D7-D0 the vector number // (HM 5.2.3, figure 5.4). vector = self.bus_read(external as u32, 8, VECTOR) & 0x7F; } self.pc = self.read32(self.vbr.wrapping_add(vector << 2)); self.delay_target = -1; self.no_interrupt = false; self.address_error = false; } /// Undefined code outside a slot: general illegal instruction (HM 4.5.4). /// /// The saved PC is the start address of the undefined code. Undefined codes carry /// the illegal sequence's plan in the decode tables (PM figure 7.97), so the step has /// already given it its slots; this only enters the handler. pub(crate) fn illegal(&mut self, _op: u32) { let saved = self.pc.wrapping_sub(2); self.enter(VECTOR_ILLEGAL, saved, -1, -1); } // -- instruction fetch ------------------------------------------------------------ pub(crate) fn read_fetch(&mut self, address: u32) -> u32 { let space = address >> 29; if space == 0 { if self.ccr_at != 0 && self.clock >= self.ccr_at { self.settle_ccr(); } if self.cache.enabled { return self.cache_read(address, 32, FETCH); } if self.observe { self.bus.observe(address, 32, FETCH | THROUGH); } return self.bus_read(address, 32, FETCH | THROUGH); } if space == 1 { if self.observe { self.bus.observe(address, 32, FETCH | THROUGH); } return self.bus_read(address, 32, FETCH | THROUGH); } if space == 6 { return self.cache.get(address & 0xFFC, 32); } // The purge, address-array, reserved and on-chip spaces hold no code: a fetch // there (an overrun past the end of code, or a jump into them, which faults // when it executes, HM table 4.6) reads nothing and touches no module. 0 } // -- CPU data accesses ------------------------------------------------------------ pub(crate) fn read8(&mut self, address: u32) -> u32 { self.read(address, 8) } pub(crate) fn read16(&mut self, address: u32) -> u32 { if address & 1 != 0 { self.address_error = true; return 0; } self.read(address, 16) } pub(crate) fn read32(&mut self, address: u32) -> u32 { if address & 3 != 0 { self.address_error = true; return 0; } self.read(address, 32) } pub(crate) fn write8(&mut self, address: u32, value: u32) { self.write(address, 8, value & 0xFF); } pub(crate) fn write16(&mut self, address: u32, value: u32) { if address & 1 != 0 { self.address_error = true; return; } self.write(address, 16, value & 0xFFFF); } pub(crate) fn write32(&mut self, address: u32, value: u32) { if address & 3 != 0 { self.address_error = true; return; } self.write(address, 32, value); } /// A CPU data read (the reference's ``chip._read``, which its tests and boards call). pub fn read(&mut self, address: u32, width: u32) -> u32 { if self.p_ma_left != 0 { self.ma_next(); // this access is the instruction's next MA (pipeline.rs) } let space = address >> 29; if space == 0 { if self.ccr_at != 0 && self.clock >= self.ccr_at { self.settle_ccr(); } if self.cache.enabled { return self.cache_read(address, width, DATA); } if self.observe { self.bus.observe(address, width, THROUGH); } return self.bus_read(address, width, THROUGH); } if space == 1 { if self.observe { self.bus.observe(address, width, THROUGH); } return self.bus_read(address, width, THROUGH); } if space == 7 { return self.onchip_read(address, width); } if space == 6 { if self.observe { self.bus.observe(address, width, DATA); } return self.cache.get(address & 0xFFF, width); } if space == 3 { if width != 32 { return 0; // longword only (HM 8.4.9); other sizes undefined: read 0 } return self.cache.read_address_array(address); } // U10, HYPOTHESIS (own choice): HM 8.4.7 documents only writes to the // associative purge space (H'40000000-), so a read purges nothing and reads 0, // like the reserved spaces (H'80000000-H'BFFFFFFF, HM table 7.3) and every other // undocumented read in this core. 0 } /// A CPU data write (the reference's ``chip._write``). pub fn write(&mut self, address: u32, width: u32, value: u32) { if self.p_ma_left != 0 { self.ma_next(); } let space = address >> 29; if space == 0 { if self.observe { self.bus.observe(address, width, WRITE); } if self.ccr_at != 0 && self.clock >= self.ccr_at { self.settle_ccr(); } if self.cache.enabled { self.cache.write_hit(address, width, value); // write-through (HM 8.4.2) } let kind = if !self.cache.enabled { THROUGH } else { DATA }; self.bus_write(address, width, value, kind); } else if space == 1 { if self.observe { self.bus.observe(address, width, WRITE | THROUGH); } self.bus_write(address, width, value, THROUGH); } else if space == 7 { self.onchip_write(address, width, value); } else if space == 6 { if self.observe { self.bus.observe(address, width, WRITE); } self.cache.put(address & 0xFFF, width, value); } else if space == 3 { if width == 32 { self.cache.write_address_array(address, value); } } else if space == 2 { self.cache.purge_line(address); // DOC: HM 8.4.7, table 8.2 (A31-A29 = 010) } // H'A0000000 (A31-A29 = 101) is reserved (HM table 7.3, absent from table 8.2): // a write there does nothing (U10, HYPOTHESIS). } /// A read in the cache area with CCR.CE = 1 (HM 8.4.1). fn cache_read(&mut self, address: u32, width: u32, kind: u32) -> u32 { let entry = (address >> 4) & 63; let way = self.cache.lookup(address); if way >= 0 { let way = way as u32; self.cache.touch(entry, way); if self.observe { self.bus.observe(address, width, kind | HIT); } return self.cache.get((way << 10) | (entry << 4) | (address & 15), width); } if self.observe { self.bus.observe(address, width, kind); } if self.clock < self.wb_end { // A miss reads the bus, so it waits for a buffered write first (HM 7.11.2), // and a CCR write queued behind that write lands before the fill (U9). self.clock = self.wb_end; if self.ccr_at != 0 { self.settle_ccr(); if !self.cache.enabled { return self.bus_read(address, width, kind | THROUGH); } let way = self.cache.lookup(address); if way >= 0 { // not purged after all: the CCR write kept the cache let way = way as u32; self.cache.touch(entry, way); return self.cache.get((way << 10) | (entry << 4) | (address & 15), width); } } } if self.cache.ccr & (if kind & FETCH != 0 { CCR_ID } else { CCR_OD }) != 0 { // ID/OD: "the missed address data is read and directly transferred to the // CPU" without replacing (HM 8.4.5). return self.bus_read(address, width, kind); } let way = self.cache.victim(entry); let base = self.cache.allocate(address, way); let line = address & 0x1FFFFFF0; let area = ((line >> 25) & 3) as usize; // The fill is one access: no refresh between its cycles (HM 7.5.7). if self.clock >= self.bsc_due { self.refresh_before(); } if self.bsc.sdram[area] { self.sdram_fill(base, line, address, kind, area); } else { let port = self.bsc.widths[area]; let mut flag = FIRST; // HM 8.4.1, figure 8.4: four longwords from address + 4, wrapping in the // line, so the one holding the requested data comes last. for step in [4, 8, 12, 0] { let offset = ((address & 0xC) + step) & 0xC; let cycle = line | offset; let fill = kind | FILL | flag; let value = if port == 32 { self.cycle_read(cycle, 32, fill, area) } else { let mut value: u32 = 0; for i in 0..(32 / port) { let part = self.cycle_read(cycle + i * (port >> 3), port, fill, area); value = ((value as u64) << port) as u32 | part; } value }; self.cache.put(base | offset, 32, value); flag = 0; } } if self.clock >= self.bsc_due { self.refresh_after(); } self.cache.get(base | (address & 15), width) } // -- the external bus (through the BSC) ------------------------------------------- /// One CPU or DMAC read on the external bus, split into port-width cycles. /// /// It waits for a buffered write's cycles to end (HM 7.11.2: the bus is the write's; /// "During reads, the CPU always has to wait for the end of the operation"). pub(crate) fn bus_read(&mut self, address: u32, width: u32, kind: u32) -> u32 { if self.clock < self.wb_end { self.clock = self.wb_end; } if self.clock >= self.bsc_due { self.refresh_before(); } let address = address & 0x1FFFFFFF; let area = ((address >> 25) & 3) as usize; let value; if self.bsc.sdram[area] { value = self.sdram_read(address, width, kind, area); } else { let port = self.bsc.widths[area]; if width <= port { value = self.cycle_read(address, width, kind, area); } else { let step = port >> 3; let mut v: u32 = 0; for i in 0..(width / port) { let part = self.cycle_read(address + i * step, port, kind, area); v = ((v as u64) << port) as u32 | part; } value = v; } } if self.clock >= self.bsc_due { self.refresh_after(); } value } fn cycle_read(&mut self, address: u32, width: u32, kind: u32, area: usize) -> u32 { self.wait = 0; let value = self.call_read(address, width, kind) & width_mask(width); // The cycle lasts the BSC's states plus the board's WAIT states; the IF or MA // that made it lasts as long as its cycles (PM 7.2.3). self.clock += self.bsc.cycle_states[area] + self.wait; value } /// One CPU write, through the BSC's one-level write buffer (HM 7.11.2). /// /// The buffer takes the write once the previous one's cycles have ended; "the CPU is /// notified that the write is completed without waiting for the actual writing ... /// to end", so the access (its MA) lasts until the buffer takes it plus one state, /// and the BSC makes the write's cycles from that state on (the callbacks see /// ``chip.clock`` at each cycle's start). ``wb_end`` is where they end. pub(crate) fn bus_write(&mut self, address: u32, width: u32, value: u32, kind: u32) { if self.clock < self.wb_end { self.clock = self.wb_end; // the buffer is full: wait for its write to end if self.ccr_at != 0 { self.settle_ccr(); } } let taken = self.clock; self.write_cycles(address, width, value, kind); self.wb_end = self.clock; self.clock = taken + 1; } /// The CCR write that waited behind a buffered write takes effect (U9, C20). pub(crate) fn settle_ccr(&mut self) { self.ccr_at = 0; let value = self.ccr_value; self.cache.write_ccr(value); } /// The port-width write cycles of one access, back to back from ``chip.clock``. fn write_cycles(&mut self, address: u32, width: u32, value: u32, kind: u32) { if self.clock >= self.bsc_due { self.refresh_before(); } let address = address & 0x1FFFFFFF; let area = ((address >> 25) & 3) as usize; let sdram = self.bsc.sdram[area]; let port = self.bsc.widths[area]; if width <= port { self.write_one(sdram, address, width, value, kind, area); } else { let step = port >> 3; let count = width / port; let mask = width_mask(port); for i in 0..count { let part = ((value as u64 >> (port * (count - 1 - i))) as u32) & mask; self.write_one(sdram, address + i * step, port, part, kind, area); } } if self.clock >= self.bsc_due { self.refresh_after(); } } /// ``cycle = self._sdram_write if self._sdram[area] else self._cycle_write``. fn write_one(&mut self, sdram: bool, address: u32, width: u32, value: u32, kind: u32, area: usize) { if sdram { self.sdram_write(address, width, value, kind, area); } else { self.cycle_write(address, width, value, kind, area); } } fn cycle_write(&mut self, address: u32, width: u32, value: u32, kind: u32, area: usize) { self.wait = 0; self.call_write(address, width, value, kind); self.clock += self.bsc.cycle_states[area] + self.wait; } // -- synchronous DRAM (HM 7.5) and refresh (HM 7.5.7) --------------------------------- /// One burst read (HM 7.5.3, 7.5.4): ``calls`` are its port cycles, each a callback, /// ``(address, width, kind)``. The first carries the burst's command states, the /// last the data cycles the access does not use (figure 7.17). fn sdram_burst(&mut self, address: u32, calls: &[(u32, u32, u32)], area: usize) -> Vec { let (start, command) = self.bsc.read_start(area, address, self.clock); self.clock = start; let unused = self.bsc.burst[area] - calls.len() as i64; let last = calls.len() - 1; let mut values = Vec::with_capacity(calls.len()); for (i, (cycle, width, kind)) in calls.iter().enumerate() { let mut length = 1; if i == 0 { length += command; } if i == last { length += unused; } self.bsc.cycle_states[area] = length; self.wait = 0; values.push(self.call_read(*cycle, *width, *kind) & width_mask(*width)); self.clock += length + self.wait; } let clock = self.clock; self.bsc.read_end(area, address, clock); values } /// A cache-through, ID/OD, fetch or DMA read: a whole burst for its 1-4 bytes. fn sdram_read(&mut self, address: u32, width: u32, kind: u32, area: usize) -> u32 { let port = self.bsc.widths[area]; if width <= port { return self.sdram_burst(address, &[(address, width, kind)], area)[0]; } let step = port >> 3; let calls: Vec<(u32, u32, u32)> = (0..width / port).map(|i| (address + i * step, port, kind)).collect(); let mut value: u32 = 0; for part in self.sdram_burst(address, &calls, area) { value = ((value as u64) << port) as u32 | part; } value } /// A line fill from synchronous DRAM: one burst, in HM 8.4.1's wrap order (HM 7.5.3: /// "reading starts from the address + 4"). fn sdram_fill(&mut self, base: u32, line: u32, address: u32, kind: u32, area: usize) { let port = self.bsc.widths[area]; let per = (32 / port) as usize; let offsets: Vec = [4, 8, 12, 0].iter().map(|step| ((address & 0xC) + step) & 0xC).collect(); let step = port >> 3; let mut calls = Vec::new(); for (j, offset) in offsets.iter().enumerate() { for i in 0..per as u32 { calls.push((line | (offset + i * step), port, kind | FILL | if j == 0 { FIRST } else { 0 })); } } let values = self.sdram_burst(line, &calls, area); for (j, offset) in offsets.iter().enumerate() { let mut word: u32 = 0; for part in &values[j * per..(j + 1) * per] { word = ((word as u64) << port) as u32 | part; } self.cache.put(base | offset, 32, word); } } /// One single write (HM 7.5.5, 7.5.6). fn sdram_write(&mut self, address: u32, width: u32, value: u32, kind: u32, area: usize) { let (start, length) = self.bsc.write_cycle(area, address, self.clock); self.clock = start; self.bsc.cycle_states[area] = length; self.wait = 0; self.call_write(address, width, value, kind); self.clock += length + self.wait; let clock = self.clock; self.bsc.write_end(area, address, clock); } /// One auto-refresh cycle, at the request or once the bus is free at ``free``, /// through ``read`` with ``REFRESH`` (HM 7.5.7). ``chip.clock`` is the cycle's start /// during the call and is put back after it. fn make_refresh(&mut self, free: i64) { let (start, length) = self.bsc.refresh_cycle(self.bsc.refresh_at.max(free)); let cursor = self.clock; let area = if self.bsc.sdram[2] { 2 } else { 3 }; self.clock = start; self.bsc.cycle_states[area] = length; self.wait = 0; let (address, port) = (self.bsc.refresh_address(), self.bsc.widths[area]); self.call_read(address, port, REFRESH); let end = start + length + self.wait; self.bsc.refresh_end(end); self.bsc.refresh_served(start); self.refresh_end = end; self.clock = cursor; } /// At an access's start, the BSC wants attention: it waits for a refresh under way, /// and refresh requests due by now are made first. fn refresh_before(&mut self) { if self.clock < self.refresh_end { self.clock = self.refresh_end; } let wanted = self.clock; // fixed: a refresh longer than the period cannot run away while self.bsc.refresh_at <= wanted { let free = self.wb_end.max(self.refresh_end); self.make_refresh(free); } if self.clock < self.refresh_end { self.clock = self.refresh_end; } self.bsc_due = self.bsc.refresh_at; } /// At an access's end: a request made during it is made now, and the next access /// will wait for it (``bsc_due`` = 0 sends it through ``refresh_before``). fn refresh_after(&mut self) { if self.bsc.refresh_at <= self.clock { let clock = self.clock; self.make_refresh(clock); self.bsc_due = 0; } } /// Requests due by ``chip.clock`` while the bus is idle (a step boundary, a BSC /// register write) are made where they fell due. pub(crate) fn refresh_idle(&mut self) { while self.bsc.refresh_at <= self.clock { let free = self.wb_end.max(self.refresh_end); self.make_refresh(free); } self.bsc_due = if self.refresh_end > self.clock { 0 } else { self.bsc.refresh_at }; } // -- on-chip modules ----------------------------------------------------------------- fn onchip_read(&mut self, address: u32, width: u32) -> u32 { if address < 0xFFFFFE00 { return 0; // reserved I/O space (HM table 7.3); the SDRAM mode space reads nothing } if (width == 8 && address >= 0xFFFFFF00) || (width == 32 && address < 0xFFFFFF00) { self.address_error = true; // HM table 4.6: wrong size for that half return 0; } if self.observe { self.bus.observe(address, width, DATA); } match self.onchip[(address - 0xFFFFFE00) as usize] { None => 0, Some(module) => self.read_onchip(module, address, width), } } fn onchip_write(&mut self, address: u32, width: u32, value: u32) { if address < 0xFFFFFE00 { return; // reserved; the SDRAM mode-register space is not modelled (BSC note) } if (width == 8 && address >= 0xFFFFFF00) || (width == 32 && address < 0xFFFFFF00) { self.address_error = true; return; } if self.observe { self.bus.observe(address, width, WRITE); } if let Some(module) = self.onchip[(address - 0xFFFFFE00) as usize] { self.write_onchip(module, address, width, value); } } // -- DMA accesses (the DMAC's side of the internal bus) ------------------------------- /// Whether a DMAC access is an address error (DOC: HM table 4.6, "CPU or DMAC"). /// /// A word at an odd address, a longword off a longword boundary (a 16-byte unit is /// four longword accesses, the table's note 2), a byte at H'FFFFFF00-H'FFFFFFFF, a /// longword at H'FFFFFE00-H'FFFFFEFF. The table's other data rows name PC-relative /// addressing and TAS.B, which only the CPU makes. pub(crate) fn dma_address_fault(address: u32, width: u32) -> bool { if address & ((width >> 3) - 1) != 0 { return true; } if address >= 0xFFFFFE00 { return (width == 8 && address >= 0xFFFFFF00) || (width == 32 && address < 0xFFFFFF00); } false } pub(crate) fn dma_read(&mut self, address: u32, width: u32, kind: u32) -> u32 { let space = address >> 29; if space == 0 || space == 1 { return self.bus_read(address, width, kind); // DMA never uses the cache } if space == 7 && address >= 0xFFFFFE00 { return match self.onchip[(address - 0xFFFFFE00) as usize] { None => 0, Some(module) => self.read_onchip(module, address, width), }; } if space == 6 { return self.cache.get(address & 0xFFF, width); } 0 } /// A 16-byte unit's four longwords. From synchronous DRAM they are one burst in /// address order (HM 7.5.3: "the access order follows the address order in 16-byte /// data transfers by the DMAC"). pub(crate) fn dma_read_unit(&mut self, address: u32, kind: u32) -> Vec { if (address >> 29 == 0 || address >> 29 == 1) && self.bsc.sdram[((address >> 25) & 3) as usize] { if self.clock < self.wb_end { self.clock = self.wb_end; } if self.clock >= self.bsc_due { self.refresh_before(); } let address = address & 0x1FFFFFFF; let area = ((address >> 25) & 3) as usize; let port = self.bsc.widths[area]; let per = (32 / port) as usize; let calls: Vec<(u32, u32, u32)> = (0..4 * per as u32).map(|i| (address + i * (port >> 3), port, kind)).collect(); let values = self.sdram_burst(address, &calls, area); if self.clock >= self.bsc_due { self.refresh_after(); } let mut words = Vec::with_capacity(4); for j in 0..4 { let mut word: u32 = 0; for part in &values[j * per..(j + 1) * per] { word = ((word as u64) << port) as u32 | part; } words.push(word); } return words; } (0..4).map(|i| self.dma_read(address.wrapping_add(4 * i), 32, kind)).collect() } pub(crate) fn dma_write(&mut self, address: u32, width: u32, value: u32, kind: u32) { let space = address >> 29; if space == 0 || space == 1 { // No snooping: DMA writes do not update the cache (HM 7.11.2, 8.5.2). Not // buffered here: the DMAC's cycles hold the bus until they end (rung 5). if self.clock < self.wb_end { self.clock = self.wb_end; } self.write_cycles(address, width, value, kind); self.wb_end = self.clock; } else if space == 7 && address >= 0xFFFFFE00 { if let Some(module) = self.onchip[(address - 0xFFFFFE00) as usize] { self.write_onchip(module, address, width, value); } } else if space == 6 { self.cache.put(address & 0xFFF, width, value); } } /// For tools: the module that answers an on-chip address (``chip._onchip``). pub fn onchip_module(&self, address: u32) -> Option { self.module_at(address) } }