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. int next_cpu;
  227. if (disable_migrate)
  228. return;
  229. /*
  230. * If for some reason the user modifies the CPU affinity
  231. * of this thread, than stop migrating for the duration
  232. * of the current test.
  233. */
  234. if (!cpumask_equal(current_mask, &current->cpus_allowed))
  235. goto disable;
  236. get_online_cpus();
  237. cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
  238. next_cpu = cpumask_next(smp_processor_id(), current_mask);
  239. put_online_cpus();
  240. if (next_cpu >= nr_cpu_ids)
  241. next_cpu = cpumask_first(current_mask);
  242. if (next_cpu >= nr_cpu_ids) /* Shouldn't happen! */
  243. goto disable;
  244. cpumask_clear(current_mask);
  245. cpumask_set_cpu(next_cpu, current_mask);
  246. sched_setaffinity(0, current_mask);
  247. return;
  248. disable:
  249. disable_migrate = true;
  250. }
  251. /*
  252. * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
  253. *
  254. * Used to periodically sample the CPU TSC via a call to get_sample. We
  255. * disable interrupts, which does (intentionally) introduce latency since we
  256. * need to ensure nothing else might be running (and thus preempting).
  257. * Obviously this should never be used in production environments.
  258. *
  259. * Executes one loop interaction on each CPU in tracing_cpumask sysfs file.
  260. */
  261. static int kthread_fn(void *data)
  262. {
  263. u64 interval;
  264. while (!kthread_should_stop()) {
  265. move_to_next_cpu();
  266. local_irq_disable();
  267. get_sample();
  268. local_irq_enable();
  269. mutex_lock(&hwlat_data.lock);
  270. interval = hwlat_data.sample_window - hwlat_data.sample_width;
  271. mutex_unlock(&hwlat_data.lock);
  272. do_div(interval, USEC_PER_MSEC); /* modifies interval value */
  273. /* Always sleep for at least 1ms */
  274. if (interval < 1)
  275. interval = 1;
  276. if (msleep_interruptible(interval))
  277. break;
  278. }
  279. return 0;
  280. }
  281. /**
  282. * start_kthread - Kick off the hardware latency sampling/detector kthread
  283. *
  284. * This starts the kernel thread that will sit and sample the CPU timestamp
  285. * counter (TSC or similar) and look for potential hardware latencies.
  286. */
  287. static int start_kthread(struct trace_array *tr)
  288. {
  289. struct cpumask *current_mask = &save_cpumask;
  290. struct task_struct *kthread;
  291. int next_cpu;
  292. if (WARN_ON(hwlat_kthread))
  293. return 0;
  294. /* Just pick the first CPU on first iteration */
  295. current_mask = &save_cpumask;
  296. get_online_cpus();
  297. cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
  298. put_online_cpus();
  299. next_cpu = cpumask_first(current_mask);
  300. kthread = kthread_create(kthread_fn, NULL, "hwlatd");
  301. if (IS_ERR(kthread)) {
  302. pr_err(BANNER "could not start sampling thread\n");
  303. return -ENOMEM;
  304. }
  305. cpumask_clear(current_mask);
  306. cpumask_set_cpu(next_cpu, current_mask);
  307. sched_setaffinity(kthread->pid, current_mask);
  308. hwlat_kthread = kthread;
  309. wake_up_process(kthread);
  310. return 0;
  311. }
  312. /**
  313. * stop_kthread - Inform the hardware latency samping/detector kthread to stop
  314. *
  315. * This kicks the running hardware latency sampling/detector kernel thread and
  316. * tells it to stop sampling now. Use this on unload and at system shutdown.
  317. */
  318. static void stop_kthread(void)
  319. {
  320. if (!hwlat_kthread)
  321. return;
  322. kthread_stop(hwlat_kthread);
  323. hwlat_kthread = NULL;
  324. }
  325. /*
  326. * hwlat_read - Wrapper read function for reading both window and width
  327. * @filp: The active open file structure
  328. * @ubuf: The userspace provided buffer to read value into
  329. * @cnt: The maximum number of bytes to read
  330. * @ppos: The current "file" position
  331. *
  332. * This function provides a generic read implementation for the global state
  333. * "hwlat_data" structure filesystem entries.
  334. */
  335. static ssize_t hwlat_read(struct file *filp, char __user *ubuf,
  336. size_t cnt, loff_t *ppos)
  337. {
  338. char buf[U64STR_SIZE];
  339. u64 *entry = filp->private_data;
  340. u64 val;
  341. int len;
  342. if (!entry)
  343. return -EFAULT;
  344. if (cnt > sizeof(buf))
  345. cnt = sizeof(buf);
  346. val = *entry;
  347. len = snprintf(buf, sizeof(buf), "%llu\n", val);
  348. return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
  349. }
  350. /**
  351. * hwlat_width_write - Write function for "width" entry
  352. * @filp: The active open file structure
  353. * @ubuf: The user buffer that contains the value to write
  354. * @cnt: The maximum number of bytes to write to "file"
  355. * @ppos: The current position in @file
  356. *
  357. * This function provides a write implementation for the "width" interface
  358. * to the hardware latency detector. It can be used to configure
  359. * for how many us of the total window us we will actively sample for any
  360. * hardware-induced latency periods. Obviously, it is not possible to
  361. * sample constantly and have the system respond to a sample reader, or,
  362. * worse, without having the system appear to have gone out to lunch. It
  363. * is enforced that width is less that the total window size.
  364. */
  365. static ssize_t
  366. hwlat_width_write(struct file *filp, const char __user *ubuf,
  367. size_t cnt, loff_t *ppos)
  368. {
  369. u64 val;
  370. int err;
  371. err = kstrtoull_from_user(ubuf, cnt, 10, &val);
  372. if (err)
  373. return err;
  374. mutex_lock(&hwlat_data.lock);
  375. if (val < hwlat_data.sample_window)
  376. hwlat_data.sample_width = val;
  377. else
  378. err = -EINVAL;
  379. mutex_unlock(&hwlat_data.lock);
  380. if (err)
  381. return err;
  382. return cnt;
  383. }
  384. /**
  385. * hwlat_window_write - Write function for "window" entry
  386. * @filp: The active open file structure
  387. * @ubuf: The user buffer that contains the value to write
  388. * @cnt: The maximum number of bytes to write to "file"
  389. * @ppos: The current position in @file
  390. *
  391. * This function provides a write implementation for the "window" interface
  392. * to the hardware latency detetector. The window is the total time
  393. * in us that will be considered one sample period. Conceptually, windows
  394. * occur back-to-back and contain a sample width period during which
  395. * actual sampling occurs. Can be used to write a new total window size. It
  396. * is enfoced that any value written must be greater than the sample width
  397. * size, or an error results.
  398. */
  399. static ssize_t
  400. hwlat_window_write(struct file *filp, const char __user *ubuf,
  401. size_t cnt, loff_t *ppos)
  402. {
  403. u64 val;
  404. int err;
  405. err = kstrtoull_from_user(ubuf, cnt, 10, &val);
  406. if (err)
  407. return err;
  408. mutex_lock(&hwlat_data.lock);
  409. if (hwlat_data.sample_width < val)
  410. hwlat_data.sample_window = val;
  411. else
  412. err = -EINVAL;
  413. mutex_unlock(&hwlat_data.lock);
  414. if (err)
  415. return err;
  416. return cnt;
  417. }
  418. static const struct file_operations width_fops = {
  419. .open = tracing_open_generic,
  420. .read = hwlat_read,
  421. .write = hwlat_width_write,
  422. };
  423. static const struct file_operations window_fops = {
  424. .open = tracing_open_generic,
  425. .read = hwlat_read,
  426. .write = hwlat_window_write,
  427. };
  428. /**
  429. * init_tracefs - A function to initialize the tracefs interface files
  430. *
  431. * This function creates entries in tracefs for "hwlat_detector".
  432. * It creates the hwlat_detector directory in the tracing directory,
  433. * and within that directory is the count, width and window files to
  434. * change and view those values.
  435. */
  436. static int init_tracefs(void)
  437. {
  438. struct dentry *d_tracer;
  439. struct dentry *top_dir;
  440. d_tracer = tracing_init_dentry();
  441. if (IS_ERR(d_tracer))
  442. return -ENOMEM;
  443. top_dir = tracefs_create_dir("hwlat_detector", d_tracer);
  444. if (!top_dir)
  445. return -ENOMEM;
  446. hwlat_sample_window = tracefs_create_file("window", 0640,
  447. top_dir,
  448. &hwlat_data.sample_window,
  449. &window_fops);
  450. if (!hwlat_sample_window)
  451. goto err;
  452. hwlat_sample_width = tracefs_create_file("width", 0644,
  453. top_dir,
  454. &hwlat_data.sample_width,
  455. &width_fops);
  456. if (!hwlat_sample_width)
  457. goto err;
  458. return 0;
  459. err:
  460. tracefs_remove_recursive(top_dir);
  461. return -ENOMEM;
  462. }
  463. static void hwlat_tracer_start(struct trace_array *tr)
  464. {
  465. int err;
  466. err = start_kthread(tr);
  467. if (err)
  468. pr_err(BANNER "Cannot start hwlat kthread\n");
  469. }
  470. static void hwlat_tracer_stop(struct trace_array *tr)
  471. {
  472. stop_kthread();
  473. }
  474. static bool hwlat_busy;
  475. static int hwlat_tracer_init(struct trace_array *tr)
  476. {
  477. /* Only allow one instance to enable this */
  478. if (hwlat_busy)
  479. return -EBUSY;
  480. hwlat_trace = tr;
  481. disable_migrate = false;
  482. hwlat_data.count = 0;
  483. tr->max_latency = 0;
  484. save_tracing_thresh = tracing_thresh;
  485. /* tracing_thresh is in nsecs, we speak in usecs */
  486. if (!tracing_thresh)
  487. tracing_thresh = last_tracing_thresh;
  488. if (tracer_tracing_is_on(tr))
  489. hwlat_tracer_start(tr);
  490. hwlat_busy = true;
  491. return 0;
  492. }
  493. static void hwlat_tracer_reset(struct trace_array *tr)
  494. {
  495. stop_kthread();
  496. /* the tracing threshold is static between runs */
  497. last_tracing_thresh = tracing_thresh;
  498. tracing_thresh = save_tracing_thresh;
  499. hwlat_busy = false;
  500. }
  501. static struct tracer hwlat_tracer __read_mostly =
  502. {
  503. .name = "hwlat",
  504. .init = hwlat_tracer_init,
  505. .reset = hwlat_tracer_reset,
  506. .start = hwlat_tracer_start,
  507. .stop = hwlat_tracer_stop,
  508. .allow_instances = true,
  509. };
  510. __init static int init_hwlat_tracer(void)
  511. {
  512. int ret;
  513. mutex_init(&hwlat_data.lock);
  514. ret = register_tracer(&hwlat_tracer);
  515. if (ret)
  516. return ret;
  517. init_tracefs();
  518. return 0;
  519. }
  520. late_initcall(init_hwlat_tracer);