builtin-record.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. #include "perf.h"
  2. #include "util/util.h"
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <sys/time.h>
  6. #include <unistd.h>
  7. #include <stdint.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <limits.h>
  11. #include <getopt.h>
  12. #include <assert.h>
  13. #include <fcntl.h>
  14. #include <stdio.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <sched.h>
  18. #include <pthread.h>
  19. #include <sys/syscall.h>
  20. #include <sys/ioctl.h>
  21. #include <sys/poll.h>
  22. #include <sys/prctl.h>
  23. #include <sys/wait.h>
  24. #include <sys/uio.h>
  25. #include <sys/mman.h>
  26. #include <linux/unistd.h>
  27. #include <linux/types.h>
  28. #define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1)
  29. #define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
  30. static int nr_counters = 0;
  31. static __u64 event_id[MAX_COUNTERS] = { };
  32. static int default_interval = 100000;
  33. static int event_count[MAX_COUNTERS];
  34. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  35. static int nr_cpus = 0;
  36. static unsigned int page_size;
  37. static unsigned int mmap_pages = 16;
  38. static int output;
  39. static char *output_name = "output.perf";
  40. static int group = 0;
  41. static unsigned int realtime_prio = 0;
  42. static int system_wide = 0;
  43. static pid_t target_pid = -1;
  44. static int inherit = 1;
  45. static int nmi = 1;
  46. const unsigned int default_count[] = {
  47. 1000000,
  48. 1000000,
  49. 10000,
  50. 10000,
  51. 1000000,
  52. 10000,
  53. };
  54. struct event_symbol {
  55. __u64 event;
  56. char *symbol;
  57. };
  58. static struct event_symbol event_symbols[] = {
  59. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cpu-cycles", },
  60. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cycles", },
  61. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS), "instructions", },
  62. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES), "cache-references", },
  63. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES), "cache-misses", },
  64. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branch-instructions", },
  65. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branches", },
  66. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_MISSES), "branch-misses", },
  67. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BUS_CYCLES), "bus-cycles", },
  68. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_CLOCK), "cpu-clock", },
  69. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK), "task-clock", },
  70. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "page-faults", },
  71. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "faults", },
  72. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MIN), "minor-faults", },
  73. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MAJ), "major-faults", },
  74. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "context-switches", },
  75. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "cs", },
  76. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "cpu-migrations", },
  77. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "migrations", },
  78. };
  79. /*
  80. * Each event can have multiple symbolic names.
  81. * Symbolic names are (almost) exactly matched.
  82. */
  83. static __u64 match_event_symbols(char *str)
  84. {
  85. __u64 config, id;
  86. int type;
  87. unsigned int i;
  88. if (sscanf(str, "r%llx", &config) == 1)
  89. return config | PERF_COUNTER_RAW_MASK;
  90. if (sscanf(str, "%d:%llu", &type, &id) == 2)
  91. return EID(type, id);
  92. for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
  93. if (!strncmp(str, event_symbols[i].symbol,
  94. strlen(event_symbols[i].symbol)))
  95. return event_symbols[i].event;
  96. }
  97. return ~0ULL;
  98. }
  99. static int parse_events(char *str)
  100. {
  101. __u64 config;
  102. again:
  103. if (nr_counters == MAX_COUNTERS)
  104. return -1;
  105. config = match_event_symbols(str);
  106. if (config == ~0ULL)
  107. return -1;
  108. event_id[nr_counters] = config;
  109. nr_counters++;
  110. str = strstr(str, ",");
  111. if (str) {
  112. str++;
  113. goto again;
  114. }
  115. return 0;
  116. }
  117. #define __PERF_COUNTER_FIELD(config, name) \
  118. ((config & PERF_COUNTER_##name##_MASK) >> PERF_COUNTER_##name##_SHIFT)
  119. #define PERF_COUNTER_RAW(config) __PERF_COUNTER_FIELD(config, RAW)
  120. #define PERF_COUNTER_CONFIG(config) __PERF_COUNTER_FIELD(config, CONFIG)
  121. #define PERF_COUNTER_TYPE(config) __PERF_COUNTER_FIELD(config, TYPE)
  122. #define PERF_COUNTER_ID(config) __PERF_COUNTER_FIELD(config, EVENT)
  123. static void display_events_help(void)
  124. {
  125. unsigned int i;
  126. __u64 e;
  127. printf(
  128. " -e EVENT --event=EVENT # symbolic-name abbreviations");
  129. for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
  130. int type, id;
  131. e = event_symbols[i].event;
  132. type = PERF_COUNTER_TYPE(e);
  133. id = PERF_COUNTER_ID(e);
  134. printf("\n %d:%d: %-20s",
  135. type, id, event_symbols[i].symbol);
  136. }
  137. printf("\n"
  138. " rNNN: raw PMU events (eventsel+umask)\n\n");
  139. }
  140. static void display_help(void)
  141. {
  142. printf(
  143. "Usage: perf-record [<options>] <cmd>\n"
  144. "perf-record Options (up to %d event types can be specified at once):\n\n",
  145. MAX_COUNTERS);
  146. display_events_help();
  147. printf(
  148. " -c CNT --count=CNT # event period to sample\n"
  149. " -m pages --mmap_pages=<pages> # number of mmap data pages\n"
  150. " -o file --output=<file> # output file\n"
  151. " -p pid --pid=<pid> # record events on existing pid\n"
  152. " -r prio --realtime=<prio> # use RT prio\n"
  153. " -s --system # system wide profiling\n"
  154. );
  155. exit(0);
  156. }
  157. static void process_options(int argc, char * const argv[])
  158. {
  159. int error = 0, counter;
  160. for (;;) {
  161. int option_index = 0;
  162. /** Options for getopt */
  163. static struct option long_options[] = {
  164. {"count", required_argument, NULL, 'c'},
  165. {"event", required_argument, NULL, 'e'},
  166. {"mmap_pages", required_argument, NULL, 'm'},
  167. {"output", required_argument, NULL, 'o'},
  168. {"pid", required_argument, NULL, 'p'},
  169. {"realtime", required_argument, NULL, 'r'},
  170. {"system", no_argument, NULL, 's'},
  171. {"inherit", no_argument, NULL, 'i'},
  172. {"nmi", no_argument, NULL, 'n'},
  173. {NULL, 0, NULL, 0 }
  174. };
  175. int c = getopt_long(argc, argv, "+:c:e:m:o:p:r:sin",
  176. long_options, &option_index);
  177. if (c == -1)
  178. break;
  179. switch (c) {
  180. case 'c': default_interval = atoi(optarg); break;
  181. case 'e': error = parse_events(optarg); break;
  182. case 'm': mmap_pages = atoi(optarg); break;
  183. case 'o': output_name = strdup(optarg); break;
  184. case 'p': target_pid = atoi(optarg); break;
  185. case 'r': realtime_prio = atoi(optarg); break;
  186. case 's': system_wide ^= 1; break;
  187. case 'i': inherit ^= 1; break;
  188. case 'n': nmi ^= 1; break;
  189. default: error = 1; break;
  190. }
  191. }
  192. if (argc - optind == 0 && target_pid == -1)
  193. error = 1;
  194. if (error)
  195. display_help();
  196. if (!nr_counters) {
  197. nr_counters = 1;
  198. event_id[0] = 0;
  199. }
  200. for (counter = 0; counter < nr_counters; counter++) {
  201. if (event_count[counter])
  202. continue;
  203. event_count[counter] = default_interval;
  204. }
  205. }
  206. struct mmap_data {
  207. int counter;
  208. void *base;
  209. unsigned int mask;
  210. unsigned int prev;
  211. };
  212. static unsigned int mmap_read_head(struct mmap_data *md)
  213. {
  214. struct perf_counter_mmap_page *pc = md->base;
  215. int head;
  216. head = pc->data_head;
  217. rmb();
  218. return head;
  219. }
  220. static long events;
  221. static struct timeval last_read, this_read;
  222. static void mmap_read(struct mmap_data *md)
  223. {
  224. unsigned int head = mmap_read_head(md);
  225. unsigned int old = md->prev;
  226. unsigned char *data = md->base + page_size;
  227. unsigned long size;
  228. void *buf;
  229. int diff;
  230. gettimeofday(&this_read, NULL);
  231. /*
  232. * If we're further behind than half the buffer, there's a chance
  233. * the writer will bite our tail and screw up the events under us.
  234. *
  235. * If we somehow ended up ahead of the head, we got messed up.
  236. *
  237. * In either case, truncate and restart at head.
  238. */
  239. diff = head - old;
  240. if (diff > md->mask / 2 || diff < 0) {
  241. struct timeval iv;
  242. unsigned long msecs;
  243. timersub(&this_read, &last_read, &iv);
  244. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  245. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  246. " Last read %lu msecs ago.\n", msecs);
  247. /*
  248. * head points to a known good entry, start there.
  249. */
  250. old = head;
  251. }
  252. last_read = this_read;
  253. if (old != head)
  254. events++;
  255. size = head - old;
  256. if ((old & md->mask) + size != (head & md->mask)) {
  257. buf = &data[old & md->mask];
  258. size = md->mask + 1 - (old & md->mask);
  259. old += size;
  260. while (size) {
  261. int ret = write(output, buf, size);
  262. if (ret < 0) {
  263. perror("failed to write");
  264. exit(-1);
  265. }
  266. size -= ret;
  267. buf += ret;
  268. }
  269. }
  270. buf = &data[old & md->mask];
  271. size = head - old;
  272. old += size;
  273. while (size) {
  274. int ret = write(output, buf, size);
  275. if (ret < 0) {
  276. perror("failed to write");
  277. exit(-1);
  278. }
  279. size -= ret;
  280. buf += ret;
  281. }
  282. md->prev = old;
  283. }
  284. static volatile int done = 0;
  285. static void sig_handler(int sig)
  286. {
  287. done = 1;
  288. }
  289. static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  290. static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  291. static int nr_poll;
  292. static int nr_cpu;
  293. struct mmap_event {
  294. struct perf_event_header header;
  295. __u32 pid, tid;
  296. __u64 start;
  297. __u64 len;
  298. __u64 pgoff;
  299. char filename[PATH_MAX];
  300. };
  301. struct comm_event {
  302. struct perf_event_header header;
  303. __u32 pid,tid;
  304. char comm[16];
  305. };
  306. static pid_t pid_synthesize_comm_event(pid_t pid)
  307. {
  308. char filename[PATH_MAX];
  309. char bf[BUFSIZ];
  310. struct comm_event comm_ev;
  311. size_t size;
  312. int fd;
  313. snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
  314. fd = open(filename, O_RDONLY);
  315. if (fd < 0) {
  316. fprintf(stderr, "couldn't open %s\n", filename);
  317. exit(EXIT_FAILURE);
  318. }
  319. if (read(fd, bf, sizeof(bf)) < 0) {
  320. fprintf(stderr, "couldn't read %s\n", filename);
  321. exit(EXIT_FAILURE);
  322. }
  323. close(fd);
  324. pid_t spid, ppid;
  325. char state;
  326. char comm[18];
  327. memset(&comm_ev, 0, sizeof(comm_ev));
  328. int nr = sscanf(bf, "%d %s %c %d %d ",
  329. &spid, comm, &state, &ppid, &comm_ev.pid);
  330. if (nr != 5) {
  331. fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
  332. filename);
  333. exit(EXIT_FAILURE);
  334. }
  335. comm_ev.header.type = PERF_EVENT_COMM;
  336. comm_ev.tid = pid;
  337. size = strlen(comm);
  338. comm[--size] = '\0'; /* Remove the ')' at the end */
  339. --size; /* Remove the '(' at the begin */
  340. memcpy(comm_ev.comm, comm + 1, size);
  341. size = ALIGN(size, sizeof(uint64_t));
  342. comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
  343. int ret = write(output, &comm_ev, comm_ev.header.size);
  344. if (ret < 0) {
  345. perror("failed to write");
  346. exit(-1);
  347. }
  348. return comm_ev.pid;
  349. }
  350. static void pid_synthesize_mmap_events(pid_t pid, pid_t pgid)
  351. {
  352. char filename[PATH_MAX];
  353. FILE *fp;
  354. snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
  355. fp = fopen(filename, "r");
  356. if (fp == NULL) {
  357. fprintf(stderr, "couldn't open %s\n", filename);
  358. exit(EXIT_FAILURE);
  359. }
  360. while (1) {
  361. char bf[BUFSIZ];
  362. unsigned char vm_read, vm_write, vm_exec, vm_mayshare;
  363. struct mmap_event mmap_ev = {
  364. .header.type = PERF_EVENT_MMAP,
  365. };
  366. unsigned long ino;
  367. int major, minor;
  368. size_t size;
  369. if (fgets(bf, sizeof(bf), fp) == NULL)
  370. break;
  371. /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
  372. sscanf(bf, "%llx-%llx %c%c%c%c %llx %x:%x %lu",
  373. &mmap_ev.start, &mmap_ev.len,
  374. &vm_read, &vm_write, &vm_exec, &vm_mayshare,
  375. &mmap_ev.pgoff, &major, &minor, &ino);
  376. if (vm_exec == 'x') {
  377. char *execname = strrchr(bf, ' ');
  378. if (execname == NULL || execname[1] != '/')
  379. continue;
  380. execname += 1;
  381. size = strlen(execname);
  382. execname[size - 1] = '\0'; /* Remove \n */
  383. memcpy(mmap_ev.filename, execname, size);
  384. size = ALIGN(size, sizeof(uint64_t));
  385. mmap_ev.len -= mmap_ev.start;
  386. mmap_ev.header.size = (sizeof(mmap_ev) -
  387. (sizeof(mmap_ev.filename) - size));
  388. mmap_ev.pid = pgid;
  389. mmap_ev.tid = pid;
  390. if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
  391. perror("failed to write");
  392. exit(-1);
  393. }
  394. }
  395. }
  396. fclose(fp);
  397. }
  398. static void open_counters(int cpu, pid_t pid)
  399. {
  400. struct perf_counter_hw_event hw_event;
  401. int counter, group_fd;
  402. int track = 1;
  403. if (pid > 0) {
  404. pid_t pgid = pid_synthesize_comm_event(pid);
  405. pid_synthesize_mmap_events(pid, pgid);
  406. }
  407. group_fd = -1;
  408. for (counter = 0; counter < nr_counters; counter++) {
  409. memset(&hw_event, 0, sizeof(hw_event));
  410. hw_event.config = event_id[counter];
  411. hw_event.irq_period = event_count[counter];
  412. hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
  413. hw_event.nmi = nmi;
  414. hw_event.mmap = track;
  415. hw_event.comm = track;
  416. hw_event.inherit = (cpu < 0) && inherit;
  417. track = 0; // only the first counter needs these
  418. fd[nr_cpu][counter] =
  419. sys_perf_counter_open(&hw_event, pid, cpu, group_fd, 0);
  420. if (fd[nr_cpu][counter] < 0) {
  421. int err = errno;
  422. printf("kerneltop error: syscall returned with %d (%s)\n",
  423. fd[nr_cpu][counter], strerror(err));
  424. if (err == EPERM)
  425. printf("Are you root?\n");
  426. exit(-1);
  427. }
  428. assert(fd[nr_cpu][counter] >= 0);
  429. fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
  430. /*
  431. * First counter acts as the group leader:
  432. */
  433. if (group && group_fd == -1)
  434. group_fd = fd[nr_cpu][counter];
  435. event_array[nr_poll].fd = fd[nr_cpu][counter];
  436. event_array[nr_poll].events = POLLIN;
  437. nr_poll++;
  438. mmap_array[nr_cpu][counter].counter = counter;
  439. mmap_array[nr_cpu][counter].prev = 0;
  440. mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
  441. mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  442. PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
  443. if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
  444. printf("kerneltop error: failed to mmap with %d (%s)\n",
  445. errno, strerror(errno));
  446. exit(-1);
  447. }
  448. }
  449. nr_cpu++;
  450. }
  451. int cmd_record(int argc, char * const argv[])
  452. {
  453. int i, counter;
  454. pid_t pid;
  455. int ret;
  456. page_size = sysconf(_SC_PAGE_SIZE);
  457. process_options(argc, argv);
  458. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  459. assert(nr_cpus <= MAX_NR_CPUS);
  460. assert(nr_cpus >= 0);
  461. output = open(output_name, O_CREAT|O_RDWR, S_IRWXU);
  462. if (output < 0) {
  463. perror("failed to create output file");
  464. exit(-1);
  465. }
  466. argc -= optind;
  467. argv += optind;
  468. if (!system_wide) {
  469. open_counters(-1, target_pid != -1 ? target_pid : 0);
  470. } else for (i = 0; i < nr_cpus; i++)
  471. open_counters(i, target_pid);
  472. signal(SIGCHLD, sig_handler);
  473. signal(SIGINT, sig_handler);
  474. if (target_pid == -1) {
  475. pid = fork();
  476. if (pid < 0)
  477. perror("failed to fork");
  478. if (!pid) {
  479. if (execvp(argv[0], argv)) {
  480. perror(argv[0]);
  481. exit(-1);
  482. }
  483. }
  484. }
  485. if (realtime_prio) {
  486. struct sched_param param;
  487. param.sched_priority = realtime_prio;
  488. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  489. printf("Could not set realtime priority.\n");
  490. exit(-1);
  491. }
  492. }
  493. /*
  494. * TODO: store the current /proc/$/maps information somewhere
  495. */
  496. while (!done) {
  497. int hits = events;
  498. for (i = 0; i < nr_cpu; i++) {
  499. for (counter = 0; counter < nr_counters; counter++)
  500. mmap_read(&mmap_array[i][counter]);
  501. }
  502. if (hits == events)
  503. ret = poll(event_array, nr_poll, 100);
  504. }
  505. return 0;
  506. }