builtin-record.c 15 KB

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