tracex6.bpf.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "vmlinux.h"
  2. #include <linux/version.h>
  3. #include <bpf/bpf_helpers.h>
  4. #include <bpf/bpf_tracing.h>
  5. #include <bpf/bpf_core_read.h>
  6. struct {
  7. __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
  8. __uint(key_size, sizeof(int));
  9. __uint(value_size, sizeof(u32));
  10. __uint(max_entries, 64);
  11. } counters SEC(".maps");
  12. struct {
  13. __uint(type, BPF_MAP_TYPE_HASH);
  14. __type(key, int);
  15. __type(value, u64);
  16. __uint(max_entries, 64);
  17. } values SEC(".maps");
  18. struct {
  19. __uint(type, BPF_MAP_TYPE_HASH);
  20. __type(key, int);
  21. __type(value, struct bpf_perf_event_value);
  22. __uint(max_entries, 64);
  23. } values2 SEC(".maps");
  24. SEC("kprobe/htab_map_get_next_key")
  25. int bpf_prog1(struct pt_regs *ctx)
  26. {
  27. u32 key = bpf_get_smp_processor_id();
  28. u64 count, *val;
  29. s64 error;
  30. count = bpf_perf_event_read(&counters, key);
  31. error = (s64)count;
  32. if (error <= -2 && error >= -22)
  33. return 0;
  34. val = bpf_map_lookup_elem(&values, &key);
  35. if (val)
  36. *val = count;
  37. else
  38. bpf_map_update_elem(&values, &key, &count, BPF_NOEXIST);
  39. return 0;
  40. }
  41. /*
  42. * Since *_map_lookup_elem can't be expected to trigger bpf programs
  43. * due to potential deadlocks (bpf_disable_instrumentation), this bpf
  44. * program will be attached to bpf_map_copy_value (which is called
  45. * from map_lookup_elem) and will only filter the hashtable type.
  46. */
  47. SEC("kprobe/bpf_map_copy_value")
  48. int BPF_KPROBE(bpf_prog2, struct bpf_map *map)
  49. {
  50. u32 key = bpf_get_smp_processor_id();
  51. struct bpf_perf_event_value *val, buf;
  52. enum bpf_map_type type;
  53. int error;
  54. type = BPF_CORE_READ(map, map_type);
  55. if (type != BPF_MAP_TYPE_HASH)
  56. return 0;
  57. error = bpf_perf_event_read_value(&counters, key, &buf, sizeof(buf));
  58. if (error)
  59. return 0;
  60. val = bpf_map_lookup_elem(&values2, &key);
  61. if (val)
  62. *val = buf;
  63. else
  64. bpf_map_update_elem(&values2, &key, &buf, BPF_NOEXIST);
  65. return 0;
  66. }
  67. char _license[] SEC("license") = "GPL";
  68. u32 _version SEC("version") = LINUX_VERSION_CODE;