Linux 4.15.6
[linux/fpc-iii.git] / kernel / trace / trace_hwlat.c
blobd7c8e4ec3d9d6cd92b6d78a2c66c984cbbc6fb6c
1 /*
2 * trace_hwlatdetect.c - A simple Hardware Latency detector.
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.
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.
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.
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).
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>
36 * Includes useful feedback from Clark Williams <clark@redhat.com>
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.
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 <linux/sched/clock.h>
48 #include "trace.h"
50 static struct trace_array *hwlat_trace;
52 #define U64STR_SIZE 22 /* 20 digits max */
54 #define BANNER "hwlat_detector: "
55 #define DEFAULT_SAMPLE_WINDOW 1000000 /* 1s */
56 #define DEFAULT_SAMPLE_WIDTH 500000 /* 0.5s */
57 #define DEFAULT_LAT_THRESHOLD 10 /* 10us */
59 /* sampling thread*/
60 static struct task_struct *hwlat_kthread;
62 static struct dentry *hwlat_sample_width; /* sample width us */
63 static struct dentry *hwlat_sample_window; /* sample window us */
65 /* Save the previous tracing_thresh value */
66 static unsigned long save_tracing_thresh;
68 /* NMI timestamp counters */
69 static u64 nmi_ts_start;
70 static u64 nmi_total_ts;
71 static int nmi_count;
72 static int nmi_cpu;
74 /* Tells NMIs to call back to the hwlat tracer to record timestamps */
75 bool trace_hwlat_callback_enabled;
77 /* If the user changed threshold, remember it */
78 static u64 last_tracing_thresh = DEFAULT_LAT_THRESHOLD * NSEC_PER_USEC;
80 /* Individual latency samples are stored here when detected. */
81 struct hwlat_sample {
82 u64 seqnum; /* unique sequence */
83 u64 duration; /* delta */
84 u64 outer_duration; /* delta (outer loop) */
85 u64 nmi_total_ts; /* Total time spent in NMIs */
86 struct timespec64 timestamp; /* wall time */
87 int nmi_count; /* # NMIs during this sample */
90 /* keep the global state somewhere. */
91 static struct hwlat_data {
93 struct mutex lock; /* protect changes */
95 u64 count; /* total since reset */
97 u64 sample_window; /* total sampling window (on+off) */
98 u64 sample_width; /* active sampling portion of window */
100 } hwlat_data = {
101 .sample_window = DEFAULT_SAMPLE_WINDOW,
102 .sample_width = DEFAULT_SAMPLE_WIDTH,
105 static void trace_hwlat_sample(struct hwlat_sample *sample)
107 struct trace_array *tr = hwlat_trace;
108 struct trace_event_call *call = &event_hwlat;
109 struct ring_buffer *buffer = tr->trace_buffer.buffer;
110 struct ring_buffer_event *event;
111 struct hwlat_entry *entry;
112 unsigned long flags;
113 int pc;
115 pc = preempt_count();
116 local_save_flags(flags);
118 event = trace_buffer_lock_reserve(buffer, TRACE_HWLAT, sizeof(*entry),
119 flags, pc);
120 if (!event)
121 return;
122 entry = ring_buffer_event_data(event);
123 entry->seqnum = sample->seqnum;
124 entry->duration = sample->duration;
125 entry->outer_duration = sample->outer_duration;
126 entry->timestamp = sample->timestamp;
127 entry->nmi_total_ts = sample->nmi_total_ts;
128 entry->nmi_count = sample->nmi_count;
130 if (!call_filter_check_discard(call, entry, buffer, event))
131 trace_buffer_unlock_commit_nostack(buffer, event);
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
142 void trace_hwlat_callback(bool enter)
144 if (smp_processor_id() != nmi_cpu)
145 return;
148 * Currently trace_clock_local() calls sched_clock() and the
149 * generic version is not NMI safe.
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;
158 if (enter)
159 nmi_count++;
163 * get_sample - sample the CPU TSC and look for likely hardware latencies
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.
169 static int get_sample(void)
171 struct trace_array *tr = hwlat_trace;
172 time_type start, t1, t2, last_t2;
173 s64 diff, total, last_total = 0;
174 u64 sample = 0;
175 u64 thresh = tracing_thresh;
176 u64 outer_sample = 0;
177 int ret = -1;
179 do_div(thresh, NSEC_PER_USEC); /* modifies interval value */
181 nmi_cpu = smp_processor_id();
182 nmi_total_ts = 0;
183 nmi_count = 0;
184 /* Make sure NMIs see this first */
185 barrier();
187 trace_hwlat_callback_enabled = true;
189 init_time(last_t2, 0);
190 start = time_get(); /* start timestamp */
192 do {
194 t1 = time_get(); /* we'll look for a discontinuity */
195 t2 = time_get();
197 if (time_u64(last_t2)) {
198 /* Check the delta from outer loop (t2 to next t1) */
199 diff = time_to_us(time_sub(t1, last_t2));
200 /* This shouldn't happen */
201 if (diff < 0) {
202 pr_err(BANNER "time running backwards\n");
203 goto out;
205 if (diff > outer_sample)
206 outer_sample = diff;
208 last_t2 = t2;
210 total = time_to_us(time_sub(t2, start)); /* sample width */
212 /* Check for possible overflows */
213 if (total < last_total) {
214 pr_err("Time total overflowed\n");
215 break;
217 last_total = total;
219 /* This checks the inner loop (t1 to t2) */
220 diff = time_to_us(time_sub(t2, t1)); /* current diff */
222 /* This shouldn't happen */
223 if (diff < 0) {
224 pr_err(BANNER "time running backwards\n");
225 goto out;
228 if (diff > sample)
229 sample = diff; /* only want highest value */
231 } while (total <= hwlat_data.sample_width);
233 barrier(); /* finish the above in the view for NMIs */
234 trace_hwlat_callback_enabled = false;
235 barrier(); /* Make sure nmi_total_ts is no longer updated */
237 ret = 0;
239 /* If we exceed the threshold value, we have found a hardware latency */
240 if (sample > thresh || outer_sample > thresh) {
241 struct hwlat_sample s;
243 ret = 1;
245 /* We read in microseconds */
246 if (nmi_total_ts)
247 do_div(nmi_total_ts, NSEC_PER_USEC);
249 hwlat_data.count++;
250 s.seqnum = hwlat_data.count;
251 s.duration = sample;
252 s.outer_duration = outer_sample;
253 ktime_get_real_ts64(&s.timestamp);
254 s.nmi_total_ts = nmi_total_ts;
255 s.nmi_count = nmi_count;
256 trace_hwlat_sample(&s);
258 /* Keep a running maximum ever recorded hardware latency */
259 if (sample > tr->max_latency)
260 tr->max_latency = sample;
263 out:
264 return ret;
267 static struct cpumask save_cpumask;
268 static bool disable_migrate;
270 static void move_to_next_cpu(void)
272 struct cpumask *current_mask = &save_cpumask;
273 int next_cpu;
275 if (disable_migrate)
276 return;
278 * If for some reason the user modifies the CPU affinity
279 * of this thread, than stop migrating for the duration
280 * of the current test.
282 if (!cpumask_equal(current_mask, &current->cpus_allowed))
283 goto disable;
285 get_online_cpus();
286 cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
287 next_cpu = cpumask_next(smp_processor_id(), current_mask);
288 put_online_cpus();
290 if (next_cpu >= nr_cpu_ids)
291 next_cpu = cpumask_first(current_mask);
293 if (next_cpu >= nr_cpu_ids) /* Shouldn't happen! */
294 goto disable;
296 cpumask_clear(current_mask);
297 cpumask_set_cpu(next_cpu, current_mask);
299 sched_setaffinity(0, current_mask);
300 return;
302 disable:
303 disable_migrate = true;
307 * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
309 * Used to periodically sample the CPU TSC via a call to get_sample. We
310 * disable interrupts, which does (intentionally) introduce latency since we
311 * need to ensure nothing else might be running (and thus preempting).
312 * Obviously this should never be used in production environments.
314 * Executes one loop interaction on each CPU in tracing_cpumask sysfs file.
316 static int kthread_fn(void *data)
318 u64 interval;
320 while (!kthread_should_stop()) {
322 move_to_next_cpu();
324 local_irq_disable();
325 get_sample();
326 local_irq_enable();
328 mutex_lock(&hwlat_data.lock);
329 interval = hwlat_data.sample_window - hwlat_data.sample_width;
330 mutex_unlock(&hwlat_data.lock);
332 do_div(interval, USEC_PER_MSEC); /* modifies interval value */
334 /* Always sleep for at least 1ms */
335 if (interval < 1)
336 interval = 1;
338 if (msleep_interruptible(interval))
339 break;
342 return 0;
346 * start_kthread - Kick off the hardware latency sampling/detector kthread
348 * This starts the kernel thread that will sit and sample the CPU timestamp
349 * counter (TSC or similar) and look for potential hardware latencies.
351 static int start_kthread(struct trace_array *tr)
353 struct cpumask *current_mask = &save_cpumask;
354 struct task_struct *kthread;
355 int next_cpu;
357 /* Just pick the first CPU on first iteration */
358 current_mask = &save_cpumask;
359 get_online_cpus();
360 cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
361 put_online_cpus();
362 next_cpu = cpumask_first(current_mask);
364 kthread = kthread_create(kthread_fn, NULL, "hwlatd");
365 if (IS_ERR(kthread)) {
366 pr_err(BANNER "could not start sampling thread\n");
367 return -ENOMEM;
370 cpumask_clear(current_mask);
371 cpumask_set_cpu(next_cpu, current_mask);
372 sched_setaffinity(kthread->pid, current_mask);
374 hwlat_kthread = kthread;
375 wake_up_process(kthread);
377 return 0;
381 * stop_kthread - Inform the hardware latency samping/detector kthread to stop
383 * This kicks the running hardware latency sampling/detector kernel thread and
384 * tells it to stop sampling now. Use this on unload and at system shutdown.
386 static void stop_kthread(void)
388 if (!hwlat_kthread)
389 return;
390 kthread_stop(hwlat_kthread);
391 hwlat_kthread = NULL;
395 * hwlat_read - Wrapper read function for reading both window and width
396 * @filp: The active open file structure
397 * @ubuf: The userspace provided buffer to read value into
398 * @cnt: The maximum number of bytes to read
399 * @ppos: The current "file" position
401 * This function provides a generic read implementation for the global state
402 * "hwlat_data" structure filesystem entries.
404 static ssize_t hwlat_read(struct file *filp, char __user *ubuf,
405 size_t cnt, loff_t *ppos)
407 char buf[U64STR_SIZE];
408 u64 *entry = filp->private_data;
409 u64 val;
410 int len;
412 if (!entry)
413 return -EFAULT;
415 if (cnt > sizeof(buf))
416 cnt = sizeof(buf);
418 val = *entry;
420 len = snprintf(buf, sizeof(buf), "%llu\n", val);
422 return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
426 * hwlat_width_write - Write function for "width" entry
427 * @filp: The active open file structure
428 * @ubuf: The user buffer that contains the value to write
429 * @cnt: The maximum number of bytes to write to "file"
430 * @ppos: The current position in @file
432 * This function provides a write implementation for the "width" interface
433 * to the hardware latency detector. It can be used to configure
434 * for how many us of the total window us we will actively sample for any
435 * hardware-induced latency periods. Obviously, it is not possible to
436 * sample constantly and have the system respond to a sample reader, or,
437 * worse, without having the system appear to have gone out to lunch. It
438 * is enforced that width is less that the total window size.
440 static ssize_t
441 hwlat_width_write(struct file *filp, const char __user *ubuf,
442 size_t cnt, loff_t *ppos)
444 u64 val;
445 int err;
447 err = kstrtoull_from_user(ubuf, cnt, 10, &val);
448 if (err)
449 return err;
451 mutex_lock(&hwlat_data.lock);
452 if (val < hwlat_data.sample_window)
453 hwlat_data.sample_width = val;
454 else
455 err = -EINVAL;
456 mutex_unlock(&hwlat_data.lock);
458 if (err)
459 return err;
461 return cnt;
465 * hwlat_window_write - Write function for "window" entry
466 * @filp: The active open file structure
467 * @ubuf: The user buffer that contains the value to write
468 * @cnt: The maximum number of bytes to write to "file"
469 * @ppos: The current position in @file
471 * This function provides a write implementation for the "window" interface
472 * to the hardware latency detetector. The window is the total time
473 * in us that will be considered one sample period. Conceptually, windows
474 * occur back-to-back and contain a sample width period during which
475 * actual sampling occurs. Can be used to write a new total window size. It
476 * is enfoced that any value written must be greater than the sample width
477 * size, or an error results.
479 static ssize_t
480 hwlat_window_write(struct file *filp, const char __user *ubuf,
481 size_t cnt, loff_t *ppos)
483 u64 val;
484 int err;
486 err = kstrtoull_from_user(ubuf, cnt, 10, &val);
487 if (err)
488 return err;
490 mutex_lock(&hwlat_data.lock);
491 if (hwlat_data.sample_width < val)
492 hwlat_data.sample_window = val;
493 else
494 err = -EINVAL;
495 mutex_unlock(&hwlat_data.lock);
497 if (err)
498 return err;
500 return cnt;
503 static const struct file_operations width_fops = {
504 .open = tracing_open_generic,
505 .read = hwlat_read,
506 .write = hwlat_width_write,
509 static const struct file_operations window_fops = {
510 .open = tracing_open_generic,
511 .read = hwlat_read,
512 .write = hwlat_window_write,
516 * init_tracefs - A function to initialize the tracefs interface files
518 * This function creates entries in tracefs for "hwlat_detector".
519 * It creates the hwlat_detector directory in the tracing directory,
520 * and within that directory is the count, width and window files to
521 * change and view those values.
523 static int init_tracefs(void)
525 struct dentry *d_tracer;
526 struct dentry *top_dir;
528 d_tracer = tracing_init_dentry();
529 if (IS_ERR(d_tracer))
530 return -ENOMEM;
532 top_dir = tracefs_create_dir("hwlat_detector", d_tracer);
533 if (!top_dir)
534 return -ENOMEM;
536 hwlat_sample_window = tracefs_create_file("window", 0640,
537 top_dir,
538 &hwlat_data.sample_window,
539 &window_fops);
540 if (!hwlat_sample_window)
541 goto err;
543 hwlat_sample_width = tracefs_create_file("width", 0644,
544 top_dir,
545 &hwlat_data.sample_width,
546 &width_fops);
547 if (!hwlat_sample_width)
548 goto err;
550 return 0;
552 err:
553 tracefs_remove_recursive(top_dir);
554 return -ENOMEM;
557 static void hwlat_tracer_start(struct trace_array *tr)
559 int err;
561 err = start_kthread(tr);
562 if (err)
563 pr_err(BANNER "Cannot start hwlat kthread\n");
566 static void hwlat_tracer_stop(struct trace_array *tr)
568 stop_kthread();
571 static bool hwlat_busy;
573 static int hwlat_tracer_init(struct trace_array *tr)
575 /* Only allow one instance to enable this */
576 if (hwlat_busy)
577 return -EBUSY;
579 hwlat_trace = tr;
581 disable_migrate = false;
582 hwlat_data.count = 0;
583 tr->max_latency = 0;
584 save_tracing_thresh = tracing_thresh;
586 /* tracing_thresh is in nsecs, we speak in usecs */
587 if (!tracing_thresh)
588 tracing_thresh = last_tracing_thresh;
590 if (tracer_tracing_is_on(tr))
591 hwlat_tracer_start(tr);
593 hwlat_busy = true;
595 return 0;
598 static void hwlat_tracer_reset(struct trace_array *tr)
600 stop_kthread();
602 /* the tracing threshold is static between runs */
603 last_tracing_thresh = tracing_thresh;
605 tracing_thresh = save_tracing_thresh;
606 hwlat_busy = false;
609 static struct tracer hwlat_tracer __read_mostly =
611 .name = "hwlat",
612 .init = hwlat_tracer_init,
613 .reset = hwlat_tracer_reset,
614 .start = hwlat_tracer_start,
615 .stop = hwlat_tracer_stop,
616 .allow_instances = true,
619 __init static int init_hwlat_tracer(void)
621 int ret;
623 mutex_init(&hwlat_data.lock);
625 ret = register_tracer(&hwlat_tracer);
626 if (ret)
627 return ret;
629 init_tracefs();
631 return 0;
633 late_initcall(init_hwlat_tracer);