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