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: Ic81409f45c8025c63419558df8b43ec9ec478082
Signed-off-by: Kees Cook <keescook@google.com>
diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig
index 372eb82..4e42f60 100644
--- a/arch/arm64/Kconfig
+++ b/arch/arm64/Kconfig
@@ -32,6 +32,8 @@
 	select HARDIRQS_SW_RESEND
 	select HAVE_ARCH_JUMP_LABEL
 	select HAVE_ARCH_KGDB
+	select HAVE_ARCH_MMAP_RND_BITS
+	select HAVE_ARCH_MMAP_RND_COMPAT_BITS if COMPAT
 	select HAVE_ARCH_TRACEHOOK
 	select HAVE_C_RECORDMCOUNT
 	select HAVE_DEBUG_BUGVERBOSE
@@ -358,6 +360,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 8f7ffff..ab79843 100644
--- a/arch/arm64/mm/mmap.c
+++ b/arch/arm64/mm/mmap.c
@@ -51,9 +51,14 @@
 {
 	unsigned long rnd = 0;
 
-	if (current->flags & PF_RANDOMIZE)
-		rnd = (long)get_random_int() & STACK_RND_MASK;
-
+	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;
 }