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