Technical documentation

Open6502 technical documentation

From a playable emulator to a synthesizable 6502/NES SoC. Architecture, timing, verification evidence, synthesis numbers, and every sharp edge still open. The commands here are meant to be copied.

Last verified · 2026-11-11 19 chapters ~25 min read Functional prototype · not tapeout-ready
00 · Overview

Overview: what this is and where to start

This is a document you can follow: every command is in the repo, and every conclusion has a test or a hash behind it. It also says plainly what has not been done yet — this is not a finished chip.

Four reading paths

Here to practice the flow: start with the learning path (inner → middle → outer loop), then follow the route below. The core is one sentence: change a line of RTL, run one command, see PASS or the first divergence within minutes.
Who you areStart hereThen
I am here to practice the flow10 Verification11 DiffTest → 12 Golden frames → 14 Synthesis → 15 Roadmap
I just want to run it01 QuickstartIf it breaks: 16 Troubleshooting
I want to understand the design03 Architecture04 CPU → 05 PPU → 10 Verification
I want to contribute or push the backend02 Repository map10 Verification → 14 Synthesis → 15 Roadmap → 17 Contributing

What it is, and what it is not

It is: a working NES functional prototype. The NEMU frontend plays all six MIT-licensed ROMs; the RTL SoC passes 28 tests, Klaus and frame-level DiffTest; the code synthesizes, and area has been estimated per module.
It is not: a cycle-exact NES; an FPGA project with a bitstream; a tapeout-ready chip; or an open-source project with a published root licence. The PPU pipeline, DMC arbitration and multi-game lockstep DiffTest are incomplete.

Three execution paths

PathRoleStatusBest for
NEMU / 6502EMUSoftware reference (REF)PlayablePlaying, golden frames, CPU reference behaviour
RTL SoCDesign under test (DUT)PrototypeSynthesis, verification, DiffTest, future FPGA/ASIC
GEM6502C functional / cycle modelLegacyFast PRG runs and instruction-level regression; not a full timing platform

DUT and REF must stay independent. NEMU is never synthesized, and RTL may not borrow NEMU's implementation to “check the answer”. DiffTest compares observable state only: registers, bus transactions, frame hashes, audio samples and mapper state.

Latest verification snapshot

CheckResultEvidence
RTL unit / integration tests28 PASScd rtl && make sim
RTL lintPASScd rtl && make lint
RTL CPU KlausPASS · PC=0x3469sim/klaus/
RTL / NEMU golden title frameSHA-256 match12 Golden frames
RTL gameplay after STARTRendered01 Quickstart
FPGA bitstream / boardNot yet15 55nm path
01 · Quickstart

Quickstart: get one frame running

The shortest path is NEMU: build once, then use roms/play.sh as often as you like. To exercise the RTL, run the same ROM through Verilator and capture a PPM frame.

Dependencies

ToolPurposeNotes
GitGet the repositoryFirst clone only
clang / gcc + makeBuild NEMU and GEM6502macOS needs Xcode Command Line Tools
SDL2Emulator window, keyboard and audiobrew install sdl2 / libsdl2-dev
Python 3iNES extraction, PPM to PNGPillow optional
Icarus Verilogmake sim runs 28 RTL testsDefault Icarus path
VerilatorRTL frame capture, Klaus, DiffTestNeeds a working C++ toolchain
Yosys 0.60Area estimatesOptional, -noabc

Build and play NEMU

shell
$ git clone https://github.com/OneDayOneApp/Open6502.git
$ cd Open6502
$ make -C NEMU m6502_defconfig
$ make -C NEMU -j8
$ ./roms/play.sh falling

You can also call the binary directly: ./NEMU/build/6502EMU roms/falling.nes. Most games start with V; 1P uses WASD + Space/Z + X, 2P uses the arrow keys and , . / '.

Bundled ROMs

ROMMapperGenreLicence300-frame status
falling.nes0 / NROMPlatformerMITBoots, title screen
galaxypatrol.nes0 / NROMShooterMITBoots, playable; known starfield rendering gap
hanoi.nes0 / NROMPuzzleMITBoots, title screen
table_tennis.nes0 / NROM2P pongMITBoots, title screen
file-fixers.nes4 / MMC3PuzzleMITBoots, title screen
stallar.nes4 / MMC3PlatformerMITBoots, title screen
Every ROM is open-source homebrew; the licence texts are in roms/LICENSES/. The repository contains no commercial ROMs.

Headless screenshots (NEMU)

Both the title frame and the post-START frame can be captured without a window. This is also where the golden frames come from:

shell
$ ./NEMU/build/6502EMU --headless --no-audio --frames=300 \
    --screenshot=/tmp/nemu-falling.ppm roms/falling.nes
$ ./NEMU/build/6502EMU --headless --no-audio --hold=start --frames=20 \
    --screenshot=/tmp/nemu-start.ppm roms/falling.nes
