Skip to main content

Lesson 18 of 26 · 11 min read

I/O devices, interrupts, DMA, and device drivers

See how the CPU talks to hardware registers, replaces wasteful polling with interrupts, offloads memory copies to DMA engines, and isolates hardware details inside drivers.

Four I/O concepts: Status / Cmd registers, Interrupt wakeup, DMA engine, and Device driver.
Interrupts and DMA keep the CPU busy on compute while device drivers hide vendor register details.
Course syllabus · lesson 18 of 26
In this lesson

A disk read begins as a request from software and ends with bytes available in memory. Between those events, a device has to receive the command, transfer the data, and report the result. These jobs compete for CPU time and bandwidth in different ways. Interrupts let the CPU work while a request is pending. Direct memory access lets the device move the bytes while the CPU works.

Canonical device with Status, Command, and Data registers comparing CPU-wasting PIO polling against interrupt-driven DMA that overlaps I/O with Process B compute inside a uniform device driver layer.
Open full-size diagram
Interrupts keep the CPU free during slow device waits, and DMA offloads bulk data copies between RAM and device.

Follow a DMA read to completion

CPU set up DMA, Device read queued, RAM buffer readyCPUset up DMADeviceread queuedRAMbuffer ready

Step 1 of 3

Program the device

The driver supplies a destination buffer and transfer size to the device, then starts the read.

The path from the CPU to a device

In the bus hierarchy used by OSTEP, the main memory path is close to the CPU and sized for high traffic. An I/O interconnect connects controllers that need substantial bandwidth, and other controllers bridge lower-bandwidth peripheral links. A PCIe storage controller, for instance, can exchange data with memory through the host interconnect. A USB keyboard talks to a host controller over USB, and the host controller is the device the CPU programs. Modern interconnects often use point-to-point links. The hierarchy remains useful because it shows where requests share bandwidth and where protocol translation happens.

A canonical device separates its hardware interface from its internal work. The interface presents a status register, a command register, and a data register. The status register reports conditions such as ready, busy, or error. The command register starts an operation, and the data register transfers payload in a simple programmed-I/O device. Real controllers can have many registers, internal buffers, and command queues in RAM. The same questions still apply. How does the driver describe work? How does it tell the device that work is available? How does it learn the result?

The processor can reach some devices through special I/O instructions, such as x86 in and out. With memory-mapped I/O, an address range routes processor loads and stores to device registers. A register read can acknowledge an event or advance a FIFO. A register write can start work. Drivers use the platform's I/O accessors to get the correct access size and ordering, including when a write that starts an operation must follow earlier writes that describe it.

Polling and programmed I/O

In a simple write protocol the driver polls status until the controller is ready, writes the payload through the data register, then writes the command. It polls again until the operation has finished and checks status for errors. A read protocol can issue its command first, wait for a data-ready state, and then read the payload. The device specification determines which order is valid and whether the data register needs repeated accesses.

CPU-driven transfers are called programmed I/O, or PIO. Polling is the separate decision to have the CPU repeatedly check for a condition. A controller can interrupt when bytes are ready and still require the CPU to read every word. A driver can also poll for a DMA completion whose payload has already reached memory. When comparing designs, account for notification and data movement separately.

If a 3 GHz core continuously polls for a 10 ms completion, the interval spans about 3 * 10^9 * 0.010 = 30,000,000 clock cycles. A clock cycle is the unit used here because instruction throughput and register-read latency vary. One MMIO read can take many cycles. The useful quantity is the amount of CPU time made unavailable to other work during the polling interval.

Interrupts, hybrid polling, and coalescence

For interrupt-driven I/O, the driver records an outstanding request and starts the device. A caller that needs the result can block and let the scheduler run another runnable process. The controller reports completion via an interrupt, which can arrive as a hardware signal or a message. The CPU enters a kernel handler. The handler identifies the source, acknowledges it according to the device protocol, and records or schedules processing of the completed requests. Completing a request can wake a blocked process, placing it in the runnable state. When that process actually runs is a scheduling decision.

Completion can arrive before the caller has blocked. As with a condition wait, a correct driver checks a recorded completion state and coordinates its transition to sleep with the completion path. If the interrupt handler records completion first, the caller sees it and skips the wait. A protocol that relies on notification alone can lose an early completion and sleep while the result is already available.

For a short operation, a few polls can cost less than handling an interrupt and rescheduling the blocked caller. For a long operation, spinning can waste time another process could use. A hybrid can poll for a limited interval, then arrange to be notified if the work remains outstanding. The transition must handle a completion arriving while notifications are being armed, typically by checking device state again according to its protocol.

A different problem occurs at very high event rates. If each packet causes an interrupt and the CPU spends all its time handling them, applications that would consume the packets can be starved. A driver can mask notifications for a busy queue and process a bounded batch through polling. After draining the queue it can reenable notifications, again guarding against a completion arriving during the transition. The batch budget helps preserve time for the application to run.

