builtin-record.c 15 KB

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