Try Embedded

DMA

Transfer modes, circular buffers, half-transfer interrupts and cache coherency.

Moving data without the CPU

A DMA (direct memory access) controller copies data between memory and peripherals, or between two memory areas, while the CPU does something else or sleeps. Without DMA, receiving a 1 Mbit/s UART stream takes an interrupt every 10 µs; with DMA it takes one interrupt per buffer.

What you configure

SettingOptions
DirectionPeripheral to memory, memory to peripheral, memory to memory
Source and destination addressesFor a peripheral: its data register, e.g. &USART2->DR
Data width8, 16 or 32 bits on each side
IncrementUsually the memory address increments and the peripheral address does not
CountNumber of items to transfer
ModeNormal (stop after count) or circular (wrap and continue)
Request sourceWhich peripheral event triggers each transfer (UART RX not empty, ADC end of conversion, timer update)
PriorityBetween channels sharing the controller
InterruptsHalf transfer, transfer complete, transfer error

The peripheral raises a request each time it has data (or needs data); the DMA moves one item per request. On STM32 parts the request-to-channel mapping is fixed (F4 "streams and channels") or flexible through a DMAMUX (G4, L4+, H7).

Normal mode: one block

Typical for transmitting a message:

  1. Fill the buffer.
  2. Point DMA at it, set the count, enable the channel and the peripheral's DMA request.
  3. The CPU continues. The transfer-complete interrupt says the buffer may be reused.
void uart_send_dma(const uint8_t *buf, uint16_t len) {
  DMA1_Stream6->CR &= ~DMA_SxCR_EN;            /* stream must be disabled to reconfigure */
  while (DMA1_Stream6->CR & DMA_SxCR_EN) { }
  DMA1_Stream6->M0AR = (uint32_t)buf;
  DMA1_Stream6->PAR  = (uint32_t)&USART2->DR;
  DMA1_Stream6->NDTR = len;
  DMA1->HIFCR = DMA_HIFCR_CTCIF6 | DMA_HIFCR_CHTIF6 | DMA_HIFCR_CTEIF6;  /* clear old flags */
  DMA1_Stream6->CR |= DMA_SxCR_EN;
  USART2->CR3 |= USART_CR3_DMAT;
}

The buffer must stay valid until the transfer completes: never pass a local array that goes out of scope when the function returns.

Circular mode and double buffering

For continuous streams (ADC sampling, audio, UART reception) circular mode wraps the address back to the start and keeps going forever. With a half-transfer interrupt you get double buffering from one buffer:

buffer: [ first half ][ second half ]
           ^ HT interrupt: first half is full, process it while DMA fills the second
                          ^ TC interrupt: second half is full, process it while DMA refills the first

The CPU must finish processing a half before DMA comes back round to it; size the buffer for the worst-case processing delay.

#include <stdio.h>
#include <stdint.h>

#define BUF_LEN 8
static volatile uint16_t buf[BUF_LEN];

static void process(const char *which, int start) {
  uint32_t sum = 0;
  for (int i = start; i < start + BUF_LEN / 2; i++) sum += buf[i];
  printf("%s half ready: average %u\n", which, sum / (BUF_LEN / 2));
}

/* Interrupt handler for the DMA channel: HT and TC flags. */
static void dma_irq(int half_transfer, int transfer_complete) {
  if (half_transfer)     process("first", 0);
  if (transfer_complete) process("second", BUF_LEN / 2);
}

int main(void) {
  /* Simulate the DMA writing 20 ADC samples into the circular buffer. */
  int pos = 0;
  for (int n = 0; n < 20; n++) {
    buf[pos] = (uint16_t)(1000 + n * 10);
    pos = (pos + 1) % BUF_LEN;
    if (pos == BUF_LEN / 2) dma_irq(1, 0);
    if (pos == 0)           dma_irq(0, 1);
  }
  return 0;
}

Receiving data of unknown length

UART reception is the classic hard case: messages arrive with unknown length at unknown times. The robust pattern:

  1. DMA in circular mode into a ring buffer, always running.
  2. Enable the UART's idle line interrupt (fires when the line goes quiet for one character time) in addition to HT and TC.
  3. In each of those interrupts, read the DMA's remaining count (NDTR) to find the current write position: head = BUF_LEN - NDTR.
  4. Process everything between the last processed position and head, handling the wrap.

This never loses bytes, never needs to know message lengths, and costs a few interrupts per message.

Cache coherency

On cores with a data cache (Cortex-M7, application processors), DMA and the CPU can see different data:

  • before a memory-to-peripheral transfer: clean the buffer's cache lines so DMA reads what the CPU wrote
  • after a peripheral-to-memory transfer: invalidate the buffer's lines so the CPU reads what DMA wrote
  • align buffers to the cache line size (32 bytes) and round their size up to it

