xref: /linux/tools/testing/selftests/bpf/progs/task_ls_uptr.c (revision fcc79e1714e8c2b8e216dc3149812edd37884eef)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2024 Meta Platforms, Inc. and affiliates. */
3 
4 #include <vmlinux.h>
5 #include <bpf/bpf_helpers.h>
6 #include "uptr_test_common.h"
7 
8 struct task_struct *bpf_task_from_pid(s32 pid) __ksym;
9 void bpf_task_release(struct task_struct *p) __ksym;
10 void bpf_cgroup_release(struct cgroup *cgrp) __ksym;
11 
12 struct {
13 	__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
14 	__uint(map_flags, BPF_F_NO_PREALLOC);
15 	__type(key, int);
16 	__type(value, struct value_type);
17 } datamap SEC(".maps");
18 
19 pid_t target_pid = 0;
20 pid_t parent_pid = 0;
21 
22 SEC("tp_btf/sys_enter")
23 int on_enter(__u64 *ctx)
24 {
25 	struct task_struct *task, *data_task;
26 	struct value_type *ptr;
27 	struct user_data *udata;
28 	struct cgroup *cgrp;
29 
30 	task = bpf_get_current_task_btf();
31 	if (task->pid != target_pid)
32 		return 0;
33 
34 	data_task = bpf_task_from_pid(parent_pid);
35 	if (!data_task)
36 		return 0;
37 
38 	ptr = bpf_task_storage_get(&datamap, data_task, 0, 0);
39 	bpf_task_release(data_task);
40 	if (!ptr)
41 		return 0;
42 
43 	cgrp = bpf_kptr_xchg(&ptr->cgrp, NULL);
44 	if (cgrp) {
45 		int lvl = cgrp->level;
46 
47 		bpf_cgroup_release(cgrp);
48 		return lvl;
49 	}
50 
51 	udata = ptr->udata;
52 	if (!udata || udata->result)
53 		return 0;
54 	udata->result = MAGIC_VALUE + udata->a + udata->b;
55 
56 	udata = ptr->nested.udata;
57 	if (udata && !udata->nested_result)
58 		udata->nested_result = udata->result;
59 
60 	return 0;
61 }
62 
63 char _license[] SEC("license") = "GPL";
64