CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 4 of 7 · 2 min read

Interrupts for I/O

Think of putting the kettle on and going to read a book. The kettle whistles when the water boils. You use the waiting time, and the whistle costs you a moment to stand up and switch it off. The analogy stops in one place: a whistle is free, while an interrupt costs the processor a state save, a handler and a state restore.

In plain words: In interrupt-driven I/O the driver starts the device, and then the OS runs some other process. When the device finishes, it raises an interrupt (page 5 of Level 0). The processor saves its state, runs the handler of the driver, and the handler wakes the process that was waiting. The processor is free during the whole wait, and it pays a fixed cost for each interrupt. This is the right method for slow devices and a poor one for devices that interrupt very often.

A worked example (made up to show the idea). One interrupt costs 5 microseconds of processor time, including the handler. A disk that raises 1,000 interrupts per second costs 1,000 x 5 microseconds = 5 ms each second, which is 0.5% of one processor. A network card that receives 100,000 packets per second and interrupts for each one costs 100,000 x 5 microseconds = 0.5 s each second, which is 50% of one processor. With one interrupt for each batch of 32 packets, the cost falls to 3,125 x 5 microseconds = 15.6 ms each second, about 1.6%.

The key lines. The break-even is simple. Polling costs about the whole wait L of the device. An interrupt costs a fixed 5 microseconds. If L is below 5 microseconds, polling uses less processor time. Fast flash devices therefore sometimes poll, or poll for a short time and then sleep and wait for the interrupt.

Interrupt-driven I/O

Interrupt-driven I/O is the method in which the driver starts a device and lets other work run, and the device raises an interrupt when the operation is complete. The processor pays a fixed cost for each interrupt and nothing for the wait itself.

Example: a process calls read, sleeps, the disk finishes, the interrupt handler runs, and the process becomes runnable again.

Common mistake

Interrupts are not always cheaper than polling. Under a very high event rate, a processor can spend all its time in handlers and get no work done. Linux network drivers therefore switch from interrupts to polling under load, a design called NAPI.

Check yourself: 1. How much processor time does the disk of the worked example use in each second? 2. Why does batching 32 packets per interrupt help? 3. At what device latency does polling become cheaper than an interrupt?