perf ftrace: Add support for tracing option 'func_stack_trace'
[linux-2.6-microblaze.git] / tools / perf / builtin-ftrace.c
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  */
7
8 #include "builtin.h"
9
10 #include <errno.h>
11 #include <unistd.h>
12 #include <signal.h>
13 #include <stdlib.h>
14 #include <fcntl.h>
15 #include <poll.h>
16 #include <linux/capability.h>
17 #include <linux/string.h>
18
19 #include "debug.h"
20 #include <subcmd/pager.h>
21 #include <subcmd/parse-options.h>
22 #include <api/fs/tracing_path.h>
23 #include "evlist.h"
24 #include "target.h"
25 #include "cpumap.h"
26 #include "thread_map.h"
27 #include "util/cap.h"
28 #include "util/config.h"
29 #include "util/units.h"
30 #include "util/parse-sublevel-options.h"
31
32 #define DEFAULT_TRACER  "function_graph"
33
34 struct perf_ftrace {
35         struct evlist           *evlist;
36         struct target           target;
37         const char              *tracer;
38         bool                    list_avail_functions;
39         struct list_head        filters;
40         struct list_head        notrace;
41         struct list_head        graph_funcs;
42         struct list_head        nograph_funcs;
43         int                     graph_depth;
44         unsigned long           percpu_buffer_size;
45         bool                    inherit;
46         int                     func_stack_trace;
47 };
48
49 struct filter_entry {
50         struct list_head        list;
51         char                    name[];
52 };
53
54 static volatile int workload_exec_errno;
55 static bool done;
56
57 static void sig_handler(int sig __maybe_unused)
58 {
59         done = true;
60 }
61
62 /*
63  * perf_evlist__prepare_workload will send a SIGUSR1 if the fork fails, since
64  * we asked by setting its exec_error to the function below,
65  * ftrace__workload_exec_failed_signal.
66  *
67  * XXX We need to handle this more appropriately, emitting an error, etc.
68  */
69 static void ftrace__workload_exec_failed_signal(int signo __maybe_unused,
70                                                 siginfo_t *info __maybe_unused,
71                                                 void *ucontext __maybe_unused)
72 {
73         workload_exec_errno = info->si_value.sival_int;
74         done = true;
75 }
76
77 static int __write_tracing_file(const char *name, const char *val, bool append)
78 {
79         char *file;
80         int fd, ret = -1;
81         ssize_t size = strlen(val);
82         int flags = O_WRONLY;
83         char errbuf[512];
84         char *val_copy;
85
86         file = get_tracing_file(name);
87         if (!file) {
88                 pr_debug("cannot get tracing file: %s\n", name);
89                 return -1;
90         }
91
92         if (append)
93                 flags |= O_APPEND;
94         else
95                 flags |= O_TRUNC;
96
97         fd = open(file, flags);
98         if (fd < 0) {
99                 pr_debug("cannot open tracing file: %s: %s\n",
100                          name, str_error_r(errno, errbuf, sizeof(errbuf)));
101                 goto out;
102         }
103
104         /*
105          * Copy the original value and append a '\n'. Without this,
106          * the kernel can hide possible errors.
107          */
108         val_copy = strdup(val);
109         if (!val_copy)
110                 goto out_close;
111         val_copy[size] = '\n';
112
113         if (write(fd, val_copy, size + 1) == size + 1)
114                 ret = 0;
115         else
116                 pr_debug("write '%s' to tracing/%s failed: %s\n",
117                          val, name, str_error_r(errno, errbuf, sizeof(errbuf)));
118
119         free(val_copy);
120 out_close:
121         close(fd);
122 out:
123         put_tracing_file(file);
124         return ret;
125 }
126
127 static int write_tracing_file(const char *name, const char *val)
128 {
129         return __write_tracing_file(name, val, false);
130 }
131
132 static int append_tracing_file(const char *name, const char *val)
133 {
134         return __write_tracing_file(name, val, true);
135 }
136
137 static int read_tracing_file_to_stdout(const char *name)
138 {
139         char buf[4096];
140         char *file;
141         int fd;
142         int ret = -1;
143
144         file = get_tracing_file(name);
145         if (!file) {
146                 pr_debug("cannot get tracing file: %s\n", name);
147                 return -1;
148         }
149
150         fd = open(file, O_RDONLY);
151         if (fd < 0) {
152                 pr_debug("cannot open tracing file: %s: %s\n",
153                          name, str_error_r(errno, buf, sizeof(buf)));
154                 goto out;
155         }
156
157         /* read contents to stdout */
158         while (true) {
159                 int n = read(fd, buf, sizeof(buf));
160                 if (n == 0)
161                         break;
162                 else if (n < 0)
163                         goto out_close;
164
165                 if (fwrite(buf, n, 1, stdout) != 1)
166                         goto out_close;
167         }
168         ret = 0;
169
170 out_close:
171         close(fd);
172 out:
173         put_tracing_file(file);
174         return ret;
175 }
176
177 static int write_tracing_file_int(const char *name, int value)
178 {
179         char buf[16];
180
181         snprintf(buf, sizeof(buf), "%d", value);
182         if (write_tracing_file(name, buf) < 0)
183                 return -1;
184
185         return 0;
186 }
187
188 static int write_tracing_option_file(const char *name, const char *val)
189 {
190         char *file;
191         int ret;
192
193         if (asprintf(&file, "options/%s", name) < 0)
194                 return -1;
195
196         ret = __write_tracing_file(file, val, false);
197         free(file);
198         return ret;
199 }
200
201 static int reset_tracing_cpu(void);
202 static void reset_tracing_filters(void);
203
204 static void reset_tracing_options(struct perf_ftrace *ftrace __maybe_unused)
205 {
206         write_tracing_option_file("function-fork", "0");
207         write_tracing_option_file("func_stack_trace", "0");
208 }
209
210 static int reset_tracing_files(struct perf_ftrace *ftrace __maybe_unused)
211 {
212         if (write_tracing_file("tracing_on", "0") < 0)
213                 return -1;
214
215         if (write_tracing_file("current_tracer", "nop") < 0)
216                 return -1;
217
218         if (write_tracing_file("set_ftrace_pid", " ") < 0)
219                 return -1;
220
221         if (reset_tracing_cpu() < 0)
222                 return -1;
223
224         if (write_tracing_file("max_graph_depth", "0") < 0)
225                 return -1;
226
227         reset_tracing_filters();
228         reset_tracing_options(ftrace);
229         return 0;
230 }
231
232 static int set_tracing_pid(struct perf_ftrace *ftrace)
233 {
234         int i;
235         char buf[16];
236
237         if (target__has_cpu(&ftrace->target))
238                 return 0;
239
240         for (i = 0; i < perf_thread_map__nr(ftrace->evlist->core.threads); i++) {
241                 scnprintf(buf, sizeof(buf), "%d",
242                           ftrace->evlist->core.threads->map[i]);
243                 if (append_tracing_file("set_ftrace_pid", buf) < 0)
244                         return -1;
245         }
246         return 0;
247 }
248
249 static int set_tracing_cpumask(struct perf_cpu_map *cpumap)
250 {
251         char *cpumask;
252         size_t mask_size;
253         int ret;
254         int last_cpu;
255
256         last_cpu = cpu_map__cpu(cpumap, cpumap->nr - 1);
257         mask_size = last_cpu / 4 + 2; /* one more byte for EOS */
258         mask_size += last_cpu / 32; /* ',' is needed for every 32th cpus */
259
260         cpumask = malloc(mask_size);
261         if (cpumask == NULL) {
262                 pr_debug("failed to allocate cpu mask\n");
263                 return -1;
264         }
265
266         cpu_map__snprint_mask(cpumap, cpumask, mask_size);
267
268         ret = write_tracing_file("tracing_cpumask", cpumask);
269
270         free(cpumask);
271         return ret;
272 }
273
274 static int set_tracing_cpu(struct perf_ftrace *ftrace)
275 {
276         struct perf_cpu_map *cpumap = ftrace->evlist->core.cpus;
277
278         if (!target__has_cpu(&ftrace->target))
279                 return 0;
280
281         return set_tracing_cpumask(cpumap);
282 }
283
284 static int set_tracing_func_stack_trace(struct perf_ftrace *ftrace)
285 {
286         if (!ftrace->func_stack_trace)
287                 return 0;
288
289         if (write_tracing_option_file("func_stack_trace", "1") < 0)
290                 return -1;
291
292         return 0;
293 }
294
295 static int reset_tracing_cpu(void)
296 {
297         struct perf_cpu_map *cpumap = perf_cpu_map__new(NULL);
298         int ret;
299
300         ret = set_tracing_cpumask(cpumap);
301         perf_cpu_map__put(cpumap);
302         return ret;
303 }
304
305 static int __set_tracing_filter(const char *filter_file, struct list_head *funcs)
306 {
307         struct filter_entry *pos;
308
309         list_for_each_entry(pos, funcs, list) {
310                 if (append_tracing_file(filter_file, pos->name) < 0)
311                         return -1;
312         }
313
314         return 0;
315 }
316
317 static int set_tracing_filters(struct perf_ftrace *ftrace)
318 {
319         int ret;
320
321         ret = __set_tracing_filter("set_ftrace_filter", &ftrace->filters);
322         if (ret < 0)
323                 return ret;
324
325         ret = __set_tracing_filter("set_ftrace_notrace", &ftrace->notrace);
326         if (ret < 0)
327                 return ret;
328
329         ret = __set_tracing_filter("set_graph_function", &ftrace->graph_funcs);
330         if (ret < 0)
331                 return ret;
332
333         /* old kernels do not have this filter */
334         __set_tracing_filter("set_graph_notrace", &ftrace->nograph_funcs);
335
336         return ret;
337 }
338
339 static void reset_tracing_filters(void)
340 {
341         write_tracing_file("set_ftrace_filter", " ");
342         write_tracing_file("set_ftrace_notrace", " ");
343         write_tracing_file("set_graph_function", " ");
344         write_tracing_file("set_graph_notrace", " ");
345 }
346
347 static int set_tracing_depth(struct perf_ftrace *ftrace)
348 {
349         if (ftrace->graph_depth == 0)
350                 return 0;
351
352         if (ftrace->graph_depth < 0) {
353                 pr_err("invalid graph depth: %d\n", ftrace->graph_depth);
354                 return -1;
355         }
356
357         if (write_tracing_file_int("max_graph_depth", ftrace->graph_depth) < 0)
358                 return -1;
359
360         return 0;
361 }
362
363 static int set_tracing_percpu_buffer_size(struct perf_ftrace *ftrace)
364 {
365         int ret;
366
367         if (ftrace->percpu_buffer_size == 0)
368                 return 0;
369
370         ret = write_tracing_file_int("buffer_size_kb",
371                                      ftrace->percpu_buffer_size / 1024);
372         if (ret < 0)
373                 return ret;
374
375         return 0;
376 }
377
378 static int set_tracing_trace_inherit(struct perf_ftrace *ftrace)
379 {
380         if (!ftrace->inherit)
381                 return 0;
382
383         if (write_tracing_option_file("function-fork", "1") < 0)
384                 return -1;
385
386         return 0;
387 }
388
389 static int __cmd_ftrace(struct perf_ftrace *ftrace, int argc, const char **argv)
390 {
391         char *trace_file;
392         int trace_fd;
393         char buf[4096];
394         struct pollfd pollfd = {
395                 .events = POLLIN,
396         };
397
398         if (!(perf_cap__capable(CAP_PERFMON) ||
399               perf_cap__capable(CAP_SYS_ADMIN))) {
400                 pr_err("ftrace only works for %s!\n",
401 #ifdef HAVE_LIBCAP_SUPPORT
402                 "users with the CAP_PERFMON or CAP_SYS_ADMIN capability"
403 #else
404                 "root"
405 #endif
406                 );
407                 return -1;
408         }
409
410         signal(SIGINT, sig_handler);
411         signal(SIGUSR1, sig_handler);
412         signal(SIGCHLD, sig_handler);
413         signal(SIGPIPE, sig_handler);
414
415         if (ftrace->list_avail_functions)
416                 return read_tracing_file_to_stdout("available_filter_functions");
417
418         if (reset_tracing_files(ftrace) < 0) {
419                 pr_err("failed to reset ftrace\n");
420                 goto out;
421         }
422
423         /* reset ftrace buffer */
424         if (write_tracing_file("trace", "0") < 0)
425                 goto out;
426
427         if (argc && perf_evlist__prepare_workload(ftrace->evlist,
428                                 &ftrace->target, argv, false,
429                                 ftrace__workload_exec_failed_signal) < 0) {
430                 goto out;
431         }
432
433         if (set_tracing_pid(ftrace) < 0) {
434                 pr_err("failed to set ftrace pid\n");
435                 goto out_reset;
436         }
437
438         if (set_tracing_cpu(ftrace) < 0) {
439                 pr_err("failed to set tracing cpumask\n");
440                 goto out_reset;
441         }
442
443         if (set_tracing_func_stack_trace(ftrace) < 0) {
444                 pr_err("failed to set tracing option func_stack_trace\n");
445                 goto out_reset;
446         }
447
448         if (set_tracing_filters(ftrace) < 0) {
449                 pr_err("failed to set tracing filters\n");
450                 goto out_reset;
451         }
452
453         if (set_tracing_depth(ftrace) < 0) {
454                 pr_err("failed to set graph depth\n");
455                 goto out_reset;
456         }
457
458         if (set_tracing_percpu_buffer_size(ftrace) < 0) {
459                 pr_err("failed to set tracing per-cpu buffer size\n");
460                 goto out_reset;
461         }
462
463         if (set_tracing_trace_inherit(ftrace) < 0) {
464                 pr_err("failed to set tracing option function-fork\n");
465                 goto out_reset;
466         }
467
468         if (write_tracing_file("current_tracer", ftrace->tracer) < 0) {
469                 pr_err("failed to set current_tracer to %s\n", ftrace->tracer);
470                 goto out_reset;
471         }
472
473         setup_pager();
474
475         trace_file = get_tracing_file("trace_pipe");
476         if (!trace_file) {
477                 pr_err("failed to open trace_pipe\n");
478                 goto out_reset;
479         }
480
481         trace_fd = open(trace_file, O_RDONLY);
482
483         put_tracing_file(trace_file);
484
485         if (trace_fd < 0) {
486                 pr_err("failed to open trace_pipe\n");
487                 goto out_reset;
488         }
489
490         fcntl(trace_fd, F_SETFL, O_NONBLOCK);
491         pollfd.fd = trace_fd;
492
493         /* display column headers */
494         read_tracing_file_to_stdout("trace");
495
496         if (write_tracing_file("tracing_on", "1") < 0) {
497                 pr_err("can't enable tracing\n");
498                 goto out_close_fd;
499         }
500
501         perf_evlist__start_workload(ftrace->evlist);
502
503         while (!done) {
504                 if (poll(&pollfd, 1, -1) < 0)
505                         break;
506
507                 if (pollfd.revents & POLLIN) {
508                         int n = read(trace_fd, buf, sizeof(buf));
509                         if (n < 0)
510                                 break;
511                         if (fwrite(buf, n, 1, stdout) != 1)
512                                 break;
513                 }
514         }
515
516         write_tracing_file("tracing_on", "0");
517
518         if (workload_exec_errno) {
519                 const char *emsg = str_error_r(workload_exec_errno, buf, sizeof(buf));
520                 /* flush stdout first so below error msg appears at the end. */
521                 fflush(stdout);
522                 pr_err("workload failed: %s\n", emsg);
523                 goto out_close_fd;
524         }
525
526         /* read remaining buffer contents */
527         while (true) {
528                 int n = read(trace_fd, buf, sizeof(buf));
529                 if (n <= 0)
530                         break;
531                 if (fwrite(buf, n, 1, stdout) != 1)
532                         break;
533         }
534
535 out_close_fd:
536         close(trace_fd);
537 out_reset:
538         reset_tracing_files(ftrace);
539 out:
540         return (done && !workload_exec_errno) ? 0 : -1;
541 }
542
543 static int perf_ftrace_config(const char *var, const char *value, void *cb)
544 {
545         struct perf_ftrace *ftrace = cb;
546
547         if (!strstarts(var, "ftrace."))
548                 return 0;
549
550         if (strcmp(var, "ftrace.tracer"))
551                 return -1;
552
553         if (!strcmp(value, "function_graph") ||
554             !strcmp(value, "function")) {
555                 ftrace->tracer = value;
556                 return 0;
557         }
558
559         pr_err("Please select \"function_graph\" (default) or \"function\"\n");
560         return -1;
561 }
562
563 static int parse_filter_func(const struct option *opt, const char *str,
564                              int unset __maybe_unused)
565 {
566         struct list_head *head = opt->value;
567         struct filter_entry *entry;
568
569         entry = malloc(sizeof(*entry) + strlen(str) + 1);
570         if (entry == NULL)
571                 return -ENOMEM;
572
573         strcpy(entry->name, str);
574         list_add_tail(&entry->list, head);
575
576         return 0;
577 }
578
579 static void delete_filter_func(struct list_head *head)
580 {
581         struct filter_entry *pos, *tmp;
582
583         list_for_each_entry_safe(pos, tmp, head, list) {
584                 list_del_init(&pos->list);
585                 free(pos);
586         }
587 }
588
589 static int parse_buffer_size(const struct option *opt,
590                              const char *str, int unset)
591 {
592         unsigned long *s = (unsigned long *)opt->value;
593         static struct parse_tag tags_size[] = {
594                 { .tag  = 'B', .mult = 1       },
595                 { .tag  = 'K', .mult = 1 << 10 },
596                 { .tag  = 'M', .mult = 1 << 20 },
597                 { .tag  = 'G', .mult = 1 << 30 },
598                 { .tag  = 0 },
599         };
600         unsigned long val;
601
602         if (unset) {
603                 *s = 0;
604                 return 0;
605         }
606
607         val = parse_tag_value(str, tags_size);
608         if (val != (unsigned long) -1) {
609                 if (val < 1024) {
610                         pr_err("buffer size too small, must larger than 1KB.");
611                         return -1;
612                 }
613                 *s = val;
614                 return 0;
615         }
616
617         return -1;
618 }
619
620 static int parse_func_tracer_opts(const struct option *opt,
621                                   const char *str, int unset)
622 {
623         int ret;
624         struct perf_ftrace *ftrace = (struct perf_ftrace *) opt->value;
625         struct sublevel_option func_tracer_opts[] = {
626                 { .name = "call-graph", .value_ptr = &ftrace->func_stack_trace },
627                 { .name = NULL, }
628         };
629
630         if (unset)
631                 return 0;
632
633         ret = perf_parse_sublevel_options(str, func_tracer_opts);
634         if (ret)
635                 return ret;
636
637         return 0;
638 }
639
640 static void select_tracer(struct perf_ftrace *ftrace)
641 {
642         bool graph = !list_empty(&ftrace->graph_funcs) ||
643                      !list_empty(&ftrace->nograph_funcs);
644         bool func = !list_empty(&ftrace->filters) ||
645                     !list_empty(&ftrace->notrace);
646
647         /* The function_graph has priority over function tracer. */
648         if (graph)
649                 ftrace->tracer = "function_graph";
650         else if (func)
651                 ftrace->tracer = "function";
652         /* Otherwise, the default tracer is used. */
653
654         pr_debug("%s tracer is used\n", ftrace->tracer);
655 }
656
657 int cmd_ftrace(int argc, const char **argv)
658 {
659         int ret;
660         struct perf_ftrace ftrace = {
661                 .tracer = DEFAULT_TRACER,
662                 .target = { .uid = UINT_MAX, },
663         };
664         const char * const ftrace_usage[] = {
665                 "perf ftrace [<options>] [<command>]",
666                 "perf ftrace [<options>] -- <command> [<options>]",
667                 NULL
668         };
669         const struct option ftrace_options[] = {
670         OPT_STRING('t', "tracer", &ftrace.tracer, "tracer",
671                    "tracer to use: function_graph(default) or function"),
672         OPT_BOOLEAN('F', "funcs", &ftrace.list_avail_functions,
673                     "Show available functions to filter"),
674         OPT_STRING('p', "pid", &ftrace.target.pid, "pid",
675                    "trace on existing process id"),
676         OPT_INCR('v', "verbose", &verbose,
677                  "be more verbose"),
678         OPT_BOOLEAN('a', "all-cpus", &ftrace.target.system_wide,
679                     "system-wide collection from all CPUs"),
680         OPT_STRING('C', "cpu", &ftrace.target.cpu_list, "cpu",
681                     "list of cpus to monitor"),
682         OPT_CALLBACK('T', "trace-funcs", &ftrace.filters, "func",
683                      "trace given functions using function tracer",
684                      parse_filter_func),
685         OPT_CALLBACK('N', "notrace-funcs", &ftrace.notrace, "func",
686                      "do not trace given functions", parse_filter_func),
687         OPT_CALLBACK(0, "func-opts", &ftrace, "options",
688                      "function tracer options, available options: call-graph",
689                      parse_func_tracer_opts),
690         OPT_CALLBACK('G', "graph-funcs", &ftrace.graph_funcs, "func",
691                      "trace given functions using function_graph tracer",
692                      parse_filter_func),
693         OPT_CALLBACK('g', "nograph-funcs", &ftrace.nograph_funcs, "func",
694                      "Set nograph filter on given functions", parse_filter_func),
695         OPT_INTEGER('D', "graph-depth", &ftrace.graph_depth,
696                     "Max depth for function graph tracer"),
697         OPT_CALLBACK('m', "buffer-size", &ftrace.percpu_buffer_size, "size",
698                      "size of per cpu buffer", parse_buffer_size),
699         OPT_BOOLEAN(0, "inherit", &ftrace.inherit,
700                     "trace children processes"),
701         OPT_END()
702         };
703
704         INIT_LIST_HEAD(&ftrace.filters);
705         INIT_LIST_HEAD(&ftrace.notrace);
706         INIT_LIST_HEAD(&ftrace.graph_funcs);
707         INIT_LIST_HEAD(&ftrace.nograph_funcs);
708
709         ret = perf_config(perf_ftrace_config, &ftrace);
710         if (ret < 0)
711                 return -1;
712
713         argc = parse_options(argc, argv, ftrace_options, ftrace_usage,
714                             PARSE_OPT_STOP_AT_NON_OPTION);
715         if (!argc && target__none(&ftrace.target))
716                 ftrace.target.system_wide = true;
717
718         select_tracer(&ftrace);
719
720         ret = target__validate(&ftrace.target);
721         if (ret) {
722                 char errbuf[512];
723
724                 target__strerror(&ftrace.target, ret, errbuf, 512);
725                 pr_err("%s\n", errbuf);
726                 goto out_delete_filters;
727         }
728
729         ftrace.evlist = evlist__new();
730         if (ftrace.evlist == NULL) {
731                 ret = -ENOMEM;
732                 goto out_delete_filters;
733         }
734
735         ret = perf_evlist__create_maps(ftrace.evlist, &ftrace.target);
736         if (ret < 0)
737                 goto out_delete_evlist;
738
739         ret = __cmd_ftrace(&ftrace, argc, argv);
740
741 out_delete_evlist:
742         evlist__delete(ftrace.evlist);
743
744 out_delete_filters:
745         delete_filter_func(&ftrace.filters);
746         delete_filter_func(&ftrace.notrace);
747         delete_filter_func(&ftrace.graph_funcs);
748         delete_filter_func(&ftrace.nograph_funcs);
749
750         return ret;
751 }