Sub topic 4
Interrupt-driven I/O
This chapter explains how a device can tell the CPU that it needs attention, so the CPU doesn't have to keep asking. It assumes you know the instruction cycle (fetch, decode, execute), how a subroutine call uses the stack, and the idea of status, control and data registers from the earlier chapters on I/O interfaces and programmed I/O. The full details of the interrupt cycle and of priority schemes come in the next two chapters. Here the goal is the working model, the cost, and the mistakes that cause wrong answers in exams and wrong behavior in drivers.
The problem with polling
In programmed I/O the CPU runs a loop that reads a device's status register until the ready bit is set. The loop does no useful work. If a device produces a byte every millisecond and the CPU can run a million instructions per millisecond, nearly all of those instructions are spent asking "ready yet?".
Interrupt-driven I/O reverses the direction of the question. The CPU starts the I/O operation, then goes back to running other code. When the device is ready, it raises a signal on an interrupt request line. The CPU finishes its current instruction, pauses the running program, and runs a short routine that handles the device. That routine is the interrupt service routine (ISR), also called the interrupt handler. When the ISR returns, the interrupted program resumes where it left off.
An interrupt is therefore a hardware-initiated, asynchronous transfer of control to a handler, with the old context saved so it can be restored.
What the device and CPU each do
Three parties cooperate.
- The device interface sets its ready flag when data is available, and drives the interrupt request line if interrupts are enabled in its control register.
- The CPU samples the interrupt request line at one fixed point: at the end of each instruction. It never abandons an instruction halfway. If a request is pending and the CPU is willing to accept it, it starts the interrupt sequence instead of fetching the next instruction.
- The ISR, which is software, transfers the data, clears the cause of the request, and returns.
A device usually has two independent enable switches that must both be on:
- An interrupt-enable bit in the device's control register. This decides whether this device may raise requests at all.
- A CPU-wide interrupt flag (often called IF or the I bit). This decides whether the CPU will listen to maskable requests at the moment.
If either is off, the request is not serviced. This is a frequent reason that a "correct" driver does nothing.
A minimal interrupt-driven input driver
The program below shows the structure. The ISR stores each incoming byte into a ring buffer. The main program consumes bytes whenever it wants. The register addresses are hypothetical, and enabling interrupts is platform specific, so it is left as a comment.
#include <stdint.h>
/* Hypothetical memory-mapped device registers */
#define DATA_REG (*(volatile uint8_t *)0x4001)
#define BUF_SIZE 64u
static volatile uint8_t buffer[BUF_SIZE];
static volatile unsigned head = 0; /* written only by the ISR */
static volatile unsigned tail = 0; /* written only by main() */
/* Called by hardware through the interrupt vector, not by main() */
void device_isr(void) {
unsigned next = (head + 1) % BUF_SIZE;
uint8_t byte = DATA_REG; /* reading usually clears the request */
if (next != tail) { /* drop the byte if the buffer is full */
buffer[head] = byte;
head = next;
}
}
/* Returns 1 and stores a byte if one is available, else returns 0 */
int get_byte(uint8_t *out) {
if (tail == head) {
return 0;
}
*out = buffer[tail];
tail = (tail + 1) % BUF_SIZE;
return 1;
}
int main(void) {
/* enable the device interrupt and global interrupts (platform specific) */
uint8_t b;
for (;;) {
if (get_byte(&b)) {
/* process b */
}
/* otherwise the CPU does other useful work */
}
}Three details in this code matter in real systems.
volatiletells the compiler that these variables can change outside the normal flow of the program. Without it, the compiler may keepheadin a register inside themainloop and never see the ISR's updates.- Each index has exactly one writer. The ISR changes only
headandmainchanges onlytail. This avoids a race in which both sides update the same variable at the same time. - The ISR reads the data register. For many devices that read is what clears the interrupt request. If the ISR forgot to do it, the request line would stay active, and the CPU would re-enter the ISR immediately after returning. That would look like a hung system.
What the ISR must do, and what it must not do
A good ISR is short. While it runs, other interrupts of the same or lower priority are typically blocked, so a long ISR delays everything else and can cause data loss in other devices.
The ISR should:
- Save any registers it will change, if the hardware did not already save them.
- Identify and service the device: move the data, update the buffer.
- Clear the interrupt cause in the device, as the device's documentation requires.
- Restore the registers and execute the return-from-interrupt instruction.
It should avoid long loops, blocking waits, and calls that might themselves wait for I/O. If heavy processing is needed, the ISR records the event and lets the main program, or a lower-priority task, do the work later.
The return instruction differs from an ordinary subroutine return. It restores the saved flags as well as the program counter, so that the interrupted program sees exactly the machine state it had before.
Level-triggered versus edge-triggered requests
Interrupt signals come in two common forms.
| Property | Level-triggered | Edge-triggered |
|---|---|---|
| Request is seen when | The line is held at active level | The line changes from inactive to active |
| If the ISR does not clear the cause | Interrupt fires again right after return | Nothing more happens until the next edge |
| Sharing a line among devices | Easy: any device can hold the line active | Hard: two near-simultaneous edges can merge into one, so one request is lost |
| Main risk | Interrupt storm if the cause is not cleared | Lost interrupts if the CPU has them masked at the wrong time |
Exam questions usually assume a simple model in which each request is eventually serviced. Real hardware needs the distinction above.
Cost of interrupt-driven I/O
An interrupt is cheaper than polling when the device is slow, but each one carries a fixed cost. That cost has three parts:
- Interrupt latency: the time from the request being raised to the first instruction of the ISR. It includes finishing the current instruction, saving state, and finding the handler address.
- ISR body: the actual work of moving the data.
- Return: restoring state and resuming.
In calculation problems these are usually folded into one number, "cycles per interrupt". The CPU time consumed is then:
CPU fraction = (interrupts per second × cycles per interrupt) ÷ CPU clock rate
The number of interrupts per second depends on how much data one interrupt moves. With a one-word-per-interrupt design, the interrupt rate equals the device rate divided by the word size.
Worked example
A device delivers 1 MB/s. The CPU runs at 500 MHz. Each interrupt transfers one 4-byte word, and the total ISR cost, including entry and return, is 1000 cycles.
- Interrupts per second = 1,000,000 ÷ 4 = 250,000.
- Cycles spent per second = 250,000 × 1000 = 250,000,000.
- Fraction of the CPU = 250,000,000 ÷ 500,000,000 = 0.5, or 50%.
Half the CPU is gone, even though the device moves only 1 MB/s. The next chapters show how DMA brings this to a fraction of a percent by paying a similar cost once per block instead of once per word.
The script below does the same calculation and also finds the saturation point, the device rate at which the CPU spends all of its time in the ISR.
def interrupt_fraction(rate_bytes_per_s, word_bytes, isr_cycles, cpu_hz):
"""Fraction of CPU time spent servicing one-word-per-interrupt I/O."""
interrupts_per_s = rate_bytes_per_s / word_bytes
return interrupts_per_s * isr_cycles / cpu_hz
def saturation_rate(word_bytes, isr_cycles, cpu_hz):
"""Device rate (bytes/s) at which the ISR consumes 100% of the CPU."""
return cpu_hz / isr_cycles * word_bytes
cpu_hz = 500_000_000
frac = interrupt_fraction(1_000_000, 4, 1000, cpu_hz)
print(f"CPU time at 1 MB/s: {frac:.0%}")
print(f"Saturation rate: {saturation_rate(4, 1000, cpu_hz) / 1e6:.1f} MB/s")It prints 50% and a saturation rate of 2.0 MB/s. Above that rate, the CPU cannot keep up. Data will be lost unless the device has its own buffer or flow control.
When interrupts are worse than polling
Interrupt-driven I/O is not always cheaper. Consider a device that is ready almost all the time, such as a fast stream where a new word arrives every few cycles. Polling finds data on nearly every check, so almost no polls are wasted. An interrupt then adds the entry and return cost on top of every word. Interrupts win when the device is rarely ready, and they lose when events are so frequent that the fixed per-event cost dominates. This is why high-rate devices move to DMA.
A related exam point: during polling, the CPU is busy for the whole waiting time. With interrupts, the CPU is busy only for the interrupt handling time. The device's waiting time is free for other work.
Common errors
- Forgetting to clear the request. The ISR returns, the line is still active, and the ISR runs again forever.
- Leaving interrupts disabled. The CPU-wide flag is off, or the device's enable bit is off, so no interrupt arrives. Check both.
- Missing
volatile. The compiler caches a shared variable, and the main program never sees the ISR's changes. - Updating shared data in two places. If the ISR and main code both modify a counter such as
count++, the read-modify-write sequence can be interrupted halfway, and one update is lost. Use single-writer indices as above, or briefly disable interrupts around the update. - Counting only the ISR body. In calculation problems, check whether the stated cycles include interrupt entry and return. If a question gives them separately, add them.
- Ignoring the instruction boundary. An interrupt is recognized between instructions, not in the middle of one. A long instruction therefore adds to the worst-case latency.
- Treating the ISR like a normal call. The ISR is not called by the program. The hardware transfers control, and the saved state must include the flags.
What stays the same, and what changes
Compared with polling, the data path is the same: the CPU still reads the data register and stores the word itself. Interrupts change only the question of when the CPU does so. Every word still passes through a CPU register, and every word still costs CPU cycles. That per-word cost is what the DMA chapters remove.
Exercise
A device transfers 2 MB/s. Each interrupt moves one 4-byte word, and the ISR (including entry and return) takes 600 cycles. The CPU clock is 500 MHz. What fraction of CPU time goes to servicing the device?
Show answer
Interrupts per second = 2,000,000 ÷ 4 = 500,000. Cycles per second = 500,000 × 600 = 300,000,000. Fraction = 300,000,000 ÷ 500,000,000 = 0.6, so 60% of CPU time.
Exercise
A driver's ISR reads the data byte and stores it in a buffer, but the interrupt fires again and again as soon as the ISR returns, even though the device has no new data. Name the most likely cause and the fix.
Show answer
The ISR did not clear the interrupt request in the device, so the level-triggered line stays active. The fix is to perform the action that clears the request, such as reading the data register or writing the device's acknowledge bit, before returning.
Exercise
A main program loop reads a shared variable done that an ISR sets to 1. The program never exits the loop even though the interrupt has occurred. Give one likely cause in the code.
Show answer
The variable is not declared volatile, so the compiler keeps its value in a register and never rereads it from memory. Declaring it volatile makes each loop iteration reload the value that the ISR wrote.