builtin-record.c 13 KB

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