Skip to content

Commit

Permalink
prevent NMI from occurring multiple times at almost the same timing
Browse files Browse the repository at this point in the history
  • Loading branch information
ichirin2501 committed Feb 9, 2024
1 parent bb7afae commit 7affd81
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
5 changes: 5 additions & 0 deletions nes/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,11 @@ func (cpu *CPU) pollInterrupts() {
}
}

func (cpu *CPU) clearNMIInterruptState() {
cpu.nmiSignal = false
cpu.nmiTriggered = false
}

func (cpu *CPU) Read(addr uint16) byte {
cpu.bus.RunDMAIfOccurred(true)
cpu.pollInterruptSignals()
Expand Down
6 changes: 3 additions & 3 deletions nes/instruction.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,10 @@ func (cpu *CPU) brk() {
// As far as I checked with cpu_interrupts_v2/2-nmi_and_brk.nes,
// it seems to be expecting the NMI edge detector timing.
if cpu.nmiSignal || cpu.nmiTriggered {
cpu.nmiSignal = false
cpu.push(cpu.P.Byte() | 0x30)
cpu.P.SetInterruptDisable(true)
cpu.PC = cpu.read16(0xFFFA)
cpu.clearNMIInterruptState()
} else {
cpu.push(cpu.P.Byte() | 0x30)
cpu.P.SetInterruptDisable(true)
Expand Down Expand Up @@ -504,7 +504,6 @@ ref: https://www.nesdev.org/wiki/CPU_interrupts#IRQ_and_NMI_tick-by-tick_executi
*/
func (cpu *CPU) nmi() {
cpu.interrupting = true
cpu.nmiSignal = false

cpu.Read(cpu.PC) // dummy read
cpu.Read(cpu.PC) // dummy read
Expand All @@ -513,6 +512,7 @@ func (cpu *CPU) nmi() {
cpu.P.SetInterruptDisable(true)
cpu.PC = cpu.read16(0xFFFA)

cpu.clearNMIInterruptState()
cpu.interrupting = false
}

Expand All @@ -522,10 +522,10 @@ func (cpu *CPU) irq() {
cpu.Read(cpu.PC) // dummy read
cpu.push16(cpu.PC)
if cpu.nmiSignal || cpu.nmiTriggered {
cpu.nmiSignal = false
cpu.push(cpu.P.Byte() | 0x20)
cpu.P.SetInterruptDisable(true)
cpu.PC = cpu.read16(0xFFFA)
cpu.clearNMIInterruptState()
} else {
cpu.push(cpu.P.Byte() | 0x20)
cpu.P.SetInterruptDisable(true)
Expand Down

0 comments on commit 7affd81

Please sign in to comment.