python
# PPM to PNG; on macOS without Pillow, use sips
$ python3 -c 'from PIL import Image; Image.open("/tmp/nemu-falling.ppm").save("/tmp/nemu-falling.png")'

GEM6502 C model

shell
$ cd GEM6502
$ make
$ make test
$ ./gem6502 game ../roms/falling.nes 60 /tmp/gem-title.ppm
$ ./gem6502 play ../roms/file-fixers.nes

play needs SDL2. Without it the CLI still builds, but play reports the missing dependency. See 13 GEM6502 for scope and limits.

Run the RTL game and capture a frame

The repository script wraps iNES extraction, the Verilator build and the run:

shell
$ ./sim/game/run.sh roms/falling.nes /tmp/falling-rtl.ppm
$ python3 -c 'from PIL import Image; Image.open("/tmp/falling-rtl.ppm").save("/tmp/falling-rtl.png")'
sim/game/run.sh defaults to macOS clang++, the macOS SDK and Homebrew LLVM's libc++ path. On Linux or a different LLVM version, override SDK=…, LIBCXX_DIR=… or CXX=…, or adjust the link flags as noted in the script.

Run the whole regression

shell
$ cd rtl
$ make lint
$ make sim
$ cd ..
$ ./sim/difftest/run.sh
$ ./sim/difftest/run_alu.sh

make sim compiles and runs 28 testbenches with Icarus. The output is large, but every step should print PASS. On Windows, use WSL2 and follow the Linux steps.

02 · Repository

Repository map: where everything lives

The repo holds the software reference, the RTL SoC, verification scripts, a C model, a game downloader and the docs. These are the most useful entry points.

Open6502/ ├── NEMU/ NEMU-derived 6502/NES emulator + BASIC + SDL frontend ├── rtl/ SystemVerilog SoC (the only synthesizable implementation) │ ├── cpu/ open6502_cpu.sv │ ├── ppu/ open6502_ppu.sv │ ├── apu/ APU + DMC │ ├── bus/ bus decode + WRAM │ ├── cart/ mapper 0/1/2/3/4/7 │ ├── dma/ OAM DMA │ ├── input/ controller shift register │ ├── video/ 341×262 video timing │ ├── clocks/ clock / reset / enables │ ├── fpga/ FPGA wrapper │ └── dbg/ DiffTest event bridge ├── tb/ 28 SystemVerilog testbenches ├── sim/ │ ├── difftest/ NEMU/RTL state and PC trace comparison │ ├── game/ RTL game bring-up + PPM capture │ └── klaus/ RTL Klaus test ├── GEM6502/ C functional / cycle model (legacy baseline) ├── nesearch/ C++20 NES search / download CLI + local Web UI ├── roms/ 6 open-source ROMs + licences ├── docs/ chip, verification, area and roadmap documents ├── skills/ reusable chip-design playbooks (xiangshan-chip-flow) └── site/ this website (plain static, GitHub Pages)
DirectoryRead firstCommon command
NEMU/6502EMU.mdmake -C NEMU -j8
rtl/README.md, open6502_top.svmake lint && make sim
sim/difftest/README.md./sim/difftest/run.sh
GEM6502/README.md, docs/requirements.mdmake && make test
nesearch/README.en.md, PRD.md./nesearch/run-ui.sh
docs/open6502-chip/Architecture, verification, DiffTest, area—
skills/xiangshan-chip-flow/SKILL.md—

Documentation index

Repository docs are maintained in English; this page is the same content in a navigable form. If this page and the repository disagree, the current code and latest test results win. The last full verification was on 2026-11-11.
03 · Architecture

Architecture: one clock, several phases

All sequential logic runs on the 21.477272 MHz master clock; enable phases create the CPU, PPU, APU and pixel beats, avoiding multi-clock CDC. Reset asserts asynchronously and releases synchronously. This is an NES/Famicom-compatible digital SoC, not a device-by-device copy of the NES board.

21.477272 MHz ──► clock / reset (÷12 CPU · ÷4 PPU · ÷24 audio) │ ┌─────────────┐ ┌───▼──────────┐ ┌──────────┐ ┌─────────┐ │ 6502 CPU │◄─►│ system bus │◄─►│ 2C02 PPU │──►│ video │ │ 2A03 profile│ │ decode / │ │ dot │ │ RGB444 │ └─────────────┘ │ arbitration │ └────┬─────┘ └─────────┘ └──┬───┬────┬──┘ │ ┌─────────▼┐ │ ▼ ▼ │ 2KB WRAM │ │ VRAM / OAM / palette └──────────┘ │ ┌──────▼─────┐ ┌──────────────┐ │ 2A03 APU │ │ cart / mapper│ │ 4ch + DMC │ │ PRG / CHR │ └──────┬─────┘ └──────┬───────┘ │ │ audio mixer cartridge bus

