CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 3 of 7 · 2 min read

Polling

Think of waiting for a kettle by standing next to it and looking at it every second. You know at once when it boils, and you do nothing else. The analogy stops in one place: you can look at the kettle for free, and the processor pays for each look with a bus cycle and a stalled instruction stream.

In plain words: In polling the driver reads the status register in a loop until the device says it is ready. In programmed I/O the processor also moves every word of the data itself, by reading or writing the data register. Both are simple and respond at once. Both occupy the processor for the whole wait and for the whole transfer. They suit a device that answers in a very short time, and they are wasteful for a slow one.

A worked example (made up to show the idea). A device becomes ready 2 ms after the command. Each poll takes 50 ns. The loop makes 2 ms / 50 ns = 40,000 polls. All 2 ms is processor time that does no useful work. Moving 64 KiB with programmed I/O at 4 bytes per word takes 65,536 / 4 = 16,384 words. At 20 ns per word the processor is busy for 327.68 microseconds more.

The key lines. The loop below is a labelled sketch. The register addresses are the made-up ones of section 1. It will not run on a normal machine, because those addresses are not mapped.

/* Sketch only: made-up registers, shown to explain the loop. */
#define STATUS  (*(volatile unsigned *)0xFE000000)
#define COMMAND (*(volatile unsigned *)0xFE000004)
#define DATA    (*(volatile unsigned *)0xFE000008)

unsigned read_word(void) {
    COMMAND = 1;                    /* ask for one word */
    while ((STATUS & 1) == 0)       /* poll until bit 0 says ready */
        ;
    return DATA;                    /* the word is in the data register */
}

The word volatile tells the compiler that the value may change without a write from the program, so each loop pass must really read the register.

Polling

Polling is the method of finding out whether a device needs attention by reading its status register again and again. The processor spends its time on the checks. Programmed I/O adds that the processor copies the data between the device and memory itself.

Example: a loop that reads the status register until a ready bit is set, and then reads the data register.

Check yourself: 1. How many polls fit into a 2 ms wait at 50 ns per poll? 2. Why must a register that is polled be declared volatile? 3. When is polling a good choice?