xref: /openbmc/linux/kernel/panic.c (revision 0c874100)
1 /*
2  *  linux/kernel/panic.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6 
7 /*
8  * This function is used through-out the kernel (including mm and fs)
9  * to indicate a major problem.
10  */
11 #include <linux/debug_locks.h>
12 #include <linux/sched/debug.h>
13 #include <linux/interrupt.h>
14 #include <linux/kmsg_dump.h>
15 #include <linux/kallsyms.h>
16 #include <linux/notifier.h>
17 #include <linux/module.h>
18 #include <linux/random.h>
19 #include <linux/ftrace.h>
20 #include <linux/reboot.h>
21 #include <linux/delay.h>
22 #include <linux/kexec.h>
23 #include <linux/sched.h>
24 #include <linux/sysrq.h>
25 #include <linux/init.h>
26 #include <linux/nmi.h>
27 #include <linux/console.h>
28 #include <linux/bug.h>
29 #include <linux/ratelimit.h>
30 #include <linux/debugfs.h>
31 #include <asm/sections.h>
32 
33 #define PANIC_TIMER_STEP 100
34 #define PANIC_BLINK_SPD 18
35 
36 int panic_on_oops = CONFIG_PANIC_ON_OOPS_VALUE;
37 static unsigned long tainted_mask =
38 	IS_ENABLED(CONFIG_GCC_PLUGIN_RANDSTRUCT) ? (1 << TAINT_RANDSTRUCT) : 0;
39 static int pause_on_oops;
40 static int pause_on_oops_flag;
41 static DEFINE_SPINLOCK(pause_on_oops_lock);
42 bool crash_kexec_post_notifiers;
43 int panic_on_warn __read_mostly;
44 
45 int panic_timeout = CONFIG_PANIC_TIMEOUT;
46 EXPORT_SYMBOL_GPL(panic_timeout);
47 
48 ATOMIC_NOTIFIER_HEAD(panic_notifier_list);
49 
50 EXPORT_SYMBOL(panic_notifier_list);
51 
52 static long no_blink(int state)
53 {
54 	return 0;
55 }
56 
57 /* Returns how long it waited in ms */
58 long (*panic_blink)(int state);
59 EXPORT_SYMBOL(panic_blink);
60 
61 /*
62  * Stop ourself in panic -- architecture code may override this
63  */
64 void __weak panic_smp_self_stop(void)
65 {
66 	while (1)
67 		cpu_relax();
68 }
69 
70 /*
71  * Stop ourselves in NMI context if another CPU has already panicked. Arch code
72  * may override this to prepare for crash dumping, e.g. save regs info.
73  */
74 void __weak nmi_panic_self_stop(struct pt_regs *regs)
75 {
76 	panic_smp_self_stop();
77 }
78 
79 /*
80  * Stop other CPUs in panic.  Architecture dependent code may override this
81  * with more suitable version.  For example, if the architecture supports
82  * crash dump, it should save registers of each stopped CPU and disable
83  * per-CPU features such as virtualization extensions.
84  */
85 void __weak crash_smp_send_stop(void)
86 {
87 	static int cpus_stopped;
88 
89 	/*
90 	 * This function can be called twice in panic path, but obviously
91 	 * we execute this only once.
92 	 */
93 	if (cpus_stopped)
94 		return;
95 
96 	/*
97 	 * Note smp_send_stop is the usual smp shutdown function, which
98 	 * unfortunately means it may not be hardened to work in a panic
99 	 * situation.
100 	 */
101 	smp_send_stop();
102 	cpus_stopped = 1;
103 }
104 
105 atomic_t panic_cpu = ATOMIC_INIT(PANIC_CPU_INVALID);
106 
107 /*
108  * A variant of panic() called from NMI context. We return if we've already
109  * panicked on this CPU. If another CPU already panicked, loop in
110  * nmi_panic_self_stop() which can provide architecture dependent code such
111  * as saving register state for crash dump.
112  */
113 void nmi_panic(struct pt_regs *regs, const char *msg)
114 {
115 	int old_cpu, cpu;
116 
117 	cpu = raw_smp_processor_id();
118 	old_cpu = atomic_cmpxchg(&panic_cpu, PANIC_CPU_INVALID, cpu);
119 
120 	if (old_cpu == PANIC_CPU_INVALID)
121 		panic("%s", msg);
122 	else if (old_cpu != cpu)
123 		nmi_panic_self_stop(regs);
124 }
125 EXPORT_SYMBOL(nmi_panic);
126 
127 /**
128  *	panic - halt the system
129  *	@fmt: The text string to print
130  *
131  *	Display a message, then perform cleanups.
132  *
133  *	This function never returns.
134  */
135 void panic(const char *fmt, ...)
136 {
137 	static char buf[1024];
138 	va_list args;
139 	long i, i_next = 0, len;
140 	int state = 0;
141 	int old_cpu, this_cpu;
142 	bool _crash_kexec_post_notifiers = crash_kexec_post_notifiers;
143 
144 	/*
145 	 * Disable local interrupts. This will prevent panic_smp_self_stop
146 	 * from deadlocking the first cpu that invokes the panic, since
147 	 * there is nothing to prevent an interrupt handler (that runs
148 	 * after setting panic_cpu) from invoking panic() again.
149 	 */
150 	local_irq_disable();
151 
152 	/*
153 	 * It's possible to come here directly from a panic-assertion and
154 	 * not have preempt disabled. Some functions called from here want
155 	 * preempt to be disabled. No point enabling it later though...
156 	 *
157 	 * Only one CPU is allowed to execute the panic code from here. For
158 	 * multiple parallel invocations of panic, all other CPUs either
159 	 * stop themself or will wait until they are stopped by the 1st CPU
160 	 * with smp_send_stop().
161 	 *
162 	 * `old_cpu == PANIC_CPU_INVALID' means this is the 1st CPU which
163 	 * comes here, so go ahead.
164 	 * `old_cpu == this_cpu' means we came from nmi_panic() which sets
165 	 * panic_cpu to this CPU.  In this case, this is also the 1st CPU.
166 	 */
167 	this_cpu = raw_smp_processor_id();
168 	old_cpu  = atomic_cmpxchg(&panic_cpu, PANIC_CPU_INVALID, this_cpu);
169 
170 	if (old_cpu != PANIC_CPU_INVALID && old_cpu != this_cpu)
171 		panic_smp_self_stop();
172 
173 	console_verbose();
174 	bust_spinlocks(1);
175 	va_start(args, fmt);
176 	len = vscnprintf(buf, sizeof(buf), fmt, args);
177 	va_end(args);
178 
179 	if (len && buf[len - 1] == '\n')
180 		buf[len - 1] = '\0';
181 
182 	pr_emerg("Kernel panic - not syncing: %s\n", buf);
183 #ifdef CONFIG_DEBUG_BUGVERBOSE
184 	/*
185 	 * Avoid nested stack-dumping if a panic occurs during oops processing
186 	 */
187 	if (!test_taint(TAINT_DIE) && oops_in_progress <= 1)
188 		dump_stack();
189 #endif
190 
191 	/*
192 	 * If we have crashed and we have a crash kernel loaded let it handle
193 	 * everything else.
194 	 * If we want to run this after calling panic_notifiers, pass
195 	 * the "crash_kexec_post_notifiers" option to the kernel.
196 	 *
197 	 * Bypass the panic_cpu check and call __crash_kexec directly.
198 	 */
199 	if (!_crash_kexec_post_notifiers) {
200 		printk_safe_flush_on_panic();
201 		__crash_kexec(NULL);
202 
203 		/*
204 		 * Note smp_send_stop is the usual smp shutdown function, which
205 		 * unfortunately means it may not be hardened to work in a
206 		 * panic situation.
207 		 */
208 		smp_send_stop();
209 	} else {
210 		/*
211 		 * If we want to do crash dump after notifier calls and
212 		 * kmsg_dump, we will need architecture dependent extra
213 		 * works in addition to stopping other CPUs.
214 		 */
215 		crash_smp_send_stop();
216 	}
217 
218 	/*
219 	 * Run any panic handlers, including those that might need to
220 	 * add information to the kmsg dump output.
221 	 */
222 	atomic_notifier_call_chain(&panic_notifier_list, 0, buf);
223 
224 	/* Call flush even twice. It tries harder with a single online CPU */
225 	printk_safe_flush_on_panic();
226 	kmsg_dump(KMSG_DUMP_PANIC);
227 
228 	/*
229 	 * If you doubt kdump always works fine in any situation,
230 	 * "crash_kexec_post_notifiers" offers you a chance to run
231 	 * panic_notifiers and dumping kmsg before kdump.
232 	 * Note: since some panic_notifiers can make crashed kernel
233 	 * more unstable, it can increase risks of the kdump failure too.
234 	 *
235 	 * Bypass the panic_cpu check and call __crash_kexec directly.
236 	 */
237 	if (_crash_kexec_post_notifiers)
238 		__crash_kexec(NULL);
239 
240 	bust_spinlocks(0);
241 
242 	/*
243 	 * We may have ended up stopping the CPU holding the lock (in
244 	 * smp_send_stop()) while still having some valuable data in the console
245 	 * buffer.  Try to acquire the lock then release it regardless of the
246 	 * result.  The release will also print the buffers out.  Locks debug
247 	 * should be disabled to avoid reporting bad unlock balance when
248 	 * panic() is not being callled from OOPS.
249 	 */
250 	debug_locks_off();
251 	console_flush_on_panic();
252 
253 	if (!panic_blink)
254 		panic_blink = no_blink;
255 
256 	if (panic_timeout > 0) {
257 		/*
258 		 * Delay timeout seconds before rebooting the machine.
259 		 * We can't use the "normal" timers since we just panicked.
260 		 */
261 		pr_emerg("Rebooting in %d seconds..\n", panic_timeout);
262 
263 		for (i = 0; i < panic_timeout * 1000; i += PANIC_TIMER_STEP) {
264 			touch_nmi_watchdog();
265 			if (i >= i_next) {
266 				i += panic_blink(state ^= 1);
267 				i_next = i + 3600 / PANIC_BLINK_SPD;
268 			}
269 			mdelay(PANIC_TIMER_STEP);
270 		}
271 	}
272 	if (panic_timeout != 0) {
273 		/*
274 		 * This will not be a clean reboot, with everything
275 		 * shutting down.  But if there is a chance of
276 		 * rebooting the system it will be rebooted.
277 		 */
278 		emergency_restart();
279 	}
280 #ifdef __sparc__
281 	{
282 		extern int stop_a_enabled;
283 		/* Make sure the user can actually press Stop-A (L1-A) */
284 		stop_a_enabled = 1;
285 		pr_emerg("Press Stop-A (L1-A) from sun keyboard or send break\n"
286 			 "twice on console to return to the boot prom\n");
287 	}
288 #endif
289 #if defined(CONFIG_S390)
290 	{
291 		unsigned long caller;
292 
293 		caller = (unsigned long)__builtin_return_address(0);
294 		disabled_wait(caller);
295 	}
296 #endif
297 	pr_emerg("---[ end Kernel panic - not syncing: %s ]---\n", buf);
298 	local_irq_enable();
299 	for (i = 0; ; i += PANIC_TIMER_STEP) {
300 		touch_softlockup_watchdog();
301 		if (i >= i_next) {
302 			i += panic_blink(state ^= 1);
303 			i_next = i + 3600 / PANIC_BLINK_SPD;
304 		}
305 		mdelay(PANIC_TIMER_STEP);
306 	}
307 }
308 
309 EXPORT_SYMBOL(panic);
310 
311 /*
312  * TAINT_FORCED_RMMOD could be a per-module flag but the module
313  * is being removed anyway.
314  */
315 const struct taint_flag taint_flags[TAINT_FLAGS_COUNT] = {
316 	[ TAINT_PROPRIETARY_MODULE ]	= { 'P', 'G', true },
317 	[ TAINT_FORCED_MODULE ]		= { 'F', ' ', true },
318 	[ TAINT_CPU_OUT_OF_SPEC ]	= { 'S', ' ', false },
319 	[ TAINT_FORCED_RMMOD ]		= { 'R', ' ', false },
320 	[ TAINT_MACHINE_CHECK ]		= { 'M', ' ', false },
321 	[ TAINT_BAD_PAGE ]		= { 'B', ' ', false },
322 	[ TAINT_USER ]			= { 'U', ' ', false },
323 	[ TAINT_DIE ]			= { 'D', ' ', false },
324 	[ TAINT_OVERRIDDEN_ACPI_TABLE ]	= { 'A', ' ', false },
325 	[ TAINT_WARN ]			= { 'W', ' ', false },
326 	[ TAINT_CRAP ]			= { 'C', ' ', true },
327 	[ TAINT_FIRMWARE_WORKAROUND ]	= { 'I', ' ', false },
328 	[ TAINT_OOT_MODULE ]		= { 'O', ' ', true },
329 	[ TAINT_UNSIGNED_MODULE ]	= { 'E', ' ', true },
330 	[ TAINT_SOFTLOCKUP ]		= { 'L', ' ', false },
331 	[ TAINT_LIVEPATCH ]		= { 'K', ' ', true },
332 	[ TAINT_AUX ]			= { 'X', ' ', true },
333 	[ TAINT_RANDSTRUCT ]		= { 'T', ' ', true },
334 };
335 
336 /**
337  * print_tainted - return a string to represent the kernel taint state.
338  *
339  * For individual taint flag meanings, see Documentation/sysctl/kernel.txt
340  *
341  * The string is overwritten by the next call to print_tainted(),
342  * but is always NULL terminated.
343  */
344 const char *print_tainted(void)
345 {
346 	static char buf[TAINT_FLAGS_COUNT + sizeof("Tainted: ")];
347 
348 	BUILD_BUG_ON(ARRAY_SIZE(taint_flags) != TAINT_FLAGS_COUNT);
349 
350 	if (tainted_mask) {
351 		char *s;
352 		int i;
353 
354 		s = buf + sprintf(buf, "Tainted: ");
355 		for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
356 			const struct taint_flag *t = &taint_flags[i];
357 			*s++ = test_bit(i, &tainted_mask) ?
358 					t->c_true : t->c_false;
359 		}
360 		*s = 0;
361 	} else
362 		snprintf(buf, sizeof(buf), "Not tainted");
363 
364 	return buf;
365 }
366 
367 int test_taint(unsigned flag)
368 {
369 	return test_bit(flag, &tainted_mask);
370 }
371 EXPORT_SYMBOL(test_taint);
372 
373 unsigned long get_taint(void)
374 {
375 	return tainted_mask;
376 }
377 
378 /**
379  * add_taint: add a taint flag if not already set.
380  * @flag: one of the TAINT_* constants.
381  * @lockdep_ok: whether lock debugging is still OK.
382  *
383  * If something bad has gone wrong, you'll want @lockdebug_ok = false, but for
384  * some notewortht-but-not-corrupting cases, it can be set to true.
385  */
386 void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)
387 {
388 	if (lockdep_ok == LOCKDEP_NOW_UNRELIABLE && __debug_locks_off())
389 		pr_warn("Disabling lock debugging due to kernel taint\n");
390 
391 	set_bit(flag, &tainted_mask);
392 }
393 EXPORT_SYMBOL(add_taint);
394 
395 static void spin_msec(int msecs)
396 {
397 	int i;
398 
399 	for (i = 0; i < msecs; i++) {
400 		touch_nmi_watchdog();
401 		mdelay(1);
402 	}
403 }
404 
405 /*
406  * It just happens that oops_enter() and oops_exit() are identically
407  * implemented...
408  */
409 static void do_oops_enter_exit(void)
410 {
411 	unsigned long flags;
412 	static int spin_counter;
413 
414 	if (!pause_on_oops)
415 		return;
416 
417 	spin_lock_irqsave(&pause_on_oops_lock, flags);
418 	if (pause_on_oops_flag == 0) {
419 		/* This CPU may now print the oops message */
420 		pause_on_oops_flag = 1;
421 	} else {
422 		/* We need to stall this CPU */
423 		if (!spin_counter) {
424 			/* This CPU gets to do the counting */
425 			spin_counter = pause_on_oops;
426 			do {
427 				spin_unlock(&pause_on_oops_lock);
428 				spin_msec(MSEC_PER_SEC);
429 				spin_lock(&pause_on_oops_lock);
430 			} while (--spin_counter);
431 			pause_on_oops_flag = 0;
432 		} else {
433 			/* This CPU waits for a different one */
434 			while (spin_counter) {
435 				spin_unlock(&pause_on_oops_lock);
436 				spin_msec(1);
437 				spin_lock(&pause_on_oops_lock);
438 			}
439 		}
440 	}
441 	spin_unlock_irqrestore(&pause_on_oops_lock, flags);
442 }
443 
444 /*
445  * Return true if the calling CPU is allowed to print oops-related info.
446  * This is a bit racy..
447  */
448 int oops_may_print(void)
449 {
450 	return pause_on_oops_flag == 0;
451 }
452 
453 /*
454  * Called when the architecture enters its oops handler, before it prints
455  * anything.  If this is the first CPU to oops, and it's oopsing the first
456  * time then let it proceed.
457  *
458  * This is all enabled by the pause_on_oops kernel boot option.  We do all
459  * this to ensure that oopses don't scroll off the screen.  It has the
460  * side-effect of preventing later-oopsing CPUs from mucking up the display,
461  * too.
462  *
463  * It turns out that the CPU which is allowed to print ends up pausing for
464  * the right duration, whereas all the other CPUs pause for twice as long:
465  * once in oops_enter(), once in oops_exit().
466  */
467 void oops_enter(void)
468 {
469 	tracing_off();
470 	/* can't trust the integrity of the kernel anymore: */
471 	debug_locks_off();
472 	do_oops_enter_exit();
473 }
474 
475 /*
476  * 64-bit random ID for oopses:
477  */
478 static u64 oops_id;
479 
480 static int init_oops_id(void)
481 {
482 	if (!oops_id)
483 		get_random_bytes(&oops_id, sizeof(oops_id));
484 	else
485 		oops_id++;
486 
487 	return 0;
488 }
489 late_initcall(init_oops_id);
490 
491 void print_oops_end_marker(void)
492 {
493 	init_oops_id();
494 	pr_warn("---[ end trace %016llx ]---\n", (unsigned long long)oops_id);
495 }
496 
497 /*
498  * Called when the architecture exits its oops handler, after printing
499  * everything.
500  */
501 void oops_exit(void)
502 {
503 	do_oops_enter_exit();
504 	print_oops_end_marker();
505 	kmsg_dump(KMSG_DUMP_OOPS);
506 }
507 
508 struct warn_args {
509 	const char *fmt;
510 	va_list args;
511 };
512 
513 void __warn(const char *file, int line, void *caller, unsigned taint,
514 	    struct pt_regs *regs, struct warn_args *args)
515 {
516 	disable_trace_on_warning();
517 
518 	if (args)
519 		pr_warn(CUT_HERE);
520 
521 	if (file)
522 		pr_warn("WARNING: CPU: %d PID: %d at %s:%d %pS\n",
523 			raw_smp_processor_id(), current->pid, file, line,
524 			caller);
525 	else
526 		pr_warn("WARNING: CPU: %d PID: %d at %pS\n",
527 			raw_smp_processor_id(), current->pid, caller);
528 
529 	if (args)
530 		vprintk(args->fmt, args->args);
531 
532 	if (panic_on_warn) {
533 		/*
534 		 * This thread may hit another WARN() in the panic path.
535 		 * Resetting this prevents additional WARN() from panicking the
536 		 * system on this thread.  Other threads are blocked by the
537 		 * panic_mutex in panic().
538 		 */
539 		panic_on_warn = 0;
540 		panic("panic_on_warn set ...\n");
541 	}
542 
543 	print_modules();
544 
545 	if (regs)
546 		show_regs(regs);
547 	else
548 		dump_stack();
549 
550 	print_irqtrace_events(current);
551 
552 	print_oops_end_marker();
553 
554 	/* Just a warning, don't kill lockdep. */
555 	add_taint(taint, LOCKDEP_STILL_OK);
556 }
557 
558 #ifdef WANT_WARN_ON_SLOWPATH
559 void warn_slowpath_fmt(const char *file, int line, const char *fmt, ...)
560 {
561 	struct warn_args args;
562 
563 	args.fmt = fmt;
564 	va_start(args.args, fmt);
565 	__warn(file, line, __builtin_return_address(0), TAINT_WARN, NULL,
566 	       &args);
567 	va_end(args.args);
568 }
569 EXPORT_SYMBOL(warn_slowpath_fmt);
570 
571 void warn_slowpath_fmt_taint(const char *file, int line,
572 			     unsigned taint, const char *fmt, ...)
573 {
574 	struct warn_args args;
575 
576 	args.fmt = fmt;
577 	va_start(args.args, fmt);
578 	__warn(file, line, __builtin_return_address(0), taint, NULL, &args);
579 	va_end(args.args);
580 }
581 EXPORT_SYMBOL(warn_slowpath_fmt_taint);
582 
583 void warn_slowpath_null(const char *file, int line)
584 {
585 	pr_warn(CUT_HERE);
586 	__warn(file, line, __builtin_return_address(0), TAINT_WARN, NULL, NULL);
587 }
588 EXPORT_SYMBOL(warn_slowpath_null);
589 #else
590 void __warn_printk(const char *fmt, ...)
591 {
592 	va_list args;
593 
594 	pr_warn(CUT_HERE);
595 
596 	va_start(args, fmt);
597 	vprintk(fmt, args);
598 	va_end(args);
599 }
600 EXPORT_SYMBOL(__warn_printk);
601 #endif
602 
603 #ifdef CONFIG_BUG
604 
605 /* Support resetting WARN*_ONCE state */
606 
607 static int clear_warn_once_set(void *data, u64 val)
608 {
609 	generic_bug_clear_once();
610 	memset(__start_once, 0, __end_once - __start_once);
611 	return 0;
612 }
613 
614 DEFINE_SIMPLE_ATTRIBUTE(clear_warn_once_fops,
615 			NULL,
616 			clear_warn_once_set,
617 			"%lld\n");
618 
619 static __init int register_warn_debugfs(void)
620 {
621 	/* Don't care about failure */
622 	debugfs_create_file("clear_warn_once", 0200, NULL,
623 			    NULL, &clear_warn_once_fops);
624 	return 0;
625 }
626 
627 device_initcall(register_warn_debugfs);
628 #endif
629 
630 #ifdef CONFIG_STACKPROTECTOR
631 
632 /*
633  * Called when gcc's -fstack-protector feature is used, and
634  * gcc detects corruption of the on-stack canary value
635  */
636 __visible void __stack_chk_fail(void)
637 {
638 	panic("stack-protector: Kernel stack is corrupted in: %pB",
639 		__builtin_return_address(0));
640 }
641 EXPORT_SYMBOL(__stack_chk_fail);
642 
643 #endif
644 
645 #ifdef CONFIG_ARCH_HAS_REFCOUNT
646 void refcount_error_report(struct pt_regs *regs, const char *err)
647 {
648 	WARN_RATELIMIT(1, "refcount_t %s at %pB in %s[%d], uid/euid: %u/%u\n",
649 		err, (void *)instruction_pointer(regs),
650 		current->comm, task_pid_nr(current),
651 		from_kuid_munged(&init_user_ns, current_uid()),
652 		from_kuid_munged(&init_user_ns, current_euid()));
653 }
654 #endif
655 
656 core_param(panic, panic_timeout, int, 0644);
657 core_param(pause_on_oops, pause_on_oops, int, 0644);
658 core_param(panic_on_warn, panic_on_warn, int, 0644);
659 core_param(crash_kexec_post_notifiers, crash_kexec_post_notifiers, bool, 0644);
660 
661 static int __init oops_setup(char *s)
662 {
663 	if (!s)
664 		return -EINVAL;
665 	if (!strcmp(s, "panic"))
666 		panic_on_oops = 1;
667 	return 0;
668 }
669 early_param("oops", oops_setup);
670