Design principles

  • RTL is the only synthesizable implementation; NEMU never enters synthesis.
  • NEMU is the REF, not the DUT; the two may not share an implementation to “check the answer”.
  • Build CPU + bus first, then PPU/APU, then mappers and accessories.
  • FPGA prototype before ASIC; every stage has exit criteria.
  • Every external interface has an observable trace for DiffTest.

Clocks and reset

SignalFrequencyUse
clk_21m21.477272 MHzSingle master clock, all sequential logic
cpu_en1.789773 MHzCPU phase (÷12)
ppu_en5.369318 MHzPPU dot phase (÷4)
aud_en44.1 kHzAudio sample
vid_pclk5.369318 MHzPixel output

Address space

AddressTargetNotes
$0000–$1FFF2 KB WRAMFour mirrors
$2000–$3FFFPPU registers8-byte mirrors
$4000–$4017APU / OAM DMA / controllers$4014 triggers OAM DMA
$4018–$401FTest / expansion—
$4020–$5FFFExpansion space—
$6000–$7FFFPRG RAMProvided by the cartridge
$8000–$FFFFCartridge PRGReset vector at $FFFC/$FFFD

Top-level ports

systemverilog
module open6502_top (
  input  logic        clk_21m,
  input  logic        rst_n,
  output logic        vid_pclk,
  output logic        vid_de,
  output logic        vid_hsync,
  output logic        vid_vsync,
  output logic [11:0] vid_rgb,
  output logic        aud_valid,
  output logic signed [15:0] aud_sample,
  input  logic [7:0]  joy1,
  input  logic [7:0]  joy2,
  output logic [15:0] cart_addr,
  output logic [7:0]  cart_wdata,
  input  logic [7:0]  cart_rdata,
  output logic        cart_we,
  input  logic        cart_irq,
  output logic        dbg_valid,
  output logic [63:0] dbg_payload
);

Module responsibilities

ModuleFileResponsibility
CPUcpu/open6502_cpu.sv2A03 profile, instructions, bus cycles, interrupts
PPUppu/open6502_ppu.svRegisters, VRAM/CHR/OAM/palette, per-dot background and sprite composition
APUapu/open6502_apu.svTwo pulses, triangle, noise, frame sequencer, envelope, length, sweep
DMCapu/open6502_dmc.svSample address/length/rate/loop/IRQ/output and DMA requests
Busbus/open6502_bus.svAddress decode, chip selects, peripheral arbitration
WRAMbus/open6502_wram.sv2 KB main RAM and four-way mirroring
Mappercart/open6502_mapper.svMapper 0/1/2/3/4/7 banking, mirroring, IRQ
OAM DMAdma/open6502_oam_dma.sv$4014 256-byte transfer and CPU stall
Clocksclocks/open6502_clocks.svReset sync, CPU/PPU/audio enables
Videovideo/open6502_video_timing.sv341×262 NTSC timing and sync signals
Controllerinput/open6502_controller.svController serial shift
DiffTest bridgedbg/open6502_difftest_bridge.svPacks CPU/BUS/PPU/APU events

For the full block diagram, ports and v0 scope, see docs/open6502-chip/architecture.md.

04 · CPU

CPU: get function right, then cycles

open6502_cpu is a 6502 core in the 2A03 configuration. The current goal is official instructions plus stable undocumented behaviour; cycle-level bus behaviour is still being filled in.

Covered

  • Official instruction set plus target-stable undocumented instructions; decimal ADC/SBC is implemented and covered by Klaus.
  • Addressing: immediate, zero page, zero-page indexed, absolute, absolute indexed, indirect, indexed indirect and branches.
  • Cycle-level bus actions: fetch, operand reads, dummy reads, RMW double writes, DMA stalls.
  • Interrupts: NMI edge, IRQ level, APU frame IRQ, mapper IRQ; corrected BRK/RTI return address.
  • Accumulator/memory shifts, JSR/RTS, PHA/PLA/PHP/PLP, INC/DEC/BIT, JMP indirect, CMP/AND/ORA/EOR/ADC/SBC.

Evidence

TestResultNotes
Klaus 6502 functionalPASS · PC=0x3469Includes decimal ADC/SBC
NEMU KlausPASSThe reference model passes too
Directed testbenchesPASSADC, BRK, decimal, INC, IRQ, JMP ind, JSR, PHP, RMW, stack, ZP37 and more
NEMU/RTL DiffTestPASSFinal state, PC trace, ALU/stack
shell
# Prepare the Klaus binary first; the default path is /tmp/klaus.bin
$ KLAUS_BIN=/path/to/klaus.bin ./sim/klaus/run.sh
Not yet exact: CPU cycle timing, some dummy reads, NMI/IRQ interaction with DMA, and DMC stall alignment are still approximate. RTL Klaus passing at PC=0x3469 proves function, not cycle-level equivalence.
05 · PPU

PPU: it draws, but it is not a dot pipeline yet

