6502 IRQ question

This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade.
View original topic
6502 IRQ question
by on (#16183)
assuming irq is pending and IRQ-disalbed flag is set,
and now clear the I flag(cause by CLI or RTI), which of the follows will happen:
1: switch to IRQ routine immediately after CLI or RTI
2: execute one instruction following CLI or RTI, then go to IRQ routine.

thx.

by on (#16184)
For CLI: #2, since the status is the I flag is polled to determine if the program is to interrupt before the CLI instruciton actually clears the flag (since the flag is cleared in the last cycle of CLI)

For RTI: #1, since the I flag is pulled from the stack near the start of the instruction -- the I flag will be its new value when it is polled on the last cycle of the instruction.

by on (#16201)
ah, I forgot the PLP.
Is it same as RTI ?

by on (#16203)
Informal tests I've run indicate that PLP is like SEI/CLI rather than RTI.

by on (#16204)
So in other words, RTI is handled just like a PLP then RTS, except a couple cycles faster, right?

by on (#16210)
tepples wrote:
So in other words, RTI is handled just like a PLP then RTS, except a couple cycles faster, right?


RTI does not change the return address once pulled from the stack.

RTS increments the return address by 1 (since JSR pushes an address 1 less than what you'd expect)


So if you try to PLP + RTS instead of doing an RTI (or vice versa), you'll end up returning to the wrong spot and possibly crashing.

But aside from that detail... yeah.

darklink wrote:
ah, I forgot the PLP.
Is it same as RTI ?


You might want to look at the instruction layouts in this doc to see what each instruction does during each of its cycles:

http://nesdev.com/6502_cpu.txt

The reason the IRQ might be delayed by one instruction is because the I flag has to be cleared BEFORE the last cycle of the instruction in order for an IRQ to trip immediately after that instruction. (Likewise, the I flag must be set before the last cycle of the instruction for the IRQ to be prevented -- so it's possible for an IRQ to trip immediately after a SEI instruction and have the I flag set when pushed to the stack!)

If you look at PLP and CLI -- they both change processor status on the last cycle of the instruction -- hence their delay. RTI, however, changes it before the last cycle, so there's no delay.


EDIT -- actually it doesn't look like CLI/SEI are listed on that doc because they're basic implied addressing. But logically, since the first cycle of CLI/SEI is fetching the opcode, the flag couldn't be changed until the second (last) cycle.

PLP and RTI are in that doc though.