tracex6_user.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #include <string.h>
  6. #include <fcntl.h>
  7. #include <poll.h>
  8. #include <sys/ioctl.h>
  9. #include <linux/perf_event.h>
  10. #include <linux/bpf.h>
  11. #include "libbpf.h"
  12. #include "bpf_load.h"
  13. #define SAMPLE_PERIOD 0x7fffffffffffffffULL
  14. static void test_bpf_perf_event(void)
  15. {
  16. int nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
  17. int *pmu_fd = malloc(nr_cpus * sizeof(int));
  18. int status, i;
  19. struct perf_event_attr attr_insn_pmu = {
  20. .freq = 0,
  21. .sample_period = SAMPLE_PERIOD,
  22. .inherit = 0,
  23. .type = PERF_TYPE_HARDWARE,
  24. .read_format = 0,
  25. .sample_type = 0,
  26. .config = 0,/* PMU: cycles */
  27. };
  28. for (i = 0; i < nr_cpus; i++) {
  29. pmu_fd[i] = perf_event_open(&attr_insn_pmu, -1/*pid*/, i/*cpu*/, -1/*group_fd*/, 0);
  30. if (pmu_fd[i] < 0) {
  31. printf("event syscall failed\n");
  32. goto exit;
  33. }
  34. bpf_update_elem(map_fd[0], &i, &pmu_fd[i], BPF_ANY);
  35. ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0);
  36. }
  37. status = system("ls > /dev/null");
  38. if (status)
  39. goto exit;
  40. status = system("sleep 2");
  41. if (status)
  42. goto exit;
  43. exit:
  44. for (i = 0; i < nr_cpus; i++)
  45. close(pmu_fd[i]);
  46. close(map_fd[0]);
  47. free(pmu_fd);
  48. }
  49. int main(int argc, char **argv)
  50. {
  51. char filename[256];
  52. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  53. if (load_bpf_file(filename)) {
  54. printf("%s", bpf_log_buf);
  55. return 1;
  56. }
  57. test_bpf_perf_event();
  58. read_trace_pipe();
  59. return 0;
  60. }