It is possible, when a very large mapping uses only one
scatterlist, that padding overflows scatterlist's length field.
This results in:
 1) silently wrapping the value
 2) smaller than desired mappings produced by iommu_map_sg
 3) leaving mapped bytes in memory (no iommu_unmap)

Address this issue by adding overflow detection for scatterlist
length field.

Fixes: 809eac54cdd6 ("iommu/dma: Implement scatterlist segment merging")
Signed-off-by: Krzysztof Karas <[email protected]>
---
v3:
 * Used check_add_overflow suggested by Jason.

I decided not to include previous r-bs due to the change in the
core of this patch: overflows_type -> check_add_overflow and I
obvserved some folks have heavy preference for one or the other.

 drivers/iommu/dma-iommu.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/drivers/iommu/dma-iommu.c b/drivers/iommu/dma-iommu.c
index 381b60d9e7ce..1a36fd9bf10b 100644
--- a/drivers/iommu/dma-iommu.c
+++ b/drivers/iommu/dma-iommu.c
@@ -1493,7 +1493,18 @@ int iommu_dma_map_sg(struct device *dev, struct 
scatterlist *sg, int nents,
                 *   time through here (i.e. before it has a meaningful value).
                 */
                if (pad_len && pad_len < s_length - 1) {
-                       prev->length += pad_len;
+                       unsigned int new_pad_len;
+                       /*
+                        * For large mappings spanning multiple GBs we
+                        * may not be able to fit all needed padding into
+                        * sg->length.
+                        */
+                       if (check_add_overflow(prev->length, pad_len, 
&new_pad_len)) {
+                               ret = -EOVERFLOW;
+                               goto out_restore_sg;
+                       }
+
+                       prev->length = new_pad_len;
                        iova_len += pad_len;
                }
 
-- 
2.34.1

Reply via email to