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