builtin-record.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. perf_header__add_attr(header, h_attr);
  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 (freq) {
  196. attr->sample_type |= PERF_SAMPLE_PERIOD;
  197. attr->freq = 1;
  198. attr->sample_freq = freq;
  199. }
  200. if (no_samples)
  201. attr->sample_freq = 0;
  202. if (inherit_stat)
  203. attr->inherit_stat = 1;
  204. if (sample_address)
  205. attr->sample_type |= PERF_SAMPLE_ADDR;
  206. if (call_graph)
  207. attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
  208. if (raw_samples) {
  209. attr->sample_type |= PERF_SAMPLE_TIME;
  210. attr->sample_type |= PERF_SAMPLE_RAW;
  211. attr->sample_type |= PERF_SAMPLE_CPU;
  212. }
  213. attr->mmap = track;
  214. attr->comm = track;
  215. attr->inherit = (cpu < 0) && inherit;
  216. attr->disabled = 1;
  217. try_again:
  218. fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
  219. if (fd[nr_cpu][counter] < 0) {
  220. int err = errno;
  221. if (err == EPERM)
  222. die("Permission error - are you root?\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. die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
  242. exit(-1);
  243. }
  244. h_attr = get_header_attr(attr, counter);
  245. if (!file_new) {
  246. if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
  247. fprintf(stderr, "incompatible append\n");
  248. exit(-1);
  249. }
  250. }
  251. if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
  252. perror("Unable to read perf file descriptor\n");
  253. exit(-1);
  254. }
  255. perf_header_attr__add_id(h_attr, read_data.id);
  256. assert(fd[nr_cpu][counter] >= 0);
  257. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  258. /*
  259. * First counter acts as the group leader:
  260. */
  261. if (group && group_fd == -1)
  262. group_fd = fd[nr_cpu][counter];
  263. if (multiplex && multiplex_fd == -1)
  264. multiplex_fd = fd[nr_cpu][counter];
  265. if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
  266. ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
  267. assert(ret != -1);
  268. } else {
  269. event_array[nr_poll].fd = fd[nr_cpu][counter];
  270. event_array[nr_poll].events = POLLIN;
  271. nr_poll++;
  272. mmap_array[nr_cpu][counter].counter = counter;
  273. mmap_array[nr_cpu][counter].prev = 0;
  274. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  275. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  276. PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
  277. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  278. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  279. exit(-1);
  280. }
  281. }
  282. if (filter != NULL) {
  283. ret = ioctl(fd[nr_cpu][counter],
  284. PERF_EVENT_IOC_SET_FILTER, filter);
  285. if (ret) {
  286. error("failed to set filter with %d (%s)\n", errno,
  287. strerror(errno));
  288. exit(-1);
  289. }
  290. }
  291. ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
  292. }
  293. static void open_counters(int cpu, pid_t pid)
  294. {
  295. int counter;
  296. group_fd = -1;
  297. for (counter = 0; counter < nr_counters; counter++)
  298. create_counter(counter, cpu, pid);
  299. nr_cpu++;
  300. }
  301. static void atexit_header(void)
  302. {
  303. header->data_size += bytes_written;
  304. perf_header__write(header, output, true);
  305. }
  306. static int __cmd_record(int argc, const char **argv)
  307. {
  308. int i, counter;
  309. struct stat st;
  310. pid_t pid = 0;
  311. int flags;
  312. int ret;
  313. unsigned long waking = 0;
  314. page_size = sysconf(_SC_PAGE_SIZE);
  315. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  316. assert(nr_cpus <= MAX_NR_CPUS);
  317. assert(nr_cpus >= 0);
  318. atexit(sig_atexit);
  319. signal(SIGCHLD, sig_handler);
  320. signal(SIGINT, sig_handler);
  321. if (!stat(output_name, &st) && st.st_size) {
  322. if (!force && !append_file) {
  323. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  324. output_name);
  325. exit(-1);
  326. }
  327. } else {
  328. append_file = 0;
  329. }
  330. flags = O_CREAT|O_RDWR;
  331. if (append_file)
  332. file_new = 0;
  333. else
  334. flags |= O_TRUNC;
  335. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  336. if (output < 0) {
  337. perror("failed to create output file");
  338. exit(-1);
  339. }
  340. if (!file_new)
  341. header = perf_header__read(output);
  342. else
  343. header = perf_header__new();
  344. if (raw_samples) {
  345. perf_header__set_feat(header, HEADER_TRACE_INFO);
  346. } else {
  347. for (i = 0; i < nr_counters; i++) {
  348. if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
  349. perf_header__set_feat(header, HEADER_TRACE_INFO);
  350. break;
  351. }
  352. }
  353. }
  354. atexit(atexit_header);
  355. if (!system_wide) {
  356. pid = target_pid;
  357. if (pid == -1)
  358. pid = getpid();
  359. open_counters(profile_cpu, pid);
  360. } else {
  361. if (profile_cpu != -1) {
  362. open_counters(profile_cpu, target_pid);
  363. } else {
  364. for (i = 0; i < nr_cpus; i++)
  365. open_counters(i, target_pid);
  366. }
  367. }
  368. if (file_new)
  369. perf_header__write(header, output, false);
  370. if (!system_wide)
  371. event__synthesize_thread(pid, process_synthesized_event);
  372. else
  373. event__synthesize_threads(process_synthesized_event);
  374. if (target_pid == -1 && argc) {
  375. pid = fork();
  376. if (pid < 0)
  377. die("failed to fork");
  378. if (!pid) {
  379. if (execvp(argv[0], (char **)argv)) {
  380. perror(argv[0]);
  381. exit(-1);
  382. }
  383. } else {
  384. /*
  385. * Wait a bit for the execv'ed child to appear
  386. * and be updated in /proc
  387. * FIXME: Do you know a less heuristical solution?
  388. */
  389. usleep(1000);
  390. event__synthesize_thread(pid,
  391. process_synthesized_event);
  392. }
  393. child_pid = pid;
  394. }
  395. if (realtime_prio) {
  396. struct sched_param param;
  397. param.sched_priority = realtime_prio;
  398. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  399. pr_err("Could not set realtime priority.\n");
  400. exit(-1);
  401. }
  402. }
  403. for (;;) {
  404. int hits = samples;
  405. for (i = 0; i < nr_cpu; i++) {
  406. for (counter = 0; counter < nr_counters; counter++) {
  407. if (mmap_array[i][counter].base)
  408. mmap_read(&mmap_array[i][counter]);
  409. }
  410. }
  411. if (hits == samples) {
  412. if (done)
  413. break;
  414. ret = poll(event_array, nr_poll, -1);
  415. waking++;
  416. }
  417. if (done) {
  418. for (i = 0; i < nr_cpu; i++) {
  419. for (counter = 0; counter < nr_counters; counter++)
  420. ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
  421. }
  422. }
  423. }
  424. fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
  425. /*
  426. * Approximate RIP event size: 24 bytes.
  427. */
  428. fprintf(stderr,
  429. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  430. (double)bytes_written / 1024.0 / 1024.0,
  431. output_name,
  432. bytes_written / 24);
  433. return 0;
  434. }
  435. static const char * const record_usage[] = {
  436. "perf record [<options>] [<command>]",
  437. "perf record [<options>] -- <command> [<options>]",
  438. NULL
  439. };
  440. static const struct option options[] = {
  441. OPT_CALLBACK('e', "event", NULL, "event",
  442. "event selector. use 'perf list' to list available events",
  443. parse_events),
  444. OPT_CALLBACK(0, "filter", NULL, "filter",
  445. "event filter", parse_filter),
  446. OPT_INTEGER('p', "pid", &target_pid,
  447. "record events on existing pid"),
  448. OPT_INTEGER('r', "realtime", &realtime_prio,
  449. "collect data with this RT SCHED_FIFO priority"),
  450. OPT_BOOLEAN('R', "raw-samples", &raw_samples,
  451. "collect raw sample records from all opened counters"),
  452. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  453. "system-wide collection from all CPUs"),
  454. OPT_BOOLEAN('A', "append", &append_file,
  455. "append to the output file to do incremental profiling"),
  456. OPT_INTEGER('C', "profile_cpu", &profile_cpu,
  457. "CPU to profile on"),
  458. OPT_BOOLEAN('f', "force", &force,
  459. "overwrite existing data file"),
  460. OPT_LONG('c', "count", &default_interval,
  461. "event period to sample"),
  462. OPT_STRING('o', "output", &output_name, "file",
  463. "output file name"),
  464. OPT_BOOLEAN('i', "inherit", &inherit,
  465. "child tasks inherit counters"),
  466. OPT_INTEGER('F', "freq", &freq,
  467. "profile at this frequency"),
  468. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  469. "number of mmap data pages"),
  470. OPT_BOOLEAN('g', "call-graph", &call_graph,
  471. "do call-graph (stack chain/backtrace) recording"),
  472. OPT_BOOLEAN('v', "verbose", &verbose,
  473. "be more verbose (show counter open errors, etc)"),
  474. OPT_BOOLEAN('s', "stat", &inherit_stat,
  475. "per thread counts"),
  476. OPT_BOOLEAN('d', "data", &sample_address,
  477. "Sample addresses"),
  478. OPT_BOOLEAN('n', "no-samples", &no_samples,
  479. "don't sample"),
  480. OPT_BOOLEAN('M', "multiplex", &multiplex,
  481. "multiplex counter output in a single channel"),
  482. OPT_END()
  483. };
  484. int cmd_record(int argc, const char **argv, const char *prefix __used)
  485. {
  486. int counter;
  487. symbol__init(0);
  488. argc = parse_options(argc, argv, options, record_usage,
  489. PARSE_OPT_STOP_AT_NON_OPTION);
  490. if (!argc && target_pid == -1 && !system_wide)
  491. usage_with_options(record_usage, options);
  492. if (!nr_counters) {
  493. nr_counters = 1;
  494. attrs[0].type = PERF_TYPE_HARDWARE;
  495. attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
  496. }
  497. /*
  498. * User specified count overrides default frequency.
  499. */
  500. if (default_interval)
  501. freq = 0;
  502. else if (freq) {
  503. default_interval = freq;
  504. } else {
  505. fprintf(stderr, "frequency and count are zero, aborting\n");
  506. exit(EXIT_FAILURE);
  507. }
  508. for (counter = 0; counter < nr_counters; counter++) {
  509. if (attrs[counter].sample_period)
  510. continue;
  511. attrs[counter].sample_period = default_interval;
  512. }
  513. return __cmd_record(argc, argv);
  514. }