
Recall first from DMA concepts and coherent memory
- A bus-mastering device initiates memory transactions using DMA addresses supplied by the DMA API.
- Coherent allocations provide CPU and device visibility without explicit cache synchronization, while access ordering still matters.
- Streaming mappings require the CPU and device to take turns accessing the buffer.
Choose the direction and address range
3 min readThe last lesson mapped a single buffer. This lesson answers how DMA_TO_DEVICE and friends record direction, and how scatterlists map many non-contiguous buffers in one dma_map_sg call.
A network driver may need to transmit a packet whose header and payload are already stored in separate memory regions. If the hardware accepts a sequence of DMA segments, the driver can describe those regions in order and submit them without first assembling the packet in a single buffer. The Linux 6.8 DMA mapping guide documents the direction and scatter-gather interfaces that make this possible. Dynamic DMA mapping Guide
Direction applies to the bytes in the mapped memory range. For a transmit payload, the device reads bytes the CPU prepared, so the direction is DMA_TO_DEVICE. For an empty receive buffer, the device writes bytes that the CPU will consume after completion, so the direction is DMA_FROM_DEVICE. Use DMA_BIDIRECTIONAL when the device may both read and write the same mapped range, such as when it reads a command record in memory and writes a result back into that record during the same mapping.
Choose the direction for each mapping. A device that supports both transmit and receive can still have one transmit mapping and a separate receive mapping, each with its own direction. Likewise, a driver can write device registers to start a receive operation while the receive buffer itself is DMA_FROM_DEVICE. The register write initiates the operation. The device’s writes to the receive buffer determine the direction. The DMA mapping implementation uses the direction to prepare the range for device access and make the data available at the appropriate stage of the transfer. Use the same direction when you release the mapping.
Before setting up DMA, configure the address range the hardware supports. During probe, a driver whose hardware supports the same address width for streaming mappings and coherent allocations can call dma_set_mask_and_coherent(dev, DMA_BIT_MASK(bits)). Here dev is the struct device for the hardware that performs DMA, and bits is the supported address width for the hardware mode the driver will use. The call sets both the streaming and coherent DMA masks on success. It returns zero on success and a negative error on failure. Check that result before proceeding. If the call fails, the driver can try a narrower mask when the hardware supports that choice, or fail DMA setup and propagate the error when the device requires DMA.
A kernel type for an address used by a DMA device holds the address you get from the DMA API. Keep it in that type until you encode it in the device’s descriptor or address registers according to the hardware format. The address is usable by the device associated with the mapping for that mapping’s lifetime. The CPU accesses the same storage through its own memory references. A DMA address can differ from the underlying physical address, for example when an IOMMU translates device accesses. The DMA mask describes the device’s address capability. Each individual mapping still has a return value to check.
Describe the buffers and map the list
3 min readA struct scatterlist entry describes a memory region with a starting page, an offset within that page, and a length in bytes. An ordered list of these entries lets the driver describe one transfer over multiple regions. The entries follow the order in which the data belongs in the transfer. Their page addresses need no particular ordering. In the transmit example, the header entry comes first because the header belongs first in the packet, even if its page has a higher address than the payload’s page.
For a flat array of entries, call sg_init_table(sgl, nents) before filling it. This initializes the entries and marks the final one as the end of the list. Then fill each entry with sg_set_page() using the page, length, and offset for that region. The setter takes the length before the offset. Each entry must describe valid DMA-capable backing storage for the full range. When using separate pages, give each fragment its own entry. Keep the list and the backing storage alive until the mapping has been released.
The following kernel driver excerpt assumes sgl points to a flat array of nents entries, nents is positive, and the caller supplies equally sized arrays of valid page pointers, lengths, and offsets. Each range fits inside its backing page. The caller has already configured the device’s DMA mask. The DMA interfaces are declared through <linux/dma-mapping.h> and the scatterlist helpers through <linux/scatterlist.h>.
sg_init_table(sgl, nents);
for (int i = 0; i < nents; i++)
sg_set_page(&sgl[i], pages[i], lengths[i], offsets[i]);
mapped = dma_map_sg(dev, sgl, nents, DMA_TO_DEVICE);
if (!mapped)
return -EIO;
dma_map_sg() prepares the populated list for streaming DMA and returns the number of usable DMA segments. A zero return means the mapping failed. The request must leave the submission path at that point, without handing any descriptors to the device. The caller still owns the memory and the list and can release them through its normal error path. There is no successful mapping to pass to dma_unmap_sg() after a zero return.
On success, the DMA mapping implementation may combine adjacent ranges that it can represent as a single segment in the device’s DMA address space, subject to its mapping rules and segment limits. The result may also have the same number of segments as the input. The driver uses the returned count in either case. Every returned segment has a DMA address and a DMA length. Use sg_dma_address(sg) and sg_dma_len(sg) on each mapped entry to get that pair. If ranges were combined, a DMA length can cover bytes described by multiple input entries. The length used in a hardware descriptor must come from the mapped pair, even when the input entries had convenient sizes.
Mapping prepares addresses and lengths. The driver must still check that the resulting segments can be represented by the hardware’s descriptor format and fit the space available for this request before starting the transfer. For hardware with a finite descriptor table, a successful mapping whose segments do not fit still needs to be released. No transfer has to complete in that case because the driver has yet to give the device access through those descriptors.
Use the mapped count and release the original list
3 min readKeep two counts in the request state if submission and completion happen in different functions. The input count, nents, is the number passed to the mapper. The output count, mapped, is the number it returned. For hardware that can represent one mapped segment per descriptor, iterate with for_each_sg(sgl, sg, mapped, i) and put the DMA address and DMA length from each iteration into the corresponding hardware descriptor. Submit the descriptors in list order. The hardware’s completion mechanism tells the driver when the device has finished accessing those ranges.
After successful mapping, treat the streaming buffer as device-owned for this one-shot transfer. Prepare transmit data before mapping. After confirmed receive completion, unmap before the CPU reads the received bytes. Once the device has finished accessing the request, call dma_unmap_sg(dev, sgl, nents, direction) with the same device, list, original count, and direction used for the successful map. For the code excerpt, the direction at this stage is DMA_TO_DEVICE. After unmapping, the driver can reuse or free the backing storage when the request no longer needs it.
The same cleanup applies if the driver abandons a request after mapping but before submission. For a request already submitted, a timeout alone says only that the driver has waited too long. The driver must establish that the hardware has stopped accessing the buffer before unmapping or freeing it. These rules give three distinct outcomes to track in an error path. A failed map gives no mapping to release. A successful map followed by an abandoned submission can be released immediately if the device never got access. A submitted request keeps its mapping until hardware access has ended.
When the original and mapped counts happen to match, a driver that passes the wrong variable to unmap can appear to work. Review the call by tracing where the variable came from. The descriptor loop consumes the count returned by the mapper. Unmap consumes the count supplied to the mapper. Also trace the stored direction and device through the completion path, especially when transmit and receive share a cleanup function.
The DMA engine API is the next lesson. It explains how a driver submits work to a DMA controller through DMAengine, building on the distinction between preparing DMA mappings and starting a transfer. The practice below focuses on the mapping contract that applies before and after submission.
Key takeaways
- DMA direction describes the flow of bytes relative to the device.
- A dma_addr_t holds an address the specified device can use for DMA.
- dma_map_sg can return fewer DMA segments than the number of input entries.
- dma_unmap_sg takes the original input count and the same device and direction as the map call.
Reflect
- Explain to a colleague, in two sentences: choose a DMA direction from the device’s reads and writes to host memory.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationDynamic DMA mapping Guide
- Kernel documentationDynamic DMA mapping using the generic device
Official documentation first. Links checked when the lesson was published.