builtin-record.c 14 KB

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