1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 
4 #ifndef _TASK_KFUNC_COMMON_H
5 #define _TASK_KFUNC_COMMON_H
6 
7 #include <errno.h>
8 #include <vmlinux.h>
9 #include <bpf/bpf_helpers.h>
10 #include <bpf/bpf_tracing.h>
11 
12 struct __tasks_kfunc_map_value {
13 	struct task_struct __kptr_ref * task;
14 };
15 
16 struct hash_map {
17 	__uint(type, BPF_MAP_TYPE_HASH);
18 	__type(key, int);
19 	__type(value, struct __tasks_kfunc_map_value);
20 	__uint(max_entries, 1);
21 } __tasks_kfunc_map SEC(".maps");
22 
23 struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;
24 struct task_struct *bpf_task_kptr_get(struct task_struct **pp) __ksym;
25 void bpf_task_release(struct task_struct *p) __ksym;
26 struct task_struct *bpf_task_from_pid(s32 pid) __ksym;
27 
28 static inline struct __tasks_kfunc_map_value *tasks_kfunc_map_value_lookup(struct task_struct *p)
29 {
30 	s32 pid;
31 	long status;
32 
33 	status = bpf_probe_read_kernel(&pid, sizeof(pid), &p->pid);
34 	if (status)
35 		return NULL;
36 
37 	return bpf_map_lookup_elem(&__tasks_kfunc_map, &pid);
38 }
39 
40 static inline int tasks_kfunc_map_insert(struct task_struct *p)
41 {
42 	struct __tasks_kfunc_map_value local, *v;
43 	long status;
44 	struct task_struct *acquired, *old;
45 	s32 pid;
46 
47 	status = bpf_probe_read_kernel(&pid, sizeof(pid), &p->pid);
48 	if (status)
49 		return status;
50 
51 	local.task = NULL;
52 	status = bpf_map_update_elem(&__tasks_kfunc_map, &pid, &local, BPF_NOEXIST);
53 	if (status)
54 		return status;
55 
56 	v = bpf_map_lookup_elem(&__tasks_kfunc_map, &pid);
57 	if (!v) {
58 		bpf_map_delete_elem(&__tasks_kfunc_map, &pid);
59 		return -ENOENT;
60 	}
61 
62 	acquired = bpf_task_acquire(p);
63 	old = bpf_kptr_xchg(&v->task, acquired);
64 	if (old) {
65 		bpf_task_release(old);
66 		return -EEXIST;
67 	}
68 
69 	return 0;
70 }
71 
72 #endif /* _TASK_KFUNC_COMMON_H */
73