Skip to content

Commit 3f0e6f2

Browse files
Byte-LabAlexei Starovoitov
authored andcommitted
bpf: Add bpf_task_from_pid() kfunc
Callers can currently store tasks as kptrs using bpf_task_acquire(), bpf_task_kptr_get(), and bpf_task_release(). These are useful if a caller already has a struct task_struct *, but there may be some callers who only have a pid, and want to look up the associated struct task_struct * from that to e.g. find task->comm. This patch therefore adds a new bpf_task_from_pid() kfunc which allows BPF programs to get a struct task_struct * kptr from a pid. Signed-off-by: David Vernet <void@manifault.com> Link: https://lore.kernel.org/r/20221122145300.251210-2-void@manifault.com Signed-off-by: Alexei Starovoitov <ast@kernel.org>
1 parent 5bad358 commit 3f0e6f2

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

kernel/bpf/helpers.c

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1959,6 +1959,25 @@ struct cgroup *bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
19591959
}
19601960
#endif /* CONFIG_CGROUPS */
19611961

1962+
/**
1963+
* bpf_task_from_pid - Find a struct task_struct from its pid by looking it up
1964+
* in the root pid namespace idr. If a task is returned, it must either be
1965+
* stored in a map, or released with bpf_task_release().
1966+
* @pid: The pid of the task being looked up.
1967+
*/
1968+
struct task_struct *bpf_task_from_pid(s32 pid)
1969+
{
1970+
struct task_struct *p;
1971+
1972+
rcu_read_lock();
1973+
p = find_task_by_pid_ns(pid, &init_pid_ns);
1974+
if (p)
1975+
bpf_task_acquire(p);
1976+
rcu_read_unlock();
1977+
1978+
return p;
1979+
}
1980+
19621981
void *bpf_cast_to_kern_ctx(void *obj)
19631982
{
19641983
return obj;
@@ -1984,13 +2003,13 @@ BTF_ID_FLAGS(func, bpf_list_pop_back, KF_ACQUIRE | KF_RET_NULL)
19842003
BTF_ID_FLAGS(func, bpf_task_acquire, KF_ACQUIRE | KF_TRUSTED_ARGS)
19852004
BTF_ID_FLAGS(func, bpf_task_kptr_get, KF_ACQUIRE | KF_KPTR_GET | KF_RET_NULL)
19862005
BTF_ID_FLAGS(func, bpf_task_release, KF_RELEASE)
1987-
19882006
#ifdef CONFIG_CGROUPS
19892007
BTF_ID_FLAGS(func, bpf_cgroup_acquire, KF_ACQUIRE | KF_TRUSTED_ARGS)
19902008
BTF_ID_FLAGS(func, bpf_cgroup_kptr_get, KF_ACQUIRE | KF_KPTR_GET | KF_RET_NULL)
19912009
BTF_ID_FLAGS(func, bpf_cgroup_release, KF_RELEASE)
19922010
BTF_ID_FLAGS(func, bpf_cgroup_ancestor, KF_ACQUIRE | KF_TRUSTED_ARGS | KF_RET_NULL)
19932011
#endif
2012+
BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL)
19942013
BTF_SET8_END(generic_btf_ids)
19952014

19962015
static const struct btf_kfunc_id_set generic_kfunc_set = {

0 commit comments

Comments
 (0)