1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2016 Linaro Ltd <ard.biesheuvel@linaro.org>
6 #include <linux/cache.h>
7 #include <linux/crc32.h>
8 #include <linux/init.h>
9 #include <linux/libfdt.h>
10 #include <linux/mm_types.h>
11 #include <linux/sched.h>
12 #include <linux/types.h>
13 #include <linux/pgtable.h>
14 #include <linux/random.h>
16 #include <asm/fixmap.h>
17 #include <asm/kernel-pgtable.h>
18 #include <asm/memory.h>
20 #include <asm/sections.h>
21 #include <asm/setup.h>
23 u64 __ro_after_init module_alloc_base;
24 u16 __initdata memstart_offset_seed;
26 struct arm64_ftr_override kaslr_feature_override __initdata;
28 static int __init kaslr_init(void)
34 * Set a reasonable default for module_alloc_base in case
35 * we end up running with module randomization disabled.
37 module_alloc_base = (u64)_etext - MODULES_VSIZE;
39 if (kaslr_feature_override.val & kaslr_feature_override.mask & 0xf) {
40 pr_info("KASLR disabled on command line\n");
44 if (!kaslr_offset()) {
45 pr_warn("KASLR disabled due to lack of seed\n");
49 pr_info("KASLR enabled\n");
52 * KASAN without KASAN_VMALLOC does not expect the module region to
53 * intersect the vmalloc region, since shadow memory is allocated for
54 * each module at load time, whereas the vmalloc region will already be
55 * shadowed by KASAN zero pages.
57 BUILD_BUG_ON((IS_ENABLED(CONFIG_KASAN_GENERIC) ||
58 IS_ENABLED(CONFIG_KASAN_SW_TAGS)) &&
59 !IS_ENABLED(CONFIG_KASAN_VMALLOC));
61 seed = get_random_u32();
63 if (IS_ENABLED(CONFIG_RANDOMIZE_MODULE_REGION_FULL)) {
65 * Randomize the module region over a 2 GB window covering the
66 * kernel. This reduces the risk of modules leaking information
67 * about the address of the kernel itself, but results in
68 * branches between modules and the core kernel that are
69 * resolved via PLTs. (Branches between modules will be
72 module_range = SZ_2G - (u64)(_end - _stext);
73 module_alloc_base = max((u64)_end - SZ_2G, (u64)MODULES_VADDR);
76 * Randomize the module region by setting module_alloc_base to
77 * a PAGE_SIZE multiple in the range [_etext - MODULES_VSIZE,
78 * _stext) . This guarantees that the resulting region still
79 * covers [_stext, _etext], and that all relative branches can
80 * be resolved without veneers unless this region is exhausted
81 * and we fall back to a larger 2GB window in module_alloc()
82 * when ARM64_MODULE_PLTS is enabled.
84 module_range = MODULES_VSIZE - (u64)(_etext - _stext);
87 /* use the lower 21 bits to randomize the base of the module region */
88 module_alloc_base += (module_range * (seed & ((1 << 21) - 1))) >> 21;
89 module_alloc_base &= PAGE_MASK;
93 subsys_initcall(kaslr_init)