Sub topic 1
I/O Interface Modules and Device Registers
Prerequisites
This chapter assumes you know basic computer organization (CPU, registers, memory, and buses), the instruction cycle (fetch, decode, execute), and binary and hexadecimal numbers. You should also read C bitwise operators such as & and |.
The I/O Interface Module
An I/O interface module is a circuit between the CPU and a peripheral device such as a keyboard, disk, or serial port. The device and the CPU run at different speeds and use different signal formats, so the module translates between them.
Each module exposes three kinds of registers:
- Data register: holds the byte being transferred.
- Status register: holds flags, such as a "ready" bit that is set when data is available.
- Control register: holds settings written by the CPU, such as enabling interrupts.
Memory-Mapped and Isolated I/O
The CPU reaches these registers in one of two ways.
- Memory-mapped I/O assigns registers addresses in the normal memory space. The CPU uses ordinary load and store instructions.
- Isolated (port-mapped) I/O uses a separate I/O address space with dedicated instructions, such as
INandOUTon x86.
Programmed I/O and Polling
In programmed I/O, the CPU checks the status register in a loop until the device is ready. This is called polling.
#include <stdint.h>
/* Hypothetical memory-mapped device registers */
#define STATUS_REG (*(volatile uint8_t *)0x4000)
#define DATA_REG (*(volatile uint8_t *)0x4001)
#define READY_BIT 0x01u
uint8_t read_byte(void) {
while ((STATUS_REG & READY_BIT) == 0) {
/* busy-wait: the CPU does no useful work here */
}
return DATA_REG;
}The volatile qualifier stops the compiler from caching the status value, so each loop check reads the hardware.
Polling is simple, but the CPU spends its time in the loop even when the device is slow.
Interrupt-Driven I/O
In interrupt-driven I/O, the device sends an interrupt request when it needs service. The CPU then runs an interrupt service routine (ISR) and returns to its previous work.
Interrupt-driven I/O removes the polling loop, so the CPU does useful work until the device needs it.
Exercise
A device sets its ready bit at 0x4000 bit 0. Why does read_byte read DATA_REG only after the loop ends?
Show answer
The loop exits only when the ready bit is 1, which means the device has placed a byte in the data register. Reading earlier could return stale or invalid data.