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