Storage, Buses & I/O

direct memory access (DMA)

/ D-M-A /

Suppose a delivery of a thousand boxes arrives and someone has to carry each box from the truck into the warehouse. The CEO could do it personally, one box at a time, getting nothing else done — or the CEO could tell a forklift, 'move all thousand boxes to aisle 7 and ping me when you are finished.' Direct memory access, or DMA, is that forklift. It is a hardware mechanism that lets a device move a block of data straight to or from main memory by itself, without the CPU copying each word — so the CPU is free to do real work during the transfer.

Without DMA, transferring data is programmed I/O: for every word, the CPU reads it from the device register and writes it to memory, burning a cycle or more per word — fine for a few bytes, ruinous for a megabyte. With DMA, the CPU just sets up the transfer once — telling a DMA controller the source, the destination memory address, and the count — and says go. The DMA engine then takes turns using the bus or interconnect to stream the whole block into memory on its own, and raises a single interrupt when the entire transfer is complete. One setup and one interrupt replace thousands of CPU copies.

DMA is essential for any high-bandwidth device — disks, SSDs, network cards, GPUs all rely on it. Two honest complications. First, because DMA writes memory behind the CPU's back, it can leave caches stale: if the CPU has a cached copy of a region the device just overwrote, the system must keep them coherent (flush or snoop), or software reads garbage — a classic source of bugs. Second, DMA still competes with the CPU for memory bandwidth; the CPU is not blocked, but a giant transfer can slow it by stealing bus cycles, sometimes called cycle stealing.

Reading a 4 MB file: with programmed I/O the CPU executes on the order of a million load-store pairs and does nothing else. With DMA the driver writes three values (source, destination, length) and one 'start', then runs other code; the DMA engine streams all 4 MB to RAM and raises one interrupt when done.

Set up once, get one interrupt — DMA replaces a million CPU copies with a single command and a single notification.

DMA's classic gotcha is cache coherence: because a device writes memory without the CPU knowing, stale cached copies must be invalidated, or the CPU reads old data. 'It works without DMA but breaks with it' is often this bug.

Also called
DMADMA enginebus mastering直接記憶體存取