[PATCH] swiotlb: sync buffer when mapping FROM_DEVICE
From: Horia GeantÄ
Date: Wed May 22 2019 - 03:24:00 EST
>From the very beginning, the swiotlb implementation (and even before that,
pci implementation if we look in full git history) did not sync
the bounced buffer in case of DMA mapping using DMA_FROM_DEVICE direction.
However, this is incorrect since the device might not write to that area
at all (or might partially write to it), which leads to data corruption
in the sense that data in original buffer is lost (overwritten with
uninitialized data in the bounced buffer at DMA unmap time).
In general, DMA mapping using DMA_FROM_DEVICE does not mean existing data
should be thrown away.
Fix this by sync-ing the bounced buffer at DMA mapping time
irrespective of DMA direction.
Link: https://lore.kernel.org/lkml/584b54f6-bd12-d036-35e6-23eb2dabe811@xxxxxxx
Signed-off-by: Horia GeantÄ <horia.geanta@xxxxxxx>
---
I haven't provided a Fixes tag since this approach goes way back in time.
If you agree with the fix, we'll have to decide if it should go
into -stable and what's the earliest LTS branch to get the backport.
Patch is based on konrad/swiotlb.git, devel/for-linus-5.2 branch.
kernel/dma/swiotlb.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/kernel/dma/swiotlb.c b/kernel/dma/swiotlb.c
index 38d57218809c..f330222f0eb5 100644
--- a/kernel/dma/swiotlb.c
+++ b/kernel/dma/swiotlb.c
@@ -545,13 +545,14 @@ phys_addr_t swiotlb_tbl_map_single(struct device *hwdev,
/*
* Save away the mapping from the original address to the DMA address.
- * This is needed when we sync the memory. Then we sync the buffer if
- * needed.
+ * This is needed when we sync the memory. Then we sync the buffer
+ * irrespective of mapping direction - since for FROM_DEVICE we want to
+ * make sure original data is not lost in the case of device not fully
+ * overwriting the area mapped.
*/
for (i = 0; i < nslots; i++)
io_tlb_orig_addr[index+i] = orig_addr + (i << IO_TLB_SHIFT);
- if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC) &&
- (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL))
+ if (!(attrs & DMA_ATTR_SKIP_CPU_SYNC))
swiotlb_bounce(orig_addr, tlb_addr, size, DMA_TO_DEVICE);
return tlb_addr;
--
2.17.1