1*49e0263aSFeng Zhou // SPDX-License-Identifier: GPL-2.0
2*49e0263aSFeng Zhou /* Copyright (c) 2023 Bytedance */
3*49e0263aSFeng Zhou 
4*49e0263aSFeng Zhou #include <vmlinux.h>
5*49e0263aSFeng Zhou #include <bpf/bpf_tracing.h>
6*49e0263aSFeng Zhou #include <bpf/bpf_helpers.h>
7*49e0263aSFeng Zhou 
8*49e0263aSFeng Zhou #include "bpf_misc.h"
9*49e0263aSFeng Zhou 
10*49e0263aSFeng Zhou struct cgroup *bpf_cgroup_from_id(u64 cgid) __ksym;
11*49e0263aSFeng Zhou long bpf_task_under_cgroup(struct task_struct *task, struct cgroup *ancestor) __ksym;
12*49e0263aSFeng Zhou void bpf_cgroup_release(struct cgroup *p) __ksym;
13*49e0263aSFeng Zhou struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;
14*49e0263aSFeng Zhou void bpf_task_release(struct task_struct *p) __ksym;
15*49e0263aSFeng Zhou 
16*49e0263aSFeng Zhou const volatile int local_pid;
17*49e0263aSFeng Zhou const volatile __u64 cgid;
18*49e0263aSFeng Zhou int remote_pid;
19*49e0263aSFeng Zhou 
20*49e0263aSFeng Zhou SEC("tp_btf/task_newtask")
BPF_PROG(handle__task_newtask,struct task_struct * task,u64 clone_flags)21*49e0263aSFeng Zhou int BPF_PROG(handle__task_newtask, struct task_struct *task, u64 clone_flags)
22*49e0263aSFeng Zhou {
23*49e0263aSFeng Zhou 	struct cgroup *cgrp = NULL;
24*49e0263aSFeng Zhou 	struct task_struct *acquired;
25*49e0263aSFeng Zhou 
26*49e0263aSFeng Zhou 	if (local_pid != (bpf_get_current_pid_tgid() >> 32))
27*49e0263aSFeng Zhou 		return 0;
28*49e0263aSFeng Zhou 
29*49e0263aSFeng Zhou 	acquired = bpf_task_acquire(task);
30*49e0263aSFeng Zhou 	if (!acquired)
31*49e0263aSFeng Zhou 		return 0;
32*49e0263aSFeng Zhou 
33*49e0263aSFeng Zhou 	if (local_pid == acquired->tgid)
34*49e0263aSFeng Zhou 		goto out;
35*49e0263aSFeng Zhou 
36*49e0263aSFeng Zhou 	cgrp = bpf_cgroup_from_id(cgid);
37*49e0263aSFeng Zhou 	if (!cgrp)
38*49e0263aSFeng Zhou 		goto out;
39*49e0263aSFeng Zhou 
40*49e0263aSFeng Zhou 	if (bpf_task_under_cgroup(acquired, cgrp))
41*49e0263aSFeng Zhou 		remote_pid = acquired->tgid;
42*49e0263aSFeng Zhou 
43*49e0263aSFeng Zhou out:
44*49e0263aSFeng Zhou 	if (cgrp)
45*49e0263aSFeng Zhou 		bpf_cgroup_release(cgrp);
46*49e0263aSFeng Zhou 	bpf_task_release(acquired);
47*49e0263aSFeng Zhou 
48*49e0263aSFeng Zhou 	return 0;
49*49e0263aSFeng Zhou }
50*49e0263aSFeng Zhou 
51*49e0263aSFeng Zhou char _license[] SEC("license") = "GPL";
52