trace_hwlat.c 17 KB

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