xref: /openbmc/linux/arch/mips/kernel/relocate.c (revision 457d2fc5)
1 /*
2  * This file is subject to the terms and conditions of the GNU General Public
3  * License.  See the file "COPYING" in the main directory of this archive
4  * for more details.
5  *
6  * Support for Kernel relocation at boot time
7  *
8  * Copyright (C) 2015, Imagination Technologies Ltd.
9  * Authors: Matt Redfearn (matt.redfearn@mips.com)
10  */
11 #include <asm/bootinfo.h>
12 #include <asm/cacheflush.h>
13 #include <asm/fw/fw.h>
14 #include <asm/sections.h>
15 #include <asm/setup.h>
16 #include <asm/timex.h>
17 #include <linux/elf.h>
18 #include <linux/kernel.h>
19 #include <linux/libfdt.h>
20 #include <linux/of_fdt.h>
21 #include <linux/sched/task.h>
22 #include <linux/start_kernel.h>
23 #include <linux/string.h>
24 #include <linux/printk.h>
25 
26 #define RELOCATED(x) ((void *)((long)x + offset))
27 
28 extern u32 _relocation_start[];	/* End kernel image / start relocation table */
29 extern u32 _relocation_end[];	/* End relocation table */
30 
31 extern long __start___ex_table;	/* Start exception table */
32 extern long __stop___ex_table;	/* End exception table */
33 
34 extern void __weak plat_fdt_relocated(void *new_location);
35 
36 /*
37  * This function may be defined for a platform to perform any post-relocation
38  * fixup necessary.
39  * Return non-zero to abort relocation
40  */
41 int __weak plat_post_relocation(long offset)
42 {
43 	return 0;
44 }
45 
46 static inline u32 __init get_synci_step(void)
47 {
48 	u32 res;
49 
50 	__asm__("rdhwr  %0, $1" : "=r" (res));
51 
52 	return res;
53 }
54 
55 static void __init sync_icache(void *kbase, unsigned long kernel_length)
56 {
57 	void *kend = kbase + kernel_length;
58 	u32 step = get_synci_step();
59 
60 	do {
61 		__asm__ __volatile__(
62 			"synci  0(%0)"
63 			: /* no output */
64 			: "r" (kbase));
65 
66 		kbase += step;
67 	} while (step && kbase < kend);
68 
69 	/* Completion barrier */
70 	__sync();
71 }
72 
73 static void __init apply_r_mips_64_rel(u32 *loc_new, long offset)
74 {
75 	*(u64 *)loc_new += offset;
76 }
77 
78 static void __init apply_r_mips_32_rel(u32 *loc_new, long offset)
79 {
80 	*loc_new += offset;
81 }
82 
83 static int __init apply_r_mips_26_rel(u32 *loc_orig, u32 *loc_new, long offset)
84 {
85 	unsigned long target_addr = (*loc_orig) & 0x03ffffff;
86 
87 	if (offset % 4) {
88 		pr_err("Dangerous R_MIPS_26 REL relocation\n");
89 		return -ENOEXEC;
90 	}
91 
92 	/* Original target address */
93 	target_addr <<= 2;
94 	target_addr += (unsigned long)loc_orig & 0xf0000000;
95 
96 	/* Get the new target address */
97 	target_addr += offset;
98 
99 	if ((target_addr & 0xf0000000) != ((unsigned long)loc_new & 0xf0000000)) {
100 		pr_err("R_MIPS_26 REL relocation overflow\n");
101 		return -ENOEXEC;
102 	}
103 
104 	target_addr -= (unsigned long)loc_new & 0xf0000000;
105 	target_addr >>= 2;
106 
107 	*loc_new = (*loc_new & ~0x03ffffff) | (target_addr & 0x03ffffff);
108 
109 	return 0;
110 }
111 
112 
113 static void __init apply_r_mips_hi16_rel(u32 *loc_orig, u32 *loc_new,
114 					 long offset)
115 {
116 	unsigned long insn = *loc_orig;
117 	unsigned long target = (insn & 0xffff) << 16; /* high 16bits of target */
118 
119 	target += offset;
120 
121 	*loc_new = (insn & ~0xffff) | ((target >> 16) & 0xffff);
122 }
123 
124 static int __init reloc_handler(u32 type, u32 *loc_orig, u32 *loc_new,
125 				long offset)
126 {
127 	switch (type) {
128 	case R_MIPS_64:
129 		apply_r_mips_64_rel(loc_new, offset);
130 		break;
131 	case R_MIPS_32:
132 		apply_r_mips_32_rel(loc_new, offset);
133 		break;
134 	case R_MIPS_26:
135 		return apply_r_mips_26_rel(loc_orig, loc_new, offset);
136 	case R_MIPS_HI16:
137 		apply_r_mips_hi16_rel(loc_orig, loc_new, offset);
138 		break;
139 	default:
140 		pr_err("Unhandled relocation type %d at 0x%pK\n", type,
141 		       loc_orig);
142 		return -ENOEXEC;
143 	}
144 
145 	return 0;
146 }
147 
148 static int __init do_relocations(void *kbase_old, void *kbase_new, long offset)
149 {
150 	u32 *r;
151 	u32 *loc_orig;
152 	u32 *loc_new;
153 	int type;
154 	int res;
155 
156 	for (r = _relocation_start; r < _relocation_end; r++) {
157 		/* Sentinel for last relocation */
158 		if (*r == 0)
159 			break;
160 
161 		type = (*r >> 24) & 0xff;
162 		loc_orig = kbase_old + ((*r & 0x00ffffff) << 2);
163 		loc_new = RELOCATED(loc_orig);
164 
165 		res = reloc_handler(type, loc_orig, loc_new, offset);
166 		if (res)
167 			return res;
168 	}
169 
170 	return 0;
171 }
172 
173 /*
174  * The exception table is filled in by the relocs tool after vmlinux is linked.
175  * It must be relocated separately since there will not be any relocation
176  * information for it filled in by the linker.
177  */
178 static int __init relocate_exception_table(long offset)
179 {
180 	unsigned long *etable_start, *etable_end, *e;
181 
182 	etable_start = RELOCATED(&__start___ex_table);
183 	etable_end = RELOCATED(&__stop___ex_table);
184 
185 	for (e = etable_start; e < etable_end; e++)
186 		*e += offset;
187 
188 	return 0;
189 }
190 
191 #ifdef CONFIG_RANDOMIZE_BASE
192 
193 static inline __init unsigned long rotate_xor(unsigned long hash,
194 					      const void *area, size_t size)
195 {
196 	size_t i;
197 	unsigned long *ptr = (unsigned long *)area;
198 
199 	for (i = 0; i < size / sizeof(hash); i++) {
200 		/* Rotate by odd number of bits and XOR. */
201 		hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7);
202 		hash ^= ptr[i];
203 	}
204 
205 	return hash;
206 }
207 
208 static inline __init unsigned long get_random_boot(void)
209 {
210 	unsigned long entropy = random_get_entropy();
211 	unsigned long hash = 0;
212 
213 	/* Attempt to create a simple but unpredictable starting entropy. */
214 	hash = rotate_xor(hash, linux_banner, strlen(linux_banner));
215 
216 	/* Add in any runtime entropy we can get */
217 	hash = rotate_xor(hash, &entropy, sizeof(entropy));
218 
219 #if defined(CONFIG_USE_OF)
220 	/* Get any additional entropy passed in device tree */
221 	if (initial_boot_params) {
222 		int node, len;
223 		u64 *prop;
224 
225 		node = fdt_path_offset(initial_boot_params, "/chosen");
226 		if (node >= 0) {
227 			prop = fdt_getprop_w(initial_boot_params, node,
228 					     "kaslr-seed", &len);
229 			if (prop && (len == sizeof(u64)))
230 				hash = rotate_xor(hash, prop, sizeof(*prop));
231 		}
232 	}
233 #endif /* CONFIG_USE_OF */
234 
235 	return hash;
236 }
237 
238 static inline __init bool kaslr_disabled(void)
239 {
240 	char *str;
241 
242 #if defined(CONFIG_CMDLINE_BOOL)
243 	const char *builtin_cmdline = CONFIG_CMDLINE;
244 
245 	str = strstr(builtin_cmdline, "nokaslr");
246 	if (str == builtin_cmdline ||
247 	    (str > builtin_cmdline && *(str - 1) == ' '))
248 		return true;
249 #endif
250 	str = strstr(arcs_cmdline, "nokaslr");
251 	if (str == arcs_cmdline || (str > arcs_cmdline && *(str - 1) == ' '))
252 		return true;
253 
254 	return false;
255 }
256 
257 static inline void __init *determine_relocation_address(void)
258 {
259 	/* Choose a new address for the kernel */
260 	unsigned long kernel_length;
261 	void *dest = &_text;
262 	unsigned long offset;
263 
264 	if (kaslr_disabled())
265 		return dest;
266 
267 	kernel_length = (long)_end - (long)(&_text);
268 
269 	offset = get_random_boot() << 16;
270 	offset &= (CONFIG_RANDOMIZE_BASE_MAX_OFFSET - 1);
271 	if (offset < kernel_length)
272 		offset += ALIGN(kernel_length, 0xffff);
273 
274 	return RELOCATED(dest);
275 }
276 
277 #else
278 
279 static inline void __init *determine_relocation_address(void)
280 {
281 	/*
282 	 * Choose a new address for the kernel
283 	 * For now we'll hard code the destination
284 	 */
285 	return (void *)0xffffffff81000000;
286 }
287 
288 #endif
289 
290 static inline int __init relocation_addr_valid(void *loc_new)
291 {
292 	if ((unsigned long)loc_new & 0x0000ffff) {
293 		/* Inappropriately aligned new location */
294 		return 0;
295 	}
296 	if ((unsigned long)loc_new < (unsigned long)&_end) {
297 		/* New location overlaps original kernel */
298 		return 0;
299 	}
300 	return 1;
301 }
302 
303 static inline void __init update_kaslr_offset(unsigned long *addr, long offset)
304 {
305 	unsigned long *new_addr = (unsigned long *)RELOCATED(addr);
306 
307 	*new_addr = (unsigned long)offset;
308 }
309 
310 #if defined(CONFIG_USE_OF)
311 void __weak *plat_get_fdt(void)
312 {
313 	return NULL;
314 }
315 #endif
316 
317 void *__init relocate_kernel(void)
318 {
319 	void *loc_new;
320 	unsigned long kernel_length;
321 	unsigned long bss_length;
322 	long offset = 0;
323 	int res = 1;
324 	/* Default to original kernel entry point */
325 	void *kernel_entry = start_kernel;
326 	void *fdt = NULL;
327 
328 	/* Get the command line */
329 	fw_init_cmdline();
330 #if defined(CONFIG_USE_OF)
331 	/* Deal with the device tree */
332 	fdt = plat_get_fdt();
333 	early_init_dt_scan(fdt);
334 	if (boot_command_line[0]) {
335 		/* Boot command line was passed in device tree */
336 		strlcpy(arcs_cmdline, boot_command_line, COMMAND_LINE_SIZE);
337 	}
338 #endif /* CONFIG_USE_OF */
339 
340 	kernel_length = (long)(&_relocation_start) - (long)(&_text);
341 	bss_length = (long)&__bss_stop - (long)&__bss_start;
342 
343 	loc_new = determine_relocation_address();
344 
345 	/* Sanity check relocation address */
346 	if (relocation_addr_valid(loc_new))
347 		offset = (unsigned long)loc_new - (unsigned long)(&_text);
348 
349 	/* Reset the command line now so we don't end up with a duplicate */
350 	arcs_cmdline[0] = '\0';
351 
352 	if (offset) {
353 		void (*fdt_relocated_)(void *) = NULL;
354 #if defined(CONFIG_USE_OF)
355 		unsigned long fdt_phys = virt_to_phys(fdt);
356 
357 		/*
358 		 * If built-in dtb is used then it will have been relocated
359 		 * during kernel _text relocation. If appended DTB is used
360 		 * then it will not be relocated, but it should remain
361 		 * intact in the original location. If dtb is loaded by
362 		 * the bootloader then it may need to be moved if it crosses
363 		 * the target memory area
364 		 */
365 
366 		if (fdt_phys >= virt_to_phys(RELOCATED(&_text)) &&
367 			fdt_phys <= virt_to_phys(RELOCATED(&_end))) {
368 			void *fdt_relocated =
369 				RELOCATED(ALIGN((long)&_end, PAGE_SIZE));
370 			memcpy(fdt_relocated, fdt, fdt_totalsize(fdt));
371 			fdt = fdt_relocated;
372 			fdt_relocated_ = RELOCATED(&plat_fdt_relocated);
373 		}
374 #endif /* CONFIG_USE_OF */
375 
376 		/* Copy the kernel to it's new location */
377 		memcpy(loc_new, &_text, kernel_length);
378 
379 		/* Perform relocations on the new kernel */
380 		res = do_relocations(&_text, loc_new, offset);
381 		if (res < 0)
382 			goto out;
383 
384 		/* Sync the caches ready for execution of new kernel */
385 		sync_icache(loc_new, kernel_length);
386 
387 		res = relocate_exception_table(offset);
388 		if (res < 0)
389 			goto out;
390 
391 		/*
392 		 * The original .bss has already been cleared, and
393 		 * some variables such as command line parameters
394 		 * stored to it so make a copy in the new location.
395 		 */
396 		memcpy(RELOCATED(&__bss_start), &__bss_start, bss_length);
397 
398 		/*
399 		 * If fdt was stored outside of the kernel image and
400 		 * had to be moved then update platform's state data
401 		 * with the new fdt location
402 		 */
403 		if (fdt_relocated_)
404 			fdt_relocated_(fdt);
405 
406 		/*
407 		 * Last chance for the platform to abort relocation.
408 		 * This may also be used by the platform to perform any
409 		 * initialisation required now that the new kernel is
410 		 * resident in memory and ready to be executed.
411 		 */
412 		if (plat_post_relocation(offset))
413 			goto out;
414 
415 		/* The current thread is now within the relocated image */
416 		__current_thread_info = RELOCATED(&init_thread_union);
417 
418 		/* Return the new kernel's entry point */
419 		kernel_entry = RELOCATED(start_kernel);
420 
421 		/* Error may occur before, so keep it at last */
422 		update_kaslr_offset(&__kaslr_offset, offset);
423 	}
424 out:
425 	return kernel_entry;
426 }
427 
428 /*
429  * Show relocation information on panic.
430  */
431 static void show_kernel_relocation(const char *level)
432 {
433 	if (__kaslr_offset > 0) {
434 		printk(level);
435 		pr_cont("Kernel relocated by 0x%pK\n", (void *)__kaslr_offset);
436 		pr_cont(" .text @ 0x%pK\n", _text);
437 		pr_cont(" .data @ 0x%pK\n", _sdata);
438 		pr_cont(" .bss  @ 0x%pK\n", __bss_start);
439 	}
440 }
441 
442 static int kernel_location_notifier_fn(struct notifier_block *self,
443 				       unsigned long v, void *p)
444 {
445 	show_kernel_relocation(KERN_EMERG);
446 	return NOTIFY_DONE;
447 }
448 
449 static struct notifier_block kernel_location_notifier = {
450 	.notifier_call = kernel_location_notifier_fn
451 };
452 
453 static int __init register_kernel_offset_dumper(void)
454 {
455 	atomic_notifier_chain_register(&panic_notifier_list,
456 				       &kernel_location_notifier);
457 	return 0;
458 }
459 __initcall(register_kernel_offset_dumper);
460