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