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