BACKPORT: FROMLIST: arm64: mm: support ARCH_MMAP_RND_BITS.

(cherry picked from commit https://lkml.org/lkml/2015/12/21/340)

arm64: arch_mmap_rnd() uses STACK_RND_MASK to generate the
random offset for the mmap base address.  This value represents a
compromise between increased ASLR effectiveness and avoiding
address-space fragmentation. Replace it with a Kconfig option, which
is sensibly bounded, so that platform developers may choose where to
place this compromise. Keep default values as new minimums.

Signed-off-by: Daniel Cashman <dcashman@android.com>
Signed-off-by: Daniel Cashman <dcashman@google.com>

Bug: 27796957
Patchset: ASLR sysctl

Change-Id: I9192fa3dd0e061066985b48c84d95c88710282db
Signed-off-by: Kees Cook <keescook@google.com>
diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig
index 11dfd3f..3c69f7e 100644
--- a/arch/arm64/Kconfig
+++ b/arch/arm64/Kconfig
@@ -29,6 +29,8 @@
 	select GENERIC_TIME_VSYSCALL
 	select HARDIRQS_SW_RESEND
 	select HAVE_ARCH_JUMP_LABEL
+	select HAVE_ARCH_MMAP_RND_BITS
+	select HAVE_ARCH_MMAP_RND_COMPAT_BITS if COMPAT
 	select HAVE_ARCH_TRACEHOOK
 	select HAVE_DEBUG_BUGVERBOSE
 	select HAVE_DEBUG_KMEMLEAK
@@ -434,6 +436,25 @@
 config SYS_SUPPORTS_HUGETLBFS
 	def_bool y
 
+config ARCH_MMAP_RND_BITS_MIN
+	default 14 if ARM64_64K_PAGES
+	default 18
+
+# max bits determined by the following formula:
+#  VA_BITS - PAGE_SHIFT - 3
+#  VA_BITS depends on 64K_PAGES, either
+#  42 if 64K_PAGES or 39 otherwise
+config ARCH_MMAP_RND_BITS_MAX
+	default 23 if ARM64_64K_PAGES
+	default 24
+
+config ARCH_MMAP_RND_COMPAT_BITS_MIN
+	default 7 if ARM64_64K_PAGES
+	default 11
+
+config ARCH_MMAP_RND_COMPAT_BITS_MAX
+	default 16
+
 config ARCH_WANT_GENERAL_HUGETLB
 	def_bool y
 
diff --git a/arch/arm64/mm/mmap.c b/arch/arm64/mm/mmap.c
index 8ed6cb1..ab79843 100644
--- a/arch/arm64/mm/mmap.c
+++ b/arch/arm64/mm/mmap.c
@@ -47,22 +47,19 @@
 	return sysctl_legacy_va_layout;
 }
 
-/*
- * Since get_random_int() returns the same value within a 1 jiffy window, we
- * will almost always get the same randomisation for the stack and mmap
- * region. This will mean the relative distance between stack and mmap will be
- * the same.
- *
- * To avoid this we can shift the randomness by 1 bit.
- */
 static unsigned long mmap_rnd(void)
 {
 	unsigned long rnd = 0;
 
-	if (current->flags & PF_RANDOMIZE)
-		rnd = (long)get_random_int() & (STACK_RND_MASK >> 1);
-
-	return rnd << (PAGE_SHIFT + 1);
+	if (current->flags & PF_RANDOMIZE) {
+#ifdef CONFIG_COMPAT
+		if (test_thread_flag(TIF_32BIT))
+			rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_compat_bits) - 1);
+		else
+#endif
+			rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1);
+	}
+	return rnd << PAGE_SHIFT;
 }
 
 static unsigned long mmap_base(void)