The PPU is both the largest block and the biggest accuracy gap. It renders the title frame and gameplay, but uses “per-dot generation + end-of-scanline sprite composition” instead of the real 2C02 fetch/shift pipeline.

CPU writes $2006/$2007 │ ▼ VRAM / CHR / OAM / palette (register arrays) │ ▼ 341 dots × 262 lines dot loop │ ├─ background pixel (nametable + pattern + attributes + scroll) ├─ sprite composition (priority, sprite 0, 8×16, overflow) ▼ palette index → RGB444 / PPM capture

Implemented

  • CPU-visible $2000–$2007 registers, including $2007 auto-increment.
  • Internal storage: CHR 8 KB, VRAM 2 KB, OAM 256 B, palette 32 B.
  • Background pixels generated per dot, with coarse/fine X/Y scroll and nametable mirroring.
  • Sprite overlay, priority, sprite 0 hit, scanline overflow and 8×16 mode.
  • VBlank/NMI and frame output; vid_rgb uses an RGB444 palette LUT.

Registers

AddressNameCurrent implementation
$2000PPUCTRLNMI, sprite size, background/sprite pattern tables, address increment
$2001PPUMASKBackground/sprite/left-column clipping, grayscale and emphasis bits
$2002PPUSTATUSVBlank, sprite 0, overflow
$2003OAMADDROAM address pointer
$2004OAMDATAOAM read/write
$2005PPUSCROLLTwo-write X/Y scroll
$2006PPUADDRTwo-write high/low address
$2007PPUDATAVRAM/palette read/write and auto-increment

Accuracy gaps

  • No complete background fetch/shift register pipeline; rendering is organised per dot/scanline.
  • Sprite evaluation is approximate, not the 2C02's per-scanline OAM scan.
  • MMC3 A12 filtering and IRQ timing are approximate.
  • PPU open bus and $2007 palette read-back are not fully covered.
  • Storage is expanded into flip-flops, which is why it costs 975,919 generic cells; it must become BRAM before board bring-up.

Related tests: ppu_tb, ppu_pixel_tb, ppu_sprite_tb, ppu_scroll_tb, ppu_overflow_tb. Area work is in 14 Synthesis & area.

06 · APU / DMC

APU & DMC: four channels, one unarbitrated bus

The APU implements the 2A03's four channels, frame sequencer, length/envelope/sweep and $4015 status, producing 16-bit samples. DMC has its own sample and DMA request logic, but bus arbitration is still missing.

ChannelImplementedTests
Pulse 1 / 2Duty, envelope, length, sweep, muteapu_tb / apu_sweep_tb
TriangleLinear counter, length, muteapu_tb
NoiseLFSR, envelope, lengthapu_tb
DMCRate, address, length, loop, IRQ, output, 4-cycle CPU stalldmc_tb · arbitration incomplete
Frame sequencer4/5-step, frame IRQ, length/envelope clocksapu_tb
Mixer16-bit samples, 44.1 kHz enableapu_tb

Output path

RTL outputs aud_valid and a signed 16-bit aud_sample; the FPGA wrapper provides a 1-bit sigma-delta audio interface. RTL has no desktop SDL frontend: frame capture works, but real-time listening still goes through NEMU or GEM6502.

DMC open items

  • DMC bus arbitration: priority and insertion timing against CPU/PPU are not complete.
  • DMA and CPU stall cycle alignment is still approximate.
  • DMC sample address/length behaviour across page boundaries and loop edges lacks hardware alignment.
Audio is “functionally usable”, not “cycle- and mixer-exact”. Do not call it passing based on listening; that needs a NEMU/RTL audio DiffTest first.
07 · Bus / Memory

Bus & memory: 2 KB of WRAM and its mirrors

The bus handles address decode, chip selects and peripheral arbitration. It routes CPU reads and writes to WRAM, PPU, APU, DMA, controllers and the cartridge; every peripheral should expose unique, observable transactions.

WRAM

$0000–$1FFF is 2 KB of physical WRAM mirrored every 2 KB, four times. $2000–$3FFF is the PPU's 8-byte mirror. open6502_wram handles mirror decoding and adds no wait states.

OAM DMA

A write to $4014 starts a 256-byte OAM DMA: the engine copies from CPU address space into PPU OAM and stalls the CPU. Integration tests cover the $4014 trigger, transferred data and stall behaviour; exact bus phases still need alignment.

Controllers

open6502_controller implements the standard serial shift: a write to $4016 latches, then eight reads return A/B/Select/Start/directions. The two ports are independent. Tests cover button order and the stable bits.

Known gaps

  • “Every peripheral has a unique bus transaction” is not fully covered.
  • Priority when OAM DMA and DMC DMA request at the same time is not verified.
  • Exact CPU access timing to PPU registers (read/write latency, open bus) is approximate.
08 · Cartridge

Cartridge & mapper: 0/1/2/3/4/7

