builtin-record.c 15 KB

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