builtin-record.c 17 KB

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