builtin-record.c 10 KB

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