[PATCH 2/2] x86/mm/KASLR: Calculate the actual size of vmemmap region

From: Baoquan He
Date: Wed Apr 03 2019 - 22:03:41 EST


Vmemmap region has different maximum size depending on paging mode.
However, its size is hardcoded as 1TB during memory KASLR handling,
this is not right for 5-level paging mode since it will cause vital
stumping if vmemmap region is randomized to be very close to the
following cpu_entry_area region and the actual size of vmemmap is much
bigger than 1 TB.

So here calculate how many TB needed by the actual size of vmemmap
region and align up to 1TB boundary. In 4-level the size will be
1 TB always since the max is 1 TB. In 5-level it's variable so that
space can be saved for randomization.

Signed-off-by: Baoquan He <bhe@xxxxxxxxxx>
---
arch/x86/mm/kaslr.c | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/arch/x86/mm/kaslr.c b/arch/x86/mm/kaslr.c
index 387d4ed25d7c..4679a0075048 100644
--- a/arch/x86/mm/kaslr.c
+++ b/arch/x86/mm/kaslr.c
@@ -52,7 +52,7 @@ static __initdata struct kaslr_memory_region {
} kaslr_regions[] = {
{ &page_offset_base, 0 },
{ &vmalloc_base, 0 },
- { &vmemmap_base, 1 },
+ { &vmemmap_base, 0 },
};

/* Get size in bytes used by the memory region */
@@ -78,6 +78,7 @@ void __init kernel_randomize_memory(void)
unsigned long rand, memory_tb;
struct rnd_state rand_state;
unsigned long remain_entropy;
+ unsigned long vmemmap_size;

vaddr_start = pgtable_l5_enabled() ? __PAGE_OFFSET_BASE_L5 : __PAGE_OFFSET_BASE_L4;
vaddr = vaddr_start;
@@ -109,6 +110,14 @@ void __init kernel_randomize_memory(void)
if (memory_tb < kaslr_regions[0].size_tb)
kaslr_regions[0].size_tb = memory_tb;

+ /**
+ * Calculate how many TB vmemmap region needs, and aligned to
+ * 1TB boundary.
+ */
+ vmemmap_size = (kaslr_regions[0].size_tb << (TB_SHIFT - PAGE_SHIFT)) *
+ sizeof(struct page);
+ kaslr_regions[2].size_tb = DIV_ROUND_UP(vmemmap_size, 1UL << TB_SHIFT);
+
/* Calculate entropy available between regions */
remain_entropy = vaddr_end - vaddr_start;
for (i = 0; i < ARRAY_SIZE(kaslr_regions); i++)
--
2.17.2