Re: [PATCH 2/2] x86/mm/KASLR: Adjust the vmemmap size according to paging mode

Baoquan He
2018-08-30T15:25:20Z

Hi Kirill,

I made a new version according to your suggestion, just a little
different, I didn't make 1TB as default, just calculate with the actual
size, then align up to 1TB boundary. Just found kcore is printing more
entries than before, I thought it's caused by my code, later got it was
touchde by other people.

Any comment about this? I can change accordingly.

From b19955ec5d439f7cb580331c83a27ad5753b06b6 Mon Sep 17 00:00:00 2001
From: Baoquan He <bhe@redhat.com>
Date: Thu, 30 Aug 2018 11:45:13 +0800
Subject: [PATCH] x86/mm/KASLR: Calculate the actual size of vmemmap region

Vmemmap region has different maximum size depending on paging mode,
now its size is hardcoded as 1TB in memory KASLR. This is not
right for 5-level paging mode. It will cause overflow if vmemmap
region is randomized to be adjacent to cpu_entry_area region and
its actual size is bigger than 1TB.

So here calculate how many TB by the actual size of vmemmap region
and align to 1TB boundary.

Signed-off-by: Baoquan He <bhe@redhat.com>
---
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 0988971069c9..1db8e166455e 100644
--- a/arch/x86/mm/kaslr.c
+++ b/arch/x86/mm/kaslr.c
@@ -51,7 +51,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 */
@@ -77,6 +77,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;
@@ -108,6 +109,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 align 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.13.6