[PATCH] mm: fix pfn calculation mistake in __ioremap_check_ram

From: Yaohui Wang
Date: Mon Jun 07 2021 - 05:20:06 EST


According to the source code in function
arch/x86/mm/ioremap.c:__ioremap_caller, after __ioremap_check_mem, if the
mem range is IORES_MAP_SYSTEM_RAM, then __ioremap_caller should fail. But
because of the pfn calculation problem, __ioremap_caller can success
on IORES_MAP_SYSTEM_RAM region when the @size parameter is less than
PAGE_SIZE. This may cause misuse of the ioremap function and raise the
risk of performance issues. For example, ioremap(phys, PAGE_SIZE-1) may
cause the direct memory mapping of @phys to be uncached, and iounmap won't
revert this change. This patch fixes this issue.

In arch/x86/mm/ioremap.c:__ioremap_check_ram, start_pfn should wrap down
the res->start address, and end_pfn should wrap up the res->end address.
This makes the check more strict and should be more reasonable.

Signed-off-by: Ben Luo <luoben@xxxxxxxxxxxxxxxxx>
Signed-off-by: Yahui Wang <yaohuiwang@xxxxxxxxxxxxxxxxx>
---
arch/x86/mm/ioremap.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/arch/x86/mm/ioremap.c b/arch/x86/mm/ioremap.c
index 9e5ccc56f..79adf0d2d 100644
--- a/arch/x86/mm/ioremap.c
+++ b/arch/x86/mm/ioremap.c
@@ -74,8 +74,8 @@ static unsigned int __ioremap_check_ram(struct resource *res)
if ((res->flags & IORESOURCE_SYSTEM_RAM) != IORESOURCE_SYSTEM_RAM)
return 0;

- start_pfn = (res->start + PAGE_SIZE - 1) >> PAGE_SHIFT;
- stop_pfn = (res->end + 1) >> PAGE_SHIFT;
+ start_pfn = res->start >> PAGE_SHIFT;
+ stop_pfn = (res->end + PAGE_SIZE) >> PAGE_SHIFT;
if (stop_pfn > start_pfn) {
for (i = 0; i < (stop_pfn - start_pfn); ++i)
if (pfn_valid(start_pfn + i) &&
--
2.25.1