trace_hwlat.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /*
  2. * trace_hwlatdetect.c - A simple Hardware Latency detector.
  3. *
  4. * Use this tracer to detect large system latencies induced by the behavior of
  5. * certain underlying system hardware or firmware, independent of Linux itself.
  6. * The code was developed originally to detect the presence of SMIs on Intel
  7. * and AMD systems, although there is no dependency upon x86 herein.
  8. *
  9. * The classical example usage of this tracer is in detecting the presence of
  10. * SMIs or System Management Interrupts on Intel and AMD systems. An SMI is a
  11. * somewhat special form of hardware interrupt spawned from earlier CPU debug
  12. * modes in which the (BIOS/EFI/etc.) firmware arranges for the South Bridge
  13. * LPC (or other device) to generate a special interrupt under certain
  14. * circumstances, for example, upon expiration of a special SMI timer device,
  15. * due to certain external thermal readings, on certain I/O address accesses,
  16. * and other situations. An SMI hits a special CPU pin, triggers a special
  17. * SMI mode (complete with special memory map), and the OS is unaware.
  18. *
  19. * Although certain hardware-inducing latencies are necessary (for example,
  20. * a modern system often requires an SMI handler for correct thermal control
  21. * and remote management) they can wreak havoc upon any OS-level performance
  22. * guarantees toward low-latency, especially when the OS is not even made
  23. * aware of the presence of these interrupts. For this reason, we need a
  24. * somewhat brute force mechanism to detect these interrupts. In this case,
  25. * we do it by hogging all of the CPU(s) for configurable timer intervals,
  26. * sampling the built-in CPU timer, looking for discontiguous readings.
  27. *
  28. * WARNING: This implementation necessarily introduces latencies. Therefore,
  29. * you should NEVER use this tracer while running in a production
  30. * environment requiring any kind of low-latency performance
  31. * guarantee(s).
  32. *
  33. * Copyright (C) 2008-2009 Jon Masters, Red Hat, Inc. <jcm@redhat.com>
  34. * Copyright (C) 2013-2016 Steven Rostedt, Red Hat, Inc. <srostedt@redhat.com>
  35. *
  36. * Includes useful feedback from Clark Williams <clark@redhat.com>
  37. *
  38. * This file is licensed under the terms of the GNU General Public
  39. * License version 2. This program is licensed "as is" without any
  40. * warranty of any kind, whether express or implied.
  41. */
  42. #include <linux/kthread.h>
  43. #include <linux/tracefs.h>
  44. #include <linux/uaccess.h>
  45. #include <linux/cpumask.h>
  46. #include <linux/delay.h>
  47. #include "trace.h"
  48. static struct trace_array *hwlat_trace;
  49. #define U64STR_SIZE 22 /* 20 digits max */
  50. #define BANNER "hwlat_detector: "
  51. #define DEFAULT_SAMPLE_WINDOW 1000000 /* 1s */
  52. #define DEFAULT_SAMPLE_WIDTH 500000 /* 0.5s */
  53. #define DEFAULT_LAT_THRESHOLD 10 /* 10us */
  54. /* sampling thread*/
  55. static struct task_struct *hwlat_kthread;
  56. static struct dentry *hwlat_sample_width; /* sample width us */
  57. static struct dentry *hwlat_sample_window; /* sample window us */
  58. /* Save the previous tracing_thresh value */
  59. static unsigned long save_tracing_thresh;
  60. /* NMI timestamp counters */
  61. static u64 nmi_ts_start;
  62. static u64 nmi_total_ts;
  63. static int nmi_count;
  64. static int nmi_cpu;
  65. /* Tells NMIs to call back to the hwlat tracer to record timestamps */
  66. bool trace_hwlat_callback_enabled;
  67. /* If the user changed threshold, remember it */
  68. static u64 last_tracing_thresh = DEFAULT_LAT_THRESHOLD * NSEC_PER_USEC;
  69. /* Individual latency samples are stored here when detected. */
  70. struct hwlat_sample {
  71. u64 seqnum; /* unique sequence */
  72. u64 duration; /* delta */
  73. u64 outer_duration; /* delta (outer loop) */
  74. u64 nmi_total_ts; /* Total time spent in NMIs */
  75. struct timespec timestamp; /* wall time */
  76. int nmi_count; /* # NMIs during this sample */
  77. };
  78. /* keep the global state somewhere. */
  79. static struct hwlat_data {
  80. struct mutex lock; /* protect changes */
  81. u64 count; /* total since reset */
  82. u64 sample_window; /* total sampling window (on+off) */
  83. u64 sample_width; /* active sampling portion of window */
  84. } hwlat_data = {
  85. .sample_window = DEFAULT_SAMPLE_WINDOW,
  86. .sample_width = DEFAULT_SAMPLE_WIDTH,
  87. };
  88. static void trace_hwlat_sample(struct hwlat_sample *sample)
  89. {
  90. struct trace_array *tr = hwlat_trace;
  91. struct trace_event_call *call = &event_hwlat;
  92. struct ring_buffer *buffer = tr->trace_buffer.buffer;
  93. struct ring_buffer_event *event;
  94. struct hwlat_entry *entry;
  95. unsigned long flags;
  96. int pc;
  97. pc = preempt_count();
  98. local_save_flags(flags);
  99. event = trace_buffer_lock_reserve(buffer, TRACE_HWLAT, sizeof(*entry),
  100. flags, pc);
  101. if (!event)
  102. return;
  103. entry = ring_buffer_event_data(event);
  104. entry->seqnum = sample->seqnum;
  105. entry->duration = sample->duration;
  106. entry->outer_duration = sample->outer_duration;
  107. entry->timestamp = sample->timestamp;
  108. entry->nmi_total_ts = sample->nmi_total_ts;
  109. entry->nmi_count = sample->nmi_count;
  110. if (!call_filter_check_discard(call, entry, buffer, event))
  111. __buffer_unlock_commit(buffer, event);
  112. }
  113. /* Macros to encapsulate the time capturing infrastructure */
  114. #define time_type u64
  115. #define time_get() trace_clock_local()
  116. #define time_to_us(x) div_u64(x, 1000)
  117. #define time_sub(a, b) ((a) - (b))
  118. #define init_time(a, b) (a = b)
  119. #define time_u64(a) a
  120. void trace_hwlat_callback(bool enter)
  121. {
  122. if (smp_processor_id() != nmi_cpu)
  123. return;
  124. /*
  125. * Currently trace_clock_local() calls sched_clock() and the
  126. * generic version is not NMI safe.
  127. */
  128. if (!IS_ENABLED(CONFIG_GENERIC_SCHED_CLOCK)) {
  129. if (enter)
  130. nmi_ts_start = time_get();
  131. else
  132. nmi_total_ts = time_get() - nmi_ts_start;
  133. }
  134. if (enter)
  135. nmi_count++;
  136. }
  137. /**
  138. * get_sample - sample the CPU TSC and look for likely hardware latencies
  139. *
  140. * Used to repeatedly capture the CPU TSC (or similar), looking for potential
  141. * hardware-induced latency. Called with interrupts disabled and with
  142. * hwlat_data.lock held.
  143. */
  144. static int get_sample(void)
  145. {
  146. struct trace_array *tr = hwlat_trace;
  147. time_type start, t1, t2, last_t2;
  148. s64 diff, total, last_total = 0;
  149. u64 sample = 0;
  150. u64 thresh = tracing_thresh;
  151. u64 outer_sample = 0;
  152. int ret = -1;
  153. do_div(thresh, NSEC_PER_USEC); /* modifies interval value */
  154. nmi_cpu = smp_processor_id();
  155. nmi_total_ts = 0;
  156. nmi_count = 0;
  157. /* Make sure NMIs see this first */
  158. barrier();
  159. trace_hwlat_callback_enabled = true;
  160. init_time(last_t2, 0);
  161. start = time_get(); /* start timestamp */
  162. do {
  163. t1 = time_get(); /* we'll look for a discontinuity */
  164. t2 = time_get();
  165. if (time_u64(last_t2)) {
  166. /* Check the delta from outer loop (t2 to next t1) */
  167. diff = time_to_us(time_sub(t1, last_t2));
  168. /* This shouldn't happen */
  169. if (diff < 0) {
  170. pr_err(BANNER "time running backwards\n");
  171. goto out;
  172. }
  173. if (diff > outer_sample)
  174. outer_sample = diff;
  175. }
  176. last_t2 = t2;
  177. total = time_to_us(time_sub(t2, start)); /* sample width */
  178. /* Check for possible overflows */
  179. if (total < last_total) {
  180. pr_err("Time total overflowed\n");
  181. break;
  182. }
  183. last_total = total;
  184. /* This checks the inner loop (t1 to t2) */
  185. diff = time_to_us(time_sub(t2, t1)); /* current diff */
  186. /* This shouldn't happen */
  187. if (diff < 0) {
  188. pr_err(BANNER "time running backwards\n");
  189. goto out;
  190. }
  191. if (diff > sample)
  192. sample = diff; /* only want highest value */
  193. } while (total <= hwlat_data.sample_width);
  194. barrier(); /* finish the above in the view for NMIs */
  195. trace_hwlat_callback_enabled = false;
  196. barrier(); /* Make sure nmi_total_ts is no longer updated */
  197. ret = 0;
  198. /* If we exceed the threshold value, we have found a hardware latency */
  199. if (sample > thresh || outer_sample > thresh) {
  200. struct hwlat_sample s;
  201. ret = 1;
  202. /* We read in microseconds */
  203. if (nmi_total_ts)
  204. do_div(nmi_total_ts, NSEC_PER_USEC);
  205. hwlat_data.count++;
  206. s.seqnum = hwlat_data.count;
  207. s.duration = sample;
  208. s.outer_duration = outer_sample;
  209. s.timestamp = CURRENT_TIME;
  210. s.nmi_total_ts = nmi_total_ts;
  211. s.nmi_count = nmi_count;
  212. trace_hwlat_sample(&s);
  213. /* Keep a running maximum ever recorded hardware latency */
  214. if (sample > tr->max_latency)
  215. tr->max_latency = sample;
  216. }
  217. out:
  218. return ret;
  219. }
  220. static struct cpumask save_cpumask;
  221. static bool disable_migrate;
  222. static void move_to_next_cpu(bool initmask)
  223. {
  224. static struct cpumask *current_mask;
  225. int next_cpu;
  226. if (disable_migrate)
  227. return;
  228. /* Just pick the first CPU on first iteration */
  229. if (initmask) {
  230. current_mask = &save_cpumask;
  231. get_online_cpus();
  232. cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
  233. put_online_cpus();
  234. next_cpu = cpumask_first(current_mask);
  235. goto set_affinity;
  236. }
  237. /*
  238. * If for some reason the user modifies the CPU affinity
  239. * of this thread, than stop migrating for the duration
  240. * of the current test.
  241. */
  242. if (!cpumask_equal(current_mask, &current->cpus_allowed))
  243. goto disable;
  244. get_online_cpus();
  245. cpumask_and(current_mask, cpu_online_mask, tracing_buffer_mask);
  246. next_cpu = cpumask_next(smp_processor_id(), current_mask);
  247. put_online_cpus();
  248. if (next_cpu >= nr_cpu_ids)
  249. next_cpu = cpumask_first(current_mask);
  250. set_affinity:
  251. if (next_cpu >= nr_cpu_ids) /* Shouldn't happen! */
  252. goto disable;
  253. cpumask_clear(current_mask);
  254. cpumask_set_cpu(next_cpu, current_mask);
  255. sched_setaffinity(0, current_mask);
  256. return;
  257. disable:
  258. disable_migrate = true;
  259. }
  260. /*
  261. * kthread_fn - The CPU time sampling/hardware latency detection kernel thread
  262. *
  263. * Used to periodically sample the CPU TSC via a call to get_sample. We
  264. * disable interrupts, which does (intentionally) introduce latency since we
  265. * need to ensure nothing else might be running (and thus preempting).
  266. * Obviously this should never be used in production environments.
  267. *
  268. * Currently this runs on which ever CPU it was scheduled on, but most
  269. * real-world hardware latency situations occur across several CPUs,
  270. * but we might later generalize this if we find there are any actualy
  271. * systems with alternate SMI delivery or other hardware latencies.
  272. */
  273. static int kthread_fn(void *data)
  274. {
  275. u64 interval;
  276. bool initmask = true;
  277. while (!kthread_should_stop()) {
  278. move_to_next_cpu(initmask);
  279. initmask = false;
  280. local_irq_disable();
  281. get_sample();
  282. local_irq_enable();
  283. mutex_lock(&hwlat_data.lock);
  284. interval = hwlat_data.sample_window - hwlat_data.sample_width;
  285. mutex_unlock(&hwlat_data.lock);
  286. do_div(interval, USEC_PER_MSEC); /* modifies interval value */
  287. /* Always sleep for at least 1ms */
  288. if (interval < 1)
  289. interval = 1;
  290. if (msleep_interruptible(interval))
  291. break;
  292. }
  293. return 0;
  294. }
  295. /**
  296. * start_kthread - Kick off the hardware latency sampling/detector kthread
  297. *
  298. * This starts the kernel thread that will sit and sample the CPU timestamp
  299. * counter (TSC or similar) and look for potential hardware latencies.
  300. */
  301. static int start_kthread(struct trace_array *tr)
  302. {
  303. struct task_struct *kthread;
  304. kthread = kthread_create(kthread_fn, NULL, "hwlatd");
  305. if (IS_ERR(kthread)) {
  306. pr_err(BANNER "could not start sampling thread\n");
  307. return -ENOMEM;
  308. }
  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);