</>EmbeddedInterview

How does DMA interact with CPU caches?

MediumARM Architecture

Short answer: A coherent device can participate in hardware coherency. Non-coherent DMA requires cache maintenance and ownership transitions; use Linux DMA mapping APIs to handle this.

CPU cacheDMA mappingRAMDMA bufferDeviceDMA engine
dma_addr_t a = dma_map_single(dev, buf, len, DMA_TO_DEVICE);
/* Check dma_mapping_error; unmap after DMA completes. */

1. CPU to device: CPU writes a buffer. On a non-coherent system, dirty cache lines may hold newer bytes than RAM. Mapping or syncing for the device performs required maintenance.

2. Device to CPU: DMA writes memory. The CPU may retain stale cached bytes, so syncing for CPU access or unmapping is necessary before reading.

Linux API Use
dma_alloc_coherent Coherent allocation
dma_map_single Streaming mapping
dma_sync_single_for_cpu Return ownership to CPU
dma_sync_single_for_device Return ownership to device
dma_unmap_single End streaming mapping

3. Important: Check dma_mapping_error, obey DMA direction and ownership, and use the returned DMA address, not a cast CPU pointer. Coherent allocation still needs ordering where appropriate.

Interview takeaway: The DMA API abstracts cache maintenance and address mapping, including IOMMUs.

Walk through both DMA directions

CPU-to-device example: the CPU fills a transmit buffer with new data, but a non-coherent device might otherwise see old RAM contents because dirty cache lines have not been written back. The DMA mapping or sync-for-device operation establishes the required visibility before the driver hands ownership to hardware.

Device-to-CPU example: hardware receives a packet into memory. Before the CPU reads it, the driver waits for completion and uses the DMA API to return ownership to the CPU. This handles stale cache lines and any platform-required maintenance.

dma_addr_t dma = dma_map_single(dev, buf, len, DMA_FROM_DEVICE);
if (dma_mapping_error(dev, dma))
    return -EIO;

/* Submit DMA and wait for completion or quiesce on error. */

dma_unmap_single(dev, dma, len, DMA_FROM_DEVICE);
/* Now CPU may consume the received data. */

For persistent streaming mappings, dma_sync_single_for_cpu and dma_sync_single_for_device bracket ownership changes instead of unmapping each time. Do not let independent objects share cache lines inappropriately with DMA buffers on a non-coherent target. For coherent descriptors, publish fields before the device ownership flag with an appropriate barrier; coherence does not itself guarantee ordering or safe simultaneous modification.