Input, output and interrupts

Intermediate

Introduction

A computer is useless without its devices: keyboard, screen, disk, network card. They are thousands of times slower than the CPU and each works in its own way. The OS must talk to all of them, keep the CPU busy while it waits, and give programs one simple way to use them. This lesson shows how the hardware and the kernel meet: controllers, polling, interrupts, DMA and buffers.

How it works

Devices and controllers

Each device has a controller, a small circuit with a few registers: a status register (is it ready? did an error happen?), a command register and a data register. The CPU reaches them in one of two ways. With port-mapped I/O there are special instructions (in and out on x86), which are privileged. With memory-mapped I/O the registers have ordinary memory addresses, and the kernel reads and writes them like variables. Programs never do either: they use system calls, and a device driver in the kernel talks to the controller.

Polling, interrupts and DMA

MethodHow it worksCost
Pollingthe CPU reads the status register again and again until the device is readywastes CPU time, but simple and fast for devices that are always busy
Interrupt-driven I/Othe CPU starts the device and does other work; the device raises an interrupt when it is readyan interrupt costs some microseconds, but the CPU is free meanwhile
DMAa DMA controller copies a whole block between the device and memory, and interrupts once at the endthe best for big transfers: one interrupt per block, not one per byte

What happens at an interrupt

  1. The device raises an interrupt line. The CPU finishes the current instruction.
  2. The CPU saves the program counter and flags, switches to kernel mode, and uses the interrupt number to look up the address of the handler in the interrupt vector table.
  3. The handler runs: it reads the device's status, takes or gives the data, and tells the controller that the interrupt is handled.
  4. A return-from-interrupt instruction restores the saved state, and the interrupted program continues as if nothing happened.

Priorities and nesting

Several devices can interrupt at the same time, so each interrupt has a priority. The CPU serves the most urgent first, and while a handler runs, an interrupt of higher priority can interrupt it (a nested interrupt), while those of equal or lower priority wait. The unfinished handlers form a stack, and the depth of nesting is the size of that stack. Critical code can turn interrupts off for a moment; this is a privileged operation.

Short handlers, then the rest

A handler runs with other interrupts held back, so it must be fast. Most kernels split the work: the top half (the handler itself) does the urgent part, such as copying a byte out of the controller, and schedules a bottom half to do the slow part, such as checking a network packet, a little later, with interrupts enabled again.

Buffers

A device and a program work at different speeds, so the kernel puts a buffer between them. The keyboard handler stores each key in a ring buffer, a circular queue with an in index, an out index and a count; the program takes characters out when it wants them. If the buffer is full, the new character is dropped, because a handler must never wait. Buffers are also used to join devices of different speeds, to cache disk blocks, and to let a program write without waiting for the disk (a write-behind buffer).

Example

The program simulates the keyboard handler and the program that reads from the buffer, with a ring buffer of four characters.

#include <stdio.h>

#define SIZE 4

char buffer[SIZE];
int in = 0, out = 0, count = 0, dropped = 0;

/* The keyboard interrupt handler: quick, and never waits. */
void key_interrupt(char c) {
    if (count == SIZE) {
        dropped++;                    /* no room: the key is lost */
        return;
    }
    buffer[in] = c;
    in = (in + 1) % SIZE;
    count++;
}

/* The program asks for a character. Returns 0 when there is none. */
char read_key(void) {
    if (count == 0) return 0;
    char c = buffer[out];
    out = (out + 1) % SIZE;
    count--;
    return c;
}

int main(void) {
    key_interrupt('h');
    key_interrupt('i');
    printf("read %c\n", read_key());
    key_interrupt('!');
    key_interrupt('?');
    key_interrupt('x');
    key_interrupt('y');               /* the buffer is full */
    printf("read %c\n", read_key());
    printf("in the buffer: %d, dropped: %d\n", count, dropped);
    return 0;
}
Open in compiler

Line by line

  • buffer, in, out and count are the ring buffer: in is where the handler writes, out is where the program reads, and count is how many characters are inside.
  • key_interrupt stands for the interrupt handler. If count equals SIZE, there is no room, so it counts the key as dropped and returns at once, without waiting.
  • Otherwise it stores the character at in, moves in on with % so that it wraps round, and adds 1 to count.
  • read_key is the program's side. It returns 0 if the buffer is empty, or the oldest character, moving out on and subtracting 1 from count.
  • main types h and i, reads one character, types four more keys (the last one finds the buffer full) and reads again.

Expected result

read h
read i
in the buffer: 3, dropped: 1

In the real world

Every keystroke, mouse click, network packet and disk completion is an interrupt. A busy network card can raise hundreds of thousands per second, and the cost of so many interrupts is one reason that fast network drivers switch to polling under heavy load (Linux's NAPI does this) and back to interrupts when the line is quiet. SSDs and 100-gigabit network cards go further and let the program poll the device directly, with no kernel in between.

DMA is why copying a large file does not freeze your computer. On the programmer's side, you meet buffering in printf (the C library buffers output until a newline), in fflush, and in the way a file that has been "written" may not be on the disk yet until you call fsync.

Common mistakes

  • Thinking that a device interrupt stops the program for good. The handler runs, and the program then goes on.
  • Doing slow or blocking work inside an interrupt handler; the whole machine waits.
  • Forgetting that a priority number can mean urgent when it is small. Check the convention first.
  • Assuming that a write has reached the disk when the system call returns. It has only reached a buffer.

Best practices

  • Keep handlers short: do the urgent part and defer the rest.
  • Use DMA for large transfers and interrupts for events; poll only when the device is nearly always busy.
  • Size ring buffers for the worst burst, and decide what to do when one is full (drop, or tell the sender to slow down).
  • Call fsync when data must survive a crash.

Summary

The CPU controls a device through its controller's registers, using port-mapped or memory-mapped I/O, and programs do it only through drivers. Polling wastes time, interrupts let the CPU work while the device is busy, and DMA moves whole blocks with one interrupt. At an interrupt the CPU saves its state, looks up the handler in the interrupt vector, runs it in kernel mode and returns. The most urgent interrupt goes first and can interrupt a less urgent handler. Handlers must be short, and ring buffers join the fast side to the slow side.

Quick check

1. Why does DMA make a large disk transfer cheaper for the CPU?
2. A key arrives when the keyboard ring buffer is full. What should the handler do?
3. Interrupt A (priority 2) is being handled when interrupt B (priority 1, where smaller is more urgent) arrives. What happens?
4. What does the interrupt vector hold?

Key takeaways

  • A device is driven through the registers of its controller, which look like memory or like special ports
  • Polling wastes CPU time, interrupts let the CPU work until the device is ready, and DMA moves whole blocks without the CPU
  • The CPU runs the most urgent interrupt first, and a more urgent one can interrupt a handler
  • A handler does the minimum and leaves the rest for later, and a ring buffer lets the two sides run at different speeds

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.