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