xref: /openbmc/linux/kernel/trace/trace_hwlat.c (revision 0330f7aa8ee63d0c435c0cb4e47ea06235ee4b7f)
1 /*
2  * trace_hwlatdetect.c - A simple Hardware Latency detector.
3  *
4  * Use this tracer to detect large system latencies induced by the behavior of
5  * certain underlying system hardware or firmware, independent of Linux itself.
6  * The code was developed originally to detect the presence of SMIs on Intel
7  * and AMD systems, although there is no dependency upon x86 herein.
8  *
9  * The classical example usage of this tracer is in detecting the presence of
10  * SMIs or System Management Interrupts on Intel and AMD systems. An SMI is a
11  * somewhat special form of hardware interrupt spawned from earlier CPU debug
12  * modes in which the (BIOS/EFI/etc.) firmware arranges for the South Bridge
13  * LPC (or other device) to generate a special interrupt under certain
14  * circumstances, for example, upon expiration of a special SMI timer device,
15  * due to certain external thermal readings, on certain I/O address accesses,
16  * and other situations. An SMI hits a special CPU pin, triggers a special
17  * SMI mode (complete with special memory map), and the OS is unaware.
18  *
19  * Although certain hardware-inducing latencies are necessary (for example,
20  * a modern system often requires an SMI handler for correct thermal control
21  * and remote management) they can wreak havoc upon any OS-level performance
22  * guarantees toward low-latency, especially when the OS is not even made
23  * aware of the presence of these interrupts. For this reason, we need a
24  * somewhat brute force mechanism to detect these interrupts. In this case,
25  * we do it by hogging all of the CPU(s) for configurable timer intervals,
26  * sampling the built-in CPU timer, looking for discontiguous readings.
27  *
28  * WARNING: This implementation necessarily introduces latencies. Therefore,
29  *          you should NEVER use this tracer while running in a production
30  *          environment requiring any kind of low-latency performance
31  *          guarantee(s).
32  *
33  * Copyright (C) 2008-2009 Jon Masters, Red Hat, Inc. <jcm@redhat.com>
34  * Copyright (C) 2013-2016 Steven Rostedt, Red Hat, Inc. <srostedt@redhat.com>
35  *
36  * Includes useful feedback from Clark Williams <clark@redhat.com>
37  *
38  * This file is licensed under the terms of the GNU General Public
39  * License version 2. This program is licensed "as is" without any
40  * warranty of any kind, whether express or implied.
41  */
42 #include <linux/kthread.h>
43 #include <linux/tracefs.h>
44 #include <linux/uaccess.h>
45 #include <linux/cpumask.h>
46 #include <linux/delay.h>
47 #include "trace.h"
48 
49 static struct trace_array	*hwlat_trace;
50 
51 #define U64STR_SIZE		22			/* 20 digits max */
52 
53 #define BANNER			"hwlat_detector: "
54 #define DEFAULT_SAMPLE_WINDOW	1000000			/* 1s */
55 #define DEFAULT_SAMPLE_WIDTH	500000			/* 0.5s */
56 #define DEFAULT_LAT_THRESHOLD	10			/* 10us */
57 
58 /* sampling thread*/
59 static struct task_struct *hwlat_kthread;
60 
61 static struct dentry *hwlat_sample_width;	/* sample width us */
62 static struct dentry *hwlat_sample_window;	/* sample window us */
63 
64 /* Save the previous tracing_thresh value */
65 static unsigned long save_tracing_thresh;
66 
67 /* If the user changed threshold, remember it */
68 static u64 last_tracing_thresh = DEFAULT_LAT_THRESHOLD * NSEC_PER_USEC;
69 
70 /* Individual latency samples are stored here when detected. */
71 struct hwlat_sample {
72 	u64		seqnum;		/* unique sequence */
73 	u64		duration;	/* delta */
74 	u64		outer_duration;	/* delta (outer loop) */
75 	struct timespec	timestamp;	/* wall time */
76 };
77 
78 /* keep the global state somewhere. */
79 static struct hwlat_data {
80 
81 	struct mutex lock;		/* protect changes */
82 
83 	u64	count;			/* total since reset */
84 
85 	u64	sample_window;		/* total sampling window (on+off) */
86 	u64	sample_width;		/* active sampling portion of window */
87 
88 } hwlat_data = {
89 	.sample_window		= DEFAULT_SAMPLE_WINDOW,
90 	.sample_width		= DEFAULT_SAMPLE_WIDTH,
91 };
92 
93 static void trace_hwlat_sample(struct hwlat_sample *sample)
94 {
95 	struct trace_array *tr = hwlat_trace;
96 	struct trace_event_call *call = &event_hwlat;
97 	struct ring_buffer *buffer = tr->trace_buffer.buffer;
98 	struct ring_buffer_event *event;
99 	struct hwlat_entry *entry;
100 	unsigned long flags;
101 	int pc;
102 
103 	pc = preempt_count();
104 	local_save_flags(flags);
105 
106 	event = trace_buffer_lock_reserve(buffer, TRACE_HWLAT, sizeof(*entry),
107 					  flags, pc);
108 	if (!event)
109 		return;
110 	entry	= ring_buffer_event_data(event);
111 	entry->seqnum			= sample->seqnum;
112 	entry->duration			= sample->duration;
113 	entry->outer_duration		= sample->outer_duration;
114 	entry->timestamp		= sample->timestamp;
115 
116 	if (!call_filter_check_discard(call, entry, buffer, event))
117 		__buffer_unlock_commit(buffer, event);
118 }
119 
120 /* Macros to encapsulate the time capturing infrastructure */
121 #define time_type	u64
122 #define time_get()	trace_clock_local()
123 #define time_to_us(x)	div_u64(x, 1000)
124 #define time_sub(a, b)	((a) - (b))
125 #define init_time(a, b)	(a = b)
126 #define time_u64(a)	a
127 
128 /**
129  * get_sample - sample the CPU TSC and look for likely hardware latencies
130  *
131  * Used to repeatedly capture the CPU TSC (or similar), looking for potential
132  * hardware-induced latency. Called with interrupts disabled and with
133  * hwlat_data.lock held.
134  */
135 static int get_sample(void)
136 {
137 	struct trace_array *tr = hwlat_trace;
138 	time_type start, t1, t2, last_t2;
139 	s64 diff, total, last_total = 0;
140 	u64 sample = 0;
141 	u64 thresh = tracing_thresh;
142 	u64 outer_sample = 0;
143 	int ret = -1;
144 
145 	do_div(thresh, NSEC_PER_USEC); /* modifies interval value */
146 
147 	init_time(last_t2, 0);
148 	start = time_get(); /* start timestamp */
149 
150 	do {
151 
152 		t1 = time_get();	/* we'll look for a discontinuity */
153 		t2 = time_get();
154 
155 		if (time_u64(last_t2)) {
156 			/* Check the delta from outer loop (t2 to next t1) */
157 			diff = time_to_us(time_sub(t1, last_t2));
158 			/* This shouldn't happen */
159 			if (diff < 0) {
160 				pr_err(BANNER "time running backwards\n");
161 				goto out;
162 			}
163 			if (diff > outer_sample)
164 				outer_sample = diff;
165 		}
166 		last_t2 = t2;
167 
168 		total = time_to_us(time_sub(t2, start)); /* sample width */
169 
170 		/* Check for possible overflows */
171 		if (total < last_total) {
172 			pr_err("Time total overflowed\n");
173 			break;
174 		}
175 		last_total = total;
176 
177 		/* This checks the inner loop (t1 to t2) */
178 		diff = time_to_us(time_sub(t2, t1));     /* current diff */
179 
180 		/* This shouldn't happen */
181 		if (diff < 0) {
182 			pr_err(BANNER "time running backwards\n");
183 			goto out;
184 		}
185 
186 		if (diff > sample)
187 			sample = diff; /* only want highest value */
188 
189 	} while (total <= hwlat_data.sample_width);
190 
191 	ret = 0;
192 
193 	/* If we exceed the threshold value, we have found a hardware latency */
194 	if (sample > thresh || outer_sample > thresh) {
195 		struct hwlat_sample s;
196 
197 		ret = 1;
198 
199 		hwlat_data.count++;
200 		s.seqnum = hwlat_data.count;
201 		s.duration = sample;
202 		s.outer_duration = outer_sample;
203 		s.timestamp = CURRENT_TIME;
204 		trace_hwlat_sample(&s);
205 
206 		/* Keep a running maximum ever recorded hardware latency */
207 		if (sample > tr->max_latency)
208 			tr->max_latency = sample;
209 	}
210 
211 out:
212 	return ret;
213 }
214 
215 static struct cpumask save_cpumask;
216 static bool disable_migrate;
217 
218 static void move_to_next_cpu(void)
219 {
220 	static struct cpumask *current_mask;
221 	int next_cpu;
222 
223 	if (disable_migrate)
224 		return;
225 
226 	/* Just pick the first CPU on first iteration */
227 	if (!current_mask) {
228 		current_mask = &save_cpumask;
229 		get_online_cpus();
230 		cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
231 		put_online_cpus();
232 		next_cpu = cpumask_first(current_mask);
233 		goto set_affinity;
234 	}
235 
236 	/*
237 	 * If for some reason the user modifies the CPU affinity
238 	 * of this thread, than stop migrating for the duration
239 	 * of the current test.
240 	 */
241 	if (!cpumask_equal(current_mask, &current->cpus_allowed))
242 		goto disable;
243 
244 	get_online_cpus();
245 	cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
246 	next_cpu = cpumask_next(smp_processor_id(), current_mask);
247 	put_online_cpus();
248 
249 	if (next_cpu >= nr_cpu_ids)
250 		next_cpu = cpumask_first(current_mask);
251 
252  set_affinity:
253 	if (next_cpu >= nr_cpu_ids) /* Shouldn't happen! */
254 		goto disable;
255 
256 	cpumask_clear(current_mask);
257 	cpumask_set_cpu(next_cpu, current_mask);
258 
259 	sched_setaffinity(0, current_mask);
260 	return;
261 
262  disable:
263 	disable_migrate = true;
264 }
265 
266 /*
267  * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
268  *
269  * Used to periodically sample the CPU TSC via a call to get_sample. We
270  * disable interrupts, which does (intentionally) introduce latency since we
271  * need to ensure nothing else might be running (and thus preempting).
272  * Obviously this should never be used in production environments.
273  *
274  * Currently this runs on which ever CPU it was scheduled on, but most
275  * real-world hardware latency situations occur across several CPUs,
276  * but we might later generalize this if we find there are any actualy
277  * systems with alternate SMI delivery or other hardware latencies.
278  */
279 static int kthread_fn(void *data)
280 {
281 	u64 interval;
282 
283 	while (!kthread_should_stop()) {
284 
285 		move_to_next_cpu();
286 
287 		local_irq_disable();
288 		get_sample();
289 		local_irq_enable();
290 
291 		mutex_lock(&hwlat_data.lock);
292 		interval = hwlat_data.sample_window - hwlat_data.sample_width;
293 		mutex_unlock(&hwlat_data.lock);
294 
295 		do_div(interval, USEC_PER_MSEC); /* modifies interval value */
296 
297 		/* Always sleep for at least 1ms */
298 		if (interval < 1)
299 			interval = 1;
300 
301 		if (msleep_interruptible(interval))
302 			break;
303 	}
304 
305 	return 0;
306 }
307 
308 /**
309  * start_kthread - Kick off the hardware latency sampling/detector kthread
310  *
311  * This starts the kernel thread that will sit and sample the CPU timestamp
312  * counter (TSC or similar) and look for potential hardware latencies.
313  */
314 static int start_kthread(struct trace_array *tr)
315 {
316 	struct task_struct *kthread;
317 
318 	kthread = kthread_create(kthread_fn, NULL, "hwlatd");
319 	if (IS_ERR(kthread)) {
320 		pr_err(BANNER "could not start sampling thread\n");
321 		return -ENOMEM;
322 	}
323 	hwlat_kthread = kthread;
324 	wake_up_process(kthread);
325 
326 	return 0;
327 }
328 
329 /**
330  * stop_kthread - Inform the hardware latency samping/detector kthread to stop
331  *
332  * This kicks the running hardware latency sampling/detector kernel thread and
333  * tells it to stop sampling now. Use this on unload and at system shutdown.
334  */
335 static void stop_kthread(void)
336 {
337 	if (!hwlat_kthread)
338 		return;
339 	kthread_stop(hwlat_kthread);
340 	hwlat_kthread = NULL;
341 }
342 
343 /*
344  * hwlat_read - Wrapper read function for reading both window and width
345  * @filp: The active open file structure
346  * @ubuf: The userspace provided buffer to read value into
347  * @cnt: The maximum number of bytes to read
348  * @ppos: The current "file" position
349  *
350  * This function provides a generic read implementation for the global state
351  * "hwlat_data" structure filesystem entries.
352  */
353 static ssize_t hwlat_read(struct file *filp, char __user *ubuf,
354 			  size_t cnt, loff_t *ppos)
355 {
356 	char buf[U64STR_SIZE];
357 	u64 *entry = filp->private_data;
358 	u64 val;
359 	int len;
360 
361 	if (!entry)
362 		return -EFAULT;
363 
364 	if (cnt > sizeof(buf))
365 		cnt = sizeof(buf);
366 
367 	val = *entry;
368 
369 	len = snprintf(buf, sizeof(buf), "%llu\n", val);
370 
371 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
372 }
373 
374 /**
375  * hwlat_width_write - Write function for "width" entry
376  * @filp: The active open file structure
377  * @ubuf: The user buffer that contains the value to write
378  * @cnt: The maximum number of bytes to write to "file"
379  * @ppos: The current position in @file
380  *
381  * This function provides a write implementation for the "width" interface
382  * to the hardware latency detector. It can be used to configure
383  * for how many us of the total window us we will actively sample for any
384  * hardware-induced latency periods. Obviously, it is not possible to
385  * sample constantly and have the system respond to a sample reader, or,
386  * worse, without having the system appear to have gone out to lunch. It
387  * is enforced that width is less that the total window size.
388  */
389 static ssize_t
390 hwlat_width_write(struct file *filp, const char __user *ubuf,
391 		  size_t cnt, loff_t *ppos)
392 {
393 	u64 val;
394 	int err;
395 
396 	err = kstrtoull_from_user(ubuf, cnt, 10, &val);
397 	if (err)
398 		return err;
399 
400 	mutex_lock(&hwlat_data.lock);
401 	if (val < hwlat_data.sample_window)
402 		hwlat_data.sample_width = val;
403 	else
404 		err = -EINVAL;
405 	mutex_unlock(&hwlat_data.lock);
406 
407 	if (err)
408 		return err;
409 
410 	return cnt;
411 }
412 
413 /**
414  * hwlat_window_write - Write function for "window" entry
415  * @filp: The active open file structure
416  * @ubuf: The user buffer that contains the value to write
417  * @cnt: The maximum number of bytes to write to "file"
418  * @ppos: The current position in @file
419  *
420  * This function provides a write implementation for the "window" interface
421  * to the hardware latency detetector. The window is the total time
422  * in us that will be considered one sample period. Conceptually, windows
423  * occur back-to-back and contain a sample width period during which
424  * actual sampling occurs. Can be used to write a new total window size. It
425  * is enfoced that any value written must be greater than the sample width
426  * size, or an error results.
427  */
428 static ssize_t
429 hwlat_window_write(struct file *filp, const char __user *ubuf,
430 		   size_t cnt, loff_t *ppos)
431 {
432 	u64 val;
433 	int err;
434 
435 	err = kstrtoull_from_user(ubuf, cnt, 10, &val);
436 	if (err)
437 		return err;
438 
439 	mutex_lock(&hwlat_data.lock);
440 	if (hwlat_data.sample_width < val)
441 		hwlat_data.sample_window = val;
442 	else
443 		err = -EINVAL;
444 	mutex_unlock(&hwlat_data.lock);
445 
446 	if (err)
447 		return err;
448 
449 	return cnt;
450 }
451 
452 static const struct file_operations width_fops = {
453 	.open		= tracing_open_generic,
454 	.read		= hwlat_read,
455 	.write		= hwlat_width_write,
456 };
457 
458 static const struct file_operations window_fops = {
459 	.open		= tracing_open_generic,
460 	.read		= hwlat_read,
461 	.write		= hwlat_window_write,
462 };
463 
464 /**
465  * init_tracefs - A function to initialize the tracefs interface files
466  *
467  * This function creates entries in tracefs for "hwlat_detector".
468  * It creates the hwlat_detector directory in the tracing directory,
469  * and within that directory is the count, width and window files to
470  * change and view those values.
471  */
472 static int init_tracefs(void)
473 {
474 	struct dentry *d_tracer;
475 	struct dentry *top_dir;
476 
477 	d_tracer = tracing_init_dentry();
478 	if (IS_ERR(d_tracer))
479 		return -ENOMEM;
480 
481 	top_dir = tracefs_create_dir("hwlat_detector", d_tracer);
482 	if (!top_dir)
483 		return -ENOMEM;
484 
485 	hwlat_sample_window = tracefs_create_file("window", 0640,
486 						  top_dir,
487 						  &hwlat_data.sample_window,
488 						  &window_fops);
489 	if (!hwlat_sample_window)
490 		goto err;
491 
492 	hwlat_sample_width = tracefs_create_file("width", 0644,
493 						 top_dir,
494 						 &hwlat_data.sample_width,
495 						 &width_fops);
496 	if (!hwlat_sample_width)
497 		goto err;
498 
499 	return 0;
500 
501  err:
502 	tracefs_remove_recursive(top_dir);
503 	return -ENOMEM;
504 }
505 
506 static void hwlat_tracer_start(struct trace_array *tr)
507 {
508 	int err;
509 
510 	err = start_kthread(tr);
511 	if (err)
512 		pr_err(BANNER "Cannot start hwlat kthread\n");
513 }
514 
515 static void hwlat_tracer_stop(struct trace_array *tr)
516 {
517 	stop_kthread();
518 }
519 
520 static bool hwlat_busy;
521 
522 static int hwlat_tracer_init(struct trace_array *tr)
523 {
524 	/* Only allow one instance to enable this */
525 	if (hwlat_busy)
526 		return -EBUSY;
527 
528 	hwlat_trace = tr;
529 
530 	disable_migrate = false;
531 	hwlat_data.count = 0;
532 	tr->max_latency = 0;
533 	save_tracing_thresh = tracing_thresh;
534 
535 	/* tracing_thresh is in nsecs, we speak in usecs */
536 	if (!tracing_thresh)
537 		tracing_thresh = last_tracing_thresh;
538 
539 	if (tracer_tracing_is_on(tr))
540 		hwlat_tracer_start(tr);
541 
542 	hwlat_busy = true;
543 
544 	return 0;
545 }
546 
547 static void hwlat_tracer_reset(struct trace_array *tr)
548 {
549 	stop_kthread();
550 
551 	/* the tracing threshold is static between runs */
552 	last_tracing_thresh = tracing_thresh;
553 
554 	tracing_thresh = save_tracing_thresh;
555 	hwlat_busy = false;
556 }
557 
558 static struct tracer hwlat_tracer __read_mostly =
559 {
560 	.name		= "hwlat",
561 	.init		= hwlat_tracer_init,
562 	.reset		= hwlat_tracer_reset,
563 	.start		= hwlat_tracer_start,
564 	.stop		= hwlat_tracer_stop,
565 	.allow_instances = true,
566 };
567 
568 __init static int init_hwlat_tracer(void)
569 {
570 	int ret;
571 
572 	mutex_init(&hwlat_data.lock);
573 
574 	ret = register_tracer(&hwlat_tracer);
575 	if (ret)
576 		return ret;
577 
578 	init_tracefs();
579 
580 	return 0;
581 }
582 late_initcall(init_hwlat_tracer);
583