xref: /linux/kernel/panic.c (revision 813b46808822db6838c43e92ba21ce013d23fcdc)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/kernel/panic.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  */
7 
8 /*
9  * This function is used through-out the kernel (including mm and fs)
10  * to indicate a major problem.
11  */
12 #include <linux/debug_locks.h>
13 #include <linux/sched/debug.h>
14 #include <linux/interrupt.h>
15 #include <linux/kgdb.h>
16 #include <linux/kmsg_dump.h>
17 #include <linux/kallsyms.h>
18 #include <linux/notifier.h>
19 #include <linux/vt_kern.h>
20 #include <linux/module.h>
21 #include <linux/random.h>
22 #include <linux/ftrace.h>
23 #include <linux/reboot.h>
24 #include <linux/delay.h>
25 #include <linux/kexec.h>
26 #include <linux/panic_notifier.h>
27 #include <linux/sched.h>
28 #include <linux/string_helpers.h>
29 #include <linux/sysrq.h>
30 #include <linux/init.h>
31 #include <linux/nmi.h>
32 #include <linux/console.h>
33 #include <linux/bug.h>
34 #include <linux/ratelimit.h>
35 #include <linux/debugfs.h>
36 #include <linux/sysfs.h>
37 #include <linux/context_tracking.h>
38 #include <linux/seq_buf.h>
39 #include <linux/sys_info.h>
40 #include <trace/events/error_report.h>
41 #include <asm/sections.h>
42 
43 #define PANIC_TIMER_STEP 100
44 #define PANIC_BLINK_SPD 18
45 
46 #ifdef CONFIG_SMP
47 /*
48  * Should we dump all CPUs backtraces in an oops event?
49  * Defaults to 0, can be changed via sysctl.
50  */
51 static unsigned int __read_mostly sysctl_oops_all_cpu_backtrace;
52 #else
53 #define sysctl_oops_all_cpu_backtrace 0
54 #endif /* CONFIG_SMP */
55 
56 int panic_on_oops = CONFIG_PANIC_ON_OOPS_VALUE;
57 static unsigned long tainted_mask =
58 	IS_ENABLED(CONFIG_RANDSTRUCT) ? (1 << TAINT_RANDSTRUCT) : 0;
59 static int pause_on_oops;
60 static int pause_on_oops_flag;
61 static DEFINE_SPINLOCK(pause_on_oops_lock);
62 bool crash_kexec_post_notifiers;
63 int panic_on_warn __read_mostly;
64 unsigned long panic_on_taint;
65 bool panic_on_taint_nousertaint = false;
66 static unsigned int warn_limit __read_mostly;
67 static bool panic_console_replay;
68 
69 bool panic_triggering_all_cpu_backtrace;
70 
71 int panic_timeout = CONFIG_PANIC_TIMEOUT;
72 EXPORT_SYMBOL_GPL(panic_timeout);
73 
74 unsigned long panic_print;
75 
76 ATOMIC_NOTIFIER_HEAD(panic_notifier_list);
77 
78 EXPORT_SYMBOL(panic_notifier_list);
79 
80 #ifdef CONFIG_SYSCTL
81 static int sysctl_panic_print_handler(const struct ctl_table *table, int write,
82 			   void *buffer, size_t *lenp, loff_t *ppos)
83 {
84 	pr_info_once("Kernel: 'panic_print' sysctl interface will be obsoleted by both 'panic_sys_info' and 'panic_console_replay'\n");
85 	return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
86 }
87 
88 static const struct ctl_table kern_panic_table[] = {
89 #ifdef CONFIG_SMP
90 	{
91 		.procname       = "oops_all_cpu_backtrace",
92 		.data           = &sysctl_oops_all_cpu_backtrace,
93 		.maxlen         = sizeof(int),
94 		.mode           = 0644,
95 		.proc_handler   = proc_dointvec_minmax,
96 		.extra1         = SYSCTL_ZERO,
97 		.extra2         = SYSCTL_ONE,
98 	},
99 #endif
100 	{
101 		.procname	= "panic",
102 		.data		= &panic_timeout,
103 		.maxlen		= sizeof(int),
104 		.mode		= 0644,
105 		.proc_handler	= proc_dointvec,
106 	},
107 	{
108 		.procname	= "panic_on_oops",
109 		.data		= &panic_on_oops,
110 		.maxlen		= sizeof(int),
111 		.mode		= 0644,
112 		.proc_handler	= proc_dointvec,
113 	},
114 	{
115 		.procname	= "panic_print",
116 		.data		= &panic_print,
117 		.maxlen		= sizeof(unsigned long),
118 		.mode		= 0644,
119 		.proc_handler	= sysctl_panic_print_handler,
120 	},
121 	{
122 		.procname	= "panic_on_warn",
123 		.data		= &panic_on_warn,
124 		.maxlen		= sizeof(int),
125 		.mode		= 0644,
126 		.proc_handler	= proc_dointvec_minmax,
127 		.extra1		= SYSCTL_ZERO,
128 		.extra2		= SYSCTL_ONE,
129 	},
130 	{
131 		.procname       = "warn_limit",
132 		.data           = &warn_limit,
133 		.maxlen         = sizeof(warn_limit),
134 		.mode           = 0644,
135 		.proc_handler   = proc_douintvec,
136 	},
137 	{
138 		.procname	= "panic_sys_info",
139 		.data		= &panic_print,
140 		.maxlen         = sizeof(panic_print),
141 		.mode		= 0644,
142 		.proc_handler	= sysctl_sys_info_handler,
143 	},
144 };
145 
146 static __init int kernel_panic_sysctls_init(void)
147 {
148 	register_sysctl_init("kernel", kern_panic_table);
149 	return 0;
150 }
151 late_initcall(kernel_panic_sysctls_init);
152 #endif
153 
154 /* The format is "panic_sys_info=tasks,mem,locks,ftrace,..." */
155 static int __init setup_panic_sys_info(char *buf)
156 {
157 	/* There is no risk of race in kernel boot phase */
158 	panic_print = sys_info_parse_param(buf);
159 	return 1;
160 }
161 __setup("panic_sys_info=", setup_panic_sys_info);
162 
163 static atomic_t warn_count = ATOMIC_INIT(0);
164 
165 #ifdef CONFIG_SYSFS
166 static ssize_t warn_count_show(struct kobject *kobj, struct kobj_attribute *attr,
167 			       char *page)
168 {
169 	return sysfs_emit(page, "%d\n", atomic_read(&warn_count));
170 }
171 
172 static struct kobj_attribute warn_count_attr = __ATTR_RO(warn_count);
173 
174 static __init int kernel_panic_sysfs_init(void)
175 {
176 	sysfs_add_file_to_group(kernel_kobj, &warn_count_attr.attr, NULL);
177 	return 0;
178 }
179 late_initcall(kernel_panic_sysfs_init);
180 #endif
181 
182 static long no_blink(int state)
183 {
184 	return 0;
185 }
186 
187 /* Returns how long it waited in ms */
188 long (*panic_blink)(int state);
189 EXPORT_SYMBOL(panic_blink);
190 
191 /*
192  * Stop ourself in panic -- architecture code may override this
193  */
194 void __weak __noreturn panic_smp_self_stop(void)
195 {
196 	while (1)
197 		cpu_relax();
198 }
199 
200 /*
201  * Stop ourselves in NMI context if another CPU has already panicked. Arch code
202  * may override this to prepare for crash dumping, e.g. save regs info.
203  */
204 void __weak __noreturn nmi_panic_self_stop(struct pt_regs *regs)
205 {
206 	panic_smp_self_stop();
207 }
208 
209 /*
210  * Stop other CPUs in panic.  Architecture dependent code may override this
211  * with more suitable version.  For example, if the architecture supports
212  * crash dump, it should save registers of each stopped CPU and disable
213  * per-CPU features such as virtualization extensions.
214  */
215 void __weak crash_smp_send_stop(void)
216 {
217 	static int cpus_stopped;
218 
219 	/*
220 	 * This function can be called twice in panic path, but obviously
221 	 * we execute this only once.
222 	 */
223 	if (cpus_stopped)
224 		return;
225 
226 	/*
227 	 * Note smp_send_stop is the usual smp shutdown function, which
228 	 * unfortunately means it may not be hardened to work in a panic
229 	 * situation.
230 	 */
231 	smp_send_stop();
232 	cpus_stopped = 1;
233 }
234 
235 atomic_t panic_cpu = ATOMIC_INIT(PANIC_CPU_INVALID);
236 
237 /*
238  * A variant of panic() called from NMI context. We return if we've already
239  * panicked on this CPU. If another CPU already panicked, loop in
240  * nmi_panic_self_stop() which can provide architecture dependent code such
241  * as saving register state for crash dump.
242  */
243 void nmi_panic(struct pt_regs *regs, const char *msg)
244 {
245 	int old_cpu, this_cpu;
246 
247 	old_cpu = PANIC_CPU_INVALID;
248 	this_cpu = raw_smp_processor_id();
249 
250 	/* atomic_try_cmpxchg updates old_cpu on failure */
251 	if (atomic_try_cmpxchg(&panic_cpu, &old_cpu, this_cpu))
252 		panic("%s", msg);
253 	else if (old_cpu != this_cpu)
254 		nmi_panic_self_stop(regs);
255 }
256 EXPORT_SYMBOL(nmi_panic);
257 
258 void check_panic_on_warn(const char *origin)
259 {
260 	unsigned int limit;
261 
262 	if (panic_on_warn)
263 		panic("%s: panic_on_warn set ...\n", origin);
264 
265 	limit = READ_ONCE(warn_limit);
266 	if (atomic_inc_return(&warn_count) >= limit && limit)
267 		panic("%s: system warned too often (kernel.warn_limit is %d)",
268 		      origin, limit);
269 }
270 
271 /*
272  * Helper that triggers the NMI backtrace (if set in panic_print)
273  * and then performs the secondary CPUs shutdown - we cannot have
274  * the NMI backtrace after the CPUs are off!
275  */
276 static void panic_other_cpus_shutdown(bool crash_kexec)
277 {
278 	if (panic_print & SYS_INFO_ALL_CPU_BT) {
279 		/* Temporary allow non-panic CPUs to write their backtraces. */
280 		panic_triggering_all_cpu_backtrace = true;
281 		trigger_all_cpu_backtrace();
282 		panic_triggering_all_cpu_backtrace = false;
283 	}
284 
285 	/*
286 	 * Note that smp_send_stop() is the usual SMP shutdown function,
287 	 * which unfortunately may not be hardened to work in a panic
288 	 * situation. If we want to do crash dump after notifier calls
289 	 * and kmsg_dump, we will need architecture dependent extra
290 	 * bits in addition to stopping other CPUs, hence we rely on
291 	 * crash_smp_send_stop() for that.
292 	 */
293 	if (!crash_kexec)
294 		smp_send_stop();
295 	else
296 		crash_smp_send_stop();
297 }
298 
299 /**
300  * panic - halt the system
301  * @fmt: The text string to print
302  *
303  * Display a message, then perform cleanups. This function never returns.
304  */
305 void panic(const char *fmt, ...)
306 {
307 	static char buf[1024];
308 	va_list args;
309 	long i, i_next = 0, len;
310 	int state = 0;
311 	int old_cpu, this_cpu;
312 	bool _crash_kexec_post_notifiers = crash_kexec_post_notifiers;
313 
314 	if (panic_on_warn) {
315 		/*
316 		 * This thread may hit another WARN() in the panic path.
317 		 * Resetting this prevents additional WARN() from panicking the
318 		 * system on this thread.  Other threads are blocked by the
319 		 * panic_mutex in panic().
320 		 */
321 		panic_on_warn = 0;
322 	}
323 
324 	/*
325 	 * Disable local interrupts. This will prevent panic_smp_self_stop
326 	 * from deadlocking the first cpu that invokes the panic, since
327 	 * there is nothing to prevent an interrupt handler (that runs
328 	 * after setting panic_cpu) from invoking panic() again.
329 	 */
330 	local_irq_disable();
331 	preempt_disable_notrace();
332 
333 	/*
334 	 * It's possible to come here directly from a panic-assertion and
335 	 * not have preempt disabled. Some functions called from here want
336 	 * preempt to be disabled. No point enabling it later though...
337 	 *
338 	 * Only one CPU is allowed to execute the panic code from here. For
339 	 * multiple parallel invocations of panic, all other CPUs either
340 	 * stop themself or will wait until they are stopped by the 1st CPU
341 	 * with smp_send_stop().
342 	 *
343 	 * cmpxchg success means this is the 1st CPU which comes here,
344 	 * so go ahead.
345 	 * `old_cpu == this_cpu' means we came from nmi_panic() which sets
346 	 * panic_cpu to this CPU.  In this case, this is also the 1st CPU.
347 	 */
348 	old_cpu = PANIC_CPU_INVALID;
349 	this_cpu = raw_smp_processor_id();
350 
351 	/* atomic_try_cmpxchg updates old_cpu on failure */
352 	if (atomic_try_cmpxchg(&panic_cpu, &old_cpu, this_cpu)) {
353 		/* go ahead */
354 	} else if (old_cpu != this_cpu)
355 		panic_smp_self_stop();
356 
357 	console_verbose();
358 	bust_spinlocks(1);
359 	va_start(args, fmt);
360 	len = vscnprintf(buf, sizeof(buf), fmt, args);
361 	va_end(args);
362 
363 	if (len && buf[len - 1] == '\n')
364 		buf[len - 1] = '\0';
365 
366 	pr_emerg("Kernel panic - not syncing: %s\n", buf);
367 #ifdef CONFIG_DEBUG_BUGVERBOSE
368 	/*
369 	 * Avoid nested stack-dumping if a panic occurs during oops processing
370 	 */
371 	if (!test_taint(TAINT_DIE) && oops_in_progress <= 1)
372 		dump_stack();
373 #endif
374 
375 	/*
376 	 * If kgdb is enabled, give it a chance to run before we stop all
377 	 * the other CPUs or else we won't be able to debug processes left
378 	 * running on them.
379 	 */
380 	kgdb_panic(buf);
381 
382 	/*
383 	 * If we have crashed and we have a crash kernel loaded let it handle
384 	 * everything else.
385 	 * If we want to run this after calling panic_notifiers, pass
386 	 * the "crash_kexec_post_notifiers" option to the kernel.
387 	 *
388 	 * Bypass the panic_cpu check and call __crash_kexec directly.
389 	 */
390 	if (!_crash_kexec_post_notifiers)
391 		__crash_kexec(NULL);
392 
393 	panic_other_cpus_shutdown(_crash_kexec_post_notifiers);
394 
395 	printk_legacy_allow_panic_sync();
396 
397 	/*
398 	 * Run any panic handlers, including those that might need to
399 	 * add information to the kmsg dump output.
400 	 */
401 	atomic_notifier_call_chain(&panic_notifier_list, 0, buf);
402 
403 	sys_info(panic_print);
404 
405 	kmsg_dump_desc(KMSG_DUMP_PANIC, buf);
406 
407 	/*
408 	 * If you doubt kdump always works fine in any situation,
409 	 * "crash_kexec_post_notifiers" offers you a chance to run
410 	 * panic_notifiers and dumping kmsg before kdump.
411 	 * Note: since some panic_notifiers can make crashed kernel
412 	 * more unstable, it can increase risks of the kdump failure too.
413 	 *
414 	 * Bypass the panic_cpu check and call __crash_kexec directly.
415 	 */
416 	if (_crash_kexec_post_notifiers)
417 		__crash_kexec(NULL);
418 
419 	console_unblank();
420 
421 	/*
422 	 * We may have ended up stopping the CPU holding the lock (in
423 	 * smp_send_stop()) while still having some valuable data in the console
424 	 * buffer.  Try to acquire the lock then release it regardless of the
425 	 * result.  The release will also print the buffers out.  Locks debug
426 	 * should be disabled to avoid reporting bad unlock balance when
427 	 * panic() is not being callled from OOPS.
428 	 */
429 	debug_locks_off();
430 	console_flush_on_panic(CONSOLE_FLUSH_PENDING);
431 
432 	if ((panic_print & SYS_INFO_PANIC_CONSOLE_REPLAY) ||
433 		panic_console_replay)
434 		console_flush_on_panic(CONSOLE_REPLAY_ALL);
435 
436 	if (!panic_blink)
437 		panic_blink = no_blink;
438 
439 	if (panic_timeout > 0) {
440 		/*
441 		 * Delay timeout seconds before rebooting the machine.
442 		 * We can't use the "normal" timers since we just panicked.
443 		 */
444 		pr_emerg("Rebooting in %d seconds..\n", panic_timeout);
445 
446 		for (i = 0; i < panic_timeout * 1000; i += PANIC_TIMER_STEP) {
447 			touch_nmi_watchdog();
448 			if (i >= i_next) {
449 				i += panic_blink(state ^= 1);
450 				i_next = i + 3600 / PANIC_BLINK_SPD;
451 			}
452 			mdelay(PANIC_TIMER_STEP);
453 		}
454 	}
455 	if (panic_timeout != 0) {
456 		/*
457 		 * This will not be a clean reboot, with everything
458 		 * shutting down.  But if there is a chance of
459 		 * rebooting the system it will be rebooted.
460 		 */
461 		if (panic_reboot_mode != REBOOT_UNDEFINED)
462 			reboot_mode = panic_reboot_mode;
463 		emergency_restart();
464 	}
465 #ifdef __sparc__
466 	{
467 		extern int stop_a_enabled;
468 		/* Make sure the user can actually press Stop-A (L1-A) */
469 		stop_a_enabled = 1;
470 		pr_emerg("Press Stop-A (L1-A) from sun keyboard or send break\n"
471 			 "twice on console to return to the boot prom\n");
472 	}
473 #endif
474 #if defined(CONFIG_S390)
475 	disabled_wait();
476 #endif
477 	pr_emerg("---[ end Kernel panic - not syncing: %s ]---\n", buf);
478 
479 	/* Do not scroll important messages printed above */
480 	suppress_printk = 1;
481 
482 	/*
483 	 * The final messages may not have been printed if in a context that
484 	 * defers printing (such as NMI) and irq_work is not available.
485 	 * Explicitly flush the kernel log buffer one last time.
486 	 */
487 	console_flush_on_panic(CONSOLE_FLUSH_PENDING);
488 	nbcon_atomic_flush_unsafe();
489 
490 	local_irq_enable();
491 	for (i = 0; ; i += PANIC_TIMER_STEP) {
492 		touch_softlockup_watchdog();
493 		if (i >= i_next) {
494 			i += panic_blink(state ^= 1);
495 			i_next = i + 3600 / PANIC_BLINK_SPD;
496 		}
497 		mdelay(PANIC_TIMER_STEP);
498 	}
499 }
500 
501 EXPORT_SYMBOL(panic);
502 
503 #define TAINT_FLAG(taint, _c_true, _c_false, _module)			\
504 	[ TAINT_##taint ] = {						\
505 		.c_true = _c_true, .c_false = _c_false,			\
506 		.module = _module,					\
507 		.desc = #taint,						\
508 	}
509 
510 /*
511  * TAINT_FORCED_RMMOD could be a per-module flag but the module
512  * is being removed anyway.
513  */
514 const struct taint_flag taint_flags[TAINT_FLAGS_COUNT] = {
515 	TAINT_FLAG(PROPRIETARY_MODULE,		'P', 'G', true),
516 	TAINT_FLAG(FORCED_MODULE,		'F', ' ', true),
517 	TAINT_FLAG(CPU_OUT_OF_SPEC,		'S', ' ', false),
518 	TAINT_FLAG(FORCED_RMMOD,		'R', ' ', false),
519 	TAINT_FLAG(MACHINE_CHECK,		'M', ' ', false),
520 	TAINT_FLAG(BAD_PAGE,			'B', ' ', false),
521 	TAINT_FLAG(USER,			'U', ' ', false),
522 	TAINT_FLAG(DIE,				'D', ' ', false),
523 	TAINT_FLAG(OVERRIDDEN_ACPI_TABLE,	'A', ' ', false),
524 	TAINT_FLAG(WARN,			'W', ' ', false),
525 	TAINT_FLAG(CRAP,			'C', ' ', true),
526 	TAINT_FLAG(FIRMWARE_WORKAROUND,		'I', ' ', false),
527 	TAINT_FLAG(OOT_MODULE,			'O', ' ', true),
528 	TAINT_FLAG(UNSIGNED_MODULE,		'E', ' ', true),
529 	TAINT_FLAG(SOFTLOCKUP,			'L', ' ', false),
530 	TAINT_FLAG(LIVEPATCH,			'K', ' ', true),
531 	TAINT_FLAG(AUX,				'X', ' ', true),
532 	TAINT_FLAG(RANDSTRUCT,			'T', ' ', true),
533 	TAINT_FLAG(TEST,			'N', ' ', true),
534 	TAINT_FLAG(FWCTL,			'J', ' ', true),
535 };
536 
537 #undef TAINT_FLAG
538 
539 static void print_tainted_seq(struct seq_buf *s, bool verbose)
540 {
541 	const char *sep = "";
542 	int i;
543 
544 	if (!tainted_mask) {
545 		seq_buf_puts(s, "Not tainted");
546 		return;
547 	}
548 
549 	seq_buf_printf(s, "Tainted: ");
550 	for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
551 		const struct taint_flag *t = &taint_flags[i];
552 		bool is_set = test_bit(i, &tainted_mask);
553 		char c = is_set ? t->c_true : t->c_false;
554 
555 		if (verbose) {
556 			if (is_set) {
557 				seq_buf_printf(s, "%s[%c]=%s", sep, c, t->desc);
558 				sep = ", ";
559 			}
560 		} else {
561 			seq_buf_putc(s, c);
562 		}
563 	}
564 }
565 
566 static const char *_print_tainted(bool verbose)
567 {
568 	/* FIXME: what should the size be? */
569 	static char buf[sizeof(taint_flags)];
570 	struct seq_buf s;
571 
572 	BUILD_BUG_ON(ARRAY_SIZE(taint_flags) != TAINT_FLAGS_COUNT);
573 
574 	seq_buf_init(&s, buf, sizeof(buf));
575 
576 	print_tainted_seq(&s, verbose);
577 
578 	return seq_buf_str(&s);
579 }
580 
581 /**
582  * print_tainted - return a string to represent the kernel taint state.
583  *
584  * For individual taint flag meanings, see Documentation/admin-guide/sysctl/kernel.rst
585  *
586  * The string is overwritten by the next call to print_tainted(),
587  * but is always NULL terminated.
588  */
589 const char *print_tainted(void)
590 {
591 	return _print_tainted(false);
592 }
593 
594 /**
595  * print_tainted_verbose - A more verbose version of print_tainted()
596  */
597 const char *print_tainted_verbose(void)
598 {
599 	return _print_tainted(true);
600 }
601 
602 int test_taint(unsigned flag)
603 {
604 	return test_bit(flag, &tainted_mask);
605 }
606 EXPORT_SYMBOL(test_taint);
607 
608 unsigned long get_taint(void)
609 {
610 	return tainted_mask;
611 }
612 
613 /**
614  * add_taint: add a taint flag if not already set.
615  * @flag: one of the TAINT_* constants.
616  * @lockdep_ok: whether lock debugging is still OK.
617  *
618  * If something bad has gone wrong, you'll want @lockdebug_ok = false, but for
619  * some notewortht-but-not-corrupting cases, it can be set to true.
620  */
621 void add_taint(unsigned flag, enum lockdep_ok lockdep_ok)
622 {
623 	if (lockdep_ok == LOCKDEP_NOW_UNRELIABLE && __debug_locks_off())
624 		pr_warn("Disabling lock debugging due to kernel taint\n");
625 
626 	set_bit(flag, &tainted_mask);
627 
628 	if (tainted_mask & panic_on_taint) {
629 		panic_on_taint = 0;
630 		panic("panic_on_taint set ...");
631 	}
632 }
633 EXPORT_SYMBOL(add_taint);
634 
635 static void spin_msec(int msecs)
636 {
637 	int i;
638 
639 	for (i = 0; i < msecs; i++) {
640 		touch_nmi_watchdog();
641 		mdelay(1);
642 	}
643 }
644 
645 /*
646  * It just happens that oops_enter() and oops_exit() are identically
647  * implemented...
648  */
649 static void do_oops_enter_exit(void)
650 {
651 	unsigned long flags;
652 	static int spin_counter;
653 
654 	if (!pause_on_oops)
655 		return;
656 
657 	spin_lock_irqsave(&pause_on_oops_lock, flags);
658 	if (pause_on_oops_flag == 0) {
659 		/* This CPU may now print the oops message */
660 		pause_on_oops_flag = 1;
661 	} else {
662 		/* We need to stall this CPU */
663 		if (!spin_counter) {
664 			/* This CPU gets to do the counting */
665 			spin_counter = pause_on_oops;
666 			do {
667 				spin_unlock(&pause_on_oops_lock);
668 				spin_msec(MSEC_PER_SEC);
669 				spin_lock(&pause_on_oops_lock);
670 			} while (--spin_counter);
671 			pause_on_oops_flag = 0;
672 		} else {
673 			/* This CPU waits for a different one */
674 			while (spin_counter) {
675 				spin_unlock(&pause_on_oops_lock);
676 				spin_msec(1);
677 				spin_lock(&pause_on_oops_lock);
678 			}
679 		}
680 	}
681 	spin_unlock_irqrestore(&pause_on_oops_lock, flags);
682 }
683 
684 /*
685  * Return true if the calling CPU is allowed to print oops-related info.
686  * This is a bit racy..
687  */
688 bool oops_may_print(void)
689 {
690 	return pause_on_oops_flag == 0;
691 }
692 
693 /*
694  * Called when the architecture enters its oops handler, before it prints
695  * anything.  If this is the first CPU to oops, and it's oopsing the first
696  * time then let it proceed.
697  *
698  * This is all enabled by the pause_on_oops kernel boot option.  We do all
699  * this to ensure that oopses don't scroll off the screen.  It has the
700  * side-effect of preventing later-oopsing CPUs from mucking up the display,
701  * too.
702  *
703  * It turns out that the CPU which is allowed to print ends up pausing for
704  * the right duration, whereas all the other CPUs pause for twice as long:
705  * once in oops_enter(), once in oops_exit().
706  */
707 void oops_enter(void)
708 {
709 	nbcon_cpu_emergency_enter();
710 	tracing_off();
711 	/* can't trust the integrity of the kernel anymore: */
712 	debug_locks_off();
713 	do_oops_enter_exit();
714 
715 	if (sysctl_oops_all_cpu_backtrace)
716 		trigger_all_cpu_backtrace();
717 }
718 
719 static void print_oops_end_marker(void)
720 {
721 	pr_warn("---[ end trace %016llx ]---\n", 0ULL);
722 }
723 
724 /*
725  * Called when the architecture exits its oops handler, after printing
726  * everything.
727  */
728 void oops_exit(void)
729 {
730 	do_oops_enter_exit();
731 	print_oops_end_marker();
732 	nbcon_cpu_emergency_exit();
733 	kmsg_dump(KMSG_DUMP_OOPS);
734 }
735 
736 struct warn_args {
737 	const char *fmt;
738 	va_list args;
739 };
740 
741 void __warn(const char *file, int line, void *caller, unsigned taint,
742 	    struct pt_regs *regs, struct warn_args *args)
743 {
744 	nbcon_cpu_emergency_enter();
745 
746 	disable_trace_on_warning();
747 
748 	if (file)
749 		pr_warn("WARNING: CPU: %d PID: %d at %s:%d %pS\n",
750 			raw_smp_processor_id(), current->pid, file, line,
751 			caller);
752 	else
753 		pr_warn("WARNING: CPU: %d PID: %d at %pS\n",
754 			raw_smp_processor_id(), current->pid, caller);
755 
756 #pragma GCC diagnostic push
757 #ifndef __clang__
758 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
759 #endif
760 	if (args)
761 		vprintk(args->fmt, args->args);
762 #pragma GCC diagnostic pop
763 
764 	print_modules();
765 
766 	if (regs)
767 		show_regs(regs);
768 
769 	check_panic_on_warn("kernel");
770 
771 	if (!regs)
772 		dump_stack();
773 
774 	print_irqtrace_events(current);
775 
776 	print_oops_end_marker();
777 	trace_error_report_end(ERROR_DETECTOR_WARN, (unsigned long)caller);
778 
779 	/* Just a warning, don't kill lockdep. */
780 	add_taint(taint, LOCKDEP_STILL_OK);
781 
782 	nbcon_cpu_emergency_exit();
783 }
784 
785 #ifdef CONFIG_BUG
786 #ifndef __WARN_FLAGS
787 void warn_slowpath_fmt(const char *file, int line, unsigned taint,
788 		       const char *fmt, ...)
789 {
790 	bool rcu = warn_rcu_enter();
791 	struct warn_args args;
792 
793 	pr_warn(CUT_HERE);
794 
795 	if (!fmt) {
796 		__warn(file, line, __builtin_return_address(0), taint,
797 		       NULL, NULL);
798 		warn_rcu_exit(rcu);
799 		return;
800 	}
801 
802 	args.fmt = fmt;
803 	va_start(args.args, fmt);
804 	__warn(file, line, __builtin_return_address(0), taint, NULL, &args);
805 	va_end(args.args);
806 	warn_rcu_exit(rcu);
807 }
808 EXPORT_SYMBOL(warn_slowpath_fmt);
809 #else
810 void __warn_printk(const char *fmt, ...)
811 {
812 	bool rcu = warn_rcu_enter();
813 	va_list args;
814 
815 	pr_warn(CUT_HERE);
816 
817 	va_start(args, fmt);
818 	vprintk(fmt, args);
819 	va_end(args);
820 	warn_rcu_exit(rcu);
821 }
822 EXPORT_SYMBOL(__warn_printk);
823 #endif
824 
825 /* Support resetting WARN*_ONCE state */
826 
827 static int clear_warn_once_set(void *data, u64 val)
828 {
829 	generic_bug_clear_once();
830 	memset(__start_once, 0, __end_once - __start_once);
831 	return 0;
832 }
833 
834 DEFINE_DEBUGFS_ATTRIBUTE(clear_warn_once_fops, NULL, clear_warn_once_set,
835 			 "%lld\n");
836 
837 static __init int register_warn_debugfs(void)
838 {
839 	/* Don't care about failure */
840 	debugfs_create_file_unsafe("clear_warn_once", 0200, NULL, NULL,
841 				   &clear_warn_once_fops);
842 	return 0;
843 }
844 
845 device_initcall(register_warn_debugfs);
846 #endif
847 
848 #ifdef CONFIG_STACKPROTECTOR
849 
850 /*
851  * Called when gcc's -fstack-protector feature is used, and
852  * gcc detects corruption of the on-stack canary value
853  */
854 __visible noinstr void __stack_chk_fail(void)
855 {
856 	unsigned long flags;
857 
858 	instrumentation_begin();
859 	flags = user_access_save();
860 
861 	panic("stack-protector: Kernel stack is corrupted in: %pB",
862 		__builtin_return_address(0));
863 
864 	user_access_restore(flags);
865 	instrumentation_end();
866 }
867 EXPORT_SYMBOL(__stack_chk_fail);
868 
869 #endif
870 
871 core_param(panic, panic_timeout, int, 0644);
872 core_param(panic_print, panic_print, ulong, 0644);
873 core_param(pause_on_oops, pause_on_oops, int, 0644);
874 core_param(panic_on_warn, panic_on_warn, int, 0644);
875 core_param(crash_kexec_post_notifiers, crash_kexec_post_notifiers, bool, 0644);
876 core_param(panic_console_replay, panic_console_replay, bool, 0644);
877 
878 static int __init oops_setup(char *s)
879 {
880 	if (!s)
881 		return -EINVAL;
882 	if (!strcmp(s, "panic"))
883 		panic_on_oops = 1;
884 	return 0;
885 }
886 early_param("oops", oops_setup);
887 
888 static int __init panic_on_taint_setup(char *s)
889 {
890 	char *taint_str;
891 
892 	if (!s)
893 		return -EINVAL;
894 
895 	taint_str = strsep(&s, ",");
896 	if (kstrtoul(taint_str, 16, &panic_on_taint))
897 		return -EINVAL;
898 
899 	/* make sure panic_on_taint doesn't hold out-of-range TAINT flags */
900 	panic_on_taint &= TAINT_FLAGS_MAX;
901 
902 	if (!panic_on_taint)
903 		return -EINVAL;
904 
905 	if (s && !strcmp(s, "nousertaint"))
906 		panic_on_taint_nousertaint = true;
907 
908 	pr_info("panic_on_taint: bitmask=0x%lx nousertaint_mode=%s\n",
909 		panic_on_taint, str_enabled_disabled(panic_on_taint_nousertaint));
910 
911 	return 0;
912 }
913 early_param("panic_on_taint", panic_on_taint_setup);
914