Why dma_alloc_coherent don't return direct mapped vaddr?

Li Chen me at linux.beauty
Thu Jul 21 19:57:46 PDT 2022


Hi Arnd,
 ---- On Thu, 21 Jul 2022 15:06:57 +0800  Arnd Bergmann <arnd at arndb.de> wrote --- 
 > On Thu, Jul 21, 2022 at 5:28 AM Li Chen <me at linux.beauty> wrote:
 > >
 > > Hi Arnd,
 > >
 > > dma_alloc_coherent two addr:
 > > 1. vaddr.
 > > 2. dma_addr
 > >
 > > I noticed vaddr is not simply linear/direct mapped to dma_addr, which means I cannot use virt_to_phys/virt_to_page to get
 > > paddr/page. Instead, I should use dma_addr as paddr and phys_to_page(dma_addr) to get struct page.
 > >
 > > My question is why dma_alloc_coherent not simply return phys_to_virt(dma_addr)? IOW, why vaddr is
 > > not directly mapped to dma_addr?
 > 
 > dma_alloc_coherent() tries to allocate memory that is the correct type
 > for the device you
 > pass. If the device is not itself marked as cache coherent in the DT,
 > then it has to use
 > an uncached mapping.
 > 
 > The normal linear map of all memory into the kernel address space is
 > cacheable, so this
 > device can't use it, and you instead get a new mapping into kernel
 > space at a different
 > virtual address.
 > 
 > Note that you should never need a 'struct page' in this case, as the
 > device needs a physical
 > ddress and access from kernel space just needs a pointer. Calling
 > phys_to_page() on
 > a dma_addr_t is not portable because a lot of devices have DMA
 > addresses that are not
 > the same number as the physical address as seen by the CPU, or there
 > may be an IOMMU
 > in between.

Thanks for your answer! My device is a misc character device, just like https://lwn.net/ml/linux-kernel/20220711122459.13773-5-me@linux.beauty/. IIUC, its dma_addr is always the same with phy addr. If I want to alloc from reserved memory and then mmap to userspace with vm_insert_pages, are cma_alloc/dma_alloc_contigous/dma_alloc_from_contigous better choices?

Regards,
Li



More information about the linux-arm-kernel mailing list