proc.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #define TASK_COMM_LEN 16
  2. #define CLONE_THREAD 0x00010000
  3. struct proc_event {
  4. __u32 type;
  5. __u32 pid;
  6. __u32 reason;
  7. };
  8. struct {
  9. __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
  10. __uint(key_size, sizeof(int));
  11. __uint(value_size, sizeof(int));
  12. } proc_events SEC(".maps");
  13. struct {
  14. __uint(type, BPF_MAP_TYPE_HASH);
  15. __uint(key_size, sizeof(__u32));
  16. __uint(value_size, sizeof(__u32));
  17. __uint(max_entries, 10240);
  18. } oom_info SEC(".maps");
  19. struct trace_event_raw_task_newtask__stub {
  20. __u64 unused;
  21. __u32 pid;
  22. char comm[TASK_COMM_LEN];
  23. long unsigned int clone_flags;
  24. };
  25. SEC("tracepoint/task/task_newtask")
  26. int task_newtask(struct trace_event_raw_task_newtask__stub *args)
  27. {
  28. if (args->clone_flags & CLONE_THREAD) { // skipping threads
  29. return 0;
  30. }
  31. struct proc_event e = {
  32. .type = EVENT_TYPE_PROCESS_START,
  33. .pid = args->pid,
  34. };
  35. bpf_perf_event_output(args, &proc_events, BPF_F_CURRENT_CPU, &e, sizeof(e));
  36. return 0;
  37. }
  38. struct trace_event_raw_sched_process_template__stub {
  39. __u64 unused;
  40. char comm[TASK_COMM_LEN];
  41. __u32 pid;
  42. };
  43. SEC("tracepoint/sched/sched_process_exit")
  44. int sched_process_exit(struct trace_event_raw_sched_process_template__stub *args)
  45. {
  46. __u64 id = bpf_get_current_pid_tgid();
  47. if (id >> 32 != (__u32)id) { // skipping threads
  48. return 0;
  49. }
  50. struct proc_event e = {
  51. .type = EVENT_TYPE_PROCESS_EXIT,
  52. .pid = args->pid,
  53. };
  54. if (bpf_map_lookup_elem(&oom_info, &e.pid)) {
  55. e.reason = EVENT_REASON_OOM_KILL;
  56. bpf_map_delete_elem(&oom_info, &e.pid);
  57. }
  58. bpf_perf_event_output(args, &proc_events, BPF_F_CURRENT_CPU, &e, sizeof(e));
  59. return 0;
  60. }
  61. struct trace_event_raw_mark_victim__stub {
  62. __u64 unused;
  63. int pid;
  64. };
  65. SEC("tracepoint/oom/mark_victim")
  66. int oom_mark_victim(struct trace_event_raw_mark_victim__stub *args)
  67. {
  68. __u32 pid = args->pid;
  69. bpf_map_update_elem(&oom_info, &pid, &pid, BPF_ANY);
  70. return 0;
  71. }