---
title: Input and output, polling, interrupts and DMA
heading: Three ways to move data between devices and memory
eyebrow: C8 · Lesson 27 · Input and output, polling, interrupts and DMA
xp: 40
---

::: hook
A serial port at 115200 baud delivers a byte about every 87 µs. An audio converter delivers 48,000 samples a second, and a fast ADC a million. Each value has to get from a device register into memory before the next one overwrites it. The processor can keep asking the device whether anything has arrived (polling), let the device interrupt it, or hand the job to a DMA controller that copies the data by itself. Which one works comes down to arithmetic: how often data arrives, and how many cycles each method spends on it.
:::

::: play
- A polling loop: it reads the switches and copies them to the LEDs, over and over. Run it and flip some switches; the LEDs follow on the next pass.
- a0 counts the polls. Almost all of them find nothing new, and each one still costs the processor four instructions.
:::
:::

```sim cpu
.text
    li t0, 0x20000       # the device registers start here
    li a0, 0             # polls so far
poll:
    lw t1, 4(t0)         # read the switches
    sw t1, 0(t0)         # show them on the LEDs
    addi a0, a0, 1
    j poll
show: a0, t1
hex: t0
leds: on
switches: on
forever: on
speed: 20
```

::: predict
## A UART sends each byte as a start bit, 8 data bits and a stop bit. At 115200 baud (bits per second), how many bytes arrive per second?

- [ ] 115,200
- [ ] 14,400
- [x] 11,520
- [ ] 1,152

::: reveal
11,520: each byte takes 10 bit times, so 115200/10. That's one byte every 86.8 µs, which is the deadline for reading each one before the next arrives (unless the UART has a FIFO to hold a few).
:::
:::

::: nameit
## Polling

The processor reads a **status register** in a loop until a device is ready, then moves the data. It's simple and reacts within one pass of the loop, but every pass spent waiting is wasted. Polling from a main loop that also does other work reacts within one trip around that loop, so the **worst-case latency** is the loop's period.

## Interrupts

The device raises an interrupt when it has data, and the processor runs a handler (lesson 25). Each event costs the **entry and exit overhead** (saving and restoring registers, often 20 to 50 cycles on a microcontroller) plus the handler's own work. With events at rate r, c cycles each, on a clock of f,

$$\text{CPU load} = \frac{r \cdot c}{f}$$

which has to stay well under 1, leaving time for everything else.

## DMA

A **DMA controller** is a small engine on the bus that copies data between a peripheral and memory by itself, one transfer per request from the device. The processor sets it up (source, destination, count) and gets one interrupt per **block** of n items, so the interrupt load falls by a factor of n. With **double buffering**, the DMA fills one buffer while the processor works on the other, so each block must be processed in less time than the next one takes to fill: n/r.

## Serial and bus rates

| Link | Rate |
|---|---|
| UART, 1 start + 8 data + 1 stop bit | baud/10 bytes per second |
| a bus w bits wide, f transfers per second | $w \cdot f/8$ bytes per second |
:::

::: example
## A 48 MHz processor takes an interrupt for each byte from a 115200-baud UART, costing 60 cycles each. What fraction of its time does that use?

::: solution
1. **Cycles per second.** The UART delivers 11,520 bytes a second:
   $$11{,}520 \times 60 = 691{,}200$$
2. **The fraction.**
   $$\frac{691{,}200}{48 \times 10^6} = 1.44\%$$

**Answer:** 1.44% of its time, which is comfortable.
:::
:::

::: example
## A 16 MHz processor must collect a 1 Msample/s ADC stream. Compare an interrupt per sample (60 cycles) with DMA in blocks of 256.

::: solution
1. **An interrupt per sample.**
   $$10^6 \times 60 = 6 \times 10^7\ \text{cycles/s}$$
   against $1.6 \times 10^7$ available, a load of 375%: impossible.
