builtin-record.c 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include "perf.h"
  2. #include "util/util.h"
  3. #include "util/parse-options.h"
  4. #include "util/parse-events.h"
  5. #include "util/exec_cmd.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, tid;
  121. __u64 start;
  122. __u64 len;
  123. __u64 pgoff;
  124. char filename[PATH_MAX];
  125. };
  126. struct comm_event {
  127. struct perf_event_header header;
  128. __u32 pid,tid;
  129. char comm[16];
  130. };
  131. static pid_t pid_synthesize_comm_event(pid_t pid)
  132. {
  133. char filename[PATH_MAX];
  134. char bf[BUFSIZ];
  135. struct comm_event comm_ev;
  136. size_t size;
  137. int fd;
  138. snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
  139. fd = open(filename, O_RDONLY);
  140. if (fd < 0) {
  141. fprintf(stderr, "couldn't open %s\n", filename);
  142. exit(EXIT_FAILURE);
  143. }
  144. if (read(fd, bf, sizeof(bf)) < 0) {
  145. fprintf(stderr, "couldn't read %s\n", filename);
  146. exit(EXIT_FAILURE);
  147. }
  148. close(fd);
  149. pid_t spid, ppid;
  150. char state;
  151. char comm[18];
  152. memset(&comm_ev, 0, sizeof(comm_ev));
  153. int nr = sscanf(bf, "%d %s %c %d %d ",
  154. &spid, comm, &state, &ppid, &comm_ev.pid);
  155. if (nr != 5) {
  156. fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
  157. filename);
  158. exit(EXIT_FAILURE);
  159. }
  160. comm_ev.header.type = PERF_EVENT_COMM;
  161. comm_ev.tid = pid;
  162. size = strlen(comm);
  163. comm[--size] = '\0'; /* Remove the ')' at the end */
  164. --size; /* Remove the '(' at the begin */
  165. memcpy(comm_ev.comm, comm + 1, size);
  166. size = ALIGN(size, sizeof(uint64_t));
  167. comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
  168. int ret = write(output, &comm_ev, comm_ev.header.size);
  169. if (ret < 0) {
  170. perror("failed to write");
  171. exit(-1);
  172. }
  173. return comm_ev.pid;
  174. }
  175. static void pid_synthesize_mmap_events(pid_t pid, pid_t pgid)
  176. {
  177. char filename[PATH_MAX];
  178. FILE *fp;
  179. snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
  180. fp = fopen(filename, "r");
  181. if (fp == NULL) {
  182. fprintf(stderr, "couldn't open %s\n", filename);
  183. exit(EXIT_FAILURE);
  184. }
  185. while (1) {
  186. char bf[BUFSIZ];
  187. unsigned char vm_read, vm_write, vm_exec, vm_mayshare;
  188. struct mmap_event mmap_ev = {
  189. .header.type = PERF_EVENT_MMAP,
  190. };
  191. unsigned long ino;
  192. int major, minor;
  193. size_t size;
  194. if (fgets(bf, sizeof(bf), fp) == NULL)
  195. break;
  196. /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
  197. sscanf(bf, "%llx-%llx %c%c%c%c %llx %x:%x %lu",
  198. &mmap_ev.start, &mmap_ev.len,
  199. &vm_read, &vm_write, &vm_exec, &vm_mayshare,
  200. &mmap_ev.pgoff, &major, &minor, &ino);
  201. if (vm_exec == 'x') {
  202. char *execname = strrchr(bf, ' ');
  203. if (execname == NULL || execname[1] != '/')
  204. continue;
  205. execname += 1;
  206. size = strlen(execname);
  207. execname[size - 1] = '\0'; /* Remove \n */
  208. memcpy(mmap_ev.filename, execname, size);
  209. size = ALIGN(size, sizeof(uint64_t));
  210. mmap_ev.len -= mmap_ev.start;
  211. mmap_ev.header.size = (sizeof(mmap_ev) -
  212. (sizeof(mmap_ev.filename) - size));
  213. mmap_ev.pid = pgid;
  214. mmap_ev.tid = pid;
  215. if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
  216. perror("failed to write");
  217. exit(-1);
  218. }
  219. }
  220. }
  221. fclose(fp);
  222. }
  223. static void open_counters(int cpu, pid_t pid)
  224. {
  225. struct perf_counter_hw_event hw_event;
  226. int counter, group_fd;
  227. int track = 1;
  228. if (pid > 0) {
  229. pid_t pgid = pid_synthesize_comm_event(pid);
  230. pid_synthesize_mmap_events(pid, pgid);
  231. }
  232. group_fd = -1;
  233. for (counter = 0; counter < nr_counters; counter++) {
  234. memset(&hw_event, 0, sizeof(hw_event));
  235. hw_event.config = event_id[counter];
  236. hw_event.irq_period = event_count[counter];
  237. hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
  238. hw_event.nmi = nmi;
  239. hw_event.mmap = track;
  240. hw_event.comm = track;
  241. hw_event.inherit = (cpu < 0) && inherit;
  242. track = 0; // only the first counter needs these
  243. fd[nr_cpu][counter] =
  244. sys_perf_counter_open(&hw_event, pid, cpu, group_fd, 0);
  245. if (fd[nr_cpu][counter] < 0) {
  246. int err = errno;
  247. printf("kerneltop error: syscall returned with %d (%s)\n",
  248. fd[nr_cpu][counter], strerror(err));
  249. if (err == EPERM)
  250. printf("Are you root?\n");
  251. exit(-1);
  252. }
  253. assert(fd[nr_cpu][counter] >= 0);
  254. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  255. /*
  256. * First counter acts as the group leader:
  257. */
  258. if (group && group_fd == -1)
  259. group_fd = fd[nr_cpu][counter];
  260. event_array[nr_poll].fd = fd[nr_cpu][counter];
  261. event_array[nr_poll].events = POLLIN;
  262. nr_poll++;
  263. mmap_array[nr_cpu][counter].counter = counter;
  264. mmap_array[nr_cpu][counter].prev = 0;
  265. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  266. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  267. PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
  268. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  269. printf("kerneltop error: failed to mmap with %d (%s)\n",
  270. errno, strerror(errno));
  271. exit(-1);
  272. }
  273. }
  274. nr_cpu++;
  275. }
  276. static int __cmd_record(int argc, const char **argv)
  277. {
  278. int i, counter;
  279. pid_t pid;
  280. int ret;
  281. page_size = sysconf(_SC_PAGE_SIZE);
  282. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  283. assert(nr_cpus <= MAX_NR_CPUS);
  284. assert(nr_cpus >= 0);
  285. output = open(output_name, O_CREAT|O_RDWR, S_IRWXU);
  286. if (output < 0) {
  287. perror("failed to create output file");
  288. exit(-1);
  289. }
  290. if (!system_wide) {
  291. open_counters(-1, target_pid != -1 ? target_pid : 0);
  292. } else for (i = 0; i < nr_cpus; i++)
  293. open_counters(i, target_pid);
  294. signal(SIGCHLD, sig_handler);
  295. signal(SIGINT, sig_handler);
  296. if (target_pid == -1) {
  297. pid = fork();
  298. if (pid < 0)
  299. perror("failed to fork");
  300. if (!pid) {
  301. if (execvp(argv[0], (char **)argv)) {
  302. perror(argv[0]);
  303. exit(-1);
  304. }
  305. }
  306. }
  307. if (realtime_prio) {
  308. struct sched_param param;
  309. param.sched_priority = realtime_prio;
  310. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  311. printf("Could not set realtime priority.\n");
  312. exit(-1);
  313. }
  314. }
  315. /*
  316. * TODO: store the current /proc/$/maps information somewhere
  317. */
  318. while (!done) {
  319. int hits = events;
  320. for (i = 0; i < nr_cpu; i++) {
  321. for (counter = 0; counter < nr_counters; counter++)
  322. mmap_read(&mmap_array[i][counter]);
  323. }
  324. if (hits == events)
  325. ret = poll(event_array, nr_poll, 100);
  326. }
  327. return 0;
  328. }
  329. static const char * const record_usage[] = {
  330. "perf record [<options>] <command>",
  331. NULL
  332. };
  333. static char events_help_msg[EVENTS_HELP_MAX];
  334. const struct option options[] = {
  335. OPT_CALLBACK('e', "event", NULL, "event",
  336. events_help_msg, parse_events),
  337. OPT_INTEGER('c', "count", &default_interval,
  338. "event period to sample"),
  339. OPT_INTEGER('m', "mmap-pages", &mmap_pages,
  340. "number of mmap data pages"),
  341. OPT_STRING('o', "output", &output_name, "file",
  342. "output file name"),
  343. OPT_BOOLEAN('i', "inherit", &inherit,
  344. "child tasks inherit counters"),
  345. OPT_INTEGER('p', "pid", &target_pid,
  346. "record events on existing pid"),
  347. OPT_INTEGER('r', "realtime", &realtime_prio,
  348. "collect data with this RT SCHED_FIFO priority"),
  349. OPT_BOOLEAN('a', "all-cpus", &system_wide,
  350. "system-wide collection from all CPUs"),
  351. OPT_END()
  352. };
  353. int cmd_record(int argc, const char **argv, const char *prefix)
  354. {
  355. int counter;
  356. create_events_help(events_help_msg);
  357. argc = parse_options(argc, argv, options, record_usage, 0);
  358. if (!argc)
  359. usage_with_options(record_usage, options);
  360. if (!nr_counters) {
  361. nr_counters = 1;
  362. event_id[0] = 0;
  363. }
  364. for (counter = 0; counter < nr_counters; counter++) {
  365. if (event_count[counter])
  366. continue;
  367. event_count[counter] = default_interval;
  368. }
  369. return __cmd_record(argc, argv);
  370. }