trace_output_user.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <poll.h>
  5. #include <time.h>
  6. #include <signal.h>
  7. #include <bpf/libbpf.h>
  8. static __u64 time_get_ns(void)
  9. {
  10. struct timespec ts;
  11. clock_gettime(CLOCK_MONOTONIC, &ts);
  12. return ts.tv_sec * 1000000000ull + ts.tv_nsec;
  13. }
  14. static __u64 start_time;
  15. static __u64 cnt;
  16. #define MAX_CNT 100000ll
  17. static void print_bpf_output(void *ctx, int cpu, void *data, __u32 size)
  18. {
  19. struct {
  20. __u64 pid;
  21. __u64 cookie;
  22. } *e = data;
  23. if (e->cookie != 0x12345678) {
  24. printf("BUG pid %llx cookie %llx sized %d\n",
  25. e->pid, e->cookie, size);
  26. return;
  27. }
  28. cnt++;
  29. if (cnt == MAX_CNT) {
  30. printf("recv %lld events per sec\n",
  31. MAX_CNT * 1000000000ll / (time_get_ns() - start_time));
  32. return;
  33. }
  34. }
  35. int main(int argc, char **argv)
  36. {
  37. struct bpf_link *link = NULL;
  38. struct bpf_program *prog;
  39. struct perf_buffer *pb;
  40. struct bpf_object *obj;
  41. int map_fd, ret = 0;
  42. char filename[256];
  43. FILE *f;
  44. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  45. obj = bpf_object__open_file(filename, NULL);
  46. if (libbpf_get_error(obj)) {
  47. fprintf(stderr, "ERROR: opening BPF object file failed\n");
  48. return 0;
  49. }
  50. /* load BPF program */
  51. if (bpf_object__load(obj)) {
  52. fprintf(stderr, "ERROR: loading BPF object file failed\n");
  53. goto cleanup;
  54. }
  55. map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
  56. if (map_fd < 0) {
  57. fprintf(stderr, "ERROR: finding a map in obj file failed\n");
  58. goto cleanup;
  59. }
  60. prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
  61. if (libbpf_get_error(prog)) {
  62. fprintf(stderr, "ERROR: finding a prog in obj file failed\n");
  63. goto cleanup;
  64. }
  65. link = bpf_program__attach(prog);
  66. if (libbpf_get_error(link)) {
  67. fprintf(stderr, "ERROR: bpf_program__attach failed\n");
  68. link = NULL;
  69. goto cleanup;
  70. }
  71. pb = perf_buffer__new(map_fd, 8, print_bpf_output, NULL, NULL, NULL);
  72. ret = libbpf_get_error(pb);
  73. if (ret) {
  74. printf("failed to setup perf_buffer: %d\n", ret);
  75. return 1;
  76. }
  77. f = popen("taskset 1 dd if=/dev/zero of=/dev/null", "r");
  78. (void) f;
  79. start_time = time_get_ns();
  80. while ((ret = perf_buffer__poll(pb, 1000)) >= 0 && cnt < MAX_CNT) {
  81. }
  82. kill(0, SIGINT);
  83. cleanup:
  84. bpf_link__destroy(link);
  85. bpf_object__close(obj);
  86. return ret;
  87. }