builtin-record.c 10 KB

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