builtin-record.c 17 KB

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