Re: [PATCH bpf-next 1/2] bpf/docs: Document struct task_struct * kfuncs

David Vernet
2022-12-05T20:58:32Z

On Mon, Dec 05, 2022 at 10:10:14AM -0600, David Vernet wrote:
> > > +.. code-block:: c
> > > +
> > > + SEC("tp_btf/task_newtask")
> > > + int BPF_PROG(task_get_pid_example, struct task_struct *task, u64 clone_flags)
> > > + {
> > > + struct task_struct *lookup;
> > > +
> > > + lookup = bpf_task_from_pid(task->pid);
> > > + if (!lookup)
> > > + /* A task should always be found, as %task is a tracepoint arg. */
> > > + return -ENOENT;
> > > +
> > > + if (lookup->pid != task->pid) {
> > > + /* The pid of the lookup task should be the same as the input task. */
> >
> > I suspect both "errors" are actually possible in practice,
> > since bpf_task_from_pid is using init_pid_ns.
> > But this taskd might be in different pid_ns. See task_active_pid_ns.
> > Probably worth mentioning this aspect of bpf_task_from_pid.
>
> Yep, agreed. Will add

Actually, I don't think either error can ever happen. p->pid is globally
unique, and always uses the init_pid_ns. See [0] where p->pid is set,
and [1] for the implementation of pid_nr(). So I think the existing
example is actually correct, though I'll still add some comments to
explain that the kfunc only works for p->pid / the init_pid_ns.

[0]: https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/kernel/fork.c#n2326
[1]: https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/include/linux/pid.h#n181