tracex6_kern.c 1.9 KB

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