xref: /linux/arch/powerpc/kexec/core_64.c (revision cd80afff4877e1151ce53d48b65eba9de80ac1d2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * PPC64 code to handle Linux booting another kernel.
4  *
5  * Copyright (C) 2004-2005, IBM Corp.
6  *
7  * Created by: Milton D Miller II
8  */
9 
10 
11 #include <linux/kexec.h>
12 #include <linux/smp.h>
13 #include <linux/thread_info.h>
14 #include <linux/init_task.h>
15 #include <linux/errno.h>
16 #include <linux/kernel.h>
17 #include <linux/cpu.h>
18 #include <linux/hardirq.h>
19 #include <linux/of.h>
20 #include <linux/libfdt.h>
21 
22 #include <asm/page.h>
23 #include <asm/current.h>
24 #include <asm/machdep.h>
25 #include <asm/cacheflush.h>
26 #include <asm/firmware.h>
27 #include <asm/paca.h>
28 #include <asm/mmu.h>
29 #include <asm/sections.h>	/* _end */
30 #include <asm/setup.h>
31 #include <asm/smp.h>
32 #include <asm/hw_breakpoint.h>
33 #include <asm/svm.h>
34 #include <asm/ultravisor.h>
35 #include <asm/crashdump-ppc64.h>
36 
machine_kexec_prepare(struct kimage * image)37 int machine_kexec_prepare(struct kimage *image)
38 {
39 	int i;
40 	unsigned long begin, end;	/* limits of segment */
41 	unsigned long low, high;	/* limits of blocked memory range */
42 	struct device_node *node;
43 	const unsigned long *basep;
44 	const unsigned int *sizep;
45 
46 	/*
47 	 * Since we use the kernel fault handlers and paging code to
48 	 * handle the virtual mode, we must make sure no destination
49 	 * overlaps kernel static data or bss.
50 	 */
51 	for (i = 0; i < image->nr_segments; i++)
52 		if (image->segment[i].mem < __pa(_end))
53 			return -ETXTBSY;
54 
55 	/* We also should not overwrite the tce tables */
56 	for_each_node_by_type(node, "pci") {
57 		basep = of_get_property(node, "linux,tce-base", NULL);
58 		sizep = of_get_property(node, "linux,tce-size", NULL);
59 		if (basep == NULL || sizep == NULL)
60 			continue;
61 
62 		low = *basep;
63 		high = low + (*sizep);
64 
65 		for (i = 0; i < image->nr_segments; i++) {
66 			begin = image->segment[i].mem;
67 			end = begin + image->segment[i].memsz;
68 
69 			if ((begin < high) && (end > low)) {
70 				of_node_put(node);
71 				return -ETXTBSY;
72 			}
73 		}
74 	}
75 
76 	return 0;
77 }
78 
79 /* Called during kexec sequence with MMU off */
copy_segments(unsigned long ind)80 static notrace void copy_segments(unsigned long ind)
81 {
82 	unsigned long entry;
83 	unsigned long *ptr;
84 	void *dest;
85 	void *addr;
86 
87 	/*
88 	 * We rely on kexec_load to create a lists that properly
89 	 * initializes these pointers before they are used.
90 	 * We will still crash if the list is wrong, but at least
91 	 * the compiler will be quiet.
92 	 */
93 	ptr = NULL;
94 	dest = NULL;
95 
96 	for (entry = ind; !(entry & IND_DONE); entry = *ptr++) {
97 		addr = __va(entry & PAGE_MASK);
98 
99 		switch (entry & IND_FLAGS) {
100 		case IND_DESTINATION:
101 			dest = addr;
102 			break;
103 		case IND_INDIRECTION:
104 			ptr = addr;
105 			break;
106 		case IND_SOURCE:
107 			copy_page(dest, addr);
108 			dest += PAGE_SIZE;
109 		}
110 	}
111 }
112 
113 /* Called during kexec sequence with MMU off */
kexec_copy_flush(struct kimage * image)114 notrace void kexec_copy_flush(struct kimage *image)
115 {
116 	long i, nr_segments = image->nr_segments;
117 	struct  kexec_segment ranges[KEXEC_SEGMENT_MAX];
118 
119 	/* save the ranges on the stack to efficiently flush the icache */
120 	memcpy(ranges, image->segment, sizeof(ranges));
121 
122 	/*
123 	 * After this call we may not use anything allocated in dynamic
124 	 * memory, including *image.
125 	 *
126 	 * Only globals and the stack are allowed.
127 	 */
128 	copy_segments(image->head);
129 
130 	/*
131 	 * we need to clear the icache for all dest pages sometime,
132 	 * including ones that were in place on the original copy
133 	 */
134 	for (i = 0; i < nr_segments; i++)
135 		flush_icache_range((unsigned long)__va(ranges[i].mem),
136 			(unsigned long)__va(ranges[i].mem + ranges[i].memsz));
137 }
138 
139 #ifdef CONFIG_SMP
140 
141 static int kexec_all_irq_disabled = 0;
142 
kexec_smp_down(void * arg)143 static void kexec_smp_down(void *arg)
144 {
145 	local_irq_disable();
146 	hard_irq_disable();
147 
148 	mb(); /* make sure our irqs are disabled before we say they are */
149 	get_paca()->kexec_state = KEXEC_STATE_IRQS_OFF;
150 	while(kexec_all_irq_disabled == 0)
151 		cpu_relax();
152 	mb(); /* make sure all irqs are disabled before this */
153 	hw_breakpoint_disable();
154 	/*
155 	 * Now every CPU has IRQs off, we can clear out any pending
156 	 * IPIs and be sure that no more will come in after this.
157 	 */
158 	if (ppc_md.kexec_cpu_down)
159 		ppc_md.kexec_cpu_down(0, 1);
160 
161 	reset_sprs();
162 
163 	kexec_smp_wait();
164 	/* NOTREACHED */
165 }
166 
kexec_prepare_cpus_wait(int wait_state)167 static void kexec_prepare_cpus_wait(int wait_state)
168 {
169 	int my_cpu, i, notified=-1;
170 
171 	hw_breakpoint_disable();
172 	my_cpu = get_cpu();
173 	/* Make sure each CPU has at least made it to the state we need.
174 	 *
175 	 * FIXME: There is a (slim) chance of a problem if not all of the CPUs
176 	 * are correctly onlined.  If somehow we start a CPU on boot with RTAS
177 	 * start-cpu, but somehow that CPU doesn't write callin_cpu_map[] in
178 	 * time, the boot CPU will timeout.  If it does eventually execute
179 	 * stuff, the secondary will start up (paca_ptrs[]->cpu_start was
180 	 * written) and get into a peculiar state.
181 	 * If the platform supports smp_ops->take_timebase(), the secondary CPU
182 	 * will probably be spinning in there.  If not (i.e. pseries), the
183 	 * secondary will continue on and try to online itself/idle/etc. If it
184 	 * survives that, we need to find these
185 	 * possible-but-not-online-but-should-be CPUs and chaperone them into
186 	 * kexec_smp_wait().
187 	 */
188 	for_each_online_cpu(i) {
189 		if (i == my_cpu)
190 			continue;
191 
192 		while (paca_ptrs[i]->kexec_state < wait_state) {
193 			barrier();
194 			if (i != notified) {
195 				printk(KERN_INFO "kexec: waiting for cpu %d "
196 				       "(physical %d) to enter %i state\n",
197 				       i, paca_ptrs[i]->hw_cpu_id, wait_state);
198 				notified = i;
199 			}
200 		}
201 	}
202 	mb();
203 }
204 
205 
206 /*
207  * The add_cpu() call in wake_offline_cpus() can fail as cpu_bootable()
208  * returns false for CPUs that fail the cpu_smt_thread_allowed() check
209  * or non primary threads if SMT is disabled. Re-enable SMT and set the
210  * number of SMT threads to threads per core.
211  */
kexec_smt_reenable(void)212 static void kexec_smt_reenable(void)
213 {
214 #if defined(CONFIG_SMP) && defined(CONFIG_HOTPLUG_SMT)
215 	lock_device_hotplug();
216 	cpu_smt_num_threads = threads_per_core;
217 	cpu_smt_control = CPU_SMT_ENABLED;
218 	unlock_device_hotplug();
219 #endif
220 }
221 
222 /*
223  * We need to make sure each present CPU is online.  The next kernel will scan
224  * the device tree and assume primary threads are online and query secondary
225  * threads via RTAS to online them if required.  If we don't online primary
226  * threads, they will be stuck.  However, we also online secondary threads as we
227  * may be using 'cede offline'.  In this case RTAS doesn't see the secondary
228  * threads as offline -- and again, these CPUs will be stuck.
229  *
230  * So, we online all CPUs that should be running, including secondary threads.
231  */
wake_offline_cpus(void)232 static void wake_offline_cpus(void)
233 {
234 	int cpu = 0;
235 
236 	kexec_smt_reenable();
237 
238 	for_each_present_cpu(cpu) {
239 		if (!cpu_online(cpu)) {
240 			printk(KERN_INFO "kexec: Waking offline cpu %d.\n",
241 			       cpu);
242 			WARN_ON(add_cpu(cpu));
243 		}
244 	}
245 }
246 
kexec_prepare_cpus(void)247 static void kexec_prepare_cpus(void)
248 {
249 	wake_offline_cpus();
250 	smp_call_function(kexec_smp_down, NULL, /* wait */0);
251 	local_irq_disable();
252 	hard_irq_disable();
253 
254 	mb(); /* make sure IRQs are disabled before we say they are */
255 	get_paca()->kexec_state = KEXEC_STATE_IRQS_OFF;
256 
257 	kexec_prepare_cpus_wait(KEXEC_STATE_IRQS_OFF);
258 	/* we are sure every CPU has IRQs off at this point */
259 	kexec_all_irq_disabled = 1;
260 
261 	/*
262 	 * Before removing MMU mappings make sure all CPUs have entered real
263 	 * mode:
264 	 */
265 	kexec_prepare_cpus_wait(KEXEC_STATE_REAL_MODE);
266 
267 	/* after we tell the others to go down */
268 	if (ppc_md.kexec_cpu_down)
269 		ppc_md.kexec_cpu_down(0, 0);
270 
271 	put_cpu();
272 }
273 
274 #else /* ! SMP */
275 
kexec_prepare_cpus(void)276 static void kexec_prepare_cpus(void)
277 {
278 	/*
279 	 * move the secondarys to us so that we can copy
280 	 * the new kernel 0-0x100 safely
281 	 *
282 	 * do this if kexec in setup.c ?
283 	 *
284 	 * We need to release the cpus if we are ever going from an
285 	 * UP to an SMP kernel.
286 	 */
287 	smp_release_cpus();
288 	if (ppc_md.kexec_cpu_down)
289 		ppc_md.kexec_cpu_down(0, 0);
290 	local_irq_disable();
291 	hard_irq_disable();
292 }
293 
294 #endif /* SMP */
295 
296 /*
297  * kexec thread structure and stack.
298  *
299  * We need to make sure that this is 16384-byte aligned due to the
300  * way process stacks are handled.  It also must be statically allocated
301  * or allocated as part of the kimage, because everything else may be
302  * overwritten when we copy the kexec image.  We piggyback on the
303  * "init_task" linker section here to statically allocate a stack.
304  *
305  * We could use a smaller stack if we don't care about anything using
306  * current, but that audit has not been performed.
307  */
308 static union thread_union kexec_stack = { };
309 
310 /*
311  * For similar reasons to the stack above, the kexecing CPU needs to be on a
312  * static PACA; we switch to kexec_paca.
313  */
314 static struct paca_struct kexec_paca;
315 
316 /* Our assembly helper, in misc_64.S */
317 extern void kexec_sequence(void *newstack, unsigned long start,
318 			   void *image, void *control,
319 			   void (*clear_all)(void),
320 			   bool copy_with_mmu_off) __noreturn;
321 
322 /* too late to fail here */
default_machine_kexec(struct kimage * image)323 void default_machine_kexec(struct kimage *image)
324 {
325 	bool copy_with_mmu_off;
326 
327 	/* prepare control code if any */
328 
329 	/*
330         * If the kexec boot is the normal one, need to shutdown other cpus
331         * into our wait loop and quiesce interrupts.
332         * Otherwise, in the case of crashed mode (crashing_cpu >= 0),
333         * stopping other CPUs and collecting their pt_regs is done before
334         * using debugger IPI.
335         */
336 
337 	if (!kdump_in_progress())
338 		kexec_prepare_cpus();
339 
340 #ifdef CONFIG_PPC_PSERIES
341 	/*
342 	 * This must be done after other CPUs have shut down, otherwise they
343 	 * could execute the 'scv' instruction, which is not supported with
344 	 * reloc disabled (see configure_exceptions()).
345 	 */
346 	if (firmware_has_feature(FW_FEATURE_SET_MODE))
347 		pseries_disable_reloc_on_exc();
348 #endif
349 
350 	printk("kexec: Starting switchover sequence.\n");
351 
352 	/* switch to a staticly allocated stack.  Based on irq stack code.
353 	 * We setup preempt_count to avoid using VMX in memcpy.
354 	 * XXX: the task struct will likely be invalid once we do the copy!
355 	 */
356 	current_thread_info()->flags = 0;
357 	current_thread_info()->preempt_count = HARDIRQ_OFFSET;
358 
359 	/* We need a static PACA, too; copy this CPU's PACA over and switch to
360 	 * it. Also poison per_cpu_offset and NULL lppaca to catch anyone using
361 	 * non-static data.
362 	 */
363 	memcpy(&kexec_paca, get_paca(), sizeof(struct paca_struct));
364 	kexec_paca.data_offset = 0xedeaddeadeeeeeeeUL;
365 #ifdef CONFIG_PPC_PSERIES
366 	kexec_paca.lppaca_ptr = NULL;
367 #endif
368 
369 	if (is_secure_guest() && !(image->preserve_context ||
370 				   image->type == KEXEC_TYPE_CRASH)) {
371 		uv_unshare_all_pages();
372 		printk("kexec: Unshared all shared pages.\n");
373 	}
374 
375 	paca_ptrs[kexec_paca.paca_index] = &kexec_paca;
376 
377 	setup_paca(&kexec_paca);
378 
379 	/*
380 	 * The lppaca should be unregistered at this point so the HV won't
381 	 * touch it. In the case of a crash, none of the lppacas are
382 	 * unregistered so there is not much we can do about it here.
383 	 */
384 
385 	/*
386 	 * On Book3S, the copy must happen with the MMU off if we are either
387 	 * using Radix page tables or we are not in an LPAR since we can
388 	 * overwrite the page tables while copying.
389 	 *
390 	 * In an LPAR, we keep the MMU on otherwise we can't access beyond
391 	 * the RMA. On BookE there is no real MMU off mode, so we have to
392 	 * keep it enabled as well (but then we have bolted TLB entries).
393 	 */
394 #ifdef CONFIG_PPC_BOOK3E_64
395 	copy_with_mmu_off = false;
396 #else
397 	copy_with_mmu_off = radix_enabled() ||
398 		!(firmware_has_feature(FW_FEATURE_LPAR) ||
399 		  firmware_has_feature(FW_FEATURE_PS3_LV1));
400 #endif
401 
402 	/* Some things are best done in assembly.  Finding globals with
403 	 * a toc is easier in C, so pass in what we can.
404 	 */
405 	kexec_sequence(&kexec_stack, image->start, image,
406 		       page_address(image->control_code_page),
407 		       mmu_cleanup_all, copy_with_mmu_off);
408 	/* NOTREACHED */
409 }
410 
411 #ifdef CONFIG_PPC_64S_HASH_MMU
412 /* Values we need to export to the second kernel via the device tree. */
413 static __be64 htab_base;
414 static __be64 htab_size;
415 
416 static struct property htab_base_prop = {
417 	.name = "linux,htab-base",
418 	.length = sizeof(unsigned long),
419 	.value = &htab_base,
420 };
421 
422 static struct property htab_size_prop = {
423 	.name = "linux,htab-size",
424 	.length = sizeof(unsigned long),
425 	.value = &htab_size,
426 };
427 
export_htab_values(void)428 static int __init export_htab_values(void)
429 {
430 	struct device_node *node;
431 
432 	/* On machines with no htab htab_address is NULL */
433 	if (!htab_address)
434 		return -ENODEV;
435 
436 	node = of_find_node_by_path("/chosen");
437 	if (!node)
438 		return -ENODEV;
439 
440 	/* remove any stale properties so ours can be found */
441 	of_remove_property(node, of_find_property(node, htab_base_prop.name, NULL));
442 	of_remove_property(node, of_find_property(node, htab_size_prop.name, NULL));
443 
444 	htab_base = cpu_to_be64(__pa(htab_address));
445 	of_add_property(node, &htab_base_prop);
446 	htab_size = cpu_to_be64(htab_size_bytes);
447 	of_add_property(node, &htab_size_prop);
448 
449 	of_node_put(node);
450 	return 0;
451 }
452 late_initcall(export_htab_values);
453 #endif /* CONFIG_PPC_64S_HASH_MMU */
454 
455 #if defined(CONFIG_KEXEC_FILE) || defined(CONFIG_CRASH_DUMP)
456 /**
457  * add_node_props - Reads node properties from device node structure and add
458  *                  them to fdt.
459  * @fdt:            Flattened device tree of the kernel
460  * @node_offset:    offset of the node to add a property at
461  * @dn:             device node pointer
462  *
463  * Returns 0 on success, negative errno on error.
464  */
add_node_props(void * fdt,int node_offset,const struct device_node * dn)465 static int add_node_props(void *fdt, int node_offset, const struct device_node *dn)
466 {
467 	int ret = 0;
468 	struct property *pp;
469 
470 	if (!dn)
471 		return -EINVAL;
472 
473 	for_each_property_of_node(dn, pp) {
474 		ret = fdt_setprop(fdt, node_offset, pp->name, pp->value, pp->length);
475 		if (ret < 0) {
476 			pr_err("Unable to add %s property: %s\n", pp->name, fdt_strerror(ret));
477 			return ret;
478 		}
479 	}
480 	return ret;
481 }
482 
483 /**
484  * update_cpus_node - Update cpus node of flattened device tree using of_root
485  *                    device node.
486  * @fdt:              Flattened device tree of the kernel.
487  *
488  * Returns 0 on success, negative errno on error.
489  *
490  * Note: expecting no subnodes under /cpus/<node> with device_type == "cpu".
491  * If this changes, update this function to include them.
492  */
update_cpus_node(void * fdt)493 int update_cpus_node(void *fdt)
494 {
495 	int prev_node_offset;
496 	const char *device_type;
497 	const struct fdt_property *prop;
498 	struct device_node *cpus_node, *dn;
499 	int cpus_offset, cpus_subnode_offset, ret = 0;
500 
501 	cpus_offset = fdt_path_offset(fdt, "/cpus");
502 	if (cpus_offset < 0 && cpus_offset != -FDT_ERR_NOTFOUND) {
503 		pr_err("Malformed device tree: error reading /cpus node: %s\n",
504 		       fdt_strerror(cpus_offset));
505 		return cpus_offset;
506 	}
507 
508 	prev_node_offset = cpus_offset;
509 	/* Delete sub-nodes of /cpus node with device_type == "cpu" */
510 	for (cpus_subnode_offset = fdt_first_subnode(fdt, cpus_offset); cpus_subnode_offset >= 0;) {
511 		/* Ignore nodes that do not have a device_type property or device_type != "cpu" */
512 		prop = fdt_get_property(fdt, cpus_subnode_offset, "device_type", NULL);
513 		if (!prop || strcmp(prop->data, "cpu")) {
514 			prev_node_offset = cpus_subnode_offset;
515 			goto next_node;
516 		}
517 
518 		ret = fdt_del_node(fdt, cpus_subnode_offset);
519 		if (ret < 0) {
520 			pr_err("Failed to delete a cpus sub-node: %s\n", fdt_strerror(ret));
521 			return ret;
522 		}
523 next_node:
524 		if (prev_node_offset == cpus_offset)
525 			cpus_subnode_offset = fdt_first_subnode(fdt, cpus_offset);
526 		else
527 			cpus_subnode_offset = fdt_next_subnode(fdt, prev_node_offset);
528 	}
529 
530 	cpus_node = of_find_node_by_path("/cpus");
531 	/* Fail here to avoid kexec/kdump kernel boot hung */
532 	if (!cpus_node) {
533 		pr_err("No /cpus node found\n");
534 		return -EINVAL;
535 	}
536 
537 	/* Add all /cpus sub-nodes of device_type == "cpu" to FDT */
538 	for_each_child_of_node(cpus_node, dn) {
539 		/* Ignore device nodes that do not have a device_type property
540 		 * or device_type != "cpu".
541 		 */
542 		device_type = of_get_property(dn, "device_type", NULL);
543 		if (!device_type || strcmp(device_type, "cpu"))
544 			continue;
545 
546 		cpus_subnode_offset = fdt_add_subnode(fdt, cpus_offset, dn->full_name);
547 		if (cpus_subnode_offset < 0) {
548 			pr_err("Unable to add %s subnode: %s\n", dn->full_name,
549 			       fdt_strerror(cpus_subnode_offset));
550 			ret = cpus_subnode_offset;
551 			goto out;
552 		}
553 
554 		ret = add_node_props(fdt, cpus_subnode_offset, dn);
555 		if (ret < 0)
556 			goto out;
557 	}
558 out:
559 	of_node_put(cpus_node);
560 	of_node_put(dn);
561 	return ret;
562 }
563 #endif /* CONFIG_KEXEC_FILE || CONFIG_CRASH_DUMP */
564