1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Detect Hung Task
4  *
5  * kernel/hung_task.c - kernel thread for detecting tasks stuck in D state
6  *
7  */
8 
9 #include <linux/mm.h>
10 #include <linux/cpu.h>
11 #include <linux/nmi.h>
12 #include <linux/init.h>
13 #include <linux/delay.h>
14 #include <linux/freezer.h>
15 #include <linux/kthread.h>
16 #include <linux/lockdep.h>
17 #include <linux/export.h>
18 #include <linux/panic_notifier.h>
19 #include <linux/sysctl.h>
20 #include <linux/suspend.h>
21 #include <linux/utsname.h>
22 #include <linux/sched/signal.h>
23 #include <linux/sched/debug.h>
24 #include <linux/sched/sysctl.h>
25 
26 #include <trace/events/sched.h>
27 
28 /*
29  * The number of tasks checked:
30  */
31 static int __read_mostly sysctl_hung_task_check_count = PID_MAX_LIMIT;
32 
33 /*
34  * Total number of tasks detected as hung since boot:
35  */
36 static unsigned long __read_mostly sysctl_hung_task_detect_count;
37 
38 /*
39  * Limit number of tasks checked in a batch.
40  *
41  * This value controls the preemptibility of khungtaskd since preemption
42  * is disabled during the critical section. It also controls the size of
43  * the RCU grace period. So it needs to be upper-bound.
44  */
45 #define HUNG_TASK_LOCK_BREAK (HZ / 10)
46 
47 /*
48  * Zero means infinite timeout - no checking done:
49  */
50 unsigned long __read_mostly sysctl_hung_task_timeout_secs = CONFIG_DEFAULT_HUNG_TASK_TIMEOUT;
51 EXPORT_SYMBOL_GPL(sysctl_hung_task_timeout_secs);
52 
53 /*
54  * Zero (default value) means use sysctl_hung_task_timeout_secs:
55  */
56 static unsigned long __read_mostly sysctl_hung_task_check_interval_secs;
57 
58 static int __read_mostly sysctl_hung_task_warnings = 10;
59 
60 static int __read_mostly did_panic;
61 static bool hung_task_show_lock;
62 static bool hung_task_call_panic;
63 static bool hung_task_show_all_bt;
64 
65 static struct task_struct *watchdog_task;
66 
67 #ifdef CONFIG_SMP
68 /*
69  * Should we dump all CPUs backtraces in a hung task event?
70  * Defaults to 0, can be changed via sysctl.
71  */
72 static unsigned int __read_mostly sysctl_hung_task_all_cpu_backtrace;
73 #else
74 #define sysctl_hung_task_all_cpu_backtrace 0
75 #endif /* CONFIG_SMP */
76 
77 /*
78  * Should we panic (and reboot, if panic_timeout= is set) when a
79  * hung task is detected:
80  */
81 static unsigned int __read_mostly sysctl_hung_task_panic =
82 	IS_ENABLED(CONFIG_BOOTPARAM_HUNG_TASK_PANIC);
83 
84 static int
hung_task_panic(struct notifier_block * this,unsigned long event,void * ptr)85 hung_task_panic(struct notifier_block *this, unsigned long event, void *ptr)
86 {
87 	did_panic = 1;
88 
89 	return NOTIFY_DONE;
90 }
91 
92 static struct notifier_block panic_block = {
93 	.notifier_call = hung_task_panic,
94 };
95 
check_hung_task(struct task_struct * t,unsigned long timeout)96 static void check_hung_task(struct task_struct *t, unsigned long timeout)
97 {
98 	unsigned long switch_count = t->nvcsw + t->nivcsw;
99 
100 	/*
101 	 * Ensure the task is not frozen.
102 	 * Also, skip vfork and any other user process that freezer should skip.
103 	 */
104 	if (unlikely(READ_ONCE(t->__state) & TASK_FROZEN))
105 		return;
106 
107 	/*
108 	 * When a freshly created task is scheduled once, changes its state to
109 	 * TASK_UNINTERRUPTIBLE without having ever been switched out once, it
110 	 * musn't be checked.
111 	 */
112 	if (unlikely(!switch_count))
113 		return;
114 
115 	if (switch_count != t->last_switch_count) {
116 		t->last_switch_count = switch_count;
117 		t->last_switch_time = jiffies;
118 		return;
119 	}
120 	if (time_is_after_jiffies(t->last_switch_time + timeout * HZ))
121 		return;
122 
123 	/*
124 	 * This counter tracks the total number of tasks detected as hung
125 	 * since boot.
126 	 */
127 	sysctl_hung_task_detect_count++;
128 
129 	trace_sched_process_hang(t);
130 
131 	if (sysctl_hung_task_panic) {
132 		console_verbose();
133 		hung_task_show_lock = true;
134 		hung_task_call_panic = true;
135 	}
136 
137 	/*
138 	 * Ok, the task did not get scheduled for more than 2 minutes,
139 	 * complain:
140 	 */
141 	if (sysctl_hung_task_warnings || hung_task_call_panic) {
142 		if (sysctl_hung_task_warnings > 0)
143 			sysctl_hung_task_warnings--;
144 		pr_err("INFO: task %s:%d blocked for more than %ld seconds.\n",
145 		       t->comm, t->pid, (jiffies - t->last_switch_time) / HZ);
146 		pr_err("      %s %s %.*s\n",
147 			print_tainted(), init_utsname()->release,
148 			(int)strcspn(init_utsname()->version, " "),
149 			init_utsname()->version);
150 		if (t->flags & PF_POSTCOREDUMP)
151 			pr_err("      Blocked by coredump.\n");
152 		pr_err("\"echo 0 > /proc/sys/kernel/hung_task_timeout_secs\""
153 			" disables this message.\n");
154 		sched_show_task(t);
155 		hung_task_show_lock = true;
156 
157 		if (sysctl_hung_task_all_cpu_backtrace)
158 			hung_task_show_all_bt = true;
159 		if (!sysctl_hung_task_warnings)
160 			pr_info("Future hung task reports are suppressed, see sysctl kernel.hung_task_warnings\n");
161 	}
162 
163 	touch_nmi_watchdog();
164 }
165 
166 /*
167  * To avoid extending the RCU grace period for an unbounded amount of time,
168  * periodically exit the critical section and enter a new one.
169  *
170  * For preemptible RCU it is sufficient to call rcu_read_unlock in order
171  * to exit the grace period. For classic RCU, a reschedule is required.
172  */
rcu_lock_break(struct task_struct * g,struct task_struct * t)173 static bool rcu_lock_break(struct task_struct *g, struct task_struct *t)
174 {
175 	bool can_cont;
176 
177 	get_task_struct(g);
178 	get_task_struct(t);
179 	rcu_read_unlock();
180 	cond_resched();
181 	rcu_read_lock();
182 	can_cont = pid_alive(g) && pid_alive(t);
183 	put_task_struct(t);
184 	put_task_struct(g);
185 
186 	return can_cont;
187 }
188 
189 /*
190  * Check whether a TASK_UNINTERRUPTIBLE does not get woken up for
191  * a really long time (120 seconds). If that happens, print out
192  * a warning.
193  */
check_hung_uninterruptible_tasks(unsigned long timeout)194 static void check_hung_uninterruptible_tasks(unsigned long timeout)
195 {
196 	int max_count = sysctl_hung_task_check_count;
197 	unsigned long last_break = jiffies;
198 	struct task_struct *g, *t;
199 
200 	/*
201 	 * If the system crashed already then all bets are off,
202 	 * do not report extra hung tasks:
203 	 */
204 	if (test_taint(TAINT_DIE) || did_panic)
205 		return;
206 
207 	hung_task_show_lock = false;
208 	rcu_read_lock();
209 	for_each_process_thread(g, t) {
210 		unsigned int state;
211 
212 		if (!max_count--)
213 			goto unlock;
214 		if (time_after(jiffies, last_break + HUNG_TASK_LOCK_BREAK)) {
215 			if (!rcu_lock_break(g, t))
216 				goto unlock;
217 			last_break = jiffies;
218 		}
219 		/*
220 		 * skip the TASK_KILLABLE tasks -- these can be killed
221 		 * skip the TASK_IDLE tasks -- those are genuinely idle
222 		 */
223 		state = READ_ONCE(t->__state);
224 		if ((state & TASK_UNINTERRUPTIBLE) &&
225 		    !(state & TASK_WAKEKILL) &&
226 		    !(state & TASK_NOLOAD))
227 			check_hung_task(t, timeout);
228 	}
229  unlock:
230 	rcu_read_unlock();
231 	if (hung_task_show_lock)
232 		debug_show_all_locks();
233 
234 	if (hung_task_show_all_bt) {
235 		hung_task_show_all_bt = false;
236 		trigger_all_cpu_backtrace();
237 	}
238 
239 	if (hung_task_call_panic)
240 		panic("hung_task: blocked tasks");
241 }
242 
hung_timeout_jiffies(unsigned long last_checked,unsigned long timeout)243 static long hung_timeout_jiffies(unsigned long last_checked,
244 				 unsigned long timeout)
245 {
246 	/* timeout of 0 will disable the watchdog */
247 	return timeout ? last_checked - jiffies + timeout * HZ :
248 		MAX_SCHEDULE_TIMEOUT;
249 }
250 
251 #ifdef CONFIG_SYSCTL
252 /*
253  * Process updating of timeout sysctl
254  */
proc_dohung_task_timeout_secs(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)255 static int proc_dohung_task_timeout_secs(const struct ctl_table *table, int write,
256 				  void *buffer,
257 				  size_t *lenp, loff_t *ppos)
258 {
259 	int ret;
260 
261 	ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
262 
263 	if (ret || !write)
264 		goto out;
265 
266 	wake_up_process(watchdog_task);
267 
268  out:
269 	return ret;
270 }
271 
272 /*
273  * This is needed for proc_doulongvec_minmax of sysctl_hung_task_timeout_secs
274  * and hung_task_check_interval_secs
275  */
276 static const unsigned long hung_task_timeout_max = (LONG_MAX / HZ);
277 static const struct ctl_table hung_task_sysctls[] = {
278 #ifdef CONFIG_SMP
279 	{
280 		.procname	= "hung_task_all_cpu_backtrace",
281 		.data		= &sysctl_hung_task_all_cpu_backtrace,
282 		.maxlen		= sizeof(int),
283 		.mode		= 0644,
284 		.proc_handler	= proc_dointvec_minmax,
285 		.extra1		= SYSCTL_ZERO,
286 		.extra2		= SYSCTL_ONE,
287 	},
288 #endif /* CONFIG_SMP */
289 	{
290 		.procname	= "hung_task_panic",
291 		.data		= &sysctl_hung_task_panic,
292 		.maxlen		= sizeof(int),
293 		.mode		= 0644,
294 		.proc_handler	= proc_dointvec_minmax,
295 		.extra1		= SYSCTL_ZERO,
296 		.extra2		= SYSCTL_ONE,
297 	},
298 	{
299 		.procname	= "hung_task_check_count",
300 		.data		= &sysctl_hung_task_check_count,
301 		.maxlen		= sizeof(int),
302 		.mode		= 0644,
303 		.proc_handler	= proc_dointvec_minmax,
304 		.extra1		= SYSCTL_ZERO,
305 	},
306 	{
307 		.procname	= "hung_task_timeout_secs",
308 		.data		= &sysctl_hung_task_timeout_secs,
309 		.maxlen		= sizeof(unsigned long),
310 		.mode		= 0644,
311 		.proc_handler	= proc_dohung_task_timeout_secs,
312 		.extra2		= (void *)&hung_task_timeout_max,
313 	},
314 	{
315 		.procname	= "hung_task_check_interval_secs",
316 		.data		= &sysctl_hung_task_check_interval_secs,
317 		.maxlen		= sizeof(unsigned long),
318 		.mode		= 0644,
319 		.proc_handler	= proc_dohung_task_timeout_secs,
320 		.extra2		= (void *)&hung_task_timeout_max,
321 	},
322 	{
323 		.procname	= "hung_task_warnings",
324 		.data		= &sysctl_hung_task_warnings,
325 		.maxlen		= sizeof(int),
326 		.mode		= 0644,
327 		.proc_handler	= proc_dointvec_minmax,
328 		.extra1		= SYSCTL_NEG_ONE,
329 	},
330 	{
331 		.procname	= "hung_task_detect_count",
332 		.data		= &sysctl_hung_task_detect_count,
333 		.maxlen		= sizeof(unsigned long),
334 		.mode		= 0444,
335 		.proc_handler	= proc_doulongvec_minmax,
336 	},
337 };
338 
hung_task_sysctl_init(void)339 static void __init hung_task_sysctl_init(void)
340 {
341 	register_sysctl_init("kernel", hung_task_sysctls);
342 }
343 #else
344 #define hung_task_sysctl_init() do { } while (0)
345 #endif /* CONFIG_SYSCTL */
346 
347 
348 static atomic_t reset_hung_task = ATOMIC_INIT(0);
349 
reset_hung_task_detector(void)350 void reset_hung_task_detector(void)
351 {
352 	atomic_set(&reset_hung_task, 1);
353 }
354 EXPORT_SYMBOL_GPL(reset_hung_task_detector);
355 
356 static bool hung_detector_suspended;
357 
hungtask_pm_notify(struct notifier_block * self,unsigned long action,void * hcpu)358 static int hungtask_pm_notify(struct notifier_block *self,
359 			      unsigned long action, void *hcpu)
360 {
361 	switch (action) {
362 	case PM_SUSPEND_PREPARE:
363 	case PM_HIBERNATION_PREPARE:
364 	case PM_RESTORE_PREPARE:
365 		hung_detector_suspended = true;
366 		break;
367 	case PM_POST_SUSPEND:
368 	case PM_POST_HIBERNATION:
369 	case PM_POST_RESTORE:
370 		hung_detector_suspended = false;
371 		break;
372 	default:
373 		break;
374 	}
375 	return NOTIFY_OK;
376 }
377 
378 /*
379  * kthread which checks for tasks stuck in D state
380  */
watchdog(void * dummy)381 static int watchdog(void *dummy)
382 {
383 	unsigned long hung_last_checked = jiffies;
384 
385 	set_user_nice(current, 0);
386 
387 	for ( ; ; ) {
388 		unsigned long timeout = sysctl_hung_task_timeout_secs;
389 		unsigned long interval = sysctl_hung_task_check_interval_secs;
390 		long t;
391 
392 		if (interval == 0)
393 			interval = timeout;
394 		interval = min_t(unsigned long, interval, timeout);
395 		t = hung_timeout_jiffies(hung_last_checked, interval);
396 		if (t <= 0) {
397 			if (!atomic_xchg(&reset_hung_task, 0) &&
398 			    !hung_detector_suspended)
399 				check_hung_uninterruptible_tasks(timeout);
400 			hung_last_checked = jiffies;
401 			continue;
402 		}
403 		schedule_timeout_interruptible(t);
404 	}
405 
406 	return 0;
407 }
408 
hung_task_init(void)409 static int __init hung_task_init(void)
410 {
411 	atomic_notifier_chain_register(&panic_notifier_list, &panic_block);
412 
413 	/* Disable hung task detector on suspend */
414 	pm_notifier(hungtask_pm_notify, 0);
415 
416 	watchdog_task = kthread_run(watchdog, NULL, "khungtaskd");
417 	hung_task_sysctl_init();
418 
419 	return 0;
420 }
421 subsys_initcall(hung_task_init);
422