builtin-record.c 10.0 KB

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