builtin-record.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /*
  2. * builtin-record.c
  3. *
  4. * Builtin record command: Record the profile of a workload
  5. * (or a CPU, or a PID) into the perf.data output file - for
  6. * later analysis via perf report.
  7. */
  8. #define _FILE_OFFSET_BITS 64
  9. #include "builtin.h"
  10. #include "perf.h"
  11. #include "util/build-id.h"
  12. #include "util/util.h"
  13. #include "util/parse-options.h"
  14. #include "util/parse-events.h"
  15. #include "util/string.h"
  16. #include "util/header.h"
  17. #include "util/event.h"
  18. #include "util/debug.h"
  19. #include "util/session.h"
  20. #include "util/symbol.h"
  21. #include <unistd.h>
  22. #include <sched.h>
  23. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  24. static long default_interval = 0;
  25. static int nr_cpus = 0;
  26. static unsigned int page_size;
  27. static unsigned int mmap_pages = 128;
  28. static int freq = 1000;
  29. static int output;
  30. static const char *output_name = "perf.data";
  31. static int group = 0;
  32. static unsigned int realtime_prio = 0;
  33. static int raw_samples = 0;
  34. static int system_wide = 0;
  35. static int profile_cpu = -1;
  36. static pid_t target_pid = -1;
  37. static pid_t child_pid = -1;
  38. static int inherit = 1;
  39. static int force = 0;
  40. static int append_file = 0;
  41. static int call_graph = 0;
  42. static int inherit_stat = 0;
  43. static int no_samples = 0;
  44. static int sample_address = 0;
  45. static int multiplex = 0;
  46. static int multiplex_fd = -1;
  47. static long samples = 0;
  48. static struct timeval last_read;
  49. static struct timeval this_read;
  50. static u64 bytes_written = 0;
  51. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  52. static int nr_poll = 0;
  53. static int nr_cpu = 0;
  54. static int file_new = 1;
  55. static off_t post_processing_offset;
  56. static struct perf_session *session;
  57. struct mmap_data {
  58. int counter;
  59. void *base;
  60. unsigned int mask;
  61. unsigned int prev;
  62. };
  63. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  64. static unsigned long mmap_read_head(struct mmap_data *md)
  65. {
  66. struct perf_event_mmap_page *pc = md->base;
  67. long head;
  68. head = pc->data_head;
  69. rmb();
  70. return head;
  71. }
  72. static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
  73. {
  74. struct perf_event_mmap_page *pc = md->base;
  75. /*
  76. * ensure all reads are done before we write the tail out.
  77. */
  78. /* mb(); */
  79. pc->data_tail = tail;
  80. }
  81. static void write_output(void *buf, size_t size)
  82. {
  83. while (size) {
  84. int ret = write(output, buf, size);
  85. if (ret < 0)
  86. die("failed to write");
  87. size -= ret;
  88. buf += ret;
  89. bytes_written += ret;
  90. }
  91. }
  92. static int process_synthesized_event(event_t *event,
  93. struct perf_session *self __used)
  94. {
  95. write_output(event, event->header.size);
  96. return 0;
  97. }
  98. static void mmap_read(struct mmap_data *md)
  99. {
  100. unsigned int head = mmap_read_head(md);
  101. unsigned int old = md->prev;
  102. unsigned char *data = md->base + page_size;
  103. unsigned long size;
  104. void *buf;
  105. int diff;
  106. gettimeofday(&this_read, NULL);
  107. /*
  108. * If we're further behind than half the buffer, there's a chance
  109. * the writer will bite our tail and mess up the samples under us.
  110. *
  111. * If we somehow ended up ahead of the head, we got messed up.
  112. *
  113. * In either case, truncate and restart at head.
  114. */
  115. diff = head - old;
  116. if (diff < 0) {
  117. struct timeval iv;
  118. unsigned long msecs;
  119. timersub(&this_read, &last_read, &iv);
  120. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  121. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  122. " Last read %lu msecs ago.\n", msecs);
  123. /*
  124. * head points to a known good entry, start there.
  125. */
  126. old = head;
  127. }
  128. last_read = this_read;
  129. if (old != head)
  130. samples++;
  131. size = head - old;
  132. if ((old & md->mask) + size != (head & md->mask)) {
  133. buf = &data[old & md->mask];
  134. size = md->mask + 1 - (old & md->mask);
  135. old += size;
  136. write_output(buf, size);
  137. }
  138. buf = &data[old & md->mask];
  139. size = head - old;
  140. old += size;
  141. write_output(buf, size);
  142. md->prev = old;
  143. mmap_write_tail(md, old);
  144. }
  145. static volatile int done = 0;
  146. static volatile int signr = -1;
  147. static void sig_handler(int sig)
  148. {
  149. done = 1;
  150. signr = sig;
  151. }
  152. static void sig_atexit(void)
  153. {
  154. if (child_pid != -1)
  155. kill(child_pid, SIGTERM);
  156. if (signr == -1)
  157. return;
  158. signal(signr, SIG_DFL);
  159. kill(getpid(), signr);
  160. }
  161. static int group_fd;
  162. static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
  163. {
  164. struct perf_header_attr *h_attr;
  165. if (nr < session->header.attrs) {
  166. h_attr = session->header.attr[nr];
  167. } else {
  168. h_attr = perf_header_attr__new(a);
  169. if (h_attr != NULL)
  170. if (perf_header__add_attr(&session->header, h_attr) < 0) {
  171. perf_header_attr__delete(h_attr);
  172. h_attr = NULL;
  173. }
  174. }
  175. return h_attr;
  176. }
  177. static void create_counter(int counter, int cpu, pid_t pid)
  178. {
  179. char *filter = filters[counter];
  180. struct perf_event_attr *attr = attrs + counter;
  181. struct perf_header_attr *h_attr;
  182. int track = !counter; /* only the first counter needs these */
  183. int ret;
  184. struct {
  185. u64 count;
  186. u64 time_enabled;
  187. u64 time_running;
  188. u64 id;
  189. } read_data;
  190. attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
  191. PERF_FORMAT_TOTAL_TIME_RUNNING |
  192. PERF_FORMAT_ID;
  193. attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
  194. if (freq) {
  195. attr->sample_type |= PERF_SAMPLE_PERIOD;
  196. attr->freq = 1;
  197. attr->sample_freq = freq;
  198. }
  199. if (no_samples)
  200. attr->sample_freq = 0;
  201. if (inherit_stat)
  202. attr->inherit_stat = 1;
  203. if (sample_address)
  204. attr->sample_type |= PERF_SAMPLE_ADDR;
  205. if (call_graph)
  206. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  207. if (raw_samples) {
  208. attr->sample_type |= PERF_SAMPLE_TIME;
  209. attr->sample_type |= PERF_SAMPLE_RAW;
  210. attr->sample_type |= PERF_SAMPLE_CPU;
  211. }
  212. attr->mmap = track;
  213. attr->comm = track;
  214. attr->inherit = inherit;
  215. attr->disabled = 1;
  216. try_again:
  217. fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
  218. if (fd[nr_cpu][counter] < 0) {
  219. int err = errno;
  220. if (err == EPERM || err == EACCES)
  221. die("Permission error - are you root?\n"
  222. "\t Consider tweaking /proc/sys/kernel/perf_event_paranoid.\n");
  223. else if (err == ENODEV && profile_cpu != -1)
  224. die("No such device - did you specify an out-of-range profile CPU?\n");
  225. /*
  226. * If it's cycles then fall back to hrtimer
  227. * based cpu-clock-tick sw counter, which
  228. * is always available even if no PMU support:
  229. */
  230. if (attr->type == PERF_TYPE_HARDWARE
  231. && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
  232. if (verbose)
  233. warning(" ... trying to fall back to cpu-clock-ticks\n");
  234. attr->type = PERF_TYPE_SOFTWARE;
  235. attr->config = PERF_COUNT_SW_CPU_CLOCK;
  236. goto try_again;
  237. }
  238. printf("\n");
  239. error("perfcounter syscall returned with %d (%s)\n",
  240. fd[nr_cpu][counter], strerror(err));
  241. #if defined(__i386__) || defined(__x86_64__)
  242. if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP)
  243. die("No hardware sampling interrupt available. No APIC? If so then you can boot the kernel with the \"lapic\" boot parameter to force-enable it.\n");
  244. #endif
  245. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  246. exit(-1);
  247. }
  248. h_attr = get_header_attr(attr, counter);
  249. if (h_attr == NULL)
  250. die("nomem\n");
  251. if (!file_new) {
  252. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  253. fprintf(stderr, "incompatible append\n");
  254. exit(-1);
  255. }
  256. }
  257. if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
  258. perror("Unable to read perf file descriptor\n");
  259. exit(-1);
  260. }
  261. if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
  262. pr_warning("Not enough memory to add id\n");
  263. exit(-1);
  264. }
  265. assert(fd[nr_cpu][counter] >= 0);
  266. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  267. /*
  268. * First counter acts as the group leader:
  269. */
  270. if (group && group_fd == -1)
  271. group_fd = fd[nr_cpu][counter];
  272. if (multiplex && multiplex_fd == -1)
  273. multiplex_fd = fd[nr_cpu][counter];
  274. if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
  275. ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
  276. assert(ret != -1);
  277. } else {
  278. event_array[nr_poll].fd = fd[nr_cpu][counter];
  279. event_array[nr_poll].events = POLLIN;
  280. nr_poll++;
  281. mmap_array[nr_cpu][counter].counter = counter;
  282. mmap_array[nr_cpu][counter].prev = 0;
  283. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  284. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  285. PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
  286. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  287. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  288. exit(-1);
  289. }
  290. }
  291. if (filter != NULL) {
  292. ret = ioctl(fd[nr_cpu][counter],
  293. PERF_EVENT_IOC_SET_FILTER, filter);
  294. if (ret) {
  295. error("failed to set filter with %d (%s)\n", errno,
  296. strerror(errno));
  297. exit(-1);
  298. }
  299. }
  300. ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
  301. }
  302. static void open_counters(int cpu, pid_t pid)
  303. {
  304. int counter;
  305. group_fd = -1;
  306. for (counter = 0; counter < nr_counters; counter++)
  307. create_counter(counter, cpu, pid);
  308. nr_cpu++;
  309. }
  310. static int process_buildids(void)
  311. {
  312. u64 size = lseek(output, 0, SEEK_CUR);
  313. session->fd = output;
  314. return __perf_session__process_events(session, post_processing_offset,
  315. size - post_processing_offset,
  316. size, &build_id__mark_dso_hit_ops);
  317. }
  318. static void atexit_header(void)
  319. {
  320. session->header.data_size += bytes_written;
  321. process_buildids();
  322. perf_header__write(&session->header, output, true);
  323. }
  324. static int __cmd_record(int argc, const char **argv)
  325. {
  326. int i, counter;
  327. struct stat st;
  328. pid_t pid = 0;
  329. int flags;
  330. int err;
  331. unsigned long waking = 0;
  332. int child_ready_pipe[2], go_pipe[2];
  333. const bool forks = target_pid == -1 && argc > 0;
  334. char buf;
  335. page_size = sysconf(_SC_PAGE_SIZE);
  336. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  337. assert(nr_cpus <= MAX_NR_CPUS);
  338. assert(nr_cpus >= 0);
  339. atexit(sig_atexit);
  340. signal(SIGCHLD, sig_handler);
  341. signal(SIGINT, sig_handler);
  342. if (forks && (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0)) {
  343. perror("failed to create pipes");
  344. exit(-1);
  345. }
  346. if (!stat(output_name, &st) && st.st_size) {
  347. if (!force) {
  348. if (!append_file) {
  349. pr_err("Error, output file %s exists, use -A "
  350. "to append or -f to overwrite.\n",
  351. output_name);
  352. exit(-1);
  353. }
  354. } else {
  355. char oldname[PATH_MAX];
  356. snprintf(oldname, sizeof(oldname), "%s.old",
  357. output_name);
  358. unlink(oldname);
  359. rename(output_name, oldname);
  360. }
  361. } else {
  362. append_file = 0;
  363. }
  364. flags = O_CREAT|O_RDWR;
  365. if (append_file)
  366. file_new = 0;
  367. else
  368. flags |= O_TRUNC;
  369. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  370. if (output < 0) {
  371. perror("failed to create output file");
  372. exit(-1);
  373. }
  374. session = perf_session__new(output_name, O_WRONLY, force);
  375. if (session == NULL) {
  376. pr_err("Not enough memory for reading perf file header\n");
  377. return -1;
  378. }
  379. if (!file_new) {
  380. err = perf_header__read(&session->header, output);
  381. if (err < 0)
  382. return err;
  383. }
  384. if (raw_samples) {
  385. perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
  386. } else {
  387. for (i = 0; i < nr_counters; i++) {
  388. if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
  389. perf_header__set_feat(&session->header, HEADER_TRACE_INFO);
  390. break;
  391. }
  392. }
  393. }
  394. atexit(atexit_header);
  395. if (forks) {
  396. pid = fork();
  397. if (pid < 0) {
  398. perror("failed to fork");
  399. exit(-1);
  400. }
  401. if (!pid) {
  402. close(child_ready_pipe[0]);
  403. close(go_pipe[1]);
  404. fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
  405. /*
  406. * Do a dummy execvp to get the PLT entry resolved,
  407. * so we avoid the resolver overhead on the real
  408. * execvp call.
  409. */
  410. execvp("", (char **)argv);
  411. /*
  412. * Tell the parent we're ready to go
  413. */
  414. close(child_ready_pipe[1]);
  415. /*
  416. * Wait until the parent tells us to go.
  417. */
  418. if (read(go_pipe[0], &buf, 1) == -1)
  419. perror("unable to read pipe");
  420. execvp(argv[0], (char **)argv);
  421. perror(argv[0]);
  422. exit(-1);
  423. }
  424. child_pid = pid;
  425. if (!system_wide)
  426. target_pid = pid;
  427. close(child_ready_pipe[1]);
  428. close(go_pipe[0]);
  429. /*
  430. * wait for child to settle
  431. */
  432. if (read(child_ready_pipe[0], &buf, 1) == -1) {
  433. perror("unable to read pipe");
  434. exit(-1);
  435. }
  436. close(child_ready_pipe[0]);
  437. }
  438. if ((!system_wide && !inherit) || profile_cpu != -1) {
  439. open_counters(profile_cpu, target_pid);
  440. } else {
  441. for (i = 0; i < nr_cpus; i++)
  442. open_counters(i, target_pid);
  443. }
  444. if (file_new) {
  445. err = perf_header__write(&session->header, output, false);
  446. if (err < 0)
  447. return err;
  448. }
  449. post_processing_offset = lseek(output, 0, SEEK_CUR);
  450. err = event__synthesize_kernel_mmap(process_synthesized_event,
  451. session, "_text");
  452. if (err < 0) {
  453. pr_err("Couldn't record kernel reference relocation symbol.\n");
  454. return err;
  455. }
  456. err = event__synthesize_modules(process_synthesized_event, session);
  457. if (err < 0) {
  458. pr_err("Couldn't record kernel reference relocation symbol.\n");
  459. return err;
  460. }
  461. if (!system_wide && profile_cpu == -1)
  462. event__synthesize_thread(target_pid, process_synthesized_event,
  463. session);
  464. else
  465. event__synthesize_threads(process_synthesized_event, session);
  466. if (realtime_prio) {
  467. struct sched_param param;
  468. param.sched_priority = realtime_prio;
  469. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  470. pr_err("Could not set realtime priority.\n");
  471. exit(-1);
  472. }
  473. }
  474. /*
  475. * Let the child rip
  476. */
  477. if (forks)
  478. close(go_pipe[1]);
  479. for (;;) {
  480. int hits = samples;
  481. for (i = 0; i < nr_cpu; i++) {
  482. for (counter = 0; counter < nr_counters; counter++) {
  483. if (mmap_array[i][counter].base)
  484. mmap_read(&mmap_array[i][counter]);
  485. }
  486. }
  487. if (hits == samples) {
  488. if (done)
  489. break;
  490. err = poll(event_array, nr_poll, -1);
  491. waking++;
  492. }
  493. if (done) {
  494. for (i = 0; i < nr_cpu; i++) {
  495. for (counter = 0; counter < nr_counters; counter++)
  496. ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
  497. }
  498. }
  499. }
  500. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  501. /*
  502. * Approximate RIP event size: 24 bytes.
  503. */
  504. fprintf(stderr,
  505. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  506. (double)bytes_written / 1024.0 / 1024.0,
  507. output_name,
  508. bytes_written / 24);
  509. return 0;
  510. }
  511. static const char * const record_usage[] = {
  512. "perf record [<options>] [<command>]",
  513. "perf record [<options>] -- <command> [<options>]",
  514. NULL
  515. };
  516. static const struct option options[] = {
  517. OPT_CALLBACK('e', "event", NULL, "event",
  518. "event selector. use 'perf list' to list available events",
  519. parse_events),
  520. OPT_CALLBACK(0, "filter", NULL, "filter",
  521. "event filter", parse_filter),
  522. OPT_INTEGER('p', "pid", &target_pid,
  523. "record events on existing pid"),
  524. OPT_INTEGER('r', "realtime", &realtime_prio,
  525. "collect data with this RT SCHED_FIFO priority"),
  526. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  527. "collect raw sample records from all opened counters"),
  528. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  529. "system-wide collection from all CPUs"),
  530. OPT_BOOLEAN('A', "append", &append_file,
  531. "append to the output file to do incremental profiling"),
  532. OPT_INTEGER('C', "profile_cpu", &profile_cpu,
  533. "CPU to profile on"),
  534. OPT_BOOLEAN('f', "force", &force,
  535. "overwrite existing data file"),
  536. OPT_LONG('c', "count", &default_interval,
  537. "event period to sample"),
  538. OPT_STRING('o', "output", &output_name, "file",
  539. "output file name"),
  540. OPT_BOOLEAN('i', "inherit", &inherit,
  541. "child tasks inherit counters"),
  542. OPT_INTEGER('F', "freq", &freq,
  543. "profile at this frequency"),
  544. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  545. "number of mmap data pages"),
  546. OPT_BOOLEAN('g', "call-graph", &call_graph,
  547. "do call-graph (stack chain/backtrace) recording"),
  548. OPT_BOOLEAN('v', "verbose", &verbose,
  549. "be more verbose (show counter open errors, etc)"),
  550. OPT_BOOLEAN('s', "stat", &inherit_stat,
  551. "per thread counts"),
  552. OPT_BOOLEAN('d', "data", &sample_address,
  553. "Sample addresses"),
  554. OPT_BOOLEAN('n', "no-samples", &no_samples,
  555. "don't sample"),
  556. OPT_BOOLEAN('M', "multiplex", &multiplex,
  557. "multiplex counter output in a single channel"),
  558. OPT_END()
  559. };
  560. int cmd_record(int argc, const char **argv, const char *prefix __used)
  561. {
  562. int counter;
  563. argc = parse_options(argc, argv, options, record_usage,
  564. PARSE_OPT_STOP_AT_NON_OPTION);
  565. if (!argc && target_pid == -1 && !system_wide && profile_cpu == -1)
  566. usage_with_options(record_usage, options);
  567. symbol__init();
  568. if (!nr_counters) {
  569. nr_counters = 1;
  570. attrs[0].type = PERF_TYPE_HARDWARE;
  571. attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
  572. }
  573. /*
  574. * User specified count overrides default frequency.
  575. */
  576. if (default_interval)
  577. freq = 0;
  578. else if (freq) {
  579. default_interval = freq;
  580. } else {
  581. fprintf(stderr, "frequency and count are zero, aborting\n");
  582. exit(EXIT_FAILURE);
  583. }
  584. for (counter = 0; counter < nr_counters; counter++) {
  585. if (attrs[counter].sample_period)
  586. continue;
  587. attrs[counter].sample_period = default_interval;
  588. }
  589. return __cmd_record(argc, argv);
  590. }