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