Blob Blame History Raw
From: Christoph Hellwig <hch@lst.de>
Date: Tue, 9 Jan 2018 23:40:57 +0100
Subject: dma-direct: retry allocations using GFP_DMA for small masks
Git-commit: 95f183916d4b0bc1943684948ecdd2469f1aa978
Patch-mainline: v4.16-rc1
References: jsc#SLE-6197 FATE#327012 bsc#1140559 LTC#173150

If an attempt to allocate memory succeeded, but isn't inside the
supported DMA mask, retry the allocation with GFP_DMA set as a
last resort.

Based on the x86 code, but an off by one error in what is now
dma_coherent_ok has been fixed vs the x86 code.

[ ptesarik: This is in fact a rewrite for dma-noop, taking only the
  idea from the original commit. ]

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Petr Tesarik <ptesarik@suse.com>
---
 lib/dma-noop.c |   16 ++++++++++++++++
 1 file changed, 16 insertions(+)

--- a/lib/dma-noop.c
+++ b/lib/dma-noop.c
@@ -16,6 +16,11 @@
 #define ARCH_ZONE_DMA_BITS 24
 #endif
 
+static bool dma_coherent_ok(struct device *dev, phys_addr_t phys, size_t size)
+{
+	return phys_to_dma(dev, phys) + size - 1 <= dev->coherent_dma_mask;
+}
+
 static void *dma_noop_alloc(struct device *dev, size_t size,
 			    dma_addr_t *dma_handle, gfp_t gfp,
 			    unsigned long attrs)
@@ -28,7 +33,18 @@ static void *dma_noop_alloc(struct devic
 	if (dev->coherent_dma_mask <= DMA_BIT_MASK(32) && !(gfp & GFP_DMA))
 		gfp |= GFP_DMA32;
 
+again:
 	ret = (void *)__get_free_pages(gfp, get_order(size));
+	if (ret && !dma_coherent_ok(dev, virt_to_phys(ret), size)) {
+		free_pages((unsigned long)ret, get_order(size));
+		ret = NULL;
+
+		if (dev->coherent_dma_mask < DMA_BIT_MASK(32) &&
+		    !(gfp & GFP_DMA)) {
+			gfp = (gfp & ~GFP_DMA32) | GFP_DMA;
+			goto again;
+		}
+	}
 	if (ret)
 		*dma_handle = virt_to_phys(ret);
 	return ret;