With interrupt coalescence, the device reports a group of completions in one interrupt, often when a count threshold or a timer expires. If processing an interrupt has a fixed cost of C and it covers k completions, that fixed cost averages C / k per completion. The individual completion work is still due. For example, 100,000 completions per second with a fixed 2 microsecond interrupt cost would consume 0.2 CPU seconds per second in that fixed cost alone. Groups of eight reduce it to 0.025 CPU seconds per second if every interrupt carries a full group. At low rates the timer lets a partial group drain, and the first member of a group can wait longer to be reported. Coalescence trades some notification latency for lower interrupt overhead.

Direct memory access and buffer ownership

A DMA engine moves bytes between a device and main memory without a CPU instruction per word. It may be integrated into the device controller. For a read, the driver prepares writable buffers and maps them for device access. The DMA address can be a bus address or an address translated by an I/O memory management unit. The mapping supplies the address that the device uses and remains valid while the operation is pending. The process's ordinary virtual address is meaningful to the CPU and is generally unsuitable as a device address.

The driver builds a descriptor with the DMA address and transfer length. A storage request also needs an operation, storage location, and usually an identifier. A scatter-gather request can describe several memory ranges so a contiguous logical transfer can use separate buffer segments. In a ring-based controller, the driver fills free descriptor slots and updates a producer index or writes a doorbell register. The CPU must publish the descriptor contents before the doorbell tells the controller to fetch them.

The controller then fetches the descriptor and moves the payload over the interconnect. After a read succeeds, it records a completion with the request ID and status. The driver observes the completion, applies the platform's DMA synchronization rules, and only then exposes the received data to the caller. On a noncoherent system that can involve explicit cache maintenance. While a device owns a buffer, the CPU must respect the transfer direction and ownership rules. The buffer and its DMA mapping must survive until the device is finished accessing them. Freeing a buffer while DMA is pending can let the device write into memory now owned by something else.

DMA frees CPU cycles but still consumes interconnect and memory bandwidth. Small transfers may cost more to prepare and map than they save in copying. A steady stream of large requests amortizes setup and can overlap device work with CPU computation, until bandwidth, queue depth, or another resource limits throughput.

For example, consider an engine sustaining 2 GB/s while moving a 64 KiB payload. The payload alone takes about 33 microseconds at that rate. Queueing, descriptor fetches, device service, and completion processing add to the request latency. Four such transfers in flight can help hide gaps in the pipeline. They still share the same bandwidth if they travel over the same saturated link. Queue depth changes how much work can be outstanding, while link bandwidth bounds how much payload can cross per second.

What the driver hides

The file system translates a file read into requests for storage locations when the needed data is absent from memory. A block layer can queue or combine requests, and a driver translates those generic requests into the controller's commands, mappings, and completion protocol. Device-specific failure information is translated back into outcomes the upper layer can use. This separation lets the filesystem use a new storage controller without knowing its register layout.

Completion has a particular meaning at each layer. Finishing a DMA write into a controller's buffer can mean the controller has received the data. Completing a storage write also depends on the device contract, since some devices acknowledge while data remains in volatile cache. Software that requires durability uses the appropriate persistence operation in addition to the ordinary request notification.

Worked trace

Process A and process B each need 100 ms of computation on one core. A submits one storage request after its first 50 ms. Assume a 10 ms device service interval, 0.20 ms of CPU copying for PIO or 0.02 ms for DMA setup, and 0.03 ms of combined notification and scheduling overhead for the interrupt path. Treat setup and notification as sequential with respect to the overlapping interval, and omit any other scheduler overhead.

Code exampleTrace
Polling plus PIO
A computes                       50.00 ms
CPU copies data                   0.20 ms
CPU polls during device service  10.00 ms
A and B finish computing        150.00 ms
Total                           210.20 ms

Interrupt plus DMA
A computes                       50.00 ms
CPU prepares DMA                  0.02 ms
B computes during device service 10.00 ms
CPU handles completion            0.03 ms
A and B finish computing        140.00 ms
Total                           200.05 ms

The second path saves 10.15 ms of elapsed time. Of that, 10 ms comes from overlapping B's work with service, 0.18 ms from lower transfer overhead, and 0.03 ms is spent on notification and scheduling. The result assumes B is ready. If B had no work to do, the CPU could idle during service but A would still depend on the device's completion.

Change one input

Keep those assumptions and reduce the service interval from 10 ms to 0.01 ms. Then polling plus PIO takes 200 + 0.20 + 0.01 = 200.21 ms. Interrupt plus DMA still takes 200 + 0.02 + 0.03 = 200.05 ms, but nearly all of the advantage now comes from DMA reducing CPU copy overhead. To isolate the notification choice, hold DMA fixed. Polling adds 0.01 ms of CPU time for the wait, for a total of 200.03 ms, while the interrupt path still costs 200.05 ms. The measured crossover depends on what else could run and on the actual costs of waiting and waking. The next lesson examines hard disks and RAID.

Before you move on

Try it in your workspace

Trace a canonical polling loop vs. an interrupt-driven driver with DMA. Compute CPU cycles saved on a slow device and name when polling actually beats interrupts.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.