perf.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * perf.c
  4. *
  5. * Performance analysis utility.
  6. *
  7. * This is the main hub from which the sub-commands (perf stat,
  8. * perf top, perf record, perf report, etc.) are started.
  9. */
  10. #include "builtin.h"
  11. #include "util/env.h"
  12. #include <subcmd/exec-cmd.h>
  13. #include "util/config.h"
  14. #include "util/quote.h"
  15. #include <subcmd/run-command.h>
  16. #include "util/parse-events.h"
  17. #include <subcmd/parse-options.h>
  18. #include "util/bpf-loader.h"
  19. #include "util/debug.h"
  20. #include "util/event.h"
  21. #include <api/fs/fs.h>
  22. #include <api/fs/tracing_path.h>
  23. #include <errno.h>
  24. #include <pthread.h>
  25. #include <signal.h>
  26. #include <stdlib.h>
  27. #include <time.h>
  28. #include <sys/types.h>
  29. #include <sys/stat.h>
  30. #include <unistd.h>
  31. #include <linux/kernel.h>
  32. const char perf_usage_string[] =
  33. "perf [--version] [--help] [OPTIONS] COMMAND [ARGS]";
  34. const char perf_more_info_string[] =
  35. "See 'perf help COMMAND' for more information on a specific command.";
  36. static int use_pager = -1;
  37. const char *input_name;
  38. struct cmd_struct {
  39. const char *cmd;
  40. int (*fn)(int, const char **);
  41. int option;
  42. };
  43. static struct cmd_struct commands[] = {
  44. { "buildid-cache", cmd_buildid_cache, 0 },
  45. { "buildid-list", cmd_buildid_list, 0 },
  46. { "config", cmd_config, 0 },
  47. { "c2c", cmd_c2c, 0 },
  48. { "diff", cmd_diff, 0 },
  49. { "evlist", cmd_evlist, 0 },
  50. { "help", cmd_help, 0 },
  51. { "kallsyms", cmd_kallsyms, 0 },
  52. { "list", cmd_list, 0 },
  53. { "record", cmd_record, 0 },
  54. { "report", cmd_report, 0 },
  55. { "bench", cmd_bench, 0 },
  56. { "stat", cmd_stat, 0 },
  57. { "timechart", cmd_timechart, 0 },
  58. { "top", cmd_top, 0 },
  59. { "annotate", cmd_annotate, 0 },
  60. { "version", cmd_version, 0 },
  61. { "script", cmd_script, 0 },
  62. { "sched", cmd_sched, 0 },
  63. #ifdef HAVE_LIBELF_SUPPORT
  64. { "probe", cmd_probe, 0 },
  65. #endif
  66. { "kmem", cmd_kmem, 0 },
  67. { "lock", cmd_lock, 0 },
  68. { "kvm", cmd_kvm, 0 },
  69. { "test", cmd_test, 0 },
  70. #if defined(HAVE_LIBAUDIT_SUPPORT) || defined(HAVE_SYSCALL_TABLE_SUPPORT)
  71. { "trace", cmd_trace, 0 },
  72. #endif
  73. { "inject", cmd_inject, 0 },
  74. { "mem", cmd_mem, 0 },
  75. { "data", cmd_data, 0 },
  76. { "ftrace", cmd_ftrace, 0 },
  77. };
  78. struct pager_config {
  79. const char *cmd;
  80. int val;
  81. };
  82. static int pager_command_config(const char *var, const char *value, void *data)
  83. {
  84. struct pager_config *c = data;
  85. if (strstarts(var, "pager.") && !strcmp(var + 6, c->cmd))
  86. c->val = perf_config_bool(var, value);
  87. return 0;
  88. }
  89. /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
  90. static int check_pager_config(const char *cmd)
  91. {
  92. int err;
  93. struct pager_config c;
  94. c.cmd = cmd;
  95. c.val = -1;
  96. err = perf_config(pager_command_config, &c);
  97. return err ?: c.val;
  98. }
  99. static int browser_command_config(const char *var, const char *value, void *data)
  100. {
  101. struct pager_config *c = data;
  102. if (strstarts(var, "tui.") && !strcmp(var + 4, c->cmd))
  103. c->val = perf_config_bool(var, value);
  104. if (strstarts(var, "gtk.") && !strcmp(var + 4, c->cmd))
  105. c->val = perf_config_bool(var, value) ? 2 : 0;
  106. return 0;
  107. }
  108. /*
  109. * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
  110. * and -1 for "not specified"
  111. */
  112. static int check_browser_config(const char *cmd)
  113. {
  114. int err;
  115. struct pager_config c;
  116. c.cmd = cmd;
  117. c.val = -1;
  118. err = perf_config(browser_command_config, &c);
  119. return err ?: c.val;
  120. }
  121. static void commit_pager_choice(void)
  122. {
  123. switch (use_pager) {
  124. case 0:
  125. setenv(PERF_PAGER_ENVIRONMENT, "cat", 1);
  126. break;
  127. case 1:
  128. /* setup_pager(); */
  129. break;
  130. default:
  131. break;
  132. }
  133. }
  134. struct option options[] = {
  135. OPT_ARGUMENT("help", "help"),
  136. OPT_ARGUMENT("version", "version"),
  137. OPT_ARGUMENT("exec-path", "exec-path"),
  138. OPT_ARGUMENT("html-path", "html-path"),
  139. OPT_ARGUMENT("paginate", "paginate"),
  140. OPT_ARGUMENT("no-pager", "no-pager"),
  141. OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
  142. OPT_ARGUMENT("buildid-dir", "buildid-dir"),
  143. OPT_ARGUMENT("list-cmds", "list-cmds"),
  144. OPT_ARGUMENT("list-opts", "list-opts"),
  145. OPT_ARGUMENT("debug", "debug"),
  146. OPT_END()
  147. };
  148. static int handle_options(const char ***argv, int *argc, int *envchanged)
  149. {
  150. int handled = 0;
  151. while (*argc > 0) {
  152. const char *cmd = (*argv)[0];
  153. if (cmd[0] != '-')
  154. break;
  155. /*
  156. * For legacy reasons, the "version" and "help"
  157. * commands can be written with "--" prepended
  158. * to make them look like flags.
  159. */
  160. if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
  161. break;
  162. /*
  163. * Shortcut for '-h' and '-v' options to invoke help
  164. * and version command.
  165. */
  166. if (!strcmp(cmd, "-h")) {
  167. (*argv)[0] = "--help";
  168. break;
  169. }
  170. if (!strcmp(cmd, "-v")) {
  171. (*argv)[0] = "--version";
  172. break;
  173. }
  174. if (!strcmp(cmd, "-vv")) {
  175. (*argv)[0] = "version";
  176. version_verbose = 1;
  177. break;
  178. }
  179. /*
  180. * Check remaining flags.
  181. */
  182. if (strstarts(cmd, CMD_EXEC_PATH)) {
  183. cmd += strlen(CMD_EXEC_PATH);
  184. if (*cmd == '=')
  185. set_argv_exec_path(cmd + 1);
  186. else {
  187. puts(get_argv_exec_path());
  188. exit(0);
  189. }
  190. } else if (!strcmp(cmd, "--html-path")) {
  191. puts(system_path(PERF_HTML_PATH));
  192. exit(0);
  193. } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
  194. use_pager = 1;
  195. } else if (!strcmp(cmd, "--no-pager")) {
  196. use_pager = 0;
  197. if (envchanged)
  198. *envchanged = 1;
  199. } else if (!strcmp(cmd, "--debugfs-dir")) {
  200. if (*argc < 2) {
  201. fprintf(stderr, "No directory given for --debugfs-dir.\n");
  202. usage(perf_usage_string);
  203. }
  204. tracing_path_set((*argv)[1]);
  205. if (envchanged)
  206. *envchanged = 1;
  207. (*argv)++;
  208. (*argc)--;
  209. } else if (!strcmp(cmd, "--buildid-dir")) {
  210. if (*argc < 2) {
  211. fprintf(stderr, "No directory given for --buildid-dir.\n");
  212. usage(perf_usage_string);
  213. }
  214. set_buildid_dir((*argv)[1]);
  215. if (envchanged)
  216. *envchanged = 1;
  217. (*argv)++;
  218. (*argc)--;
  219. } else if (strstarts(cmd, CMD_DEBUGFS_DIR)) {
  220. tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
  221. fprintf(stderr, "dir: %s\n", tracing_path);
  222. if (envchanged)
  223. *envchanged = 1;
  224. } else if (!strcmp(cmd, "--list-cmds")) {
  225. unsigned int i;
  226. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  227. struct cmd_struct *p = commands+i;
  228. printf("%s ", p->cmd);
  229. }
  230. putchar('\n');
  231. exit(0);
  232. } else if (!strcmp(cmd, "--list-opts")) {
  233. unsigned int i;
  234. for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
  235. struct option *p = options+i;
  236. printf("--%s ", p->long_name);
  237. }
  238. putchar('\n');
  239. exit(0);
  240. } else if (!strcmp(cmd, "--debug")) {
  241. if (*argc < 2) {
  242. fprintf(stderr, "No variable specified for --debug.\n");
  243. usage(perf_usage_string);
  244. }
  245. if (perf_debug_option((*argv)[1]))
  246. usage(perf_usage_string);
  247. (*argv)++;
  248. (*argc)--;
  249. } else {
  250. fprintf(stderr, "Unknown option: %s\n", cmd);
  251. usage(perf_usage_string);
  252. }
  253. (*argv)++;
  254. (*argc)--;
  255. handled++;
  256. }
  257. return handled;
  258. }
  259. #define RUN_SETUP (1<<0)
  260. #define USE_PAGER (1<<1)
  261. static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
  262. {
  263. int status;
  264. struct stat st;
  265. char sbuf[STRERR_BUFSIZE];
  266. if (use_browser == -1)
  267. use_browser = check_browser_config(p->cmd);
  268. if (use_pager == -1 && p->option & RUN_SETUP)
  269. use_pager = check_pager_config(p->cmd);
  270. if (use_pager == -1 && p->option & USE_PAGER)
  271. use_pager = 1;
  272. commit_pager_choice();
  273. perf_env__set_cmdline(&perf_env, argc, argv);
  274. status = p->fn(argc, argv);
  275. perf_config__exit();
  276. exit_browser(status);
  277. perf_env__exit(&perf_env);
  278. bpf__clear();
  279. if (status)
  280. return status & 0xff;
  281. /* Somebody closed stdout? */
  282. if (fstat(fileno(stdout), &st))
  283. return 0;
  284. /* Ignore write errors for pipes and sockets.. */
  285. if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
  286. return 0;
  287. status = 1;
  288. /* Check for ENOSPC and EIO errors.. */
  289. if (fflush(stdout)) {
  290. fprintf(stderr, "write failure on standard output: %s",
  291. str_error_r(errno, sbuf, sizeof(sbuf)));
  292. goto out;
  293. }
  294. if (ferror(stdout)) {
  295. fprintf(stderr, "unknown write failure on standard output");
  296. goto out;
  297. }
  298. if (fclose(stdout)) {
  299. fprintf(stderr, "close failed on standard output: %s",
  300. str_error_r(errno, sbuf, sizeof(sbuf)));
  301. goto out;
  302. }
  303. status = 0;
  304. out:
  305. return status;
  306. }
  307. static void handle_internal_command(int argc, const char **argv)
  308. {
  309. const char *cmd = argv[0];
  310. unsigned int i;
  311. /* Turn "perf cmd --help" into "perf help cmd" */
  312. if (argc > 1 && !strcmp(argv[1], "--help")) {
  313. argv[1] = argv[0];
  314. argv[0] = cmd = "help";
  315. }
  316. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  317. struct cmd_struct *p = commands+i;
  318. if (strcmp(p->cmd, cmd))
  319. continue;
  320. exit(run_builtin(p, argc, argv));
  321. }
  322. }
  323. static void execv_dashed_external(const char **argv)
  324. {
  325. char *cmd;
  326. const char *tmp;
  327. int status;
  328. if (asprintf(&cmd, "perf-%s", argv[0]) < 0)
  329. goto do_die;
  330. /*
  331. * argv[0] must be the perf command, but the argv array
  332. * belongs to the caller, and may be reused in
  333. * subsequent loop iterations. Save argv[0] and
  334. * restore it on error.
  335. */
  336. tmp = argv[0];
  337. argv[0] = cmd;
  338. /*
  339. * if we fail because the command is not found, it is
  340. * OK to return. Otherwise, we just pass along the status code.
  341. */
  342. status = run_command_v_opt(argv, 0);
  343. if (status != -ERR_RUN_COMMAND_EXEC) {
  344. if (IS_RUN_COMMAND_ERR(status)) {
  345. do_die:
  346. pr_err("FATAL: unable to run '%s'", argv[0]);
  347. status = -128;
  348. }
  349. exit(-status);
  350. }
  351. errno = ENOENT; /* as if we called execvp */
  352. argv[0] = tmp;
  353. zfree(&cmd);
  354. }
  355. static int run_argv(int *argcp, const char ***argv)
  356. {
  357. /* See if it's an internal command */
  358. handle_internal_command(*argcp, *argv);
  359. /* .. then try the external ones */
  360. execv_dashed_external(*argv);
  361. return 0;
  362. }
  363. static void pthread__block_sigwinch(void)
  364. {
  365. sigset_t set;
  366. sigemptyset(&set);
  367. sigaddset(&set, SIGWINCH);
  368. pthread_sigmask(SIG_BLOCK, &set, NULL);
  369. }
  370. void pthread__unblock_sigwinch(void)
  371. {
  372. sigset_t set;
  373. sigemptyset(&set);
  374. sigaddset(&set, SIGWINCH);
  375. pthread_sigmask(SIG_UNBLOCK, &set, NULL);
  376. }
  377. #ifdef _SC_LEVEL1_DCACHE_LINESIZE
  378. #define cache_line_size(cacheline_sizep) *cacheline_sizep = sysconf(_SC_LEVEL1_DCACHE_LINESIZE)
  379. #else
  380. static void cache_line_size(int *cacheline_sizep)
  381. {
  382. if (sysfs__read_int("devices/system/cpu/cpu0/cache/index0/coherency_line_size", cacheline_sizep))
  383. pr_debug("cannot determine cache line size");
  384. }
  385. #endif
  386. int main(int argc, const char **argv)
  387. {
  388. int err;
  389. const char *cmd;
  390. char sbuf[STRERR_BUFSIZE];
  391. int value;
  392. /* libsubcmd init */
  393. exec_cmd_init("perf", PREFIX, PERF_EXEC_PATH, EXEC_PATH_ENVIRONMENT);
  394. pager_init(PERF_PAGER_ENVIRONMENT);
  395. /* The page_size is placed in util object. */
  396. page_size = sysconf(_SC_PAGE_SIZE);
  397. cache_line_size(&cacheline_size);
  398. if (sysctl__read_int("kernel/perf_event_max_stack", &value) == 0)
  399. sysctl_perf_event_max_stack = value;
  400. if (sysctl__read_int("kernel/perf_event_max_contexts_per_stack", &value) == 0)
  401. sysctl_perf_event_max_contexts_per_stack = value;
  402. cmd = extract_argv0_path(argv[0]);
  403. if (!cmd)
  404. cmd = "perf-help";
  405. srandom(time(NULL));
  406. perf_config__init();
  407. err = perf_config(perf_default_config, NULL);
  408. if (err)
  409. return err;
  410. set_buildid_dir(NULL);
  411. /* get debugfs/tracefs mount point from /proc/mounts */
  412. tracing_path_mount();
  413. /*
  414. * "perf-xxxx" is the same as "perf xxxx", but we obviously:
  415. *
  416. * - cannot take flags in between the "perf" and the "xxxx".
  417. * - cannot execute it externally (since it would just do
  418. * the same thing over again)
  419. *
  420. * So we just directly call the internal command handler. If that one
  421. * fails to handle this, then maybe we just run a renamed perf binary
  422. * that contains a dash in its name. To handle this scenario, we just
  423. * fall through and ignore the "xxxx" part of the command string.
  424. */
  425. if (strstarts(cmd, "perf-")) {
  426. cmd += 5;
  427. argv[0] = cmd;
  428. handle_internal_command(argc, argv);
  429. /*
  430. * If the command is handled, the above function does not
  431. * return undo changes and fall through in such a case.
  432. */
  433. cmd -= 5;
  434. argv[0] = cmd;
  435. }
  436. if (strstarts(cmd, "trace")) {
  437. #if defined(HAVE_LIBAUDIT_SUPPORT) || defined(HAVE_SYSCALL_TABLE_SUPPORT)
  438. setup_path();
  439. argv[0] = "trace";
  440. return cmd_trace(argc, argv);
  441. #else
  442. fprintf(stderr,
  443. "trace command not available: missing audit-libs devel package at build time.\n");
  444. goto out;
  445. #endif
  446. }
  447. /* Look for flags.. */
  448. argv++;
  449. argc--;
  450. handle_options(&argv, &argc, NULL);
  451. commit_pager_choice();
  452. if (argc > 0) {
  453. if (strstarts(argv[0], "--"))
  454. argv[0] += 2;
  455. } else {
  456. /* The user didn't specify a command; give them help */
  457. printf("\n usage: %s\n\n", perf_usage_string);
  458. list_common_cmds_help();
  459. printf("\n %s\n\n", perf_more_info_string);
  460. goto out;
  461. }
  462. cmd = argv[0];
  463. test_attr__init();
  464. /*
  465. * We use PATH to find perf commands, but we prepend some higher
  466. * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
  467. * environment, and the $(perfexecdir) from the Makefile at build
  468. * time.
  469. */
  470. setup_path();
  471. /*
  472. * Block SIGWINCH notifications so that the thread that wants it can
  473. * unblock and get syscalls like select interrupted instead of waiting
  474. * forever while the signal goes to some other non interested thread.
  475. */
  476. pthread__block_sigwinch();
  477. perf_debug_setup();
  478. while (1) {
  479. static int done_help;
  480. run_argv(&argc, &argv);
  481. if (errno != ENOENT)
  482. break;
  483. if (!done_help) {
  484. cmd = argv[0] = help_unknown_cmd(cmd);
  485. done_help = 1;
  486. } else
  487. break;
  488. }
  489. fprintf(stderr, "Failed to run command '%s': %s\n",
  490. cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
  491. out:
  492. return 1;
  493. }