RTL mappers cover NROM, MMC1, UxROM, CNROM, MMC3 and AxROM. They handle PRG/CHR banks, mirroring, PRG RAM and IRQ; MMC3 A12 filtering remains approximate.

MapperNameKey behaviourStatus
0NROMFixed PRG/CHR, no bankingPass
1MMC1Serial shift register, PRG/CHR banks, mirroringBasic
2UxROMPRG bank switchingBasic
3CNROMCHR bank switchingBasic
4MMC3Banks, PRG RAM, scanline IRQA12 approximate
7AxROM32 KB PRG banks, single-screen mirroringBasic

How ROMs enter RTL

  • NEMU loads iNES directly and supports mapper 0/1/2/3/4/7.
  • RTL simulation: sim/game/extract_ines.py turns iNES into Verilog $readmemh images for PRG/CHR.
  • FPGA (future): load iNES from SPI Flash/SD into SRAM/BRAM, or use a physical cartridge connector.
file-fixers.nes and stallar.nes are the key MMC3 regression samples. Running does not mean A12/IRQ timing is exact.
09 · Video / Input

Video, input and clocks: the last analogue edge

The digital side outputs 341×262 NTSC timing, RGB444 pixels and 44.1 kHz audio. Analogue video/audio and physical controller ports are left to the FPGA board or external DACs.

ItemCurrent implementationNotes
Scan timing341 dots × 262 linesvid_pclk / de / hsync / vsync
Pixel formatRGB444Internal palette index through a LUT
Frame rateNTSC, ~60 HzSimulation driven by the frame loop
Audio16-bit PCM / σΔFPGA wrapper provides 1-bit sigma-delta
InputTwo standard controllersSerial shift, joy1/joy2
FPGA outputWrapper existsNo bitstream, no board validation

FPGA wrapper

fpga/open6502_fpga_top.sv wraps VGA and sigma-delta audio, but full synthesis, BRAM inference, timing constraints and board bring-up are not done. Artix-7/Nexys A7 class is a planning target, not a verified result.

Clock strategy

No free-running multiple clocks: one clk_21m plus enables. CPU/PPU/APU relative phase is therefore deterministic in simulation and after synthesis, which makes tick-aligned DiffTest possible. The cost is enable discipline; any write missing its enable repeats across all 12 21 MHz cycles.

A real bug from this rule: PPU chip select was not qualified by cpu_ce, so one CPU store committed on all 12 master clocks and $2006/$2007 writes landed wrong. The title frame only matched NEMU after the fix.
10 · Verification

Verification: evidence, not slogans

Verification has eight levels: package/decode unit tests, CPU + bus, PPU frames, APU samples, mapper, full games, FPGA board validation, and L8 formal verification. The strongest evidence today is L0–L2, a single L3 frame, and the 19 instruction refinement proofs at L8.

LevelObjectMethodStatus
L0package / decode / countersSystemVerilog unit testsPASS
L1CPU / PPU / APU blocksDirected tests + vectorsPASS
L2CPU + busKlaus, nestest, DiffTestKlaus PASS
nestest not wired up
L3PPU + CPUPPU ROMs, frame hashesSingle frame
L4APUapu_test, DMC, sample hashesBlock level
L5MapperBank/IRQ test ROMsBasic
L6SystemOpen-source games, hardware6 ROMs run
L7FPGABoard video/audio/inputNot started
L8CPU ISA ↔ RTL FSMLean 4 refinement proofsPASS · 19 instructions

Current regression results

CheckResultCommand / location
RTL lintPASScd rtl && make lint
RTL unit/integration tests28 PASScd rtl && make sim
RTL KlausPASS · PC=0x3469sim/klaus/run.sh
NEMU/RTL final statePASSsim/difftest/run.sh
NEMU/RTL PC tracePASSsim/difftest/run.sh
NEMU/RTL ALU / stackPASSsim/difftest/run_alu.sh
Lean formal modelPASS · 151 opcodescd formal && lake build
FALLING title frameSHA matchsim/game/run.sh
FALLING post-START frameRendered01 Quickstart

Still missing

Test suiteCoverageStatus
Klaus 6502 functionalOfficial instructions and flagsPASS
nestestInstruction/cycle golden logNot wired up
instr_test-v5 / instr_miscUndocumented instructionsNot wired up
cpu_timing_test6Cycle-level CPUNot wired up
cpu_interrupts_v2NMI/IRQ/BRK timingNot wired up
ppu_vbl_nmi / sprite_hit / overflow / open_busPPU edge casesPartial
apu_test / apu_reset / DMCAudio accuracyPartial
240p Test SuiteVideo and syncNot wired up
Multi-game lockstep DiffTestSystem-level consistencyNot wired up

Formal verification (L8)

