trace_output_user.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 perf_buffer_opts pb_opts = {};
  38. struct bpf_link *link = NULL;
  39. struct bpf_program *prog;
  40. struct perf_buffer *pb;
  41. struct bpf_object *obj;
  42. int map_fd, ret = 0;
  43. char filename[256];
  44. FILE *f;
  45. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  46. obj = bpf_object__open_file(filename, NULL);
  47. if (libbpf_get_error(obj)) {
  48. fprintf(stderr, "ERROR: opening BPF object file failed\n");
  49. return 0;
  50. }
  51. /* load BPF program */
  52. if (bpf_object__load(obj)) {
  53. fprintf(stderr, "ERROR: loading BPF object file failed\n");
  54. goto cleanup;
  55. }
  56. map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
  57. if (map_fd < 0) {
  58. fprintf(stderr, "ERROR: finding a map in obj file failed\n");
  59. goto cleanup;
  60. }
  61. prog = bpf_object__find_program_by_name(obj, "bpf_prog1");
  62. if (libbpf_get_error(prog)) {
  63. fprintf(stderr, "ERROR: finding a prog in obj file failed\n");
  64. goto cleanup;
  65. }
  66. link = bpf_program__attach(prog);
  67. if (libbpf_get_error(link)) {
  68. fprintf(stderr, "ERROR: bpf_program__attach failed\n");
  69. link = NULL;
  70. goto cleanup;
  71. }
  72. pb_opts.sample_cb = print_bpf_output;
  73. pb = perf_buffer__new(map_fd, 8, &pb_opts);
  74. ret = libbpf_get_error(pb);
  75. if (ret) {
  76. printf("failed to setup perf_buffer: %d\n", ret);
  77. return 1;
  78. }
  79. f = popen("taskset 1 dd if=/dev/zero of=/dev/null", "r");
  80. (void) f;
  81. start_time = time_get_ns();
  82. while ((ret = perf_buffer__poll(pb, 1000)) >= 0 && cnt < MAX_CNT) {
  83. }
  84. kill(0, SIGINT);
  85. cleanup:
  86. bpf_link__destroy(link);
  87. bpf_object__close(obj);
  88. return ret;
  89. }