xref: /linux/tools/tracing/rtla/src/osnoise_top.c (revision 40648d246fa4307ef11d185933cb0d79fc9ff46c)
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 	osnoise_report_missed_events(top);
284 }
285 
286 /*
287  * osnoise_top_usage - prints osnoise top usage message
288  */
osnoise_top_usage(struct osnoise_top_params * params,char * usage)289 static void osnoise_top_usage(struct osnoise_top_params *params, char *usage)
290 {
291 	int i;
292 
293 	static const char * const msg[] = {
294 		" [-h] [-q] [-D] [-d s] [-a us] [-p us] [-r us] [-s us] [-S us] \\",
295 		"	  [-T us] [-t[file]] [-e sys[:event]] [--filter <filter>] [--trigger <trigger>] \\",
296 		"	  [-c cpu-list] [-H cpu-list] [-P priority] [-C[=cgroup_name]] [--warm-up s]",
297 		"",
298 		"	  -h/--help: print this menu",
299 		"	  -a/--auto: set automatic trace mode, stopping the session if argument in us sample is hit",
300 		"	  -p/--period us: osnoise period in us",
301 		"	  -r/--runtime us: osnoise runtime in us",
302 		"	  -s/--stop us: stop trace if a single sample is higher than the argument in us",
303 		"	  -S/--stop-total us: stop trace if the total sample is higher than the argument in us",
304 		"	  -T/--threshold us: the minimum delta to be considered a noise",
305 		"	  -c/--cpus cpu-list: list of cpus to run osnoise threads",
306 		"	  -H/--house-keeping cpus: run rtla control threads only on the given cpus",
307 		"	  -C/--cgroup[=cgroup_name]: set cgroup, if no cgroup_name is passed, the rtla's cgroup will be inherited",
308 		"	  -d/--duration time[s|m|h|d]: duration of the session",
309 		"	  -D/--debug: print debug info",
310 		"	  -t/--trace[file]: save the stopped trace to [file|osnoise_trace.txt]",
311 		"	  -e/--event <sys:event>: enable the <sys:event> in the trace instance, multiple -e are allowed",
312 		"	     --filter <filter>: enable a trace event filter to the previous -e event",
313 		"	     --trigger <trigger>: enable a trace event trigger to the previous -e event",
314 		"	  -q/--quiet print only a summary at the end",
315 		"	  -P/--priority o:prio|r:prio|f:prio|d:runtime:period : set scheduling parameters",
316 		"		o:prio - use SCHED_OTHER with prio",
317 		"		r:prio - use SCHED_RR with prio",
318 		"		f:prio - use SCHED_FIFO with prio",
319 		"		d:runtime[us|ms|s]:period[us|ms|s] - use SCHED_DEADLINE with runtime and period",
320 		"						       in nanoseconds",
321 		"	     --warm-up s: let the workload run for s seconds before collecting data",
322 		"	     --trace-buffer-size kB: set the per-cpu trace buffer size in kB",
323 		NULL,
324 	};
325 
326 	if (usage)
327 		fprintf(stderr, "%s\n", usage);
328 
329 	if (params->mode == MODE_OSNOISE) {
330 		fprintf(stderr,
331 			"rtla osnoise top: a per-cpu summary of the OS noise (version %s)\n",
332 			VERSION);
333 
334 		fprintf(stderr, "  usage: rtla osnoise [top]");
335 	}
336 
337 	if (params->mode == MODE_HWNOISE) {
338 		fprintf(stderr,
339 			"rtla hwnoise: a summary of hardware-related noise (version %s)\n",
340 			VERSION);
341 
342 		fprintf(stderr, "  usage: rtla hwnoise");
343 	}
344 
345 	for (i = 0; msg[i]; i++)
346 		fprintf(stderr, "%s\n", msg[i]);
347 
348 	if (usage)
349 		exit(EXIT_FAILURE);
350 
351 	exit(EXIT_SUCCESS);
352 }
353 
354 /*
355  * osnoise_top_parse_args - allocs, parse and fill the cmd line parameters
356  */
osnoise_top_parse_args(int argc,char ** argv)357 struct osnoise_top_params *osnoise_top_parse_args(int argc, char **argv)
358 {
359 	struct osnoise_top_params *params;
360 	struct trace_events *tevent;
361 	int retval;
362 	int c;
363 
364 	params = calloc(1, sizeof(*params));
365 	if (!params)
366 		exit(1);
367 
368 	if (strcmp(argv[0], "hwnoise") == 0) {
369 		params->mode = MODE_HWNOISE;
370 		/*
371 		 * Reduce CPU usage for 75% to avoid killing the system.
372 		 */
373 		params->runtime = 750000;
374 		params->period = 1000000;
375 	}
376 
377 	while (1) {
378 		static struct option long_options[] = {
379 			{"auto",		required_argument,	0, 'a'},
380 			{"cpus",		required_argument,	0, 'c'},
381 			{"cgroup",		optional_argument,	0, 'C'},
382 			{"debug",		no_argument,		0, 'D'},
383 			{"duration",		required_argument,	0, 'd'},
384 			{"event",		required_argument,	0, 'e'},
385 			{"house-keeping",	required_argument,	0, 'H'},
386 			{"help",		no_argument,		0, 'h'},
387 			{"period",		required_argument,	0, 'p'},
388 			{"priority",		required_argument,	0, 'P'},
389 			{"quiet",		no_argument,		0, 'q'},
390 			{"runtime",		required_argument,	0, 'r'},
391 			{"stop",		required_argument,	0, 's'},
392 			{"stop-total",		required_argument,	0, 'S'},
393 			{"threshold",		required_argument,	0, 'T'},
394 			{"trace",		optional_argument,	0, 't'},
395 			{"trigger",		required_argument,	0, '0'},
396 			{"filter",		required_argument,	0, '1'},
397 			{"warm-up",		required_argument,	0, '2'},
398 			{"trace-buffer-size",	required_argument,	0, '3'},
399 			{0, 0, 0, 0}
400 		};
401 
402 		/* getopt_long stores the option index here. */
403 		int option_index = 0;
404 
405 		c = getopt_long(argc, argv, "a:c:C::d:De:hH:p:P:qr:s:S:t::T:0:1:2:3:",
406 				 long_options, &option_index);
407 
408 		/* Detect the end of the options. */
409 		if (c == -1)
410 			break;
411 
412 		switch (c) {
413 		case 'a':
414 			/* set sample stop to auto_thresh */
415 			params->stop_us = get_llong_from_str(optarg);
416 
417 			/* set sample threshold to 1 */
418 			params->threshold = 1;
419 
420 			/* set trace */
421 			params->trace_output = "osnoise_trace.txt";
422 
423 			break;
424 		case 'c':
425 			retval = parse_cpu_set(optarg, &params->monitored_cpus);
426 			if (retval)
427 				osnoise_top_usage(params, "\nInvalid -c cpu list\n");
428 			params->cpus = optarg;
429 			break;
430 		case 'C':
431 			params->cgroup = 1;
432 			if (!optarg) {
433 				/* will inherit this cgroup */
434 				params->cgroup_name = NULL;
435 			} else if (*optarg == '=') {
436 				/* skip the = */
437 				params->cgroup_name = ++optarg;
438 			}
439 			break;
440 		case 'D':
441 			config_debug = 1;
442 			break;
443 		case 'd':
444 			params->duration = parse_seconds_duration(optarg);
445 			if (!params->duration)
446 				osnoise_top_usage(params, "Invalid -d duration\n");
447 			break;
448 		case 'e':
449 			tevent = trace_event_alloc(optarg);
450 			if (!tevent) {
451 				err_msg("Error alloc trace event");
452 				exit(EXIT_FAILURE);
453 			}
454 
455 			if (params->events)
456 				tevent->next = params->events;
457 			params->events = tevent;
458 
459 			break;
460 		case 'h':
461 		case '?':
462 			osnoise_top_usage(params, NULL);
463 			break;
464 		case 'H':
465 			params->hk_cpus = 1;
466 			retval = parse_cpu_set(optarg, &params->hk_cpu_set);
467 			if (retval) {
468 				err_msg("Error parsing house keeping CPUs\n");
469 				exit(EXIT_FAILURE);
470 			}
471 			break;
472 		case 'p':
473 			params->period = get_llong_from_str(optarg);
474 			if (params->period > 10000000)
475 				osnoise_top_usage(params, "Period longer than 10 s\n");
476 			break;
477 		case 'P':
478 			retval = parse_prio(optarg, &params->sched_param);
479 			if (retval == -1)
480 				osnoise_top_usage(params, "Invalid -P priority");
481 			params->set_sched = 1;
482 			break;
483 		case 'q':
484 			params->quiet = 1;
485 			break;
486 		case 'r':
487 			params->runtime = get_llong_from_str(optarg);
488 			if (params->runtime < 100)
489 				osnoise_top_usage(params, "Runtime shorter than 100 us\n");
490 			break;
491 		case 's':
492 			params->stop_us = get_llong_from_str(optarg);
493 			break;
494 		case 'S':
495 			params->stop_total_us = get_llong_from_str(optarg);
496 			break;
497 		case 't':
498 			if (optarg) {
499 				if (optarg[0] == '=')
500 					params->trace_output = &optarg[1];
501 				else
502 					params->trace_output = &optarg[0];
503 			} else if (optind < argc && argv[optind][0] != '-')
504 				params->trace_output = argv[optind];
505 			else
506 				params->trace_output = "osnoise_trace.txt";
507 			break;
508 		case 'T':
509 			params->threshold = get_llong_from_str(optarg);
510 			break;
511 		case '0': /* trigger */
512 			if (params->events) {
513 				retval = trace_event_add_trigger(params->events, optarg);
514 				if (retval) {
515 					err_msg("Error adding trigger %s\n", optarg);
516 					exit(EXIT_FAILURE);
517 				}
518 			} else {
519 				osnoise_top_usage(params, "--trigger requires a previous -e\n");
520 			}
521 			break;
522 		case '1': /* filter */
523 			if (params->events) {
524 				retval = trace_event_add_filter(params->events, optarg);
525 				if (retval) {
526 					err_msg("Error adding filter %s\n", optarg);
527 					exit(EXIT_FAILURE);
528 				}
529 			} else {
530 				osnoise_top_usage(params, "--filter requires a previous -e\n");
531 			}
532 			break;
533 		case '2':
534 			params->warmup = get_llong_from_str(optarg);
535 			break;
536 		case '3':
537 			params->buffer_size = get_llong_from_str(optarg);
538 			break;
539 		default:
540 			osnoise_top_usage(params, "Invalid option");
541 		}
542 	}
543 
544 	if (geteuid()) {
545 		err_msg("osnoise needs root permission\n");
546 		exit(EXIT_FAILURE);
547 	}
548 
549 	return params;
550 }
551 
552 /*
553  * osnoise_top_apply_config - apply the top configs to the initialized tool
554  */
555 static int
osnoise_top_apply_config(struct osnoise_tool * tool,struct osnoise_top_params * params)556 osnoise_top_apply_config(struct osnoise_tool *tool, struct osnoise_top_params *params)
557 {
558 	int retval;
559 
560 	if (!params->sleep_time)
561 		params->sleep_time = 1;
562 
563 	if (params->cpus) {
564 		retval = osnoise_set_cpus(tool->context, params->cpus);
565 		if (retval) {
566 			err_msg("Failed to apply CPUs config\n");
567 			goto out_err;
568 		}
569 	}
570 
571 	if (params->runtime || params->period) {
572 		retval = osnoise_set_runtime_period(tool->context,
573 						    params->runtime,
574 						    params->period);
575 		if (retval) {
576 			err_msg("Failed to set runtime and/or period\n");
577 			goto out_err;
578 		}
579 	}
580 
581 	if (params->stop_us) {
582 		retval = osnoise_set_stop_us(tool->context, params->stop_us);
583 		if (retval) {
584 			err_msg("Failed to set stop us\n");
585 			goto out_err;
586 		}
587 	}
588 
589 	if (params->stop_total_us) {
590 		retval = osnoise_set_stop_total_us(tool->context, params->stop_total_us);
591 		if (retval) {
592 			err_msg("Failed to set stop total us\n");
593 			goto out_err;
594 		}
595 	}
596 
597 	if (params->threshold) {
598 		retval = osnoise_set_tracing_thresh(tool->context, params->threshold);
599 		if (retval) {
600 			err_msg("Failed to set tracing_thresh\n");
601 			goto out_err;
602 		}
603 	}
604 
605 	if (params->mode == MODE_HWNOISE) {
606 		retval = osnoise_set_irq_disable(tool->context, 1);
607 		if (retval) {
608 			err_msg("Failed to set OSNOISE_IRQ_DISABLE option\n");
609 			goto out_err;
610 		}
611 	}
612 
613 	if (params->hk_cpus) {
614 		retval = sched_setaffinity(getpid(), sizeof(params->hk_cpu_set),
615 					   &params->hk_cpu_set);
616 		if (retval == -1) {
617 			err_msg("Failed to set rtla to the house keeping CPUs\n");
618 			goto out_err;
619 		}
620 	} else if (params->cpus) {
621 		/*
622 		 * Even if the user do not set a house-keeping CPU, try to
623 		 * move rtla to a CPU set different to the one where the user
624 		 * set the workload to run.
625 		 *
626 		 * No need to check results as this is an automatic attempt.
627 		 */
628 		auto_house_keeping(&params->monitored_cpus);
629 	}
630 
631 	if (isatty(STDOUT_FILENO) && !params->quiet)
632 		params->pretty_output = 1;
633 
634 	return 0;
635 
636 out_err:
637 	return -1;
638 }
639 
640 /*
641  * osnoise_init_top - initialize a osnoise top tool with parameters
642  */
osnoise_init_top(struct osnoise_top_params * params)643 struct osnoise_tool *osnoise_init_top(struct osnoise_top_params *params)
644 {
645 	struct osnoise_tool *tool;
646 	int nr_cpus;
647 
648 	nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
649 
650 	tool = osnoise_init_tool("osnoise_top");
651 	if (!tool)
652 		return NULL;
653 
654 	tool->data = osnoise_alloc_top(nr_cpus);
655 	if (!tool->data) {
656 		osnoise_destroy_tool(tool);
657 		return NULL;
658 	}
659 
660 	tool->params = params;
661 
662 	tep_register_event_handler(tool->trace.tep, -1, "ftrace", "osnoise",
663 				   osnoise_top_handler, NULL);
664 
665 	return tool;
666 }
667 
668 static int stop_tracing;
stop_top(int sig)669 static void stop_top(int sig)
670 {
671 	stop_tracing = 1;
672 }
673 
674 /*
675  * osnoise_top_set_signals - handles the signal to stop the tool
676  */
osnoise_top_set_signals(struct osnoise_top_params * params)677 static void osnoise_top_set_signals(struct osnoise_top_params *params)
678 {
679 	signal(SIGINT, stop_top);
680 	if (params->duration) {
681 		signal(SIGALRM, stop_top);
682 		alarm(params->duration);
683 	}
684 }
685 
osnoise_top_main(int argc,char ** argv)686 int osnoise_top_main(int argc, char **argv)
687 {
688 	struct osnoise_top_params *params;
689 	struct osnoise_tool *record = NULL;
690 	struct osnoise_tool *tool = NULL;
691 	struct trace_instance *trace;
692 	int return_value = 1;
693 	int retval;
694 
695 	params = osnoise_top_parse_args(argc, argv);
696 	if (!params)
697 		exit(1);
698 
699 	tool = osnoise_init_top(params);
700 	if (!tool) {
701 		err_msg("Could not init osnoise top\n");
702 		goto out_exit;
703 	}
704 
705 	retval = osnoise_top_apply_config(tool, params);
706 	if (retval) {
707 		err_msg("Could not apply config\n");
708 		goto out_free;
709 	}
710 
711 	trace = &tool->trace;
712 
713 	retval = enable_osnoise(trace);
714 	if (retval) {
715 		err_msg("Failed to enable osnoise tracer\n");
716 		goto out_free;
717 	}
718 
719 	if (params->set_sched) {
720 		retval = set_comm_sched_attr("osnoise/", &params->sched_param);
721 		if (retval) {
722 			err_msg("Failed to set sched parameters\n");
723 			goto out_free;
724 		}
725 	}
726 
727 	if (params->cgroup) {
728 		retval = set_comm_cgroup("osnoise/", params->cgroup_name);
729 		if (!retval) {
730 			err_msg("Failed to move threads to cgroup\n");
731 			goto out_free;
732 		}
733 	}
734 
735 	if (params->trace_output) {
736 		record = osnoise_init_trace_tool("osnoise");
737 		if (!record) {
738 			err_msg("Failed to enable the trace instance\n");
739 			goto out_free;
740 		}
741 
742 		if (params->events) {
743 			retval = trace_events_enable(&record->trace, params->events);
744 			if (retval)
745 				goto out_top;
746 		}
747 
748 		if (params->buffer_size > 0) {
749 			retval = trace_set_buffer_size(&record->trace, params->buffer_size);
750 			if (retval)
751 				goto out_top;
752 		}
753 	}
754 
755 	/*
756 	 * Start the tracer here, after having set all instances.
757 	 *
758 	 * Let the trace instance start first for the case of hitting a stop
759 	 * tracing while enabling other instances. The trace instance is the
760 	 * one with most valuable information.
761 	 */
762 	if (params->trace_output)
763 		trace_instance_start(&record->trace);
764 	trace_instance_start(trace);
765 
766 	if (params->warmup > 0) {
767 		debug_msg("Warming up for %d seconds\n", params->warmup);
768 		sleep(params->warmup);
769 		if (stop_tracing)
770 			goto out_top;
771 
772 		/*
773 		 * Clean up the buffer. The osnoise workload do not run
774 		 * with tracing off to avoid creating a performance penalty
775 		 * when not needed.
776 		 */
777 		retval = tracefs_instance_file_write(trace->inst, "trace", "");
778 		if (retval < 0) {
779 			debug_msg("Error cleaning up the buffer");
780 			goto out_top;
781 		}
782 
783 	}
784 
785 	tool->start_time = time(NULL);
786 	osnoise_top_set_signals(params);
787 
788 	while (!stop_tracing) {
789 		sleep(params->sleep_time);
790 
791 		retval = tracefs_iterate_raw_events(trace->tep,
792 						    trace->inst,
793 						    NULL,
794 						    0,
795 						    collect_registered_events,
796 						    trace);
797 		if (retval < 0) {
798 			err_msg("Error iterating on events\n");
799 			goto out_top;
800 		}
801 
802 		if (!params->quiet)
803 			osnoise_print_stats(params, tool);
804 
805 		if (osnoise_trace_is_off(tool, record))
806 			break;
807 
808 	}
809 
810 	osnoise_print_stats(params, tool);
811 
812 	return_value = 0;
813 
814 	if (osnoise_trace_is_off(tool, record)) {
815 		printf("osnoise hit stop tracing\n");
816 		if (params->trace_output) {
817 			printf("  Saving trace to %s\n", params->trace_output);
818 			save_trace_to_file(record->trace.inst, params->trace_output);
819 		}
820 	}
821 
822 out_top:
823 	trace_events_destroy(&record->trace, params->events);
824 	params->events = NULL;
825 out_free:
826 	osnoise_free_top(tool->data);
827 	osnoise_destroy_tool(record);
828 	osnoise_destroy_tool(tool);
829 	free(params);
830 out_exit:
831 	exit(return_value);
832 }
833