builtin-record.c 15 KB

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