Re: [PATCH] kernel: dma: let dma use vmalloc area

From: Zhaoyang Huang
Date: Sun Nov 26 2023 - 22:29:48 EST


This patch arose from a real problem where the driver failed to use
dma_map_single(dev, ptr). The ptr is a vmalloc va which is mapped over
the reserve memory by dma_init_coherent_memory.

On Mon, Nov 27, 2023 at 11:09 AM zhaoyang.huang
<zhaoyang.huang@xxxxxxxxxx> wrote:
>
> From: Zhaoyang Huang <zhaoyang.huang@xxxxxxxxxx>
>
> memremap within dma_init_coherent_memory will map the given phys_addr
> into vmalloc area if the pa is not found during iterating iomem_resources,
> which conflict the rejection of vmalloc area in dma_map_single_attrs.
> IMO, it is find to let all valid virtual address be valid for DMA as the
> user will keep corresponding RAM safe for transfer.
>
> Signed-off-by: Zhaoyang Huang <zhaoyang.huang@xxxxxxxxxx>
> ---
> include/linux/dma-mapping.h | 12 +++++++-----
> kernel/dma/debug.c | 4 ----
> 2 files changed, 7 insertions(+), 9 deletions(-)
>
> diff --git a/include/linux/dma-mapping.h b/include/linux/dma-mapping.h
> index f0ccca16a0ac..7a7b87289d55 100644
> --- a/include/linux/dma-mapping.h
> +++ b/include/linux/dma-mapping.h
> @@ -328,12 +328,14 @@ static inline void dma_free_noncoherent(struct device *dev, size_t size,
> static inline dma_addr_t dma_map_single_attrs(struct device *dev, void *ptr,
> size_t size, enum dma_data_direction dir, unsigned long attrs)
> {
> - /* DMA must never operate on areas that might be remapped. */
> - if (dev_WARN_ONCE(dev, is_vmalloc_addr(ptr),
> - "rejecting DMA map of vmalloc memory\n"))
> - return DMA_MAPPING_ERROR;
> + struct page *page;
> +
> debug_dma_map_single(dev, ptr, size);
> - return dma_map_page_attrs(dev, virt_to_page(ptr), offset_in_page(ptr),
> + if (is_vmalloc_addr(ptr))
> + page = vmalloc_to_page(ptr);
> + else
> + page = virt_to_page(ptr);
> + return dma_map_page_attrs(dev, page, offset_in_page(ptr),
> size, dir, attrs);
> }
>
> diff --git a/kernel/dma/debug.c b/kernel/dma/debug.c
> index 06366acd27b0..51e1fe9a70aa 100644
> --- a/kernel/dma/debug.c
> +++ b/kernel/dma/debug.c
> @@ -1198,10 +1198,6 @@ void debug_dma_map_single(struct device *dev, const void *addr,
> if (!virt_addr_valid(addr))
> err_printk(dev, NULL, "device driver maps memory from invalid area [addr=%p] [len=%lu]\n",
> addr, len);
> -
> - if (is_vmalloc_addr(addr))
> - err_printk(dev, NULL, "device driver maps memory from vmalloc area [addr=%p] [len=%lu]\n",
> - addr, len);
> }
> EXPORT_SYMBOL(debug_dma_map_single);
>
> --
> 2.25.1
>