formal/ writes the CPU's ISA specification and a cycle-level model in Lean 4, then proves the model implements the specification: the 151-opcode decode matches the RTL dispatch; ADC/SBC (including BCD), CMP, shifts and BIT hold for all 8-bit operands; 19 instructions have mrun n m = step m refinement theorems; 15 executable program tests are run by the kernel itself; and 4 programs agree with the real RTL in co-simulation. The method follows CktFormalizer/CktLean: typed hardware representation → kernel proofs → SystemVerilog/JSON extraction → an RTL consistency gate.

Run: cd formal && lake build (about 15 s, no sorry); make check-rtl check-cosim runs the RTL cross-check and co-simulation. Entry point: formal/README.md. Known limits: cycle counts follow the current RTL (no page-cross penalty) and IRQ/NMI entry/reset are not refined yet.

Release gates

A v0 FPGA prototype needs at least: Klaus, PPU VBlank/NMI/sprite 0, four APU channels, mapper 0/1/2/3/4/7, six playable open-source ROMs, and a passing CPU + frame-level DiffTest. ASIC adds DFT, timing closure, power, package and hardware alignment.

“28 tests pass” means those 28 tests pass. It does not equal NES compatibility, and it does not equal cycle accuracy. Never substitute a test count for coverage analysis.
11 · DiffTest

DiffTest: make two implementations testify

The goal is to compare observable DUT (RTL) and REF (NEMU) state under identical input, from instructions and bus transactions to scanlines, frame hashes, audio samples and mapper state. It cannot prove RTL matches real NES hardware; it only proves RTL matches REF.

┌───────────────────┐ DPI / shared memory ┌───────────────────┐ │ Verilator RTL DUT │ ◄─────────────────────► │ NEMU NES REF │ │ open6502_top │ │ nes_ref_machine │ └─────────┬─────────┘ └─────────┬─────────┘ │ │ └────────────── DiffTest runner ───────────────┘ │ mismatch report

Event record

systemverilog
typedef struct packed {
  logic        valid;
  logic [1:0]  kind;   // 0=cpu, 1=bus, 2=ppu, 3=apu
  logic [63:0] tick;
  logic [15:0] addr;
  logic [7:0]  data;
  logic        we;
  logic [7:0]  source;
} open6502_dbg_event;

Sync points

GranularityRTLREFCompare
Instructioncpu_retirecpu_stepPC / A / X / Y / SP / P / cycles
Busbus_eventbus traceaddr / data / we / tick
Scanlineppu_scanline_endPPU statev / t / x / w / OAM / status
Frameframe_endframebufferframe hash
Audioaud_validAPU samplessample hash / tolerance
Mappercart_eventmapper statebank / IRQ / PRG RAM

Modes and budget

  • cpu-only: Klaus/hello first, zero mismatches before anything else.
  • frame-only: per-frame hash, good for NROM games.
  • scanline: PPU state level, for test ROMs.
  • audio: per-sample or hash tolerance.
  • full: bus + PPU + APU + mapper.

Performance budget: Verilator + REF at least 106 cycles/s; stop at the first mismatch and keep a window around it. FPGA compares frames/hashes only; dot-level comparison stays in simulation.

REF independence is the current risk: the NEMU frontend and REF still share some PPU/APU code, so REF itself is provisional. Keep calibrating against Klaus, external test ROMs and hardware captures, or DiffTest may be “wrong together”.
12 · Golden hashes

Golden frames and hashes: read before changing output

Golden hashes anchor the regression. Any change that alters output must explain why the hash moved; never update the hash just to make a test pass.

ObjectHash / valueScope
RTL title frame41e8ebc137e3b8ede2f0adf915956fb9454346e9454e358c6dad2ee5a58f5a33FALLING, 256×240, same as NEMU
NEMU title frame41e8ebc137e3b8ede2f0adf915956fb9454346e9454e358c6dad2ee5a58f5a33Same, byte-identical
REF 60-frame frame hash67667b1cbc4c1cf3Bundled NROM game, REF/frontend parity
REF 60-frame audio hashe78422afbcb92ac3Same
RTL Klaus end pointPC=0x3469Functional test, not cycle test

Reproduce

shell
$ ./NEMU/build/6502EMU --headless --no-audio --frames=300 \
    --screenshot=/tmp/nemu-title.ppm roms/falling.nes
$ ./sim/game/run.sh roms/falling.nes /tmp/rtl-title.ppm
$ shasum -a 256 /tmp/nemu-title.ppm /tmp/rtl-title.ppm
Compare shape and pixels before comparing file hashes: different tools may emit different PPM headers (comments, maxval formatting). The repository's 41e8… comes from its own capture tooling; the comparison on this site uses the same pixel data.
13 · GEM6502

GEM6502: being rewritten, do not overrate it

GEM6502 targets a gem5-style, event-driven architecture and timing platform: clock domains, resource contention, DMA arbitration, checkpoints, causal statistics and independent RTL calibration. The current implementation is still a legacy instruction-driven functional/cycle model.

