// SPDX-License-Identifier: MIT //! The expansion sockets: the reference's `tests/test_sockets.py`. Every socket reaches a //! test-only device (tests/support/fake_devices.rs), and with nothing plugged in the //! board is what it was. //! //! The fakes model no add-on. What is checked is the board's side of the contract: which //! accesses reach a device, from which bus master, at which master clock, and the events //! and records it is handed. The reference's `test_a_further_source_keeps_its_leftovers_ //! through_a_pickle` has no counterpart: Rust has no pickle, and a state here does not //! hold a device's side (src/state.rs, `Config`). #[path = "support/fake_devices.rs"] mod fake_devices; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; use fake_devices::{FakeAudio, FakeDevice, FakePicture, FakeVideo, Shared}; use megadrive_rust::board::{Low, PORT, SLOT}; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::machine::{machine, M68K_DIVIDER}; use megadrive_rust::render::LEVELS; use megadrive_rust::sockets::{Reset, M68K, Z80}; use megadrive_rust::system::{ClockedDevice, System}; use megadrive_rust::vdp::HName; const STACK: u32 = 0x00FFFE00; const CODE: usize = 0x200; /// A ROM: the two reset vectors, a header, and `code` (hex) at `at`. fn image_at(code: &str, at: usize) -> Vec { let mut rom = vec![0u8; 0x10000]; rom[0..4].copy_from_slice(&STACK.to_be_bytes()); rom[4..8].copy_from_slice(&(at as u32).to_be_bytes()); rom[0x100..0x110].copy_from_slice(b"SEGA GENESIS "); let program: Vec = (0..code.len()) .step_by(2) .map(|i| u8::from_str_radix(&code[i..i + 2], 16).unwrap()) .collect(); rom[at..at + program.len()].copy_from_slice(&program); rom } fn image(code: &str) -> Vec { image_at(code, CODE) } fn cartridge(code: &str) -> Cartridge { Cartridge::new(image(code), "rom", 0, "") } fn run(system: &mut System, instructions: usize) { for _ in 0..instructions { system.step().unwrap(); } } fn ram(system: &mut System, address: u32) -> u16 { let ram = &system.board().dev.ram; u16::from(ram[(address & 0xFFFF) as usize]) << 8 | u16::from(ram[((address + 1) & 0xFFFF) as usize]) } const LOOP: &str = "60fe"; // bra.s * // -- nothing plugged in --------------------------------------------------------------- #[test] fn nothing_attached_is_the_board_as_it_was() { let mut system = System::new( machine("genesis").unwrap(), Some(cartridge(LOOP)), None, None, ); assert!(system.clocked.is_empty() && system.audio_sources.is_empty()); let board = system.board(); assert!(board.dev.slot.is_none() && board.dev.port.is_none() && board.dev.devices.is_empty()); assert!(board.dev.pages.is_none()); // the paths that look at claims see None at once assert_eq!(board.dev.low, Low::Slot); assert!(board.dev.slot_cartridge && board.dev.cartridge_present()); assert!(board.vdp.video_timing.is_none() && board.vdp.renderer.picture.is_none()); assert!(board.dev.io.version & 0x20 != 0); // no expansion unit // move.w $840000,d0: the 32X area without a 32X locks up. let mut system = System::new( machine("genesis").unwrap(), Some(cartridge("303900840000")), None, None, ); assert!(system.step().unwrap_err().0.contains("32X area")); // ... and so does the Z80's bank window there. let mut system = System::new( machine("genesis").unwrap(), Some(cartridge(LOOP)), None, None, ); let board = system.board(); board.dev.arbiter_enabled = false; board.dev.bank = 0x840000; z80_rust::Bus::read_byte(board, 0x8000); assert!(board.dev.lockup.as_ref().unwrap().0.contains("32X area")); } #[test] fn an_empty_slot_is_a_state_and_still_reads_ff() { let mut system = System::new(machine("genesis").unwrap(), None, None, None); let dev = &mut system.board().dev; assert!(!dev.slot_cartridge && !dev.cartridge_present()); assert_eq!(dev.cart_read_word(0x1000), 0xFFFF); // as the board always read it } #[test] fn claims_are_whole_pages_on_a_sockets_bus() { for ranges in [ (0xA15180, 0xA15200), (0xA11100, 0xA11200), (0xE00000, 0xE00100), (0xA10000, 0xA10100), (0xA14000, 0xA14100), ] { let (device, _) = FakeDevice::new(vec![ranges]); let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { System::with_sockets( machine("genesis").unwrap(), None, None, None, None, Some(Box::new(device)), ) })); assert!(refused.is_err(), "{ranges:X?}"); } } // -- socket 1: the slot, and socket 3: one decode --------------------------------------- const SLOT_PROGRAM: &str = concat!( "303900a15100", // move.w $A15100,d0 -- the slot device's register "33c000ff0000", // move.w d0,$FF0000 "33fc123400a15102", // move.w #$1234,$A15102 "123900a15103", // move.b $A15103,d1 -- the byte just written, back "13c100ff0002", // move.b d1,$FF0002 "343900840000", // move.w $840000,d2 -- the 32X area, claimed "33c200ff0004", // move.w d2,$FF0004 "303900000200", // move.w $000200,d0 -- the held cartridge, unclaimed "33c000ff0006", // move.w d0,$FF0006 "4e70", // reset "60fe", // bra.s * ); fn slot_system_with(code: &str, port: Option, tmss: bool) -> (System, Shared) { let (device, s) = FakeDevice::slot(Some(cartridge(code))); let name = if tmss { "genesis-tmss" } else { "genesis" }; let mut system = System::with_sockets( machine(name).unwrap(), None, None, None, Some(Box::new(device)), port.map(|p| Box::new(p) as _), ); system.board().dev.fm.enabled = false; (system, s) } fn slot_system(code: &str) -> (System, Shared) { slot_system_with(code, None, false) } #[test] fn a_slot_device_answers_its_claims_and_its_cartridge_the_rest() { let (mut system, s) = slot_system(SLOT_PROGRAM); let dev = &system.board().dev; assert!(dev.slot.is_some() && dev.slot_cartridge); assert_eq!(dev.low, Low::Slot); // nothing claimed at $000000: no decode assert!(dev.cartridge_present() && dev.io.version & 0x20 != 0); run(&mut system, 10); let log = s.lock().unwrap(); assert_eq!(ram(&mut system, 0xFF0000), log.value(0xA15100)); assert_eq!(log.written[&0xA15102], 0x1234); assert_eq!(system.board().dev.ram[2], 0x34); // the byte read back from the device assert_eq!(ram(&mut system, 0xFF0004), log.value(0x840000)); assert_eq!(ram(&mut system, 0xFF0006), 0x3039); // the cartridge's own first word let kinds: Vec<(&str, u32, u8)> = log.log.iter().map(|e| (e.0, e.1, e.3)).collect(); assert_eq!( kinds, [ ("rw", 0xA15100, M68K), ("ww", 0xA15102, M68K), ("rb", 0xA15103, M68K), ("rw", 0x840000, M68K) ] ); } /// Socket 4: the clock handed over is the access's own, past the instruction's start, and /// the device has run to it before answering. Socket 5: after each instruction it is run /// to the 68000's. #[test] fn an_access_carries_its_clock_and_catches_the_device_up_inside_it() { let (mut system, s) = slot_system(SLOT_PROGRAM); system.step().unwrap(); // move.w $A15100,d0 let log = s.lock().unwrap(); let (_kind, _address, mclk, _master, step_start, clock) = log.log[0]; assert!(mclk > step_start && clock == mclk); // Two bus cycles of 4 clocks before it (the prefetch: the opcode and the first // extension word were already in), then the read. assert_eq!(mclk, step_start + 8 * M68K_DIVIDER); assert_eq!(*log.catch_ups.last().unwrap(), system.mclk()); assert_eq!(log.clock, system.mclk()); } #[test] fn a_device_holds_the_68000_on_its_clock_edge() { let mut elapsed = Vec::new(); for hold in [0, 10] { let (mut system, s) = slot_system(SLOT_PROGRAM); s.lock().unwrap().hold_mclk = hold; elapsed.push(system.step().unwrap()); } assert_eq!(elapsed[1] - elapsed[0], 2 * M68K_DIVIDER); // 10 MCLK, rounded up to 14 } #[test] fn the_z80_reaches_a_claim_through_its_bank_window() { let (mut system, s) = slot_system(SLOT_PROGRAM); let board = system.board(); board.dev.arbiter_enabled = false; board.dev.bank = 0x840000; let value = s.lock().unwrap().value(0x840000); assert_eq!(z80_rust::Bus::read_byte(board, 0x8000), (value >> 8) as u8); z80_rust::Bus::write_byte(board, 0x8003, 0x42); { let log = s.lock().unwrap(); assert_eq!( (log.log[0].0, log.log[0].3, log.log[0].1), ("rb", Z80, 0x840000) ); assert_eq!((log.log[1].0, log.log[1].1), ("wb", 0x840003)); assert_eq!(log.log[1].3, Z80); assert_eq!(log.written[&0x840002], 0x42); } assert_eq!(board.dev.z80_peek(0x8000), 0x5A); assert_eq!(s.lock().unwrap().peeks, [0x840000]); } #[test] fn the_schedulers_probe_peeks_through_the_same_decode() { let (mut system, s) = slot_system(SLOT_PROGRAM); system.board().dev.bank = 0x800000; system.md().z80.pc = 0; system.board().dev.z80_ram[0..3].copy_from_slice(&[0x3A, 0x00, 0x80]); // ld a,($8000) let reads = s.lock().unwrap().log.len(); system.md().z80_probe(); let log = s.lock().unwrap(); assert_eq!(log.peeks, [0x800000]); assert_eq!(log.log.len(), reads); // no side effects } const DMA_PROGRAM: &str = concat!( "33fc811400c00004", // move.w #$8114,$C00004 -- DMA on, mode 5 "33fc8f0200c00004", // move.w #$8F02,$C00004 -- increment 2 "33fc930200c00004", // move.w #$9302,$C00004 -- two words "33fc940000c00004", // move.w #$9400,$C00004 "33fc950000c00004", // move.w #$9500,$C00004 -- from $840000 "33fc960000c00004", // move.w #$9600,$C00004 "33fc974200c00004", // move.w #$9742,$C00004 "23fc4000008000c00004", // move.l #$40000080,$C00004 -- to VRAM 0, DMA "60fe", // bra.s * ); #[test] fn vdp_dma_reaches_a_claim_with_a_start_notice() { let (mut system, s) = slot_system(DMA_PROGRAM); system.run_frame().unwrap(); let log = s.lock().unwrap(); assert_eq!(log.dma_starts.len(), 1); let (started, bus) = log.dma_starts[0]; assert_eq!(bus, 0x60FE); // the 68000's prefetch: the loop it runs next let addresses: Vec = log.dma_reads.iter().map(|r| r.0).collect(); assert_eq!(addresses, [0x840000, 0x840002]); assert!(log.dma_reads.iter().all(|r| r.1 > started)); assert!(log.dma_reads[0].1 < log.dma_reads[1].1); assert!(log.log.is_empty()); // DMA has its own entry } // -- socket 2: the expansion port ------------------------------------------------------- fn port_bios() -> Vec { image(concat!( "33fc000100a12000", // move.w #1,$A12000 -- the port's gate array "103900a10001", // move.b $A10001,d0 -- the version register "13c000ff0000", // move.b d0,$FF0000 "60fe", // bra.s * )) } #[test] fn a_port_device_boots_with_no_cartridge() { let (device, s) = FakeDevice::port(port_bios()); let mut system = System::with_sockets( machine("genesis").unwrap(), None, None, None, None, Some(Box::new(device)), ); assert!(!system.board().dev.cartridge_present() && s.lock().unwrap().base == 0); assert_eq!(system.board().dev.low, Low::Decode); // its claims at $000000 run(&mut system, 4); assert_eq!(system.board().dev.ram[0] & 0x20, 0); // /DISK: an expansion unit is there let log = s.lock().unwrap(); assert_eq!(log.written[&0xA12000], 1); let fetched: Vec = log .log .iter() .filter(|e| e.0 == "rw" && e.1 < 8) .map(|e| e.1) .collect(); assert_eq!(fetched, [0, 2, 4, 6]); // the 68000's reset vectors came from the port } #[test] fn a_port_device_moves_to_400000_with_a_cartridge() { let (device, s) = FakeDevice::port(port_bios()); // move.w $400000,d0; move.w d0,$FF0000; bra.s * let cart = cartridge(&format!("303900400000{}{LOOP}", "33c000ff0000")); let mut system = System::with_sockets( machine("genesis").unwrap(), Some(cart), None, None, None, Some(Box::new(device)), ); let dev = &system.board().dev; assert!(dev.cartridge_present() && s.lock().unwrap().base == 0x400000); assert_eq!(dev.low, Low::Slot); assert_eq!(dev.io.version & 0x20, 0); run(&mut system, 3); assert_eq!(ram(&mut system, 0xFF0000), 0x00FF); // the BIOS's first word, at $400000 } #[test] fn the_tmss_rom_sits_above_the_port() { let (device, s) = FakeDevice::port(port_bios()); let mut system = System::with_sockets( machine("genesis-tmss").unwrap(), None, None, Some(image(LOOP)), None, Some(Box::new(device)), ); assert_eq!(system.board().dev.low, Low::Boot); assert!(!s.lock().unwrap().log.iter().any(|e| e.1 < 8)); // vectors: the boot ROM's system.board().dev.tmss_select(true); assert_eq!(system.board().dev.low, Low::Decode); system.board().dev.tmss_select(false); assert_eq!(system.board().dev.low, Low::Boot); } #[test] fn the_port_wins_a_page_both_claim() { let (port, _) = FakeDevice::new(vec![(0xA15100, 0xA15200)]); let (mut system, _) = slot_system_with(SLOT_PROGRAM, Some(port), false); let pages = system.board().dev.pages.as_ref().unwrap(); assert_eq!((pages[0xA151], pages[0xA152]), (PORT, SLOT)); } // -- socket 9: the three resets ----------------------------------------------------------- #[test] fn the_three_resets_reach_the_devices() { let (mut system, s) = slot_system(SLOT_PROGRAM); assert_eq!(s.lock().unwrap().resets, [(Reset::PowerOn, 0)]); run(&mut system, 10); // ... ends with RESET let (kind, at) = s.lock().unwrap().resets[1]; assert!(kind == Reset::Instruction && 0 < at && at <= system.mclk()); system.press_reset(None); let reset_at = system.md().reset_at; assert_eq!(s.lock().unwrap().resets[2], (Reset::Button, reset_at)); } // -- socket 5: clock domains ------------------------------------------------------------ #[test] fn clocked_devices_follow_the_68000() { let (mut system, s) = slot_system(LOOP); assert!(matches!(system.clocked[..], [ClockedDevice::Socket(SLOT)])); for _ in 0..50 { system.step().unwrap(); assert_eq!(s.lock().unwrap().clock, system.mclk()); } } // -- socket 8: sound ------------------------------------------------------------------------ fn audio(source: Option) -> Vec<(i32, i32)> { let mut system = System::new( machine("genesis").unwrap(), Some(cartridge(LOOP)), None, None, ); if let Some(source) = source { system.audio_sources.push(Box::new(source)); } let mut out = Vec::new(); for _ in 0..3 { system.run_frame().unwrap(); out.extend(system.take_audio()); } out } #[test] fn a_further_source_is_mixed_at_its_own_rate() { let plain = audio(None); let (silent, _) = FakeAudio::new(32_552.08, 0.0, (1000.0, -1000.0)); assert_eq!(audio(Some(silent)), plain); // no gain: nothing let (source, s) = FakeAudio::new(32_552.08, 1.0, (1000.0, -1000.0)); let mixed = audio(Some(source)); assert!(mixed.len() == plain.len() && mixed != plain); assert_eq!(s.lock().unwrap().calls.len(), 3); let late: Vec = mixed[mixed.len() - 200..] .iter() .zip(&plain[plain.len() - 200..]) .map(|(m, p)| m.0 - p.0) .collect(); assert!(late.iter().all(|&value| value > 0)); // the level comes through, left positive let (source, s) = FakeAudio::new(32_552.08, 1.0, (1000.0, -1000.0)); s.lock().unwrap().rate = 22_050.0; // a rate may change between calls assert!(!audio(Some(source)).is_empty()); } // -- socket 6: video timing ----------------------------------------------------------------- #[test] fn every_line_is_published_with_its_edges() { let mut system = System::new( machine("genesis").unwrap(), Some(cartridge(LOOP)), None, None, ); let lines = Arc::new(Mutex::new(Vec::new())); system.attach_video_timing(Box::new(FakeVideo { lines: lines.clone(), })); system.run_frame().unwrap(); let first = lines.lock().unwrap().len(); system.run_frame().unwrap(); let lines = lines.lock().unwrap(); let frame = &lines[first..]; assert_eq!(frame.len(), 262); // NTSC V28, no mode change for pair in frame.windows(2) { assert_eq!(pair[1].start, pair[0].start + pair[0].length); } for line in frame { assert!(line.start <= line.hblank_set && line.hblank_set < line.start + line.length); assert!(line.start <= line.hblank_clear && line.hblank_clear < line.start + line.length); assert!(line.hmode == HName::H32 && !line.pal && line.pixels.len() == 342); } assert_eq!(frame.iter().filter(|line| line.vsync).count(), 1); assert!(frame.iter().any(|line| line.vblank) && !frame[0].vblank); } // -- socket 7: the picture ------------------------------------------------------------------ fn picture_system( replace: HashMap, ) -> ( System, Arc>>, ) { let mut system = System::new( machine("genesis").unwrap(), Some(cartridge(LOOP)), None, None, ); system.board().dev.fm.enabled = false; system.run_frame().unwrap(); let vdp = &mut system.board().vdp; vdp.s.registers[1] = 0x44; // display on, mode 5 vdp.s.registers[2] = 0x30; // plane A at $C000 vdp.s.registers[4] = 0x07; // plane B at $E000 // Plane A's first cell: tile $101 (the name word reads the same either byte order), // every pixel colour 1, which is white. vdp.s.vram[0xC000] = 0x01; vdp.s.vram[0xC001] = 0x01; vdp.s.vram[0x2020..0x2040].fill(0x11); vdp.s.cram[1] = 0x0EEE; vdp.renderer.cram_dirty = true; let lines = Arc::new(Mutex::new(Vec::new())); system.attach_picture(Box::new(FakePicture { lines: lines.clone(), replace, })); system.run_frame().unwrap(); system.run_frame().unwrap(); (system, lines) } #[test] fn each_finished_line_is_handed_over_with_ys_and_shade() { let (mut system, lines) = picture_system(HashMap::new()); let lines = lines.lock().unwrap(); let line = lines.iter().filter(|line| line.row == 0).last().unwrap(); assert!(line.hmode == HName::H32 && line.width == 256 && line.pixel_mclk == 10); assert!(line.output_delay == 24 && line.display_at > line.start); let white = LEVELS[0][7] << 16 | LEVELS[0][7] << 8 | LEVELS[0][7]; assert_eq!(line.rgb[..8], [white; 8]); assert_eq!(line.rgb[8], 0); assert_eq!(line.ys[..8], [0; 8]); assert_eq!(line.ys[8..], [1; 248]); assert_eq!(line.shade, [0; 256]); let vdp = &system.board().vdp; assert_eq!(line.rgb, vdp.renderer.frame_rgb(&vdp.s)[0]); // what leaves without a change assert_eq!( lines .iter() .map(|line| line.row) .collect::>() .len(), 224 ); } #[test] fn the_line_the_device_returns_leaves_the_console() { let (mut system, _) = picture_system(HashMap::from([(0, 0x123456)])); let vdp = &system.board().vdp; let rows = vdp.renderer.frame_rgb(&vdp.s); assert_eq!(rows[0], vec![0x123456; 320]); // wider than the H32 line: the device's own assert_eq!(rows[1].len(), 256); }