[PATCH] arm64: kasan: fix phys_to_virt() false positive on tag-based kasan

From: Walter Wu
Date: Mon Aug 19 2019 - 07:44:55 EST


__arm_v7s_unmap() call iopte_deref() to translate pyh_to_virt address,
but it will modify pointer tag into 0xff, so there is a false positive.

When enable tag-based kasan, phys_to_virt() function need to rewrite
its original pointer tag in order to avoid kasan report an incorrect
memory corruption.

BUG: KASAN: double-free or invalid-free in __arm_v7s_unmap+0x720/0xda4
Pointer tag: [ff], memory tag: [c1]

Call trace:
dump_backtrace+0x0/0x1d4
show_stack+0x14/0x1c
dump_stack+0xe8/0x140
print_address_description+0x80/0x2f0
kasan_report_invalid_free+0x58/0x74
__kasan_slab_free+0x1e4/0x220
kasan_slab_free+0xc/0x18
kmem_cache_free+0xfc/0x884
__arm_v7s_unmap+0x720/0xda4
__arm_v7s_map+0xc8/0x774
arm_v7s_map+0x80/0x158
mtk_iommu_map+0xb4/0xe0
iommu_map+0x154/0x450
iommu_map_sg+0xe4/0x150
iommu_dma_map_sg+0x214/0x4ec
__iommu_map_sg_attrs+0xf0/0x110
ion_map_dma_buf+0xe8/0x114
dma_buf_map_attachment+0x4c/0x80
disp_sync_prepare_buf+0x378/0x820
_ioctl_prepare_buffer+0x130/0x870
mtk_disp_mgr_ioctl+0x5c4/0xab0
do_vfs_ioctl+0x8e0/0x15a4
__arm64_sys_ioctl+0x8c/0xb4
el0_svc_common+0xe4/0x1e0
el0_svc_handler+0x30/0x3c
el0_svc+0x8/0xc

Signed-off-by: Walter Wu <walter-zh.wu@xxxxxxxxxxxx>
---
arch/arm64/include/asm/kasan.h | 1 -
arch/arm64/include/asm/memory.h | 10 ++++++++++
2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/arch/arm64/include/asm/kasan.h b/arch/arm64/include/asm/kasan.h
index b52aacd2c526..59894cafad60 100644
--- a/arch/arm64/include/asm/kasan.h
+++ b/arch/arm64/include/asm/kasan.h
@@ -5,7 +5,6 @@
#ifndef __ASSEMBLY__

#include <linux/linkage.h>
-#include <asm/memory.h>
#include <asm/pgtable-types.h>

#define arch_kasan_set_tag(addr, tag) __tag_set(addr, tag)
diff --git a/arch/arm64/include/asm/memory.h b/arch/arm64/include/asm/memory.h
index 8ffcf5a512bb..75af5ba9ff22 100644
--- a/arch/arm64/include/asm/memory.h
+++ b/arch/arm64/include/asm/memory.h
@@ -171,6 +171,7 @@

#include <linux/bitops.h>
#include <linux/mmdebug.h>
+#include <asm/kasan.h>

extern s64 memstart_addr;
/* PHYS_OFFSET - the physical address of the start of memory. */
@@ -282,7 +283,16 @@ static inline phys_addr_t virt_to_phys(const volatile void *x)
#define phys_to_virt phys_to_virt
static inline void *phys_to_virt(phys_addr_t x)
{
+#ifdef CONFIG_KASAN_SW_TAGS
+ unsigned long addr = __phys_to_virt(x);
+ u8 *tag = (void *)(addr >> KASAN_SHADOW_SCALE_SHIFT)
+ + KASAN_SHADOW_OFFSET;
+
+ addr = __tag_set(addr, *tag);
+ return (void *)addr;
+#else
return (void *)(__phys_to_virt(x));
+#endif
}

/*
--
2.18.0