builtin-record.c 12 KB

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