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