2. **Interrupts with DMA.**
   $$\frac{10^6}{256} = 3906\ \text{a second}$$
3. **Their cost.**
   $$3906 \times 60 \approx 234{,}000\ \text{cycles}$$
   a load of 1.5%.
4. **The deadline.** Each block of 256 must be processed within 256 µs.

**Answer:** an interrupt per sample would need 375% of the processor, which is impossible; DMA in blocks of 256 needs 1.5%.
:::
:::

::: example
## A UART receives at 1 Mbaud, 10 bits per byte, into a 16-byte FIFO that interrupts when it holds 12 bytes. How long does the processor have to respond, and how many interrupts a second does it take?

::: solution
1. **Byte time.** A byte arrives every 10 µs.
2. **Time to respond.** When the interrupt fires there's room for 4 more bytes, so the handler must start emptying the FIFO within 40 µs or a byte is lost.
3. **Interrupt rate.**
   $$\frac{10^5}{12} \approx 8333\ \text{a second}$$
   against 100,000 with an interrupt per byte.
4. **The trade.** A higher threshold means fewer interrupts but less time to respond: the FIFO trades latency tolerance against overhead.

**Answer:** 40 µs to respond, and about 8333 interrupts a second.
:::
:::

::: check
given: B = 9600 | 19200 | 57600 | 115200
answer: B/10
unit: bytes/s
tolerance: 0.5%

## How many bytes per second does a {B}-baud UART carry (1 start, 8 data, 1 stop bit)?

::: right
Right. 10 bit times a byte: {answer} bytes per second.
:::

::: misses
- [B/8] Count the start and stop bits: 10 bit times a byte.
- [any] Not yet. Baud divided by 10.
:::
:::

::: check
given: r = 1000 | 11520 | 48000; c = 40 | 100 | 200; f = 16 | 48 | 160
answer: r*c/(f*1e6)*100
unit: %
tolerance: 0.5%

## A {f} MHz processor takes {r} interrupts a second, each costing {c} cycles. What percentage of its time do they use?

::: right
Right. $rc/f$ = {answer}%.
:::

::: misses
- [r*c/(f*1e6)] Give it as a percentage.
- [any] Not yet. Cycles used per second over cycles available.
:::
:::

::: check
kind: parts
given: T = 1 | 5 | 20

## A main loop checks a button once every {T} ms.

::: part
answer: T
unit: ms
tolerance: 0.5%

### What is the longest the program can take to notice a press?

::: misses
- [T/2] That's the average. A press just after a check waits a whole period.
- [any] Not yet. One full period.
:::
:::

::: part
answer: T/2
unit: ms
tolerance: 0.5%

### What is the average delay, for presses at random times?

::: misses
- [any] Half the period.
:::
:::
:::

::: check
kind: parts
given: R = 44100 | 48000 | 1000000; n = 64 | 256 | 1024

## A converter delivers {R} samples a second through DMA, in blocks of {n} samples with double buffering.

::: part
answer: R/n
tolerance: 0.5%

### How many interrupts a second does the processor take?

::: misses
- [R] With DMA the interrupt comes once per block.
- [any] Not yet. Rate over block size.
:::
:::

::: part
answer: n/R*1000
unit: ms
tolerance: 0.5%

### How long does the processor have to finish each block?

::: misses
- [any] The time the next block takes to fill.
:::
:::
:::

::: check
given: w = 8 | 16 | 32; f = 8 | 50 | 100
answer: w*f/8
unit: MB/s
tolerance: 0.5%

## A bus moves {w} bits per transfer at {f} million transfers a second. What is its bandwidth?

::: right
Right. {w}/8 bytes × {f} million = {answer} MB/s.
:::

::: misses
- [w*f] That's in megabits a second. Divide by 8 for bytes.
- [any] Not yet. Bytes per transfer times transfers per second.
:::
:::

::: check
kind: asm
given: s = 16..255 int
setup: switches = s
expect: leds = s + 15 - 2*(s - 16*floor(s/16))

