Linux Audio

Check our new training course

Loading...
v6.2
  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#include <getopt.h>
  7#include <stdlib.h>
  8#include <string.h>
  9#include <signal.h>
 10#include <unistd.h>
 11#include <errno.h>
 12#include <stdio.h>
 13#include <time.h>
 
 14
 15#include "utils.h"
 16#include "osnoise.h"
 17
 18struct osnoise_hist_params {
 19	char			*cpus;
 20	char			*monitored_cpus;
 21	char			*trace_output;
 
 22	unsigned long long	runtime;
 23	unsigned long long	period;
 24	long long		threshold;
 25	long long		stop_us;
 26	long long		stop_total_us;
 27	int			sleep_time;
 28	int			duration;
 29	int			set_sched;
 30	int			output_divisor;
 
 
 
 31	struct sched_attr	sched_param;
 32	struct trace_events	*events;
 33
 34	char			no_header;
 35	char			no_summary;
 36	char			no_index;
 37	char			with_zeros;
 38	int			bucket_size;
 39	int			entries;
 40};
 41
 42struct osnoise_hist_cpu {
 43	int			*samples;
 44	int			count;
 45
 46	unsigned long long	min_sample;
 47	unsigned long long	sum_sample;
 48	unsigned long long	max_sample;
 49
 50};
 51
 52struct osnoise_hist_data {
 53	struct tracefs_hist	*trace_hist;
 54	struct osnoise_hist_cpu	*hist;
 55	int			entries;
 56	int			bucket_size;
 57	int			nr_cpus;
 58};
 59
 60/*
 61 * osnoise_free_histogram - free runtime data
 62 */
 63static void
 64osnoise_free_histogram(struct osnoise_hist_data *data)
 65{
 66	int cpu;
 67
 68	/* one histogram for IRQ and one for thread, per CPU */
 69	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
 70		if (data->hist[cpu].samples)
 71			free(data->hist[cpu].samples);
 72	}
 73
 74	/* one set of histograms per CPU */
 75	if (data->hist)
 76		free(data->hist);
 77
 78	free(data);
 79}
 80
 81/*
 82 * osnoise_alloc_histogram - alloc runtime data
 83 */
 84static struct osnoise_hist_data
 85*osnoise_alloc_histogram(int nr_cpus, int entries, int bucket_size)
 86{
 87	struct osnoise_hist_data *data;
 88	int cpu;
 89
 90	data = calloc(1, sizeof(*data));
 91	if (!data)
 92		return NULL;
 93
 94	data->entries = entries;
 95	data->bucket_size = bucket_size;
 96	data->nr_cpus = nr_cpus;
 97
 98	data->hist = calloc(1, sizeof(*data->hist) * nr_cpus);
 99	if (!data->hist)
100		goto cleanup;
101
102	for (cpu = 0; cpu < nr_cpus; cpu++) {
103		data->hist[cpu].samples = calloc(1, sizeof(*data->hist->samples) * (entries + 1));
104		if (!data->hist[cpu].samples)
105			goto cleanup;
106	}
107
108	/* set the min to max */
109	for (cpu = 0; cpu < nr_cpus; cpu++)
110		data->hist[cpu].min_sample = ~0;
111
112	return data;
113
114cleanup:
115	osnoise_free_histogram(data);
116	return NULL;
117}
118
119static void osnoise_hist_update_multiple(struct osnoise_tool *tool, int cpu,
120					 unsigned long long duration, int count)
121{
122	struct osnoise_hist_params *params = tool->params;
123	struct osnoise_hist_data *data = tool->data;
 
124	int entries = data->entries;
125	int bucket;
126	int *hist;
127
128	if (params->output_divisor)
129		duration = duration / params->output_divisor;
130
131	if (data->bucket_size)
132		bucket = duration / data->bucket_size;
 
133
134	hist = data->hist[cpu].samples;
135	data->hist[cpu].count += count;
136	update_min(&data->hist[cpu].min_sample, &duration);
137	update_sum(&data->hist[cpu].sum_sample, &duration);
138	update_max(&data->hist[cpu].max_sample, &duration);
139
140	if (bucket < entries)
141		hist[bucket] += count;
142	else
143		hist[entries] += count;
144}
145
146/*
147 * osnoise_destroy_trace_hist - disable events used to collect histogram
148 */
149static void osnoise_destroy_trace_hist(struct osnoise_tool *tool)
150{
151	struct osnoise_hist_data *data = tool->data;
152
153	tracefs_hist_pause(tool->trace.inst, data->trace_hist);
154	tracefs_hist_destroy(tool->trace.inst, data->trace_hist);
155}
156
157/*
158 * osnoise_init_trace_hist - enable events used to collect histogram
159 */
160static int osnoise_init_trace_hist(struct osnoise_tool *tool)
161{
162	struct osnoise_hist_params *params = tool->params;
163	struct osnoise_hist_data *data = tool->data;
164	int bucket_size;
165	char buff[128];
166	int retval = 0;
167
168	/*
169	 * Set the size of the bucket.
170	 */
171	bucket_size = params->output_divisor * params->bucket_size;
172	snprintf(buff, sizeof(buff), "duration.buckets=%d", bucket_size);
173
174	data->trace_hist = tracefs_hist_alloc(tool->trace.tep, "osnoise", "sample_threshold",
175			buff, TRACEFS_HIST_KEY_NORMAL);
176	if (!data->trace_hist)
177		return 1;
178
179	retval = tracefs_hist_add_key(data->trace_hist, "cpu", 0);
180	if (retval)
181		goto out_err;
182
183	retval = tracefs_hist_start(tool->trace.inst, data->trace_hist);
184	if (retval)
185		goto out_err;
186
187	return 0;
188
189out_err:
190	osnoise_destroy_trace_hist(tool);
191	return 1;
192}
193
194/*
195 * osnoise_read_trace_hist - parse histogram file and file osnoise histogram
196 */
197static void osnoise_read_trace_hist(struct osnoise_tool *tool)
198{
199	struct osnoise_hist_data *data = tool->data;
200	long long cpu, counter, duration;
201	char *content, *position;
202
203	tracefs_hist_pause(tool->trace.inst, data->trace_hist);
204
205	content = tracefs_event_file_read(tool->trace.inst, "osnoise",
206					  "sample_threshold",
207					  "hist", NULL);
208	if (!content)
209		return;
210
211	position = content;
212	while (true) {
213		position = strstr(position, "duration: ~");
214		if (!position)
215			break;
216		position += strlen("duration: ~");
217		duration = get_llong_from_str(position);
218		if (duration == -1)
219			err_msg("error reading duration from histogram\n");
220
221		position = strstr(position, "cpu:");
222		if (!position)
223			break;
224		position += strlen("cpu: ");
225		cpu = get_llong_from_str(position);
226		if (cpu == -1)
227			err_msg("error reading cpu from histogram\n");
228
229		position = strstr(position, "hitcount:");
230		if (!position)
231			break;
232		position += strlen("hitcount: ");
233		counter = get_llong_from_str(position);
234		if (counter == -1)
235			err_msg("error reading counter from histogram\n");
236
237		osnoise_hist_update_multiple(tool, cpu, duration, counter);
238	}
239	free(content);
240}
241
242/*
243 * osnoise_hist_header - print the header of the tracer to the output
244 */
245static void osnoise_hist_header(struct osnoise_tool *tool)
246{
247	struct osnoise_hist_params *params = tool->params;
248	struct osnoise_hist_data *data = tool->data;
249	struct trace_seq *s = tool->trace.seq;
250	char duration[26];
251	int cpu;
252
253	if (params->no_header)
254		return;
255
256	get_duration(tool->start_time, duration, sizeof(duration));
257	trace_seq_printf(s, "# RTLA osnoise histogram\n");
258	trace_seq_printf(s, "# Time unit is %s (%s)\n",
259			params->output_divisor == 1 ? "nanoseconds" : "microseconds",
260			params->output_divisor == 1 ? "ns" : "us");
261
262	trace_seq_printf(s, "# Duration: %s\n", duration);
263
264	if (!params->no_index)
265		trace_seq_printf(s, "Index");
266
267	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
268		if (params->cpus && !params->monitored_cpus[cpu])
269			continue;
270
271		if (!data->hist[cpu].count)
272			continue;
273
274		trace_seq_printf(s, "   CPU-%03d", cpu);
275	}
276	trace_seq_printf(s, "\n");
277
278	trace_seq_do_printf(s);
279	trace_seq_reset(s);
280}
281
282/*
283 * osnoise_print_summary - print the summary of the hist data to the output
284 */
285static void
286osnoise_print_summary(struct osnoise_hist_params *params,
287		       struct trace_instance *trace,
288		       struct osnoise_hist_data *data)
289{
290	int cpu;
291
292	if (params->no_summary)
293		return;
294
295	if (!params->no_index)
296		trace_seq_printf(trace->seq, "count:");
297
298	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
299		if (params->cpus && !params->monitored_cpus[cpu])
300			continue;
301
302		if (!data->hist[cpu].count)
303			continue;
304
305		trace_seq_printf(trace->seq, "%9d ", data->hist[cpu].count);
306	}
307	trace_seq_printf(trace->seq, "\n");
308
309	if (!params->no_index)
310		trace_seq_printf(trace->seq, "min:  ");
311
312	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
313		if (params->cpus && !params->monitored_cpus[cpu])
314			continue;
315
316		if (!data->hist[cpu].count)
317			continue;
318
319		trace_seq_printf(trace->seq, "%9llu ",	data->hist[cpu].min_sample);
320
321	}
322	trace_seq_printf(trace->seq, "\n");
323
324	if (!params->no_index)
325		trace_seq_printf(trace->seq, "avg:  ");
326
327	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
328		if (params->cpus && !params->monitored_cpus[cpu])
329			continue;
330
331		if (!data->hist[cpu].count)
332			continue;
333
334		if (data->hist[cpu].count)
335			trace_seq_printf(trace->seq, "%9llu ",
336					data->hist[cpu].sum_sample / data->hist[cpu].count);
337		else
338			trace_seq_printf(trace->seq, "        - ");
339	}
340	trace_seq_printf(trace->seq, "\n");
341
342	if (!params->no_index)
343		trace_seq_printf(trace->seq, "max:  ");
344
345	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
346		if (params->cpus && !params->monitored_cpus[cpu])
347			continue;
348
349		if (!data->hist[cpu].count)
350			continue;
351
352		trace_seq_printf(trace->seq, "%9llu ", data->hist[cpu].max_sample);
353
354	}
355	trace_seq_printf(trace->seq, "\n");
356	trace_seq_do_printf(trace->seq);
357	trace_seq_reset(trace->seq);
358}
359
360/*
361 * osnoise_print_stats - print data for all CPUs
362 */
363static void
364osnoise_print_stats(struct osnoise_hist_params *params, struct osnoise_tool *tool)
365{
366	struct osnoise_hist_data *data = tool->data;
367	struct trace_instance *trace = &tool->trace;
368	int bucket, cpu;
369	int total;
370
371	osnoise_hist_header(tool);
372
373	for (bucket = 0; bucket < data->entries; bucket++) {
374		total = 0;
375
376		if (!params->no_index)
377			trace_seq_printf(trace->seq, "%-6d",
378					 bucket * data->bucket_size);
379
380		for (cpu = 0; cpu < data->nr_cpus; cpu++) {
381			if (params->cpus && !params->monitored_cpus[cpu])
382				continue;
383
384			if (!data->hist[cpu].count)
385				continue;
386
387			total += data->hist[cpu].samples[bucket];
388			trace_seq_printf(trace->seq, "%9d ", data->hist[cpu].samples[bucket]);
389		}
390
391		if (total == 0 && !params->with_zeros) {
392			trace_seq_reset(trace->seq);
393			continue;
394		}
395
396		trace_seq_printf(trace->seq, "\n");
397		trace_seq_do_printf(trace->seq);
398		trace_seq_reset(trace->seq);
399	}
400
401	if (!params->no_index)
402		trace_seq_printf(trace->seq, "over: ");
403
404	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
405		if (params->cpus && !params->monitored_cpus[cpu])
406			continue;
407
408		if (!data->hist[cpu].count)
409			continue;
410
411		trace_seq_printf(trace->seq, "%9d ",
412				 data->hist[cpu].samples[data->entries]);
413	}
414	trace_seq_printf(trace->seq, "\n");
415	trace_seq_do_printf(trace->seq);
416	trace_seq_reset(trace->seq);
417
418	osnoise_print_summary(params, trace, data);
419}
420
421/*
422 * osnoise_hist_usage - prints osnoise hist usage message
423 */
424static void osnoise_hist_usage(char *usage)
425{
426	int i;
427
428	static const char * const msg[] = {
429		"",
430		"  usage: rtla osnoise hist [-h] [-D] [-d s] [-a us] [-p us] [-r us] [-s us] [-S us] \\",
431		"	  [-T us] [-t[=file]] [-e sys[:event]] [--filter <filter>] [--trigger <trigger>] \\",
432		"	  [-c cpu-list] [-P priority] [-b N] [-E N] [--no-header] [--no-summary] [--no-index] \\",
433		"	  [--with-zeros]",
434		"",
435		"	  -h/--help: print this menu",
436		"	  -a/--auto: set automatic trace mode, stopping the session if argument in us sample is hit",
437		"	  -p/--period us: osnoise period in us",
438		"	  -r/--runtime us: osnoise runtime in us",
439		"	  -s/--stop us: stop trace if a single sample is higher than the argument in us",
440		"	  -S/--stop-total us: stop trace if the total sample is higher than the argument in us",
441		"	  -T/--threshold us: the minimum delta to be considered a noise",
442		"	  -c/--cpus cpu-list: list of cpus to run osnoise threads",
 
 
443		"	  -d/--duration time[s|m|h|d]: duration of the session",
444		"	  -D/--debug: print debug info",
445		"	  -t/--trace[=file]: save the stopped trace to [file|osnoise_trace.txt]",
446		"	  -e/--event <sys:event>: enable the <sys:event> in the trace instance, multiple -e are allowed",
447		"	     --filter <filter>: enable a trace event filter to the previous -e event",
448		"	     --trigger <trigger>: enable a trace event trigger to the previous -e event",
449		"	  -b/--bucket-size N: set the histogram bucket size (default 1)",
450		"	  -E/--entries N: set the number of entries of the histogram (default 256)",
451		"	     --no-header: do not print header",
452		"	     --no-summary: do not print summary",
453		"	     --no-index: do not print index",
454		"	     --with-zeros: print zero only entries",
455		"	  -P/--priority o:prio|r:prio|f:prio|d:runtime:period: set scheduling parameters",
456		"		o:prio - use SCHED_OTHER with prio",
457		"		r:prio - use SCHED_RR with prio",
458		"		f:prio - use SCHED_FIFO with prio",
459		"		d:runtime[us|ms|s]:period[us|ms|s] - use SCHED_DEADLINE with runtime and period",
460		"						       in nanoseconds",
461		NULL,
462	};
463
464	if (usage)
465		fprintf(stderr, "%s\n", usage);
466
467	fprintf(stderr, "rtla osnoise hist: a per-cpu histogram of the OS noise (version %s)\n",
468			VERSION);
469
470	for (i = 0; msg[i]; i++)
471		fprintf(stderr, "%s\n", msg[i]);
472	exit(1);
 
 
 
 
473}
474
475/*
476 * osnoise_hist_parse_args - allocs, parse and fill the cmd line parameters
477 */
478static struct osnoise_hist_params
479*osnoise_hist_parse_args(int argc, char *argv[])
480{
481	struct osnoise_hist_params *params;
482	struct trace_events *tevent;
483	int retval;
484	int c;
485
486	params = calloc(1, sizeof(*params));
487	if (!params)
488		exit(1);
489
490	/* display data in microseconds */
491	params->output_divisor = 1000;
492	params->bucket_size = 1;
493	params->entries = 256;
494
495	while (1) {
496		static struct option long_options[] = {
497			{"auto",		required_argument,	0, 'a'},
498			{"bucket-size",		required_argument,	0, 'b'},
499			{"entries",		required_argument,	0, 'E'},
500			{"cpus",		required_argument,	0, 'c'},
 
501			{"debug",		no_argument,		0, 'D'},
502			{"duration",		required_argument,	0, 'd'},
 
503			{"help",		no_argument,		0, 'h'},
504			{"period",		required_argument,	0, 'p'},
505			{"priority",		required_argument,	0, 'P'},
506			{"runtime",		required_argument,	0, 'r'},
507			{"stop",		required_argument,	0, 's'},
508			{"stop-total",		required_argument,	0, 'S'},
509			{"trace",		optional_argument,	0, 't'},
510			{"event",		required_argument,	0, 'e'},
511			{"threshold",		required_argument,	0, 'T'},
512			{"no-header",		no_argument,		0, '0'},
513			{"no-summary",		no_argument,		0, '1'},
514			{"no-index",		no_argument,		0, '2'},
515			{"with-zeros",		no_argument,		0, '3'},
516			{"trigger",		required_argument,	0, '4'},
517			{"filter",		required_argument,	0, '5'},
518			{0, 0, 0, 0}
519		};
520
521		/* getopt_long stores the option index here. */
522		int option_index = 0;
523
524		c = getopt_long(argc, argv, "a:c:b:d:e:E:Dhp:P:r:s:S:t::T:01234:5:",
525				 long_options, &option_index);
526
527		/* detect the end of the options. */
528		if (c == -1)
529			break;
530
531		switch (c) {
532		case 'a':
533			/* set sample stop to auto_thresh */
534			params->stop_us = get_llong_from_str(optarg);
535
536			/* set sample threshold to 1 */
537			params->threshold = 1;
538
539			/* set trace */
540			params->trace_output = "osnoise_trace.txt";
541
542			break;
543		case 'b':
544			params->bucket_size = get_llong_from_str(optarg);
545			if ((params->bucket_size == 0) || (params->bucket_size >= 1000000))
546				osnoise_hist_usage("Bucket size needs to be > 0 and <= 1000000\n");
547			break;
548		case 'c':
549			retval = parse_cpu_list(optarg, &params->monitored_cpus);
550			if (retval)
551				osnoise_hist_usage("\nInvalid -c cpu list\n");
552			params->cpus = optarg;
553			break;
 
 
 
 
 
 
 
 
 
 
554		case 'D':
555			config_debug = 1;
556			break;
557		case 'd':
558			params->duration = parse_seconds_duration(optarg);
559			if (!params->duration)
560				osnoise_hist_usage("Invalid -D duration\n");
561			break;
562		case 'e':
563			tevent = trace_event_alloc(optarg);
564			if (!tevent) {
565				err_msg("Error alloc trace event");
566				exit(EXIT_FAILURE);
567			}
568
569			if (params->events)
570				tevent->next = params->events;
571
572			params->events = tevent;
573			break;
574		case 'E':
575			params->entries = get_llong_from_str(optarg);
576			if ((params->entries < 10) || (params->entries > 9999999))
577				osnoise_hist_usage("Entries must be > 10 and < 9999999\n");
578			break;
579		case 'h':
580		case '?':
581			osnoise_hist_usage(NULL);
582			break;
 
 
 
 
 
 
 
 
583		case 'p':
584			params->period = get_llong_from_str(optarg);
585			if (params->period > 10000000)
586				osnoise_hist_usage("Period longer than 10 s\n");
587			break;
588		case 'P':
589			retval = parse_prio(optarg, &params->sched_param);
590			if (retval == -1)
591				osnoise_hist_usage("Invalid -P priority");
592			params->set_sched = 1;
593			break;
594		case 'r':
595			params->runtime = get_llong_from_str(optarg);
596			if (params->runtime < 100)
597				osnoise_hist_usage("Runtime shorter than 100 us\n");
598			break;
599		case 's':
600			params->stop_us = get_llong_from_str(optarg);
601			break;
602		case 'S':
603			params->stop_total_us = get_llong_from_str(optarg);
604			break;
605		case 'T':
606			params->threshold = get_llong_from_str(optarg);
607			break;
608		case 't':
609			if (optarg)
610				/* skip = */
611				params->trace_output = &optarg[1];
612			else
613				params->trace_output = "osnoise_trace.txt";
614			break;
615		case '0': /* no header */
616			params->no_header = 1;
617			break;
618		case '1': /* no summary */
619			params->no_summary = 1;
620			break;
621		case '2': /* no index */
622			params->no_index = 1;
623			break;
624		case '3': /* with zeros */
625			params->with_zeros = 1;
626			break;
627		case '4': /* trigger */
628			if (params->events) {
629				retval = trace_event_add_trigger(params->events, optarg);
630				if (retval) {
631					err_msg("Error adding trigger %s\n", optarg);
632					exit(EXIT_FAILURE);
633				}
634			} else {
635				osnoise_hist_usage("--trigger requires a previous -e\n");
636			}
637			break;
638		case '5': /* filter */
639			if (params->events) {
640				retval = trace_event_add_filter(params->events, optarg);
641				if (retval) {
642					err_msg("Error adding filter %s\n", optarg);
643					exit(EXIT_FAILURE);
644				}
645			} else {
646				osnoise_hist_usage("--filter requires a previous -e\n");
647			}
648			break;
649		default:
650			osnoise_hist_usage("Invalid option");
651		}
652	}
653
654	if (geteuid()) {
655		err_msg("rtla needs root permission\n");
656		exit(EXIT_FAILURE);
657	}
658
659	if (params->no_index && !params->with_zeros)
660		osnoise_hist_usage("no-index set and with-zeros not set - it does not make sense");
661
662	return params;
663}
664
665/*
666 * osnoise_hist_apply_config - apply the hist configs to the initialized tool
667 */
668static int
669osnoise_hist_apply_config(struct osnoise_tool *tool, struct osnoise_hist_params *params)
670{
671	int retval;
672
673	if (!params->sleep_time)
674		params->sleep_time = 1;
675
676	if (params->cpus) {
677		retval = osnoise_set_cpus(tool->context, params->cpus);
678		if (retval) {
679			err_msg("Failed to apply CPUs config\n");
680			goto out_err;
681		}
682	}
683
684	if (params->runtime || params->period) {
685		retval = osnoise_set_runtime_period(tool->context,
686						    params->runtime,
687						    params->period);
688		if (retval) {
689			err_msg("Failed to set runtime and/or period\n");
690			goto out_err;
691		}
692	}
693
694	if (params->stop_us) {
695		retval = osnoise_set_stop_us(tool->context, params->stop_us);
696		if (retval) {
697			err_msg("Failed to set stop us\n");
698			goto out_err;
699		}
700	}
701
702	if (params->stop_total_us) {
703		retval = osnoise_set_stop_total_us(tool->context, params->stop_total_us);
704		if (retval) {
705			err_msg("Failed to set stop total us\n");
706			goto out_err;
707		}
708	}
709
710	if (params->threshold) {
711		retval = osnoise_set_tracing_thresh(tool->context, params->threshold);
712		if (retval) {
713			err_msg("Failed to set tracing_thresh\n");
714			goto out_err;
715		}
716	}
717
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718	return 0;
719
720out_err:
721	return -1;
722}
723
724/*
725 * osnoise_init_hist - initialize a osnoise hist tool with parameters
726 */
727static struct osnoise_tool
728*osnoise_init_hist(struct osnoise_hist_params *params)
729{
730	struct osnoise_tool *tool;
731	int nr_cpus;
732
733	nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
734
735	tool = osnoise_init_tool("osnoise_hist");
736	if (!tool)
737		return NULL;
738
739	tool->data = osnoise_alloc_histogram(nr_cpus, params->entries, params->bucket_size);
740	if (!tool->data)
741		goto out_err;
742
743	tool->params = params;
744
745	return tool;
746
747out_err:
748	osnoise_destroy_tool(tool);
749	return NULL;
750}
751
752static int stop_tracing;
753static void stop_hist(int sig)
754{
755	stop_tracing = 1;
756}
757
758/*
759 * osnoise_hist_set_signals - handles the signal to stop the tool
760 */
761static void
762osnoise_hist_set_signals(struct osnoise_hist_params *params)
763{
764	signal(SIGINT, stop_hist);
765	if (params->duration) {
766		signal(SIGALRM, stop_hist);
767		alarm(params->duration);
768	}
769}
770
771int osnoise_hist_main(int argc, char *argv[])
772{
773	struct osnoise_hist_params *params;
774	struct osnoise_tool *record = NULL;
775	struct osnoise_tool *tool = NULL;
776	struct trace_instance *trace;
777	int return_value = 1;
778	int retval;
779
780	params = osnoise_hist_parse_args(argc, argv);
781	if (!params)
782		exit(1);
783
784	tool = osnoise_init_hist(params);
785	if (!tool) {
786		err_msg("Could not init osnoise hist\n");
787		goto out_exit;
788	}
789
790	retval = osnoise_hist_apply_config(tool, params);
791	if (retval) {
792		err_msg("Could not apply config\n");
793		goto out_destroy;
794	}
795
796	trace = &tool->trace;
797
798	retval = enable_osnoise(trace);
799	if (retval) {
800		err_msg("Failed to enable osnoise tracer\n");
801		goto out_destroy;
802	}
803
804	retval = osnoise_init_trace_hist(tool);
805	if (retval)
806		goto out_destroy;
807
808	if (params->set_sched) {
809		retval = set_comm_sched_attr("osnoise/", &params->sched_param);
810		if (retval) {
811			err_msg("Failed to set sched parameters\n");
812			goto out_free;
813		}
814	}
815
816	trace_instance_start(trace);
 
 
 
 
 
 
817
818	if (params->trace_output) {
819		record = osnoise_init_trace_tool("osnoise");
820		if (!record) {
821			err_msg("Failed to enable the trace instance\n");
822			goto out_free;
823		}
824
825		if (params->events) {
826			retval = trace_events_enable(&record->trace, params->events);
827			if (retval)
828				goto out_hist;
829		}
830
831		trace_instance_start(&record->trace);
832	}
 
 
 
 
 
 
 
 
 
 
 
833
834	tool->start_time = time(NULL);
835	osnoise_hist_set_signals(params);
836
837	while (!stop_tracing) {
838		sleep(params->sleep_time);
839
840		retval = tracefs_iterate_raw_events(trace->tep,
841						    trace->inst,
842						    NULL,
843						    0,
844						    collect_registered_events,
845						    trace);
846		if (retval < 0) {
847			err_msg("Error iterating on events\n");
848			goto out_hist;
849		}
850
851		if (trace_is_off(&tool->trace, &record->trace))
852			break;
853	}
854
855	osnoise_read_trace_hist(tool);
856
857	osnoise_print_stats(params, tool);
858
859	return_value = 0;
860
861	if (trace_is_off(&tool->trace, &record->trace)) {
862		printf("rtla osnoise hit stop tracing\n");
863		if (params->trace_output) {
864			printf("  Saving trace to %s\n", params->trace_output);
865			save_trace_to_file(record->trace.inst, params->trace_output);
866		}
867	}
868
869out_hist:
870	trace_events_destroy(&record->trace, params->events);
871	params->events = NULL;
872out_free:
873	osnoise_free_histogram(tool->data);
874out_destroy:
875	osnoise_destroy_tool(record);
876	osnoise_destroy_tool(tool);
877	free(params);
878out_exit:
879	exit(return_value);
880}
v6.9.4
  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 <errno.h>
 13#include <stdio.h>
 14#include <time.h>
 15#include <sched.h>
 16
 17#include "utils.h"
 18#include "osnoise.h"
 19
 20struct osnoise_hist_params {
 21	char			*cpus;
 22	cpu_set_t		monitored_cpus;
 23	char			*trace_output;
 24	char			*cgroup_name;
 25	unsigned long long	runtime;
 26	unsigned long long	period;
 27	long long		threshold;
 28	long long		stop_us;
 29	long long		stop_total_us;
 30	int			sleep_time;
 31	int			duration;
 32	int			set_sched;
 33	int			output_divisor;
 34	int			cgroup;
 35	int			hk_cpus;
 36	cpu_set_t		hk_cpu_set;
 37	struct sched_attr	sched_param;
 38	struct trace_events	*events;
 39
 40	char			no_header;
 41	char			no_summary;
 42	char			no_index;
 43	char			with_zeros;
 44	int			bucket_size;
 45	int			entries;
 46};
 47
 48struct osnoise_hist_cpu {
 49	int			*samples;
 50	int			count;
 51
 52	unsigned long long	min_sample;
 53	unsigned long long	sum_sample;
 54	unsigned long long	max_sample;
 55
 56};
 57
 58struct osnoise_hist_data {
 59	struct tracefs_hist	*trace_hist;
 60	struct osnoise_hist_cpu	*hist;
 61	int			entries;
 62	int			bucket_size;
 63	int			nr_cpus;
 64};
 65
 66/*
 67 * osnoise_free_histogram - free runtime data
 68 */
 69static void
 70osnoise_free_histogram(struct osnoise_hist_data *data)
 71{
 72	int cpu;
 73
 74	/* one histogram for IRQ and one for thread, per CPU */
 75	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
 76		if (data->hist[cpu].samples)
 77			free(data->hist[cpu].samples);
 78	}
 79
 80	/* one set of histograms per CPU */
 81	if (data->hist)
 82		free(data->hist);
 83
 84	free(data);
 85}
 86
 87/*
 88 * osnoise_alloc_histogram - alloc runtime data
 89 */
 90static struct osnoise_hist_data
 91*osnoise_alloc_histogram(int nr_cpus, int entries, int bucket_size)
 92{
 93	struct osnoise_hist_data *data;
 94	int cpu;
 95
 96	data = calloc(1, sizeof(*data));
 97	if (!data)
 98		return NULL;
 99
100	data->entries = entries;
101	data->bucket_size = bucket_size;
102	data->nr_cpus = nr_cpus;
103
104	data->hist = calloc(1, sizeof(*data->hist) * nr_cpus);
105	if (!data->hist)
106		goto cleanup;
107
108	for (cpu = 0; cpu < nr_cpus; cpu++) {
109		data->hist[cpu].samples = calloc(1, sizeof(*data->hist->samples) * (entries + 1));
110		if (!data->hist[cpu].samples)
111			goto cleanup;
112	}
113
114	/* set the min to max */
115	for (cpu = 0; cpu < nr_cpus; cpu++)
116		data->hist[cpu].min_sample = ~0;
117
118	return data;
119
120cleanup:
121	osnoise_free_histogram(data);
122	return NULL;
123}
124
125static void osnoise_hist_update_multiple(struct osnoise_tool *tool, int cpu,
126					 unsigned long long duration, int count)
127{
128	struct osnoise_hist_params *params = tool->params;
129	struct osnoise_hist_data *data = tool->data;
130	unsigned long long total_duration;
131	int entries = data->entries;
132	int bucket;
133	int *hist;
134
135	if (params->output_divisor)
136		duration = duration / params->output_divisor;
137
138	bucket = duration / data->bucket_size;
139
140	total_duration = duration * count;
141
142	hist = data->hist[cpu].samples;
143	data->hist[cpu].count += count;
144	update_min(&data->hist[cpu].min_sample, &duration);
145	update_sum(&data->hist[cpu].sum_sample, &total_duration);
146	update_max(&data->hist[cpu].max_sample, &duration);
147
148	if (bucket < entries)
149		hist[bucket] += count;
150	else
151		hist[entries] += count;
152}
153
154/*
155 * osnoise_destroy_trace_hist - disable events used to collect histogram
156 */
157static void osnoise_destroy_trace_hist(struct osnoise_tool *tool)
158{
159	struct osnoise_hist_data *data = tool->data;
160
161	tracefs_hist_pause(tool->trace.inst, data->trace_hist);
162	tracefs_hist_destroy(tool->trace.inst, data->trace_hist);
163}
164
165/*
166 * osnoise_init_trace_hist - enable events used to collect histogram
167 */
168static int osnoise_init_trace_hist(struct osnoise_tool *tool)
169{
170	struct osnoise_hist_params *params = tool->params;
171	struct osnoise_hist_data *data = tool->data;
172	int bucket_size;
173	char buff[128];
174	int retval = 0;
175
176	/*
177	 * Set the size of the bucket.
178	 */
179	bucket_size = params->output_divisor * params->bucket_size;
180	snprintf(buff, sizeof(buff), "duration.buckets=%d", bucket_size);
181
182	data->trace_hist = tracefs_hist_alloc(tool->trace.tep, "osnoise", "sample_threshold",
183			buff, TRACEFS_HIST_KEY_NORMAL);
184	if (!data->trace_hist)
185		return 1;
186
187	retval = tracefs_hist_add_key(data->trace_hist, "cpu", 0);
188	if (retval)
189		goto out_err;
190
191	retval = tracefs_hist_start(tool->trace.inst, data->trace_hist);
192	if (retval)
193		goto out_err;
194
195	return 0;
196
197out_err:
198	osnoise_destroy_trace_hist(tool);
199	return 1;
200}
201
202/*
203 * osnoise_read_trace_hist - parse histogram file and file osnoise histogram
204 */
205static void osnoise_read_trace_hist(struct osnoise_tool *tool)
206{
207	struct osnoise_hist_data *data = tool->data;
208	long long cpu, counter, duration;
209	char *content, *position;
210
211	tracefs_hist_pause(tool->trace.inst, data->trace_hist);
212
213	content = tracefs_event_file_read(tool->trace.inst, "osnoise",
214					  "sample_threshold",
215					  "hist", NULL);
216	if (!content)
217		return;
218
219	position = content;
220	while (true) {
221		position = strstr(position, "duration: ~");
222		if (!position)
223			break;
224		position += strlen("duration: ~");
225		duration = get_llong_from_str(position);
226		if (duration == -1)
227			err_msg("error reading duration from histogram\n");
228
229		position = strstr(position, "cpu:");
230		if (!position)
231			break;
232		position += strlen("cpu: ");
233		cpu = get_llong_from_str(position);
234		if (cpu == -1)
235			err_msg("error reading cpu from histogram\n");
236
237		position = strstr(position, "hitcount:");
238		if (!position)
239			break;
240		position += strlen("hitcount: ");
241		counter = get_llong_from_str(position);
242		if (counter == -1)
243			err_msg("error reading counter from histogram\n");
244
245		osnoise_hist_update_multiple(tool, cpu, duration, counter);
246	}
247	free(content);
248}
249
250/*
251 * osnoise_hist_header - print the header of the tracer to the output
252 */
253static void osnoise_hist_header(struct osnoise_tool *tool)
254{
255	struct osnoise_hist_params *params = tool->params;
256	struct osnoise_hist_data *data = tool->data;
257	struct trace_seq *s = tool->trace.seq;
258	char duration[26];
259	int cpu;
260
261	if (params->no_header)
262		return;
263
264	get_duration(tool->start_time, duration, sizeof(duration));
265	trace_seq_printf(s, "# RTLA osnoise histogram\n");
266	trace_seq_printf(s, "# Time unit is %s (%s)\n",
267			params->output_divisor == 1 ? "nanoseconds" : "microseconds",
268			params->output_divisor == 1 ? "ns" : "us");
269
270	trace_seq_printf(s, "# Duration: %s\n", duration);
271
272	if (!params->no_index)
273		trace_seq_printf(s, "Index");
274
275	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
276		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
277			continue;
278
279		if (!data->hist[cpu].count)
280			continue;
281
282		trace_seq_printf(s, "   CPU-%03d", cpu);
283	}
284	trace_seq_printf(s, "\n");
285
286	trace_seq_do_printf(s);
287	trace_seq_reset(s);
288}
289
290/*
291 * osnoise_print_summary - print the summary of the hist data to the output
292 */
293static void
294osnoise_print_summary(struct osnoise_hist_params *params,
295		       struct trace_instance *trace,
296		       struct osnoise_hist_data *data)
297{
298	int cpu;
299
300	if (params->no_summary)
301		return;
302
303	if (!params->no_index)
304		trace_seq_printf(trace->seq, "count:");
305
306	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
307		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
308			continue;
309
310		if (!data->hist[cpu].count)
311			continue;
312
313		trace_seq_printf(trace->seq, "%9d ", data->hist[cpu].count);
314	}
315	trace_seq_printf(trace->seq, "\n");
316
317	if (!params->no_index)
318		trace_seq_printf(trace->seq, "min:  ");
319
320	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
321		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
322			continue;
323
324		if (!data->hist[cpu].count)
325			continue;
326
327		trace_seq_printf(trace->seq, "%9llu ",	data->hist[cpu].min_sample);
328
329	}
330	trace_seq_printf(trace->seq, "\n");
331
332	if (!params->no_index)
333		trace_seq_printf(trace->seq, "avg:  ");
334
335	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
336		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
337			continue;
338
339		if (!data->hist[cpu].count)
340			continue;
341
342		if (data->hist[cpu].count)
343			trace_seq_printf(trace->seq, "%9.2f ",
344				((double) data->hist[cpu].sum_sample) / data->hist[cpu].count);
345		else
346			trace_seq_printf(trace->seq, "        - ");
347	}
348	trace_seq_printf(trace->seq, "\n");
349
350	if (!params->no_index)
351		trace_seq_printf(trace->seq, "max:  ");
352
353	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
354		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
355			continue;
356
357		if (!data->hist[cpu].count)
358			continue;
359
360		trace_seq_printf(trace->seq, "%9llu ", data->hist[cpu].max_sample);
361
362	}
363	trace_seq_printf(trace->seq, "\n");
364	trace_seq_do_printf(trace->seq);
365	trace_seq_reset(trace->seq);
366}
367
368/*
369 * osnoise_print_stats - print data for all CPUs
370 */
371static void
372osnoise_print_stats(struct osnoise_hist_params *params, struct osnoise_tool *tool)
373{
374	struct osnoise_hist_data *data = tool->data;
375	struct trace_instance *trace = &tool->trace;
376	int bucket, cpu;
377	int total;
378
379	osnoise_hist_header(tool);
380
381	for (bucket = 0; bucket < data->entries; bucket++) {
382		total = 0;
383
384		if (!params->no_index)
385			trace_seq_printf(trace->seq, "%-6d",
386					 bucket * data->bucket_size);
387
388		for (cpu = 0; cpu < data->nr_cpus; cpu++) {
389			if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
390				continue;
391
392			if (!data->hist[cpu].count)
393				continue;
394
395			total += data->hist[cpu].samples[bucket];
396			trace_seq_printf(trace->seq, "%9d ", data->hist[cpu].samples[bucket]);
397		}
398
399		if (total == 0 && !params->with_zeros) {
400			trace_seq_reset(trace->seq);
401			continue;
402		}
403
404		trace_seq_printf(trace->seq, "\n");
405		trace_seq_do_printf(trace->seq);
406		trace_seq_reset(trace->seq);
407	}
408
409	if (!params->no_index)
410		trace_seq_printf(trace->seq, "over: ");
411
412	for (cpu = 0; cpu < data->nr_cpus; cpu++) {
413		if (params->cpus && !CPU_ISSET(cpu, &params->monitored_cpus))
414			continue;
415
416		if (!data->hist[cpu].count)
417			continue;
418
419		trace_seq_printf(trace->seq, "%9d ",
420				 data->hist[cpu].samples[data->entries]);
421	}
422	trace_seq_printf(trace->seq, "\n");
423	trace_seq_do_printf(trace->seq);
424	trace_seq_reset(trace->seq);
425
426	osnoise_print_summary(params, trace, data);
427}
428
429/*
430 * osnoise_hist_usage - prints osnoise hist usage message
431 */
432static void osnoise_hist_usage(char *usage)
433{
434	int i;
435
436	static const char * const msg[] = {
437		"",
438		"  usage: rtla osnoise hist [-h] [-D] [-d s] [-a us] [-p us] [-r us] [-s us] [-S us] \\",
439		"	  [-T us] [-t[=file]] [-e sys[:event]] [--filter <filter>] [--trigger <trigger>] \\",
440		"	  [-c cpu-list] [-H cpu-list] [-P priority] [-b N] [-E N] [--no-header] [--no-summary] \\",
441		"	  [--no-index] [--with-zeros] [-C[=cgroup_name]]",
442		"",
443		"	  -h/--help: print this menu",
444		"	  -a/--auto: set automatic trace mode, stopping the session if argument in us sample is hit",
445		"	  -p/--period us: osnoise period in us",
446		"	  -r/--runtime us: osnoise runtime in us",
447		"	  -s/--stop us: stop trace if a single sample is higher than the argument in us",
448		"	  -S/--stop-total us: stop trace if the total sample is higher than the argument in us",
449		"	  -T/--threshold us: the minimum delta to be considered a noise",
450		"	  -c/--cpus cpu-list: list of cpus to run osnoise threads",
451		"	  -H/--house-keeping cpus: run rtla control threads only on the given cpus",
452		"	  -C/--cgroup[=cgroup_name]: set cgroup, if no cgroup_name is passed, the rtla's cgroup will be inherited",
453		"	  -d/--duration time[s|m|h|d]: duration of the session",
454		"	  -D/--debug: print debug info",
455		"	  -t/--trace[=file]: save the stopped trace to [file|osnoise_trace.txt]",
456		"	  -e/--event <sys:event>: enable the <sys:event> in the trace instance, multiple -e are allowed",
457		"	     --filter <filter>: enable a trace event filter to the previous -e event",
458		"	     --trigger <trigger>: enable a trace event trigger to the previous -e event",
459		"	  -b/--bucket-size N: set the histogram bucket size (default 1)",
460		"	  -E/--entries N: set the number of entries of the histogram (default 256)",
461		"	     --no-header: do not print header",
462		"	     --no-summary: do not print summary",
463		"	     --no-index: do not print index",
464		"	     --with-zeros: print zero only entries",
465		"	  -P/--priority o:prio|r:prio|f:prio|d:runtime:period: set scheduling parameters",
466		"		o:prio - use SCHED_OTHER with prio",
467		"		r:prio - use SCHED_RR with prio",
468		"		f:prio - use SCHED_FIFO with prio",
469		"		d:runtime[us|ms|s]:period[us|ms|s] - use SCHED_DEADLINE with runtime and period",
470		"						       in nanoseconds",
471		NULL,
472	};
473
474	if (usage)
475		fprintf(stderr, "%s\n", usage);
476
477	fprintf(stderr, "rtla osnoise hist: a per-cpu histogram of the OS noise (version %s)\n",
478			VERSION);
479
480	for (i = 0; msg[i]; i++)
481		fprintf(stderr, "%s\n", msg[i]);
482
483	if (usage)
484		exit(EXIT_FAILURE);
485
486	exit(EXIT_SUCCESS);
487}
488
489/*
490 * osnoise_hist_parse_args - allocs, parse and fill the cmd line parameters
491 */
492static struct osnoise_hist_params
493*osnoise_hist_parse_args(int argc, char *argv[])
494{
495	struct osnoise_hist_params *params;
496	struct trace_events *tevent;
497	int retval;
498	int c;
499
500	params = calloc(1, sizeof(*params));
501	if (!params)
502		exit(1);
503
504	/* display data in microseconds */
505	params->output_divisor = 1000;
506	params->bucket_size = 1;
507	params->entries = 256;
508
509	while (1) {
510		static struct option long_options[] = {
511			{"auto",		required_argument,	0, 'a'},
512			{"bucket-size",		required_argument,	0, 'b'},
513			{"entries",		required_argument,	0, 'E'},
514			{"cpus",		required_argument,	0, 'c'},
515			{"cgroup",		optional_argument,	0, 'C'},
516			{"debug",		no_argument,		0, 'D'},
517			{"duration",		required_argument,	0, 'd'},
518			{"house-keeping",	required_argument,		0, 'H'},
519			{"help",		no_argument,		0, 'h'},
520			{"period",		required_argument,	0, 'p'},
521			{"priority",		required_argument,	0, 'P'},
522			{"runtime",		required_argument,	0, 'r'},
523			{"stop",		required_argument,	0, 's'},
524			{"stop-total",		required_argument,	0, 'S'},
525			{"trace",		optional_argument,	0, 't'},
526			{"event",		required_argument,	0, 'e'},
527			{"threshold",		required_argument,	0, 'T'},
528			{"no-header",		no_argument,		0, '0'},
529			{"no-summary",		no_argument,		0, '1'},
530			{"no-index",		no_argument,		0, '2'},
531			{"with-zeros",		no_argument,		0, '3'},
532			{"trigger",		required_argument,	0, '4'},
533			{"filter",		required_argument,	0, '5'},
534			{0, 0, 0, 0}
535		};
536
537		/* getopt_long stores the option index here. */
538		int option_index = 0;
539
540		c = getopt_long(argc, argv, "a:c:C::b:d:e:E:DhH:p:P:r:s:S:t::T:01234:5:",
541				 long_options, &option_index);
542
543		/* detect the end of the options. */
544		if (c == -1)
545			break;
546
547		switch (c) {
548		case 'a':
549			/* set sample stop to auto_thresh */
550			params->stop_us = get_llong_from_str(optarg);
551
552			/* set sample threshold to 1 */
553			params->threshold = 1;
554
555			/* set trace */
556			params->trace_output = "osnoise_trace.txt";
557
558			break;
559		case 'b':
560			params->bucket_size = get_llong_from_str(optarg);
561			if ((params->bucket_size == 0) || (params->bucket_size >= 1000000))
562				osnoise_hist_usage("Bucket size needs to be > 0 and <= 1000000\n");
563			break;
564		case 'c':
565			retval = parse_cpu_set(optarg, &params->monitored_cpus);
566			if (retval)
567				osnoise_hist_usage("\nInvalid -c cpu list\n");
568			params->cpus = optarg;
569			break;
570		case 'C':
571			params->cgroup = 1;
572			if (!optarg) {
573				/* will inherit this cgroup */
574				params->cgroup_name = NULL;
575			} else if (*optarg == '=') {
576				/* skip the = */
577				params->cgroup_name = ++optarg;
578			}
579			break;
580		case 'D':
581			config_debug = 1;
582			break;
583		case 'd':
584			params->duration = parse_seconds_duration(optarg);
585			if (!params->duration)
586				osnoise_hist_usage("Invalid -D duration\n");
587			break;
588		case 'e':
589			tevent = trace_event_alloc(optarg);
590			if (!tevent) {
591				err_msg("Error alloc trace event");
592				exit(EXIT_FAILURE);
593			}
594
595			if (params->events)
596				tevent->next = params->events;
597
598			params->events = tevent;
599			break;
600		case 'E':
601			params->entries = get_llong_from_str(optarg);
602			if ((params->entries < 10) || (params->entries > 9999999))
603				osnoise_hist_usage("Entries must be > 10 and < 9999999\n");
604			break;
605		case 'h':
606		case '?':
607			osnoise_hist_usage(NULL);
608			break;
609		case 'H':
610			params->hk_cpus = 1;
611			retval = parse_cpu_set(optarg, &params->hk_cpu_set);
612			if (retval) {
613				err_msg("Error parsing house keeping CPUs\n");
614				exit(EXIT_FAILURE);
615			}
616			break;
617		case 'p':
618			params->period = get_llong_from_str(optarg);
619			if (params->period > 10000000)
620				osnoise_hist_usage("Period longer than 10 s\n");
621			break;
622		case 'P':
623			retval = parse_prio(optarg, &params->sched_param);
624			if (retval == -1)
625				osnoise_hist_usage("Invalid -P priority");
626			params->set_sched = 1;
627			break;
628		case 'r':
629			params->runtime = get_llong_from_str(optarg);
630			if (params->runtime < 100)
631				osnoise_hist_usage("Runtime shorter than 100 us\n");
632			break;
633		case 's':
634			params->stop_us = get_llong_from_str(optarg);
635			break;
636		case 'S':
637			params->stop_total_us = get_llong_from_str(optarg);
638			break;
639		case 'T':
640			params->threshold = get_llong_from_str(optarg);
641			break;
642		case 't':
643			if (optarg)
644				/* skip = */
645				params->trace_output = &optarg[1];
646			else
647				params->trace_output = "osnoise_trace.txt";
648			break;
649		case '0': /* no header */
650			params->no_header = 1;
651			break;
652		case '1': /* no summary */
653			params->no_summary = 1;
654			break;
655		case '2': /* no index */
656			params->no_index = 1;
657			break;
658		case '3': /* with zeros */
659			params->with_zeros = 1;
660			break;
661		case '4': /* trigger */
662			if (params->events) {
663				retval = trace_event_add_trigger(params->events, optarg);
664				if (retval) {
665					err_msg("Error adding trigger %s\n", optarg);
666					exit(EXIT_FAILURE);
667				}
668			} else {
669				osnoise_hist_usage("--trigger requires a previous -e\n");
670			}
671			break;
672		case '5': /* filter */
673			if (params->events) {
674				retval = trace_event_add_filter(params->events, optarg);
675				if (retval) {
676					err_msg("Error adding filter %s\n", optarg);
677					exit(EXIT_FAILURE);
678				}
679			} else {
680				osnoise_hist_usage("--filter requires a previous -e\n");
681			}
682			break;
683		default:
684			osnoise_hist_usage("Invalid option");
685		}
686	}
687
688	if (geteuid()) {
689		err_msg("rtla needs root permission\n");
690		exit(EXIT_FAILURE);
691	}
692
693	if (params->no_index && !params->with_zeros)
694		osnoise_hist_usage("no-index set and with-zeros not set - it does not make sense");
695
696	return params;
697}
698
699/*
700 * osnoise_hist_apply_config - apply the hist configs to the initialized tool
701 */
702static int
703osnoise_hist_apply_config(struct osnoise_tool *tool, struct osnoise_hist_params *params)
704{
705	int retval;
706
707	if (!params->sleep_time)
708		params->sleep_time = 1;
709
710	if (params->cpus) {
711		retval = osnoise_set_cpus(tool->context, params->cpus);
712		if (retval) {
713			err_msg("Failed to apply CPUs config\n");
714			goto out_err;
715		}
716	}
717
718	if (params->runtime || params->period) {
719		retval = osnoise_set_runtime_period(tool->context,
720						    params->runtime,
721						    params->period);
722		if (retval) {
723			err_msg("Failed to set runtime and/or period\n");
724			goto out_err;
725		}
726	}
727
728	if (params->stop_us) {
729		retval = osnoise_set_stop_us(tool->context, params->stop_us);
730		if (retval) {
731			err_msg("Failed to set stop us\n");
732			goto out_err;
733		}
734	}
735
736	if (params->stop_total_us) {
737		retval = osnoise_set_stop_total_us(tool->context, params->stop_total_us);
738		if (retval) {
739			err_msg("Failed to set stop total us\n");
740			goto out_err;
741		}
742	}
743
744	if (params->threshold) {
745		retval = osnoise_set_tracing_thresh(tool->context, params->threshold);
746		if (retval) {
747			err_msg("Failed to set tracing_thresh\n");
748			goto out_err;
749		}
750	}
751
752	if (params->hk_cpus) {
753		retval = sched_setaffinity(getpid(), sizeof(params->hk_cpu_set),
754					   &params->hk_cpu_set);
755		if (retval == -1) {
756			err_msg("Failed to set rtla to the house keeping CPUs\n");
757			goto out_err;
758		}
759	} else if (params->cpus) {
760		/*
761		 * Even if the user do not set a house-keeping CPU, try to
762		 * move rtla to a CPU set different to the one where the user
763		 * set the workload to run.
764		 *
765		 * No need to check results as this is an automatic attempt.
766		 */
767		auto_house_keeping(&params->monitored_cpus);
768	}
769
770	return 0;
771
772out_err:
773	return -1;
774}
775
776/*
777 * osnoise_init_hist - initialize a osnoise hist tool with parameters
778 */
779static struct osnoise_tool
780*osnoise_init_hist(struct osnoise_hist_params *params)
781{
782	struct osnoise_tool *tool;
783	int nr_cpus;
784
785	nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
786
787	tool = osnoise_init_tool("osnoise_hist");
788	if (!tool)
789		return NULL;
790
791	tool->data = osnoise_alloc_histogram(nr_cpus, params->entries, params->bucket_size);
792	if (!tool->data)
793		goto out_err;
794
795	tool->params = params;
796
797	return tool;
798
799out_err:
800	osnoise_destroy_tool(tool);
801	return NULL;
802}
803
804static int stop_tracing;
805static void stop_hist(int sig)
806{
807	stop_tracing = 1;
808}
809
810/*
811 * osnoise_hist_set_signals - handles the signal to stop the tool
812 */
813static void
814osnoise_hist_set_signals(struct osnoise_hist_params *params)
815{
816	signal(SIGINT, stop_hist);
817	if (params->duration) {
818		signal(SIGALRM, stop_hist);
819		alarm(params->duration);
820	}
821}
822
823int osnoise_hist_main(int argc, char *argv[])
824{
825	struct osnoise_hist_params *params;
826	struct osnoise_tool *record = NULL;
827	struct osnoise_tool *tool = NULL;
828	struct trace_instance *trace;
829	int return_value = 1;
830	int retval;
831
832	params = osnoise_hist_parse_args(argc, argv);
833	if (!params)
834		exit(1);
835
836	tool = osnoise_init_hist(params);
837	if (!tool) {
838		err_msg("Could not init osnoise hist\n");
839		goto out_exit;
840	}
841
842	retval = osnoise_hist_apply_config(tool, params);
843	if (retval) {
844		err_msg("Could not apply config\n");
845		goto out_destroy;
846	}
847
848	trace = &tool->trace;
849
850	retval = enable_osnoise(trace);
851	if (retval) {
852		err_msg("Failed to enable osnoise tracer\n");
853		goto out_destroy;
854	}
855
856	retval = osnoise_init_trace_hist(tool);
857	if (retval)
858		goto out_destroy;
859
860	if (params->set_sched) {
861		retval = set_comm_sched_attr("osnoise/", &params->sched_param);
862		if (retval) {
863			err_msg("Failed to set sched parameters\n");
864			goto out_free;
865		}
866	}
867
868	if (params->cgroup) {
869		retval = set_comm_cgroup("timerlat/", params->cgroup_name);
870		if (!retval) {
871			err_msg("Failed to move threads to cgroup\n");
872			goto out_free;
873		}
874	}
875
876	if (params->trace_output) {
877		record = osnoise_init_trace_tool("osnoise");
878		if (!record) {
879			err_msg("Failed to enable the trace instance\n");
880			goto out_free;
881		}
882
883		if (params->events) {
884			retval = trace_events_enable(&record->trace, params->events);
885			if (retval)
886				goto out_hist;
887		}
888
 
889	}
890
891	/*
892	 * Start the tracer here, after having set all instances.
893	 *
894	 * Let the trace instance start first for the case of hitting a stop
895	 * tracing while enabling other instances. The trace instance is the
896	 * one with most valuable information.
897	 */
898	if (params->trace_output)
899		trace_instance_start(&record->trace);
900	trace_instance_start(trace);
901
902	tool->start_time = time(NULL);
903	osnoise_hist_set_signals(params);
904
905	while (!stop_tracing) {
906		sleep(params->sleep_time);
907
908		retval = tracefs_iterate_raw_events(trace->tep,
909						    trace->inst,
910						    NULL,
911						    0,
912						    collect_registered_events,
913						    trace);
914		if (retval < 0) {
915			err_msg("Error iterating on events\n");
916			goto out_hist;
917		}
918
919		if (trace_is_off(&tool->trace, &record->trace))
920			break;
921	}
922
923	osnoise_read_trace_hist(tool);
924
925	osnoise_print_stats(params, tool);
926
927	return_value = 0;
928
929	if (trace_is_off(&tool->trace, &record->trace)) {
930		printf("rtla osnoise hit stop tracing\n");
931		if (params->trace_output) {
932			printf("  Saving trace to %s\n", params->trace_output);
933			save_trace_to_file(record->trace.inst, params->trace_output);
934		}
935	}
936
937out_hist:
938	trace_events_destroy(&record->trace, params->events);
939	params->events = NULL;
940out_free:
941	osnoise_free_histogram(tool->data);
942out_destroy:
943	osnoise_destroy_tool(record);
944	osnoise_destroy_tool(tool);
945	free(params);
946out_exit:
947	exit(return_value);
948}