Topics / Linux Kernel & Device Drivers / Q31
How does mmap work in a driver?
Short answer: Implementing .mmap lets user space map device memory or a driver buffer directly into its address space, avoiding copies. The driver checks the requested size and offset in the vm_area_struct, then maps the pages: remap_pfn_range() (or io_remap_pfn_range / vm_iomap_memory()) for device registers or reserved physical memory, dma_mmap_coherent() for DMA buffers, or vm_insert_page/vm_map_pages for normal kernel pages. Register mappings must be uncached (pgprot_noncached / pgprot_device).
Mapping a DMA buffer to user space
static int mydev_mmap(struct file *f, struct vm_area_struct *vma)
{
struct mydev *d = f->private_data;
size_t size = vma->vm_end - vma->vm_start;
if (vma->vm_pgoff != 0 || size > d->buf_size)
return -EINVAL; /* never map more than you own */
return dma_mmap_coherent(d->dev, vma, d->buf, d->buf_dma, size);
}
Mapping a register page (e.g. for a user-space data path)
static int regs_mmap(struct file *f, struct vm_area_struct *vma)
{
struct mydev *d = f->private_data;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return vm_iomap_memory(vma, d->regs_phys, d->regs_len); /* checks size/offset for you */
}
User space
uint32_t *buf = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Points to discuss
- Security: validate size and offset; exposing registers can let user space break isolation (e.g. by programming DMA to arbitrary memory) — usually only for trusted or privileged processes, or use VFIO with an IOMMU.
- Lifetime: the mapping can outlive
close(); the buffer must stay valid until the VMA is unmapped (reference counting, orvm_operations_struct.close). - Synchronisation: user space and hardware now share memory directly: define a protocol (head/tail indices, memory barriers, cache maintenance for non-coherent buffers).
- Page-fault-based mapping: for large or lazily allocated buffers, implement
vm_ops->faultand insert pages on demand. - Frameworks provide this already: V4L2 (
VIDIOC_REQBUFS+ mmap), DRM dumb buffers/GEM, UIO, anddma-heap.