## Read the switches (at 0x20004) and show them on the LEDs (at 0x20000) with the low four bits inverted.

```asm starter
    li t0, 0x20000
    ebreak
```

```asm solution
    li t0, 0x20000
    lw t1, 4(t0)
    xori t1, t1, 15
    sw t1, 0(t0)
    ebreak
```

::: right
Right. A load from the device, an XOR with 0x0F, and a store to the other device.
:::
:::

::: check
kind: choice

## A 16 MHz microcontroller must record a 500 kHz ADC stream without losing samples. Each interrupt costs about 50 cycles. Which approach works?

- [ ] An interrupt for every sample
- [ ] Polling the ADC's status register from the main loop
- [x] DMA into a pair of buffers, with an interrupt per buffer
- [ ] A faster UART

::: misses
- [1] 500,000 × 50 cycles is 25 million a second, more than the 16 million there are.
- [2] The main loop would have to come round every 2 µs, 32 cycles, and do nothing else.
- [4] The data comes from the ADC; the UART isn't involved.
:::
:::

::: check
kind: parts
given: B = 115200 | 1000000 | 3000000; D = 16 | 64; T = 4 | 8 | 12

## A UART at {B} baud (10 bits a byte) fills a {D}-byte FIFO that interrupts at {T} bytes.

::: part
answer: (D - T)*10/B*1e6
unit: µs
tolerance: 0.5%

### How long does the handler have before a byte is lost?

::: misses
- [D*10/B*1e6] The FIFO already holds T bytes when it interrupts.
- [any] Free space × time per byte.
:::
:::

::: part
answer: B/10/T
tolerance: 0.5%

### How many interrupts a second?

::: misses
- [any] Byte rate ÷ threshold.
:::
:::
:::

::: check
kind: parts
given: R = 100 | 500 | 2000; N = 64 | 256; c = 50 | 80; f = 16 | 48 | 100

## A {R} ksample/s ADC feeds a {f} MHz core; an interrupt costs {c} cycles.

::: part
answer: R*1000*c/(f*1e6)*100
unit: %
tolerance: 0.5%

### What load does an interrupt per sample put on the core?

::: misses
- [any] Rate × cycles ÷ clock.
:::
:::

::: part
answer: R*1000/N*c/(f*1e6)*100
unit: %
tolerance: 0.5%

### And DMA with an interrupt per block of {N}?

::: misses
- [any] Divide the interrupt rate by the block size.
:::
:::
:::

::: explain
## Why does DMA make a fast data stream manageable when an interrupt per sample doesn't?

::: model
An interrupt has a fixed cost each time, the cycles spent entering and leaving the handler and saving registers, no matter how little data it moves. At a million samples a second that fixed cost alone can exceed the processor's whole cycle budget. A DMA controller moves each sample with its own hardware, using the bus but not the processor, and only interrupts when a whole block is done. The fixed cost is paid once per block instead of once per sample, so the load falls by the block size, and the processor's job becomes processing each block before the next one fills.
:::
:::

::: practice

::: check
given: B = 9600 | 115200 | 1000000
answer: 1e6/B
unit: µs
tolerance: 0.5%

## How long is one bit at {B} baud?

::: misses
- [any] One over the baud rate.
:::
:::

::: check
given: B = 9600 | 115200; L = 10 | 64 | 1500
answer: 10*L/B*1000
unit: ms
tolerance: 0.5%

## How long does a {L}-byte message take at {B} baud, 10 bit times a byte?

::: misses
- [any] 10L bit times.
:::
:::

::: check
given: r = 1000 | 8000; c = 50 | 300; f = 8 | 72
answer: r*c/(f*1e6)*100
unit: %
tolerance: 0.5%

## {r} events a second, {c} cycles each, on a {f} MHz clock: what percentage load?

::: misses
- [any] $rc/f$.
:::
:::
:::
