Re: [PATCH v4 7/9] rust: file: add `Kuid` wrapper

From: Valentin Obst
Date: Mon Feb 05 2024 - 17:24:19 EST


> > + /// Returns the given task's pid in the current pid namespace.
> > + pub fn pid_in_current_ns(&self) -> Pid {
> > + let current = Task::current_raw();
> > + // SAFETY: Calling `task_active_pid_ns` with the current task is always safe.
> > + let namespace = unsafe { bindings::task_active_pid_ns(current) };
> > + // SAFETY: We know that `self.0.get()` is valid by the type invariant, and the namespace
> > + // pointer is not dangling since it points at this task's namespace.
> > + unsafe { bindings::task_tgid_nr_ns(self.0.get(), namespace) }
> > + }
>
> pids are reference counted in the kernel, how does this deal with that?
> Are they just ignored somehow? Where is the reference count given back?
>
> thanks,
>
> greg k-h

As far as I can see, neither `task_active_pid_ns` nor `task_active_pid_ns`
return with an incremented refcount. However, looking at the above code,
it looks like it could be simplified to:

```rust
pub fn pid_in_current_ns(&self) -> Pid {
// SAFETY: We know that `self.0.get()` is valid by the type invariant.
// Passing a null pointer in the second argument defaults to the current ns.
unsafe { bindings::task_tgid_nr_ns(self.0.get(), ptr::null_mut()) }
}
```

Since:

```C
static inline pid_t task_tgid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
{
return __task_pid_nr_ns(tsk, PIDTYPE_TGID, ns);
}
..
pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
struct pid_namespace *ns)
{
pid_t nr = 0;

rcu_read_lock();
if (!ns)
ns = task_active_pid_ns(current);
nr = pid_nr_ns(rcu_dereference(*task_pid_ptr(task, type)), ns);
rcu_read_unlock();

return nr;
}
EXPORT_SYMBOL(__task_pid_nr_ns);
```

anyway defaults to current's pid ns (plus some RCU lock protection, not sure if
that is relevant here).

- Best Valentin