builtin-record.c 13 KB

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