builtin-record.c 15 KB

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