builtin-record.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 void sig_handler(int sig)
  133. {
  134. done = 1;
  135. }
  136. static void pid_synthesize_comm_event(pid_t pid, int full)
  137. {
  138. struct comm_event comm_ev;
  139. char filename[PATH_MAX];
  140. char bf[BUFSIZ];
  141. int fd, ret;
  142. size_t size;
  143. char *field, *sep;
  144. DIR *tasks;
  145. struct dirent dirent, *next;
  146. snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
  147. fd = open(filename, O_RDONLY);
  148. if (fd < 0) {
  149. fprintf(stderr, "couldn't open %s\n", filename);
  150. exit(EXIT_FAILURE);
  151. }
  152. if (read(fd, bf, sizeof(bf)) < 0) {
  153. fprintf(stderr, "couldn't read %s\n", filename);
  154. exit(EXIT_FAILURE);
  155. }
  156. close(fd);
  157. /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
  158. memset(&comm_ev, 0, sizeof(comm_ev));
  159. field = strchr(bf, '(');
  160. if (field == NULL)
  161. goto out_failure;
  162. sep = strchr(++field, ')');
  163. if (sep == NULL)
  164. goto out_failure;
  165. size = sep - field;
  166. memcpy(comm_ev.comm, field, size++);
  167. comm_ev.pid = pid;
  168. comm_ev.header.type = PERF_EVENT_COMM;
  169. size = ALIGN(size, sizeof(uint64_t));
  170. comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
  171. if (!full) {
  172. comm_ev.tid = pid;
  173. ret = write(output, &comm_ev, comm_ev.header.size);
  174. if (ret < 0) {
  175. perror("failed to write");
  176. exit(-1);
  177. }
  178. return;
  179. }
  180. snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
  181. tasks = opendir(filename);
  182. while (!readdir_r(tasks, &dirent, &next) && next) {
  183. char *end;
  184. pid = strtol(dirent.d_name, &end, 10);
  185. if (*end)
  186. continue;
  187. comm_ev.tid = pid;
  188. ret = write(output, &comm_ev, comm_ev.header.size);
  189. if (ret < 0) {
  190. perror("failed to write");
  191. exit(-1);
  192. }
  193. }
  194. closedir(tasks);
  195. return;
  196. out_failure:
  197. fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
  198. filename);
  199. exit(EXIT_FAILURE);
  200. }
  201. static void pid_synthesize_mmap_samples(pid_t pid)
  202. {
  203. char filename[PATH_MAX];
  204. FILE *fp;
  205. snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
  206. fp = fopen(filename, "r");
  207. if (fp == NULL) {
  208. fprintf(stderr, "couldn't open %s\n", filename);
  209. exit(EXIT_FAILURE);
  210. }
  211. while (1) {
  212. char bf[BUFSIZ], *pbf = bf;
  213. struct mmap_event mmap_ev = {
  214. .header.type = PERF_EVENT_MMAP,
  215. };
  216. int n;
  217. size_t size;
  218. if (fgets(bf, sizeof(bf), fp) == NULL)
  219. break;
  220. /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
  221. n = hex2u64(pbf, &mmap_ev.start);
  222. if (n < 0)
  223. continue;
  224. pbf += n + 1;
  225. n = hex2u64(pbf, &mmap_ev.len);
  226. if (n < 0)
  227. continue;
  228. pbf += n + 3;
  229. if (*pbf == 'x') { /* vm_exec */
  230. char *execname = strrchr(bf, ' ');
  231. if (execname == NULL || execname[1] != '/')
  232. continue;
  233. execname += 1;
  234. size = strlen(execname);
  235. execname[size - 1] = '\0'; /* Remove \n */
  236. memcpy(mmap_ev.filename, execname, size);
  237. size = ALIGN(size, sizeof(uint64_t));
  238. mmap_ev.len -= mmap_ev.start;
  239. mmap_ev.header.size = (sizeof(mmap_ev) -
  240. (sizeof(mmap_ev.filename) - size));
  241. mmap_ev.pid = pid;
  242. mmap_ev.tid = pid;
  243. if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
  244. perror("failed to write");
  245. exit(-1);
  246. }
  247. }
  248. }
  249. fclose(fp);
  250. }
  251. static void synthesize_samples(void)
  252. {
  253. DIR *proc;
  254. struct dirent dirent, *next;
  255. proc = opendir("/proc");
  256. while (!readdir_r(proc, &dirent, &next) && next) {
  257. char *end;
  258. pid_t pid;
  259. pid = strtol(dirent.d_name, &end, 10);
  260. if (*end) /* only interested in proper numerical dirents */
  261. continue;
  262. pid_synthesize_comm_event(pid, 1);
  263. pid_synthesize_mmap_samples(pid);
  264. }
  265. closedir(proc);
  266. }
  267. static int group_fd;
  268. static void create_counter(int counter, int cpu, pid_t pid)
  269. {
  270. struct perf_counter_attr *attr = attrs + counter;
  271. int track = 1;
  272. attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD;
  273. if (freq) {
  274. attr->freq = 1;
  275. attr->sample_freq = freq;
  276. }
  277. attr->mmap = track;
  278. attr->comm = track;
  279. attr->inherit = (cpu < 0) && inherit;
  280. track = 0; /* only the first counter needs these */
  281. try_again:
  282. fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
  283. if (fd[nr_cpu][counter] < 0) {
  284. int err = errno;
  285. if (err == EPERM)
  286. die("Permission error - are you root?\n");
  287. /*
  288. * If it's cycles then fall back to hrtimer
  289. * based cpu-clock-tick sw counter, which
  290. * is always available even if no PMU support:
  291. */
  292. if (attr->type == PERF_TYPE_HARDWARE
  293. && attr->config == PERF_COUNT_CPU_CYCLES) {
  294. if (verbose)
  295. warning(" ... trying to fall back to cpu-clock-ticks\n");
  296. attr->type = PERF_TYPE_SOFTWARE;
  297. attr->config = PERF_COUNT_CPU_CLOCK;
  298. goto try_again;
  299. }
  300. printf("\n");
  301. error("perfcounter syscall returned with %d (%s)\n",
  302. fd[nr_cpu][counter], strerror(err));
  303. die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
  304. exit(-1);
  305. }
  306. assert(fd[nr_cpu][counter] >= 0);
  307. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  308. /*
  309. * First counter acts as the group leader:
  310. */
  311. if (group && group_fd == -1)
  312. group_fd = fd[nr_cpu][counter];
  313. event_array[nr_poll].fd = fd[nr_cpu][counter];
  314. event_array[nr_poll].events = POLLIN;
  315. nr_poll++;
  316. mmap_array[nr_cpu][counter].counter = counter;
  317. mmap_array[nr_cpu][counter].prev = 0;
  318. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  319. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  320. PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
  321. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  322. error("failed to mmap with %d (%s)\n", errno, strerror(errno));
  323. exit(-1);
  324. }
  325. }
  326. static void open_counters(int cpu, pid_t pid)
  327. {
  328. int counter;
  329. if (pid > 0) {
  330. pid_synthesize_comm_event(pid, 0);
  331. pid_synthesize_mmap_samples(pid);
  332. }
  333. group_fd = -1;
  334. for (counter = 0; counter < nr_counters; counter++)
  335. create_counter(counter, cpu, pid);
  336. nr_cpu++;
  337. }
  338. static int __cmd_record(int argc, const char **argv)
  339. {
  340. int i, counter;
  341. struct stat st;
  342. pid_t pid;
  343. int flags;
  344. int ret;
  345. page_size = sysconf(_SC_PAGE_SIZE);
  346. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  347. assert(nr_cpus <= MAX_NR_CPUS);
  348. assert(nr_cpus >= 0);
  349. if (!stat(output_name, &st) && !force && !append_file) {
  350. fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
  351. output_name);
  352. exit(-1);
  353. }
  354. flags = O_CREAT|O_RDWR;
  355. if (append_file)
  356. flags |= O_APPEND;
  357. else
  358. flags |= O_TRUNC;
  359. output = open(output_name, flags, S_IRUSR|S_IWUSR);
  360. if (output < 0) {
  361. perror("failed to create output file");
  362. exit(-1);
  363. }
  364. if (!system_wide) {
  365. open_counters(-1, target_pid != -1 ? target_pid : getpid());
  366. } else for (i = 0; i < nr_cpus; i++)
  367. open_counters(i, target_pid);
  368. signal(SIGCHLD, sig_handler);
  369. signal(SIGINT, sig_handler);
  370. if (target_pid == -1 && argc) {
  371. pid = fork();
  372. if (pid < 0)
  373. perror("failed to fork");
  374. if (!pid) {
  375. if (execvp(argv[0], (char **)argv)) {
  376. perror(argv[0]);
  377. exit(-1);
  378. }
  379. }
  380. }
  381. if (realtime_prio) {
  382. struct sched_param param;
  383. param.sched_priority = realtime_prio;
  384. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  385. printf("Could not set realtime priority.\n");
  386. exit(-1);
  387. }
  388. }
  389. if (system_wide)
  390. synthesize_samples();
  391. while (!done) {
  392. int hits = samples;
  393. for (i = 0; i < nr_cpu; i++) {
  394. for (counter = 0; counter < nr_counters; counter++)
  395. mmap_read(&mmap_array[i][counter]);
  396. }
  397. if (hits == samples)
  398. ret = poll(event_array, nr_poll, 100);
  399. }
  400. /*
  401. * Approximate RIP event size: 24 bytes.
  402. */
  403. fprintf(stderr,
  404. "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
  405. (double)bytes_written / 1024.0 / 1024.0,
  406. output_name,
  407. bytes_written / 24);
  408. return 0;
  409. }
  410. static const char * const record_usage[] = {
  411. "perf record [<options>] [<command>]",
  412. "perf record [<options>] -- <command> [<options>]",
  413. NULL
  414. };
  415. static const struct option options[] = {
  416. OPT_CALLBACK('e', "event", NULL, "event",
  417. "event selector. use 'perf list' to list available events",
  418. parse_events),
  419. OPT_INTEGER('p', "pid", &target_pid,
  420. "record events on existing pid"),
  421. OPT_INTEGER('r', "realtime", &realtime_prio,
  422. "collect data with this RT SCHED_FIFO priority"),
  423. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  424. "system-wide collection from all CPUs"),
  425. OPT_BOOLEAN('A', "append", &append_file,
  426. "append to the output file to do incremental profiling"),
  427. OPT_BOOLEAN('f', "force", &force,
  428. "overwrite existing data file"),
  429. OPT_LONG('c', "count", &default_interval,
  430. "event period to sample"),
  431. OPT_STRING('o', "output", &output_name, "file",
  432. "output file name"),
  433. OPT_BOOLEAN('i', "inherit", &inherit,
  434. "child tasks inherit counters"),
  435. OPT_INTEGER('F', "freq", &freq,
  436. "profile at this frequency"),
  437. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  438. "number of mmap data pages"),
  439. OPT_BOOLEAN('v', "verbose", &verbose,
  440. "be more verbose (show counter open errors, etc)"),
  441. OPT_END()
  442. };
  443. int cmd_record(int argc, const char **argv, const char *prefix)
  444. {
  445. int counter;
  446. argc = parse_options(argc, argv, options, record_usage, 0);
  447. if (!argc && target_pid == -1 && !system_wide)
  448. usage_with_options(record_usage, options);
  449. if (!nr_counters)
  450. nr_counters = 1;
  451. for (counter = 0; counter < nr_counters; counter++) {
  452. if (attrs[counter].sample_period)
  453. continue;
  454. attrs[counter].sample_period = default_interval;
  455. }
  456. return __cmd_record(argc, argv);
  457. }