Loading...
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);
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 <williams@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
57static struct dentry *hwlat_sample_width; /* sample width us */
58static struct dentry *hwlat_sample_window; /* sample window us */
59static struct dentry *hwlat_thread_mode; /* hwlat thread mode */
60
61enum {
62 MODE_NONE = 0,
63 MODE_ROUND_ROBIN,
64 MODE_PER_CPU,
65 MODE_MAX
66};
67static char *thread_mode_str[] = { "none", "round-robin", "per-cpu" };
68
69/* Save the previous tracing_thresh value */
70static unsigned long save_tracing_thresh;
71
72/* runtime kthread data */
73struct hwlat_kthread_data {
74 struct task_struct *kthread;
75 /* NMI timestamp counters */
76 u64 nmi_ts_start;
77 u64 nmi_total_ts;
78 int nmi_count;
79 int nmi_cpu;
80};
81
82static struct hwlat_kthread_data hwlat_single_cpu_data;
83static DEFINE_PER_CPU(struct hwlat_kthread_data, hwlat_per_cpu_data);
84
85/* Tells NMIs to call back to the hwlat tracer to record timestamps */
86bool trace_hwlat_callback_enabled;
87
88/* If the user changed threshold, remember it */
89static u64 last_tracing_thresh = DEFAULT_LAT_THRESHOLD * NSEC_PER_USEC;
90
91/* Individual latency samples are stored here when detected. */
92struct hwlat_sample {
93 u64 seqnum; /* unique sequence */
94 u64 duration; /* delta */
95 u64 outer_duration; /* delta (outer loop) */
96 u64 nmi_total_ts; /* Total time spent in NMIs */
97 struct timespec64 timestamp; /* wall time */
98 int nmi_count; /* # NMIs during this sample */
99 int count; /* # of iterations over thresh */
100};
101
102/* keep the global state somewhere. */
103static struct hwlat_data {
104
105 struct mutex lock; /* protect changes */
106
107 u64 count; /* total since reset */
108
109 u64 sample_window; /* total sampling window (on+off) */
110 u64 sample_width; /* active sampling portion of window */
111
112 int thread_mode; /* thread mode */
113
114} hwlat_data = {
115 .sample_window = DEFAULT_SAMPLE_WINDOW,
116 .sample_width = DEFAULT_SAMPLE_WIDTH,
117 .thread_mode = MODE_ROUND_ROBIN
118};
119
120static struct hwlat_kthread_data *get_cpu_data(void)
121{
122 if (hwlat_data.thread_mode == MODE_PER_CPU)
123 return this_cpu_ptr(&hwlat_per_cpu_data);
124 else
125 return &hwlat_single_cpu_data;
126}
127
128static bool hwlat_busy;
129
130static void trace_hwlat_sample(struct hwlat_sample *sample)
131{
132 struct trace_array *tr = hwlat_trace;
133 struct trace_buffer *buffer = tr->array_buffer.buffer;
134 struct ring_buffer_event *event;
135 struct hwlat_entry *entry;
136
137 event = trace_buffer_lock_reserve(buffer, TRACE_HWLAT, sizeof(*entry),
138 tracing_gen_ctx());
139 if (!event)
140 return;
141 entry = ring_buffer_event_data(event);
142 entry->seqnum = sample->seqnum;
143 entry->duration = sample->duration;
144 entry->outer_duration = sample->outer_duration;
145 entry->timestamp = sample->timestamp;
146 entry->nmi_total_ts = sample->nmi_total_ts;
147 entry->nmi_count = sample->nmi_count;
148 entry->count = sample->count;
149
150 trace_buffer_unlock_commit_nostack(buffer, event);
151}
152
153/* Macros to encapsulate the time capturing infrastructure */
154#define time_type u64
155#define time_get() trace_clock_local()
156#define time_to_us(x) div_u64(x, 1000)
157#define time_sub(a, b) ((a) - (b))
158#define init_time(a, b) (a = b)
159#define time_u64(a) a
160
161void trace_hwlat_callback(bool enter)
162{
163 struct hwlat_kthread_data *kdata = get_cpu_data();
164
165 if (!kdata->kthread)
166 return;
167
168 /*
169 * Currently trace_clock_local() calls sched_clock() and the
170 * generic version is not NMI safe.
171 */
172 if (!IS_ENABLED(CONFIG_GENERIC_SCHED_CLOCK)) {
173 if (enter)
174 kdata->nmi_ts_start = time_get();
175 else
176 kdata->nmi_total_ts += time_get() - kdata->nmi_ts_start;
177 }
178
179 if (enter)
180 kdata->nmi_count++;
181}
182
183/*
184 * hwlat_err - report a hwlat error.
185 */
186#define hwlat_err(msg) ({ \
187 struct trace_array *tr = hwlat_trace; \
188 \
189 trace_array_printk_buf(tr->array_buffer.buffer, _THIS_IP_, msg); \
190})
191
192/**
193 * get_sample - sample the CPU TSC and look for likely hardware latencies
194 *
195 * Used to repeatedly capture the CPU TSC (or similar), looking for potential
196 * hardware-induced latency. Called with interrupts disabled and with
197 * hwlat_data.lock held.
198 */
199static int get_sample(void)
200{
201 struct hwlat_kthread_data *kdata = get_cpu_data();
202 struct trace_array *tr = hwlat_trace;
203 struct hwlat_sample s;
204 time_type start, t1, t2, last_t2;
205 s64 diff, outer_diff, total, last_total = 0;
206 u64 sample = 0;
207 u64 thresh = tracing_thresh;
208 u64 outer_sample = 0;
209 int ret = -1;
210 unsigned int count = 0;
211
212 do_div(thresh, NSEC_PER_USEC); /* modifies interval value */
213
214 kdata->nmi_total_ts = 0;
215 kdata->nmi_count = 0;
216 /* Make sure NMIs see this first */
217 barrier();
218
219 trace_hwlat_callback_enabled = true;
220
221 init_time(last_t2, 0);
222 start = time_get(); /* start timestamp */
223 outer_diff = 0;
224
225 do {
226
227 t1 = time_get(); /* we'll look for a discontinuity */
228 t2 = time_get();
229
230 if (time_u64(last_t2)) {
231 /* Check the delta from outer loop (t2 to next t1) */
232 outer_diff = time_to_us(time_sub(t1, last_t2));
233 /* This shouldn't happen */
234 if (outer_diff < 0) {
235 hwlat_err(BANNER "time running backwards\n");
236 goto out;
237 }
238 if (outer_diff > outer_sample)
239 outer_sample = outer_diff;
240 }
241 last_t2 = t2;
242
243 total = time_to_us(time_sub(t2, start)); /* sample width */
244
245 /* Check for possible overflows */
246 if (total < last_total) {
247 hwlat_err("Time total overflowed\n");
248 break;
249 }
250 last_total = total;
251
252 /* This checks the inner loop (t1 to t2) */
253 diff = time_to_us(time_sub(t2, t1)); /* current diff */
254
255 if (diff > thresh || outer_diff > thresh) {
256 if (!count)
257 ktime_get_real_ts64(&s.timestamp);
258 count++;
259 }
260
261 /* This shouldn't happen */
262 if (diff < 0) {
263 hwlat_err(BANNER "time running backwards\n");
264 goto out;
265 }
266
267 if (diff > sample)
268 sample = diff; /* only want highest value */
269
270 } while (total <= hwlat_data.sample_width);
271
272 barrier(); /* finish the above in the view for NMIs */
273 trace_hwlat_callback_enabled = false;
274 barrier(); /* Make sure nmi_total_ts is no longer updated */
275
276 ret = 0;
277
278 /* If we exceed the threshold value, we have found a hardware latency */
279 if (sample > thresh || outer_sample > thresh) {
280 u64 latency;
281
282 ret = 1;
283
284 /* We read in microseconds */
285 if (kdata->nmi_total_ts)
286 do_div(kdata->nmi_total_ts, NSEC_PER_USEC);
287
288 hwlat_data.count++;
289 s.seqnum = hwlat_data.count;
290 s.duration = sample;
291 s.outer_duration = outer_sample;
292 s.nmi_total_ts = kdata->nmi_total_ts;
293 s.nmi_count = kdata->nmi_count;
294 s.count = count;
295 trace_hwlat_sample(&s);
296
297 latency = max(sample, outer_sample);
298
299 /* Keep a running maximum ever recorded hardware latency */
300 if (latency > tr->max_latency) {
301 tr->max_latency = latency;
302 latency_fsnotify(tr);
303 }
304 }
305
306out:
307 return ret;
308}
309
310static struct cpumask save_cpumask;
311
312static void move_to_next_cpu(void)
313{
314 struct cpumask *current_mask = &save_cpumask;
315 struct trace_array *tr = hwlat_trace;
316 int next_cpu;
317
318 /*
319 * If for some reason the user modifies the CPU affinity
320 * of this thread, then stop migrating for the duration
321 * of the current test.
322 */
323 if (!cpumask_equal(current_mask, current->cpus_ptr))
324 goto change_mode;
325
326 cpus_read_lock();
327 cpumask_and(current_mask, cpu_online_mask, tr->tracing_cpumask);
328 next_cpu = cpumask_next(raw_smp_processor_id(), current_mask);
329 cpus_read_unlock();
330
331 if (next_cpu >= nr_cpu_ids)
332 next_cpu = cpumask_first(current_mask);
333
334 if (next_cpu >= nr_cpu_ids) /* Shouldn't happen! */
335 goto change_mode;
336
337 cpumask_clear(current_mask);
338 cpumask_set_cpu(next_cpu, current_mask);
339
340 set_cpus_allowed_ptr(current, current_mask);
341 return;
342
343 change_mode:
344 hwlat_data.thread_mode = MODE_NONE;
345 pr_info(BANNER "cpumask changed while in round-robin mode, switching to mode none\n");
346}
347
348/*
349 * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
350 *
351 * Used to periodically sample the CPU TSC via a call to get_sample. We
352 * disable interrupts, which does (intentionally) introduce latency since we
353 * need to ensure nothing else might be running (and thus preempting).
354 * Obviously this should never be used in production environments.
355 *
356 * Executes one loop interaction on each CPU in tracing_cpumask sysfs file.
357 */
358static int kthread_fn(void *data)
359{
360 u64 interval;
361
362 while (!kthread_should_stop()) {
363
364 if (hwlat_data.thread_mode == MODE_ROUND_ROBIN)
365 move_to_next_cpu();
366
367 local_irq_disable();
368 get_sample();
369 local_irq_enable();
370
371 mutex_lock(&hwlat_data.lock);
372 interval = hwlat_data.sample_window - hwlat_data.sample_width;
373 mutex_unlock(&hwlat_data.lock);
374
375 do_div(interval, USEC_PER_MSEC); /* modifies interval value */
376
377 /* Always sleep for at least 1ms */
378 if (interval < 1)
379 interval = 1;
380
381 if (msleep_interruptible(interval))
382 break;
383 }
384
385 return 0;
386}
387
388/*
389 * stop_stop_kthread - Inform the hardware latency sampling/detector kthread to stop
390 *
391 * This kicks the running hardware latency sampling/detector kernel thread and
392 * tells it to stop sampling now. Use this on unload and at system shutdown.
393 */
394static void stop_single_kthread(void)
395{
396 struct hwlat_kthread_data *kdata = get_cpu_data();
397 struct task_struct *kthread;
398
399 cpus_read_lock();
400 kthread = kdata->kthread;
401
402 if (!kthread)
403 goto out_put_cpus;
404
405 kthread_stop(kthread);
406 kdata->kthread = NULL;
407
408out_put_cpus:
409 cpus_read_unlock();
410}
411
412
413/*
414 * start_single_kthread - Kick off the hardware latency sampling/detector kthread
415 *
416 * This starts the kernel thread that will sit and sample the CPU timestamp
417 * counter (TSC or similar) and look for potential hardware latencies.
418 */
419static int start_single_kthread(struct trace_array *tr)
420{
421 struct hwlat_kthread_data *kdata = get_cpu_data();
422 struct cpumask *current_mask = &save_cpumask;
423 struct task_struct *kthread;
424 int next_cpu;
425
426 cpus_read_lock();
427 if (kdata->kthread)
428 goto out_put_cpus;
429
430 kthread = kthread_create(kthread_fn, NULL, "hwlatd");
431 if (IS_ERR(kthread)) {
432 pr_err(BANNER "could not start sampling thread\n");
433 cpus_read_unlock();
434 return -ENOMEM;
435 }
436
437 /* Just pick the first CPU on first iteration */
438 cpumask_and(current_mask, cpu_online_mask, tr->tracing_cpumask);
439
440 if (hwlat_data.thread_mode == MODE_ROUND_ROBIN) {
441 next_cpu = cpumask_first(current_mask);
442 cpumask_clear(current_mask);
443 cpumask_set_cpu(next_cpu, current_mask);
444
445 }
446
447 set_cpus_allowed_ptr(kthread, current_mask);
448
449 kdata->kthread = kthread;
450 wake_up_process(kthread);
451
452out_put_cpus:
453 cpus_read_unlock();
454 return 0;
455}
456
457/*
458 * stop_cpu_kthread - Stop a hwlat cpu kthread
459 */
460static void stop_cpu_kthread(unsigned int cpu)
461{
462 struct task_struct *kthread;
463
464 kthread = per_cpu(hwlat_per_cpu_data, cpu).kthread;
465 if (kthread)
466 kthread_stop(kthread);
467 per_cpu(hwlat_per_cpu_data, cpu).kthread = NULL;
468}
469
470/*
471 * stop_per_cpu_kthreads - Inform the hardware latency sampling/detector kthread to stop
472 *
473 * This kicks the running hardware latency sampling/detector kernel threads and
474 * tells it to stop sampling now. Use this on unload and at system shutdown.
475 */
476static void stop_per_cpu_kthreads(void)
477{
478 unsigned int cpu;
479
480 cpus_read_lock();
481 for_each_online_cpu(cpu)
482 stop_cpu_kthread(cpu);
483 cpus_read_unlock();
484}
485
486/*
487 * start_cpu_kthread - Start a hwlat cpu kthread
488 */
489static int start_cpu_kthread(unsigned int cpu)
490{
491 struct task_struct *kthread;
492
493 /* Do not start a new hwlatd thread if it is already running */
494 if (per_cpu(hwlat_per_cpu_data, cpu).kthread)
495 return 0;
496
497 kthread = kthread_run_on_cpu(kthread_fn, NULL, cpu, "hwlatd/%u");
498 if (IS_ERR(kthread)) {
499 pr_err(BANNER "could not start sampling thread\n");
500 return -ENOMEM;
501 }
502
503 per_cpu(hwlat_per_cpu_data, cpu).kthread = kthread;
504
505 return 0;
506}
507
508#ifdef CONFIG_HOTPLUG_CPU
509static void hwlat_hotplug_workfn(struct work_struct *dummy)
510{
511 struct trace_array *tr = hwlat_trace;
512 unsigned int cpu = smp_processor_id();
513
514 mutex_lock(&trace_types_lock);
515 mutex_lock(&hwlat_data.lock);
516 cpus_read_lock();
517
518 if (!hwlat_busy || hwlat_data.thread_mode != MODE_PER_CPU)
519 goto out_unlock;
520
521 if (!cpu_online(cpu))
522 goto out_unlock;
523 if (!cpumask_test_cpu(cpu, tr->tracing_cpumask))
524 goto out_unlock;
525
526 start_cpu_kthread(cpu);
527
528out_unlock:
529 cpus_read_unlock();
530 mutex_unlock(&hwlat_data.lock);
531 mutex_unlock(&trace_types_lock);
532}
533
534static DECLARE_WORK(hwlat_hotplug_work, hwlat_hotplug_workfn);
535
536/*
537 * hwlat_cpu_init - CPU hotplug online callback function
538 */
539static int hwlat_cpu_init(unsigned int cpu)
540{
541 schedule_work_on(cpu, &hwlat_hotplug_work);
542 return 0;
543}
544
545/*
546 * hwlat_cpu_die - CPU hotplug offline callback function
547 */
548static int hwlat_cpu_die(unsigned int cpu)
549{
550 stop_cpu_kthread(cpu);
551 return 0;
552}
553
554static void hwlat_init_hotplug_support(void)
555{
556 int ret;
557
558 ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "trace/hwlat:online",
559 hwlat_cpu_init, hwlat_cpu_die);
560 if (ret < 0)
561 pr_warn(BANNER "Error to init cpu hotplug support\n");
562
563 return;
564}
565#else /* CONFIG_HOTPLUG_CPU */
566static void hwlat_init_hotplug_support(void)
567{
568 return;
569}
570#endif /* CONFIG_HOTPLUG_CPU */
571
572/*
573 * start_per_cpu_kthreads - Kick off the hardware latency sampling/detector kthreads
574 *
575 * This starts the kernel threads that will sit on potentially all cpus and
576 * sample the CPU timestamp counter (TSC or similar) and look for potential
577 * hardware latencies.
578 */
579static int start_per_cpu_kthreads(struct trace_array *tr)
580{
581 struct cpumask *current_mask = &save_cpumask;
582 unsigned int cpu;
583 int retval;
584
585 cpus_read_lock();
586 /*
587 * Run only on CPUs in which hwlat is allowed to run.
588 */
589 cpumask_and(current_mask, cpu_online_mask, tr->tracing_cpumask);
590
591 for_each_cpu(cpu, current_mask) {
592 retval = start_cpu_kthread(cpu);
593 if (retval)
594 goto out_error;
595 }
596 cpus_read_unlock();
597
598 return 0;
599
600out_error:
601 cpus_read_unlock();
602 stop_per_cpu_kthreads();
603 return retval;
604}
605
606static void *s_mode_start(struct seq_file *s, loff_t *pos)
607{
608 int mode = *pos;
609
610 mutex_lock(&hwlat_data.lock);
611
612 if (mode >= MODE_MAX)
613 return NULL;
614
615 return pos;
616}
617
618static void *s_mode_next(struct seq_file *s, void *v, loff_t *pos)
619{
620 int mode = ++(*pos);
621
622 if (mode >= MODE_MAX)
623 return NULL;
624
625 return pos;
626}
627
628static int s_mode_show(struct seq_file *s, void *v)
629{
630 loff_t *pos = v;
631 int mode = *pos;
632
633 if (mode == hwlat_data.thread_mode)
634 seq_printf(s, "[%s]", thread_mode_str[mode]);
635 else
636 seq_printf(s, "%s", thread_mode_str[mode]);
637
638 if (mode < MODE_MAX - 1) /* if mode is any but last */
639 seq_puts(s, " ");
640
641 return 0;
642}
643
644static void s_mode_stop(struct seq_file *s, void *v)
645{
646 seq_puts(s, "\n");
647 mutex_unlock(&hwlat_data.lock);
648}
649
650static const struct seq_operations thread_mode_seq_ops = {
651 .start = s_mode_start,
652 .next = s_mode_next,
653 .show = s_mode_show,
654 .stop = s_mode_stop
655};
656
657static int hwlat_mode_open(struct inode *inode, struct file *file)
658{
659 return seq_open(file, &thread_mode_seq_ops);
660};
661
662static void hwlat_tracer_start(struct trace_array *tr);
663static void hwlat_tracer_stop(struct trace_array *tr);
664
665/**
666 * hwlat_mode_write - Write function for "mode" entry
667 * @filp: The active open file structure
668 * @ubuf: The user buffer that contains the value to write
669 * @cnt: The maximum number of bytes to write to "file"
670 * @ppos: The current position in @file
671 *
672 * This function provides a write implementation for the "mode" interface
673 * to the hardware latency detector. hwlatd has different operation modes.
674 * The "none" sets the allowed cpumask for a single hwlatd thread at the
675 * startup and lets the scheduler handle the migration. The default mode is
676 * the "round-robin" one, in which a single hwlatd thread runs, migrating
677 * among the allowed CPUs in a round-robin fashion. The "per-cpu" mode
678 * creates one hwlatd thread per allowed CPU.
679 */
680static ssize_t hwlat_mode_write(struct file *filp, const char __user *ubuf,
681 size_t cnt, loff_t *ppos)
682{
683 struct trace_array *tr = hwlat_trace;
684 const char *mode;
685 char buf[64];
686 int ret, i;
687
688 if (cnt >= sizeof(buf))
689 return -EINVAL;
690
691 if (copy_from_user(buf, ubuf, cnt))
692 return -EFAULT;
693
694 buf[cnt] = 0;
695
696 mode = strstrip(buf);
697
698 ret = -EINVAL;
699
700 /*
701 * trace_types_lock is taken to avoid concurrency on start/stop
702 * and hwlat_busy.
703 */
704 mutex_lock(&trace_types_lock);
705 if (hwlat_busy)
706 hwlat_tracer_stop(tr);
707
708 mutex_lock(&hwlat_data.lock);
709
710 for (i = 0; i < MODE_MAX; i++) {
711 if (strcmp(mode, thread_mode_str[i]) == 0) {
712 hwlat_data.thread_mode = i;
713 ret = cnt;
714 }
715 }
716
717 mutex_unlock(&hwlat_data.lock);
718
719 if (hwlat_busy)
720 hwlat_tracer_start(tr);
721 mutex_unlock(&trace_types_lock);
722
723 *ppos += cnt;
724
725
726
727 return ret;
728}
729
730/*
731 * The width parameter is read/write using the generic trace_min_max_param
732 * method. The *val is protected by the hwlat_data lock and is upper
733 * bounded by the window parameter.
734 */
735static struct trace_min_max_param hwlat_width = {
736 .lock = &hwlat_data.lock,
737 .val = &hwlat_data.sample_width,
738 .max = &hwlat_data.sample_window,
739 .min = NULL,
740};
741
742/*
743 * The window parameter is read/write using the generic trace_min_max_param
744 * method. The *val is protected by the hwlat_data lock and is lower
745 * bounded by the width parameter.
746 */
747static struct trace_min_max_param hwlat_window = {
748 .lock = &hwlat_data.lock,
749 .val = &hwlat_data.sample_window,
750 .max = NULL,
751 .min = &hwlat_data.sample_width,
752};
753
754static const struct file_operations thread_mode_fops = {
755 .open = hwlat_mode_open,
756 .read = seq_read,
757 .llseek = seq_lseek,
758 .release = seq_release,
759 .write = hwlat_mode_write
760};
761/**
762 * init_tracefs - A function to initialize the tracefs interface files
763 *
764 * This function creates entries in tracefs for "hwlat_detector".
765 * It creates the hwlat_detector directory in the tracing directory,
766 * and within that directory is the count, width and window files to
767 * change and view those values.
768 */
769static int init_tracefs(void)
770{
771 int ret;
772 struct dentry *top_dir;
773
774 ret = tracing_init_dentry();
775 if (ret)
776 return -ENOMEM;
777
778 top_dir = tracefs_create_dir("hwlat_detector", NULL);
779 if (!top_dir)
780 return -ENOMEM;
781
782 hwlat_sample_window = tracefs_create_file("window", TRACE_MODE_WRITE,
783 top_dir,
784 &hwlat_window,
785 &trace_min_max_fops);
786 if (!hwlat_sample_window)
787 goto err;
788
789 hwlat_sample_width = tracefs_create_file("width", TRACE_MODE_WRITE,
790 top_dir,
791 &hwlat_width,
792 &trace_min_max_fops);
793 if (!hwlat_sample_width)
794 goto err;
795
796 hwlat_thread_mode = trace_create_file("mode", TRACE_MODE_WRITE,
797 top_dir,
798 NULL,
799 &thread_mode_fops);
800 if (!hwlat_thread_mode)
801 goto err;
802
803 return 0;
804
805 err:
806 tracefs_remove(top_dir);
807 return -ENOMEM;
808}
809
810static void hwlat_tracer_start(struct trace_array *tr)
811{
812 int err;
813
814 if (hwlat_data.thread_mode == MODE_PER_CPU)
815 err = start_per_cpu_kthreads(tr);
816 else
817 err = start_single_kthread(tr);
818 if (err)
819 pr_err(BANNER "Cannot start hwlat kthread\n");
820}
821
822static void hwlat_tracer_stop(struct trace_array *tr)
823{
824 if (hwlat_data.thread_mode == MODE_PER_CPU)
825 stop_per_cpu_kthreads();
826 else
827 stop_single_kthread();
828}
829
830static int hwlat_tracer_init(struct trace_array *tr)
831{
832 /* Only allow one instance to enable this */
833 if (hwlat_busy)
834 return -EBUSY;
835
836 hwlat_trace = tr;
837
838 hwlat_data.count = 0;
839 tr->max_latency = 0;
840 save_tracing_thresh = tracing_thresh;
841
842 /* tracing_thresh is in nsecs, we speak in usecs */
843 if (!tracing_thresh)
844 tracing_thresh = last_tracing_thresh;
845
846 if (tracer_tracing_is_on(tr))
847 hwlat_tracer_start(tr);
848
849 hwlat_busy = true;
850
851 return 0;
852}
853
854static void hwlat_tracer_reset(struct trace_array *tr)
855{
856 hwlat_tracer_stop(tr);
857
858 /* the tracing threshold is static between runs */
859 last_tracing_thresh = tracing_thresh;
860
861 tracing_thresh = save_tracing_thresh;
862 hwlat_busy = false;
863}
864
865static struct tracer hwlat_tracer __read_mostly =
866{
867 .name = "hwlat",
868 .init = hwlat_tracer_init,
869 .reset = hwlat_tracer_reset,
870 .start = hwlat_tracer_start,
871 .stop = hwlat_tracer_stop,
872 .allow_instances = true,
873};
874
875__init static int init_hwlat_tracer(void)
876{
877 int ret;
878
879 mutex_init(&hwlat_data.lock);
880
881 ret = register_tracer(&hwlat_tracer);
882 if (ret)
883 return ret;
884
885 hwlat_init_hotplug_support();
886
887 init_tracefs();
888
889 return 0;
890}
891late_initcall(init_hwlat_tracer);