
Recall first from The QEMU edu device
- Edu exposes a 1 MiB BAR0 and uses 32-bit accesses in the low register range from 0x00 through 0x7f.
- Writing the factorial register starts a calculation, and reading it after completion returns the result.
- Edu requires a device-level acknowledgement for both MSI and legacy INTx.
What address does the device use?
3 min readThe last lesson ended with the edu device's DMA registers. This lesson answers the DMA machinery behind them: bus mastering, cache coherency, and the coherent and streaming mapping APIs.
A working CPU pointer can produce a broken DMA transfer. The kernel's Dynamic DMA mapping Guide describes why. The CPU can dereference a virtual address, while the device issues transactions in its own DMA address space. Even the CPU physical address of the buffer can differ from the address the device must issue. A driver that guesses the device address can appear to work on one machine and fail when address translation or the device's address limits differ. Dynamic DMA mapping Guide
With programmed I/O, or PIO, the CPU moves the payload by executing loads or stores against a device interface. A DMA transfer still usually begins with CPU writes to control registers. The difference is who moves the payload. A a device that can initiate transactions on the bus can read or write host memory while the CPU does other work. In a PCI driver, pci_set_master(pdev) enables bus mastering. The DMA API prepares memory for access. The device starts only when the driver submits work through its device-specific interface, and the driver learns when the work is done from the device's completion mechanism. Submission and completion are separate from mapping and unmapping. How To Write Linux PCI Drivers
Keep three address types straight. The CPU uses the kernel virtual pointer to initialize or inspect a buffer. The underlying RAM has a CPU physical address. The device uses the DMA address, stored by the driver in a dma_addr_t. An IOMMU can translate the device's DMA address to physical memory. A streaming mapping can also use a bounce buffer, with the DMA implementation copying data as required. The device address can therefore refer to a different location from the original allocation during a transfer. Use the mapping API's result for the device and keep the original pointer for the CPU and its eventual cleanup.
Addressability and visibility are separate problems. A device may be able to reach the right memory but still see old bytes if the CPU has modified a cache line that the device cannot observe. In the other direction, a device can write memory while the CPU still has an older copy cached. Cache coherency describes whether those views are kept consistent. Coherent DMA allocations provide that visibility through the platform's implementation. Streaming mappings let the DMA API do any necessary cache maintenance or copying at defined transitions. Both APIs also account for constraints that apply to the particular device.
Set the DMA masks before allocating or mapping. Use the struct device for the actual PCI function, &pdev->dev. If the hardware supports the same address width for both kinds of access, call dma_set_mask_and_coherent(dev, DMA_BIT_MASK(bits)) with the supported width in bits and check the return value. The width comes from the device's specification or configuration. If the device has different limits for streaming data and coherent structures, use dma_set_mask() and dma_set_coherent_mask() separately and check each result. A failed setup must stop that DMA path unless the driver can configure a supported alternative. Enabling PCI bus mastering does not set these masks.
Coherent allocations for shared control data
2 min readA device can repeatedly read descriptors or write completion records during the life of a queue. For this kind of shared control data, use dma_alloc_coherent(dev, size, &dma_handle, GFP_KERNEL) from sleepable setup code. The function returns a CPU pointer and stores the DMA address through dma_handle. Check the pointer for NULL before using either result. Save the pointer, DMA handle, and size in the driver if the allocation survives beyond the setup routine. A small coherent buffer is also convenient for learning the API without setting up a queue.
Initialize the buffer through the CPU pointer and use the DMA handle wherever the device expects the buffer's host address. Coherent memory needs no dma_sync_single_for_cpu() or dma_sync_single_for_device() calls. The driver still needs a protocol for deciding who may read or write each field. For example, if a device polls a descriptor's valid flag, first write the descriptor fields, then use dma_wmb() before writing the flag. That orders the preceding shared-memory writes before the device observes the publication flag. Accesses to device registers also follow the ordering rules of the device and the MMIO accessors.
Coherency also gives no indication that a write has happened yet. If a buffer is supposed to contain a device response, the CPU waits until the completion protocol says the response is ready before inspecting it. The device can retain and reuse the DMA handle across transfers while the allocation lives. On teardown, stop submissions and ensure that the device has finished with the buffer. Then call dma_free_coherent(dev, size, cpu_ptr, dma_handle) with the original arguments. Use the same cleanup if a later setup step fails after allocation, and make sure any hardware activity started by that step has stopped first.
Streaming mappings for payload buffers
6 min readA streaming mapping makes an existing buffer available for DMA over a defined lifetime. For a one-shot device read, allocate a dedicated payload buffer with kmalloc(size, GFP_KERNEL) and check for NULL. Fill it through the CPU pointer. Call dma_map_single(dev, buf, size, DMA_TO_DEVICE). That direction describes bytes traveling from host memory to the device, which is all the direction detail this example needs. Hold the result in a dma_addr_t and check dma_mapping_error(dev, dma_handle). On error, the device receives no address and there is no successful mapping to unmap. Release the CPU buffer and unwind any earlier allocations that belong to the failed operation.
After a successful map, the device owns the mapped range for DMA API purposes. Give the device the returned address and byte count and submit the transfer. Keep CPU reads and writes away from the range during device ownership, even on a system where a shortcut appears to work. Once you know the device has stopped accessing the range, call dma_unmap_single(dev, dma_handle, size, DMA_TO_DEVICE). Use the same device, base DMA address, size, and direction used for the mapping. The CPU can then access the buffer or release it with kfree(). The handle's lifetime ends at unmap. If waiting for completion times out, first establish that the device has stopped accessing the buffer before unmapping or freeing it. A timeout establishes only that the driver did not observe completion in time.
Sometimes a driver keeps the streaming mapping across submissions. For example, the CPU might inspect a buffer between transfers and then hand it back to the device. After device completion, call dma_sync_single_for_cpu(dev, dma_handle, size, dir) before accessing the range. Use the CPU pointer and follow the original direction's access rules. Call dma_sync_single_for_device(dev, dma_handle, size, dir) after CPU access and before handing the range back to the device. Here dir is the original mapping direction. These calls leave the address mapped. They synchronize memory at the ownership transition, while the driver still has to wait for completion and submit the next transfer explicitly. If the CPU leaves the range untouched between two completed or resubmitted device operations, it can leave ownership with the device. When retiring a one-shot mapping, unmap after completion and before touching the buffer. There is no intermediate CPU sync step in that sequence.
Use a buffer backed by suitable contiguous memory for dma_map_single(). A dedicated kmalloc() allocation works for a small payload. A stack object or vmalloc() buffer is unsuitable for this API, even if the CPU can access it as a continuous sequence of bytes. Keep the storage alive through the last device access and the final unmap. When both mapping types are used together, each retains its own cleanup rule. Free the coherent allocation with dma_free_coherent() and unmap the streaming buffer before freeing its storage.
Going deeperAlignment, boundaries, and scatterlist limits
A DMA buffer on a noncoherent system must avoid sharing cache lines with unrelated CPU-written data. Cache maintenance can affect a whole line, so mapping a field within a larger object can affect its neighbors. The device can also impose address or length alignment requirements. A boundary rule can require that the first and last bytes of a hardware segment lie within the same aligned window. Starting at an aligned address alone does not ensure this if the segment is too long.
Check the device's DMA constraints as well as the mapping API's limits. dma_max_mapping_size(dev) reports the maximum size of a single mapping. The DMA parameters accessible through dma_get_max_seg_size(dev) and dma_get_seg_boundary(dev) describe segment size and boundary constraints. The hardware can also limit how many segments fit in a request. A scatterlist is subject to those limits even if its total payload fits in memory. The next lesson covers how to map one and how mapping can change the number of segments presented to hardware.
Going deeperChecking mappings with DMA API debugging
Build and boot the Ubuntu guest kernel with CONFIG_DMA_API_DEBUG=y and CONFIG_DEBUG_FS=y. Use the running kernel's config file if installed under /boot, or consult the build configuration for the image you booted. With debugfs mounted at /sys/kernel/debug, read dma-api/error_count under that mount as root before and after exercising the driver. Read the kernel log with sudo dmesg and look for DMA API diagnostics associated with the test. The count is system-wide, so use the device or call site in any diagnostic to determine whether it came from your driver.
Log each returned DMA handle with %pad and pass its address, for example dev_info(dev, "stream DMA=%pad\n", &dma_handle). Log the size and mapping stage alongside it in your driver. Compare the logged value with the handle used when constructing the device request, if you submit one. You can also inspect /sys/kernel/debug/dma-api/dump as root while keeping a mapping live and look for the device's tracked address. A short-lived mapping can disappear before you read the dump, so log it at map and unmap time as well. DMA API debugging can catch errors such as passing the wrong size to unmap. It does not verify register programming or the bytes transferred. You can do the allocation and bookkeeping check without starting DMA on the device.
In the check run (Linux 6.8 built with CONFIG_DMA_API_DEBUG=y in QEMU with an edu device, a small test driver, an example: your addresses and index numbers will differ), the dma-api directory held all_errors, disabled, driver_filter, dump, error_count, min_free_entries, nr_total_entries, num_errors and num_free_entries. With one coherent buffer and one DMA_TO_DEVICE mapping alive, the dump contained one line for each:
dmadbg 0000:00:04.0 coherent idx 291 P=8247000 N=8247 D=8247000 L=40 ... DMA_BIDIRECTIONAL dma map error check not applicable
dmadbg 0000:00:04.0 single idx 298 P=8255380 N=8255 D=8255380 L=40 ... DMA_TO_DEVICE dma map error checked
D is the DMA address, matching the %pad value the driver logged, and L=40 is the length in hexadecimal (64 bytes). After unloading the driver, the lines were gone and error_count was still 0. When the driver was changed to unmap the 64-byte mapping with a size of 32, error_count became 1 and the log showed DMA-API: dmadbg 0000:00:04.0: device driver frees DMA memory with different size [device address=0x00000000084ca880] [map size=64 bytes] [unmap size=32 bytes].
Before moving on, trace one streaming buffer from its CPU pointer to the DMA address and back to CPU ownership. The next lesson, “DMA direction and scatter-gather,” explains how direction governs access and how the driver prepares a transfer whose payload spans several memory ranges.
Key takeaways
- 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.
- DMA API debugging checks API bookkeeping, while transfer completion and payload checks validate device behavior.
Reflect
- Explain to a colleague, in two sentences: distinguish CPU virtual, CPU physical, and device DMA addresses.
- 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: DMA addresses, memory, and mapping lifetimes
- Kernel documentationDynamic DMA mapping using the generic device: mapping constraints and DMA API debugging
- Kernel documentationHow To Write Linux PCI Drivers: DMA setup and PCI bus mastering
Official documentation first. Links checked when the lesson was published.