xref: /linux/tools/perf/builtin-ftrace.c (revision 430a6dfe41d329001a1edf2338cff8ac5ce841d4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * builtin-ftrace.c
4  *
5  * Copyright (c) 2013  LG Electronics,  Namhyung Kim <namhyung@kernel.org>
6  * Copyright (c) 2020  Changbin Du <changbin.du@gmail.com>, significant enhancement.
7  */
8 
9 #include "builtin.h"
10 
11 #include <errno.h>
12 #include <unistd.h>
13 #include <signal.h>
14 #include <stdlib.h>
15 #include <fcntl.h>
16 #include <inttypes.h>
17 #include <math.h>
18 #include <poll.h>
19 #include <ctype.h>
20 #include <linux/capability.h>
21 #include <linux/string.h>
22 
23 #include "debug.h"
24 #include <subcmd/pager.h>
25 #include <subcmd/parse-options.h>
26 #include <api/io.h>
27 #include <api/fs/tracing_path.h>
28 #include "evlist.h"
29 #include "target.h"
30 #include "cpumap.h"
31 #include "hashmap.h"
32 #include "thread_map.h"
33 #include "strfilter.h"
34 #include "util/cap.h"
35 #include "util/config.h"
36 #include "util/ftrace.h"
37 #include "util/stat.h"
38 #include "util/units.h"
39 #include "util/parse-sublevel-options.h"
40 
41 #define DEFAULT_TRACER  "function_graph"
42 
43 static volatile sig_atomic_t workload_exec_errno;
44 static volatile sig_atomic_t done;
45 
46 static struct stats latency_stats;  /* for tracepoints */
47 
48 static void sig_handler(int sig __maybe_unused)
49 {
50 	done = true;
51 }
52 
53 /*
54  * evlist__prepare_workload will send a SIGUSR1 if the fork fails, since
55  * we asked by setting its exec_error to the function below,
56  * ftrace__workload_exec_failed_signal.
57  *
58  * XXX We need to handle this more appropriately, emitting an error, etc.
59  */
60 static void ftrace__workload_exec_failed_signal(int signo __maybe_unused,
61 						siginfo_t *info __maybe_unused,
62 						void *ucontext __maybe_unused)
63 {
64 	workload_exec_errno = info->si_value.sival_int;
65 	done = true;
66 }
67 
68 static bool check_ftrace_capable(void)
69 {
70 	bool used_root;
71 
72 	if (perf_cap__capable(CAP_PERFMON, &used_root))
73 		return true;
74 
75 	if (!used_root && perf_cap__capable(CAP_SYS_ADMIN, &used_root))
76 		return true;
77 
78 	pr_err("ftrace only works for %s!\n",
79 		used_root ? "root"
80 			  : "users with the CAP_PERFMON or CAP_SYS_ADMIN capability"
81 		);
82 	return false;
83 }
84 
85 static bool is_ftrace_supported(void)
86 {
87 	char *file;
88 	bool supported = false;
89 
90 	file = get_tracing_file("set_ftrace_pid");
91 	if (!file) {
92 		pr_debug("cannot get tracing file set_ftrace_pid\n");
93 		return false;
94 	}
95 
96 	if (!access(file, F_OK))
97 		supported = true;
98 
99 	put_tracing_file(file);
100 	return supported;
101 }
102 
103 static int __write_tracing_file(const char *name, const char *val, bool append)
104 {
105 	char *file;
106 	int fd, ret = -1;
107 	ssize_t size = strlen(val);
108 	int flags = O_WRONLY;
109 	char errbuf[512];
110 	char *val_copy;
111 
112 	file = get_tracing_file(name);
113 	if (!file) {
114 		pr_debug("cannot get tracing file: %s\n", name);
115 		return -1;
116 	}
117 
118 	if (append)
119 		flags |= O_APPEND;
120 	else
121 		flags |= O_TRUNC;
122 
123 	fd = open(file, flags);
124 	if (fd < 0) {
125 		pr_debug("cannot open tracing file: %s: %s\n",
126 			 name, str_error_r(errno, errbuf, sizeof(errbuf)));
127 		goto out;
128 	}
129 
130 	/*
131 	 * Copy the original value and append a '\n'. Without this,
132 	 * the kernel can hide possible errors.
133 	 */
134 	val_copy = strdup(val);
135 	if (!val_copy)
136 		goto out_close;
137 	val_copy[size] = '\n';
138 
139 	if (write(fd, val_copy, size + 1) == size + 1)
140 		ret = 0;
141 	else
142 		pr_debug("write '%s' to tracing/%s failed: %s\n",
143 			 val, name, str_error_r(errno, errbuf, sizeof(errbuf)));
144 
145 	free(val_copy);
146 out_close:
147 	close(fd);
148 out:
149 	put_tracing_file(file);
150 	return ret;
151 }
152 
153 static int write_tracing_file(const char *name, const char *val)
154 {
155 	return __write_tracing_file(name, val, false);
156 }
157 
158 static int append_tracing_file(const char *name, const char *val)
159 {
160 	return __write_tracing_file(name, val, true);
161 }
162 
163 static int read_tracing_file_to_stdout(const char *name)
164 {
165 	char buf[4096];
166 	char *file;
167 	int fd;
168 	int ret = -1;
169 
170 	file = get_tracing_file(name);
171 	if (!file) {
172 		pr_debug("cannot get tracing file: %s\n", name);
173 		return -1;
174 	}
175 
176 	fd = open(file, O_RDONLY);
177 	if (fd < 0) {
178 		pr_debug("cannot open tracing file: %s: %s\n",
179 			 name, str_error_r(errno, buf, sizeof(buf)));
180 		goto out;
181 	}
182 
183 	/* read contents to stdout */
184 	while (true) {
185 		int n = read(fd, buf, sizeof(buf));
186 		if (n == 0)
187 			break;
188 		else if (n < 0)
189 			goto out_close;
190 
191 		if (fwrite(buf, n, 1, stdout) != 1)
192 			goto out_close;
193 	}
194 	ret = 0;
195 
196 out_close:
197 	close(fd);
198 out:
199 	put_tracing_file(file);
200 	return ret;
201 }
202 
203 static int read_tracing_file_by_line(const char *name,
204 				     void (*cb)(char *str, void *arg),
205 				     void *cb_arg)
206 {
207 	char *line = NULL;
208 	size_t len = 0;
209 	char *file;
210 	FILE *fp;
211 
212 	file = get_tracing_file(name);
213 	if (!file) {
214 		pr_debug("cannot get tracing file: %s\n", name);
215 		return -1;
216 	}
217 
218 	fp = fopen(file, "r");
219 	if (fp == NULL) {
220 		pr_debug("cannot open tracing file: %s\n", name);
221 		put_tracing_file(file);
222 		return -1;
223 	}
224 
225 	while (getline(&line, &len, fp) != -1) {
226 		cb(line, cb_arg);
227 	}
228 
229 	if (line)
230 		free(line);
231 
232 	fclose(fp);
233 	put_tracing_file(file);
234 	return 0;
235 }
236 
237 static int write_tracing_file_int(const char *name, int value)
238 {
239 	char buf[16];
240 
241 	snprintf(buf, sizeof(buf), "%d", value);
242 	if (write_tracing_file(name, buf) < 0)
243 		return -1;
244 
245 	return 0;
246 }
247 
248 static int write_tracing_option_file(const char *name, const char *val)
249 {
250 	char *file;
251 	int ret;
252 
253 	if (asprintf(&file, "options/%s", name) < 0)
254 		return -1;
255 
256 	ret = __write_tracing_file(file, val, false);
257 	free(file);
258 	return ret;
259 }
260 
261 static int reset_tracing_cpu(void);
262 static void reset_tracing_filters(void);
263 
264 static void reset_tracing_options(struct perf_ftrace *ftrace __maybe_unused)
265 {
266 	write_tracing_option_file("function-fork", "0");
267 	write_tracing_option_file("func_stack_trace", "0");
268 	write_tracing_option_file("sleep-time", "1");
269 	write_tracing_option_file("funcgraph-irqs", "1");
270 	write_tracing_option_file("funcgraph-proc", "0");
271 	write_tracing_option_file("funcgraph-abstime", "0");
272 	write_tracing_option_file("funcgraph-tail", "0");
273 	write_tracing_option_file("latency-format", "0");
274 	write_tracing_option_file("irq-info", "0");
275 }
276 
277 static int reset_tracing_files(struct perf_ftrace *ftrace __maybe_unused)
278 {
279 	if (write_tracing_file("tracing_on", "0") < 0)
280 		return -1;
281 
282 	if (write_tracing_file("current_tracer", "nop") < 0)
283 		return -1;
284 
285 	if (write_tracing_file("set_ftrace_pid", " ") < 0)
286 		return -1;
287 
288 	if (reset_tracing_cpu() < 0)
289 		return -1;
290 
291 	if (write_tracing_file("max_graph_depth", "0") < 0)
292 		return -1;
293 
294 	if (write_tracing_file("tracing_thresh", "0") < 0)
295 		return -1;
296 
297 	reset_tracing_filters();
298 	reset_tracing_options(ftrace);
299 	return 0;
300 }
301 
302 static int set_tracing_pid(struct perf_ftrace *ftrace)
303 {
304 	int i;
305 	char buf[16];
306 
307 	if (target__has_cpu(&ftrace->target))
308 		return 0;
309 
310 	for (i = 0; i < perf_thread_map__nr(ftrace->evlist->core.threads); i++) {
311 		scnprintf(buf, sizeof(buf), "%d",
312 			  perf_thread_map__pid(ftrace->evlist->core.threads, i));
313 		if (append_tracing_file("set_ftrace_pid", buf) < 0)
314 			return -1;
315 	}
316 	return 0;
317 }
318 
319 static int set_tracing_cpumask(struct perf_cpu_map *cpumap)
320 {
321 	char *cpumask;
322 	size_t mask_size;
323 	int ret;
324 	int last_cpu;
325 
326 	last_cpu = perf_cpu_map__cpu(cpumap, perf_cpu_map__nr(cpumap) - 1).cpu;
327 	mask_size = last_cpu / 4 + 2; /* one more byte for EOS */
328 	mask_size += last_cpu / 32; /* ',' is needed for every 32th cpus */
329 
330 	cpumask = malloc(mask_size);
331 	if (cpumask == NULL) {
332 		pr_debug("failed to allocate cpu mask\n");
333 		return -1;
334 	}
335 
336 	cpu_map__snprint_mask(cpumap, cpumask, mask_size);
337 
338 	ret = write_tracing_file("tracing_cpumask", cpumask);
339 
340 	free(cpumask);
341 	return ret;
342 }
343 
344 static int set_tracing_cpu(struct perf_ftrace *ftrace)
345 {
346 	struct perf_cpu_map *cpumap = ftrace->evlist->core.user_requested_cpus;
347 
348 	if (!target__has_cpu(&ftrace->target))
349 		return 0;
350 
351 	return set_tracing_cpumask(cpumap);
352 }
353 
354 static int set_tracing_func_stack_trace(struct perf_ftrace *ftrace)
355 {
356 	if (!ftrace->func_stack_trace)
357 		return 0;
358 
359 	if (write_tracing_option_file("func_stack_trace", "1") < 0)
360 		return -1;
361 
362 	return 0;
363 }
364 
365 static int set_tracing_func_irqinfo(struct perf_ftrace *ftrace)
366 {
367 	if (!ftrace->func_irq_info)
368 		return 0;
369 
370 	if (write_tracing_option_file("irq-info", "1") < 0)
371 		return -1;
372 
373 	return 0;
374 }
375 
376 static int reset_tracing_cpu(void)
377 {
378 	struct perf_cpu_map *cpumap = perf_cpu_map__new_online_cpus();
379 	int ret;
380 
381 	ret = set_tracing_cpumask(cpumap);
382 	perf_cpu_map__put(cpumap);
383 	return ret;
384 }
385 
386 static int __set_tracing_filter(const char *filter_file, struct list_head *funcs)
387 {
388 	struct filter_entry *pos;
389 
390 	list_for_each_entry(pos, funcs, list) {
391 		if (append_tracing_file(filter_file, pos->name) < 0)
392 			return -1;
393 	}
394 
395 	return 0;
396 }
397 
398 static int set_tracing_filters(struct perf_ftrace *ftrace)
399 {
400 	int ret;
401 
402 	ret = __set_tracing_filter("set_ftrace_filter", &ftrace->filters);
403 	if (ret < 0)
404 		return ret;
405 
406 	ret = __set_tracing_filter("set_ftrace_notrace", &ftrace->notrace);
407 	if (ret < 0)
408 		return ret;
409 
410 	ret = __set_tracing_filter("set_graph_function", &ftrace->graph_funcs);
411 	if (ret < 0)
412 		return ret;
413 
414 	/* old kernels do not have this filter */
415 	__set_tracing_filter("set_graph_notrace", &ftrace->nograph_funcs);
416 
417 	return ret;
418 }
419 
420 static void reset_tracing_filters(void)
421 {
422 	write_tracing_file("set_ftrace_filter", " ");
423 	write_tracing_file("set_ftrace_notrace", " ");
424 	write_tracing_file("set_graph_function", " ");
425 	write_tracing_file("set_graph_notrace", " ");
426 }
427 
428 static int set_tracing_depth(struct perf_ftrace *ftrace)
429 {
430 	if (ftrace->graph_depth == 0)
431 		return 0;
432 
433 	if (ftrace->graph_depth < 0) {
434 		pr_err("invalid graph depth: %d\n", ftrace->graph_depth);
435 		return -1;
436 	}
437 
438 	if (write_tracing_file_int("max_graph_depth", ftrace->graph_depth) < 0)
439 		return -1;
440 
441 	return 0;
442 }
443 
444 static int set_tracing_percpu_buffer_size(struct perf_ftrace *ftrace)
445 {
446 	int ret;
447 
448 	if (ftrace->percpu_buffer_size == 0)
449 		return 0;
450 
451 	ret = write_tracing_file_int("buffer_size_kb",
452 				     ftrace->percpu_buffer_size / 1024);
453 	if (ret < 0)
454 		return ret;
455 
456 	return 0;
457 }
458 
459 static int set_tracing_trace_inherit(struct perf_ftrace *ftrace)
460 {
461 	if (!ftrace->inherit)
462 		return 0;
463 
464 	if (write_tracing_option_file("function-fork", "1") < 0)
465 		return -1;
466 
467 	return 0;
468 }
469 
470 static int set_tracing_sleep_time(struct perf_ftrace *ftrace)
471 {
472 	if (!ftrace->graph_nosleep_time)
473 		return 0;
474 
475 	if (write_tracing_option_file("sleep-time", "0") < 0)
476 		return -1;
477 
478 	return 0;
479 }
480 
481 static int set_tracing_funcgraph_irqs(struct perf_ftrace *ftrace)
482 {
483 	if (!ftrace->graph_noirqs)
484 		return 0;
485 
486 	if (write_tracing_option_file("funcgraph-irqs", "0") < 0)
487 		return -1;
488 
489 	return 0;
490 }
491 
492 static int set_tracing_funcgraph_verbose(struct perf_ftrace *ftrace)
493 {
494 	if (!ftrace->graph_verbose)
495 		return 0;
496 
497 	if (write_tracing_option_file("funcgraph-proc", "1") < 0)
498 		return -1;
499 
500 	if (write_tracing_option_file("funcgraph-abstime", "1") < 0)
501 		return -1;
502 
503 	if (write_tracing_option_file("latency-format", "1") < 0)
504 		return -1;
505 
506 	return 0;
507 }
508 
509 static int set_tracing_funcgraph_tail(struct perf_ftrace *ftrace)
510 {
511 	if (!ftrace->graph_tail)
512 		return 0;
513 
514 	if (write_tracing_option_file("funcgraph-tail", "1") < 0)
515 		return -1;
516 
517 	return 0;
518 }
519 
520 static int set_tracing_thresh(struct perf_ftrace *ftrace)
521 {
522 	int ret;
523 
524 	if (ftrace->graph_thresh == 0)
525 		return 0;
526 
527 	ret = write_tracing_file_int("tracing_thresh", ftrace->graph_thresh);
528 	if (ret < 0)
529 		return ret;
530 
531 	return 0;
532 }
533 
534 static int set_tracing_options(struct perf_ftrace *ftrace)
535 {
536 	if (set_tracing_pid(ftrace) < 0) {
537 		pr_err("failed to set ftrace pid\n");
538 		return -1;
539 	}
540 
541 	if (set_tracing_cpu(ftrace) < 0) {
542 		pr_err("failed to set tracing cpumask\n");
543 		return -1;
544 	}
545 
546 	if (set_tracing_func_stack_trace(ftrace) < 0) {
547 		pr_err("failed to set tracing option func_stack_trace\n");
548 		return -1;
549 	}
550 
551 	if (set_tracing_func_irqinfo(ftrace) < 0) {
552 		pr_err("failed to set tracing option irq-info\n");
553 		return -1;
554 	}
555 
556 	if (set_tracing_filters(ftrace) < 0) {
557 		pr_err("failed to set tracing filters\n");
558 		return -1;
559 	}
560 
561 	if (set_tracing_depth(ftrace) < 0) {
562 		pr_err("failed to set graph depth\n");
563 		return -1;
564 	}
565 
566 	if (set_tracing_percpu_buffer_size(ftrace) < 0) {
567 		pr_err("failed to set tracing per-cpu buffer size\n");
568 		return -1;
569 	}
570 
571 	if (set_tracing_trace_inherit(ftrace) < 0) {
572 		pr_err("failed to set tracing option function-fork\n");
573 		return -1;
574 	}
575 
576 	if (set_tracing_sleep_time(ftrace) < 0) {
577 		pr_err("failed to set tracing option sleep-time\n");
578 		return -1;
579 	}
580 
581 	if (set_tracing_funcgraph_irqs(ftrace) < 0) {
582 		pr_err("failed to set tracing option funcgraph-irqs\n");
583 		return -1;
584 	}
585 
586 	if (set_tracing_funcgraph_verbose(ftrace) < 0) {
587 		pr_err("failed to set tracing option funcgraph-proc/funcgraph-abstime\n");
588 		return -1;
589 	}
590 
591 	if (set_tracing_thresh(ftrace) < 0) {
592 		pr_err("failed to set tracing thresh\n");
593 		return -1;
594 	}
595 
596 	if (set_tracing_funcgraph_tail(ftrace) < 0) {
597 		pr_err("failed to set tracing option funcgraph-tail\n");
598 		return -1;
599 	}
600 
601 	return 0;
602 }
603 
604 static void select_tracer(struct perf_ftrace *ftrace)
605 {
606 	bool graph = !list_empty(&ftrace->graph_funcs) ||
607 		     !list_empty(&ftrace->nograph_funcs);
608 	bool func = !list_empty(&ftrace->filters) ||
609 		    !list_empty(&ftrace->notrace);
610 
611 	/* The function_graph has priority over function tracer. */
612 	if (graph)
613 		ftrace->tracer = "function_graph";
614 	else if (func)
615 		ftrace->tracer = "function";
616 	/* Otherwise, the default tracer is used. */
617 
618 	pr_debug("%s tracer is used\n", ftrace->tracer);
619 }
620 
621 static int __cmd_ftrace(struct perf_ftrace *ftrace)
622 {
623 	char *trace_file;
624 	int trace_fd;
625 	char buf[4096];
626 	struct pollfd pollfd = {
627 		.events = POLLIN,
628 	};
629 
630 	select_tracer(ftrace);
631 
632 	if (reset_tracing_files(ftrace) < 0) {
633 		pr_err("failed to reset ftrace\n");
634 		goto out;
635 	}
636 
637 	/* reset ftrace buffer */
638 	if (write_tracing_file("trace", "0") < 0)
639 		goto out;
640 
641 	if (set_tracing_options(ftrace) < 0)
642 		goto out_reset;
643 
644 	if (write_tracing_file("current_tracer", ftrace->tracer) < 0) {
645 		pr_err("failed to set current_tracer to %s\n", ftrace->tracer);
646 		goto out_reset;
647 	}
648 
649 	setup_pager();
650 
651 	trace_file = get_tracing_file("trace_pipe");
652 	if (!trace_file) {
653 		pr_err("failed to open trace_pipe\n");
654 		goto out_reset;
655 	}
656 
657 	trace_fd = open(trace_file, O_RDONLY);
658 
659 	put_tracing_file(trace_file);
660 
661 	if (trace_fd < 0) {
662 		pr_err("failed to open trace_pipe\n");
663 		goto out_reset;
664 	}
665 
666 	fcntl(trace_fd, F_SETFL, O_NONBLOCK);
667 	pollfd.fd = trace_fd;
668 
669 	/* display column headers */
670 	read_tracing_file_to_stdout("trace");
671 
672 	if (!ftrace->target.initial_delay) {
673 		if (write_tracing_file("tracing_on", "1") < 0) {
674 			pr_err("can't enable tracing\n");
675 			goto out_close_fd;
676 		}
677 	}
678 
679 	evlist__start_workload(ftrace->evlist);
680 
681 	if (ftrace->target.initial_delay > 0) {
682 		usleep(ftrace->target.initial_delay * 1000);
683 		if (write_tracing_file("tracing_on", "1") < 0) {
684 			pr_err("can't enable tracing\n");
685 			goto out_close_fd;
686 		}
687 	}
688 
689 	while (!done) {
690 		if (poll(&pollfd, 1, -1) < 0)
691 			break;
692 
693 		if (pollfd.revents & POLLIN) {
694 			int n = read(trace_fd, buf, sizeof(buf));
695 			if (n < 0)
696 				break;
697 			if (fwrite(buf, n, 1, stdout) != 1)
698 				break;
699 			/* flush output since stdout is in full buffering mode due to pager */
700 			fflush(stdout);
701 		}
702 	}
703 
704 	write_tracing_file("tracing_on", "0");
705 
706 	if (workload_exec_errno) {
707 		const char *emsg = str_error_r(workload_exec_errno, buf, sizeof(buf));
708 		/* flush stdout first so below error msg appears at the end. */
709 		fflush(stdout);
710 		pr_err("workload failed: %s\n", emsg);
711 		goto out_close_fd;
712 	}
713 
714 	/* read remaining buffer contents */
715 	while (true) {
716 		int n = read(trace_fd, buf, sizeof(buf));
717 		if (n <= 0)
718 			break;
719 		if (fwrite(buf, n, 1, stdout) != 1)
720 			break;
721 	}
722 
723 out_close_fd:
724 	close(trace_fd);
725 out_reset:
726 	reset_tracing_files(ftrace);
727 out:
728 	return (done && !workload_exec_errno) ? 0 : -1;
729 }
730 
731 static void make_histogram(struct perf_ftrace *ftrace, int buckets[],
732 			   char *buf, size_t len, char *linebuf)
733 {
734 	int min_latency = ftrace->min_latency;
735 	int max_latency = ftrace->max_latency;
736 	char *p, *q;
737 	char *unit;
738 	double num;
739 	int i;
740 
741 	/* ensure NUL termination */
742 	buf[len] = '\0';
743 
744 	/* handle data line by line */
745 	for (p = buf; (q = strchr(p, '\n')) != NULL; p = q + 1) {
746 		*q = '\0';
747 		/* move it to the line buffer */
748 		strcat(linebuf, p);
749 
750 		/*
751 		 * parse trace output to get function duration like in
752 		 *
753 		 * # tracer: function_graph
754 		 * #
755 		 * # CPU  DURATION                  FUNCTION CALLS
756 		 * # |     |   |                     |   |   |   |
757 		 *  1) + 10.291 us   |  do_filp_open();
758 		 *  1)   4.889 us    |  do_filp_open();
759 		 *  1)   6.086 us    |  do_filp_open();
760 		 *
761 		 */
762 		if (linebuf[0] == '#')
763 			goto next;
764 
765 		/* ignore CPU */
766 		p = strchr(linebuf, ')');
767 		if (p == NULL)
768 			p = linebuf;
769 
770 		while (*p && !isdigit(*p) && (*p != '|'))
771 			p++;
772 
773 		/* no duration */
774 		if (*p == '\0' || *p == '|')
775 			goto next;
776 
777 		num = strtod(p, &unit);
778 		if (!unit || strncmp(unit, " us", 3))
779 			goto next;
780 
781 		if (ftrace->use_nsec)
782 			num *= 1000;
783 
784 		i = 0;
785 		if (num < min_latency)
786 			goto do_inc;
787 
788 		num -= min_latency;
789 
790 		if (!ftrace->bucket_range) {
791 			i = log2(num);
792 			if (i < 0)
793 				i = 0;
794 		} else {
795 			// Less than 1 unit (ms or ns), or, in the future,
796 			// than the min latency desired.
797 			if (num > 0) // 1st entry: [ 1 unit .. bucket_range units ]
798 				i = num / ftrace->bucket_range + 1;
799 		}
800 		if (i >= NUM_BUCKET || num >= max_latency - min_latency)
801 			i = NUM_BUCKET - 1;
802 
803 		num += min_latency;
804 do_inc:
805 		buckets[i]++;
806 		update_stats(&latency_stats, num);
807 
808 next:
809 		/* empty the line buffer for the next output  */
810 		linebuf[0] = '\0';
811 	}
812 
813 	/* preserve any remaining output (before newline) */
814 	strcat(linebuf, p);
815 }
816 
817 static void display_histogram(struct perf_ftrace *ftrace, int buckets[])
818 {
819 	int min_latency = ftrace->min_latency;
820 	bool use_nsec = ftrace->use_nsec;
821 	int i;
822 	int total = 0;
823 	int bar_total = 46;  /* to fit in 80 column */
824 	char bar[] = "###############################################";
825 	int bar_len;
826 
827 	for (i = 0; i < NUM_BUCKET; i++)
828 		total += buckets[i];
829 
830 	if (total == 0) {
831 		printf("No data found\n");
832 		return;
833 	}
834 
835 	printf("# %14s | %10s | %-*s |\n",
836 	       "  DURATION    ", "COUNT", bar_total, "GRAPH");
837 
838 	bar_len = buckets[0] * bar_total / total;
839 
840 	printf("  %4d - %4d %s | %10d | %.*s%*s |\n",
841 	       0, min_latency, use_nsec ? "ns" : "us",
842 	       buckets[0], bar_len, bar, bar_total - bar_len, "");
843 
844 	for (i = 1; i < NUM_BUCKET - 1; i++) {
845 		unsigned int start, stop;
846 		const char *unit = use_nsec ? "ns" : "us";
847 
848 		if (!ftrace->bucket_range) {
849 			start = (1 << (i - 1));
850 			stop  = 1 << i;
851 
852 			if (start >= 1024) {
853 				start >>= 10;
854 				stop >>= 10;
855 				unit = use_nsec ? "us" : "ms";
856 			}
857 		} else {
858 			start = (i - 1) * ftrace->bucket_range + min_latency;
859 			stop  = i * ftrace->bucket_range + min_latency;
860 
861 			if (start >= ftrace->max_latency)
862 				break;
863 			if (stop > ftrace->max_latency)
864 				stop = ftrace->max_latency;
865 
866 			if (start >= 1000) {
867 				double dstart = start / 1000.0,
868 				       dstop  = stop / 1000.0;
869 				printf("  %4.2f - %-4.2f", dstart, dstop);
870 				unit = use_nsec ? "us" : "ms";
871 				goto print_bucket_info;
872 			}
873 		}
874 
875 		printf("  %4d - %4d", start, stop);
876 print_bucket_info:
877 		bar_len = buckets[i] * bar_total / total;
878 		printf(" %s | %10d | %.*s%*s |\n", unit, buckets[i], bar_len, bar,
879 		       bar_total - bar_len, "");
880 	}
881 
882 	bar_len = buckets[NUM_BUCKET - 1] * bar_total / total;
883 	if (!ftrace->bucket_range) {
884 		printf("  %4d - %-4s %s", 1, "...", use_nsec ? "ms" : "s ");
885 	} else {
886 		unsigned int upper_outlier = (NUM_BUCKET - 2) * ftrace->bucket_range + min_latency;
887 		if (upper_outlier > ftrace->max_latency)
888 			upper_outlier = ftrace->max_latency;
889 
890 		if (upper_outlier >= 1000) {
891 			double dstart = upper_outlier / 1000.0;
892 
893 			printf("  %4.2f - %-4s %s", dstart, "...", use_nsec ? "us" : "ms");
894 		} else {
895 			printf("  %4d - %4s %s", upper_outlier, "...", use_nsec ? "ns" : "us");
896 		}
897 	}
898 	printf(" | %10d | %.*s%*s |\n", buckets[NUM_BUCKET - 1],
899 	       bar_len, bar, bar_total - bar_len, "");
900 
901 	printf("\n# statistics  (in %s)\n", ftrace->use_nsec ? "nsec" : "usec");
902 	printf("  total time: %20.0f\n", latency_stats.mean * latency_stats.n);
903 	printf("    avg time: %20.0f\n", latency_stats.mean);
904 	printf("    max time: %20"PRIu64"\n", latency_stats.max);
905 	printf("    min time: %20"PRIu64"\n", latency_stats.min);
906 	printf("       count: %20.0f\n", latency_stats.n);
907 }
908 
909 static int prepare_func_latency(struct perf_ftrace *ftrace)
910 {
911 	char *trace_file;
912 	int fd;
913 
914 	if (ftrace->target.use_bpf)
915 		return perf_ftrace__latency_prepare_bpf(ftrace);
916 
917 	if (reset_tracing_files(ftrace) < 0) {
918 		pr_err("failed to reset ftrace\n");
919 		return -1;
920 	}
921 
922 	/* reset ftrace buffer */
923 	if (write_tracing_file("trace", "0") < 0)
924 		return -1;
925 
926 	if (set_tracing_options(ftrace) < 0)
927 		return -1;
928 
929 	/* force to use the function_graph tracer to track duration */
930 	if (write_tracing_file("current_tracer", "function_graph") < 0) {
931 		pr_err("failed to set current_tracer to function_graph\n");
932 		return -1;
933 	}
934 
935 	trace_file = get_tracing_file("trace_pipe");
936 	if (!trace_file) {
937 		pr_err("failed to open trace_pipe\n");
938 		return -1;
939 	}
940 
941 	fd = open(trace_file, O_RDONLY);
942 	if (fd < 0)
943 		pr_err("failed to open trace_pipe\n");
944 
945 	init_stats(&latency_stats);
946 
947 	put_tracing_file(trace_file);
948 	return fd;
949 }
950 
951 static int start_func_latency(struct perf_ftrace *ftrace)
952 {
953 	if (ftrace->target.use_bpf)
954 		return perf_ftrace__latency_start_bpf(ftrace);
955 
956 	if (write_tracing_file("tracing_on", "1") < 0) {
957 		pr_err("can't enable tracing\n");
958 		return -1;
959 	}
960 
961 	return 0;
962 }
963 
964 static int stop_func_latency(struct perf_ftrace *ftrace)
965 {
966 	if (ftrace->target.use_bpf)
967 		return perf_ftrace__latency_stop_bpf(ftrace);
968 
969 	write_tracing_file("tracing_on", "0");
970 	return 0;
971 }
972 
973 static int read_func_latency(struct perf_ftrace *ftrace, int buckets[])
974 {
975 	if (ftrace->target.use_bpf)
976 		return perf_ftrace__latency_read_bpf(ftrace, buckets, &latency_stats);
977 
978 	return 0;
979 }
980 
981 static int cleanup_func_latency(struct perf_ftrace *ftrace)
982 {
983 	if (ftrace->target.use_bpf)
984 		return perf_ftrace__latency_cleanup_bpf(ftrace);
985 
986 	reset_tracing_files(ftrace);
987 	return 0;
988 }
989 
990 static int __cmd_latency(struct perf_ftrace *ftrace)
991 {
992 	int trace_fd;
993 	char buf[4096];
994 	char line[256];
995 	struct pollfd pollfd = {
996 		.events = POLLIN,
997 	};
998 	int buckets[NUM_BUCKET] = { };
999 
1000 	trace_fd = prepare_func_latency(ftrace);
1001 	if (trace_fd < 0)
1002 		goto out;
1003 
1004 	fcntl(trace_fd, F_SETFL, O_NONBLOCK);
1005 	pollfd.fd = trace_fd;
1006 
1007 	if (start_func_latency(ftrace) < 0)
1008 		goto out;
1009 
1010 	evlist__start_workload(ftrace->evlist);
1011 
1012 	line[0] = '\0';
1013 	while (!done) {
1014 		if (poll(&pollfd, 1, -1) < 0)
1015 			break;
1016 
1017 		if (pollfd.revents & POLLIN) {
1018 			int n = read(trace_fd, buf, sizeof(buf) - 1);
1019 			if (n < 0)
1020 				break;
1021 
1022 			make_histogram(ftrace, buckets, buf, n, line);
1023 		}
1024 	}
1025 
1026 	stop_func_latency(ftrace);
1027 
1028 	if (workload_exec_errno) {
1029 		const char *emsg = str_error_r(workload_exec_errno, buf, sizeof(buf));
1030 		pr_err("workload failed: %s\n", emsg);
1031 		goto out;
1032 	}
1033 
1034 	/* read remaining buffer contents */
1035 	while (!ftrace->target.use_bpf) {
1036 		int n = read(trace_fd, buf, sizeof(buf) - 1);
1037 		if (n <= 0)
1038 			break;
1039 		make_histogram(ftrace, buckets, buf, n, line);
1040 	}
1041 
1042 	read_func_latency(ftrace, buckets);
1043 
1044 	display_histogram(ftrace, buckets);
1045 
1046 out:
1047 	close(trace_fd);
1048 	cleanup_func_latency(ftrace);
1049 
1050 	return (done && !workload_exec_errno) ? 0 : -1;
1051 }
1052 
1053 static size_t profile_hash(long func, void *ctx __maybe_unused)
1054 {
1055 	return str_hash((char *)func);
1056 }
1057 
1058 static bool profile_equal(long func1, long func2, void *ctx __maybe_unused)
1059 {
1060 	return !strcmp((char *)func1, (char *)func2);
1061 }
1062 
1063 static int prepare_func_profile(struct perf_ftrace *ftrace)
1064 {
1065 	ftrace->tracer = "function_graph";
1066 	ftrace->graph_tail = 1;
1067 	ftrace->graph_verbose = 0;
1068 
1069 	ftrace->profile_hash = hashmap__new(profile_hash, profile_equal, NULL);
1070 	if (ftrace->profile_hash == NULL)
1071 		return -ENOMEM;
1072 
1073 	return 0;
1074 }
1075 
1076 /* This is saved in a hashmap keyed by the function name */
1077 struct ftrace_profile_data {
1078 	struct stats st;
1079 };
1080 
1081 static int add_func_duration(struct perf_ftrace *ftrace, char *func, double time_ns)
1082 {
1083 	struct ftrace_profile_data *prof = NULL;
1084 
1085 	if (!hashmap__find(ftrace->profile_hash, func, &prof)) {
1086 		char *key = strdup(func);
1087 
1088 		if (key == NULL)
1089 			return -ENOMEM;
1090 
1091 		prof = zalloc(sizeof(*prof));
1092 		if (prof == NULL) {
1093 			free(key);
1094 			return -ENOMEM;
1095 		}
1096 
1097 		init_stats(&prof->st);
1098 		hashmap__add(ftrace->profile_hash, key, prof);
1099 	}
1100 
1101 	update_stats(&prof->st, time_ns);
1102 	return 0;
1103 }
1104 
1105 /*
1106  * The ftrace function_graph text output normally looks like below:
1107  *
1108  * CPU   DURATION       FUNCTION
1109  *
1110  *  0)               |  syscall_trace_enter.isra.0() {
1111  *  0)               |    __audit_syscall_entry() {
1112  *  0)               |      auditd_test_task() {
1113  *  0)   0.271 us    |        __rcu_read_lock();
1114  *  0)   0.275 us    |        __rcu_read_unlock();
1115  *  0)   1.254 us    |      } /\* auditd_test_task *\/
1116  *  0)   0.279 us    |      ktime_get_coarse_real_ts64();
1117  *  0)   2.227 us    |    } /\* __audit_syscall_entry *\/
1118  *  0)   2.713 us    |  } /\* syscall_trace_enter.isra.0 *\/
1119  *
1120  *  Parse the line and get the duration and function name.
1121  */
1122 static int parse_func_duration(struct perf_ftrace *ftrace, char *line, size_t len)
1123 {
1124 	char *p;
1125 	char *func;
1126 	double duration;
1127 
1128 	/* skip CPU */
1129 	p = strchr(line, ')');
1130 	if (p == NULL)
1131 		return 0;
1132 
1133 	/* get duration */
1134 	p = skip_spaces(p + 1);
1135 
1136 	/* no duration? */
1137 	if (p == NULL || *p == '|')
1138 		return 0;
1139 
1140 	/* skip markers like '*' or '!' for longer than ms */
1141 	if (!isdigit(*p))
1142 		p++;
1143 
1144 	duration = strtod(p, &p);
1145 
1146 	if (strncmp(p, " us", 3)) {
1147 		pr_debug("non-usec time found.. ignoring\n");
1148 		return 0;
1149 	}
1150 
1151 	/*
1152 	 * profile stat keeps the max and min values as integer,
1153 	 * convert to nsec time so that we can have accurate max.
1154 	 */
1155 	duration *= 1000;
1156 
1157 	/* skip to the pipe */
1158 	while (p < line + len && *p != '|')
1159 		p++;
1160 
1161 	if (*p++ != '|')
1162 		return -EINVAL;
1163 
1164 	/* get function name */
1165 	func = skip_spaces(p);
1166 
1167 	/* skip the closing bracket and the start of comment */
1168 	if (*func == '}')
1169 		func += 5;
1170 
1171 	/* remove semi-colon or end of comment at the end */
1172 	p = line + len - 1;
1173 	while (!isalnum(*p) && *p != ']') {
1174 		*p = '\0';
1175 		--p;
1176 	}
1177 
1178 	return add_func_duration(ftrace, func, duration);
1179 }
1180 
1181 enum perf_ftrace_profile_sort_key {
1182 	PFP_SORT_TOTAL = 0,
1183 	PFP_SORT_AVG,
1184 	PFP_SORT_MAX,
1185 	PFP_SORT_COUNT,
1186 	PFP_SORT_NAME,
1187 };
1188 
1189 static enum perf_ftrace_profile_sort_key profile_sort = PFP_SORT_TOTAL;
1190 
1191 static int cmp_profile_data(const void *a, const void *b)
1192 {
1193 	const struct hashmap_entry *e1 = *(const struct hashmap_entry **)a;
1194 	const struct hashmap_entry *e2 = *(const struct hashmap_entry **)b;
1195 	struct ftrace_profile_data *p1 = e1->pvalue;
1196 	struct ftrace_profile_data *p2 = e2->pvalue;
1197 	double v1, v2;
1198 
1199 	switch (profile_sort) {
1200 	case PFP_SORT_NAME:
1201 		return strcmp(e1->pkey, e2->pkey);
1202 	case PFP_SORT_AVG:
1203 		v1 = p1->st.mean;
1204 		v2 = p2->st.mean;
1205 		break;
1206 	case PFP_SORT_MAX:
1207 		v1 = p1->st.max;
1208 		v2 = p2->st.max;
1209 		break;
1210 	case PFP_SORT_COUNT:
1211 		v1 = p1->st.n;
1212 		v2 = p2->st.n;
1213 		break;
1214 	case PFP_SORT_TOTAL:
1215 	default:
1216 		v1 = p1->st.n * p1->st.mean;
1217 		v2 = p2->st.n * p2->st.mean;
1218 		break;
1219 	}
1220 
1221 	if (v1 > v2)
1222 		return -1;
1223 	if (v1 < v2)
1224 		return 1;
1225 	return 0;
1226 }
1227 
1228 static void print_profile_result(struct perf_ftrace *ftrace)
1229 {
1230 	struct hashmap_entry *entry, **profile;
1231 	size_t i, nr, bkt;
1232 
1233 	nr = hashmap__size(ftrace->profile_hash);
1234 	if (nr == 0)
1235 		return;
1236 
1237 	profile = calloc(nr, sizeof(*profile));
1238 	if (profile == NULL) {
1239 		pr_err("failed to allocate memory for the result\n");
1240 		return;
1241 	}
1242 
1243 	i = 0;
1244 	hashmap__for_each_entry(ftrace->profile_hash, entry, bkt)
1245 		profile[i++] = entry;
1246 
1247 	assert(i == nr);
1248 
1249 	//cmp_profile_data(profile[0], profile[1]);
1250 	qsort(profile, nr, sizeof(*profile), cmp_profile_data);
1251 
1252 	printf("# %10s %10s %10s %10s   %s\n",
1253 	       "Total (us)", "Avg (us)", "Max (us)", "Count", "Function");
1254 
1255 	for (i = 0; i < nr; i++) {
1256 		const char *name = profile[i]->pkey;
1257 		struct ftrace_profile_data *p = profile[i]->pvalue;
1258 
1259 		printf("%12.3f %10.3f %6"PRIu64".%03"PRIu64" %10.0f   %s\n",
1260 		       p->st.n * p->st.mean / 1000, p->st.mean / 1000,
1261 		       p->st.max / 1000, p->st.max % 1000, p->st.n, name);
1262 	}
1263 
1264 	free(profile);
1265 
1266 	hashmap__for_each_entry(ftrace->profile_hash, entry, bkt) {
1267 		free((char *)entry->pkey);
1268 		free(entry->pvalue);
1269 	}
1270 
1271 	hashmap__free(ftrace->profile_hash);
1272 	ftrace->profile_hash = NULL;
1273 }
1274 
1275 static int __cmd_profile(struct perf_ftrace *ftrace)
1276 {
1277 	char *trace_file;
1278 	int trace_fd;
1279 	char buf[4096];
1280 	struct io io;
1281 	char *line = NULL;
1282 	size_t line_len = 0;
1283 
1284 	if (prepare_func_profile(ftrace) < 0) {
1285 		pr_err("failed to prepare func profiler\n");
1286 		goto out;
1287 	}
1288 
1289 	if (reset_tracing_files(ftrace) < 0) {
1290 		pr_err("failed to reset ftrace\n");
1291 		goto out;
1292 	}
1293 
1294 	/* reset ftrace buffer */
1295 	if (write_tracing_file("trace", "0") < 0)
1296 		goto out;
1297 
1298 	if (set_tracing_options(ftrace) < 0)
1299 		return -1;
1300 
1301 	if (write_tracing_file("current_tracer", ftrace->tracer) < 0) {
1302 		pr_err("failed to set current_tracer to %s\n", ftrace->tracer);
1303 		goto out_reset;
1304 	}
1305 
1306 	setup_pager();
1307 
1308 	trace_file = get_tracing_file("trace_pipe");
1309 	if (!trace_file) {
1310 		pr_err("failed to open trace_pipe\n");
1311 		goto out_reset;
1312 	}
1313 
1314 	trace_fd = open(trace_file, O_RDONLY);
1315 
1316 	put_tracing_file(trace_file);
1317 
1318 	if (trace_fd < 0) {
1319 		pr_err("failed to open trace_pipe\n");
1320 		goto out_reset;
1321 	}
1322 
1323 	fcntl(trace_fd, F_SETFL, O_NONBLOCK);
1324 
1325 	if (write_tracing_file("tracing_on", "1") < 0) {
1326 		pr_err("can't enable tracing\n");
1327 		goto out_close_fd;
1328 	}
1329 
1330 	evlist__start_workload(ftrace->evlist);
1331 
1332 	io__init(&io, trace_fd, buf, sizeof(buf));
1333 	io.timeout_ms = -1;
1334 
1335 	while (!done && !io.eof) {
1336 		if (io__getline(&io, &line, &line_len) < 0)
1337 			break;
1338 
1339 		if (parse_func_duration(ftrace, line, line_len) < 0)
1340 			break;
1341 	}
1342 
1343 	write_tracing_file("tracing_on", "0");
1344 
1345 	if (workload_exec_errno) {
1346 		const char *emsg = str_error_r(workload_exec_errno, buf, sizeof(buf));
1347 		/* flush stdout first so below error msg appears at the end. */
1348 		fflush(stdout);
1349 		pr_err("workload failed: %s\n", emsg);
1350 		goto out_free_line;
1351 	}
1352 
1353 	/* read remaining buffer contents */
1354 	io.timeout_ms = 0;
1355 	while (!io.eof) {
1356 		if (io__getline(&io, &line, &line_len) < 0)
1357 			break;
1358 
1359 		if (parse_func_duration(ftrace, line, line_len) < 0)
1360 			break;
1361 	}
1362 
1363 	print_profile_result(ftrace);
1364 
1365 out_free_line:
1366 	free(line);
1367 out_close_fd:
1368 	close(trace_fd);
1369 out_reset:
1370 	reset_tracing_files(ftrace);
1371 out:
1372 	return (done && !workload_exec_errno) ? 0 : -1;
1373 }
1374 
1375 static int perf_ftrace_config(const char *var, const char *value, void *cb)
1376 {
1377 	struct perf_ftrace *ftrace = cb;
1378 
1379 	if (!strstarts(var, "ftrace."))
1380 		return 0;
1381 
1382 	if (strcmp(var, "ftrace.tracer"))
1383 		return -1;
1384 
1385 	if (!strcmp(value, "function_graph") ||
1386 	    !strcmp(value, "function")) {
1387 		ftrace->tracer = value;
1388 		return 0;
1389 	}
1390 
1391 	pr_err("Please select \"function_graph\" (default) or \"function\"\n");
1392 	return -1;
1393 }
1394 
1395 static void list_function_cb(char *str, void *arg)
1396 {
1397 	struct strfilter *filter = (struct strfilter *)arg;
1398 
1399 	if (strfilter__compare(filter, str))
1400 		printf("%s", str);
1401 }
1402 
1403 static int opt_list_avail_functions(const struct option *opt __maybe_unused,
1404 				    const char *str, int unset)
1405 {
1406 	struct strfilter *filter;
1407 	const char *err = NULL;
1408 	int ret;
1409 
1410 	if (unset || !str)
1411 		return -1;
1412 
1413 	filter = strfilter__new(str, &err);
1414 	if (!filter)
1415 		return err ? -EINVAL : -ENOMEM;
1416 
1417 	ret = strfilter__or(filter, str, &err);
1418 	if (ret == -EINVAL) {
1419 		pr_err("Filter parse error at %td.\n", err - str + 1);
1420 		pr_err("Source: \"%s\"\n", str);
1421 		pr_err("         %*c\n", (int)(err - str + 1), '^');
1422 		strfilter__delete(filter);
1423 		return ret;
1424 	}
1425 
1426 	ret = read_tracing_file_by_line("available_filter_functions",
1427 					list_function_cb, filter);
1428 	strfilter__delete(filter);
1429 	if (ret < 0)
1430 		return ret;
1431 
1432 	exit(0);
1433 }
1434 
1435 static int parse_filter_func(const struct option *opt, const char *str,
1436 			     int unset __maybe_unused)
1437 {
1438 	struct list_head *head = opt->value;
1439 	struct filter_entry *entry;
1440 
1441 	entry = malloc(sizeof(*entry) + strlen(str) + 1);
1442 	if (entry == NULL)
1443 		return -ENOMEM;
1444 
1445 	strcpy(entry->name, str);
1446 	list_add_tail(&entry->list, head);
1447 
1448 	return 0;
1449 }
1450 
1451 static void delete_filter_func(struct list_head *head)
1452 {
1453 	struct filter_entry *pos, *tmp;
1454 
1455 	list_for_each_entry_safe(pos, tmp, head, list) {
1456 		list_del_init(&pos->list);
1457 		free(pos);
1458 	}
1459 }
1460 
1461 static int parse_buffer_size(const struct option *opt,
1462 			     const char *str, int unset)
1463 {
1464 	unsigned long *s = (unsigned long *)opt->value;
1465 	static struct parse_tag tags_size[] = {
1466 		{ .tag  = 'B', .mult = 1       },
1467 		{ .tag  = 'K', .mult = 1 << 10 },
1468 		{ .tag  = 'M', .mult = 1 << 20 },
1469 		{ .tag  = 'G', .mult = 1 << 30 },
1470 		{ .tag  = 0 },
1471 	};
1472 	unsigned long val;
1473 
1474 	if (unset) {
1475 		*s = 0;
1476 		return 0;
1477 	}
1478 
1479 	val = parse_tag_value(str, tags_size);
1480 	if (val != (unsigned long) -1) {
1481 		if (val < 1024) {
1482 			pr_err("buffer size too small, must larger than 1KB.");
1483 			return -1;
1484 		}
1485 		*s = val;
1486 		return 0;
1487 	}
1488 
1489 	return -1;
1490 }
1491 
1492 static int parse_func_tracer_opts(const struct option *opt,
1493 				  const char *str, int unset)
1494 {
1495 	int ret;
1496 	struct perf_ftrace *ftrace = (struct perf_ftrace *) opt->value;
1497 	struct sublevel_option func_tracer_opts[] = {
1498 		{ .name = "call-graph",	.value_ptr = &ftrace->func_stack_trace },
1499 		{ .name = "irq-info",	.value_ptr = &ftrace->func_irq_info },
1500 		{ .name = NULL, }
1501 	};
1502 
1503 	if (unset)
1504 		return 0;
1505 
1506 	ret = perf_parse_sublevel_options(str, func_tracer_opts);
1507 	if (ret)
1508 		return ret;
1509 
1510 	return 0;
1511 }
1512 
1513 static int parse_graph_tracer_opts(const struct option *opt,
1514 				  const char *str, int unset)
1515 {
1516 	int ret;
1517 	struct perf_ftrace *ftrace = (struct perf_ftrace *) opt->value;
1518 	struct sublevel_option graph_tracer_opts[] = {
1519 		{ .name = "nosleep-time",	.value_ptr = &ftrace->graph_nosleep_time },
1520 		{ .name = "noirqs",		.value_ptr = &ftrace->graph_noirqs },
1521 		{ .name = "verbose",		.value_ptr = &ftrace->graph_verbose },
1522 		{ .name = "thresh",		.value_ptr = &ftrace->graph_thresh },
1523 		{ .name = "depth",		.value_ptr = &ftrace->graph_depth },
1524 		{ .name = "tail",		.value_ptr = &ftrace->graph_tail },
1525 		{ .name = NULL, }
1526 	};
1527 
1528 	if (unset)
1529 		return 0;
1530 
1531 	ret = perf_parse_sublevel_options(str, graph_tracer_opts);
1532 	if (ret)
1533 		return ret;
1534 
1535 	return 0;
1536 }
1537 
1538 static int parse_sort_key(const struct option *opt, const char *str, int unset)
1539 {
1540 	enum perf_ftrace_profile_sort_key *key = (void *)opt->value;
1541 
1542 	if (unset)
1543 		return 0;
1544 
1545 	if (!strcmp(str, "total"))
1546 		*key = PFP_SORT_TOTAL;
1547 	else if (!strcmp(str, "avg"))
1548 		*key = PFP_SORT_AVG;
1549 	else if (!strcmp(str, "max"))
1550 		*key = PFP_SORT_MAX;
1551 	else if (!strcmp(str, "count"))
1552 		*key = PFP_SORT_COUNT;
1553 	else if (!strcmp(str, "name"))
1554 		*key = PFP_SORT_NAME;
1555 	else {
1556 		pr_err("Unknown sort key: %s\n", str);
1557 		return -1;
1558 	}
1559 	return 0;
1560 }
1561 
1562 enum perf_ftrace_subcommand {
1563 	PERF_FTRACE_NONE,
1564 	PERF_FTRACE_TRACE,
1565 	PERF_FTRACE_LATENCY,
1566 	PERF_FTRACE_PROFILE,
1567 };
1568 
1569 int cmd_ftrace(int argc, const char **argv)
1570 {
1571 	int ret;
1572 	int (*cmd_func)(struct perf_ftrace *) = NULL;
1573 	struct perf_ftrace ftrace = {
1574 		.tracer = DEFAULT_TRACER,
1575 		.target = { .uid = UINT_MAX, },
1576 	};
1577 	const struct option common_options[] = {
1578 	OPT_STRING('p', "pid", &ftrace.target.pid, "pid",
1579 		   "Trace on existing process id"),
1580 	/* TODO: Add short option -t after -t/--tracer can be removed. */
1581 	OPT_STRING(0, "tid", &ftrace.target.tid, "tid",
1582 		   "Trace on existing thread id (exclusive to --pid)"),
1583 	OPT_INCR('v', "verbose", &verbose,
1584 		 "Be more verbose"),
1585 	OPT_BOOLEAN('a', "all-cpus", &ftrace.target.system_wide,
1586 		    "System-wide collection from all CPUs"),
1587 	OPT_STRING('C', "cpu", &ftrace.target.cpu_list, "cpu",
1588 		    "List of cpus to monitor"),
1589 	OPT_END()
1590 	};
1591 	const struct option ftrace_options[] = {
1592 	OPT_STRING('t', "tracer", &ftrace.tracer, "tracer",
1593 		   "Tracer to use: function_graph(default) or function"),
1594 	OPT_CALLBACK_DEFAULT('F', "funcs", NULL, "[FILTER]",
1595 			     "Show available functions to filter",
1596 			     opt_list_avail_functions, "*"),
1597 	OPT_CALLBACK('T', "trace-funcs", &ftrace.filters, "func",
1598 		     "Trace given functions using function tracer",
1599 		     parse_filter_func),
1600 	OPT_CALLBACK('N', "notrace-funcs", &ftrace.notrace, "func",
1601 		     "Do not trace given functions", parse_filter_func),
1602 	OPT_CALLBACK(0, "func-opts", &ftrace, "options",
1603 		     "Function tracer options, available options: call-graph,irq-info",
1604 		     parse_func_tracer_opts),
1605 	OPT_CALLBACK('G', "graph-funcs", &ftrace.graph_funcs, "func",
1606 		     "Trace given functions using function_graph tracer",
1607 		     parse_filter_func),
1608 	OPT_CALLBACK('g', "nograph-funcs", &ftrace.nograph_funcs, "func",
1609 		     "Set nograph filter on given functions", parse_filter_func),
1610 	OPT_CALLBACK(0, "graph-opts", &ftrace, "options",
1611 		     "Graph tracer options, available options: nosleep-time,noirqs,verbose,thresh=<n>,depth=<n>",
1612 		     parse_graph_tracer_opts),
1613 	OPT_CALLBACK('m', "buffer-size", &ftrace.percpu_buffer_size, "size",
1614 		     "Size of per cpu buffer, needs to use a B, K, M or G suffix.", parse_buffer_size),
1615 	OPT_BOOLEAN(0, "inherit", &ftrace.inherit,
1616 		    "Trace children processes"),
1617 	OPT_INTEGER('D', "delay", &ftrace.target.initial_delay,
1618 		    "Number of milliseconds to wait before starting tracing after program start"),
1619 	OPT_PARENT(common_options),
1620 	};
1621 	const struct option latency_options[] = {
1622 	OPT_CALLBACK('T', "trace-funcs", &ftrace.filters, "func",
1623 		     "Show latency of given function", parse_filter_func),
1624 #ifdef HAVE_BPF_SKEL
1625 	OPT_BOOLEAN('b', "use-bpf", &ftrace.target.use_bpf,
1626 		    "Use BPF to measure function latency"),
1627 #endif
1628 	OPT_BOOLEAN('n', "use-nsec", &ftrace.use_nsec,
1629 		    "Use nano-second histogram"),
1630 	OPT_UINTEGER(0, "bucket-range", &ftrace.bucket_range,
1631 		    "Bucket range in ms or ns (-n/--use-nsec), default is log2() mode"),
1632 	OPT_UINTEGER(0, "min-latency", &ftrace.min_latency,
1633 		    "Minimum latency (1st bucket). Works only with --bucket-range."),
1634 	OPT_UINTEGER(0, "max-latency", &ftrace.max_latency,
1635 		    "Maximum latency (last bucket). Works only with --bucket-range and total buckets less than 22."),
1636 	OPT_PARENT(common_options),
1637 	};
1638 	const struct option profile_options[] = {
1639 	OPT_CALLBACK('T', "trace-funcs", &ftrace.filters, "func",
1640 		     "Trace given functions using function tracer",
1641 		     parse_filter_func),
1642 	OPT_CALLBACK('N', "notrace-funcs", &ftrace.notrace, "func",
1643 		     "Do not trace given functions", parse_filter_func),
1644 	OPT_CALLBACK('G', "graph-funcs", &ftrace.graph_funcs, "func",
1645 		     "Trace given functions using function_graph tracer",
1646 		     parse_filter_func),
1647 	OPT_CALLBACK('g', "nograph-funcs", &ftrace.nograph_funcs, "func",
1648 		     "Set nograph filter on given functions", parse_filter_func),
1649 	OPT_CALLBACK('m', "buffer-size", &ftrace.percpu_buffer_size, "size",
1650 		     "Size of per cpu buffer, needs to use a B, K, M or G suffix.", parse_buffer_size),
1651 	OPT_CALLBACK('s', "sort", &profile_sort, "key",
1652 		     "Sort result by key: total (default), avg, max, count, name.",
1653 		     parse_sort_key),
1654 	OPT_CALLBACK(0, "graph-opts", &ftrace, "options",
1655 		     "Graph tracer options, available options: nosleep-time,noirqs,thresh=<n>,depth=<n>",
1656 		     parse_graph_tracer_opts),
1657 	OPT_PARENT(common_options),
1658 	};
1659 	const struct option *options = ftrace_options;
1660 
1661 	const char * const ftrace_usage[] = {
1662 		"perf ftrace [<options>] [<command>]",
1663 		"perf ftrace [<options>] -- [<command>] [<options>]",
1664 		"perf ftrace {trace|latency|profile} [<options>] [<command>]",
1665 		"perf ftrace {trace|latency|profile} [<options>] -- [<command>] [<options>]",
1666 		NULL
1667 	};
1668 	enum perf_ftrace_subcommand subcmd = PERF_FTRACE_NONE;
1669 
1670 	INIT_LIST_HEAD(&ftrace.filters);
1671 	INIT_LIST_HEAD(&ftrace.notrace);
1672 	INIT_LIST_HEAD(&ftrace.graph_funcs);
1673 	INIT_LIST_HEAD(&ftrace.nograph_funcs);
1674 
1675 	signal(SIGINT, sig_handler);
1676 	signal(SIGUSR1, sig_handler);
1677 	signal(SIGCHLD, sig_handler);
1678 	signal(SIGPIPE, sig_handler);
1679 
1680 	if (!check_ftrace_capable())
1681 		return -1;
1682 
1683 	if (!is_ftrace_supported()) {
1684 		pr_err("ftrace is not supported on this system\n");
1685 		return -ENOTSUP;
1686 	}
1687 
1688 	ret = perf_config(perf_ftrace_config, &ftrace);
1689 	if (ret < 0)
1690 		return -1;
1691 
1692 	if (argc > 1) {
1693 		if (!strcmp(argv[1], "trace")) {
1694 			subcmd = PERF_FTRACE_TRACE;
1695 		} else if (!strcmp(argv[1], "latency")) {
1696 			subcmd = PERF_FTRACE_LATENCY;
1697 			options = latency_options;
1698 		} else if (!strcmp(argv[1], "profile")) {
1699 			subcmd = PERF_FTRACE_PROFILE;
1700 			options = profile_options;
1701 		}
1702 
1703 		if (subcmd != PERF_FTRACE_NONE) {
1704 			argc--;
1705 			argv++;
1706 		}
1707 	}
1708 	/* for backward compatibility */
1709 	if (subcmd == PERF_FTRACE_NONE)
1710 		subcmd = PERF_FTRACE_TRACE;
1711 
1712 	argc = parse_options(argc, argv, options, ftrace_usage,
1713 			    PARSE_OPT_STOP_AT_NON_OPTION);
1714 	if (argc < 0) {
1715 		ret = -EINVAL;
1716 		goto out_delete_filters;
1717 	}
1718 
1719 	/* Make system wide (-a) the default target. */
1720 	if (!argc && target__none(&ftrace.target))
1721 		ftrace.target.system_wide = true;
1722 
1723 	switch (subcmd) {
1724 	case PERF_FTRACE_TRACE:
1725 		cmd_func = __cmd_ftrace;
1726 		break;
1727 	case PERF_FTRACE_LATENCY:
1728 		if (list_empty(&ftrace.filters)) {
1729 			pr_err("Should provide a function to measure\n");
1730 			parse_options_usage(ftrace_usage, options, "T", 1);
1731 			ret = -EINVAL;
1732 			goto out_delete_filters;
1733 		}
1734 		if (!ftrace.bucket_range && ftrace.min_latency) {
1735 			pr_err("--min-latency works only with --bucket-range\n");
1736 			parse_options_usage(ftrace_usage, options,
1737 					    "min-latency", /*short_opt=*/false);
1738 			ret = -EINVAL;
1739 			goto out_delete_filters;
1740 		}
1741 		if (!ftrace.min_latency) {
1742 			/* default min latency should be the bucket range */
1743 			ftrace.min_latency = ftrace.bucket_range;
1744 		}
1745 		if (!ftrace.bucket_range && ftrace.max_latency) {
1746 			pr_err("--max-latency works only with --bucket-range\n");
1747 			parse_options_usage(ftrace_usage, options,
1748 					    "max-latency", /*short_opt=*/false);
1749 			ret = -EINVAL;
1750 			goto out_delete_filters;
1751 		}
1752 		if (!ftrace.max_latency) {
1753 			/* default max latency should depend on bucket range and num_buckets */
1754 			ftrace.max_latency = (NUM_BUCKET - 2) * ftrace.bucket_range +
1755 						ftrace.min_latency;
1756 		}
1757 		cmd_func = __cmd_latency;
1758 		break;
1759 	case PERF_FTRACE_PROFILE:
1760 		cmd_func = __cmd_profile;
1761 		break;
1762 	case PERF_FTRACE_NONE:
1763 	default:
1764 		pr_err("Invalid subcommand\n");
1765 		ret = -EINVAL;
1766 		goto out_delete_filters;
1767 	}
1768 
1769 	ret = target__validate(&ftrace.target);
1770 	if (ret) {
1771 		char errbuf[512];
1772 
1773 		target__strerror(&ftrace.target, ret, errbuf, 512);
1774 		pr_err("%s\n", errbuf);
1775 		goto out_delete_filters;
1776 	}
1777 
1778 	ftrace.evlist = evlist__new();
1779 	if (ftrace.evlist == NULL) {
1780 		ret = -ENOMEM;
1781 		goto out_delete_filters;
1782 	}
1783 
1784 	ret = evlist__create_maps(ftrace.evlist, &ftrace.target);
1785 	if (ret < 0)
1786 		goto out_delete_evlist;
1787 
1788 	if (argc) {
1789 		ret = evlist__prepare_workload(ftrace.evlist, &ftrace.target,
1790 					       argv, false,
1791 					       ftrace__workload_exec_failed_signal);
1792 		if (ret < 0)
1793 			goto out_delete_evlist;
1794 	}
1795 
1796 	ret = cmd_func(&ftrace);
1797 
1798 out_delete_evlist:
1799 	evlist__delete(ftrace.evlist);
1800 
1801 out_delete_filters:
1802 	delete_filter_func(&ftrace.filters);
1803 	delete_filter_func(&ftrace.notrace);
1804 	delete_filter_func(&ftrace.graph_funcs);
1805 	delete_filter_func(&ftrace.nograph_funcs);
1806 
1807 	return ret;
1808 }
1809