It can do nowIt cannot do yet
Load NROM PRG, run instructions, print registers/cycle statsNo completed timing CPU, timing bus or calibrated chip profile
SDL player, PPM frames, MMC3 game regressionThe event queue does not drive normal execution yet; not a chip-level timing model
Compare traces against NEMUNot a pre-silicon signoff or RTL timing substitute
shell
$ cd GEM6502
$ make
$ make test
$ ./gem6502 run /tmp/gem-demo.bin 1000
$ ./gem6502 stats /tmp/gem-demo.bin
$ ./gem6502 play ../roms/stallar.nes

Target specification (Chinese): requirements.md; architecture and coding rules: coding-guide.md. Those documents describe target capabilities, not implemented features.

14 · Synthesis

Synthesis & area: 1.02M generic cells

Per-module synthesis uses Yosys 0.60 with read_verilog -sv -DSYNTHESIS → hierarchy → synth -flatten -noabc → stat. -noabc is used because the full PPU combinational renderer is too large for ABC mapping; the counts are generic cells.

shell
$ yosys -s rtl/scripts/synth_open6502.ys
ModuleGeneric cellsNotes
open6502_cpu4,138Small
open6502_apu1,855—
open6502_dmc828—
open6502_mapper7456 mappers
open6502_oam_dma154—
open6502_wram37,003Flip-flop implementation
open6502_bus171—
open6502_clocks360—
open6502_video_timing164—
open6502_controller19—
open6502_difftest_bridge65—
open6502_ppu975,919Dominant
Hierarchical sum1,021,421—

PPU breakdown

975,919 cells 84,224 flip-flops 840,701 muxes 40,283 AND 9,301 OR 674 XOR

Most of the area is the expanded chr[8192], vram[2048], oam[256] and pal[32] storage plus per-pixel/attribute mux trees. An FPGA flow must map them to BRAM and shrink the combinational sprite scan.

Caveats you must read together

  1. These are generic-cell estimates, not placed-and-routed area.
  2. SYNTHESIS skips memory reset loops; simulation still initialises them.
  3. SYNTHESIS limits the PPU sprite scan to 8 sprites for runtime; simulation scans all 64.
  4. Full top-level flatten did not finish within 600 seconds; the table is a per-module sum, not one flattened result.
  5. No timing closure, LUT mapping, BRAM mapping or ASIC standard-cell mapping has been done.

55nm planning estimate

ScenarioDie areaNotes
Current RTL, flip-flop memories4–7 mm²Not acceptable
SRAM + PPU refactor1.2–2.0 mm²Planning target
Recommended planning value~1.5 mm²Used for the cost model

At 1.5–2.0 mm² and 55nm, unit cost at volume is roughly USD 0.3–0.7 (die + package + test), with mask/NRE around USD 150k–400k+. These are planning numbers, not quotes.

15 · Tapeout

Toward 55nm: four gates, no skipping

The roadmap is not a schedule; it is an acceptance order: NEMU → RTL → FPGA → 55nm ASIC. A later stage may not hide an earlier failure. Without FPGA validation, physical design should not start.

StagePurposeCurrent statusExit gate
1. NEMUPlayable reference modelWorkingGames playable, Klaus PASS, golden frames stable
2. RTLSystemVerilog SoCFunctional prototypeMulti-game frame match, no unexplained divergence, deterministic regression
3. FPGAReal board prototypeNot startedBitstream runs a game; video/audio/input stable
4. ASIC55nm tapeoutPlanningTiming/DFT/DRC/LVS clean; shuttle and funding secured

Before RTL → FPGA

  1. Add bus transaction strobes for every peripheral.
  2. Make CPU cycle timing accurate enough for NMI/DMA-sensitive games.
  3. Replace PPU flip-flop storage with BRAM-friendly arrays.
  4. Rewrite sprite selection as a sequential scan.
  5. Rewrite background rendering as a fetch/shift pipeline.
  6. Complete DMC bus arbitration.
  7. Add deterministic frame-index DiffTest.
  8. Complete full-SoC synthesis and timing constraints.

Before FPGA → ASIC

  1. Replace BRAM with 55nm SRAM macros.
  2. Insert DFT/scan and set coverage targets.
  3. Define clock/reset/power intent.
  4. Synthesize with the 55nm standard-cell library.
  5. Run place-and-route and timing closure.
  6. Run DRC/LVS clean.
  7. Define package, pad ring and ESD.
  8. Secure a foundry shuttle and funding.
Non-negotiable: no commercial ROMs or proprietary PDK data in the repo; no tapeout claims before timing/DFT/DRC/LVS are clean; golden hash changes need review; do not delete tests to make a change pass.
16 · Troubleshooting

Troubleshooting: find your symptom first

These are the most common failures. First decide whether you are running NEMU, GEM6502 or RTL — their dependencies and outputs are completely different.

1. SDL2 not found, or sdl2-config missing

NEMU and the GEM6502 player need SDL2. The CLI can build without it, but play, the window and audio will be missing.

