Sub topic 3
Programmed I/O and polling
This chapter assumes you know the instruction cycle, how a CPU reads and writes registers and memory over a bus, and basic hexadecimal and bit masking. It also assumes you have seen the idea of device registers (status, control, data) and of memory-mapped versus isolated addressing from the previous chapters. Here we use both ideas to build the simplest way a CPU can talk to a device.
What programmed I/O means
In programmed I/O, the CPU runs a program that does everything about a transfer. It asks the device whether it is ready, waits if it is not, moves each data item itself, and decides when the transfer is finished. The device only supplies a status flag and a data register. It does not interrupt the CPU and it does not touch memory.
The technique that checks the status flag over and over is called polling. A poll is one read of the status register followed by a test of the relevant bit.
Programmed I/O is the baseline for the next two techniques. Interrupt-driven I/O removes the waiting loop. DMA removes the per-word involvement of the CPU. To understand what they improve, you need to see exactly what the CPU does here.
The basic polling loop
The device exposes a status register and a data register. One bit of the status register, here called READY, says whether the data register holds a valid byte. The CPU reads the status register in a loop until the bit is 1, then reads the data register.
/* Hypothetical memory-mapped device registers */
#define STATUS_REG (*(volatile unsigned char *)0x4000)
#define DATA_REG (*(volatile unsigned char *)0x4001)
#define READY_BIT 0x01
unsigned char read_byte(void) {
while ((STATUS_REG & READY_BIT) == 0) {
/* busy-wait: the CPU does nothing useful here */
}
return DATA_REG;
}Three details matter here.
STATUS_REG & READY_BITisolates one bit. Other bits in the status register, such as error flags, are ignored by this test.volatiletells the compiler that the register can change without any write by the program. Without it, the compiler may readSTATUS_REGonce, keep the value in a CPU register, and turn the loop into an infinite loop or remove it.- Reading
DATA_REGis usually more than a read. On most devices it also clears READY, which tells the device that the byte was taken and it may load the next one. This is a side effect of the access itself.
The sequence of steps
The loop above is one case of a general protocol. For input, the steps are:
- The CPU reads the device status.
- If the device is not ready, go back to step 1.
- If the device is ready, the CPU reads the data register into a CPU register.
- The CPU stores that value to memory, if the data is to be kept.
- The CPU checks whether more data is needed. If so, go back to step 1.
For output, the roles reverse. The CPU waits until the device reports that it can accept data (often a bit called TXREADY or BUSY cleared), writes the data register, and moves on. A write to the data register typically clears TXREADY until the device has consumed the value.
#define STATUS_REG (*(volatile unsigned char *)0x4000)
#define DATA_REG (*(volatile unsigned char *)0x4001)
#define TX_READY 0x02
void write_byte(unsigned char value) {
while ((STATUS_REG & TX_READY) == 0) {
/* wait until the device can take another byte */
}
DATA_REG = value;
}Every word passes through the CPU
In programmed I/O, data goes device → CPU register → memory. A block of 1000 words needs 1000 passes through the loop. Each pass costs several instructions: the status read, the mask and compare, the branch, the data read, the store, and the counter update. For a block transfer, the CPU therefore executes at least one status read and one data transfer per word, and often many more status reads while it waits.
This is why the technique is called programmed: the CPU's own instructions carry the data. It is also the reason the transfer rate is bounded by how fast the CPU can run the loop, not only by how fast the device can supply data.
Busy-waiting versus periodic polling
Polling comes in two forms that behave very differently.
Busy-waiting spins in a tight loop until the device is ready, as in read_byte. The CPU can do nothing else for the whole duration of the transfer. If a device delivers one byte every 100 µs, a 1000-byte transfer holds the CPU for 100 ms, and almost all of that time is wasted status reads. CPU utilization on useful work during the transfer is close to zero.
Periodic polling lets the CPU do other work and check the device at intervals, for example from a timer tick or between units of other work. This frees time, but it creates a new constraint. The CPU must poll often enough that no data is lost. If the device holds only one byte in its data register and the next byte arrives before the CPU has read the first, the first is overwritten. This is called an overrun.
The minimum polling rate is therefore set by the device:
- Polls per second ≥ (data rate in bytes per second) ÷ (bytes the device can hold between polls).
- The polling interval must be at most the time the device takes to produce one unit that the CPU must collect.
A slow device such as a mouse needs only tens of polls per second. A fast device such as a disk needs hundreds of thousands, and that is where polling stops being practical.
Calculating polling overhead
The CPU time consumed by periodic polling is the number of polls per second multiplied by the cycles per poll, divided by the clock rate. The cycles per poll include the status read, the test, and any bookkeeping, and the question usually gives them as one number.
Consider a 500 MHz CPU where each poll costs 400 cycles. Three devices:
- A mouse that must be polled 30 times per second.
- A floppy disk that sends 16-bit (2-byte) units at 50 KB/s, so it needs 50,000 ÷ 2 = 25,000 polls per second.
- A hard disk that sends 16-byte chunks at 4 MB/s, so it needs 4,000,000 ÷ 16 = 250,000 polls per second.
cpu_hz = 500_000_000
cycles_per_poll = 400
devices = [
("mouse", 30), # polls per second
("floppy", 50_000 // 2), # 2 bytes per poll at 50 KB/s
("hard disk", 4_000_000 // 16), # 16 bytes per poll at 4 MB/s
]
for name, polls_per_s in devices:
fraction = polls_per_s * cycles_per_poll / cpu_hz
print(f"{name:10s} {polls_per_s:>8d} polls/s -> {fraction:.4%} of CPU time")The output is:
mouse 30 polls/s -> 0.0024% of CPU time
floppy 25000 polls/s -> 2.0000% of CPU time
hard disk 250000 polls/s -> 20.0000% of CPU timePolling a mouse is almost free. Polling a hard disk takes a fifth of the CPU, and the polls are charged whether or not data is ready. This is the central weakness of polling: the cost depends on the required polling rate, not on how much data actually arrives. A device that is idle for long stretches still costs the same.
The later chapter on performance analysis uses this same pattern for interrupts and DMA, so the structure is worth remembering: rate × cycles per event ÷ clock frequency.
Edge cases and failure modes
Missing volatile or an equivalent. The compiler may hoist the status read out of the loop. The symptom is a program that hangs only when optimization is turned on. In hardware terms, the same issue appears if a cache serves the status read. Device registers must be in uncached address ranges.
Clearing semantics. Some devices clear READY when the data register is read. Others need an explicit write to the control register. If you read the data register twice to "check" it, you may consume a second byte or trigger a side effect. Read it exactly once per item.
Status bits that mean different things. A status register usually holds more than READY. An error bit (parity error, framing error, overrun) can be set while READY is also set. Code that checks only READY will accept corrupt data. A careful driver reads the status once into a local variable and tests all bits from that one snapshot, because a second read may see a different state.
Infinite waits. If the device is absent or faulty, READY never arrives and the loop never exits. A bounded loop with a timeout gives the program a way out.
#define STATUS_REG (*(volatile unsigned char *)0x4000)
#define DATA_REG (*(volatile unsigned char *)0x4001)
#define READY_BIT 0x01
#define ERROR_BIT 0x80
/* Returns 0 on success, -1 on timeout, -2 on device error. */
int read_byte_checked(unsigned char *out, unsigned long max_polls) {
while (max_polls--) {
unsigned char status = STATUS_REG; /* one snapshot */
if (status & ERROR_BIT) {
return -2;
}
if (status & READY_BIT) {
*out = DATA_REG;
return 0;
}
}
return -1;
}Several devices. A single loop that polls device A and then device B delays B whenever A is slow. If A is busy-waited, B is starved. The order of polling also acts as a fixed priority: the device checked first is served first. Fixing this priority is one reason software polling is sometimes used to identify the source of an interrupt, which a later chapter covers.
Latency. Even when the CPU is not busy-waiting, the time from "device ready" to "CPU notices" depends on the polling interval. The worst case equals one full interval. Real-time requirements can rule out periodic polling for this reason.
When programmed I/O is the right choice
Programmed I/O has real advantages. The hardware is simple, the behavior is deterministic, and no interrupt machinery is needed. It suits very small systems, boot code that runs before interrupts are set up, and devices that are fast enough that the wait is shorter than the cost of an interrupt.
It is the wrong choice when the device is slow compared with the CPU, because the CPU wastes most of its time waiting, or when the device is fast and continuous, because the polling rate then consumes a large share of the CPU. The next chapter shows how interrupts remove the waiting.
| Aspect | Busy-wait polling | Periodic polling |
|---|---|---|
| CPU during wait | Fully occupied | Free between polls |
| Risk | Wasted CPU, hangs if device fails | Overrun if polled too slowly |
| Response latency | Very small | Up to one polling interval |
| Cost driver | Duration of the transfer | Polling rate × cycles per poll |
Exercise
A 1 GHz CPU polls a device. Each poll takes 500 cycles. The device sends 8-byte chunks at 2 MB/s and must be polled once per chunk to avoid overrun. What fraction of CPU time does polling use?
Show answer
Polls per second = 2,000,000 ÷ 8 = 250,000. Cycles per second spent polling = 250,000 × 500 = 125,000,000. Fraction = 125,000,000 ÷ 1,000,000,000 = 0.125, so 12.5% of CPU time.
Exercise
A driver waits for READY with while ((STATUS_REG & READY_BIT) == 0) {} and STATUS_REG is declared as a plain unsigned char * without volatile. With optimization on, the program hangs. Give the cause and the fix.
Show answer
The compiler assumes that memory not written by the program does not change, so it reads the status register once and reuses the value, which turns the loop into an infinite loop. The fix is to declare the register access as volatile, which forces a fresh read on every iteration.
Exercise
A device holds one byte in its data register and produces a new byte every 200 µs. What is the minimum polling rate to avoid overrun, and what happens if the CPU polls every 300 µs?
Show answer
The CPU must poll at least once per 200 µs, which is 5,000 polls per second. If it polls every 300 µs, some bytes are overwritten by the next byte before the CPU reads them, so data is lost (an overrun).