# Spec: DMA/HDMA hardware-glitch family, CPU-measured, SRAM-recorded Target console: Super Famicom, 5A22 **version 1** (`$4210 & $0F == 1`, "S-CPU", 5A22-01), PPU1 v1, PPU2 v1, NTSC. Undisbeliever calls this console "Model-1 1/1/1". Sources read (zlib, Marcus Rowe), paths relative to `tests/test_roms/undisbeliever-src/src/`: - `hardware-glitch-tests/scpu-a-dma-bug/` (dma-test.inc + 10 variants) - `hardware-glitch-tests/quick-model-1-dma-crash/` (3 includes + 8 variants) - `hardware-glitch-tests/dma-ends-at-hdma-start/` (2 tests) - `hardware-tests/hdma-timing-demonstration.asm`, `hdmaen_latch_test.asm`, `hdmaen_latch_test_2.asm` - shared: `reset_handler.inc`, `break_handler.inc`, `wait.inc`, `_common/snes_header.inc` Background read: `snes-python/docs/{timing,undocumented-behavior,validation}.md`, `reference/docs/anomie_timing.txt`, `reference/snesdev-wiki/{Errata,Version_differences,DMA_registers}.wiki`, ares 9408cb4 (ISC) `sfc/cpu/{timing,dma,cpu}.cpp`. (A GPL emulator's DMA source was also read when this spec was first written; every statement resting on it below has been struck, 2026-11-19.) --- ## 0. Facts every test depends on ### 0.1 Which bug belongs to which CPU version (important for a v1 console) - **v1 bug (your console): the DMA/HDMA crash.** `Version_differences.wiki`: "S-CPU (5A22-01), RDNMI version 1. Known bugs: Crashes if a DMA finishes just before HDMA happens". `Errata.wiki:96`: "On version 1 of the 5A22 chip ("S-CPU"), the chip can crash if DMA finishes right before HDMA happens." - **v2 bug (not your console): the "S-CPU-A DMA bug".** `Errata.wiki:97-99`: "On version 2 of the 5A22 chip ("S-CPU-A"), a recent HDMA transfer to/from INIDISP (... BBADn is set to zero $00) can make a DMA transfer fail. Nothing will happen and the DMA size registers (DASnL, DASnH) will be unchanged ... S-CPU (the first version), S-CPU-B and the 1-CHIP SNES are not affected by this bug." Undisbeliever agrees on the numbering: "S-CPU-A (CPU version 2)" (`dma-ends-hdma-start-1-ch.asm:6`). - So on your console the S-CPU-A test is a **negative control**: expected 0 failures. A non-zero count would be news. - **snes-python docs have this backwards.** `docs/undocumented-behavior.md:19` (Q9) says "CPU version 1 DMA failure after an HDMA to `$2100`", and `docs/timing.md:128` says "CPU version 1's 'DMA fails if an HDMA to `$2100` happened on the previous line'". Both should say version 2 (S-CPU-A). The v1 behaviour is the crash. Q9 should be split: Q9a is the v2 DMA failure, Q9b is the v1 DMA-end/HDMA-start crash. ### 0.2 Timing constants (each one is a model claim that these tests can check) - Master clock (mc) per NTSC line: 1364 (1360 for line 240 of every other frame when interlace is off). One dot is 4 mc, except dots 323 and 327, which are 6 mc. H counter runs 0..339. - Per-line HDMA starts at **1104 mc** in ares 9408cb4 (ISC) `sfc/cpu/timing.cpp` `CPU::scanline()` (the per-line HDMA position, set on every visible line), which is dot 276. anomie says "dot 278 ... (or just after, the current CPU cycle is completed before pausing)" (`anomie_timing.txt:265-266`). The tests below report raw latched H and do not assume either value. - HDMA init at V=0. ares 9408cb4 `sfc/cpu/timing.cpp` `CPU::scanline()` (at V=0) puts it at 12 + 8 minus the CPU clock's phase mod 8 on version 1 (12 plus the phase on version 2), so on v1 it is 13..20 mc into line 0 (about dot 3-5). anomie: "about V=0 H=6 ... ~18 master cycles, plus 8 ... per direct ... 24 ... per indirect" (`anomie_timing.txt:254-257`). - DRAM refresh on v1 is at **530 mc** (dot 132.5), 40 mc, every line (ares 9408cb4 `sfc/cpu/cpu.cpp` `CPU::power()`; the 40 mc is five 8-mc steps in `sfc/cpu/timing.cpp` `CPU::step()`). In ares v2 uses 538 - jitter (`CPU::scanline()`). Keep every measurement window clear of it or include it identically in every config. - **8-clock DMA grid.** DMA and HDMA start snaps to `8 - (cpuclock & 7)` (ares 9408cb4 `sfc/cpu/timing.cpp` `CPU::dmaEdge()`). Because 1364 ≡ 4 (mod 8), **the grid phase relative to H flips by 4 mc on every line**. The short line (1360) flips it again every other frame. So line parity and frame parity are hidden variables of every DMA-vs-HDMA alignment test. Record V parity and the `$213F` bit 7 field flag with every sample. - IRQ: "If H≠0, $4211 bit 7 gets set 14+H*4 master cycles after dot 0.0" (`anomie_timing.txt:118-120`). - Latching H/V: read `$2137` (SLHV). Then read `$213F` once to reset the flip-flop, then `$213C` twice (OPHCT lo, hi bit 0) and `$213D` twice (OPVCT). The latch only works with **WRIO `$4201` bit 7 = 1**, which is `$FF` after reset. `break_handler.inc:104-108` sets it explicitly for this reason. - Hidden HDMA state that the CPU can read: `A2An` ($43n8/9), `NLTRn` ($43nA), `DASn` ($43n5/6, the indirect address or the DMA byte counter), `A1Tn` (the DMA current address). The `DoTransfer` flag is not readable. It is cleared for all channels at V=0 (ares 9408cb4 `sfc/cpu/dma.cpp` `Channel::hdmaReset()`, called from `sfc/cpu/timing.cpp` `CPU::step()` at the init point) and set by init only if `HDMAEN≠0` at init. A transfer shows up as an `A2An` advance, so the flag can be inferred. - **Interrupt vectors are 16-bit, so every handler executes in bank $00, which is always SlowROM** (8 mc per ROM byte), even in undisbeliever's FastROM builds. `_common/snes_header.inc:130-145` points the vectors at `code()` labels in `$80xxxx`, but the CPU fetches from `$00:xxxx`. Each handler runs slow until `rti` restores PBR=$80. This matters for every IRQ-timed test below. ### 0.3 SRAM-recording conventions used below - "H" is the 9-bit OPHCT value and "V" is the 9-bit OPVCT value. A packed "H8" byte is `H - 192` (range 192..447 covers the windows used here). Store 0xFF when out of range. - Each record block gets a 16-bit additive checksum (or a CRC). A wild CPU in the crash tests could scribble on SRAM. Keep a duplicate of the family header. - Before each test, write "started(test_id, attempt_id)". After it, write "finished(test_id, attempt_id, checksum)". Make the finished marker a magic value plus the ids plus a checksum, so a wild CPU is unlikely to forge it. --- ## T1. S-CPU-A DMA bug (scpu-a-dma-bug/*, 10 ROMs) ### 1. What it tests and exact sequence Header: "Near has reported that a DMA transfer can fail if a HDMA transfer with a B-Bus address of $2100 occurs on the previous scanline." (`dma-test.inc:4-5`) Build: LoROM, `ROM_SPEED = fast` (MEMSEL=1), code at `$80:8000` (`dma-test.inc:55-69`). IRQ handler in bank $00, slow (see 0.2). Setup (`DoTest`, `dma-test.inc:306-356`): - WMADD (`$2181-3`) = `testStatus` (`$7F:xxxx`, 896 = 28×32 bytes). The byte before the end and the byte after the end are pre-set to sentinel `$42` (`l.320-323`). - MDMA channel m: `DMAP = $08` (A→B, fixed, 1 reg), `BBAD = $80` (WMDATA), `A1T = SuccessByte`, `A1B = $00` (bank $00 ROM, value 1), `DAS = 1` (`l.329-337`). - Wait for vblank. `SetupHdma`: HDMA channel h, `DMAP = {hdma_dmap}` (default `$00`, direct, 1 reg), `BBAD = {hdma_bbad}` (default `$00`, INIDISP), table in ROM bank $80, `HDMAEN = 1< WMDATA ldx.w DASmL ; X is 16-bit: reads DASL+DASH beq ok [fix2 only: sta.w MDMAEN again; ldx.w DASmL; beq ok] lda #2 ; sta.w WMDATA ; CPU writes the "failure tile" byte so WRAM stays aligned inc errorCount ok: lda #(1<= 3" (`-strange.asm:43-52`) | | ch0 | MDMA ch5, HDMA ch0 | as bug-2 | "I can also trigger this bug with MDMA ch 5, HDMA ch 0" (`-ch0.asm:28`) | | fix | $01/$FF (2 regs: $21FF,$2100) | 128 × (2, 0, sv) | "BBAD is not 0x00 and the bug is no-longer triggered" (`-fix.asm:31-32`) | | fix2 | as bug-2 + retry | | "If a DMA transfer fails, retry it once before marking it red." (`-fix2.asm:31`) | | two-regs | $01/$00 ($2100,$2101) | 128 × (2, sv, 1) | writes OBSEL=1 too (`-two-regs.asm:31-33`) | Also: "The bug also happens in h-blank (irqXpos = 205)" (`dma-test.inc:79`). ### 2. Original reporting and recorded console results - Visual (`dma-test.inc:20-28`): green squares with a scanline effect = no failure. Red squares and no scanline effect = at least one failure, after which the test stops. Half brightness = break handler ran. - Console results recorded in the sources: only for a **2/1/3** console (CPU v2): the per-table rates quoted above, and the `strange` table never failing in 3 hours. Nothing is recorded for a v1 console. The wiki (0.1) says v1 is unaffected. - Emulators run as closed boxes (OBSERVED, `snes-python/docs/validation.md`): Mesen2 and MAME both show green. MAME does not draw the INIDISP scanline effect. ### 3. CPU-measured version The original already measures with the CPU (the `DASm` readback), so keep its loop **instruction for instruction**: same banks, and the same IRQ handler bytes in bank $00. Change only the bookkeeping: - Merge fix2 into every config: always retry once and count both outcomes. That leaves **9 configs**: bug-1, bug-2, bug-3, bug-5, r2, strange, ch0, fix, two-regs. - Run a fixed number of passes per config instead of looping until failure: 16 passes = 14,336 tests, about 64 frames (≈1.1 s). The whole test takes about 10 s. - Failure path only (it does not perturb the success path): right after the first `ldx DASmL` reads non-zero, save X (the DAS value), then `lda $2137` and read OPVCT. That gives the V of the failing line, which identifies the HDMA table phase. - After each pass, scan the 896-byte buffer and count bytes ≠ SUCCESS (1). Check both sentinels. - HDMA sanity (replaces the "scanline effect"): in the first vblank of each config, read `A2Ah` and `NLTRh` and compare with the expected end-of-table position. This proves the HDMA to `$2100` really ran on all 225 lines. - One timing sample per config: a separate one-pass "calibration" loop identical to the real one plus `lda.w $2137` immediately after `ldx.w DASmL`. Store the latched H (where the DMA ends). Do not include this extra instruction in the counted passes. SRAM per config (28 bytes): `passes u8, tests u16, fail_first u16, fail_retry u16, buf_nonsuccess u16, sentinel_errs u8, first_fail_DAS u16, first_4_fail_V 4×u16, A2Ah_vbl u16, NLTRh_vbl u8, dma_end_H u16, rsv 3`. 9 configs × 28 = **252 bytes**. Expected on v1: every fail counter is 0, `buf_nonsuccess` = 0, and A2A/NLTR match. ### 5. Traps - Alignment estimate (mine, unverified; check it with the calibration H). IRQ flag at 14+20×4 = 94 mc. Wake plus native IRQ entry (4 stack writes to WRAM, 8 mc each; 2 vector reads from bank $00, 8 mc each) puts the handler start near 160 mc. The handler in slow ROM (`sep` 22, `pha` 22, `lda.l` 38, `pla` 28, `rti` 52) adds about 162 mc. The fast-ROM main path to `sta MDMAEN` adds about 132 mc. So MDMAEN is written at about 454 mc (dot ≈113), and the 1-byte DMA ends at about dot 122, roughly 40 mc before the v1 DRAM refresh at 530 mc. The bug might depend on this proximity, so **keep the handler in bank $00 slow ROM and the main loop FastROM in bank $80 with MEMSEL=1.** Otherwise the DMA moves relative to refresh. - `ldx.w DASmL` must be the instruction right after `sta MDMAEN` (16-bit X). - `stz HDMAEN` / re-enable happens mid-line, before dot 276. If you add code to the success path and push the re-enable past 1104 mc, HDMA skips that line and the "previous line had HDMA" premise breaks. - The `irqXpos = 205` variant moves the DMA to about dot 250-330, close to the per-line HDMA point. **On a v1 console that approaches the crash condition (T6).** Run it only inside the crash-guarded section, or not at all. - The HDMA payload writes INIDISP 15/8, both display-on values. That cancels force blank, so this test cannot run in force blank. --- ## T2. HDMA timing demonstration (hdma-timing-demonstration.asm) ### 1. What it does It is a picture generator for the SNESdev wiki diagram, viewed in Mesen's event viewer: "Create a read breakpoint for $80A000 to $80A0FF ... Enable Mark on Event Viewer" (`l.3-8`). "Using 2 HDMA channels to show that the line-counter is decremented/read after the HDMA transfers are completed." (`l.72-73`) - ch0: `DMAP=$00` → CGADD, `CgaddTable` = 11 × (16 lines, data 0) + `$00` (`l.125-132`). - ch1: `DMAP=$02` (write twice) → CGDATA, `CgdataTable` = 11 × (16 lines, grey 31-3i) (`l.136-143`), **with no terminator**. It relies on the zero padding after the table. - Tables in bank $80 at `$A000`. The wait loop `lda HVBJOY; bmi -` (`l.100-104`) is commented "Wait until VBlank starts" but actually waits until vblank *ends*. HDMA is therefore enabled mid-frame on the first frame, after which the CPU sits in `wai` forever with no interrupts enabled. ### 2. Reporting None. The output is a grey staircase plus Mesen event-viewer marks. No console result is recorded. ### 3. CPU-measured version: two probes **T2a. Transfer-before-reload order probe.** This measures the demonstration's claim with the CPU. It uses a B→A (read) HDMA that writes into another channel's next header, in WRAM: - Set MPYL = M via `M7A = M (write lo, hi = 0)` and `M7B = 1`. Use M = `$05`. - Table bytes in WRAM at `T` (`$7E:2xxx`): `T+0 = $01` (ch0 header, 1 line); `T+1 = $01` (ch0 data, and ch1's header); `T+2 = $03` (ch0's next header "old value", and ch1's data slot); `T+3 = $00`; `T+4.. = $00`. - ch0: `DMAP=$00` (A→B, direct, 1 reg), `BBAD=$FF` (writes to the unused `$21FF`), `A1T=T`, `A1B=$7E`. - ch1: `DMAP=$80` (B→A, direct, 1 reg), `BBAD=$34` (MPYL), `A1T=T+1`, `A1B=$7E`. - Enable `HDMAEN=$03` in vblank. Init loads ch0 header `$01` (A2A0=T+1) and ch1 header `$01` (A2A1=T+2). At line 0's HDMA, ch0 sends T+1 to `$21FF`, and ch1 reads MPYL and **writes M to T+2**. Then the advance phase: ch0's counter reaches 0 and it reloads its header from T+2. - On line 1 (H≈50, after the line-0 HDMA), the CPU reads `NLTR0`, `A2A0`, `NLTR1`, `A2A1`, and the WRAM byte T+2. - `NLTR0 = $05`: all transfers happen before any reload. This is the demonstration's claim (undisbeliever, `l.72-73`) and the ares order (ares 9408cb4 `sfc/cpu/dma.cpp` `CPU::hdmaRun()`: every channel's `hdmaTransfer()`, then every channel's `hdmaAdvance()`). - `NLTR0 = $03`: transfer and reload are interleaved per channel. - `T+2 = M` proves B→A HDMA wrote into WRAM. - Control variant: swap the roles (ch0 writes, ch1 reads its header). The reader must see M in both orderings. - SRAM: 2 variants × (NLTR0, A2A0 lo, NLTR1, A2A1 lo) = **8 bytes**. **T2b. HDMA stall stopwatch (per-line cost) and T2c (init cost).** The CPU brackets dot ≈276 with two H latches: ``` H-IRQ at line L, HTIME ≈ 230; after wake: NMITIMEN=0 (no more IRQs) lda $2137 ; lda $213F ; lda $213C ; sta H1lo ; lda $213C ; sta H1hi (fixed-length readout) lda $2137 ; (read out H2 the same way) ``` The stall in mc is ((H2 - H1) - (H2 - H1 with HDMAEN=0)) × 4, quantised to one dot. The 4 pre-delays and 2 line parities (L even/odd) remove the quantisation and the 8-mc grid ambiguity. The window starts at about dot 240 and ends before 323 (no long dots) and is far from the refresh at dot 132. Configs for T2b, all in **force blank** so CGRAM targets are harmless: 1. HDMAEN=0 (baseline) 2. 1 direct channel, mode 0, on a line with no transfer and no reload (non-repeat entry, count > 1). This is pure per-channel overhead. 3. same channel, repeat entry (1-byte transfer) 4. 1 channel, mode 3, repeat (4 bytes) 5. 1 channel on its reload line (count expires, so the next header is fetched) 6. the demonstration's own pair (ch0 CGADD mode 0, ch1 CGDATA mode 2), measured on line 15 (reload) and on line 16 (transfer) 7. 1 indirect channel on a reload line (+16 mc indirect fetch per anomie `l.271-272`) 8. 8 direct channels, repeat mode 0 T2c: the same stopwatch around the V=261 → V=0 boundary. Use a V+H IRQ at V=261, HTIME ≈ 300, and compute H2 - H1 modulo 340 dots. Configs: HDMAEN=0; 1 direct; 1 indirect; 8 direct; 8 indirect; 1 direct whose first header is `$00`. This measures init overhead (anomie: 18 + 8/direct + 24/indirect) on v1. SRAM: per sample, 2 bytes (`H8(H1)`, `H2-H1` in dots). T2b is 8 configs × 8 samples × 2 = 128 bytes. T2c is 6 × 8 × 2 = 96 bytes. Store V parity and the field bit implicitly by schedule, plus 1 field byte per config. Total **≈ 240 bytes**. ### 5. Traps - The H latch has 4-mc granularity, and the two readouts take fixed time. Keep the block identical across configs, and change only `HDMAEN` and the table pointers, both set in vblank. - The demonstration's own first frame is a mid-frame enable (wait-loop bug above). Measure only in frames where HDMAEN was set before V=0. --- ## T3. HDMAEN latch tests (hdmaen_latch_test.asm, hdmaen_latch_test_2.asm) ### 1. What they test and exact sequence When must an `HDMAEN` write land to take effect at this line's HDMA point? Common setup (`hdmaen_latch_test.asm:207-231`). All 8 channels: `DMAP=$03` (2 regs write twice), `BBAD=$21` (CGADD, so the 4 bytes go to CGADD, CGADD, CGDATA, CGDATA). `A1T = A2A = PartialHdmaTable` = `dw 0, $001F; db 0` (CGADD 0, colour red) (`l.86-89`). `NLTR` = 0 (cleared by reset, `l.165-169`). Backdrop white, display on. Then wait for a V-IRQ at V=6 (`VERTICAL_OFFSET`, `l.47`, `l.234-243`). **Test 1** (`l.254-305`), for channels 0..7 and `HTIME = 220..232` (`FIRST_HTIME`/`LAST_HTIME`, `l.48-49`): ``` stz NLTRn ; A2AnL = table (low byte only; l.264-271) HTIME = h ; NMITIMEN = $10 lda _hdmaen ; wai ; sta.w HDMAEN ; IRQ handler (bank $00 slow): bit.w $4211 ; rti (l.97-99) wait hblank start; wait hblank end ; one HDMA point passes stz NMITIMEN ; stz HDMAEN ; early on the next line wait hblank; colour 0 := white; wait hblank end ``` That makes 8 × 13 = 104 tests on 2-3 lines each, then `jmp Main`, once per frame. **Test 2** (diff vs test 1). `HTIME = 206` fixed (`hdmaen_latch_test_2.asm:50`). Each of 13 steps t does `wai; w(24+2t); lda _hdmaen; sta HDMAEN; w(48-2t); jsr _OddScanline` (`l.262-275`). That gives **2-master-clock steps** over 24 mc. `_OddScanline` (`l.299-338`) does `wai`, `stz HDMAEN`, resets `NLTRn`/`A2AnL`, restores white in hblank, and adds a fixed delay so the next IRQ is consistent. The IRQ handler is `sep #$20; bit.w $4211; rti` in bank $00. `wdm #t` markers are for the debugger. My estimate of the write time (not verified). Test 1: IRQ flag at 14+4h mc, entry about 60 mc, handler 30 + `rti` 52, then `sta.w` with 18 mc of fetches before the write. That puts the write at about 4h + 178 mc, so h 220..232 maps to about dot 264-277. Test 2: about 1090..1114 mc, straddling 1104. Both sweeps bracket the HDMA point. ### 2. Reporting and recorded results - A red line appears on the screen when the write took effect and the channel's hidden `DoTransfer` was set. White means no effect. No console result is in the sources. - Emulators run as closed boxes (OBSERVED): "Mesen2 shows red stripes, MAME a white screen: they disagree on when an HDMAEN write latches; **a console run decides**" (`docs/validation.md`). - Why a hidden flag matters: with NLTR=0 at enable, the first HDMA point *decrements* (0 → $FF, sets `DoTransfer` from bit 7) but transfers only if `DoTransfer` was already true (ares 9408cb4 `sfc/cpu/dma.cpp` `Channel::hdmaTransfer()` and `hdmaAdvance()`). `DoTransfer` is cleared at V=0 in ares (`hdmaReset()`). So the **first** test per channel per frame cannot show red, even if latched, and later ones can because the flag stays set from the previous test. The picture mixes "latched?" with "flag state?". ### 3. CPU-measured version The CPU reads the effect directly from the channel registers, and stamps the write time with an H latch taken immediately before the write: ``` (prepared in previous line: NLTRn=0, A2An=T (full 16 bits), X = 1< lda.w $2137 ; latch H_pre stx.w HDMAEN ; write lands H_pre + 24 mc (opcode 6 + 2 operands 12 + write cycle 6, FastROM bank $80) ...next line, H≈20: stz HDMAEN ; read OPHCT/OPVCT (H_pre, V) ; read A2An, NLTRn ``` Outcome classes, with no picture needed: - `NLTRn` still `$00`: the write missed this line's HDMA point. - `NLTRn = $FF`, A2A unchanged: latched; the decrement ran and `DoTransfer` was false. - `NLTRn = $FF`, A2A + 4: latched and transferred (the "red line"). - anything else: record it raw. Optional confirmation of the B-bus write itself: run the sweep in force blank and read CGRAM colour 0 (`$2121=0`, `$213B` ×2) after each test. Then restore white. Sweep plan (it merges tests 1 and 2): - **Coarse**: ch0, 40 positions at 4 mc (160 mc ≈ dots 256-296), on even lines. 2 bytes each = 80 bytes. The ROM finds the transition from these. - **Fine**: all 8 channels, 16 positions at 2 mc centred on the coarse transition, × 2 line parities. Run the sweep twice, offset by one line: the original's 2-line test cadence keeps every test on the same parity. That is 256 entries × 2 bytes = 512 bytes. - **DoTransfer probe**: per channel, 2 tests on one line pair with the write well before the HDMA point. The first test that frame shows an A2A delta of 0 (flag clear after V=0) and the second shows 4. 8 × 2 × 1 byte = 16 bytes. Entry format: byte 0 = `H8(H_pre)`. Byte 1 = `bit7: NLTR==$FF, bit6: NLTR∉{$00,$FF}, bits5-0: A2A delta`. Total **≈ 610 bytes** (with 2 bytes of field flags). ### 5. Traps - The IRQ and handler path runs in bank $00 SlowROM. Main code runs in bank $80 FastROM. The H latch makes the result layout-independent, but keep the instruction between the latch and the write fixed (`stx.w`, 4 cycles). If X is 16-bit, `stx.w` also writes `$420D` (MEMSEL!). **Use 8-bit X**, as the original does (`i8`). - Reset the full 16-bit A2A. The original resets only the low byte and asserts the table does not cross a page (`hdmaen_latch_test.asm:270-271`). - Use only visible lines (V < 225). The original uses lines 6..~214. - The grid phase alternates per line (0.2). Without the parity split, half the possible alignments are never seen. --- ## T4. DMA ends at HDMA start (dma-ends-hdma-start-1-ch.asm, hdma-failure-last-dma-value-test.asm) ### 1. What they test and exact sequence "the flicking gradient occurs when the DMA finishes at around the same time HDMA is initialized (shortly after the start of scanline 0)" (`dma-ends-hdma-start-1-ch.asm:5-8`). **1-ch test.** HDMA ch2: `DMAP=$02` (write twice) → BG2HOFS, table = `$F8` + 120 words, `$F8` + 120 words, `$00` (`l.661-685`). Expected `A2A2` at vblank = `table + 2 + 225*2` = table+452 (`l.688-689`). NLTR at vblank is therefore `$8F` (my calculation: 105 decrements in the second entry; not checked by the original). `NmiHandler` runs in bank $00 SlowROM ("DB = 0x00 or 0x80", `l.580`), with no branches or indexing (`l.296-302`): 1. Read `A2A2`→`hdmaA2an` and `NLTR2`→`hdmaNltr`. Reset `A2A2=0`, `NLTR2=0`. 2. `INIDISP=$0F`. `BG2HOFS = 246` (visible if HDMA does not run). `HDMAEN=$04`. 3. DMA ch0: 1024-byte text buffer → VMDATAL. 4. DMA ch1: `DMAP=$98` (B→A, fixed, 1 reg) from `$2134` MPYL (forced to 0 via M7A=M7B=0, `l.276-280`), to a fixed WRAM byte, `dmaDelay` bytes. 5. `lda SLHV` and store OPVCT/OPHCT of the DMA end (`l.387-400`). Main, after each frame: if `hdmaA2an ≠ EXPECTED` then failure (latched forever). Otherwise every 4 frames (`DMA_DELAY_REPEAT`, `l.104`, "most likely caused by NMI interrupt jitter", `l.101`) increment `dmaDelay` through `$1310..$1350` (`l.97-98`), wrapping. **Last-value test** (diff). DMA_DELAY channel 6, A→B from a WRAM buffer to **`$2104` OAMDATA** (`l.82`). DMA channel 7, HDMA channel 0 (`l.76-78`). dmaDelay `$1330..$133A` (`l.65-66`). The buffer is 0 except `[MIN-8 .. end]`, which is filled with `valueToTest`. So the last ≥8 bytes read equal the value. For each value 0..255, all 11 delays run × 4 frames. `testResults[value] = 1` if any frame failed. "If no HDMA failures are detected when the last DMA value is 0 (a known failure value), the test will display an error message" (`l.15-16`). That is 11,264 frames (≈3 min). ### 2. Reporting and recorded results - 1-ch test visual (`l.40-44`): a straight green line on the left means no HDMA. A wavy green line on the right means HDMA OK. A straight green line on the right means "HDMA was interrupted". Red means a break (crash). Text: "HDMA OK" or "HDMA FAILURE DETECTED" plus A2A/NLTR on failure. - **Console results** (`dma-ends-hdma-start-1-ch.asm:47-50`, "My Observations (on version 1 of this test)"): "Model-1 1/1/1 Super Famicom: No crash. HDMA Failure detected." "S-CPU-A Super Famicom: HDMA Failure detected." "1-CHIP Super Famicom: HDMA Failure detected." **The Model-1 1/1/1 is your exact configuration.** The source does not say which dmaDelay failed or what A2A was. - Last-value test: the only result stated is that value 0 fails. The per-value grid is unpublished. ### 3. CPU-measured version The original is already CPU-measured (A2A at vblank). Make it deterministic and richer: - **Start**: a V+H IRQ at V=232 (instead of NMI at 225; this removes the NMI jitter), HTIME fixed. Then `wai`, then ch1 DMA MPYL→WRAM fixed, N bytes (≈4,800, long like the original). The 1024-byte VRAM DMA is not needed for the effect. Drop it, or keep it as an option for faithfulness. - **Pass A (calibration, HDMAEN=0, safe)**: binary-search N so the DMA-end latch is the first one with V=0 and H ≥ 8. Call that N0. Then record the end H of N0-24 .. N0+7 (32 values). - **Pass B (HDMAEN=$04, measured)**: for each N in N0-24..N0+7 and 2 consecutive frames (both field parities): - In vblank before V=232: read and store last frame's `A2A2`/`NLTR2` (vbl snapshot). Reset A2A2=0, NLTR2=0. BG2HOFS any. HDMAEN=$04. - IRQ, then DMA, then `lda $2137` (end H/V). - Poll until V=0, H ≥ 100 (OPHCT polling or HVBJOY), before 1104 mc. Read `A2A2`/`NLTR2` (line-0 snapshot). Expected: A2A = table+1 and NLTR = $F8 if init ran; 0/0 if it was skipped. - At the next vblank: expected A2A = table+452 and NLTR = $8F. - **Last value (T4b)**: same frame structure. DMA A→B from a WRAM buffer to `$2104`, ch6, HDMA ch0 (as the original), buffer = 0 then the final 16 bytes = v. 1. First sweep v=0 over the 32 N values × 2 parities and record which fail (8 bytes). 2. Pick up to 2 failing N (prefer one per parity). If none fail, pick the N with the end closest to init. 3. Run v = 0..255 × 2 N × 2 frames = 1,024 frames (≈17 s). Store a 1-bit fail map (128 bytes) plus the first 8 failures in detail (v, A2A lo, A2A hi, NLTR = 4 bytes each, 32 bytes). SRAM: - T4a: N0 (2), 32 × calibration end H (2) = 64, 64 samples × 7 bytes (end H with V flag 2, line-0 A2A delta 1, line-0 NLTR 1, vbl A2A-table 2, vbl NLTR 1) = 448. Total about 514. - T4b: 8 + 4 (chosen N) + 128 + 32 = 172. - Family total **≈ 690 bytes**. ### 5. Traps - The original window `$1310..$1350` belongs to *his* NMI path. The NMI handler executes from bank $00 slow, with the 1024-byte VRAM DMA first and two refresh pauses per line inside the long DMA. Your window will differ, which is why there is a calibration pass. - The DMA end can only move in 8-mc steps (1 byte), and the init position on v1 depends on the 8-clock phase (`12 + 8 - dmaCounter()`). Frame parity changes that phase every other frame (short line 240). Hence 2 frames per N, with the field bit recorded. - MPYL must stay 0 (M7A/M7B untouched by HDMA). In T4b the OAM writes are harmless in vblank, but they change OAM contents. - Reported "no crash" on 1/1/1, but this is still a DMA ending next to an HDMA event on a v1 CPU. Keep it in the guarded section (started/finished markers, NMI watchdog from T5). --- ## T5. Quick Model-1 DMA crash (quick-model-1-dma-crash/*, 8 ROMs). MAY CRASH YOUR CONSOLE ### 1. What it tests and exact sequence "designed to recreate the conditions of the model 1/1/1 DMA/HDMA crash as quickly as possible (frame 0, scanline 1 or 0)" (`_quick-model-1-dma-crash-test.inc:3-4`). Map mode `$20` = **SlowROM LoROM**, and all code is in **bank $00** (`l.65`, `l.188`, `l.254`). "sd2snes has a different reset position to a normal cartridge ... a 10 dot jitter ... use an IRQ interrupt to delay the test by a single scanline to minimize the test-start jitter to 3 dots" (`l.13-16`). `QuickDmaTest(N)` (`l.78-180`), N = 4, 5, 6, 7 (one ROM each): ``` lda.w SLHV ; latch as early as possible clc ; xce ; rep #$38 ; sep #$24 ; native, a8 i16, I set lda.w OPHCT ; sta.b $00 ; H at entry, for verification stz CGADD ; lda #$FF ; sta CGDATA ×2 ; backdrop white HDMA ch7: DMAP7/BBAD7 = $03/$21 (CGADD,CGADD,CGDATA,CGDATA), A1T7 = HdmaTable ($00:E000), A1B7 = 0 A2A7 = HdmaTable+1 ; NLTR7 = $FF ; manual mid-frame state: repeat, 127 lines HDMAEN = $80 DMA ch0: DMAP0/BBAD0 = $00/$04 (OAMDATA), A1T0 = DmaBlock ($FF×4096, bank 0), DAS0 = N, MDMAEN = 1 nop ×20 ; let the HDMA point pass lda.w NLTR7 ; cmp #$FE ; beq + ; stz HDMAEN ; + ; HDMA ran exactly once on this line? jsr ResetRegistersExceptHdma ; INIDISP = $0F ; loop: wai ; bra loop ``` - No-IRQ variant (`_test-no-irq-delay.inc`, file l.44-46): the body *is* the reset handler (emulation mode, bank $00, SlowROM). The table is a 4-byte repeat gradient. - IRQ variant (`_test-with-irq-delay.inc`, file l.51-72): reset does `clc; xce; rep #$10`, `VTIME=1`, `HTIME=23`, `NMITIMEN=$30`, `nop`, `cli`, `wai`. The body runs in `IrqHandler` at `$00:9000` (file l.81-83). It never acknowledges `$4211`, and I is set by `sep #$24`. - Unused ROM is zero-filled (`seek(0x03ffff) db 0`, `l.287-288`), so a wild PC soon executes `$00` = BRK → `BreakHandler` (all native/emu vectors except reset/IRQ, `l.264-282`). My estimate of the timing (IRQ variant, all fetches 8 mc, I/O 6 mc; not verified): about 810 mc from the first `lda SLHV` to the `sta MDMAEN` write. Add the IRQ flag at 14+23×4 = 106 mc, about 60 mc of entry, and 40 mc of refresh at 530 mc. MDMAEN then lands near 1010-1020 mc, and the N=4..7 DMAs (snap + 8 + 8 + 8N) end at about 1070-1100 mc, **just before the 1104-mc HDMA point**. That fits the reported crash condition. ### 2. Reporting and recorded results - Visual (`l.6-10`): "Red screen: A break interrupt occurred (crash). White screen: HDMA was not active on scanline 0. Green HDMA gradient: No crashes detected and no HDMA errors. The S-CPU may have done something unexpected, but it did not execute a `brk` or `cop` instructions." Red also shows the stacked PC, P, e, DB, SP, DP, A, X, Y (`break_handler.inc:63-79`). - **No console results are recorded in the sources** (no file:line). The only v1 statements are the wiki's "Crashes if a DMA finishes just before HDMA happens" (Version_differences) and Errata l.96. - **What exactly crashes is not documented here.** The original's only detectors are "executed BRK/COP" and "HDMA did not decrement NLTR7". A CPU hang (no BRK) shows a frozen gradient or white screen, which it does not distinguish from success. Do not assume a mechanism. Design the detectors to tell these apart: (a) hard hang (CPU or DMA never resumes), (b) wild execution (BRK/COP/vector hit, or a loop elsewhere), (c) silent corruption (wrong registers, stack, or DMA/HDMA state), (d) clean. ### 3. CPU-measured version (controlled sweep, IRQ-variant body) Handler = the original IRQ-variant body, byte-for-byte, in **bank $00** at a fixed address, with these changes: - `ldx.w #N` becomes `ldx.b zpN` (+8 mc, uniform, absorbed by the sweep). - `lda #HDMAEN.dma7` becomes `lda.b zpHdmaen` (+8 mc, uniform). Calibration uses 0 and the attempt uses $80. This keeps the two passes cycle-identical up to MDMAEN. - Two copies that differ only *after* `sta MDMAEN`: - **Calibration copy** (HDMA off, safe): `lda.w $2137` immediately after `sta MDMAEN`. The latched H marks the DMA end (+30 mc: 3 slow fetches + I/O read). - **Attempt copy**: the original 20 `nop`s and the `lda NLTR7` check, unchanged. After that, `jml` to `AttemptDone` (bank $80) instead of falling into the wai loop. - `AttemptDone`: `NMITIMEN=0`, `lda $4211`. Set SP, D, DB to known values (do not trust them). Save the pre-reset SP/D/DB for comparison. Read `NLTR7`, `A2A7`, `DAS0`, `A1T0`, `HDMAEN`-dependent state. In vblank, read OAM bytes 0..7 (OAMADD set to 0 before the attempt; expect `$FF` × (N rounded down to even), because OAM low-table writes commit in pairs). Read CGRAM colour 0 (expect the table's first green value if HDMA wrote it). Compute the status byte, write SRAM, write "finished". Sweep: N ∈ {1..12} × HTIME ∈ {21, 22, 23, 24} (4-mc steps) × V ∈ {1, 2} (line parity) = 96 attempts. Run the calibration pass for all 96 first (HDMA off). Use the measured DMA-end H to **order the attempts from far to near the HDMA point**, so the least risky attempts finish before the first crash. Status byte: `b0 NLTR7==$FE (HDMA ran once)`, `b1 A2A7==table+5`, `b2 DAS0==0`, `b3 A1T0==DmaBlock+N`, `b4 OAM readback ok`, `b5 CGRAM colour0 ok`, `b6 SP/D/DB as expected`, `b7 reached AttemptDone`. ### 4. Crash handling, after-the-fact detection, and watchdog - **Before each attempt**, in vblank and outside the timed path, write SRAM "started(T5, k)". Record "finished(T5, k, status)" in AttemptDone. On boot, if "started k" exists without "finished k", mark k as **HUNG/LOST**. Then skip k and continue at k+1. Never retry k automatically. - **Wild execution recorder**: point *all* unused vectors (native COP/BRK/ABORT/NMI-when-not-armed, and emulation COP/ABORT/NMI/IRQ-BRK `$FFFE`) at a bank $00 stub that does `jml Recorder`. The Recorder starts with `clc; xce` before touching carry (carry then holds the old e flag, the trick in `break_handler.inc:92-127`), then `sei`, saves the old SP (`tsc`) so the stacked frame can be found, then sets SP/D/DB, and copies the stacked P/PC/PBR plus A/X/Y, the vector id, and an SLHV latch to an SRAM crash record (16 bytes). It then **soft-recovers**: reinitialise like reset and continue with attempt k+1. Fill all unused ROM and all unused WRAM with `$00` so a wild PC reaches BRK. - **NMI watchdog** (possible and useful): set `NMITIMEN = $B0` (NMI + V + H IRQ) during attempts. NMI fires at V=225, about 223 lines after the test line, by which time a healthy attempt reached AttemptDone. The NMI handler (bank $00 → `jml`) checks the WRAM "attempt armed" byte. If it is still armed, the CPU is running but lost. Record the NMI's stacked PC/PBR/P: it shows **where** the CPU is looping. Then soft-recover. Limits: - (a) If the CPU is truly halted (DMA never releases, STP, a locked core), NMI never runs. Only the reset path catches it, with no PC. - (b) Wild code may have changed SP. The NMI push then goes to `$00:SP`, which can hit `$21xx`/`$42xx`/`$43xx` I/O, so treat post-crash hardware state as untrusted and reinitialise all of it. - (c) Wild code with I clear re-enters the test handler at the next V=1 IRQ. AttemptDone clears NMITIMEN first to narrow that window, and the NMI check catches the rest. - **Crash budget**: stop the T5 sweep after 8 HUNG/wild results, so the user is not asked for dozens of resets. Mark the remaining attempts NOT RUN. - SRAM integrity: a wild CPU can write `$70:0000-7FFF`. Use a CRC per record block, with the family header duplicated. ### 4b. Optional exact replica: reset-entry probe (opt-in, needs manual resets) The no-IRQ ROMs test the **reset** position, which only a reset can reproduce. Option: if SRAM holds "armed(R, N)", the reset vector jumps straight into `QuickDmaTest(N)` (bank $00, emulation mode, as the original). The first instructions are unchanged. Afterwards, write {entry OPHCT/V, NLTR7, DAS0, status} to SRAM, disarm, and continue normal boot. A crash leaves "armed + started", and the next reset records HUNG and disarms before running anything. That is 4 N values × (no-IRQ, IRQ) = 8 resets, 6 bytes each = 48 bytes. EverDrive caveat (unverified): confirm that pressing reset on the Super EverDrive X5 restarts the game rather than returning to the menu, and that SRAM survives the trip to SD. Also note undisbeliever's finding that flash carts change the reset position. ### 5. Traps - **Bank $00 SlowROM is part of the condition.** The original's CPU resumes from DMA into a slow-ROM `nop` fetch. If the crash depends on the CPU's first bus cycle after the DMA meeting the HDMA halt, that cycle's type matters. So the attempt copy must keep the `nop` stream, in bank $00. - Keep DMA ch0 and HDMA ch7 (ch7 is processed last), the mode-3 CGADD table, and the manual `A2A7=table+1, NLTR7=$FF` mid-frame enable. HDMAEN must be 0 at V=0 so no init happens, matching the original. Turn autojoypad off. - INIDISP during the original test is whatever reset left. Force blank is probably fine (HDMA does not depend on display), but this is unverified. Do one display-on pass of the 8 nearest attempts if the budget allows. - MEMSEL does not matter for bank $00. If you run the handler from bank $80 instead, the timing changes by 2 mc per fetch, and so does the behaviour of the post-DMA fetch. --- ## Family plan (ordered; crash tests last) | # | Test | Merges | Risk on v1 | SRAM bytes | Time | |---|---|---|---|---|---| | H | Family header: `$4210/$213E/$213F` versions, field bit, per-test status, duplicate | | none | 32 | - | | 1 | T2a HDMA transfer-before-reload probe | demonstration (claim) | none | 8 | 2 frames | | 2 | T2b/T2c HDMA stall stopwatch, per line + init | demonstration (timing) | none | 240 | ~30 frames | | 3 | T3 HDMAEN latch: coarse + fine × 8 ch × 2 parities + DoTransfer probe | latch_test + latch_test_2 | none | 610 | ~10 frames | | 4 | T1 S-CPU-A DMA bug, 9 configs, retry merged | 10 ROMs → 9 configs (fix2 folded) | none (DMA at ~dot 113) | 252 | ~10 s | | 5 | T4a DMA ends at HDMA init (calibrate, then sweep) | dma-ends-1-ch | low (1/1/1 "No crash") | 514 | ~2 s | | 6 | T4b last-DMA-value at the failing N | hdma-failure-last-dma-value | low | 172 | ~18 s | | 7 | T5 calibration (HDMA off) then 96-attempt crash sweep, far → near, budget 8 | quick-crash 4/5/6/7 + irq-4..7 | **HIGH** | 96×2 cal + 96×2 status + 8×16 crash recs + 8 progress = 520 | ~2 s + resets | | 8 | T5b reset-entry replica (opt-in) | no-IRQ ROMs | **HIGH** | 48 | 8 resets | | | **Total** | | | **≈ 2,400 bytes** (under 3 KiB; ~650 spare) | | Global rules for the family: - Autojoypad off. NMI off except in the T5 watchdog. Use WRIO=$FF so SLHV latches. - Every DMA/HDMA-alignment result carries V parity and the `$213F` field bit (0.2). - Every IRQ-timed path keeps its handler in bank $00 (SlowROM) like the originals. Main code goes in bank $80 with MEMSEL=1. **Record the latched H at each critical write** rather than relying on instruction counts. This makes the result self-describing even if your layout differs. - Order inside the risky section: T4 (reported safe on 1/1/1) before T5. Within T5, run calibration first (no HDMA), then attempts sorted by distance from the HDMA point, far first. Checks the results answer directly: - HDMA per-line point: 1104 mc (ares) vs "dot 278" (anomie). Answered by T2b and T3. - Init cost on v1. Answered by T2c. - Transfer/reload order. Answered by T2a. - HDMAEN latch point and the DoTransfer reset at V=0 (Mesen2 and MAME disagree when run, OBSERVED). Answered by T3. - S-CPU-A bug absent on v1. Answered by T1. - Where the DMA end crosses HDMA init, and whether the last DMA value matters. Answered by T4. - v1 crash window and failure mode (hang vs wild vs silent). Answered by T5.