1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2021 Red Hat Inc, Daniel Bristot de Oliveira <bristot@kernel.org>
4 */
5
6 #include <getopt.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <signal.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <time.h>
13
14 #include "utils.h"
15 #include "osnoise.h"
16 #include "timerlat.h"
17
18 struct timerlat_top_params {
19 char *cpus;
20 char *monitored_cpus;
21 char *trace_output;
22 unsigned long long runtime;
23 long long stop_us;
24 long long stop_total_us;
25 long long timerlat_period_us;
26 long long print_stack;
27 int sleep_time;
28 int output_divisor;
29 int duration;
30 int quiet;
31 int set_sched;
32 int dma_latency;
33 struct sched_attr sched_param;
34 struct trace_events *events;
35 };
36
37 struct timerlat_top_cpu {
38 int irq_count;
39 int thread_count;
40
41 unsigned long long cur_irq;
42 unsigned long long min_irq;
43 unsigned long long sum_irq;
44 unsigned long long max_irq;
45
46 unsigned long long cur_thread;
47 unsigned long long min_thread;
48 unsigned long long sum_thread;
49 unsigned long long max_thread;
50 };
51
52 struct timerlat_top_data {
53 struct timerlat_top_cpu *cpu_data;
54 int nr_cpus;
55 };
56
57 /*
58 * timerlat_free_top - free runtime data
59 */
60 static void
timerlat_free_top(struct timerlat_top_data * data)61 timerlat_free_top(struct timerlat_top_data *data)
62 {
63 free(data->cpu_data);
64 free(data);
65 }
66
67 /*
68 * timerlat_alloc_histogram - alloc runtime data
69 */
timerlat_alloc_top(int nr_cpus)70 static struct timerlat_top_data *timerlat_alloc_top(int nr_cpus)
71 {
72 struct timerlat_top_data *data;
73 int cpu;
74
75 data = calloc(1, sizeof(*data));
76 if (!data)
77 return NULL;
78
79 data->nr_cpus = nr_cpus;
80
81 /* one set of histograms per CPU */
82 data->cpu_data = calloc(1, sizeof(*data->cpu_data) * nr_cpus);
83 if (!data->cpu_data)
84 goto cleanup;
85
86 /* set the min to max */
87 for (cpu = 0; cpu < nr_cpus; cpu++) {
88 data->cpu_data[cpu].min_irq = ~0;
89 data->cpu_data[cpu].min_thread = ~0;
90 }
91
92 return data;
93
94 cleanup:
95 timerlat_free_top(data);
96 return NULL;
97 }
98
99 /*
100 * timerlat_hist_update - record a new timerlat occurent on cpu, updating data
101 */
102 static void
timerlat_top_update(struct osnoise_tool * tool,int cpu,unsigned long long thread,unsigned long long latency)103 timerlat_top_update(struct osnoise_tool *tool, int cpu,
104 unsigned long long thread,
105 unsigned long long latency)
106 {
107 struct timerlat_top_data *data = tool->data;
108 struct timerlat_top_cpu *cpu_data = &data->cpu_data[cpu];
109
110 if (!thread) {
111 cpu_data->irq_count++;
112 cpu_data->cur_irq = latency;
113 update_min(&cpu_data->min_irq, &latency);
114 update_sum(&cpu_data->sum_irq, &latency);
115 update_max(&cpu_data->max_irq, &latency);
116 } else {
117 cpu_data->thread_count++;
118 cpu_data->cur_thread = latency;
119 update_min(&cpu_data->min_thread, &latency);
120 update_sum(&cpu_data->sum_thread, &latency);
121 update_max(&cpu_data->max_thread, &latency);
122 }
123 }
124
125 /*
126 * timerlat_top_handler - this is the handler for timerlat tracer events
127 */
128 static int
timerlat_top_handler(struct trace_seq * s,struct tep_record * record,struct tep_event * event,void * context)129 timerlat_top_handler(struct trace_seq *s, struct tep_record *record,
130 struct tep_event *event, void *context)
131 {
132 struct trace_instance *trace = context;
133 unsigned long long latency, thread;
134 struct osnoise_tool *top;
135 int cpu = record->cpu;
136
137 top = container_of(trace, struct osnoise_tool, trace);
138
139 tep_get_field_val(s, event, "context", record, &thread, 1);
140 tep_get_field_val(s, event, "timer_latency", record, &latency, 1);
141
142 timerlat_top_update(top, cpu, thread, latency);
143
144 return 0;
145 }
146
147 /*
148 * timerlat_top_header - print the header of the tool output
149 */
timerlat_top_header(struct osnoise_tool * top)150 static void timerlat_top_header(struct osnoise_tool *top)
151 {
152 struct timerlat_top_params *params = top->params;
153 struct trace_seq *s = top->trace.seq;
154 char duration[26];
155
156 get_duration(top->start_time, duration, sizeof(duration));
157
158 trace_seq_printf(s, "\033[2;37;40m");
159 trace_seq_printf(s, " Timer Latency ");
160 trace_seq_printf(s, "\033[0;0;0m");
161 trace_seq_printf(s, "\n");
162
163 trace_seq_printf(s, "%-6s | IRQ Timer Latency (%s) | Thread Timer Latency (%s)\n", duration,
164 params->output_divisor == 1 ? "ns" : "us",
165 params->output_divisor == 1 ? "ns" : "us");
166
167 trace_seq_printf(s, "\033[2;30;47m");
168 trace_seq_printf(s, "CPU COUNT | cur min avg max | cur min avg max");
169 trace_seq_printf(s, "\033[0;0;0m");
170 trace_seq_printf(s, "\n");
171 }
172
173 /*
174 * timerlat_top_print - prints the output of a given CPU
175 */
timerlat_top_print(struct osnoise_tool * top,int cpu)176 static void timerlat_top_print(struct osnoise_tool *top, int cpu)
177 {
178
179 struct timerlat_top_params *params = top->params;
180 struct timerlat_top_data *data = top->data;
181 struct timerlat_top_cpu *cpu_data = &data->cpu_data[cpu];
182 int divisor = params->output_divisor;
183 struct trace_seq *s = top->trace.seq;
184
185 if (divisor == 0)
186 return;
187
188 /*
189 * Skip if no data is available: is this cpu offline?
190 */
191 if (!cpu_data->irq_count && !cpu_data->thread_count)
192 return;
193
194 /*
195 * Unless trace is being lost, IRQ counter is always the max.
196 */
197 trace_seq_printf(s, "%3d #%-9d |", cpu, cpu_data->irq_count);
198
199 if (!cpu_data->irq_count) {
200 trace_seq_printf(s, " - ");
201 trace_seq_printf(s, " - ");
202 trace_seq_printf(s, " - ");
203 trace_seq_printf(s, " - |");
204 } else {
205 trace_seq_printf(s, "%9llu ", cpu_data->cur_irq / params->output_divisor);
206 trace_seq_printf(s, "%9llu ", cpu_data->min_irq / params->output_divisor);
207 trace_seq_printf(s, "%9llu ", (cpu_data->sum_irq / cpu_data->irq_count) / divisor);
208 trace_seq_printf(s, "%9llu |", cpu_data->max_irq / divisor);
209 }
210
211 if (!cpu_data->thread_count) {
212 trace_seq_printf(s, " - ");
213 trace_seq_printf(s, " - ");
214 trace_seq_printf(s, " - ");
215 trace_seq_printf(s, " -\n");
216 } else {
217 trace_seq_printf(s, "%9llu ", cpu_data->cur_thread / divisor);
218 trace_seq_printf(s, "%9llu ", cpu_data->min_thread / divisor);
219 trace_seq_printf(s, "%9llu ",
220 (cpu_data->sum_thread / cpu_data->thread_count) / divisor);
221 trace_seq_printf(s, "%9llu\n", cpu_data->max_thread / divisor);
222 }
223 }
224
225 /*
226 * clear_terminal - clears the output terminal
227 */
clear_terminal(struct trace_seq * seq)228 static void clear_terminal(struct trace_seq *seq)
229 {
230 if (!config_debug)
231 trace_seq_printf(seq, "\033c");
232 }
233
234 /*
235 * timerlat_print_stats - print data for all cpus
236 */
237 static void
timerlat_print_stats(struct timerlat_top_params * params,struct osnoise_tool * top)238 timerlat_print_stats(struct timerlat_top_params *params, struct osnoise_tool *top)
239 {
240 struct trace_instance *trace = &top->trace;
241 static int nr_cpus = -1;
242 int i;
243
244 if (nr_cpus == -1)
245 nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
246
247 if (!params->quiet)
248 clear_terminal(trace->seq);
249
250 timerlat_top_header(top);
251
252 for (i = 0; i < nr_cpus; i++) {
253 if (params->cpus && !params->monitored_cpus[i])
254 continue;
255 timerlat_top_print(top, i);
256 }
257
258 trace_seq_do_printf(trace->seq);
259 trace_seq_reset(trace->seq);
260 }
261
262 /*
263 * timerlat_top_usage - prints timerlat top usage message
264 */
timerlat_top_usage(char * usage)265 static void timerlat_top_usage(char *usage)
266 {
267 int i;
268
269 static const char *const msg[] = {
270 "",
271 " usage: rtla timerlat [top] [-h] [-q] [-a us] [-d s] [-D] [-n] [-p us] [-i us] [-T us] [-s us] \\",
272 " [[-t[=file]] [-e sys[:event]] [--filter <filter>] [--trigger <trigger>] [-c cpu-list] \\",
273 " [-P priority] [--dma-latency us]",
274 "",
275 " -h/--help: print this menu",
276 " -a/--auto: set automatic trace mode, stopping the session if argument in us latency is hit",
277 " -p/--period us: timerlat period in us",
278 " -i/--irq us: stop trace if the irq latency is higher than the argument in us",
279 " -T/--thread us: stop trace if the thread latency is higher than the argument in us",
280 " -s/--stack us: save the stack trace at the IRQ if a thread latency is higher than the argument in us",
281 " -c/--cpus cpus: run the tracer only on the given cpus",
282 " -d/--duration time[m|h|d]: duration of the session in seconds",
283 " -D/--debug: print debug info",
284 " -t/--trace[=file]: save the stopped trace to [file|timerlat_trace.txt]",
285 " -e/--event <sys:event>: enable the <sys:event> in the trace instance, multiple -e are allowed",
286 " --filter <command>: enable a trace event filter to the previous -e event",
287 " --trigger <command>: enable a trace event trigger to the previous -e event",
288 " -n/--nano: display data in nanoseconds",
289 " -q/--quiet print only a summary at the end",
290 " --dma-latency us: set /dev/cpu_dma_latency latency <us> to reduce exit from idle latency",
291 " -P/--priority o:prio|r:prio|f:prio|d:runtime:period : set scheduling parameters",
292 " o:prio - use SCHED_OTHER with prio",
293 " r:prio - use SCHED_RR with prio",
294 " f:prio - use SCHED_FIFO with prio",
295 " d:runtime[us|ms|s]:period[us|ms|s] - use SCHED_DEADLINE with runtime and period",
296 " in nanoseconds",
297 NULL,
298 };
299
300 if (usage)
301 fprintf(stderr, "%s\n", usage);
302
303 fprintf(stderr, "rtla timerlat top: a per-cpu summary of the timer latency (version %s)\n",
304 VERSION);
305
306 for (i = 0; msg[i]; i++)
307 fprintf(stderr, "%s\n", msg[i]);
308
309 if (usage)
310 exit(EXIT_FAILURE);
311
312 exit(EXIT_SUCCESS);
313 }
314
315 /*
316 * timerlat_top_parse_args - allocs, parse and fill the cmd line parameters
317 */
318 static struct timerlat_top_params
timerlat_top_parse_args(int argc,char ** argv)319 *timerlat_top_parse_args(int argc, char **argv)
320 {
321 struct timerlat_top_params *params;
322 struct trace_events *tevent;
323 long long auto_thresh;
324 int retval;
325 int c;
326
327 params = calloc(1, sizeof(*params));
328 if (!params)
329 exit(1);
330
331 /* disabled by default */
332 params->dma_latency = -1;
333
334 /* display data in microseconds */
335 params->output_divisor = 1000;
336
337 while (1) {
338 static struct option long_options[] = {
339 {"auto", required_argument, 0, 'a'},
340 {"cpus", required_argument, 0, 'c'},
341 {"debug", no_argument, 0, 'D'},
342 {"duration", required_argument, 0, 'd'},
343 {"event", required_argument, 0, 'e'},
344 {"help", no_argument, 0, 'h'},
345 {"irq", required_argument, 0, 'i'},
346 {"nano", no_argument, 0, 'n'},
347 {"period", required_argument, 0, 'p'},
348 {"priority", required_argument, 0, 'P'},
349 {"quiet", no_argument, 0, 'q'},
350 {"stack", required_argument, 0, 's'},
351 {"thread", required_argument, 0, 'T'},
352 {"trace", optional_argument, 0, 't'},
353 {"trigger", required_argument, 0, '0'},
354 {"filter", required_argument, 0, '1'},
355 {"dma-latency", required_argument, 0, '2'},
356 {0, 0, 0, 0}
357 };
358
359 /* getopt_long stores the option index here. */
360 int option_index = 0;
361
362 c = getopt_long(argc, argv, "a:c:d:De:hi:np:P:qs:t::T:0:1:2:",
363 long_options, &option_index);
364
365 /* detect the end of the options. */
366 if (c == -1)
367 break;
368
369 switch (c) {
370 case 'a':
371 auto_thresh = get_llong_from_str(optarg);
372
373 /* set thread stop to auto_thresh */
374 params->stop_total_us = auto_thresh;
375
376 /* get stack trace */
377 params->print_stack = auto_thresh;
378
379 /* set trace */
380 params->trace_output = "timerlat_trace.txt";
381
382 break;
383 case 'c':
384 retval = parse_cpu_list(optarg, ¶ms->monitored_cpus);
385 if (retval)
386 timerlat_top_usage("\nInvalid -c cpu list\n");
387 params->cpus = optarg;
388 break;
389 case 'D':
390 config_debug = 1;
391 break;
392 case 'd':
393 params->duration = parse_seconds_duration(optarg);
394 if (!params->duration)
395 timerlat_top_usage("Invalid -D duration\n");
396 break;
397 case 'e':
398 tevent = trace_event_alloc(optarg);
399 if (!tevent) {
400 err_msg("Error alloc trace event");
401 exit(EXIT_FAILURE);
402 }
403
404 if (params->events)
405 tevent->next = params->events;
406 params->events = tevent;
407 break;
408 case 'h':
409 case '?':
410 timerlat_top_usage(NULL);
411 break;
412 case 'i':
413 params->stop_us = get_llong_from_str(optarg);
414 break;
415 case 'n':
416 params->output_divisor = 1;
417 break;
418 case 'p':
419 params->timerlat_period_us = get_llong_from_str(optarg);
420 if (params->timerlat_period_us > 1000000)
421 timerlat_top_usage("Period longer than 1 s\n");
422 break;
423 case 'P':
424 retval = parse_prio(optarg, ¶ms->sched_param);
425 if (retval == -1)
426 timerlat_top_usage("Invalid -P priority");
427 params->set_sched = 1;
428 break;
429 case 'q':
430 params->quiet = 1;
431 break;
432 case 's':
433 params->print_stack = get_llong_from_str(optarg);
434 break;
435 case 'T':
436 params->stop_total_us = get_llong_from_str(optarg);
437 break;
438 case 't':
439 if (optarg)
440 /* skip = */
441 params->trace_output = &optarg[1];
442 else
443 params->trace_output = "timerlat_trace.txt";
444 break;
445 case '0': /* trigger */
446 if (params->events) {
447 retval = trace_event_add_trigger(params->events, optarg);
448 if (retval) {
449 err_msg("Error adding trigger %s\n", optarg);
450 exit(EXIT_FAILURE);
451 }
452 } else {
453 timerlat_top_usage("--trigger requires a previous -e\n");
454 }
455 break;
456 case '1': /* filter */
457 if (params->events) {
458 retval = trace_event_add_filter(params->events, optarg);
459 if (retval) {
460 err_msg("Error adding filter %s\n", optarg);
461 exit(EXIT_FAILURE);
462 }
463 } else {
464 timerlat_top_usage("--filter requires a previous -e\n");
465 }
466 break;
467 case '2': /* dma-latency */
468 params->dma_latency = get_llong_from_str(optarg);
469 if (params->dma_latency < 0 || params->dma_latency > 10000) {
470 err_msg("--dma-latency needs to be >= 0 and < 10000");
471 exit(EXIT_FAILURE);
472 }
473 break;
474 default:
475 timerlat_top_usage("Invalid option");
476 }
477 }
478
479 if (geteuid()) {
480 err_msg("rtla needs root permission\n");
481 exit(EXIT_FAILURE);
482 }
483
484 return params;
485 }
486
487 /*
488 * timerlat_top_apply_config - apply the top configs to the initialized tool
489 */
490 static int
timerlat_top_apply_config(struct osnoise_tool * top,struct timerlat_top_params * params)491 timerlat_top_apply_config(struct osnoise_tool *top, struct timerlat_top_params *params)
492 {
493 int retval;
494
495 if (!params->sleep_time)
496 params->sleep_time = 1;
497
498 if (params->cpus) {
499 retval = osnoise_set_cpus(top->context, params->cpus);
500 if (retval) {
501 err_msg("Failed to apply CPUs config\n");
502 goto out_err;
503 }
504 }
505
506 if (params->stop_us) {
507 retval = osnoise_set_stop_us(top->context, params->stop_us);
508 if (retval) {
509 err_msg("Failed to set stop us\n");
510 goto out_err;
511 }
512 }
513
514 if (params->stop_total_us) {
515 retval = osnoise_set_stop_total_us(top->context, params->stop_total_us);
516 if (retval) {
517 err_msg("Failed to set stop total us\n");
518 goto out_err;
519 }
520 }
521
522
523 if (params->timerlat_period_us) {
524 retval = osnoise_set_timerlat_period_us(top->context, params->timerlat_period_us);
525 if (retval) {
526 err_msg("Failed to set timerlat period\n");
527 goto out_err;
528 }
529 }
530
531
532 if (params->print_stack) {
533 retval = osnoise_set_print_stack(top->context, params->print_stack);
534 if (retval) {
535 err_msg("Failed to set print stack\n");
536 goto out_err;
537 }
538 }
539
540 return 0;
541
542 out_err:
543 return -1;
544 }
545
546 /*
547 * timerlat_init_top - initialize a timerlat top tool with parameters
548 */
549 static struct osnoise_tool
timerlat_init_top(struct timerlat_top_params * params)550 *timerlat_init_top(struct timerlat_top_params *params)
551 {
552 struct osnoise_tool *top;
553 int nr_cpus;
554
555 nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
556
557 top = osnoise_init_tool("timerlat_top");
558 if (!top)
559 return NULL;
560
561 top->data = timerlat_alloc_top(nr_cpus);
562 if (!top->data)
563 goto out_err;
564
565 top->params = params;
566
567 tep_register_event_handler(top->trace.tep, -1, "ftrace", "timerlat",
568 timerlat_top_handler, top);
569
570 return top;
571
572 out_err:
573 osnoise_destroy_tool(top);
574 return NULL;
575 }
576
577 static int stop_tracing;
stop_top(int sig)578 static void stop_top(int sig)
579 {
580 stop_tracing = 1;
581 }
582
583 /*
584 * timerlat_top_set_signals - handles the signal to stop the tool
585 */
586 static void
timerlat_top_set_signals(struct timerlat_top_params * params)587 timerlat_top_set_signals(struct timerlat_top_params *params)
588 {
589 signal(SIGINT, stop_top);
590 if (params->duration) {
591 signal(SIGALRM, stop_top);
592 alarm(params->duration);
593 }
594 }
595
timerlat_top_main(int argc,char * argv[])596 int timerlat_top_main(int argc, char *argv[])
597 {
598 struct timerlat_top_params *params;
599 struct osnoise_tool *record = NULL;
600 struct osnoise_tool *top = NULL;
601 struct trace_instance *trace;
602 int dma_latency_fd = -1;
603 int return_value = 1;
604 int retval;
605
606 params = timerlat_top_parse_args(argc, argv);
607 if (!params)
608 exit(1);
609
610 top = timerlat_init_top(params);
611 if (!top) {
612 err_msg("Could not init osnoise top\n");
613 goto out_exit;
614 }
615
616 retval = timerlat_top_apply_config(top, params);
617 if (retval) {
618 err_msg("Could not apply config\n");
619 goto out_free;
620 }
621
622 trace = &top->trace;
623
624 retval = enable_timerlat(trace);
625 if (retval) {
626 err_msg("Failed to enable timerlat tracer\n");
627 goto out_free;
628 }
629
630 if (params->set_sched) {
631 retval = set_comm_sched_attr("timerlat/", ¶ms->sched_param);
632 if (retval) {
633 err_msg("Failed to set sched parameters\n");
634 goto out_free;
635 }
636 }
637
638 if (params->dma_latency >= 0) {
639 dma_latency_fd = set_cpu_dma_latency(params->dma_latency);
640 if (dma_latency_fd < 0) {
641 err_msg("Could not set /dev/cpu_dma_latency.\n");
642 goto out_free;
643 }
644 }
645
646 trace_instance_start(trace);
647
648 if (params->trace_output) {
649 record = osnoise_init_trace_tool("timerlat");
650 if (!record) {
651 err_msg("Failed to enable the trace instance\n");
652 goto out_free;
653 }
654
655 if (params->events) {
656 retval = trace_events_enable(&record->trace, params->events);
657 if (retval)
658 goto out_top;
659 }
660
661 trace_instance_start(&record->trace);
662 }
663
664 top->start_time = time(NULL);
665 timerlat_top_set_signals(params);
666
667 while (!stop_tracing) {
668 sleep(params->sleep_time);
669
670 retval = tracefs_iterate_raw_events(trace->tep,
671 trace->inst,
672 NULL,
673 0,
674 collect_registered_events,
675 trace);
676 if (retval < 0) {
677 err_msg("Error iterating on events\n");
678 goto out_top;
679 }
680
681 if (!params->quiet)
682 timerlat_print_stats(params, top);
683
684 if (trace_is_off(&top->trace, &record->trace))
685 break;
686
687 }
688
689 timerlat_print_stats(params, top);
690
691 return_value = 0;
692
693 if (trace_is_off(&top->trace, &record->trace)) {
694 printf("rtla timerlat hit stop tracing\n");
695 if (params->trace_output) {
696 printf(" Saving trace to %s\n", params->trace_output);
697 save_trace_to_file(record->trace.inst, params->trace_output);
698 }
699 }
700
701 out_top:
702 if (dma_latency_fd >= 0)
703 close(dma_latency_fd);
704 trace_events_destroy(&record->trace, params->events);
705 params->events = NULL;
706 out_free:
707 timerlat_free_top(top->data);
708 osnoise_destroy_tool(record);
709 osnoise_destroy_tool(top);
710 free(params);
711 out_exit:
712 exit(return_value);
713 }
714