Or place DMA buffers in a non-cacheable memory region configured with the MPU.

Other pitfalls

  • Wrong memory. Some RAM blocks are not reachable by some DMA controllers (core-coupled memory on STM32F4, DTCM on some H7 configurations). The transfer silently does nothing or errors.
  • Width mismatch. A 16-bit ADC result moved as 8-bit loses the top byte; moving it as 32-bit into a uint16_t buffer overruns the buffer.
  • Disabling mid-transfer. On many controllers you must wait for the enable bit to read back 0 before reconfiguring.
  • Flags not cleared. A leftover transfer-complete flag from a previous transfer can block the next one or fire the interrupt immediately.
  • Bus contention. DMA steals bus cycles; heavy DMA on the same SRAM the CPU is using slows the CPU. Put DMA buffers in a separate SRAM block where possible.

Interview question: How do you receive variable-length UART messages with DMA without losing bytes?

Answer: Run DMA permanently in circular mode into a ring buffer, and enable the UART idle-line interrupt plus the DMA half and full transfer interrupts. In each, compute the DMA write position from the remaining-count register, process all bytes from the last read position up to it (handling wrap-around), and update the read position. Message framing is then handled in software on the byte stream. The DMA never stops, so bytes cannot be lost between messages, as long as the buffer is large enough for the worst-case processing delay.

Interview question: When is DMA not worth it?

Answer: For very small or infrequent transfers, where setting up the channel costs more cycles than copying a few bytes, and when the CPU must inspect each byte immediately anyway. Also when DMA channels are scarce and needed for higher-rate peripherals, or when the code complexity (cache maintenance, error handling, buffer lifetime) outweighs the CPU time saved. A good rule is DMA for continuous streams and large blocks, and interrupts or polling for short, sporadic transfers.

Build it: sample the probe continuously with DMA

This is step 4 of the module project. In step 3 the CPU waited for every conversion. Now the greenhouse also logs the soil probe all the time, so the ADC runs non-stop and DMA moves every result into RAM with no help from the CPU.

Lab: Average each half of a circular DMA buffer

The ADC converts channel 4 continuously and hands each 16-bit result to DMA1 channel 1, which writes it into a buffer in circular mode. The DMA sets a flag when the first half of the buffer is full (HTIF1) and another when the second half is (TCIF1), then starts again at the beginning. While the DMA fills one half, your code averages the other: that is double buffering, and it is how real data loggers, audio and motor control keep up.

  • logger_start(buf, n) remembers the buffer, then sets up the DMA channel: from &ADC1->DR (CPAR) to buf (CMAR), n items (CNDTR), 16 bits on both sides, memory address stepping, circular. Enable it last: CPAR, CMAR and CNDTR can only be written while the channel is off. Then start the ADC on channel 4 with ADON, CONT and DMA set, and SWSTART.
  • logger_poll() never waits. If the first half is ready, clear its flag and return the average of buf[0] to buf[n/2 - 1]. Otherwise, if the second half is ready, clear that flag and return the average of the second half. If neither is, return -1.

Clear a flag by writing 1 to its bit in IFCR. A flag left set makes the next poll process the same half again.

Going deeper

Interview question: How would you design a digital oscilloscope's capture path?

Answer: The ADC samples into memory by DMA in circular mode, triggered by a timer for an exact sample rate, while a comparator or a firmware search finds the trigger point. The CPU only processes the captured buffer for display. Size the buffers for the deepest capture, align them for the DMA and keep cache coherency in mind on cores with a data cache.

Interview question: What is a DMA memory-to-memory transfer good for, and what are its limits?

Answer: Copying large blocks (framebuffers, sample arrays) without CPU involvement, freeing the CPU for other work or sleep. Limits: setup overhead makes it slower than memcpy for small blocks, it competes for bus bandwidth with the CPU, it may not reach all memories, cache maintenance is needed on cached cores, and some DMA controllers do memory-to-memory only on certain streams.

Interview question: Why should a DMA transfer-error interrupt be enabled and handled?

Answer: Errors such as an access to an invalid address, a bus fault or a FIFO error stop the transfer, often silently disabling the stream. Without the error interrupt, the driver waits forever for a completion that never comes. Handling it lets the driver log, reset the stream and the peripheral, and report a failure to the caller.

Explain it: In your own words, explain how circular DMA with half and full transfer interrupts gives double buffering from one buffer.

Answer: The DMA fills one buffer continuously from start to end and then wraps back to the start without stopping. When it reaches the middle it raises a half-transfer interrupt, meaning the first half is now complete and stable while the DMA keeps writing the second half, so the CPU processes the first half. When it reaches the end it raises the transfer-complete interrupt and wraps, so the CPU processes the second half while the first is refilled. Each half alternates between being filled and processed, as long as processing finishes within half a buffer's time.