Search topics...
DMACache and Performancefoundational

What happens if the CPU and DMA access the same memory or peripheral simultaneously?

0 upvotes
Practice with AISoon
Study the fundamentals first — DMA topic page

When the CPU and DMA contend for the same bus (AHB or APB), the bus matrix arbiter serializes the accesses. One gets through first, the other is stalled. For the CPU, this stall manifests as the current instruction taking extra clock cycles to complete — software cannot detect it, but it reduces effective CPU throughput. This is called bus contention or cycle stealing. For individual transfers, the stall is typically 1-2 clock cycles and is invisible to software. But for sustained high-bandwidth DMA (memory-to-memory at maximum speed, or multiple DMA channels active simultaneously), the cumulative stalling can reduce CPU performance by 10-30%.

For simultaneous access to the same peripheral register, the bus arbiter serializes the accesses cleanly — no data corruption occurs at the hardware level. However, logical races are a real danger: if the CPU reads the UART data register (DR) while a DMA RX transfer is active on the same UART, both are consuming from the same source. Reading DR clears the RXNE flag, so whichever reads first (CPU or DMA) gets the byte, and the other sees nothing or gets the next byte. This is a configuration error — never use both CPU and DMA to access the same peripheral's data path simultaneously.

Similarly, if both the CPU and DMA write to the same RAM buffer without coordination, data corruption occurs. The HT/TC interrupt mechanism exists precisely to provide this synchronization — the CPU processes one half only after the DMA has moved on to the other half. Breaking this contract (processing too slowly and overrunning into the DMA's active half) produces silent data corruption with no error flag or interrupt. In performance-critical systems, add a runtime check: compare the DMA's current NDTR value against the processing pointer to detect overrun conditions and log them.

Source: DMA Q&A