• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/mm.h>
16 #include <linux/cpu.h>
17 #include <linux/device.h>
18 #include <linux/nmi.h>
19 #include <linux/init.h>
20 #include <linux/module.h>
21 #include <linux/sysctl.h>
22 #include <linux/tick.h>
23 #include <linux/sched/clock.h>
24 #include <linux/sched/debug.h>
25 #include <linux/sched/isolation.h>
26 #include <linux/stop_machine.h>
27 
28 #include <asm/irq_regs.h>
29 #include <linux/kvm_para.h>
30 
31 static DEFINE_MUTEX(watchdog_mutex);
32 
33 #if defined(CONFIG_HARDLOCKUP_DETECTOR) || defined(CONFIG_HARDLOCKUP_DETECTOR_SPARC64)
34 # define WATCHDOG_HARDLOCKUP_DEFAULT	1
35 #else
36 # define WATCHDOG_HARDLOCKUP_DEFAULT	0
37 #endif
38 
39 unsigned long __read_mostly watchdog_enabled;
40 int __read_mostly watchdog_user_enabled = 1;
41 static int __read_mostly watchdog_hardlockup_user_enabled = WATCHDOG_HARDLOCKUP_DEFAULT;
42 static int __read_mostly watchdog_softlockup_user_enabled = 1;
43 int __read_mostly watchdog_thresh = 10;
44 static int __read_mostly watchdog_thresh_next;
45 static int __read_mostly watchdog_hardlockup_available;
46 
47 struct cpumask watchdog_cpumask __read_mostly;
48 unsigned long *watchdog_cpumask_bits = cpumask_bits(&watchdog_cpumask);
49 
50 #ifdef CONFIG_HARDLOCKUP_DETECTOR
51 
52 # ifdef CONFIG_SMP
53 int __read_mostly sysctl_hardlockup_all_cpu_backtrace;
54 # endif /* CONFIG_SMP */
55 
56 /*
57  * Should we panic when a soft-lockup or hard-lockup occurs:
58  */
59 unsigned int __read_mostly hardlockup_panic =
60 			IS_ENABLED(CONFIG_BOOTPARAM_HARDLOCKUP_PANIC);
61 /*
62  * We may not want to enable hard lockup detection by default in all cases,
63  * for example when running the kernel as a guest on a hypervisor. In these
64  * cases this function can be called to disable hard lockup detection. This
65  * function should only be executed once by the boot processor before the
66  * kernel command line parameters are parsed, because otherwise it is not
67  * possible to override this in hardlockup_panic_setup().
68  */
hardlockup_detector_disable(void)69 void __init hardlockup_detector_disable(void)
70 {
71 	watchdog_hardlockup_user_enabled = 0;
72 }
73 
hardlockup_panic_setup(char * str)74 static int __init hardlockup_panic_setup(char *str)
75 {
76 	if (!strncmp(str, "panic", 5))
77 		hardlockup_panic = 1;
78 	else if (!strncmp(str, "nopanic", 7))
79 		hardlockup_panic = 0;
80 	else if (!strncmp(str, "0", 1))
81 		watchdog_hardlockup_user_enabled = 0;
82 	else if (!strncmp(str, "1", 1))
83 		watchdog_hardlockup_user_enabled = 1;
84 	return 1;
85 }
86 __setup("nmi_watchdog=", hardlockup_panic_setup);
87 
88 #endif /* CONFIG_HARDLOCKUP_DETECTOR */
89 
90 #if defined(CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER)
91 
92 static DEFINE_PER_CPU(atomic_t, hrtimer_interrupts);
93 static DEFINE_PER_CPU(int, hrtimer_interrupts_saved);
94 static DEFINE_PER_CPU(bool, watchdog_hardlockup_warned);
95 static DEFINE_PER_CPU(bool, watchdog_hardlockup_touched);
96 static unsigned long watchdog_hardlockup_all_cpu_dumped;
97 
arch_touch_nmi_watchdog(void)98 notrace void arch_touch_nmi_watchdog(void)
99 {
100 	/*
101 	 * Using __raw here because some code paths have
102 	 * preemption enabled.  If preemption is enabled
103 	 * then interrupts should be enabled too, in which
104 	 * case we shouldn't have to worry about the watchdog
105 	 * going off.
106 	 */
107 	raw_cpu_write(watchdog_hardlockup_touched, true);
108 }
109 EXPORT_SYMBOL(arch_touch_nmi_watchdog);
110 
watchdog_hardlockup_touch_cpu(unsigned int cpu)111 void watchdog_hardlockup_touch_cpu(unsigned int cpu)
112 {
113 	per_cpu(watchdog_hardlockup_touched, cpu) = true;
114 }
115 
is_hardlockup(unsigned int cpu)116 static bool is_hardlockup(unsigned int cpu)
117 {
118 	int hrint = atomic_read(&per_cpu(hrtimer_interrupts, cpu));
119 
120 	if (per_cpu(hrtimer_interrupts_saved, cpu) == hrint)
121 		return true;
122 
123 	/*
124 	 * NOTE: we don't need any fancy atomic_t or READ_ONCE/WRITE_ONCE
125 	 * for hrtimer_interrupts_saved. hrtimer_interrupts_saved is
126 	 * written/read by a single CPU.
127 	 */
128 	per_cpu(hrtimer_interrupts_saved, cpu) = hrint;
129 
130 	return false;
131 }
132 
watchdog_hardlockup_kick(void)133 static void watchdog_hardlockup_kick(void)
134 {
135 	int new_interrupts;
136 
137 	new_interrupts = atomic_inc_return(this_cpu_ptr(&hrtimer_interrupts));
138 	watchdog_buddy_check_hardlockup(new_interrupts);
139 }
140 
watchdog_hardlockup_check(unsigned int cpu,struct pt_regs * regs)141 void watchdog_hardlockup_check(unsigned int cpu, struct pt_regs *regs)
142 {
143 	if (per_cpu(watchdog_hardlockup_touched, cpu)) {
144 		per_cpu(watchdog_hardlockup_touched, cpu) = false;
145 		return;
146 	}
147 
148 	/*
149 	 * Check for a hardlockup by making sure the CPU's timer
150 	 * interrupt is incrementing. The timer interrupt should have
151 	 * fired multiple times before we overflow'd. If it hasn't
152 	 * then this is a good indication the cpu is stuck
153 	 */
154 	if (is_hardlockup(cpu)) {
155 		unsigned int this_cpu = smp_processor_id();
156 
157 		/* Only print hardlockups once. */
158 		if (per_cpu(watchdog_hardlockup_warned, cpu))
159 			return;
160 
161 		pr_emerg("Watchdog detected hard LOCKUP on cpu %d\n", cpu);
162 		print_modules();
163 		print_irqtrace_events(current);
164 		if (cpu == this_cpu) {
165 			if (regs)
166 				show_regs(regs);
167 			else
168 				dump_stack();
169 		} else {
170 			trigger_single_cpu_backtrace(cpu);
171 		}
172 
173 		/*
174 		 * Perform multi-CPU dump only once to avoid multiple
175 		 * hardlockups generating interleaving traces
176 		 */
177 		if (sysctl_hardlockup_all_cpu_backtrace &&
178 		    !test_and_set_bit(0, &watchdog_hardlockup_all_cpu_dumped))
179 			trigger_allbutcpu_cpu_backtrace(cpu);
180 
181 		if (hardlockup_panic)
182 			nmi_panic(regs, "Hard LOCKUP");
183 
184 		per_cpu(watchdog_hardlockup_warned, cpu) = true;
185 	} else {
186 		per_cpu(watchdog_hardlockup_warned, cpu) = false;
187 	}
188 }
189 
190 #else /* CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER */
191 
watchdog_hardlockup_kick(void)192 static inline void watchdog_hardlockup_kick(void) { }
193 
194 #endif /* !CONFIG_HARDLOCKUP_DETECTOR_COUNTS_HRTIMER */
195 
196 /*
197  * These functions can be overridden based on the configured hardlockdup detector.
198  *
199  * watchdog_hardlockup_enable/disable can be implemented to start and stop when
200  * softlockup watchdog start and stop. The detector must select the
201  * SOFTLOCKUP_DETECTOR Kconfig.
202  */
watchdog_hardlockup_enable(unsigned int cpu)203 void __weak watchdog_hardlockup_enable(unsigned int cpu) { }
204 
watchdog_hardlockup_disable(unsigned int cpu)205 void __weak watchdog_hardlockup_disable(unsigned int cpu) { }
206 
207 /*
208  * Watchdog-detector specific API.
209  *
210  * Return 0 when hardlockup watchdog is available, negative value otherwise.
211  * Note that the negative value means that a delayed probe might
212  * succeed later.
213  */
watchdog_hardlockup_probe(void)214 int __weak __init watchdog_hardlockup_probe(void)
215 {
216 	return -ENODEV;
217 }
218 
219 /**
220  * watchdog_hardlockup_stop - Stop the watchdog for reconfiguration
221  *
222  * The reconfiguration steps are:
223  * watchdog_hardlockup_stop();
224  * update_variables();
225  * watchdog_hardlockup_start();
226  */
watchdog_hardlockup_stop(void)227 void __weak watchdog_hardlockup_stop(void) { }
228 
229 /**
230  * watchdog_hardlockup_start - Start the watchdog after reconfiguration
231  *
232  * Counterpart to watchdog_hardlockup_stop().
233  *
234  * The following variables have been updated in update_variables() and
235  * contain the currently valid configuration:
236  * - watchdog_enabled
237  * - watchdog_thresh
238  * - watchdog_cpumask
239  */
watchdog_hardlockup_start(void)240 void __weak watchdog_hardlockup_start(void) { }
241 
242 /**
243  * lockup_detector_update_enable - Update the sysctl enable bit
244  *
245  * Caller needs to make sure that the hard watchdogs are off, so this
246  * can't race with watchdog_hardlockup_disable().
247  */
lockup_detector_update_enable(void)248 static void lockup_detector_update_enable(void)
249 {
250 	watchdog_enabled = 0;
251 	if (!watchdog_user_enabled)
252 		return;
253 	if (watchdog_hardlockup_available && watchdog_hardlockup_user_enabled)
254 		watchdog_enabled |= WATCHDOG_HARDLOCKUP_ENABLED;
255 	if (watchdog_softlockup_user_enabled)
256 		watchdog_enabled |= WATCHDOG_SOFTOCKUP_ENABLED;
257 }
258 
259 #ifdef CONFIG_SOFTLOCKUP_DETECTOR
260 
261 /*
262  * Delay the soflockup report when running a known slow code.
263  * It does _not_ affect the timestamp of the last successdul reschedule.
264  */
265 #define SOFTLOCKUP_DELAY_REPORT	ULONG_MAX
266 
267 #ifdef CONFIG_SMP
268 int __read_mostly sysctl_softlockup_all_cpu_backtrace;
269 #endif
270 
271 static struct cpumask watchdog_allowed_mask __read_mostly;
272 
273 /* Global variables, exported for sysctl */
274 unsigned int __read_mostly softlockup_panic =
275 			IS_ENABLED(CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC);
276 
277 static bool softlockup_initialized __read_mostly;
278 static u64 __read_mostly sample_period;
279 
280 /* Timestamp taken after the last successful reschedule. */
281 static DEFINE_PER_CPU(unsigned long, watchdog_touch_ts);
282 /* Timestamp of the last softlockup report. */
283 static DEFINE_PER_CPU(unsigned long, watchdog_report_ts);
284 static DEFINE_PER_CPU(struct hrtimer, watchdog_hrtimer);
285 static DEFINE_PER_CPU(bool, softlockup_touch_sync);
286 static unsigned long soft_lockup_nmi_warn;
287 
softlockup_panic_setup(char * str)288 static int __init softlockup_panic_setup(char *str)
289 {
290 	softlockup_panic = simple_strtoul(str, NULL, 0);
291 	return 1;
292 }
293 __setup("softlockup_panic=", softlockup_panic_setup);
294 
nowatchdog_setup(char * str)295 static int __init nowatchdog_setup(char *str)
296 {
297 	watchdog_user_enabled = 0;
298 	return 1;
299 }
300 __setup("nowatchdog", nowatchdog_setup);
301 
nosoftlockup_setup(char * str)302 static int __init nosoftlockup_setup(char *str)
303 {
304 	watchdog_softlockup_user_enabled = 0;
305 	return 1;
306 }
307 __setup("nosoftlockup", nosoftlockup_setup);
308 
watchdog_thresh_setup(char * str)309 static int __init watchdog_thresh_setup(char *str)
310 {
311 	get_option(&str, &watchdog_thresh);
312 	return 1;
313 }
314 __setup("watchdog_thresh=", watchdog_thresh_setup);
315 
316 static void __lockup_detector_cleanup(void);
317 
318 /*
319  * Hard-lockup warnings should be triggered after just a few seconds. Soft-
320  * lockups can have false positives under extreme conditions. So we generally
321  * want a higher threshold for soft lockups than for hard lockups. So we couple
322  * the thresholds with a factor: we make the soft threshold twice the amount of
323  * time the hard threshold is.
324  */
get_softlockup_thresh(void)325 static int get_softlockup_thresh(void)
326 {
327 	return watchdog_thresh * 2;
328 }
329 
330 /*
331  * Returns seconds, approximately.  We don't need nanosecond
332  * resolution, and we don't need to waste time with a big divide when
333  * 2^30ns == 1.074s.
334  */
get_timestamp(void)335 static unsigned long get_timestamp(void)
336 {
337 	return running_clock() >> 30LL;  /* 2^30 ~= 10^9 */
338 }
339 
set_sample_period(void)340 static void set_sample_period(void)
341 {
342 	/*
343 	 * convert watchdog_thresh from seconds to ns
344 	 * the divide by 5 is to give hrtimer several chances (two
345 	 * or three with the current relation between the soft
346 	 * and hard thresholds) to increment before the
347 	 * hardlockup detector generates a warning
348 	 */
349 	sample_period = get_softlockup_thresh() * ((u64)NSEC_PER_SEC / 5);
350 	watchdog_update_hrtimer_threshold(sample_period);
351 }
352 
update_report_ts(void)353 static void update_report_ts(void)
354 {
355 	__this_cpu_write(watchdog_report_ts, get_timestamp());
356 }
357 
358 /* Commands for resetting the watchdog */
update_touch_ts(void)359 static void update_touch_ts(void)
360 {
361 	__this_cpu_write(watchdog_touch_ts, get_timestamp());
362 	update_report_ts();
363 }
364 
365 /**
366  * touch_softlockup_watchdog_sched - touch watchdog on scheduler stalls
367  *
368  * Call when the scheduler may have stalled for legitimate reasons
369  * preventing the watchdog task from executing - e.g. the scheduler
370  * entering idle state.  This should only be used for scheduler events.
371  * Use touch_softlockup_watchdog() for everything else.
372  */
touch_softlockup_watchdog_sched(void)373 notrace void touch_softlockup_watchdog_sched(void)
374 {
375 	/*
376 	 * Preemption can be enabled.  It doesn't matter which CPU's watchdog
377 	 * report period gets restarted here, so use the raw_ operation.
378 	 */
379 	raw_cpu_write(watchdog_report_ts, SOFTLOCKUP_DELAY_REPORT);
380 }
381 
touch_softlockup_watchdog(void)382 notrace void touch_softlockup_watchdog(void)
383 {
384 	touch_softlockup_watchdog_sched();
385 	wq_watchdog_touch(raw_smp_processor_id());
386 }
387 EXPORT_SYMBOL(touch_softlockup_watchdog);
388 
touch_all_softlockup_watchdogs(void)389 void touch_all_softlockup_watchdogs(void)
390 {
391 	int cpu;
392 
393 	/*
394 	 * watchdog_mutex cannpt be taken here, as this might be called
395 	 * from (soft)interrupt context, so the access to
396 	 * watchdog_allowed_cpumask might race with a concurrent update.
397 	 *
398 	 * The watchdog time stamp can race against a concurrent real
399 	 * update as well, the only side effect might be a cycle delay for
400 	 * the softlockup check.
401 	 */
402 	for_each_cpu(cpu, &watchdog_allowed_mask) {
403 		per_cpu(watchdog_report_ts, cpu) = SOFTLOCKUP_DELAY_REPORT;
404 		wq_watchdog_touch(cpu);
405 	}
406 }
407 
touch_softlockup_watchdog_sync(void)408 void touch_softlockup_watchdog_sync(void)
409 {
410 	__this_cpu_write(softlockup_touch_sync, true);
411 	__this_cpu_write(watchdog_report_ts, SOFTLOCKUP_DELAY_REPORT);
412 }
413 
is_softlockup(unsigned long touch_ts,unsigned long period_ts,unsigned long now)414 static int is_softlockup(unsigned long touch_ts,
415 			 unsigned long period_ts,
416 			 unsigned long now)
417 {
418 	if ((watchdog_enabled & WATCHDOG_SOFTOCKUP_ENABLED) && watchdog_thresh) {
419 		/* Warn about unreasonable delays. */
420 		if (time_after(now, period_ts + get_softlockup_thresh()))
421 			return now - touch_ts;
422 	}
423 	return 0;
424 }
425 
426 /* watchdog detector functions */
427 static DEFINE_PER_CPU(struct completion, softlockup_completion);
428 static DEFINE_PER_CPU(struct cpu_stop_work, softlockup_stop_work);
429 
430 /*
431  * The watchdog feed function - touches the timestamp.
432  *
433  * It only runs once every sample_period seconds (4 seconds by
434  * default) to reset the softlockup timestamp. If this gets delayed
435  * for more than 2*watchdog_thresh seconds then the debug-printout
436  * triggers in watchdog_timer_fn().
437  */
softlockup_fn(void * data)438 static int softlockup_fn(void *data)
439 {
440 	update_touch_ts();
441 	complete(this_cpu_ptr(&softlockup_completion));
442 
443 	return 0;
444 }
445 
446 /* watchdog kicker functions */
watchdog_timer_fn(struct hrtimer * hrtimer)447 static enum hrtimer_restart watchdog_timer_fn(struct hrtimer *hrtimer)
448 {
449 	unsigned long touch_ts, period_ts, now;
450 	struct pt_regs *regs = get_irq_regs();
451 	int duration;
452 	int softlockup_all_cpu_backtrace = sysctl_softlockup_all_cpu_backtrace;
453 
454 	if (!watchdog_enabled)
455 		return HRTIMER_NORESTART;
456 
457 	watchdog_hardlockup_kick();
458 
459 	/* kick the softlockup detector */
460 	if (completion_done(this_cpu_ptr(&softlockup_completion))) {
461 		reinit_completion(this_cpu_ptr(&softlockup_completion));
462 		stop_one_cpu_nowait(smp_processor_id(),
463 				softlockup_fn, NULL,
464 				this_cpu_ptr(&softlockup_stop_work));
465 	}
466 
467 	/* .. and repeat */
468 	hrtimer_forward_now(hrtimer, ns_to_ktime(sample_period));
469 
470 	/*
471 	 * Read the current timestamp first. It might become invalid anytime
472 	 * when a virtual machine is stopped by the host or when the watchog
473 	 * is touched from NMI.
474 	 */
475 	now = get_timestamp();
476 	/*
477 	 * If a virtual machine is stopped by the host it can look to
478 	 * the watchdog like a soft lockup. This function touches the watchdog.
479 	 */
480 	kvm_check_and_clear_guest_paused();
481 	/*
482 	 * The stored timestamp is comparable with @now only when not touched.
483 	 * It might get touched anytime from NMI. Make sure that is_softlockup()
484 	 * uses the same (valid) value.
485 	 */
486 	period_ts = READ_ONCE(*this_cpu_ptr(&watchdog_report_ts));
487 
488 	/* Reset the interval when touched by known problematic code. */
489 	if (period_ts == SOFTLOCKUP_DELAY_REPORT) {
490 		if (unlikely(__this_cpu_read(softlockup_touch_sync))) {
491 			/*
492 			 * If the time stamp was touched atomically
493 			 * make sure the scheduler tick is up to date.
494 			 */
495 			__this_cpu_write(softlockup_touch_sync, false);
496 			sched_clock_tick();
497 		}
498 
499 		update_report_ts();
500 		return HRTIMER_RESTART;
501 	}
502 
503 	/* Check for a softlockup. */
504 	touch_ts = __this_cpu_read(watchdog_touch_ts);
505 	duration = is_softlockup(touch_ts, period_ts, now);
506 	if (unlikely(duration)) {
507 		/*
508 		 * Prevent multiple soft-lockup reports if one cpu is already
509 		 * engaged in dumping all cpu back traces.
510 		 */
511 		if (softlockup_all_cpu_backtrace) {
512 			if (test_and_set_bit_lock(0, &soft_lockup_nmi_warn))
513 				return HRTIMER_RESTART;
514 		}
515 
516 		/* Start period for the next softlockup warning. */
517 		update_report_ts();
518 
519 		pr_emerg("BUG: soft lockup - CPU#%d stuck for %us! [%s:%d]\n",
520 			smp_processor_id(), duration,
521 			current->comm, task_pid_nr(current));
522 		print_modules();
523 		print_irqtrace_events(current);
524 		if (regs)
525 			show_regs(regs);
526 		else
527 			dump_stack();
528 
529 		if (softlockup_all_cpu_backtrace) {
530 			trigger_allbutcpu_cpu_backtrace(smp_processor_id());
531 			clear_bit_unlock(0, &soft_lockup_nmi_warn);
532 		}
533 
534 		add_taint(TAINT_SOFTLOCKUP, LOCKDEP_STILL_OK);
535 		if (softlockup_panic)
536 			panic("softlockup: hung tasks");
537 	}
538 
539 	return HRTIMER_RESTART;
540 }
541 
watchdog_enable(unsigned int cpu)542 void watchdog_enable(unsigned int cpu)
543 {
544 	struct hrtimer *hrtimer = this_cpu_ptr(&watchdog_hrtimer);
545 	struct completion *done = this_cpu_ptr(&softlockup_completion);
546 	unsigned int *enabled = this_cpu_ptr(&watchdog_en);
547 
548 	WARN_ON_ONCE(cpu != smp_processor_id());
549 
550 	init_completion(done);
551 	complete(done);
552 
553 	if (*enabled)
554 		return;
555 
556 	/*
557 	 * Start the timer first to prevent the hardlockup watchdog triggering
558 	 * before the timer has a chance to fire.
559 	 */
560 	hrtimer_init(hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
561 	hrtimer->function = watchdog_timer_fn;
562 	hrtimer_start(hrtimer, ns_to_ktime(sample_period),
563 		      HRTIMER_MODE_REL_PINNED_HARD);
564 
565 	/* Initialize timestamp */
566 	update_touch_ts();
567 	/* Enable the hardlockup detector */
568 	if (watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED)
569 		watchdog_hardlockup_enable(cpu);
570 
571 	/*
572 	 * Need to ensure above operations are observed by other CPUs before
573 	 * indicating that timer is enabled. This is to synchronize core
574 	 * isolation and hotplug. Core isolation will wait for this flag to be
575 	 * set.
576 	 */
577 	mb();
578 	*enabled = 1;
579 }
580 
watchdog_disable(unsigned int cpu)581 void watchdog_disable(unsigned int cpu)
582 {
583 	struct hrtimer *hrtimer = per_cpu_ptr(&watchdog_hrtimer, cpu);
584 	unsigned int *enabled = per_cpu_ptr(&watchdog_en, cpu);
585 
586 	if (!*enabled)
587 		return;
588 
589 	WARN_ON_ONCE(cpu != smp_processor_id());
590 
591 	/*
592 	 * Disable the hardlockup detector first. That prevents that a large
593 	 * delay between disabling the timer and disabling the hardlockup
594 	 * detector causes a false positive.
595 	 */
596 	watchdog_hardlockup_disable(cpu);
597 	hrtimer_cancel(hrtimer);
598 	wait_for_completion(per_cpu_ptr(&softlockup_completion, cpu));
599 
600 	/*
601 	 * No need for barrier here since disabling the watchdog is
602 	 * synchronized with hotplug lock
603 	 */
604 	*enabled = 0;
605 }
606 
watchdog_configured(unsigned int cpu)607 bool watchdog_configured(unsigned int cpu)
608 {
609 	return *per_cpu_ptr(&watchdog_en, cpu);
610 }
611 
softlockup_stop_fn(void * data)612 static int softlockup_stop_fn(void *data)
613 {
614 	watchdog_disable(smp_processor_id());
615 	return 0;
616 }
617 
softlockup_stop_all(void)618 static void softlockup_stop_all(void)
619 {
620 	int cpu;
621 
622 	if (!softlockup_initialized)
623 		return;
624 
625 	for_each_cpu(cpu, &watchdog_allowed_mask)
626 		smp_call_on_cpu(cpu, softlockup_stop_fn, NULL, false);
627 
628 	cpumask_clear(&watchdog_allowed_mask);
629 }
630 
softlockup_start_fn(void * data)631 static int softlockup_start_fn(void *data)
632 {
633 	watchdog_enable(smp_processor_id());
634 	return 0;
635 }
636 
softlockup_start_all(void)637 static void softlockup_start_all(void)
638 {
639 	int cpu;
640 
641 	cpumask_copy(&watchdog_allowed_mask, &watchdog_cpumask);
642 	for_each_cpu(cpu, &watchdog_allowed_mask)
643 		smp_call_on_cpu(cpu, softlockup_start_fn, NULL, false);
644 }
645 
lockup_detector_online_cpu(unsigned int cpu)646 int lockup_detector_online_cpu(unsigned int cpu)
647 {
648 	if (cpumask_test_cpu(cpu, &watchdog_allowed_mask))
649 		watchdog_enable(cpu);
650 	return 0;
651 }
652 
lockup_detector_offline_cpu(unsigned int cpu)653 int lockup_detector_offline_cpu(unsigned int cpu)
654 {
655 	if (cpumask_test_cpu(cpu, &watchdog_allowed_mask))
656 		watchdog_disable(cpu);
657 	return 0;
658 }
659 
__lockup_detector_reconfigure(bool thresh_changed)660 static void __lockup_detector_reconfigure(bool thresh_changed)
661 {
662 	cpus_read_lock();
663 	watchdog_hardlockup_stop();
664 
665 	softlockup_stop_all();
666 	/*
667 	 * To prevent watchdog_timer_fn from using the old interval and
668 	 * the new watchdog_thresh at the same time, which could lead to
669 	 * false softlockup reports, it is necessary to update the
670 	 * watchdog_thresh after the softlockup is completed.
671 	 */
672 	if (thresh_changed)
673 		watchdog_thresh = READ_ONCE(watchdog_thresh_next);
674 	set_sample_period();
675 	lockup_detector_update_enable();
676 	if (watchdog_enabled && watchdog_thresh)
677 		softlockup_start_all();
678 
679 	watchdog_hardlockup_start();
680 	cpus_read_unlock();
681 	/*
682 	 * Must be called outside the cpus locked section to prevent
683 	 * recursive locking in the perf code.
684 	 */
685 	__lockup_detector_cleanup();
686 }
687 
lockup_detector_reconfigure(void)688 void lockup_detector_reconfigure(void)
689 {
690 	mutex_lock(&watchdog_mutex);
691 	__lockup_detector_reconfigure(false);
692 	mutex_unlock(&watchdog_mutex);
693 }
694 
695 /*
696  * Create the watchdog infrastructure and configure the detector(s).
697  */
lockup_detector_setup(void)698 static __init void lockup_detector_setup(void)
699 {
700 	/*
701 	 * If sysctl is off and watchdog got disabled on the command line,
702 	 * nothing to do here.
703 	 */
704 	lockup_detector_update_enable();
705 
706 	if (!IS_ENABLED(CONFIG_SYSCTL) &&
707 	    !(watchdog_enabled && watchdog_thresh))
708 		return;
709 
710 	mutex_lock(&watchdog_mutex);
711 	__lockup_detector_reconfigure(false);
712 	softlockup_initialized = true;
713 	mutex_unlock(&watchdog_mutex);
714 }
715 
716 #else /* CONFIG_SOFTLOCKUP_DETECTOR */
__lockup_detector_reconfigure(bool thresh_changed)717 static void __lockup_detector_reconfigure(bool thresh_changed)
718 {
719 	cpus_read_lock();
720 	watchdog_hardlockup_stop();
721 	if (thresh_changed)
722 		watchdog_thresh = READ_ONCE(watchdog_thresh_next);
723 	lockup_detector_update_enable();
724 	watchdog_hardlockup_start();
725 	cpus_read_unlock();
726 }
lockup_detector_reconfigure(void)727 void lockup_detector_reconfigure(void)
728 {
729 	__lockup_detector_reconfigure(false);
730 }
lockup_detector_setup(void)731 static inline void lockup_detector_setup(void)
732 {
733 	__lockup_detector_reconfigure(false);
734 }
735 #endif /* !CONFIG_SOFTLOCKUP_DETECTOR */
736 
__lockup_detector_cleanup(void)737 static void __lockup_detector_cleanup(void)
738 {
739 	lockdep_assert_held(&watchdog_mutex);
740 	hardlockup_detector_perf_cleanup();
741 }
742 
743 /**
744  * lockup_detector_cleanup - Cleanup after cpu hotplug or sysctl changes
745  *
746  * Caller must not hold the cpu hotplug rwsem.
747  */
lockup_detector_cleanup(void)748 void lockup_detector_cleanup(void)
749 {
750 	mutex_lock(&watchdog_mutex);
751 	__lockup_detector_cleanup();
752 	mutex_unlock(&watchdog_mutex);
753 }
754 
755 /**
756  * lockup_detector_soft_poweroff - Interface to stop lockup detector(s)
757  *
758  * Special interface for parisc. It prevents lockup detector warnings from
759  * the default pm_poweroff() function which busy loops forever.
760  */
lockup_detector_soft_poweroff(void)761 void lockup_detector_soft_poweroff(void)
762 {
763 	watchdog_enabled = 0;
764 }
765 
766 #ifdef CONFIG_SYSCTL
767 
768 /* Propagate any changes to the watchdog infrastructure */
proc_watchdog_update(bool thresh_changed)769 static void proc_watchdog_update(bool thresh_changed)
770 {
771 	/* Remove impossible cpus to keep sysctl output clean. */
772 	cpumask_and(&watchdog_cpumask, &watchdog_cpumask, cpu_possible_mask);
773 	__lockup_detector_reconfigure(thresh_changed);
774 }
775 
776 /*
777  * common function for watchdog, nmi_watchdog and soft_watchdog parameter
778  *
779  * caller             | table->data points to            | 'which'
780  * -------------------|----------------------------------|-------------------------------
781  * proc_watchdog      | watchdog_user_enabled            | WATCHDOG_HARDLOCKUP_ENABLED |
782  *                    |                                  | WATCHDOG_SOFTOCKUP_ENABLED
783  * -------------------|----------------------------------|-------------------------------
784  * proc_nmi_watchdog  | watchdog_hardlockup_user_enabled | WATCHDOG_HARDLOCKUP_ENABLED
785  * -------------------|----------------------------------|-------------------------------
786  * proc_soft_watchdog | watchdog_softlockup_user_enabled | WATCHDOG_SOFTOCKUP_ENABLED
787  */
proc_watchdog_common(int which,struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)788 static int proc_watchdog_common(int which, struct ctl_table *table, int write,
789 				void *buffer, size_t *lenp, loff_t *ppos)
790 {
791 	int err, old, *param = table->data;
792 
793 	mutex_lock(&watchdog_mutex);
794 
795 	if (!write) {
796 		/*
797 		 * On read synchronize the userspace interface. This is a
798 		 * racy snapshot.
799 		 */
800 		*param = (watchdog_enabled & which) != 0;
801 		err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
802 	} else {
803 		old = READ_ONCE(*param);
804 		err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
805 		if (!err && old != READ_ONCE(*param))
806 			proc_watchdog_update(false);
807 	}
808 	mutex_unlock(&watchdog_mutex);
809 	return err;
810 }
811 
812 /*
813  * /proc/sys/kernel/watchdog
814  */
proc_watchdog(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)815 int proc_watchdog(struct ctl_table *table, int write,
816 		  void *buffer, size_t *lenp, loff_t *ppos)
817 {
818 	return proc_watchdog_common(WATCHDOG_HARDLOCKUP_ENABLED |
819 				    WATCHDOG_SOFTOCKUP_ENABLED,
820 				    table, write, buffer, lenp, ppos);
821 }
822 
823 /*
824  * /proc/sys/kernel/nmi_watchdog
825  */
proc_nmi_watchdog(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)826 int proc_nmi_watchdog(struct ctl_table *table, int write,
827 		      void *buffer, size_t *lenp, loff_t *ppos)
828 {
829 	if (!watchdog_hardlockup_available && write)
830 		return -ENOTSUPP;
831 	return proc_watchdog_common(WATCHDOG_HARDLOCKUP_ENABLED,
832 				    table, write, buffer, lenp, ppos);
833 }
834 
835 /*
836  * /proc/sys/kernel/soft_watchdog
837  */
proc_soft_watchdog(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)838 int proc_soft_watchdog(struct ctl_table *table, int write,
839 			void *buffer, size_t *lenp, loff_t *ppos)
840 {
841 	return proc_watchdog_common(WATCHDOG_SOFTOCKUP_ENABLED,
842 				    table, write, buffer, lenp, ppos);
843 }
844 
845 /*
846  * /proc/sys/kernel/watchdog_thresh
847  */
proc_watchdog_thresh(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)848 int proc_watchdog_thresh(struct ctl_table *table, int write,
849 			 void *buffer, size_t *lenp, loff_t *ppos)
850 {
851 	int err, old;
852 
853 	mutex_lock(&watchdog_mutex);
854 
855 	watchdog_thresh_next = READ_ONCE(watchdog_thresh);
856 
857 	old = watchdog_thresh_next;
858 	err = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
859 
860 	if (!err && write && old != READ_ONCE(watchdog_thresh_next))
861 		proc_watchdog_update(true);
862 
863 	mutex_unlock(&watchdog_mutex);
864 	return err;
865 }
866 
867 /*
868  * The cpumask is the mask of possible cpus that the watchdog can run
869  * on, not the mask of cpus it is actually running on.  This allows the
870  * user to specify a mask that will include cpus that have not yet
871  * been brought online, if desired.
872  */
proc_watchdog_cpumask(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)873 int proc_watchdog_cpumask(struct ctl_table *table, int write,
874 			  void *buffer, size_t *lenp, loff_t *ppos)
875 {
876 	int err;
877 
878 	mutex_lock(&watchdog_mutex);
879 
880 	err = proc_do_large_bitmap(table, write, buffer, lenp, ppos);
881 	if (!err && write)
882 		proc_watchdog_update(false);
883 
884 	mutex_unlock(&watchdog_mutex);
885 	return err;
886 }
887 
888 static const int sixty = 60;
889 
890 static struct ctl_table watchdog_sysctls[] = {
891 	{
892 		.procname       = "watchdog",
893 		.data		= &watchdog_user_enabled,
894 		.maxlen		= sizeof(int),
895 		.mode		= 0644,
896 		.proc_handler   = proc_watchdog,
897 		.extra1		= SYSCTL_ZERO,
898 		.extra2		= SYSCTL_ONE,
899 	},
900 	{
901 		.procname	= "watchdog_thresh",
902 		.data		= &watchdog_thresh_next,
903 		.maxlen		= sizeof(int),
904 		.mode		= 0644,
905 		.proc_handler	= proc_watchdog_thresh,
906 		.extra1		= SYSCTL_ZERO,
907 		.extra2		= (void *)&sixty,
908 	},
909 	{
910 		.procname	= "watchdog_cpumask",
911 		.data		= &watchdog_cpumask_bits,
912 		.maxlen		= NR_CPUS,
913 		.mode		= 0644,
914 		.proc_handler	= proc_watchdog_cpumask,
915 	},
916 #ifdef CONFIG_SOFTLOCKUP_DETECTOR
917 	{
918 		.procname       = "soft_watchdog",
919 		.data		= &watchdog_softlockup_user_enabled,
920 		.maxlen		= sizeof(int),
921 		.mode		= 0644,
922 		.proc_handler   = proc_soft_watchdog,
923 		.extra1		= SYSCTL_ZERO,
924 		.extra2		= SYSCTL_ONE,
925 	},
926 	{
927 		.procname	= "softlockup_panic",
928 		.data		= &softlockup_panic,
929 		.maxlen		= sizeof(int),
930 		.mode		= 0644,
931 		.proc_handler	= proc_dointvec_minmax,
932 		.extra1		= SYSCTL_ZERO,
933 		.extra2		= SYSCTL_ONE,
934 	},
935 #ifdef CONFIG_SMP
936 	{
937 		.procname	= "softlockup_all_cpu_backtrace",
938 		.data		= &sysctl_softlockup_all_cpu_backtrace,
939 		.maxlen		= sizeof(int),
940 		.mode		= 0644,
941 		.proc_handler	= proc_dointvec_minmax,
942 		.extra1		= SYSCTL_ZERO,
943 		.extra2		= SYSCTL_ONE,
944 	},
945 #endif /* CONFIG_SMP */
946 #endif
947 #ifdef CONFIG_HARDLOCKUP_DETECTOR
948 	{
949 		.procname	= "hardlockup_panic",
950 		.data		= &hardlockup_panic,
951 		.maxlen		= sizeof(int),
952 		.mode		= 0644,
953 		.proc_handler	= proc_dointvec_minmax,
954 		.extra1		= SYSCTL_ZERO,
955 		.extra2		= SYSCTL_ONE,
956 	},
957 #ifdef CONFIG_SMP
958 	{
959 		.procname	= "hardlockup_all_cpu_backtrace",
960 		.data		= &sysctl_hardlockup_all_cpu_backtrace,
961 		.maxlen		= sizeof(int),
962 		.mode		= 0644,
963 		.proc_handler	= proc_dointvec_minmax,
964 		.extra1		= SYSCTL_ZERO,
965 		.extra2		= SYSCTL_ONE,
966 	},
967 #endif /* CONFIG_SMP */
968 #endif
969 	{}
970 };
971 
972 static struct ctl_table watchdog_hardlockup_sysctl[] = {
973 	{
974 		.procname       = "nmi_watchdog",
975 		.data		= &watchdog_hardlockup_user_enabled,
976 		.maxlen		= sizeof(int),
977 		.mode		= 0444,
978 		.proc_handler   = proc_nmi_watchdog,
979 		.extra1		= SYSCTL_ZERO,
980 		.extra2		= SYSCTL_ONE,
981 	},
982 	{}
983 };
984 
watchdog_sysctl_init(void)985 static void __init watchdog_sysctl_init(void)
986 {
987 	register_sysctl_init("kernel", watchdog_sysctls);
988 
989 	if (watchdog_hardlockup_available)
990 		watchdog_hardlockup_sysctl[0].mode = 0644;
991 	register_sysctl_init("kernel", watchdog_hardlockup_sysctl);
992 }
993 
994 #else
995 #define watchdog_sysctl_init() do { } while (0)
996 #endif /* CONFIG_SYSCTL */
997 
998 static void __init lockup_detector_delay_init(struct work_struct *work);
999 static bool allow_lockup_detector_init_retry __initdata;
1000 
1001 static struct work_struct detector_work __initdata =
1002 		__WORK_INITIALIZER(detector_work, lockup_detector_delay_init);
1003 
lockup_detector_delay_init(struct work_struct * work)1004 static void __init lockup_detector_delay_init(struct work_struct *work)
1005 {
1006 	int ret;
1007 
1008 	ret = watchdog_hardlockup_probe();
1009 	if (ret) {
1010 		pr_info("Delayed init of the lockup detector failed: %d\n", ret);
1011 		pr_info("Hard watchdog permanently disabled\n");
1012 		return;
1013 	}
1014 
1015 	allow_lockup_detector_init_retry = false;
1016 
1017 	watchdog_hardlockup_available = true;
1018 	lockup_detector_setup();
1019 }
1020 
1021 /*
1022  * lockup_detector_retry_init - retry init lockup detector if possible.
1023  *
1024  * Retry hardlockup detector init. It is useful when it requires some
1025  * functionality that has to be initialized later on a particular
1026  * platform.
1027  */
lockup_detector_retry_init(void)1028 void __init lockup_detector_retry_init(void)
1029 {
1030 	/* Must be called before late init calls */
1031 	if (!allow_lockup_detector_init_retry)
1032 		return;
1033 
1034 	schedule_work(&detector_work);
1035 }
1036 
1037 /*
1038  * Ensure that optional delayed hardlockup init is proceed before
1039  * the init code and memory is freed.
1040  */
lockup_detector_check(void)1041 static int __init lockup_detector_check(void)
1042 {
1043 	/* Prevent any later retry. */
1044 	allow_lockup_detector_init_retry = false;
1045 
1046 	/* Make sure no work is pending. */
1047 	flush_work(&detector_work);
1048 
1049 	watchdog_sysctl_init();
1050 
1051 	return 0;
1052 
1053 }
1054 late_initcall_sync(lockup_detector_check);
1055 
lockup_detector_init(void)1056 void __init lockup_detector_init(void)
1057 {
1058 	if (tick_nohz_full_enabled())
1059 		pr_info("Disabling watchdog on nohz_full cores by default\n");
1060 
1061 	cpumask_copy(&watchdog_cpumask,
1062 		     housekeeping_cpumask(HK_TYPE_TIMER));
1063 
1064 	if (!watchdog_hardlockup_probe())
1065 		watchdog_hardlockup_available = true;
1066 	else
1067 		allow_lockup_detector_init_retry = true;
1068 
1069 	lockup_detector_setup();
1070 }
1071