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