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