dma-direct: check for overflows on 32 bit DMA addresses
authorNicolas Saenz Julienne <nsaenzjulienne@suse.de>
Thu, 7 Nov 2019 15:06:44 +0000 (16:06 +0100)
committerpopcornmix <popcornmix@gmail.com>
Wed, 1 Jul 2020 15:33:25 +0000 (16:33 +0100)
As seen on the new Raspberry Pi 4 and sta2x11's DMA implementation it is
possible for a device configured with 32 bit DMA addresses and a partial
DMA mapping located at the end of the address space to overflow. It
happens when a higher physical address, not DMAable, is translated to
it's DMA counterpart.

For example the Raspberry Pi 4, configurable up to 4 GB of memory, has
an interconnect capable of addressing the lower 1 GB of physical memory
with a DMA offset of 0xc0000000. It transpires that, any attempt to
translate physical addresses higher than the first GB will result in an
overflow which dma_capable() can't detect as it only checks for
addresses bigger then the maximum allowed DMA address.

Fix this by verifying in dma_capable() if the DMA address range provided
is at any point lower than the minimum possible DMA address on the bus.

Signed-off-by: Nicolas Saenz Julienne <nsaenzjulienne@suse.de>
Signed-off-by: Christoph Hellwig <hch@lst.de>
(cherry picked from commit b12d66278dd627cbe1ea7c000aa4715aaf8830c8)

include/linux/dma-direct.h

index d03af36..7aadb77 100644 (file)
@@ -3,10 +3,13 @@
 #define _LINUX_DMA_DIRECT_H 1
 
 #include <linux/dma-mapping.h>
+#include <linux/memblock.h> /* for min_low_pfn */
 #include <linux/mem_encrypt.h>
 
 extern unsigned int zone_dma_bits;
 
+static inline dma_addr_t phys_to_dma(struct device *dev, phys_addr_t paddr);
+
 #ifdef CONFIG_ARCH_HAS_PHYS_TO_DMA
 #include <asm/dma-direct.h>
 #else
@@ -26,11 +29,16 @@ static inline phys_addr_t __dma_to_phys(struct device *dev, dma_addr_t dev_addr)
 
 static inline bool dma_capable(struct device *dev, dma_addr_t addr, size_t size)
 {
+       dma_addr_t end = addr + size - 1;
+
        if (!dev->dma_mask)
                return false;
 
-       return addr + size - 1 <=
-               min_not_zero(*dev->dma_mask, dev->bus_dma_mask);
+       if (!IS_ENABLED(CONFIG_ARCH_DMA_ADDR_T_64BIT) &&
+           min(addr, end) < phys_to_dma(dev, PFN_PHYS(min_low_pfn)))
+               return false;
+
+       return end <= min_not_zero(*dev->dma_mask, dev->bus_dma_mask);
 }
 #endif /* !CONFIG_ARCH_HAS_PHYS_TO_DMA */