xref: /linux/arch/powerpc/kexec/core_64.c (revision da5b2ad1c2f18834cb1ce429e2e5a5cf5cbdf21b)
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 
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 */
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 */
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 
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 
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  * We need to make sure each present CPU is online.  The next kernel will scan
207  * the device tree and assume primary threads are online and query secondary
208  * threads via RTAS to online them if required.  If we don't online primary
209  * threads, they will be stuck.  However, we also online secondary threads as we
210  * may be using 'cede offline'.  In this case RTAS doesn't see the secondary
211  * threads as offline -- and again, these CPUs will be stuck.
212  *
213  * So, we online all CPUs that should be running, including secondary threads.
214  */
215 static void wake_offline_cpus(void)
216 {
217 	int cpu = 0;
218 
219 	for_each_present_cpu(cpu) {
220 		if (!cpu_online(cpu)) {
221 			printk(KERN_INFO "kexec: Waking offline cpu %d.\n",
222 			       cpu);
223 			WARN_ON(add_cpu(cpu));
224 		}
225 	}
226 }
227 
228 static void kexec_prepare_cpus(void)
229 {
230 	wake_offline_cpus();
231 	smp_call_function(kexec_smp_down, NULL, /* wait */0);
232 	local_irq_disable();
233 	hard_irq_disable();
234 
235 	mb(); /* make sure IRQs are disabled before we say they are */
236 	get_paca()->kexec_state = KEXEC_STATE_IRQS_OFF;
237 
238 	kexec_prepare_cpus_wait(KEXEC_STATE_IRQS_OFF);
239 	/* we are sure every CPU has IRQs off at this point */
240 	kexec_all_irq_disabled = 1;
241 
242 	/*
243 	 * Before removing MMU mappings make sure all CPUs have entered real
244 	 * mode:
245 	 */
246 	kexec_prepare_cpus_wait(KEXEC_STATE_REAL_MODE);
247 
248 	/* after we tell the others to go down */
249 	if (ppc_md.kexec_cpu_down)
250 		ppc_md.kexec_cpu_down(0, 0);
251 
252 	put_cpu();
253 }
254 
255 #else /* ! SMP */
256 
257 static void kexec_prepare_cpus(void)
258 {
259 	/*
260 	 * move the secondarys to us so that we can copy
261 	 * the new kernel 0-0x100 safely
262 	 *
263 	 * do this if kexec in setup.c ?
264 	 *
265 	 * We need to release the cpus if we are ever going from an
266 	 * UP to an SMP kernel.
267 	 */
268 	smp_release_cpus();
269 	if (ppc_md.kexec_cpu_down)
270 		ppc_md.kexec_cpu_down(0, 0);
271 	local_irq_disable();
272 	hard_irq_disable();
273 }
274 
275 #endif /* SMP */
276 
277 /*
278  * kexec thread structure and stack.
279  *
280  * We need to make sure that this is 16384-byte aligned due to the
281  * way process stacks are handled.  It also must be statically allocated
282  * or allocated as part of the kimage, because everything else may be
283  * overwritten when we copy the kexec image.  We piggyback on the
284  * "init_task" linker section here to statically allocate a stack.
285  *
286  * We could use a smaller stack if we don't care about anything using
287  * current, but that audit has not been performed.
288  */
289 static union thread_union kexec_stack = { };
290 
291 /*
292  * For similar reasons to the stack above, the kexecing CPU needs to be on a
293  * static PACA; we switch to kexec_paca.
294  */
295 static struct paca_struct kexec_paca;
296 
297 /* Our assembly helper, in misc_64.S */
298 extern void kexec_sequence(void *newstack, unsigned long start,
299 			   void *image, void *control,
300 			   void (*clear_all)(void),
301 			   bool copy_with_mmu_off) __noreturn;
302 
303 /* too late to fail here */
304 void default_machine_kexec(struct kimage *image)
305 {
306 	bool copy_with_mmu_off;
307 
308 	/* prepare control code if any */
309 
310 	/*
311         * If the kexec boot is the normal one, need to shutdown other cpus
312         * into our wait loop and quiesce interrupts.
313         * Otherwise, in the case of crashed mode (crashing_cpu >= 0),
314         * stopping other CPUs and collecting their pt_regs is done before
315         * using debugger IPI.
316         */
317 
318 	if (!kdump_in_progress())
319 		kexec_prepare_cpus();
320 
321 #ifdef CONFIG_PPC_PSERIES
322 	/*
323 	 * This must be done after other CPUs have shut down, otherwise they
324 	 * could execute the 'scv' instruction, which is not supported with
325 	 * reloc disabled (see configure_exceptions()).
326 	 */
327 	if (firmware_has_feature(FW_FEATURE_SET_MODE))
328 		pseries_disable_reloc_on_exc();
329 #endif
330 
331 	printk("kexec: Starting switchover sequence.\n");
332 
333 	/* switch to a staticly allocated stack.  Based on irq stack code.
334 	 * We setup preempt_count to avoid using VMX in memcpy.
335 	 * XXX: the task struct will likely be invalid once we do the copy!
336 	 */
337 	current_thread_info()->flags = 0;
338 	current_thread_info()->preempt_count = HARDIRQ_OFFSET;
339 
340 	/* We need a static PACA, too; copy this CPU's PACA over and switch to
341 	 * it. Also poison per_cpu_offset and NULL lppaca to catch anyone using
342 	 * non-static data.
343 	 */
344 	memcpy(&kexec_paca, get_paca(), sizeof(struct paca_struct));
345 	kexec_paca.data_offset = 0xedeaddeadeeeeeeeUL;
346 #ifdef CONFIG_PPC_PSERIES
347 	kexec_paca.lppaca_ptr = NULL;
348 #endif
349 
350 	if (is_secure_guest() && !(image->preserve_context ||
351 				   image->type == KEXEC_TYPE_CRASH)) {
352 		uv_unshare_all_pages();
353 		printk("kexec: Unshared all shared pages.\n");
354 	}
355 
356 	paca_ptrs[kexec_paca.paca_index] = &kexec_paca;
357 
358 	setup_paca(&kexec_paca);
359 
360 	/*
361 	 * The lppaca should be unregistered at this point so the HV won't
362 	 * touch it. In the case of a crash, none of the lppacas are
363 	 * unregistered so there is not much we can do about it here.
364 	 */
365 
366 	/*
367 	 * On Book3S, the copy must happen with the MMU off if we are either
368 	 * using Radix page tables or we are not in an LPAR since we can
369 	 * overwrite the page tables while copying.
370 	 *
371 	 * In an LPAR, we keep the MMU on otherwise we can't access beyond
372 	 * the RMA. On BookE there is no real MMU off mode, so we have to
373 	 * keep it enabled as well (but then we have bolted TLB entries).
374 	 */
375 #ifdef CONFIG_PPC_BOOK3E_64
376 	copy_with_mmu_off = false;
377 #else
378 	copy_with_mmu_off = radix_enabled() ||
379 		!(firmware_has_feature(FW_FEATURE_LPAR) ||
380 		  firmware_has_feature(FW_FEATURE_PS3_LV1));
381 #endif
382 
383 	/* Some things are best done in assembly.  Finding globals with
384 	 * a toc is easier in C, so pass in what we can.
385 	 */
386 	kexec_sequence(&kexec_stack, image->start, image,
387 		       page_address(image->control_code_page),
388 		       mmu_cleanup_all, copy_with_mmu_off);
389 	/* NOTREACHED */
390 }
391 
392 #ifdef CONFIG_PPC_64S_HASH_MMU
393 /* Values we need to export to the second kernel via the device tree. */
394 static __be64 htab_base;
395 static __be64 htab_size;
396 
397 static struct property htab_base_prop = {
398 	.name = "linux,htab-base",
399 	.length = sizeof(unsigned long),
400 	.value = &htab_base,
401 };
402 
403 static struct property htab_size_prop = {
404 	.name = "linux,htab-size",
405 	.length = sizeof(unsigned long),
406 	.value = &htab_size,
407 };
408 
409 static int __init export_htab_values(void)
410 {
411 	struct device_node *node;
412 
413 	/* On machines with no htab htab_address is NULL */
414 	if (!htab_address)
415 		return -ENODEV;
416 
417 	node = of_find_node_by_path("/chosen");
418 	if (!node)
419 		return -ENODEV;
420 
421 	/* remove any stale properties so ours can be found */
422 	of_remove_property(node, of_find_property(node, htab_base_prop.name, NULL));
423 	of_remove_property(node, of_find_property(node, htab_size_prop.name, NULL));
424 
425 	htab_base = cpu_to_be64(__pa(htab_address));
426 	of_add_property(node, &htab_base_prop);
427 	htab_size = cpu_to_be64(htab_size_bytes);
428 	of_add_property(node, &htab_size_prop);
429 
430 	of_node_put(node);
431 	return 0;
432 }
433 late_initcall(export_htab_values);
434 #endif /* CONFIG_PPC_64S_HASH_MMU */
435 
436 #if defined(CONFIG_KEXEC_FILE) || defined(CONFIG_CRASH_DUMP)
437 /**
438  * add_node_props - Reads node properties from device node structure and add
439  *                  them to fdt.
440  * @fdt:            Flattened device tree of the kernel
441  * @node_offset:    offset of the node to add a property at
442  * @dn:             device node pointer
443  *
444  * Returns 0 on success, negative errno on error.
445  */
446 static int add_node_props(void *fdt, int node_offset, const struct device_node *dn)
447 {
448 	int ret = 0;
449 	struct property *pp;
450 
451 	if (!dn)
452 		return -EINVAL;
453 
454 	for_each_property_of_node(dn, pp) {
455 		ret = fdt_setprop(fdt, node_offset, pp->name, pp->value, pp->length);
456 		if (ret < 0) {
457 			pr_err("Unable to add %s property: %s\n", pp->name, fdt_strerror(ret));
458 			return ret;
459 		}
460 	}
461 	return ret;
462 }
463 
464 /**
465  * update_cpus_node - Update cpus node of flattened device tree using of_root
466  *                    device node.
467  * @fdt:              Flattened device tree of the kernel.
468  *
469  * Returns 0 on success, negative errno on error.
470  *
471  * Note: expecting no subnodes under /cpus/<node> with device_type == "cpu".
472  * If this changes, update this function to include them.
473  */
474 int update_cpus_node(void *fdt)
475 {
476 	int prev_node_offset;
477 	const char *device_type;
478 	const struct fdt_property *prop;
479 	struct device_node *cpus_node, *dn;
480 	int cpus_offset, cpus_subnode_offset, ret = 0;
481 
482 	cpus_offset = fdt_path_offset(fdt, "/cpus");
483 	if (cpus_offset < 0 && cpus_offset != -FDT_ERR_NOTFOUND) {
484 		pr_err("Malformed device tree: error reading /cpus node: %s\n",
485 		       fdt_strerror(cpus_offset));
486 		return cpus_offset;
487 	}
488 
489 	prev_node_offset = cpus_offset;
490 	/* Delete sub-nodes of /cpus node with device_type == "cpu" */
491 	for (cpus_subnode_offset = fdt_first_subnode(fdt, cpus_offset); cpus_subnode_offset >= 0;) {
492 		/* Ignore nodes that do not have a device_type property or device_type != "cpu" */
493 		prop = fdt_get_property(fdt, cpus_subnode_offset, "device_type", NULL);
494 		if (!prop || strcmp(prop->data, "cpu")) {
495 			prev_node_offset = cpus_subnode_offset;
496 			goto next_node;
497 		}
498 
499 		ret = fdt_del_node(fdt, cpus_subnode_offset);
500 		if (ret < 0) {
501 			pr_err("Failed to delete a cpus sub-node: %s\n", fdt_strerror(ret));
502 			return ret;
503 		}
504 next_node:
505 		if (prev_node_offset == cpus_offset)
506 			cpus_subnode_offset = fdt_first_subnode(fdt, cpus_offset);
507 		else
508 			cpus_subnode_offset = fdt_next_subnode(fdt, prev_node_offset);
509 	}
510 
511 	cpus_node = of_find_node_by_path("/cpus");
512 	/* Fail here to avoid kexec/kdump kernel boot hung */
513 	if (!cpus_node) {
514 		pr_err("No /cpus node found\n");
515 		return -EINVAL;
516 	}
517 
518 	/* Add all /cpus sub-nodes of device_type == "cpu" to FDT */
519 	for_each_child_of_node(cpus_node, dn) {
520 		/* Ignore device nodes that do not have a device_type property
521 		 * or device_type != "cpu".
522 		 */
523 		device_type = of_get_property(dn, "device_type", NULL);
524 		if (!device_type || strcmp(device_type, "cpu"))
525 			continue;
526 
527 		cpus_subnode_offset = fdt_add_subnode(fdt, cpus_offset, dn->full_name);
528 		if (cpus_subnode_offset < 0) {
529 			pr_err("Unable to add %s subnode: %s\n", dn->full_name,
530 			       fdt_strerror(cpus_subnode_offset));
531 			ret = cpus_subnode_offset;
532 			goto out;
533 		}
534 
535 		ret = add_node_props(fdt, cpus_subnode_offset, dn);
536 		if (ret < 0)
537 			goto out;
538 	}
539 out:
540 	of_node_put(cpus_node);
541 	of_node_put(dn);
542 	return ret;
543 }
544 #endif /* CONFIG_KEXEC_FILE || CONFIG_CRASH_DUMP */
545