1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Detect hard lockups on a system using perf
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) "NMI watchdog: " fmt
14 
15 #include <linux/nmi.h>
16 #include <linux/atomic.h>
17 #include <linux/module.h>
18 #include <linux/sched/debug.h>
19 
20 #include <asm/irq_regs.h>
21 #include <linux/perf_event.h>
22 
23 static DEFINE_PER_CPU(struct perf_event *, watchdog_ev);
24 
25 static atomic_t watchdog_cpus = ATOMIC_INIT(0);
26 
27 #ifdef CONFIG_HARDLOCKUP_CHECK_TIMESTAMP
28 static DEFINE_PER_CPU(ktime_t, last_timestamp);
29 static DEFINE_PER_CPU(unsigned int, nmi_rearmed);
30 static ktime_t watchdog_hrtimer_sample_threshold __read_mostly;
31 
watchdog_update_hrtimer_threshold(u64 period)32 void watchdog_update_hrtimer_threshold(u64 period)
33 {
34 	/*
35 	 * The hrtimer runs with a period of (watchdog_threshold * 2) / 5
36 	 *
37 	 * So it runs effectively with 2.5 times the rate of the NMI
38 	 * watchdog. That means the hrtimer should fire 2-3 times before
39 	 * the NMI watchdog expires. The NMI watchdog on x86 is based on
40 	 * unhalted CPU cycles, so if Turbo-Mode is enabled the CPU cycles
41 	 * might run way faster than expected and the NMI fires in a
42 	 * smaller period than the one deduced from the nominal CPU
43 	 * frequency. Depending on the Turbo-Mode factor this might be fast
44 	 * enough to get the NMI period smaller than the hrtimer watchdog
45 	 * period and trigger false positives.
46 	 *
47 	 * The sample threshold is used to check in the NMI handler whether
48 	 * the minimum time between two NMI samples has elapsed. That
49 	 * prevents false positives.
50 	 *
51 	 * Set this to 4/5 of the actual watchdog threshold period so the
52 	 * hrtimer is guaranteed to fire at least once within the real
53 	 * watchdog threshold.
54 	 */
55 	watchdog_hrtimer_sample_threshold = period * 2;
56 }
57 
watchdog_check_timestamp(void)58 static bool watchdog_check_timestamp(void)
59 {
60 	ktime_t delta, now = ktime_get_mono_fast_ns();
61 
62 	delta = now - __this_cpu_read(last_timestamp);
63 	if (delta < watchdog_hrtimer_sample_threshold) {
64 		/*
65 		 * If ktime is jiffies based, a stalled timer would prevent
66 		 * jiffies from being incremented and the filter would look
67 		 * at a stale timestamp and never trigger.
68 		 */
69 		if (__this_cpu_inc_return(nmi_rearmed) < 10)
70 			return false;
71 	}
72 	__this_cpu_write(nmi_rearmed, 0);
73 	__this_cpu_write(last_timestamp, now);
74 	return true;
75 }
76 
watchdog_init_timestamp(void)77 static void watchdog_init_timestamp(void)
78 {
79 	__this_cpu_write(nmi_rearmed, 0);
80 	__this_cpu_write(last_timestamp, ktime_get_mono_fast_ns());
81 }
82 #else
watchdog_check_timestamp(void)83 static inline bool watchdog_check_timestamp(void) { return true; }
watchdog_init_timestamp(void)84 static inline void watchdog_init_timestamp(void) { }
85 #endif
86 
87 static struct perf_event_attr wd_hw_attr = {
88 	.type		= PERF_TYPE_HARDWARE,
89 	.config		= PERF_COUNT_HW_CPU_CYCLES,
90 	.size		= sizeof(struct perf_event_attr),
91 	.pinned		= 1,
92 	.disabled	= 1,
93 };
94 
95 static struct perf_event_attr fallback_wd_hw_attr = {
96 	.type		= PERF_TYPE_HARDWARE,
97 	.config		= PERF_COUNT_HW_CPU_CYCLES,
98 	.size		= sizeof(struct perf_event_attr),
99 	.pinned		= 1,
100 	.disabled	= 1,
101 };
102 
103 /* Callback function for perf event subsystem */
watchdog_overflow_callback(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)104 static void watchdog_overflow_callback(struct perf_event *event,
105 				       struct perf_sample_data *data,
106 				       struct pt_regs *regs)
107 {
108 	/* Ensure the watchdog never gets throttled */
109 	event->hw.interrupts = 0;
110 
111 	if (!watchdog_check_timestamp())
112 		return;
113 
114 	watchdog_hardlockup_check(smp_processor_id(), regs);
115 }
116 
hardlockup_detector_event_create(void)117 static int hardlockup_detector_event_create(void)
118 {
119 	unsigned int cpu;
120 	struct perf_event_attr *wd_attr;
121 	struct perf_event *evt;
122 
123 	/*
124 	 * Preemption is not disabled because memory will be allocated.
125 	 * Ensure CPU-locality by calling this in per-CPU kthread.
126 	 */
127 	WARN_ON(!is_percpu_thread());
128 	cpu = raw_smp_processor_id();
129 	wd_attr = &wd_hw_attr;
130 	wd_attr->sample_period = hw_nmi_get_sample_period(watchdog_thresh);
131 
132 	/* Try to register using hardware perf events */
133 	evt = perf_event_create_kernel_counter(wd_attr, cpu, NULL,
134 					       watchdog_overflow_callback, NULL);
135 	if (IS_ERR(evt)) {
136 		wd_attr = &fallback_wd_hw_attr;
137 		wd_attr->sample_period = hw_nmi_get_sample_period(watchdog_thresh);
138 		evt = perf_event_create_kernel_counter(wd_attr, cpu, NULL,
139 						       watchdog_overflow_callback, NULL);
140 	}
141 
142 	if (IS_ERR(evt)) {
143 		pr_debug("Perf event create on CPU %d failed with %ld\n", cpu,
144 			 PTR_ERR(evt));
145 		return PTR_ERR(evt);
146 	}
147 	this_cpu_write(watchdog_ev, evt);
148 	return 0;
149 }
150 
151 /**
152  * watchdog_hardlockup_enable - Enable the local event
153  * @cpu: The CPU to enable hard lockup on.
154  */
watchdog_hardlockup_enable(unsigned int cpu)155 void watchdog_hardlockup_enable(unsigned int cpu)
156 {
157 	WARN_ON_ONCE(cpu != smp_processor_id());
158 
159 	if (hardlockup_detector_event_create())
160 		return;
161 
162 	/* use original value for check */
163 	if (!atomic_fetch_inc(&watchdog_cpus))
164 		pr_info("Enabled. Permanently consumes one hw-PMU counter.\n");
165 
166 	watchdog_init_timestamp();
167 	perf_event_enable(this_cpu_read(watchdog_ev));
168 }
169 
170 /**
171  * watchdog_hardlockup_disable - Disable the local event
172  * @cpu: The CPU to enable hard lockup on.
173  */
watchdog_hardlockup_disable(unsigned int cpu)174 void watchdog_hardlockup_disable(unsigned int cpu)
175 {
176 	struct perf_event *event = this_cpu_read(watchdog_ev);
177 
178 	WARN_ON_ONCE(cpu != smp_processor_id());
179 
180 	if (event) {
181 		perf_event_disable(event);
182 		perf_event_release_kernel(event);
183 		this_cpu_write(watchdog_ev, NULL);
184 		atomic_dec(&watchdog_cpus);
185 	}
186 }
187 
188 /**
189  * hardlockup_detector_perf_stop - Globally stop watchdog events
190  *
191  * Special interface for x86 to handle the perf HT bug.
192  */
hardlockup_detector_perf_stop(void)193 void __init hardlockup_detector_perf_stop(void)
194 {
195 	int cpu;
196 
197 	lockdep_assert_cpus_held();
198 
199 	for_each_online_cpu(cpu) {
200 		struct perf_event *event = per_cpu(watchdog_ev, cpu);
201 
202 		if (event)
203 			perf_event_disable(event);
204 	}
205 }
206 
207 /**
208  * hardlockup_detector_perf_restart - Globally restart watchdog events
209  *
210  * Special interface for x86 to handle the perf HT bug.
211  */
hardlockup_detector_perf_restart(void)212 void __init hardlockup_detector_perf_restart(void)
213 {
214 	int cpu;
215 
216 	lockdep_assert_cpus_held();
217 
218 	if (!(watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED))
219 		return;
220 
221 	for_each_online_cpu(cpu) {
222 		struct perf_event *event = per_cpu(watchdog_ev, cpu);
223 
224 		if (event)
225 			perf_event_enable(event);
226 	}
227 }
228 
arch_perf_nmi_is_available(void)229 bool __weak __init arch_perf_nmi_is_available(void)
230 {
231 	return true;
232 }
233 
234 /**
235  * watchdog_hardlockup_probe - Probe whether NMI event is available at all
236  */
watchdog_hardlockup_probe(void)237 int __init watchdog_hardlockup_probe(void)
238 {
239 	int ret;
240 
241 	if (!arch_perf_nmi_is_available())
242 		return -ENODEV;
243 
244 	ret = hardlockup_detector_event_create();
245 
246 	if (ret) {
247 		pr_info("Perf NMI watchdog permanently disabled\n");
248 	} else {
249 		perf_event_release_kernel(this_cpu_read(watchdog_ev));
250 		this_cpu_write(watchdog_ev, NULL);
251 	}
252 	return ret;
253 }
254 
255 /**
256  * hardlockup_config_perf_event - Overwrite config of wd_hw_attr.
257  * @str: number which identifies the raw perf event to use
258  */
hardlockup_config_perf_event(const char * str)259 void __init hardlockup_config_perf_event(const char *str)
260 {
261 	u64 config;
262 	char buf[24];
263 	char *comma = strchr(str, ',');
264 
265 	if (!comma) {
266 		if (kstrtoull(str, 16, &config))
267 			return;
268 	} else {
269 		unsigned int len = comma - str;
270 
271 		if (len >= sizeof(buf))
272 			return;
273 
274 		if (strscpy(buf, str, sizeof(buf)) < 0)
275 			return;
276 		buf[len] = 0;
277 		if (kstrtoull(buf, 16, &config))
278 			return;
279 	}
280 
281 	wd_hw_attr.type = PERF_TYPE_RAW;
282 	wd_hw_attr.config = config;
283 }
284