shell
$ brew install sdl2
# Debian/Ubuntu:
$ sudo apt install -y libsdl2-dev

If it is installed but still not found, make sure sdl2-config --cflags --libs is on PATH. GEM6502's Makefile probes it through that command and falls back to a no-UI build.

2. Verilator link fails with Undefined symbols ... __cxa_*

This is a known macOS mismatch between Verilator-generated code and the C++ runtime. The repo scripts explicitly select clang++, the macOS SDK and Homebrew LLVM's libc++. If your LLVM version differs, find the real path and override it:

shell
$ ls /opt/homebrew/Cellar/llvm/*/lib/c++
$ LIBCXX_DIR=/opt/homebrew/Cellar/llvm/<version>/lib/c++ \
    ./sim/game/run.sh roms/falling.nes /tmp/falling-rtl.ppm

If you only need functional verification, use Icarus first: cd rtl && make sim avoids Verilator's C++ link path.

3. make sim is slow and noisy

It compiles and runs 28 testbenches, so it is not a silent command. Run make lint first to rule out syntax errors, then redirect: make sim > /tmp/rtl-sim.log 2>&1 and finish with grep -i fail /tmp/rtl-sim.log.

4. The game runs but stays on the title screen

Most ROMs need START, not any key. NEMU's default START is V and Select is C; the GEM6502 player uses Enter / Backspace. Make sure the window has focus and the player is not paused (press P in GEM6502).

5. No sound

Check that you did not pass --no-audio (the headless screenshot commands do). GEM6502 needs an SDL2 audio device; on Linux check ALSA/PulseAudio. If opening the device fails, the player prints the SDL error and continues without audio by design.

6. RTL has no window and no sound

RTL is an SoC simulation, not a desktop emulator. It captures PPM frames through Verilator and has no SDL frontend; audio is 16-bit samples/sigma-delta only. To play on a desktop, use NEMU or GEM6502.

7. My SHA does not match the docs

Compare pixels before file bytes: PPM headers can differ between tools. Convert both to PNG and compare pixels, or generate with the repo's own capture scripts. The hashes in the docs come from the repository toolchain; confirm the format before comparing across tools.

8. Pillow is missing, so PPM → PNG fails

On macOS use sips -s format png /tmp/frame.ppm --out /tmp/frame.png, or install Pillow with python3 -m pip install Pillow. If you only want to look at an RTL frame, Preview can open PPM directly.

Still stuck?

When filing an issue, include: OS and version, the exact command, the full error, clang --version / verilator --version, and which path you are on (NEMU / GEM6502 / RTL). Use the GitHub issue or PR template; specific information gets reproduced faster.

17 · Contributing

Contributing: start with a verifiable small problem

Read the licence first: the root licence has not been published. The maintainers explicitly ask contributors not to contribute code until the root licence and contribution terms are published. ROMs are MIT; ASIC contributions must not upload PDKs, SRAM compiler output or proprietary standard-cell libraries.

Workstreams

WorkstreamTypical tasksEntry point
CPU / busCycle timing, NMI/DMA interaction, bus strobes, Klaus/nestestrtl/cpu/, rtl/bus/
PPUFetch/shift pipeline, sprite evaluation, open bus, mirroring, frame comparisonrtl/ppu/
APU / DMCFrame sequencer, sweep/envelope edges, DMC arbitrationrtl/apu/
Cartridge / mapperBank/IRQ timing, MMC3 A12, iNES/NES 2.0rtl/cart/
FPGAYosys synthesis, BRAM inference, timing, VGA/HDMI, audiortl/fpga/
ASIC / 55nmSRAM, DFT, clock/reset/power, packagedocs/55nm-tapeout-roadmap.md
Software / CILockstep DiffTest, frame index, CI, repro scriptssim/

Before you submit

shell
$ cd rtl
$ make lint
$ make sim
$ cd ..
$ ./sim/difftest/run.sh
$ ./sim/difftest/run_alu.sh
  • Use English commit messages and English repository docs; keep changes small and reversible.
  • Add/update tests before changing RTL behaviour; state the verification evidence in the PR.
  • Do not change golden hashes to “fix” a test; do not delete tests to make a change pass.
  • Prefer forward fixes over reverts.
  • No commercial ROMs, BIOS files or proprietary PDK data.

Good first issues

  • Add a unit test for PPU $2007 palette read behaviour.
  • Add frame-index assertions to sim/game.
  • Add a controller A/B/Select/Start order test.
  • Rewrite sprite selection as a sequential scan to remove the big combinational mux.
  • Add deterministic frame-hash output to DiffTest.
18 · Further reading

Further reading: find docs by goal

Repository docs are maintained in English; this page is the navigable version. When you finish here, the next step is usually one of these source documents.

Found a documentation bug? Edit the matching file under docs/, or open a PR against this page's source. Documentation needs reproducible evidence just like code.