Definition
Direct memory access (DMA) is a hardware mechanism that moves data between memory and a peripheral device, or between two memory areas, without the processor executing a load and a store for each item. Software programs a DMA controller, the hardware unit that performs the transfer, with a source address, a destination address and a length, and starts it. The controller then reads and writes memory by itself, at the same time as the processor runs other code, and signals completion, usually with a status bit or an interrupt §6.11.
The idea
A serial port receives 1000 bytes. Without DMA, the port raises an interrupt for every byte: the processor stops what it is doing, runs a handler that copies one byte into a buffer, and returns, 1000 times. Suppose each interruption costs 100 processor cycles; the transfer then costs cycles of processor time. With DMA, the processor spends a few instructions programming the controller, the controller stores each byte as it arrives, and the processor is interrupted once, at the end.
The price is a second agent that reads and writes memory on its own schedule. The DMA controller knows nothing of the program’s variables, locks, calls to free or caches. It uses the addresses it was given until it finishes or is told to stop. A buffer in a transfer must therefore have exactly one owner at a time, the processor or the controller, and ownership §4.2 changes hands only at agreed points. Lending a book to a copy shop is a fair picture: while the shop is copying, you neither write in the book nor throw it away, and you take it back when the shop says it is done. The picture stops in one respect. If you threw the book away and put another on the same shelf, the shop would copy, or write into, whatever now sits there.
How it works
The steps below assume a processor with a data cache, a small fast memory that keeps copies of recently used RAM contents in units called cache lines, typically 32 or 64 bytes each. The cache is called coherent with DMA when the hardware keeps the cache and the controller’s view of RAM consistent by itself, and non-coherent when software must do it. On a processor without a data cache, the cache steps disappear, but the ownership rules stay.
Prepare; the processor owns the buffer. Choose a buffer that stays allocated until the transfer ends; a local array §14.5 of a function that returns before then does not qualify. The buffer must lie in memory the controller can reach and meet the controller’s alignment §4.22 rules. For a transmit, write the data into the buffer.
Hand over. With a non-coherent cache, clean the cache lines that cover the buffer, which writes their modified contents back to RAM. For a receive, clean or invalidate those lines before starting, so that no modified line is later written back over the data the controller stores. Then execute a memory barrier §4.37, so that these writes reach memory before the start command does, and write the start command to the controller’s register.
Transfer; the controller owns the buffer. The processor must not write a transmit buffer, because the controller may not yet have read all of it. It must not read a receive buffer, because the buffer may hold a mix of new and old bytes. It must not free or reuse either.
Take back. Wait for the completion signal whose documented meaning is that the controller has finished with the buffer. For a receive with a non-coherent cache, invalidate the cache lines that cover the buffer, that is, discard the cache’s copies, so that the next processor read fetches the new data from RAM. The processor owns the buffer again.
Canceling follows the same rule. A software timeout §9.34 that expires does not stop the controller. The program must disable the transfer and then wait until the controller reports that it has stopped, for example by reading the channel’s enable bit back as 0, before it reuses the buffer.
Some controllers return a buffer piece by piece. In circular mode with a half-transfer interrupt, the controller fills the two halves of one buffer in turn and signals each time a half is full, so the processor processes one half while the controller fills the other. Network controllers commonly use a ring of descriptors, small records in memory that each describe one buffer, and each descriptor carries an ownership bit that says whether the processor or the controller currently owns that buffer.
Operating systems make the protocol explicit. In the Linux kernel’s DMA interface, mapping a buffer for a device hands the buffer to the device and unmapping it hands it back; in between, dma_sync_single_for_cpu lends it to the processor and dma_sync_single_for_device returns it to the device.
Worked example
A program puts the four bytes 1, 2, 3, 4 into buffer A and starts a DMA transmit. After the controller has read and sent the first 2 bytes, the program writes 9, 9, 9, 9 into A to prepare the next message. The controller reads the remaining two positions and sends 9 and 9. The receiver gets 1, 2, 9, 9, a message that the program never meant to send. Waiting for the completion signal before writing A, or preparing the next message in a second buffer B, prevents the mix.
A processor has a data cache with 32-byte lines that is not coherent with DMA. A receive buffer occupies addresses 0x20001000 to 0x2000103F, which is 64 bytes, exactly two cache lines, starting at 0x20001000 and 0x20001020. Before the transfer the program read the buffer, so the cache holds a copy whose first byte is 3. The controller then writes 7 into that byte in RAM.
Without invalidation, the program’s next read of the first byte is served from the cache and returns 3. The transfer worked; the program read a stale copy.
After the program invalidates both lines, the read misses the cache, fetches the line from RAM and returns 7.
Now let the buffer be 40 bytes long, still starting at 0x20001000. Its last byte is at 0x20001000 plus 39, which is 0x20001027, since 39 is 0x27 in hexadecimal. The second cache line covers 0x20001020 to 0x2000103F. The buffer uses 8 of its 32 bytes, and the other bytes hold an unrelated variable that the program has just changed in the cache. Invalidating that line throws away the variable’s new value; not invalidating it leaves 8 stale buffer bytes. Neither choice is correct. The repair is to start every receive buffer on a cache-line boundary and round its size up to a whole number of lines, here bytes.
Stated precisely
Describe one buffer by its ownership state.
Processor-owned: the processor may read and write the buffer, and no programmed transfer uses it.
Handed over: the processor has stopped writing, the data are in RAM (with the cache lines cleaned, if the cache is non-coherent), and a barrier orders those writes before the start command.
Controller-owned: from the start command until the completion signal, the controller may read or write any byte of the buffer at any moment.
Returned: the completion signal has been observed, any barrier the architecture requires after it has executed, and for a receive the cache lines covering the buffer have been invalidated. The buffer is processor-owned again.
The rule: the processor may write the buffer, read data the controller wrote, or release the memory only while the buffer is processor-owned. The completion signal that ends the controller-owned state must be one whose documented meaning is that the controller will make no further access to the buffer. The rule rests on two assumptions: the controller accesses only the addresses and length it was programmed with, and the memory stays allocated, and is used for nothing else, for as long as the controller owns it.
Limits and common mistakes
A lock does not stop DMA. Mutexes §9.5 and disabled interrupts coordinate software; the controller ignores both.
Memory protection for the processor does not cover DMA. A memory protection unit §6.8 (MPU), the hardware on many microcontrollers §6.1 that restricts which addresses software may access, checks only the processor’s own accesses. A DMA controller is a separate bus master, a component that starts memory transfers on its own, and the MPU does not check it. Larger systems confine devices with an input-output memory management unit §6.9 (IOMMU), which translates and restricts the addresses each device may use. Without one, a controller programmed with a wrong address overwrites whatever memory it can reach.
Freeing a buffer the controller still owns turns the controller’s later writes into a use-after-free §4.6 performed by hardware: the bytes land in whatever object now occupies that memory, and no software check sees them arrive.
A memory barrier is not cache maintenance, and cache maintenance is not a barrier. With a non-coherent cache both are needed, in the order the processor architecture prescribes. The Arm Cortex-M4 §6.3 has no data cache, so on it only ordering and ownership matter. The Cortex-M7 can have a data cache, so code moved from one to the other can meet the stale-copy problem for the first time.
The bus write that starts a transfer completes long before the transfer does. Only the controller’s completion signal says that the buffer is free.
Questions answered
When may the CPU reuse a buffer that a DMA engine still owns?
The CPU, the processor, must not reuse a buffer while a DMA (direct memory access) engine, the controller that performs the transfer, still owns it. It may reuse the buffer only after the engine can make no further access to it and the processor has completed the steps that make the engine’s data visible. In order:
The transfer has ended, as shown by the engine’s documented completion signal, or the transfer has been canceled and the engine has confirmed that it stopped. An expired software timeout, or a pointer that the program no longer holds, does not stop the engine.
Any memory barrier the processor architecture requires after the completion signal has executed.
For a receive buffer on a processor whose data cache does not see DMA writes, the cache lines covering the buffer have been invalidated, so later reads fetch the new data from RAM.
After these steps the processor may read the data, write new data, or free the memory. Some engines are designed to return a buffer in parts, half by half in circular mode or one descriptor at a time with an ownership bit; the processor may then reuse each part as soon as that part has been returned.
Related entries: Borrowed pointer (§4.3), Memory-mapped I/O (MMIO) (§4.35), Memory barrier (§4.37), Ownership (§4.2), Use-after-free (§4.6), Memory protection unit (MPU) (§6.8). Further reading: [5].