Topics / Linux Kernel & Device Drivers / Q41
What is the difference between dma_alloc_coherent and dma_map_single?
dma_alloc_coherent and dma_map_single solve different buffer-management problems. Coherent allocation creates a new CPU/device-visible buffer; streaming mapping makes an existing suitable CPU buffer available for a DMA transfer.
| dma_alloc_coherent | dma_map_single |
|---|---|
| Allocates DMA-suitable storage | Maps existing suitable buffer |
| Returns CPU pointer and DMA address | Returns DMA address |
| Coherent CPU/device visibility | Ownership and cache synchronization required |
| Often used for descriptors/rings | Often used for packet or data transfers |
1. Coherent example
dma_addr_t dma;
void *cpu = dma_alloc_coherent(dev, size, &dma, GFP_KERNEL);
if (!cpu)
return -ENOMEM;
// CPU initializes descriptor; device uses dma.
// Stop hardware before freeing.
dma_free_coherent(dev, size, cpu, dma);
Coherent visibility does not guarantee descriptor publication ordering. Use appropriate barriers before handing ownership to the device.
2. Streaming example
dma_addr_t dma = dma_map_single(dev, buf, len, DMA_FROM_DEVICE);
if (dma_mapping_error(dev, dma))
return -EIO;
// Start device receive; wait for completion.
dma_unmap_single(dev, dma, len, DMA_FROM_DEVICE);
// Now CPU may consume received data.
Do not touch the buffer while owned by the device. For persistent mappings use matching sync-for-CPU/device operations.
Interview takeaway: Use coherent memory for shared control structures when appropriate and streaming DMA for transient data. Always use the device's DMA address, correct direction and matching release API.