The Bridge Between CPU and Devices
Your computer isn't just a CPU and memory โ it's connected to keyboards, mice, monitors, printers, network cards, USB drives, and countless other devices. The I/O system is the part of the operating system that manages communication between the CPU and all these devices.
I/O is one of the most complex parts of an operating system because every device is different. A keyboard sends data one character at a time. A hard drive transfers data in large blocks. A printer needs pages formatted in a specific way. The OS must handle all of these different communication styles through a unified interface.
How I/O Works
When a program needs to read from or write to a device, it makes a system call. The OS then:
- Checks if the program has permission to access the device.
- Passes the request to the appropriate device driver.
- The device driver translates the request into device-specific commands.
- The device performs the operation (reading data, printing a page, etc.).
- The device notifies the OS when it's done (usually via an interrupt).
- The OS returns the result to the requesting program.
This process involves both hardware and software working together in a carefully orchestrated dance.
Programmed I/O vs. Interrupt-Driven I/O
There are different ways the CPU can communicate with devices:
- Programmed I/O (Polling) โ The CPU repeatedly checks (polls) the device's status register to see if it's ready. It's like standing at the window asking "Is my food ready yet? Is it ready now? How about now?" Simple but wasteful โ the CPU could be doing other work instead of polling.
- Interrupt-Driven I/O โ The device sends an interrupt signal to the CPU when it's ready. The CPU stops what it's doing, handles the interrupt, and resumes its previous task. This is much more efficient โ the CPU doesn't waste time polling.
Modern systems almost exclusively use interrupt-driven I/O for most devices. Polling is only used for very fast devices where the overhead of an interrupt would be greater than the overhead of polling.
I/O Methods
The OS provides three main I/O methods:
- Synchronous I/O โ The program waits until the I/O operation completes. It's blocked from doing anything else. Simple to program but inefficient โ the CPU sits idle during the wait.
- Asynchronous I/O โ The program initiates the I/O and continues executing. The OS notifies the program when the operation completes. More complex to program but allows the CPU to do useful work while waiting.
- Direct Memory Access (DMA) โ A special hardware controller handles the data transfer between device and memory, without involving the CPU for every byte. The CPU sets up the DMA transfer and is free to do other work. DMA is used for high-bandwidth devices like disks and network cards.
DMA is essential for performance. Without it, the CPU would spend all its time copying bytes between devices and memory, leaving no time for actual computation.