builtin-record.c 13 KB

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