xref: /linux/kernel/watchdog.c (revision 80bab43f6f235664fff2d3518b3901ba9c4ac5a3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Detect hard and soft lockups on a system
4  *
5  * started by Don Zickus, Copyright (C) 2010 Red Hat, Inc.
6  *
7  * Note: Most of this code is borrowed heavily from the original softlockup
8  * detector, so thanks to Ingo for the initial implementation.
9  * Some chunks also taken from the old x86-specific nmi watchdog code, thanks
10  * to those contributors as well.
11  */
12 
13 #define pr_fmt(fmt) "watchdog: " fmt
14 
15 #include <linux/cpu.h>
16 #include <linux/init.h>
17 #include <linux/irq.h>
18 #include <linux/irqdesc.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/kvm_para.h>
21 #include <linux/math64.h>
22 #include <linux/mm.h>
23 #include <linux/module.h>
24 #include <linux/nmi.h>
25 #include <linux/stop_machine.h>
26 #include <linux/sysctl.h>
27 #include <linux/tick.h>
28 #include <linux/sys_info.h>
29 
30 #include <linux/sched/clock.h>
31 #include <linux/sched/debug.h>
32 #include <linux/sched/isolation.h>
33 
34 #include <asm/irq_regs.h>
35 
36 static DEFINE_MUTEX(watchdog_mutex);
37 
38 #if defined(CONFIG_HARDLOCKUP_DETECTOR) || defined(CONFIG_HARDLOCKUP_DETECTOR_SPARC64)
39 # define WATCHDOG_HARDLOCKUP_DEFAULT	1
40 #else
41 # define WATCHDOG_HARDLOCKUP_DEFAULT	0
42 #endif
43 
44 #define NUM_SAMPLE_PERIODS	5
45 
46 unsigned long __read_mostly watchdog_enabled;
47 int __read_mostly watchdog_user_enabled = 1;
48 static int __read_mostly watchdog_hardlockup_user_enabled = WATCHDOG_HARDLOCKUP_DEFAULT;
49 static int __read_mostly watchdog_softlockup_user_enabled = 1;
50 int __read_mostly watchdog_thresh = 10;
51 static int __read_mostly watchdog_thresh_next;
52 static int __read_mostly watchdog_hardlockup_available;
53 
54 struct cpumask watchdog_cpumask __read_mostly;
55 unsigned long *watchdog_cpumask_bits = cpumask_bits(&watchdog_cpumask);
56 
57 #ifdef CONFIG_HARDLOCKUP_DETECTOR
58 
59 # ifdef CONFIG_SMP
60 int __read_mostly sysctl_hardlockup_all_cpu_backtrace;
61 # endif /* CONFIG_SMP */
62 
63 /*
64  * Should we panic when a soft-lockup or hard-lockup occurs:
65  */
66 unsigned int __read_mostly hardlockup_panic =
67 			IS_ENABLED(CONFIG_BOOTPARAM_HARDLOCKUP_PANIC);
68 
69 /*
70  * bitmasks to control what kinds of system info to be printed when
71  * hard lockup is detected, it could be task, memory, lock etc.
72  * Refer include/linux/sys_info.h for detailed bit definition.
73  */
74 static unsigned long hardlockup_si_mask;
75 
76 #ifdef CONFIG_SYSFS
77 
78 static unsigned int hardlockup_count;
79 
80 static ssize_t hardlockup_count_show(struct kobject *kobj, struct kobj_attribute *attr,
81 				     char *page)
82 {
83 	return sysfs_emit(page, "%u\n", hardlockup_count);
84 }
85 
86 static struct kobj_attribute hardlockup_count_attr = __ATTR_RO(hardlockup_count);
87 
88 static __init int kernel_hardlockup_sysfs_init(void)
89 {
90 	sysfs_add_file_to_group(kernel_kobj, &hardlockup_count_attr.attr, NULL);
91 	return 0;
92 }
93 
94 late_initcall(kernel_hardlockup_sysfs_init);
95 
96 #endif // CONFIG_SYSFS
97 
98 /*
99  * We may not want to enable hard lockup detection by default in all cases,
100  * for example when running the kernel as a guest on a hypervisor. In these
101  * cases this function can be called to disable hard lockup detection. This
102  * function should only be executed once by the boot processor before the
103  * kernel command line parameters are parsed, because otherwise it is not
104  * possible to override this in hardlockup_panic_setup().
105  */
106 void __init hardlockup_detector_disable(void)
107 {
108 	watchdog_hardlockup_user_enabled = 0;
109 }
110 
111 static int __init hardlockup_panic_setup(char *str)
112 {
113 next:
114 	if (!strncmp(str, "panic", 5))
115 		hardlockup_panic = 1;
116 	else if (!strncmp(str, "nopanic", 7))
117 		hardlockup_panic = 0;
118 	else if (!strncmp(str, "0", 1))
119 		watchdog_hardlockup_user_enabled = 0;
120 	else if (!strncmp(str, "1", 1))
121 		watchdog_hardlockup_user_enabled = 1;
122 	else if (!strncmp(str, "r", 1))
123 		hardlockup_config_perf_event(str + 1);
124 	while (*(str++)) {
125 		if (*str == ',') {
126 			str++;
127 			goto next;
128 		}
129 	}
130 	return 1;
131 }
132 __setup("nmi_watchdog=", hardlockup_panic_setup);
133 
134 #endif /* CONFIG_HARDLOCKUP_DETECTOR */
135 
136 #if defined(CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER)
137 
138 static DEFINE_PER_CPU(atomic_t, hrtimer_interrupts);
139 static DEFINE_PER_CPU(int, hrtimer_interrupts_saved);
140 static DEFINE_PER_CPU(bool, watchdog_hardlockup_warned);
141 static DEFINE_PER_CPU(bool, watchdog_hardlockup_touched);
142 static unsigned long hard_lockup_nmi_warn;
143 
144 notrace void arch_touch_nmi_watchdog(void)
145 {
146 	/*
147 	 * Using __raw here because some code paths have
148 	 * preemption enabled.  If preemption is enabled
149 	 * then interrupts should be enabled too, in which
150 	 * case we shouldn't have to worry about the watchdog
151 	 * going off.
152 	 */
153 	raw_cpu_write(watchdog_hardlockup_touched, true);
154 }
155 EXPORT_SYMBOL(arch_touch_nmi_watchdog);
156 
157 void watchdog_hardlockup_touch_cpu(unsigned int cpu)
158 {
159 	per_cpu(watchdog_hardlockup_touched, cpu) = true;
160 }
161 
162 static bool is_hardlockup(unsigned int cpu)
163 {
164 	int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
165 
166 	if (per_cpu(hrtimer_interrupts_saved, cpu) == hrint)
167 		return true;
168 
169 	/*
170 	 * NOTE: we don't need any fancy atomic_t or READ_ONCE/WRITE_ONCE
171 	 * for hrtimer_interrupts_saved. hrtimer_interrupts_saved is
172 	 * written/read by a single CPU.
173 	 */
174 	per_cpu(hrtimer_interrupts_saved, cpu) = hrint;
175 
176 	return false;
177 }
178 
179 static void watchdog_hardlockup_kick(void)
180 {
181 	int new_interrupts;
182 
183 	new_interrupts = atomic_inc_return(this_cpu_ptr(&hrtimer_interrupts));
184 	watchdog_buddy_check_hardlockup(new_interrupts);
185 }
186 
187 void watchdog_hardlockup_check(unsigned int cpu, struct pt_regs *regs)
188 {
189 	int hardlockup_all_cpu_backtrace;
190 
191 	if (per_cpu(watchdog_hardlockup_touched, cpu)) {
192 		per_cpu(watchdog_hardlockup_touched, cpu) = false;
193 		return;
194 	}
195 
196 	hardlockup_all_cpu_backtrace = (hardlockup_si_mask & SYS_INFO_ALL_BT) ?
197 					1 : sysctl_hardlockup_all_cpu_backtrace;
198 	/*
199 	 * Check for a hardlockup by making sure the CPU's timer
200 	 * interrupt is incrementing. The timer interrupt should have
201 	 * fired multiple times before we overflow'd. If it hasn't
202 	 * then this is a good indication the cpu is stuck
203 	 */
204 	if (is_hardlockup(cpu)) {
205 		unsigned int this_cpu = smp_processor_id();
206 		unsigned long flags;
207 
208 #ifdef CONFIG_SYSFS
209 		++hardlockup_count;
210 #endif
211 
212 		/* Only print hardlockups once. */
213 		if (per_cpu(watchdog_hardlockup_warned, cpu))
214 			return;
215 
216 		/*
217 		 * Prevent multiple hard-lockup reports if one cpu is already
218 		 * engaged in dumping all cpu back traces.
219 		 */
220 		if (hardlockup_all_cpu_backtrace) {
221 			if (test_and_set_bit_lock(0, &hard_lockup_nmi_warn))
222 				return;
223 		}
224 
225 		/*
226 		 * NOTE: we call printk_cpu_sync_get_irqsave() after printing
227 		 * the lockup message. While it would be nice to serialize
228 		 * that printout, we really want to make sure that if some
229 		 * other CPU somehow locked up while holding the lock associated
230 		 * with printk_cpu_sync_get_irqsave() that we can still at least
231 		 * get the message about the lockup out.
232 		 */
233 		pr_emerg("CPU%u: Watchdog detected hard LOCKUP on cpu %u\n", this_cpu, cpu);
234 		printk_cpu_sync_get_irqsave(flags);
235 
236 		print_modules();
237 		print_irqtrace_events(current);
238 		if (cpu == this_cpu) {
239 			if (regs)
240 				show_regs(regs);
241 			else
242 				dump_stack();
243 			printk_cpu_sync_put_irqrestore(flags);
244 		} else {
245 			printk_cpu_sync_put_irqrestore(flags);
246 			trigger_single_cpu_backtrace(cpu);
247 		}
248 
249 		if (hardlockup_all_cpu_backtrace) {
250 			trigger_allbutcpu_cpu_backtrace(cpu);
251 			if (!hardlockup_panic)
252 				clear_bit_unlock(0, &hard_lockup_nmi_warn);
253 		}
254 
255 		sys_info(hardlockup_si_mask & ~SYS_INFO_ALL_BT);
256 		if (hardlockup_panic)
257 			nmi_panic(regs, "Hard LOCKUP");
258 
259 		per_cpu(watchdog_hardlockup_warned, cpu) = true;
260 	} else {
261 		per_cpu(watchdog_hardlockup_warned, cpu) = false;
262 	}
263 }
264 
265 #else /* CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER */
266 
267 static inline void watchdog_hardlockup_kick(void) { }
268 
269 #endif /* !CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER */
270 
271 /*
272  * These functions can be overridden based on the configured hardlockdup detector.
273  *
274  * watchdog_hardlockup_enable/disable can be implemented to start and stop when
275  * softlockup watchdog start and stop. The detector must select the
276  * SOFTLOCKUP_DETECTOR Kconfig.
277  */
278 void __weak watchdog_hardlockup_enable(unsigned int cpu) { }
279 
280 void __weak watchdog_hardlockup_disable(unsigned int cpu) { }
281 
282 /*
283  * Watchdog-detector specific API.
284  *
285  * Return 0 when hardlockup watchdog is available, negative value otherwise.
286  * Note that the negative value means that a delayed probe might
287  * succeed later.
288  */
289 int __weak __init watchdog_hardlockup_probe(void)
290 {
291 	return -ENODEV;
292 }
293 
294 /**
295  * watchdog_hardlockup_stop - Stop the watchdog for reconfiguration
296  *
297  * The reconfiguration steps are:
298  * watchdog_hardlockup_stop();
299  * update_variables();
300  * watchdog_hardlockup_start();
301  */
302 void __weak watchdog_hardlockup_stop(void) { }
303 
304 /**
305  * watchdog_hardlockup_start - Start the watchdog after reconfiguration
306  *
307  * Counterpart to watchdog_hardlockup_stop().
308  *
309  * The following variables have been updated in update_variables() and
310  * contain the currently valid configuration:
311  * - watchdog_enabled
312  * - watchdog_thresh
313  * - watchdog_cpumask
314  */
315 void __weak watchdog_hardlockup_start(void) { }
316 
317 /**
318  * lockup_detector_update_enable - Update the sysctl enable bit
319  *
320  * Caller needs to make sure that the hard watchdogs are off, so this
321  * can't race with watchdog_hardlockup_disable().
322  */
323 static void lockup_detector_update_enable(void)
324 {
325 	watchdog_enabled = 0;
326 	if (!watchdog_user_enabled)
327 		return;
328 	if (watchdog_hardlockup_available && watchdog_hardlockup_user_enabled)
329 		watchdog_enabled |= WATCHDOG_HARDLOCKUP_ENABLED;
330 	if (watchdog_softlockup_user_enabled)
331 		watchdog_enabled |= WATCHDOG_SOFTOCKUP_ENABLED;
332 }
333 
334 #ifdef CONFIG_SOFTLOCKUP_DETECTOR
335 
336 /*
337  * Delay the soflockup report when running a known slow code.
338  * It does _not_ affect the timestamp of the last successdul reschedule.
339  */
340 #define SOFTLOCKUP_DELAY_REPORT	ULONG_MAX
341 
342 #ifdef CONFIG_SMP
343 int __read_mostly sysctl_softlockup_all_cpu_backtrace;
344 #endif
345 
346 /*
347  * bitmasks to control what kinds of system info to be printed when
348  * soft lockup is detected, it could be task, memory, lock etc.
349  * Refer include/linux/sys_info.h for detailed bit definition.
350  */
351 static unsigned long softlockup_si_mask;
352 
353 static struct cpumask watchdog_allowed_mask __read_mostly;
354 
355 /* Global variables, exported for sysctl */
356 unsigned int __read_mostly softlockup_panic =
357 			IS_ENABLED(CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC);
358 
359 static bool softlockup_initialized __read_mostly;
360 static u64 __read_mostly sample_period;
361 
362 #ifdef CONFIG_SYSFS
363 
364 static unsigned int softlockup_count;
365 
366 static ssize_t softlockup_count_show(struct kobject *kobj, struct kobj_attribute *attr,
367 				     char *page)
368 {
369 	return sysfs_emit(page, "%u\n", softlockup_count);
370 }
371 
372 static struct kobj_attribute softlockup_count_attr = __ATTR_RO(softlockup_count);
373 
374 static __init int kernel_softlockup_sysfs_init(void)
375 {
376 	sysfs_add_file_to_group(kernel_kobj, &softlockup_count_attr.attr, NULL);
377 	return 0;
378 }
379 
380 late_initcall(kernel_softlockup_sysfs_init);
381 
382 #endif // CONFIG_SYSFS
383 
384 /* Timestamp taken after the last successful reschedule. */
385 static DEFINE_PER_CPU(unsigned long, watchdog_touch_ts);
386 /* Timestamp of the last softlockup report. */
387 static DEFINE_PER_CPU(unsigned long, watchdog_report_ts);
388 static DEFINE_PER_CPU(struct hrtimer, watchdog_hrtimer);
389 static DEFINE_PER_CPU(bool, softlockup_touch_sync);
390 static unsigned long soft_lockup_nmi_warn;
391 
392 static int __init softlockup_panic_setup(char *str)
393 {
394 	softlockup_panic = simple_strtoul(str, NULL, 0);
395 	return 1;
396 }
397 __setup("softlockup_panic=", softlockup_panic_setup);
398 
399 static int __init nowatchdog_setup(char *str)
400 {
401 	watchdog_user_enabled = 0;
402 	return 1;
403 }
404 __setup("nowatchdog", nowatchdog_setup);
405 
406 static int __init nosoftlockup_setup(char *str)
407 {
408 	watchdog_softlockup_user_enabled = 0;
409 	return 1;
410 }
411 __setup("nosoftlockup", nosoftlockup_setup);
412 
413 static int __init watchdog_thresh_setup(char *str)
414 {
415 	get_option(&str, &watchdog_thresh);
416 	return 1;
417 }
418 __setup("watchdog_thresh=", watchdog_thresh_setup);
419 
420 #ifdef CONFIG_SOFTLOCKUP_DETECTOR_INTR_STORM
421 enum stats_per_group {
422 	STATS_SYSTEM,
423 	STATS_SOFTIRQ,
424 	STATS_HARDIRQ,
425 	STATS_IDLE,
426 	NUM_STATS_PER_GROUP,
427 };
428 
429 static const enum cpu_usage_stat tracked_stats[NUM_STATS_PER_GROUP] = {
430 	CPUTIME_SYSTEM,
431 	CPUTIME_SOFTIRQ,
432 	CPUTIME_IRQ,
433 	CPUTIME_IDLE,
434 };
435 
436 static DEFINE_PER_CPU(u16, cpustat_old[NUM_STATS_PER_GROUP]);
437 static DEFINE_PER_CPU(u8, cpustat_util[NUM_SAMPLE_PERIODS][NUM_STATS_PER_GROUP]);
438 static DEFINE_PER_CPU(u8, cpustat_tail);
439 
440 /*
441  * We don't need nanosecond resolution. A granularity of 16ms is
442  * sufficient for our precision, allowing us to use u16 to store
443  * cpustats, which will roll over roughly every ~1000 seconds.
444  * 2^24 ~= 16 * 10^6
445  */
446 static u16 get_16bit_precision(u64 data_ns)
447 {
448 	/*
449 	 * 2^24ns ~= 16.8ms
450 	 * Round to the nearest multiple of 16.8 milliseconds.
451 	 */
452 	return (data_ns + (1 << 23)) >> 24LL;
453 }
454 
455 static void update_cpustat(void)
456 {
457 	int i;
458 	u8 util;
459 	u16 old_stat, new_stat;
460 	struct kernel_cpustat kcpustat;
461 	u64 *cpustat = kcpustat.cpustat;
462 	u8 tail = __this_cpu_read(cpustat_tail);
463 	u16 sample_period_16 = get_16bit_precision(sample_period);
464 
465 	kcpustat_cpu_fetch(&kcpustat, smp_processor_id());
466 
467 	for (i = 0; i < NUM_STATS_PER_GROUP; i++) {
468 		old_stat = __this_cpu_read(cpustat_old[i]);
469 		new_stat = get_16bit_precision(cpustat[tracked_stats[i]]);
470 		util = DIV_ROUND_UP(100 * (new_stat - old_stat), sample_period_16);
471 		/*
472 		 * Since we use 16-bit precision, the raw data will undergo
473 		 * integer division, which may sometimes result in data loss,
474 		 * and then result might exceed 100%. To avoid confusion,
475 		 * we enforce a 100% display cap when calculations exceed this threshold.
476 		 */
477 		if (util > 100)
478 			util = 100;
479 		__this_cpu_write(cpustat_util[tail][i], util);
480 		__this_cpu_write(cpustat_old[i], new_stat);
481 	}
482 
483 	__this_cpu_write(cpustat_tail, (tail + 1) % NUM_SAMPLE_PERIODS);
484 }
485 
486 static void print_cpustat(void)
487 {
488 	int i, group;
489 	u8 tail = __this_cpu_read(cpustat_tail);
490 	u64 sample_period_msecond = sample_period;
491 
492 	do_div(sample_period_msecond, NSEC_PER_MSEC);
493 
494 	/*
495 	 * Outputting the "watchdog" prefix on every line is redundant and not
496 	 * concise, and the original alarm information is sufficient for
497 	 * positioning in logs, hence here printk() is used instead of pr_crit().
498 	 */
499 	printk(KERN_CRIT "CPU#%d Utilization every %llums during lockup:\n",
500 	       smp_processor_id(), sample_period_msecond);
501 
502 	for (i = 0; i < NUM_SAMPLE_PERIODS; i++) {
503 		group = (tail + i) % NUM_SAMPLE_PERIODS;
504 		printk(KERN_CRIT "\t#%d: %3u%% system,\t%3u%% softirq,\t"
505 			"%3u%% hardirq,\t%3u%% idle\n", i + 1,
506 			__this_cpu_read(cpustat_util[group][STATS_SYSTEM]),
507 			__this_cpu_read(cpustat_util[group][STATS_SOFTIRQ]),
508 			__this_cpu_read(cpustat_util[group][STATS_HARDIRQ]),
509 			__this_cpu_read(cpustat_util[group][STATS_IDLE]));
510 	}
511 }
512 
513 #define HARDIRQ_PERCENT_THRESH          50
514 #define NUM_HARDIRQ_REPORT              5
515 struct irq_counts {
516 	int irq;
517 	u32 counts;
518 };
519 
520 static DEFINE_PER_CPU(bool, snapshot_taken);
521 
522 /* Tabulate the most frequent interrupts. */
523 static void tabulate_irq_count(struct irq_counts *irq_counts, int irq, u32 counts, int rank)
524 {
525 	int i;
526 	struct irq_counts new_count = {irq, counts};
527 
528 	for (i = 0; i < rank; i++) {
529 		if (counts > irq_counts[i].counts)
530 			swap(new_count, irq_counts[i]);
531 	}
532 }
533 
534 /*
535  * If the hardirq time exceeds HARDIRQ_PERCENT_THRESH% of the sample_period,
536  * then the cause of softlockup might be interrupt storm. In this case, it
537  * would be useful to start interrupt counting.
538  */
539 static bool need_counting_irqs(void)
540 {
541 	u8 util;
542 	int tail = __this_cpu_read(cpustat_tail);
543 
544 	tail = (tail + NUM_HARDIRQ_REPORT - 1) % NUM_HARDIRQ_REPORT;
545 	util = __this_cpu_read(cpustat_util[tail][STATS_HARDIRQ]);
546 	return util > HARDIRQ_PERCENT_THRESH;
547 }
548 
549 static void start_counting_irqs(void)
550 {
551 	if (!__this_cpu_read(snapshot_taken)) {
552 		kstat_snapshot_irqs();
553 		__this_cpu_write(snapshot_taken, true);
554 	}
555 }
556 
557 static void stop_counting_irqs(void)
558 {
559 	__this_cpu_write(snapshot_taken, false);
560 }
561 
562 static void print_irq_counts(void)
563 {
564 	unsigned int i, count;
565 	struct irq_counts irq_counts_sorted[NUM_HARDIRQ_REPORT] = {
566 		{-1, 0}, {-1, 0}, {-1, 0}, {-1, 0}, {-1, 0}
567 	};
568 
569 	if (__this_cpu_read(snapshot_taken)) {
570 		for_each_active_irq(i) {
571 			count = kstat_get_irq_since_snapshot(i);
572 			tabulate_irq_count(irq_counts_sorted, i, count, NUM_HARDIRQ_REPORT);
573 		}
574 
575 		/*
576 		 * Outputting the "watchdog" prefix on every line is redundant and not
577 		 * concise, and the original alarm information is sufficient for
578 		 * positioning in logs, hence here printk() is used instead of pr_crit().
579 		 */
580 		printk(KERN_CRIT "CPU#%d Detect HardIRQ Time exceeds %d%%. Most frequent HardIRQs:\n",
581 		       smp_processor_id(), HARDIRQ_PERCENT_THRESH);
582 
583 		for (i = 0; i < NUM_HARDIRQ_REPORT; i++) {
584 			if (irq_counts_sorted[i].irq == -1)
585 				break;
586 
587 			printk(KERN_CRIT "\t#%u: %-10u\tirq#%d\n",
588 			       i + 1, irq_counts_sorted[i].counts,
589 			       irq_counts_sorted[i].irq);
590 		}
591 
592 		/*
593 		 * If the hardirq time is less than HARDIRQ_PERCENT_THRESH% in the last
594 		 * sample_period, then we suspect the interrupt storm might be subsiding.
595 		 */
596 		if (!need_counting_irqs())
597 			stop_counting_irqs();
598 	}
599 }
600 
601 static void report_cpu_status(void)
602 {
603 	print_cpustat();
604 	print_irq_counts();
605 }
606 #else
607 static inline void update_cpustat(void) { }
608 static inline void report_cpu_status(void) { }
609 static inline bool need_counting_irqs(void) { return false; }
610 static inline void start_counting_irqs(void) { }
611 static inline void stop_counting_irqs(void) { }
612 #endif
613 
614 /*
615  * Hard-lockup warnings should be triggered after just a few seconds. Soft-
616  * lockups can have false positives under extreme conditions. So we generally
617  * want a higher threshold for soft lockups than for hard lockups. So we couple
618  * the thresholds with a factor: we make the soft threshold twice the amount of
619  * time the hard threshold is.
620  */
621 static int get_softlockup_thresh(void)
622 {
623 	return watchdog_thresh * 2;
624 }
625 
626 /*
627  * Returns seconds, approximately.  We don't need nanosecond
628  * resolution, and we don't need to waste time with a big divide when
629  * 2^30ns == 1.074s.
630  */
631 static unsigned long get_timestamp(void)
632 {
633 	return running_clock() >> 30LL;  /* 2^30 ~= 10^9 */
634 }
635 
636 static void set_sample_period(void)
637 {
638 	/*
639 	 * convert watchdog_thresh from seconds to ns
640 	 * the divide by 5 is to give hrtimer several chances (two
641 	 * or three with the current relation between the soft
642 	 * and hard thresholds) to increment before the
643 	 * hardlockup detector generates a warning
644 	 */
645 	sample_period = get_softlockup_thresh() * ((u64)NSEC_PER_SEC / NUM_SAMPLE_PERIODS);
646 	watchdog_update_hrtimer_threshold(sample_period);
647 }
648 
649 static void update_report_ts(void)
650 {
651 	__this_cpu_write(watchdog_report_ts, get_timestamp());
652 }
653 
654 /* Commands for resetting the watchdog */
655 static void update_touch_ts(void)
656 {
657 	__this_cpu_write(watchdog_touch_ts, get_timestamp());
658 	update_report_ts();
659 }
660 
661 /**
662  * touch_softlockup_watchdog_sched - touch watchdog on scheduler stalls
663  *
664  * Call when the scheduler may have stalled for legitimate reasons
665  * preventing the watchdog task from executing - e.g. the scheduler
666  * entering idle state.  This should only be used for scheduler events.
667  * Use touch_softlockup_watchdog() for everything else.
668  */
669 notrace void touch_softlockup_watchdog_sched(void)
670 {
671 	/*
672 	 * Preemption can be enabled.  It doesn't matter which CPU's watchdog
673 	 * report period gets restarted here, so use the raw_ operation.
674 	 */
675 	raw_cpu_write(watchdog_report_ts, SOFTLOCKUP_DELAY_REPORT);
676 }
677 
678 notrace void touch_softlockup_watchdog(void)
679 {
680 	touch_softlockup_watchdog_sched();
681 	wq_watchdog_touch(raw_smp_processor_id());
682 }
683 EXPORT_SYMBOL(touch_softlockup_watchdog);
684 
685 void touch_all_softlockup_watchdogs(void)
686 {
687 	int cpu;
688 
689 	/*
690 	 * watchdog_mutex cannpt be taken here, as this might be called
691 	 * from (soft)interrupt context, so the access to
692 	 * watchdog_allowed_cpumask might race with a concurrent update.
693 	 *
694 	 * The watchdog time stamp can race against a concurrent real
695 	 * update as well, the only side effect might be a cycle delay for
696 	 * the softlockup check.
697 	 */
698 	for_each_cpu(cpu, &watchdog_allowed_mask) {
699 		per_cpu(watchdog_report_ts, cpu) = SOFTLOCKUP_DELAY_REPORT;
700 		wq_watchdog_touch(cpu);
701 	}
702 }
703 
704 void touch_softlockup_watchdog_sync(void)
705 {
706 	__this_cpu_write(softlockup_touch_sync, true);
707 	__this_cpu_write(watchdog_report_ts, SOFTLOCKUP_DELAY_REPORT);
708 }
709 
710 static int is_softlockup(unsigned long touch_ts,
711 			 unsigned long period_ts,
712 			 unsigned long now)
713 {
714 	if ((watchdog_enabled & WATCHDOG_SOFTOCKUP_ENABLED) && watchdog_thresh) {
715 		/*
716 		 * If period_ts has not been updated during a sample_period, then
717 		 * in the subsequent few sample_periods, period_ts might also not
718 		 * be updated, which could indicate a potential softlockup. In
719 		 * this case, if we suspect the cause of the potential softlockup
720 		 * might be interrupt storm, then we need to count the interrupts
721 		 * to find which interrupt is storming.
722 		 */
723 		if (time_after_eq(now, period_ts + get_softlockup_thresh() / NUM_SAMPLE_PERIODS) &&
724 		    need_counting_irqs())
725 			start_counting_irqs();
726 
727 		/*
728 		 * A poorly behaving BPF scheduler can live-lock the system into
729 		 * soft lockups. Tell sched_ext to try ejecting the BPF
730 		 * scheduler when close to a soft lockup.
731 		 */
732 		if (time_after_eq(now, period_ts + get_softlockup_thresh() * 3 / 4))
733 			scx_softlockup(now - touch_ts);
734 
735 		/* Warn about unreasonable delays. */
736 		if (time_after(now, period_ts + get_softlockup_thresh()))
737 			return now - touch_ts;
738 	}
739 	return 0;
740 }
741 
742 /* watchdog detector functions */
743 static DEFINE_PER_CPU(struct completion, softlockup_completion);
744 static DEFINE_PER_CPU(struct cpu_stop_work, softlockup_stop_work);
745 
746 /*
747  * The watchdog feed function - touches the timestamp.
748  *
749  * It only runs once every sample_period seconds (4 seconds by
750  * default) to reset the softlockup timestamp. If this gets delayed
751  * for more than 2*watchdog_thresh seconds then the debug-printout
752  * triggers in watchdog_timer_fn().
753  */
754 static int softlockup_fn(void *data)
755 {
756 	update_touch_ts();
757 	stop_counting_irqs();
758 	complete(this_cpu_ptr(&softlockup_completion));
759 
760 	return 0;
761 }
762 
763 /* watchdog kicker functions */
764 static enum hrtimer_restart watchdog_timer_fn(struct hrtimer *hrtimer)
765 {
766 	unsigned long touch_ts, period_ts, now;
767 	struct pt_regs *regs = get_irq_regs();
768 	int duration;
769 	int softlockup_all_cpu_backtrace;
770 	unsigned long flags;
771 
772 	if (!watchdog_enabled)
773 		return HRTIMER_NORESTART;
774 
775 	/*
776 	 * pass the buddy check if a panic is in process
777 	 */
778 	if (panic_in_progress())
779 		return HRTIMER_NORESTART;
780 
781 	softlockup_all_cpu_backtrace = (softlockup_si_mask & SYS_INFO_ALL_BT) ?
782 					1 : sysctl_softlockup_all_cpu_backtrace;
783 
784 	watchdog_hardlockup_kick();
785 
786 	/* kick the softlockup detector */
787 	if (completion_done(this_cpu_ptr(&softlockup_completion))) {
788 		reinit_completion(this_cpu_ptr(&softlockup_completion));
789 		stop_one_cpu_nowait(smp_processor_id(),
790 				softlockup_fn, NULL,
791 				this_cpu_ptr(&softlockup_stop_work));
792 	}
793 
794 	/* .. and repeat */
795 	hrtimer_forward_now(hrtimer, ns_to_ktime(sample_period));
796 
797 	/*
798 	 * Read the current timestamp first. It might become invalid anytime
799 	 * when a virtual machine is stopped by the host or when the watchog
800 	 * is touched from NMI.
801 	 */
802 	now = get_timestamp();
803 	/*
804 	 * If a virtual machine is stopped by the host it can look to
805 	 * the watchdog like a soft lockup. This function touches the watchdog.
806 	 */
807 	kvm_check_and_clear_guest_paused();
808 	/*
809 	 * The stored timestamp is comparable with @now only when not touched.
810 	 * It might get touched anytime from NMI. Make sure that is_softlockup()
811 	 * uses the same (valid) value.
812 	 */
813 	period_ts = READ_ONCE(*this_cpu_ptr(&watchdog_report_ts));
814 
815 	update_cpustat();
816 
817 	/* Reset the interval when touched by known problematic code. */
818 	if (period_ts == SOFTLOCKUP_DELAY_REPORT) {
819 		if (unlikely(__this_cpu_read(softlockup_touch_sync))) {
820 			/*
821 			 * If the time stamp was touched atomically
822 			 * make sure the scheduler tick is up to date.
823 			 */
824 			__this_cpu_write(softlockup_touch_sync, false);
825 			sched_clock_tick();
826 		}
827 
828 		update_report_ts();
829 		return HRTIMER_RESTART;
830 	}
831 
832 	/* Check for a softlockup. */
833 	touch_ts = __this_cpu_read(watchdog_touch_ts);
834 	duration = is_softlockup(touch_ts, period_ts, now);
835 	if (unlikely(duration)) {
836 #ifdef CONFIG_SYSFS
837 		++softlockup_count;
838 #endif
839 
840 		/*
841 		 * Prevent multiple soft-lockup reports if one cpu is already
842 		 * engaged in dumping all cpu back traces.
843 		 */
844 		if (softlockup_all_cpu_backtrace) {
845 			if (test_and_set_bit_lock(0, &soft_lockup_nmi_warn))
846 				return HRTIMER_RESTART;
847 		}
848 
849 		/* Start period for the next softlockup warning. */
850 		update_report_ts();
851 
852 		printk_cpu_sync_get_irqsave(flags);
853 		pr_emerg("BUG: soft lockup - CPU#%d stuck for %us! [%s:%d]\n",
854 			smp_processor_id(), duration,
855 			current->comm, task_pid_nr(current));
856 		report_cpu_status();
857 		print_modules();
858 		print_irqtrace_events(current);
859 		if (regs)
860 			show_regs(regs);
861 		else
862 			dump_stack();
863 		printk_cpu_sync_put_irqrestore(flags);
864 
865 		if (softlockup_all_cpu_backtrace) {
866 			trigger_allbutcpu_cpu_backtrace(smp_processor_id());
867 			if (!softlockup_panic)
868 				clear_bit_unlock(0, &soft_lockup_nmi_warn);
869 		}
870 
871 		add_taint(TAINT_SOFTLOCKUP, LOCKDEP_STILL_OK);
872 		sys_info(softlockup_si_mask & ~SYS_INFO_ALL_BT);
873 		if (softlockup_panic)
874 			panic("softlockup: hung tasks");
875 	}
876 
877 	return HRTIMER_RESTART;
878 }
879 
880 static void watchdog_enable(unsigned int cpu)
881 {
882 	struct hrtimer *hrtimer = this_cpu_ptr(&watchdog_hrtimer);
883 	struct completion *done = this_cpu_ptr(&softlockup_completion);
884 
885 	WARN_ON_ONCE(cpu != smp_processor_id());
886 
887 	init_completion(done);
888 	complete(done);
889 
890 	/*
891 	 * Start the timer first to prevent the hardlockup watchdog triggering
892 	 * before the timer has a chance to fire.
893 	 */
894 	hrtimer_setup(hrtimer, watchdog_timer_fn, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
895 	hrtimer_start(hrtimer, ns_to_ktime(sample_period),
896 		      HRTIMER_MODE_REL_PINNED_HARD);
897 
898 	/* Initialize timestamp */
899 	update_touch_ts();
900 	/* Enable the hardlockup detector */
901 	if (watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED)
902 		watchdog_hardlockup_enable(cpu);
903 }
904 
905 static void watchdog_disable(unsigned int cpu)
906 {
907 	struct hrtimer *hrtimer = this_cpu_ptr(&watchdog_hrtimer);
908 
909 	WARN_ON_ONCE(cpu != smp_processor_id());
910 
911 	/*
912 	 * Disable the hardlockup detector first. That prevents that a large
913 	 * delay between disabling the timer and disabling the hardlockup
914 	 * detector causes a false positive.
915 	 */
916 	watchdog_hardlockup_disable(cpu);
917 	hrtimer_cancel(hrtimer);
918 	wait_for_completion(this_cpu_ptr(&softlockup_completion));
919 }
920 
921 static int softlockup_stop_fn(void *data)
922 {
923 	watchdog_disable(smp_processor_id());
924 	return 0;
925 }
926 
927 static void softlockup_stop_all(void)
928 {
929 	int cpu;
930 
931 	if (!softlockup_initialized)
932 		return;
933 
934 	for_each_cpu(cpu, &watchdog_allowed_mask)
935 		smp_call_on_cpu(cpu, softlockup_stop_fn, NULL, false);
936 
937 	cpumask_clear(&watchdog_allowed_mask);
938 }
939 
940 static int softlockup_start_fn(void *data)
941 {
942 	watchdog_enable(smp_processor_id());
943 	return 0;
944 }
945 
946 static void softlockup_start_all(void)
947 {
948 	int cpu;
949 
950 	cpumask_copy(&watchdog_allowed_mask, &watchdog_cpumask);
951 	for_each_cpu(cpu, &watchdog_allowed_mask)
952 		smp_call_on_cpu(cpu, softlockup_start_fn, NULL, false);
953 }
954 
955 int lockup_detector_online_cpu(unsigned int cpu)
956 {
957 	if (cpumask_test_cpu(cpu, &watchdog_allowed_mask))
958 		watchdog_enable(cpu);
959 	return 0;
960 }
961 
962 int lockup_detector_offline_cpu(unsigned int cpu)
963 {
964 	if (cpumask_test_cpu(cpu, &watchdog_allowed_mask))
965 		watchdog_disable(cpu);
966 	return 0;
967 }
968 
969 static void __lockup_detector_reconfigure(bool thresh_changed)
970 {
971 	cpus_read_lock();
972 	watchdog_hardlockup_stop();
973 
974 	softlockup_stop_all();
975 	/*
976 	 * To prevent watchdog_timer_fn from using the old interval and
977 	 * the new watchdog_thresh at the same time, which could lead to
978 	 * false softlockup reports, it is necessary to update the
979 	 * watchdog_thresh after the softlockup is completed.
980 	 */
981 	if (thresh_changed)
982 		watchdog_thresh = READ_ONCE(watchdog_thresh_next);
983 	set_sample_period();
984 	lockup_detector_update_enable();
985 	if (watchdog_enabled && watchdog_thresh)
986 		softlockup_start_all();
987 
988 	watchdog_hardlockup_start();
989 	cpus_read_unlock();
990 }
991 
992 void lockup_detector_reconfigure(void)
993 {
994 	mutex_lock(&watchdog_mutex);
995 	__lockup_detector_reconfigure(false);
996 	mutex_unlock(&watchdog_mutex);
997 }
998 
999 /*
1000  * Create the watchdog infrastructure and configure the detector(s).
1001  */
1002 static __init void lockup_detector_setup(void)
1003 {
1004 	/*
1005 	 * If sysctl is off and watchdog got disabled on the command line,
1006 	 * nothing to do here.
1007 	 */
1008 	lockup_detector_update_enable();
1009 
1010 	if (!IS_ENABLED(CONFIG_SYSCTL) &&
1011 	    !(watchdog_enabled && watchdog_thresh))
1012 		return;
1013 
1014 	mutex_lock(&watchdog_mutex);
1015 	__lockup_detector_reconfigure(false);
1016 	softlockup_initialized = true;
1017 	mutex_unlock(&watchdog_mutex);
1018 }
1019 
1020 #else /* CONFIG_SOFTLOCKUP_DETECTOR */
1021 static void __lockup_detector_reconfigure(bool thresh_changed)
1022 {
1023 	cpus_read_lock();
1024 	watchdog_hardlockup_stop();
1025 	if (thresh_changed)
1026 		watchdog_thresh = READ_ONCE(watchdog_thresh_next);
1027 	lockup_detector_update_enable();
1028 	watchdog_hardlockup_start();
1029 	cpus_read_unlock();
1030 }
1031 void lockup_detector_reconfigure(void)
1032 {
1033 	__lockup_detector_reconfigure(false);
1034 }
1035 static inline void lockup_detector_setup(void)
1036 {
1037 	__lockup_detector_reconfigure(false);
1038 }
1039 #endif /* !CONFIG_SOFTLOCKUP_DETECTOR */
1040 
1041 /**
1042  * lockup_detector_soft_poweroff - Interface to stop lockup detector(s)
1043  *
1044  * Special interface for parisc. It prevents lockup detector warnings from
1045  * the default pm_poweroff() function which busy loops forever.
1046  */
1047 void lockup_detector_soft_poweroff(void)
1048 {
1049 	watchdog_enabled = 0;
1050 }
1051 
1052 #ifdef CONFIG_SYSCTL
1053 
1054 /* Propagate any changes to the watchdog infrastructure */
1055 static void proc_watchdog_update(bool thresh_changed)
1056 {
1057 	/* Remove impossible cpus to keep sysctl output clean. */
1058 	cpumask_and(&watchdog_cpumask, &watchdog_cpumask, cpu_possible_mask);
1059 	__lockup_detector_reconfigure(thresh_changed);
1060 }
1061 
1062 /*
1063  * common function for watchdog, nmi_watchdog and soft_watchdog parameter
1064  *
1065  * caller             | table->data points to            | 'which'
1066  * -------------------|----------------------------------|-------------------------------
1067  * proc_watchdog      | watchdog_user_enabled            | WATCHDOG_HARDLOCKUP_ENABLED |
1068  *                    |                                  | WATCHDOG_SOFTOCKUP_ENABLED
1069  * -------------------|----------------------------------|-------------------------------
1070  * proc_nmi_watchdog  | watchdog_hardlockup_user_enabled | WATCHDOG_HARDLOCKUP_ENABLED
1071  * -------------------|----------------------------------|-------------------------------
1072  * proc_soft_watchdog | watchdog_softlockup_user_enabled | WATCHDOG_SOFTOCKUP_ENABLED
1073  */
1074 static int proc_watchdog_common(int which, const struct ctl_table *table, int write,
1075 				void *buffer, size_t *lenp, loff_t *ppos)
1076 {
1077 	int err, old, *param = table->data;
1078 
1079 	mutex_lock(&watchdog_mutex);
1080 
1081 	old = *param;
1082 	if (!write) {
1083 		/*
1084 		 * On read synchronize the userspace interface. This is a
1085 		 * racy snapshot.
1086 		 */
1087 		*param = (watchdog_enabled & which) != 0;
1088 		err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
1089 		*param = old;
1090 	} else {
1091 		err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
1092 		if (!err && old != READ_ONCE(*param))
1093 			proc_watchdog_update(false);
1094 	}
1095 	mutex_unlock(&watchdog_mutex);
1096 	return err;
1097 }
1098 
1099 /*
1100  * /proc/sys/kernel/watchdog
1101  */
1102 static int proc_watchdog(const struct ctl_table *table, int write,
1103 			 void *buffer, size_t *lenp, loff_t *ppos)
1104 {
1105 	return proc_watchdog_common(WATCHDOG_HARDLOCKUP_ENABLED |
1106 				    WATCHDOG_SOFTOCKUP_ENABLED,
1107 				    table, write, buffer, lenp, ppos);
1108 }
1109 
1110 /*
1111  * /proc/sys/kernel/nmi_watchdog
1112  */
1113 static int proc_nmi_watchdog(const struct ctl_table *table, int write,
1114 			     void *buffer, size_t *lenp, loff_t *ppos)
1115 {
1116 	if (!watchdog_hardlockup_available && write)
1117 		return -ENOTSUPP;
1118 	return proc_watchdog_common(WATCHDOG_HARDLOCKUP_ENABLED,
1119 				    table, write, buffer, lenp, ppos);
1120 }
1121 
1122 #ifdef CONFIG_SOFTLOCKUP_DETECTOR
1123 /*
1124  * /proc/sys/kernel/soft_watchdog
1125  */
1126 static int proc_soft_watchdog(const struct ctl_table *table, int write,
1127 			      void *buffer, size_t *lenp, loff_t *ppos)
1128 {
1129 	return proc_watchdog_common(WATCHDOG_SOFTOCKUP_ENABLED,
1130 				    table, write, buffer, lenp, ppos);
1131 }
1132 #endif
1133 
1134 /*
1135  * /proc/sys/kernel/watchdog_thresh
1136  */
1137 static int proc_watchdog_thresh(const struct ctl_table *table, int write,
1138 				void *buffer, size_t *lenp, loff_t *ppos)
1139 {
1140 	int err, old;
1141 
1142 	mutex_lock(&watchdog_mutex);
1143 
1144 	watchdog_thresh_next = READ_ONCE(watchdog_thresh);
1145 
1146 	old = watchdog_thresh_next;
1147 	err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
1148 
1149 	if (!err && write && old != READ_ONCE(watchdog_thresh_next))
1150 		proc_watchdog_update(true);
1151 
1152 	mutex_unlock(&watchdog_mutex);
1153 	return err;
1154 }
1155 
1156 /*
1157  * The cpumask is the mask of possible cpus that the watchdog can run
1158  * on, not the mask of cpus it is actually running on.  This allows the
1159  * user to specify a mask that will include cpus that have not yet
1160  * been brought online, if desired.
1161  */
1162 static int proc_watchdog_cpumask(const struct ctl_table *table, int write,
1163 				 void *buffer, size_t *lenp, loff_t *ppos)
1164 {
1165 	int err;
1166 
1167 	mutex_lock(&watchdog_mutex);
1168 
1169 	err = proc_do_large_bitmap(table, write, buffer, lenp, ppos);
1170 	if (!err && write)
1171 		proc_watchdog_update(false);
1172 
1173 	mutex_unlock(&watchdog_mutex);
1174 	return err;
1175 }
1176 
1177 static const int sixty = 60;
1178 
1179 static const struct ctl_table watchdog_sysctls[] = {
1180 	{
1181 		.procname       = "watchdog",
1182 		.data		= &watchdog_user_enabled,
1183 		.maxlen		= sizeof(int),
1184 		.mode		= 0644,
1185 		.proc_handler   = proc_watchdog,
1186 		.extra1		= SYSCTL_ZERO,
1187 		.extra2		= SYSCTL_ONE,
1188 	},
1189 	{
1190 		.procname	= "watchdog_thresh",
1191 		.data		= &watchdog_thresh_next,
1192 		.maxlen		= sizeof(int),
1193 		.mode		= 0644,
1194 		.proc_handler	= proc_watchdog_thresh,
1195 		.extra1		= SYSCTL_ZERO,
1196 		.extra2		= (void *)&sixty,
1197 	},
1198 	{
1199 		.procname	= "watchdog_cpumask",
1200 		.data		= &watchdog_cpumask_bits,
1201 		.maxlen		= NR_CPUS,
1202 		.mode		= 0644,
1203 		.proc_handler	= proc_watchdog_cpumask,
1204 	},
1205 #ifdef CONFIG_SOFTLOCKUP_DETECTOR
1206 	{
1207 		.procname       = "soft_watchdog",
1208 		.data		= &watchdog_softlockup_user_enabled,
1209 		.maxlen		= sizeof(int),
1210 		.mode		= 0644,
1211 		.proc_handler   = proc_soft_watchdog,
1212 		.extra1		= SYSCTL_ZERO,
1213 		.extra2		= SYSCTL_ONE,
1214 	},
1215 	{
1216 		.procname	= "softlockup_panic",
1217 		.data		= &softlockup_panic,
1218 		.maxlen		= sizeof(int),
1219 		.mode		= 0644,
1220 		.proc_handler	= proc_dointvec_minmax,
1221 		.extra1		= SYSCTL_ZERO,
1222 		.extra2		= SYSCTL_ONE,
1223 	},
1224 	{
1225 		.procname	= "softlockup_sys_info",
1226 		.data		= &softlockup_si_mask,
1227 		.maxlen         = sizeof(softlockup_si_mask),
1228 		.mode		= 0644,
1229 		.proc_handler	= sysctl_sys_info_handler,
1230 	},
1231 #ifdef CONFIG_SMP
1232 	{
1233 		.procname	= "softlockup_all_cpu_backtrace",
1234 		.data		= &sysctl_softlockup_all_cpu_backtrace,
1235 		.maxlen		= sizeof(int),
1236 		.mode		= 0644,
1237 		.proc_handler	= proc_dointvec_minmax,
1238 		.extra1		= SYSCTL_ZERO,
1239 		.extra2		= SYSCTL_ONE,
1240 	},
1241 #endif /* CONFIG_SMP */
1242 #endif
1243 #ifdef CONFIG_HARDLOCKUP_DETECTOR
1244 	{
1245 		.procname	= "hardlockup_panic",
1246 		.data		= &hardlockup_panic,
1247 		.maxlen		= sizeof(int),
1248 		.mode		= 0644,
1249 		.proc_handler	= proc_dointvec_minmax,
1250 		.extra1		= SYSCTL_ZERO,
1251 		.extra2		= SYSCTL_ONE,
1252 	},
1253 	{
1254 		.procname	= "hardlockup_sys_info",
1255 		.data		= &hardlockup_si_mask,
1256 		.maxlen         = sizeof(hardlockup_si_mask),
1257 		.mode		= 0644,
1258 		.proc_handler	= sysctl_sys_info_handler,
1259 	},
1260 #ifdef CONFIG_SMP
1261 	{
1262 		.procname	= "hardlockup_all_cpu_backtrace",
1263 		.data		= &sysctl_hardlockup_all_cpu_backtrace,
1264 		.maxlen		= sizeof(int),
1265 		.mode		= 0644,
1266 		.proc_handler	= proc_dointvec_minmax,
1267 		.extra1		= SYSCTL_ZERO,
1268 		.extra2		= SYSCTL_ONE,
1269 	},
1270 #endif /* CONFIG_SMP */
1271 #endif
1272 };
1273 
1274 static struct ctl_table watchdog_hardlockup_sysctl[] = {
1275 	{
1276 		.procname       = "nmi_watchdog",
1277 		.data		= &watchdog_hardlockup_user_enabled,
1278 		.maxlen		= sizeof(int),
1279 		.mode		= 0444,
1280 		.proc_handler   = proc_nmi_watchdog,
1281 		.extra1		= SYSCTL_ZERO,
1282 		.extra2		= SYSCTL_ONE,
1283 	},
1284 };
1285 
1286 static void __init watchdog_sysctl_init(void)
1287 {
1288 	register_sysctl_init("kernel", watchdog_sysctls);
1289 
1290 	if (watchdog_hardlockup_available)
1291 		watchdog_hardlockup_sysctl[0].mode = 0644;
1292 	register_sysctl_init("kernel", watchdog_hardlockup_sysctl);
1293 }
1294 
1295 #else
1296 #define watchdog_sysctl_init() do { } while (0)
1297 #endif /* CONFIG_SYSCTL */
1298 
1299 static void __init lockup_detector_delay_init(struct work_struct *work);
1300 static bool allow_lockup_detector_init_retry __initdata;
1301 
1302 static struct work_struct detector_work __initdata =
1303 		__WORK_INITIALIZER(detector_work, lockup_detector_delay_init);
1304 
1305 static void __init lockup_detector_delay_init(struct work_struct *work)
1306 {
1307 	int ret;
1308 
1309 	ret = watchdog_hardlockup_probe();
1310 	if (ret) {
1311 		if (ret == -ENODEV)
1312 			pr_info("NMI not fully supported\n");
1313 		else
1314 			pr_info("Delayed init of the lockup detector failed: %d\n", ret);
1315 		pr_info("Hard watchdog permanently disabled\n");
1316 		return;
1317 	}
1318 
1319 	allow_lockup_detector_init_retry = false;
1320 
1321 	watchdog_hardlockup_available = true;
1322 	lockup_detector_setup();
1323 }
1324 
1325 /*
1326  * lockup_detector_retry_init - retry init lockup detector if possible.
1327  *
1328  * Retry hardlockup detector init. It is useful when it requires some
1329  * functionality that has to be initialized later on a particular
1330  * platform.
1331  */
1332 void __init lockup_detector_retry_init(void)
1333 {
1334 	/* Must be called before late init calls */
1335 	if (!allow_lockup_detector_init_retry)
1336 		return;
1337 
1338 	schedule_work(&detector_work);
1339 }
1340 
1341 /*
1342  * Ensure that optional delayed hardlockup init is proceed before
1343  * the init code and memory is freed.
1344  */
1345 static int __init lockup_detector_check(void)
1346 {
1347 	/* Prevent any later retry. */
1348 	allow_lockup_detector_init_retry = false;
1349 
1350 	/* Make sure no work is pending. */
1351 	flush_work(&detector_work);
1352 
1353 	watchdog_sysctl_init();
1354 
1355 	return 0;
1356 
1357 }
1358 late_initcall_sync(lockup_detector_check);
1359 
1360 void __init lockup_detector_init(void)
1361 {
1362 	if (tick_nohz_full_enabled())
1363 		pr_info("Disabling watchdog on nohz_full cores by default\n");
1364 
1365 	cpumask_copy(&watchdog_cpumask,
1366 		     housekeeping_cpumask(HK_TYPE_TIMER));
1367 
1368 	if (!watchdog_hardlockup_probe())
1369 		watchdog_hardlockup_available = true;
1370 	else
1371 		allow_lockup_detector_init_retry = true;
1372 
1373 	lockup_detector_setup();
1374 }
1375