perf env: Introduce read_cpu_topology_map() method
[firefly-linux-kernel-4.4.55.git] / tools / perf / perf.c
1 /*
2  * perf.c
3  *
4  * Performance analysis utility.
5  *
6  * This is the main hub from which the sub-commands (perf stat,
7  * perf top, perf record, perf report, etc.) are started.
8  */
9 #include "builtin.h"
10
11 #include "util/env.h"
12 #include "util/exec_cmd.h"
13 #include "util/cache.h"
14 #include "util/quote.h"
15 #include "util/run-command.h"
16 #include "util/parse-events.h"
17 #include "util/parse-options.h"
18 #include "util/debug.h"
19 #include <api/fs/tracing_path.h>
20 #include <pthread.h>
21
22 const char perf_usage_string[] =
23         "perf [--version] [--help] [OPTIONS] COMMAND [ARGS]";
24
25 const char perf_more_info_string[] =
26         "See 'perf help COMMAND' for more information on a specific command.";
27
28 int use_browser = -1;
29 static int use_pager = -1;
30 const char *input_name;
31
32 struct cmd_struct {
33         const char *cmd;
34         int (*fn)(int, const char **, const char *);
35         int option;
36 };
37
38 static struct cmd_struct commands[] = {
39         { "buildid-cache", cmd_buildid_cache, 0 },
40         { "buildid-list", cmd_buildid_list, 0 },
41         { "diff",       cmd_diff,       0 },
42         { "evlist",     cmd_evlist,     0 },
43         { "help",       cmd_help,       0 },
44         { "list",       cmd_list,       0 },
45         { "record",     cmd_record,     0 },
46         { "report",     cmd_report,     0 },
47         { "bench",      cmd_bench,      0 },
48         { "stat",       cmd_stat,       0 },
49         { "timechart",  cmd_timechart,  0 },
50         { "top",        cmd_top,        0 },
51         { "annotate",   cmd_annotate,   0 },
52         { "version",    cmd_version,    0 },
53         { "script",     cmd_script,     0 },
54         { "sched",      cmd_sched,      0 },
55 #ifdef HAVE_LIBELF_SUPPORT
56         { "probe",      cmd_probe,      0 },
57 #endif
58         { "kmem",       cmd_kmem,       0 },
59         { "lock",       cmd_lock,       0 },
60         { "kvm",        cmd_kvm,        0 },
61         { "test",       cmd_test,       0 },
62 #ifdef HAVE_LIBAUDIT_SUPPORT
63         { "trace",      cmd_trace,      0 },
64 #endif
65         { "inject",     cmd_inject,     0 },
66         { "mem",        cmd_mem,        0 },
67         { "data",       cmd_data,       0 },
68 };
69
70 struct pager_config {
71         const char *cmd;
72         int val;
73 };
74
75 static int pager_command_config(const char *var, const char *value, void *data)
76 {
77         struct pager_config *c = data;
78         if (!prefixcmp(var, "pager.") && !strcmp(var + 6, c->cmd))
79                 c->val = perf_config_bool(var, value);
80         return 0;
81 }
82
83 /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
84 int check_pager_config(const char *cmd)
85 {
86         struct pager_config c;
87         c.cmd = cmd;
88         c.val = -1;
89         perf_config(pager_command_config, &c);
90         return c.val;
91 }
92
93 static int browser_command_config(const char *var, const char *value, void *data)
94 {
95         struct pager_config *c = data;
96         if (!prefixcmp(var, "tui.") && !strcmp(var + 4, c->cmd))
97                 c->val = perf_config_bool(var, value);
98         if (!prefixcmp(var, "gtk.") && !strcmp(var + 4, c->cmd))
99                 c->val = perf_config_bool(var, value) ? 2 : 0;
100         return 0;
101 }
102
103 /*
104  * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
105  * and -1 for "not specified"
106  */
107 static int check_browser_config(const char *cmd)
108 {
109         struct pager_config c;
110         c.cmd = cmd;
111         c.val = -1;
112         perf_config(browser_command_config, &c);
113         return c.val;
114 }
115
116 static void commit_pager_choice(void)
117 {
118         switch (use_pager) {
119         case 0:
120                 setenv("PERF_PAGER", "cat", 1);
121                 break;
122         case 1:
123                 /* setup_pager(); */
124                 break;
125         default:
126                 break;
127         }
128 }
129
130 struct option options[] = {
131         OPT_ARGUMENT("help", "help"),
132         OPT_ARGUMENT("version", "version"),
133         OPT_ARGUMENT("exec-path", "exec-path"),
134         OPT_ARGUMENT("html-path", "html-path"),
135         OPT_ARGUMENT("paginate", "paginate"),
136         OPT_ARGUMENT("no-pager", "no-pager"),
137         OPT_ARGUMENT("perf-dir", "perf-dir"),
138         OPT_ARGUMENT("work-tree", "work-tree"),
139         OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
140         OPT_ARGUMENT("buildid-dir", "buildid-dir"),
141         OPT_ARGUMENT("list-cmds", "list-cmds"),
142         OPT_ARGUMENT("list-opts", "list-opts"),
143         OPT_ARGUMENT("debug", "debug"),
144         OPT_END()
145 };
146
147 static int handle_options(const char ***argv, int *argc, int *envchanged)
148 {
149         int handled = 0;
150
151         while (*argc > 0) {
152                 const char *cmd = (*argv)[0];
153                 if (cmd[0] != '-')
154                         break;
155
156                 /*
157                  * For legacy reasons, the "version" and "help"
158                  * commands can be written with "--" prepended
159                  * to make them look like flags.
160                  */
161                 if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
162                         break;
163
164                 /*
165                  * Check remaining flags.
166                  */
167                 if (!prefixcmp(cmd, CMD_EXEC_PATH)) {
168                         cmd += strlen(CMD_EXEC_PATH);
169                         if (*cmd == '=')
170                                 perf_set_argv_exec_path(cmd + 1);
171                         else {
172                                 puts(perf_exec_path());
173                                 exit(0);
174                         }
175                 } else if (!strcmp(cmd, "--html-path")) {
176                         puts(system_path(PERF_HTML_PATH));
177                         exit(0);
178                 } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
179                         use_pager = 1;
180                 } else if (!strcmp(cmd, "--no-pager")) {
181                         use_pager = 0;
182                         if (envchanged)
183                                 *envchanged = 1;
184                 } else if (!strcmp(cmd, "--perf-dir")) {
185                         if (*argc < 2) {
186                                 fprintf(stderr, "No directory given for --perf-dir.\n");
187                                 usage(perf_usage_string);
188                         }
189                         setenv(PERF_DIR_ENVIRONMENT, (*argv)[1], 1);
190                         if (envchanged)
191                                 *envchanged = 1;
192                         (*argv)++;
193                         (*argc)--;
194                         handled++;
195                 } else if (!prefixcmp(cmd, CMD_PERF_DIR)) {
196                         setenv(PERF_DIR_ENVIRONMENT, cmd + strlen(CMD_PERF_DIR), 1);
197                         if (envchanged)
198                                 *envchanged = 1;
199                 } else if (!strcmp(cmd, "--work-tree")) {
200                         if (*argc < 2) {
201                                 fprintf(stderr, "No directory given for --work-tree.\n");
202                                 usage(perf_usage_string);
203                         }
204                         setenv(PERF_WORK_TREE_ENVIRONMENT, (*argv)[1], 1);
205                         if (envchanged)
206                                 *envchanged = 1;
207                         (*argv)++;
208                         (*argc)--;
209                 } else if (!prefixcmp(cmd, CMD_WORK_TREE)) {
210                         setenv(PERF_WORK_TREE_ENVIRONMENT, cmd + strlen(CMD_WORK_TREE), 1);
211                         if (envchanged)
212                                 *envchanged = 1;
213                 } else if (!strcmp(cmd, "--debugfs-dir")) {
214                         if (*argc < 2) {
215                                 fprintf(stderr, "No directory given for --debugfs-dir.\n");
216                                 usage(perf_usage_string);
217                         }
218                         tracing_path_set((*argv)[1]);
219                         if (envchanged)
220                                 *envchanged = 1;
221                         (*argv)++;
222                         (*argc)--;
223                 } else if (!strcmp(cmd, "--buildid-dir")) {
224                         if (*argc < 2) {
225                                 fprintf(stderr, "No directory given for --buildid-dir.\n");
226                                 usage(perf_usage_string);
227                         }
228                         set_buildid_dir((*argv)[1]);
229                         if (envchanged)
230                                 *envchanged = 1;
231                         (*argv)++;
232                         (*argc)--;
233                 } else if (!prefixcmp(cmd, CMD_DEBUGFS_DIR)) {
234                         tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
235                         fprintf(stderr, "dir: %s\n", tracing_path);
236                         if (envchanged)
237                                 *envchanged = 1;
238                 } else if (!strcmp(cmd, "--list-cmds")) {
239                         unsigned int i;
240
241                         for (i = 0; i < ARRAY_SIZE(commands); i++) {
242                                 struct cmd_struct *p = commands+i;
243                                 printf("%s ", p->cmd);
244                         }
245                         putchar('\n');
246                         exit(0);
247                 } else if (!strcmp(cmd, "--list-opts")) {
248                         unsigned int i;
249
250                         for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
251                                 struct option *p = options+i;
252                                 printf("--%s ", p->long_name);
253                         }
254                         putchar('\n');
255                         exit(0);
256                 } else if (!strcmp(cmd, "--debug")) {
257                         if (*argc < 2) {
258                                 fprintf(stderr, "No variable specified for --debug.\n");
259                                 usage(perf_usage_string);
260                         }
261                         if (perf_debug_option((*argv)[1]))
262                                 usage(perf_usage_string);
263
264                         (*argv)++;
265                         (*argc)--;
266                 } else {
267                         fprintf(stderr, "Unknown option: %s\n", cmd);
268                         usage(perf_usage_string);
269                 }
270
271                 (*argv)++;
272                 (*argc)--;
273                 handled++;
274         }
275         return handled;
276 }
277
278 static int handle_alias(int *argcp, const char ***argv)
279 {
280         int envchanged = 0, ret = 0, saved_errno = errno;
281         int count, option_count;
282         const char **new_argv;
283         const char *alias_command;
284         char *alias_string;
285
286         alias_command = (*argv)[0];
287         alias_string = alias_lookup(alias_command);
288         if (alias_string) {
289                 if (alias_string[0] == '!') {
290                         if (*argcp > 1) {
291                                 struct strbuf buf;
292
293                                 strbuf_init(&buf, PATH_MAX);
294                                 strbuf_addstr(&buf, alias_string);
295                                 sq_quote_argv(&buf, (*argv) + 1, PATH_MAX);
296                                 free(alias_string);
297                                 alias_string = buf.buf;
298                         }
299                         ret = system(alias_string + 1);
300                         if (ret >= 0 && WIFEXITED(ret) &&
301                             WEXITSTATUS(ret) != 127)
302                                 exit(WEXITSTATUS(ret));
303                         die("Failed to run '%s' when expanding alias '%s'",
304                             alias_string + 1, alias_command);
305                 }
306                 count = split_cmdline(alias_string, &new_argv);
307                 if (count < 0)
308                         die("Bad alias.%s string", alias_command);
309                 option_count = handle_options(&new_argv, &count, &envchanged);
310                 if (envchanged)
311                         die("alias '%s' changes environment variables\n"
312                                  "You can use '!perf' in the alias to do this.",
313                                  alias_command);
314                 memmove(new_argv - option_count, new_argv,
315                                 count * sizeof(char *));
316                 new_argv -= option_count;
317
318                 if (count < 1)
319                         die("empty alias for %s", alias_command);
320
321                 if (!strcmp(alias_command, new_argv[0]))
322                         die("recursive alias: %s", alias_command);
323
324                 new_argv = realloc(new_argv, sizeof(char *) *
325                                     (count + *argcp + 1));
326                 /* insert after command name */
327                 memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);
328                 new_argv[count + *argcp] = NULL;
329
330                 *argv = new_argv;
331                 *argcp += count - 1;
332
333                 ret = 1;
334         }
335
336         errno = saved_errno;
337
338         return ret;
339 }
340
341 const char perf_version_string[] = PERF_VERSION;
342
343 #define RUN_SETUP       (1<<0)
344 #define USE_PAGER       (1<<1)
345 /*
346  * require working tree to be present -- anything uses this needs
347  * RUN_SETUP for reading from the configuration file.
348  */
349 #define NEED_WORK_TREE  (1<<2)
350
351 static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
352 {
353         int status;
354         struct stat st;
355         const char *prefix;
356         char sbuf[STRERR_BUFSIZE];
357
358         prefix = NULL;
359         if (p->option & RUN_SETUP)
360                 prefix = NULL; /* setup_perf_directory(); */
361
362         if (use_browser == -1)
363                 use_browser = check_browser_config(p->cmd);
364
365         if (use_pager == -1 && p->option & RUN_SETUP)
366                 use_pager = check_pager_config(p->cmd);
367         if (use_pager == -1 && p->option & USE_PAGER)
368                 use_pager = 1;
369         commit_pager_choice();
370
371         status = p->fn(argc, argv, prefix);
372         exit_browser(status);
373         perf_env__exit(&perf_env);
374
375         if (status)
376                 return status & 0xff;
377
378         /* Somebody closed stdout? */
379         if (fstat(fileno(stdout), &st))
380                 return 0;
381         /* Ignore write errors for pipes and sockets.. */
382         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
383                 return 0;
384
385         status = 1;
386         /* Check for ENOSPC and EIO errors.. */
387         if (fflush(stdout)) {
388                 fprintf(stderr, "write failure on standard output: %s",
389                         strerror_r(errno, sbuf, sizeof(sbuf)));
390                 goto out;
391         }
392         if (ferror(stdout)) {
393                 fprintf(stderr, "unknown write failure on standard output");
394                 goto out;
395         }
396         if (fclose(stdout)) {
397                 fprintf(stderr, "close failed on standard output: %s",
398                         strerror_r(errno, sbuf, sizeof(sbuf)));
399                 goto out;
400         }
401         status = 0;
402 out:
403         return status;
404 }
405
406 static void handle_internal_command(int argc, const char **argv)
407 {
408         const char *cmd = argv[0];
409         unsigned int i;
410         static const char ext[] = STRIP_EXTENSION;
411
412         if (sizeof(ext) > 1) {
413                 i = strlen(argv[0]) - strlen(ext);
414                 if (i > 0 && !strcmp(argv[0] + i, ext)) {
415                         char *argv0 = strdup(argv[0]);
416                         argv[0] = cmd = argv0;
417                         argv0[i] = '\0';
418                 }
419         }
420
421         /* Turn "perf cmd --help" into "perf help cmd" */
422         if (argc > 1 && !strcmp(argv[1], "--help")) {
423                 argv[1] = argv[0];
424                 argv[0] = cmd = "help";
425         }
426
427         for (i = 0; i < ARRAY_SIZE(commands); i++) {
428                 struct cmd_struct *p = commands+i;
429                 if (strcmp(p->cmd, cmd))
430                         continue;
431                 exit(run_builtin(p, argc, argv));
432         }
433 }
434
435 static void execv_dashed_external(const char **argv)
436 {
437         struct strbuf cmd = STRBUF_INIT;
438         const char *tmp;
439         int status;
440
441         strbuf_addf(&cmd, "perf-%s", argv[0]);
442
443         /*
444          * argv[0] must be the perf command, but the argv array
445          * belongs to the caller, and may be reused in
446          * subsequent loop iterations. Save argv[0] and
447          * restore it on error.
448          */
449         tmp = argv[0];
450         argv[0] = cmd.buf;
451
452         /*
453          * if we fail because the command is not found, it is
454          * OK to return. Otherwise, we just pass along the status code.
455          */
456         status = run_command_v_opt(argv, 0);
457         if (status != -ERR_RUN_COMMAND_EXEC) {
458                 if (IS_RUN_COMMAND_ERR(status))
459                         die("unable to run '%s'", argv[0]);
460                 exit(-status);
461         }
462         errno = ENOENT; /* as if we called execvp */
463
464         argv[0] = tmp;
465
466         strbuf_release(&cmd);
467 }
468
469 static int run_argv(int *argcp, const char ***argv)
470 {
471         int done_alias = 0;
472
473         while (1) {
474                 /* See if it's an internal command */
475                 handle_internal_command(*argcp, *argv);
476
477                 /* .. then try the external ones */
478                 execv_dashed_external(*argv);
479
480                 /* It could be an alias -- this works around the insanity
481                  * of overriding "perf log" with "perf show" by having
482                  * alias.log = show
483                  */
484                 if (done_alias || !handle_alias(argcp, argv))
485                         break;
486                 done_alias = 1;
487         }
488
489         return done_alias;
490 }
491
492 static void pthread__block_sigwinch(void)
493 {
494         sigset_t set;
495
496         sigemptyset(&set);
497         sigaddset(&set, SIGWINCH);
498         pthread_sigmask(SIG_BLOCK, &set, NULL);
499 }
500
501 void pthread__unblock_sigwinch(void)
502 {
503         sigset_t set;
504
505         sigemptyset(&set);
506         sigaddset(&set, SIGWINCH);
507         pthread_sigmask(SIG_UNBLOCK, &set, NULL);
508 }
509
510 int main(int argc, const char **argv)
511 {
512         const char *cmd;
513         char sbuf[STRERR_BUFSIZE];
514
515         /* The page_size is placed in util object. */
516         page_size = sysconf(_SC_PAGE_SIZE);
517         cacheline_size = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);
518
519         cmd = perf_extract_argv0_path(argv[0]);
520         if (!cmd)
521                 cmd = "perf-help";
522
523         /* get debugfs/tracefs mount point from /proc/mounts */
524         tracing_path_mount();
525
526         /*
527          * "perf-xxxx" is the same as "perf xxxx", but we obviously:
528          *
529          *  - cannot take flags in between the "perf" and the "xxxx".
530          *  - cannot execute it externally (since it would just do
531          *    the same thing over again)
532          *
533          * So we just directly call the internal command handler, and
534          * die if that one cannot handle it.
535          */
536         if (!prefixcmp(cmd, "perf-")) {
537                 cmd += 5;
538                 argv[0] = cmd;
539                 handle_internal_command(argc, argv);
540                 fprintf(stderr, "cannot handle %s internally", cmd);
541                 goto out;
542         }
543         if (!prefixcmp(cmd, "trace")) {
544 #ifdef HAVE_LIBAUDIT_SUPPORT
545                 set_buildid_dir(NULL);
546                 setup_path();
547                 argv[0] = "trace";
548                 return cmd_trace(argc, argv, NULL);
549 #else
550                 fprintf(stderr,
551                         "trace command not available: missing audit-libs devel package at build time.\n");
552                 goto out;
553 #endif
554         }
555         /* Look for flags.. */
556         argv++;
557         argc--;
558         handle_options(&argv, &argc, NULL);
559         commit_pager_choice();
560         set_buildid_dir(NULL);
561
562         if (argc > 0) {
563                 if (!prefixcmp(argv[0], "--"))
564                         argv[0] += 2;
565         } else {
566                 /* The user didn't specify a command; give them help */
567                 printf("\n usage: %s\n\n", perf_usage_string);
568                 list_common_cmds_help();
569                 printf("\n %s\n\n", perf_more_info_string);
570                 goto out;
571         }
572         cmd = argv[0];
573
574         test_attr__init();
575
576         /*
577          * We use PATH to find perf commands, but we prepend some higher
578          * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
579          * environment, and the $(perfexecdir) from the Makefile at build
580          * time.
581          */
582         setup_path();
583         /*
584          * Block SIGWINCH notifications so that the thread that wants it can
585          * unblock and get syscalls like select interrupted instead of waiting
586          * forever while the signal goes to some other non interested thread.
587          */
588         pthread__block_sigwinch();
589
590         while (1) {
591                 static int done_help;
592                 int was_alias = run_argv(&argc, &argv);
593
594                 if (errno != ENOENT)
595                         break;
596
597                 if (was_alias) {
598                         fprintf(stderr, "Expansion of alias '%s' failed; "
599                                 "'%s' is not a perf-command\n",
600                                 cmd, argv[0]);
601                         goto out;
602                 }
603                 if (!done_help) {
604                         cmd = argv[0] = help_unknown_cmd(cmd);
605                         done_help = 1;
606                 } else
607                         break;
608         }
609
610         fprintf(stderr, "Failed to run command '%s': %s\n",
611                 cmd, strerror_r(errno, sbuf, sizeof(sbuf)));
612 out:
613         return 1;
614 }