Sub topic 2
What happens when an interrupt occurs
This chapter assumes you know CPU registers, the instruction cycle (fetch, decode, execute), and how a subroutine call returns using the stack. It also assumes you can read hexadecimal addresses.
An interrupt is a signal from a device that asks the CPU to pause its current work and handle an event. The CPU services the device, then resumes the interrupted program.
The interrupt cycle
The CPU checks for interrupt requests after it finishes each instruction. If a request is pending and interrupts are enabled, the CPU:
- Saves the program counter and status flags on the stack.
- Identifies the device that raised the request.
- Loads the address of the Interrupt Service Routine (ISR) and jumps to it.
- Runs the ISR, then returns with a special instruction (such as
RETI) that restores the saved state.
Interrupt types
- Maskable interrupts (INTR) can be disabled by the CPU's interrupt-enable flag or by a per-device mask register.
- Non-maskable interrupts (NMI) cannot be disabled. Systems use them for urgent events such as power failure.
- Vectored interrupts let the device send a vector number on the data bus. The CPU uses that number to index a table of ISR addresses.
- Non-vectored interrupts use one shared request line. The CPU must poll devices to find the source, which is slower.
Daisy-chain priority
In a daisy chain, the acknowledge signal (INTA) passes from device to device. The device closest to the CPU gets the signal first. If it has a pending request, it takes the acknowledge and blocks the signal from passing on. Therefore, devices nearer the CPU have higher priority.
def daisy_chain_grant(requests):
"""Return the index of the device that receives the acknowledge, or None."""
for device_id, requesting in enumerate(requests):
if requesting:
return device_id # nearest device with a request wins
return None
print(daisy_chain_grant([False, True, True])) # prints 1Why DMA: moving blocks without the CPU
Interrupt-driven I/O still costs the CPU one interrupt and one ISR run per word. For a large block, that overhead adds up. A Direct Memory Access (DMA) controller solves this. The CPU gives the controller a start address, a byte count, and a direction. The controller then requests the bus, receives a grant, and moves the data itself. It interrupts the CPU once, when the whole block is done.
Exercise
A device sends 1,000 bytes. Interrupt-driven I/O costs one ISR per byte. If DMA costs one interrupt for the whole block, how many CPU interrupts does each method need?
Show answer
Interrupt-driven I/O needs 1,000 interrupts. DMA needs 1 interrupt at the end of the block.