trace_hwlat.c 17 KB

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