1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2020 Wenbo Zhang
3 #include <vmlinux.h>
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_core_read.h>
6 #include <bpf/bpf_tracing.h>
7 #include "cpudist.h"
8 #include "bits.bpf.h"
9 #include "core_fixes.bpf.h"
10
11 #define TASK_RUNNING 0
12
13 const volatile bool targ_per_process = false;
14 const volatile bool targ_per_thread = false;
15 const volatile bool targ_offcpu = false;
16 const volatile bool targ_ms = false;
17 const volatile pid_t targ_tgid = -1;
18
19 struct {
20 __uint(type, BPF_MAP_TYPE_HASH);
21 __type(key, u32);
22 __type(value, u64);
23 } start SEC(".maps");
24
25 static struct hist initial_hist;
26
27 struct {
28 __uint(type, BPF_MAP_TYPE_HASH);
29 __type(key, u32);
30 __type(value, struct hist);
31 } hists SEC(".maps");
32
store_start(u32 tgid,u32 pid,u64 ts)33 static __always_inline void store_start(u32 tgid, u32 pid, u64 ts)
34 {
35 if (targ_tgid != -1 && targ_tgid != tgid)
36 return;
37 bpf_map_update_elem(&start, &pid, &ts, 0);
38 }
39
update_hist(struct task_struct * task,u32 tgid,u32 pid,u64 ts)40 static __always_inline void update_hist(struct task_struct *task,
41 u32 tgid, u32 pid, u64 ts)
42 {
43 u64 delta, *tsp, slot;
44 struct hist *histp;
45 u32 id;
46
47 if (targ_tgid != -1 && targ_tgid != tgid)
48 return;
49
50 tsp = bpf_map_lookup_elem(&start, &pid);
51 if (!tsp || ts < *tsp)
52 return;
53
54 if (targ_per_process)
55 id = tgid;
56 else if (targ_per_thread)
57 id = pid;
58 else
59 id = -1;
60 histp = bpf_map_lookup_elem(&hists, &id);
61 if (!histp) {
62 bpf_map_update_elem(&hists, &id, &initial_hist, 0);
63 histp = bpf_map_lookup_elem(&hists, &id);
64 if (!histp)
65 return;
66 bpf_probe_read_kernel_str(&histp->comm, sizeof(task->comm),
67 task->comm);
68 }
69 delta = ts - *tsp;
70 if (targ_ms)
71 delta /= 1000000;
72 else
73 delta /= 1000;
74 slot = log2l(delta);
75 if (slot >= MAX_SLOTS)
76 slot = MAX_SLOTS - 1;
77 __sync_fetch_and_add(&histp->slots[slot], 1);
78 }
79
80 SEC("tp_btf/sched_switch")
BPF_PROG(sched_switch,bool preempt,struct task_struct * prev,struct task_struct * next)81 int BPF_PROG(sched_switch, bool preempt, struct task_struct *prev,
82 struct task_struct *next)
83 {
84 u32 prev_tgid = prev->tgid, prev_pid = prev->pid;
85 u32 tgid = next->tgid, pid = next->pid;
86 u64 ts = bpf_ktime_get_ns();
87
88 if (targ_offcpu) {
89 store_start(prev_tgid, prev_pid, ts);
90 update_hist(next, tgid, pid, ts);
91 } else {
92 if (get_task_state(prev) == TASK_RUNNING)
93 update_hist(prev, prev_tgid, prev_pid, ts);
94 store_start(tgid, pid, ts);
95 }
96 return 0;
97 }
98
99 char LICENSE[] SEC("license") = "GPL";
100