perf-record.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #define _GNU_SOURCE
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <sys/time.h>
  5. #include <unistd.h>
  6. #include <stdint.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <limits.h>
  10. #include <getopt.h>
  11. #include <assert.h>
  12. #include <fcntl.h>
  13. #include <stdio.h>
  14. #include <errno.h>
  15. #include <ctype.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. #include "../../include/linux/perf_counter.h"
  29. /*
  30. * prctl(PR_TASK_PERF_COUNTERS_DISABLE) will (cheaply) disable all
  31. * counters in the current task.
  32. */
  33. #define PR_TASK_PERF_COUNTERS_DISABLE 31
  34. #define PR_TASK_PERF_COUNTERS_ENABLE 32
  35. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  36. #define rdclock() \
  37. ({ \
  38. struct timespec ts; \
  39. \
  40. clock_gettime(CLOCK_MONOTONIC, &ts); \
  41. ts.tv_sec * 1000000000ULL + ts.tv_nsec; \
  42. })
  43. /*
  44. * Pick up some kernel type conventions:
  45. */
  46. #define __user
  47. #define asmlinkage
  48. #ifdef __x86_64__
  49. #define __NR_perf_counter_open 295
  50. #define rmb() asm volatile("lfence" ::: "memory")
  51. #define cpu_relax() asm volatile("rep; nop" ::: "memory");
  52. #endif
  53. #ifdef __i386__
  54. #define __NR_perf_counter_open 333
  55. #define rmb() asm volatile("lfence" ::: "memory")
  56. #define cpu_relax() asm volatile("rep; nop" ::: "memory");
  57. #endif
  58. #ifdef __powerpc__
  59. #define __NR_perf_counter_open 319
  60. #define rmb() asm volatile ("sync" ::: "memory")
  61. #define cpu_relax() asm volatile ("" ::: "memory");
  62. #endif
  63. #define unlikely(x) __builtin_expect(!!(x), 0)
  64. #define min(x, y) ({ \
  65. typeof(x) _min1 = (x); \
  66. typeof(y) _min2 = (y); \
  67. (void) (&_min1 == &_min2); \
  68. _min1 < _min2 ? _min1 : _min2; })
  69. asmlinkage int sys_perf_counter_open(
  70. struct perf_counter_hw_event *hw_event_uptr __user,
  71. pid_t pid,
  72. int cpu,
  73. int group_fd,
  74. unsigned long flags)
  75. {
  76. return syscall(
  77. __NR_perf_counter_open, hw_event_uptr, pid, cpu, group_fd, flags);
  78. }
  79. #define MAX_COUNTERS 64
  80. #define MAX_NR_CPUS 256
  81. #define EID(type, id) (((__u64)(type) << PERF_COUNTER_TYPE_SHIFT) | (id))
  82. static int nr_counters = 0;
  83. static __u64 event_id[MAX_COUNTERS] = { };
  84. static int default_interval = 100000;
  85. static int event_count[MAX_COUNTERS];
  86. static int fd[MAX_NR_CPUS][MAX_COUNTERS];
  87. static int nr_cpus = 0;
  88. static unsigned int page_size;
  89. static unsigned int mmap_pages = 16;
  90. static int output;
  91. static char *output_name = "output.perf";
  92. static int group = 0;
  93. static unsigned int realtime_prio = 0;
  94. const unsigned int default_count[] = {
  95. 1000000,
  96. 1000000,
  97. 10000,
  98. 10000,
  99. 1000000,
  100. 10000,
  101. };
  102. static char *hw_event_names[] = {
  103. "CPU cycles",
  104. "instructions",
  105. "cache references",
  106. "cache misses",
  107. "branches",
  108. "branch misses",
  109. "bus cycles",
  110. };
  111. static char *sw_event_names[] = {
  112. "cpu clock ticks",
  113. "task clock ticks",
  114. "pagefaults",
  115. "context switches",
  116. "CPU migrations",
  117. "minor faults",
  118. "major faults",
  119. };
  120. struct event_symbol {
  121. __u64 event;
  122. char *symbol;
  123. };
  124. static struct event_symbol event_symbols[] = {
  125. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cpu-cycles", },
  126. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CPU_CYCLES), "cycles", },
  127. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_INSTRUCTIONS), "instructions", },
  128. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_REFERENCES), "cache-references", },
  129. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_CACHE_MISSES), "cache-misses", },
  130. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branch-instructions", },
  131. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_INSTRUCTIONS), "branches", },
  132. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BRANCH_MISSES), "branch-misses", },
  133. {EID(PERF_TYPE_HARDWARE, PERF_COUNT_BUS_CYCLES), "bus-cycles", },
  134. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_CLOCK), "cpu-clock", },
  135. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_TASK_CLOCK), "task-clock", },
  136. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "page-faults", },
  137. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS), "faults", },
  138. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MIN), "minor-faults", },
  139. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_PAGE_FAULTS_MAJ), "major-faults", },
  140. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "context-switches", },
  141. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CONTEXT_SWITCHES), "cs", },
  142. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "cpu-migrations", },
  143. {EID(PERF_TYPE_SOFTWARE, PERF_COUNT_CPU_MIGRATIONS), "migrations", },
  144. };
  145. /*
  146. * Each event can have multiple symbolic names.
  147. * Symbolic names are (almost) exactly matched.
  148. */
  149. static __u64 match_event_symbols(char *str)
  150. {
  151. __u64 config, id;
  152. int type;
  153. unsigned int i;
  154. if (sscanf(str, "r%llx", &config) == 1)
  155. return config | PERF_COUNTER_RAW_MASK;
  156. if (sscanf(str, "%d:%llu", &type, &id) == 2)
  157. return EID(type, id);
  158. for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
  159. if (!strncmp(str, event_symbols[i].symbol,
  160. strlen(event_symbols[i].symbol)))
  161. return event_symbols[i].event;
  162. }
  163. return ~0ULL;
  164. }
  165. static int parse_events(char *str)
  166. {
  167. __u64 config;
  168. again:
  169. if (nr_counters == MAX_COUNTERS)
  170. return -1;
  171. config = match_event_symbols(str);
  172. if (config == ~0ULL)
  173. return -1;
  174. event_id[nr_counters] = config;
  175. nr_counters++;
  176. str = strstr(str, ",");
  177. if (str) {
  178. str++;
  179. goto again;
  180. }
  181. return 0;
  182. }
  183. #define __PERF_COUNTER_FIELD(config, name) \
  184. ((config & PERF_COUNTER_##name##_MASK) >> PERF_COUNTER_##name##_SHIFT)
  185. #define PERF_COUNTER_RAW(config) __PERF_COUNTER_FIELD(config, RAW)
  186. #define PERF_COUNTER_CONFIG(config) __PERF_COUNTER_FIELD(config, CONFIG)
  187. #define PERF_COUNTER_TYPE(config) __PERF_COUNTER_FIELD(config, TYPE)
  188. #define PERF_COUNTER_ID(config) __PERF_COUNTER_FIELD(config, EVENT)
  189. static void display_events_help(void)
  190. {
  191. unsigned int i;
  192. __u64 e;
  193. printf(
  194. " -e EVENT --event=EVENT # symbolic-name abbreviations");
  195. for (i = 0; i < ARRAY_SIZE(event_symbols); i++) {
  196. int type, id;
  197. e = event_symbols[i].event;
  198. type = PERF_COUNTER_TYPE(e);
  199. id = PERF_COUNTER_ID(e);
  200. printf("\n %d:%d: %-20s",
  201. type, id, event_symbols[i].symbol);
  202. }
  203. printf("\n"
  204. " rNNN: raw PMU events (eventsel+umask)\n\n");
  205. }
  206. static void display_help(void)
  207. {
  208. printf(
  209. "Usage: perf-record [<options>]\n"
  210. "perf-record Options (up to %d event types can be specified at once):\n\n",
  211. MAX_COUNTERS);
  212. display_events_help();
  213. printf(
  214. " -c CNT --count=CNT # event period to sample\n"
  215. " -m pages --mmap_pages=<pages> # number of mmap data pages\n"
  216. " -o file --output=<file> # output file\n"
  217. " -r prio --realtime=<prio> # use RT prio\n"
  218. );
  219. exit(0);
  220. }
  221. static void process_options(int argc, char *argv[])
  222. {
  223. int error = 0, counter;
  224. for (;;) {
  225. int option_index = 0;
  226. /** Options for getopt */
  227. static struct option long_options[] = {
  228. {"count", required_argument, NULL, 'c'},
  229. {"event", required_argument, NULL, 'e'},
  230. {"mmap_pages", required_argument, NULL, 'm'},
  231. {"output", required_argument, NULL, 'o'},
  232. {"realtime", required_argument, NULL, 'r'},
  233. {NULL, 0, NULL, 0 }
  234. };
  235. int c = getopt_long(argc, argv, "+:c:e:m:o:r:",
  236. long_options, &option_index);
  237. if (c == -1)
  238. break;
  239. switch (c) {
  240. case 'c': default_interval = atoi(optarg); break;
  241. case 'e': error = parse_events(optarg); break;
  242. case 'm': mmap_pages = atoi(optarg); break;
  243. case 'o': output_name = strdup(optarg); break;
  244. case 'r': realtime_prio = atoi(optarg); break;
  245. default: error = 1; break;
  246. }
  247. }
  248. if (error)
  249. display_help();
  250. if (!nr_counters) {
  251. nr_counters = 1;
  252. event_id[0] = 0;
  253. }
  254. for (counter = 0; counter < nr_counters; counter++) {
  255. if (event_count[counter])
  256. continue;
  257. event_count[counter] = default_interval;
  258. }
  259. }
  260. struct mmap_data {
  261. int counter;
  262. void *base;
  263. unsigned int mask;
  264. unsigned int prev;
  265. };
  266. static unsigned int mmap_read_head(struct mmap_data *md)
  267. {
  268. struct perf_counter_mmap_page *pc = md->base;
  269. int head;
  270. head = pc->data_head;
  271. rmb();
  272. return head;
  273. }
  274. static long events;
  275. static struct timeval last_read, this_read;
  276. static void mmap_read(struct mmap_data *md)
  277. {
  278. unsigned int head = mmap_read_head(md);
  279. unsigned int old = md->prev;
  280. unsigned char *data = md->base + page_size;
  281. unsigned long size;
  282. void *buf;
  283. int diff;
  284. gettimeofday(&this_read, NULL);
  285. /*
  286. * If we're further behind than half the buffer, there's a chance
  287. * the writer will bite our tail and screw up the events under us.
  288. *
  289. * If we somehow ended up ahead of the head, we got messed up.
  290. *
  291. * In either case, truncate and restart at head.
  292. */
  293. diff = head - old;
  294. if (diff > md->mask / 2 || diff < 0) {
  295. struct timeval iv;
  296. unsigned long msecs;
  297. timersub(&this_read, &last_read, &iv);
  298. msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
  299. fprintf(stderr, "WARNING: failed to keep up with mmap data."
  300. " Last read %lu msecs ago.\n", msecs);
  301. /*
  302. * head points to a known good entry, start there.
  303. */
  304. old = head;
  305. }
  306. last_read = this_read;
  307. if (old != head)
  308. events++;
  309. size = head - old;
  310. if ((old & md->mask) + size != (head & md->mask)) {
  311. buf = &data[old & md->mask];
  312. size = md->mask + 1 - (old & md->mask);
  313. old += size;
  314. while (size) {
  315. int ret = write(output, buf, size);
  316. if (ret < 0) {
  317. perror("failed to write");
  318. exit(-1);
  319. }
  320. size -= ret;
  321. buf += ret;
  322. }
  323. }
  324. buf = &data[old & md->mask];
  325. size = head - old;
  326. old += size;
  327. while (size) {
  328. int ret = write(output, buf, size);
  329. if (ret < 0) {
  330. perror("failed to write");
  331. exit(-1);
  332. }
  333. size -= ret;
  334. buf += ret;
  335. }
  336. md->prev = old;
  337. }
  338. static volatile int done = 0;
  339. static void sigchld_handler(int sig)
  340. {
  341. if (sig == SIGCHLD)
  342. done = 1;
  343. }
  344. int main(int argc, char *argv[])
  345. {
  346. struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
  347. struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
  348. struct perf_counter_hw_event hw_event;
  349. int i, counter, group_fd, nr_poll = 0;
  350. pid_t pid;
  351. int ret;
  352. page_size = sysconf(_SC_PAGE_SIZE);
  353. process_options(argc, argv);
  354. nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
  355. assert(nr_cpus <= MAX_NR_CPUS);
  356. assert(nr_cpus >= 0);
  357. output = open(output_name, O_CREAT|O_RDWR, S_IRWXU);
  358. if (output < 0) {
  359. perror("failed to create output file");
  360. exit(-1);
  361. }
  362. argc -= optind;
  363. argv += optind;
  364. for (i = 0; i < nr_cpus; i++) {
  365. group_fd = -1;
  366. for (counter = 0; counter < nr_counters; counter++) {
  367. memset(&hw_event, 0, sizeof(hw_event));
  368. hw_event.config = event_id[counter];
  369. hw_event.irq_period = event_count[counter];
  370. hw_event.record_type = PERF_RECORD_IP | PERF_RECORD_TID;
  371. hw_event.nmi = 1;
  372. hw_event.mmap = 1;
  373. hw_event.comm = 1;
  374. fd[i][counter] = sys_perf_counter_open(&hw_event, -1, i, group_fd, 0);
  375. if (fd[i][counter] < 0) {
  376. int err = errno;
  377. printf("kerneltop error: syscall returned with %d (%s)\n",
  378. fd[i][counter], strerror(err));
  379. if (err == EPERM)
  380. printf("Are you root?\n");
  381. exit(-1);
  382. }
  383. assert(fd[i][counter] >= 0);
  384. fcntl(fd[i][counter], F_SETFL, O_NONBLOCK);
  385. /*
  386. * First counter acts as the group leader:
  387. */
  388. if (group && group_fd == -1)
  389. group_fd = fd[i][counter];
  390. event_array[nr_poll].fd = fd[i][counter];
  391. event_array[nr_poll].events = POLLIN;
  392. nr_poll++;
  393. mmap_array[i][counter].counter = counter;
  394. mmap_array[i][counter].prev = 0;
  395. mmap_array[i][counter].mask = mmap_pages*page_size - 1;
  396. mmap_array[i][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
  397. PROT_READ, MAP_SHARED, fd[i][counter], 0);
  398. if (mmap_array[i][counter].base == MAP_FAILED) {
  399. printf("kerneltop error: failed to mmap with %d (%s)\n",
  400. errno, strerror(errno));
  401. exit(-1);
  402. }
  403. }
  404. }
  405. signal(SIGCHLD, sigchld_handler);
  406. pid = fork();
  407. if (pid < 0)
  408. perror("failed to fork");
  409. if (!pid) {
  410. if (execvp(argv[0], argv)) {
  411. perror(argv[0]);
  412. exit(-1);
  413. }
  414. }
  415. if (realtime_prio) {
  416. struct sched_param param;
  417. param.sched_priority = realtime_prio;
  418. if (sched_setscheduler(0, SCHED_FIFO, &param)) {
  419. printf("Could not set realtime priority.\n");
  420. exit(-1);
  421. }
  422. }
  423. /*
  424. * TODO: store the current /proc/$/maps information somewhere
  425. */
  426. while (!done) {
  427. int hits = events;
  428. for (i = 0; i < nr_cpus; i++) {
  429. for (counter = 0; counter < nr_counters; counter++)
  430. mmap_read(&mmap_array[i][counter]);
  431. }
  432. if (hits == events)
  433. ret = poll(event_array, nr_poll, 100);
  434. }
  435. return 0;
  436. }