builtin-record.c 14 KB

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