builtin-record.c 15 KB

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