xref: /openbmc/linux/tools/tracing/rtla/src/timerlat_top.c (revision 0f9b4c3ca5fdf3e177266ef994071b1a03f07318)
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 	unsigned long long	irq_count;
53 	unsigned long long	thread_count;
54 	unsigned long long	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
timerlat_free_top(struct timerlat_top_data * data)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  */
timerlat_alloc_top(int nr_cpus)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
timerlat_top_update(struct osnoise_tool * tool,int cpu,unsigned long long thread,unsigned long long latency)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
timerlat_top_handler(struct trace_seq * s,struct tep_record * record,struct tep_event * event,void * context)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  */
timerlat_top_header(struct osnoise_tool * top)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  */
timerlat_top_print(struct osnoise_tool * top,int cpu)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 #%-9llu |", 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  */
clear_terminal(struct trace_seq * seq)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
timerlat_print_stats(struct timerlat_top_params * params,struct osnoise_tool * top)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  */
timerlat_top_usage(char * usage)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
timerlat_top_parse_args(int argc,char ** argv)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
timerlat_top_apply_config(struct osnoise_tool * top,struct timerlat_top_params * params)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 	/*
683 	* Set workload according to type of thread if the kernel supports it.
684 	* On kernels without support, user threads will have already failed
685 	* on missing timerlat_fd, and kernel threads do not need it.
686 	*/
687 	retval = osnoise_set_workload(top->context, !params->user_top);
688 	if (retval < -1) {
689 		err_msg("Failed to set OSNOISE_WORKLOAD option\n");
690 		goto out_err;
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
timerlat_init_top(struct timerlat_top_params * params)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 struct trace_instance *top_inst = NULL;
stop_top(int sig)732 static void stop_top(int sig)
733 {
734 	if (stop_tracing) {
735 		/*
736 		 * Stop requested twice in a row; abort event processing and
737 		 * exit immediately
738 		 */
739 		tracefs_iterate_stop(top_inst->inst);
740 		return;
741 	}
742 	stop_tracing = 1;
743 	if (top_inst)
744 		trace_instance_stop(top_inst);
745 }
746 
747 /*
748  * timerlat_top_set_signals - handles the signal to stop the tool
749  */
750 static void
timerlat_top_set_signals(struct timerlat_top_params * params)751 timerlat_top_set_signals(struct timerlat_top_params *params)
752 {
753 	signal(SIGINT, stop_top);
754 	if (params->duration) {
755 		signal(SIGALRM, stop_top);
756 		alarm(params->duration);
757 	}
758 }
759 
timerlat_top_main(int argc,char * argv[])760 int timerlat_top_main(int argc, char *argv[])
761 {
762 	struct timerlat_top_params *params;
763 	struct osnoise_tool *record = NULL;
764 	struct timerlat_u_params params_u;
765 	struct osnoise_tool *top = NULL;
766 	struct osnoise_tool *aa = NULL;
767 	struct trace_instance *trace;
768 	int dma_latency_fd = -1;
769 	pthread_t timerlat_u;
770 	int return_value = 1;
771 	char *max_lat;
772 	int retval;
773 
774 	params = timerlat_top_parse_args(argc, argv);
775 	if (!params)
776 		exit(1);
777 
778 	top = timerlat_init_top(params);
779 	if (!top) {
780 		err_msg("Could not init osnoise top\n");
781 		goto out_exit;
782 	}
783 
784 	retval = timerlat_top_apply_config(top, params);
785 	if (retval) {
786 		err_msg("Could not apply config\n");
787 		goto out_free;
788 	}
789 
790 	trace = &top->trace;
791 	/*
792 	* Save trace instance into global variable so that SIGINT can stop
793 	* the timerlat tracer.
794 	* Otherwise, rtla could loop indefinitely when overloaded.
795 	*/
796 	top_inst = trace;
797 
798 
799 	retval = enable_timerlat(trace);
800 	if (retval) {
801 		err_msg("Failed to enable timerlat tracer\n");
802 		goto out_free;
803 	}
804 
805 	if (params->set_sched) {
806 		retval = set_comm_sched_attr("timerlat/", &params->sched_param);
807 		if (retval) {
808 			err_msg("Failed to set sched parameters\n");
809 			goto out_free;
810 		}
811 	}
812 
813 	if (params->cgroup && !params->user_top) {
814 		retval = set_comm_cgroup("timerlat/", params->cgroup_name);
815 		if (!retval) {
816 			err_msg("Failed to move threads to cgroup\n");
817 			goto out_free;
818 		}
819 	}
820 
821 	if (params->dma_latency >= 0) {
822 		dma_latency_fd = set_cpu_dma_latency(params->dma_latency);
823 		if (dma_latency_fd < 0) {
824 			err_msg("Could not set /dev/cpu_dma_latency.\n");
825 			goto out_free;
826 		}
827 	}
828 
829 	if (params->trace_output) {
830 		record = osnoise_init_trace_tool("timerlat");
831 		if (!record) {
832 			err_msg("Failed to enable the trace instance\n");
833 			goto out_free;
834 		}
835 
836 		if (params->events) {
837 			retval = trace_events_enable(&record->trace, params->events);
838 			if (retval)
839 				goto out_top;
840 		}
841 	}
842 
843 	if (!params->no_aa) {
844 		if (params->aa_only) {
845 			/* as top is not used for display, use it for aa */
846 			aa = top;
847 		} else  {
848 			/* otherwise, a new instance is needed */
849 			aa = osnoise_init_tool("timerlat_aa");
850 			if (!aa)
851 				goto out_top;
852 		}
853 
854 		retval = timerlat_aa_init(aa, params->dump_tasks);
855 		if (retval) {
856 			err_msg("Failed to enable the auto analysis instance\n");
857 			goto out_top;
858 		}
859 
860 		/* if it is re-using the main instance, there is no need to start it */
861 		if (aa != top) {
862 			retval = enable_timerlat(&aa->trace);
863 			if (retval) {
864 				err_msg("Failed to enable timerlat tracer\n");
865 				goto out_top;
866 			}
867 		}
868 	}
869 
870 	/*
871 	 * Start the tracers here, after having set all instances.
872 	 *
873 	 * Let the trace instance start first for the case of hitting a stop
874 	 * tracing while enabling other instances. The trace instance is the
875 	 * one with most valuable information.
876 	 */
877 	if (params->trace_output)
878 		trace_instance_start(&record->trace);
879 	if (!params->no_aa && aa != top)
880 		trace_instance_start(&aa->trace);
881 	trace_instance_start(trace);
882 
883 	top->start_time = time(NULL);
884 	timerlat_top_set_signals(params);
885 
886 	if (params->user_top) {
887 		/* rtla asked to stop */
888 		params_u.should_run = 1;
889 		/* all threads left */
890 		params_u.stopped_running = 0;
891 
892 		params_u.set = &params->monitored_cpus;
893 		if (params->set_sched)
894 			params_u.sched_param = &params->sched_param;
895 		else
896 			params_u.sched_param = NULL;
897 
898 		params_u.cgroup_name = params->cgroup_name;
899 
900 		retval = pthread_create(&timerlat_u, NULL, timerlat_u_dispatcher, &params_u);
901 		if (retval)
902 			err_msg("Error creating timerlat user-space threads\n");
903 	}
904 
905 	while (!stop_tracing) {
906 		sleep(params->sleep_time);
907 
908 		if (params->aa_only && !trace_is_off(&top->trace, &record->trace))
909 			continue;
910 
911 		retval = tracefs_iterate_raw_events(trace->tep,
912 						    trace->inst,
913 						    NULL,
914 						    0,
915 						    collect_registered_events,
916 						    trace);
917 		if (retval < 0) {
918 			err_msg("Error iterating on events\n");
919 			goto out_top;
920 		}
921 
922 		if (!params->quiet)
923 			timerlat_print_stats(params, top);
924 
925 		if (trace_is_off(&top->trace, &record->trace))
926 			break;
927 
928 		/* is there still any user-threads ? */
929 		if (params->user_top) {
930 			if (params_u.stopped_running) {
931 				debug_msg("timerlat user space threads stopped!\n");
932 				break;
933 			}
934 		}
935 	}
936 
937 	if (params->user_top && !params_u.stopped_running) {
938 		params_u.should_run = 0;
939 		sleep(1);
940 	}
941 
942 	timerlat_print_stats(params, top);
943 
944 	return_value = 0;
945 
946 	if (trace_is_off(&top->trace, &record->trace) && !stop_tracing) {
947 		printf("rtla timerlat hit stop tracing\n");
948 
949 		if (!params->no_aa)
950 			timerlat_auto_analysis(params->stop_us, params->stop_total_us);
951 
952 		if (params->trace_output) {
953 			printf("  Saving trace to %s\n", params->trace_output);
954 			save_trace_to_file(record->trace.inst, params->trace_output);
955 		}
956 	} else if (params->aa_only) {
957 		/*
958 		 * If the trace did not stop with --aa-only, at least print the
959 		 * max known latency.
960 		 */
961 		max_lat = tracefs_instance_file_read(trace->inst, "tracing_max_latency", NULL);
962 		if (max_lat) {
963 			printf("  Max latency was %s\n", max_lat);
964 			free(max_lat);
965 		}
966 	}
967 
968 out_top:
969 	timerlat_aa_destroy();
970 	if (dma_latency_fd >= 0)
971 		close(dma_latency_fd);
972 	trace_events_destroy(&record->trace, params->events);
973 	params->events = NULL;
974 out_free:
975 	timerlat_free_top(top->data);
976 	if (aa && aa != top)
977 		osnoise_destroy_tool(aa);
978 	osnoise_destroy_tool(record);
979 	osnoise_destroy_tool(top);
980 	free(params);
981 out_exit:
982 	exit(return_value);
983 }
984