trace_output_user.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* This program is free software; you can redistribute it and/or
  2. * modify it under the terms of version 2 of the GNU General Public
  3. * License as published by the Free Software Foundation.
  4. */
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <stdlib.h>
  8. #include <stdbool.h>
  9. #include <string.h>
  10. #include <fcntl.h>
  11. #include <poll.h>
  12. #include <linux/perf_event.h>
  13. #include <linux/bpf.h>
  14. #include <errno.h>
  15. #include <assert.h>
  16. #include <sys/syscall.h>
  17. #include <sys/ioctl.h>
  18. #include <sys/mman.h>
  19. #include <time.h>
  20. #include <signal.h>
  21. #include <libbpf.h>
  22. #include "bpf_load.h"
  23. #include "perf-sys.h"
  24. #include "trace_helpers.h"
  25. static int pmu_fd;
  26. static __u64 time_get_ns(void)
  27. {
  28. struct timespec ts;
  29. clock_gettime(CLOCK_MONOTONIC, &ts);
  30. return ts.tv_sec * 1000000000ull + ts.tv_nsec;
  31. }
  32. static __u64 start_time;
  33. #define MAX_CNT 100000ll
  34. static int print_bpf_output(void *data, int size)
  35. {
  36. static __u64 cnt;
  37. struct {
  38. __u64 pid;
  39. __u64 cookie;
  40. } *e = data;
  41. if (e->cookie != 0x12345678) {
  42. printf("BUG pid %llx cookie %llx sized %d\n",
  43. e->pid, e->cookie, size);
  44. return LIBBPF_PERF_EVENT_ERROR;
  45. }
  46. cnt++;
  47. if (cnt == MAX_CNT) {
  48. printf("recv %lld events per sec\n",
  49. MAX_CNT * 1000000000ll / (time_get_ns() - start_time));
  50. return LIBBPF_PERF_EVENT_DONE;
  51. }
  52. return LIBBPF_PERF_EVENT_CONT;
  53. }
  54. static void test_bpf_perf_event(void)
  55. {
  56. struct perf_event_attr attr = {
  57. .sample_type = PERF_SAMPLE_RAW,
  58. .type = PERF_TYPE_SOFTWARE,
  59. .config = PERF_COUNT_SW_BPF_OUTPUT,
  60. };
  61. int key = 0;
  62. pmu_fd = sys_perf_event_open(&attr, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
  63. assert(pmu_fd >= 0);
  64. assert(bpf_map_update_elem(map_fd[0], &key, &pmu_fd, BPF_ANY) == 0);
  65. ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0);
  66. }
  67. int main(int argc, char **argv)
  68. {
  69. char filename[256];
  70. FILE *f;
  71. int ret;
  72. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  73. if (load_bpf_file(filename)) {
  74. printf("%s", bpf_log_buf);
  75. return 1;
  76. }
  77. test_bpf_perf_event();
  78. if (perf_event_mmap(pmu_fd) < 0)
  79. return 1;
  80. f = popen("taskset 1 dd if=/dev/zero of=/dev/null", "r");
  81. (void) f;
  82. start_time = time_get_ns();
  83. ret = perf_event_poller(pmu_fd, print_bpf_output);
  84. kill(0, SIGINT);
  85. return ret;
  86. }