1
2
3
4
5
6
7
8
9#include <linux/crc32.h>
10#include <linux/init.h>
11#include <linux/libfdt.h>
12#include <linux/mm_types.h>
13#include <linux/sched.h>
14#include <linux/types.h>
15
16#include <asm/fixmap.h>
17#include <asm/kernel-pgtable.h>
18#include <asm/memory.h>
19#include <asm/mmu.h>
20#include <asm/pgtable.h>
21#include <asm/sections.h>
22
23u64 __read_mostly module_alloc_base;
24u16 __initdata memstart_offset_seed;
25
26static __init u64 get_kaslr_seed(void *fdt)
27{
28 int node, len;
29 u64 *prop;
30 u64 ret;
31
32 node = fdt_path_offset(fdt, "/chosen");
33 if (node < 0)
34 return 0;
35
36 prop = fdt_getprop_w(fdt, node, "kaslr-seed", &len);
37 if (!prop || len != sizeof(u64))
38 return 0;
39
40 ret = fdt64_to_cpu(*prop);
41 *prop = 0;
42 return ret;
43}
44
45static __init const u8 *get_cmdline(void *fdt)
46{
47 static __initconst const u8 default_cmdline[] = CONFIG_CMDLINE;
48
49 if (!IS_ENABLED(CONFIG_CMDLINE_FORCE)) {
50 int node;
51 const u8 *prop;
52
53 node = fdt_path_offset(fdt, "/chosen");
54 if (node < 0)
55 goto out;
56
57 prop = fdt_getprop(fdt, node, "bootargs", NULL);
58 if (!prop)
59 goto out;
60 return prop;
61 }
62out:
63 return default_cmdline;
64}
65
66extern void *__init __fixmap_remap_fdt(phys_addr_t dt_phys, int *size,
67 pgprot_t prot);
68
69
70
71
72
73
74
75
76
77u64 __init kaslr_early_init(u64 dt_phys)
78{
79 void *fdt;
80 u64 seed, offset, mask, module_range;
81 const u8 *cmdline, *str;
82 int size;
83
84
85
86
87
88 module_alloc_base = (u64)_etext - MODULES_VSIZE;
89
90
91
92
93
94
95 early_fixmap_init();
96 fdt = __fixmap_remap_fdt(dt_phys, &size, PAGE_KERNEL);
97 if (!fdt)
98 return 0;
99
100
101
102
103 seed = get_kaslr_seed(fdt);
104 if (!seed)
105 return 0;
106
107
108
109
110
111 cmdline = get_cmdline(fdt);
112 str = strstr(cmdline, "nokaslr");
113 if (str == cmdline || (str > cmdline && *(str - 1) == ' '))
114 return 0;
115
116
117
118
119
120
121
122
123
124 mask = ((1UL << (VA_BITS - 2)) - 1) & ~(SZ_2M - 1);
125 offset = seed & mask;
126
127
128 memstart_offset_seed = seed >> 48;
129
130
131
132
133
134
135 if ((((u64)_text + offset) >> SWAPPER_TABLE_SHIFT) !=
136 (((u64)_end + offset) >> SWAPPER_TABLE_SHIFT))
137 offset = (offset + (u64)(_end - _text)) & mask;
138
139 if (IS_ENABLED(CONFIG_KASAN))
140
141
142
143
144
145
146
147 return offset;
148
149 if (IS_ENABLED(CONFIG_RANDOMIZE_MODULE_REGION_FULL)) {
150
151
152
153
154
155
156
157
158 module_range = VMALLOC_END - VMALLOC_START - MODULES_VSIZE;
159 module_alloc_base = VMALLOC_START;
160 } else {
161
162
163
164
165
166
167
168 module_range = MODULES_VSIZE - (u64)(_etext - _stext);
169 module_alloc_base = (u64)_etext + offset - MODULES_VSIZE;
170 }
171
172
173 module_alloc_base += (module_range * (seed & ((1 << 21) - 1))) >> 21;
174 module_alloc_base &= PAGE_MASK;
175
176 return offset;
177}
178