event.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright 2013, Michael Ellerman, IBM Corp.
  3. * Licensed under GPLv2.
  4. */
  5. #define _GNU_SOURCE
  6. #include <unistd.h>
  7. #include <sys/syscall.h>
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <sys/ioctl.h>
  11. #include "event.h"
  12. int perf_event_open(struct perf_event_attr *attr, pid_t pid, int cpu,
  13. int group_fd, unsigned long flags)
  14. {
  15. return syscall(__NR_perf_event_open, attr, pid, cpu,
  16. group_fd, flags);
  17. }
  18. void event_init_opts(struct event *e, u64 config, int type, char *name)
  19. {
  20. memset(e, 0, sizeof(*e));
  21. e->name = name;
  22. e->attr.type = type;
  23. e->attr.config = config;
  24. e->attr.size = sizeof(e->attr);
  25. /* This has to match the structure layout in the header */
  26. e->attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | \
  27. PERF_FORMAT_TOTAL_TIME_RUNNING;
  28. }
  29. void event_init_named(struct event *e, u64 config, char *name)
  30. {
  31. event_init_opts(e, config, PERF_TYPE_RAW, name);
  32. }
  33. #define PERF_CURRENT_PID 0
  34. #define PERF_NO_CPU -1
  35. #define PERF_NO_GROUP -1
  36. int event_open_with_options(struct event *e, pid_t pid, int cpu, int group_fd)
  37. {
  38. e->fd = perf_event_open(&e->attr, pid, cpu, group_fd, 0);
  39. if (e->fd == -1) {
  40. perror("perf_event_open");
  41. return -1;
  42. }
  43. return 0;
  44. }
  45. int event_open_with_group(struct event *e, int group_fd)
  46. {
  47. return event_open_with_options(e, PERF_CURRENT_PID, PERF_NO_CPU, group_fd);
  48. }
  49. int event_open(struct event *e)
  50. {
  51. return event_open_with_options(e, PERF_CURRENT_PID, PERF_NO_CPU, PERF_NO_GROUP);
  52. }
  53. void event_close(struct event *e)
  54. {
  55. close(e->fd);
  56. }
  57. int event_reset(struct event *e)
  58. {
  59. return ioctl(e->fd, PERF_EVENT_IOC_RESET);
  60. }
  61. int event_read(struct event *e)
  62. {
  63. int rc;
  64. rc = read(e->fd, &e->result, sizeof(e->result));
  65. if (rc != sizeof(e->result)) {
  66. fprintf(stderr, "read error on event %p!\n", e);
  67. return -1;
  68. }
  69. return 0;
  70. }
  71. void event_report_justified(struct event *e, int name_width, int result_width)
  72. {
  73. printf("%*s: result %*llu ", name_width, e->name, result_width,
  74. e->result.value);
  75. if (e->result.running == e->result.enabled)
  76. printf("running/enabled %llu\n", e->result.running);
  77. else
  78. printf("running %llu enabled %llu\n", e->result.running,
  79. e->result.enabled);
  80. }
  81. void event_report(struct event *e)
  82. {
  83. event_report_justified(e, 0, 0);
  84. }