builtin-record.c 11 KB

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