Re: [PATCH] pid: use READ_ONCE() and WRITE_ONCE() for pid_namespace::pid_allocated

From: Oleg Nesterov

Date: Thu Dec 03 2026 - 07:00:22 EST


On 12/02, Jiayi Zhang wrote:
>
> --- a/kernel/fork.c
> +++ b/kernel/fork.c
> @@ -2507,7 +2507,7 @@ __latent_entropy struct task_struct *copy_process(
> * child missed SIGKILL. If current is not in the same namespace,
> * we can't rely on fatal_signal_pending() below.
> */
> - if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
> + if (unlikely(!(READ_ONCE(ns_of_pid(pid)->pid_allocated) & PIDNS_ADDING))) {
> retval = -ENOMEM;
> goto bad_fork_core_free;
> }
> diff --git a/kernel/pid.c b/kernel/pid.c
> index adf7216..7b31ec7 100644
> --- a/kernel/pid.c
> +++ b/kernel/pid.c
> @@ -121,7 +121,10 @@ void free_pid(struct pid *pid)
> for (i = 0; i <= pid->level; i++) {
> struct upid *upid = pid->numbers + i;
> struct pid_namespace *ns = upid->ns;
> - switch (--ns->pid_allocated) {
> + unsigned int nr_allocated = ns->pid_allocated - 1;
> +
> + WRITE_ONCE(ns->pid_allocated, nr_allocated);
> + switch (nr_allocated) {
> case 2:
> case 1:
> /* When all that is left in the pid namespace
> @@ -331,7 +334,8 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid,
> for (upid = pid->numbers + ns->level; upid >= pid->numbers; --upid) {
> /* Make the PID visible to find_pid_ns. */
> idr_replace(&upid->ns->idr, pid, upid->nr);
> - upid->ns->pid_allocated++;
> + WRITE_ONCE(upid->ns->pid_allocated,
> + upid->ns->pid_allocated + 1);
> }
> spin_unlock(&pidmap_lock);
> idr_preload_end();
> @@ -363,7 +367,7 @@ out_abort:
> void disable_pid_allocation(struct pid_namespace *ns)
> {
> spin_lock(&pidmap_lock);
> - ns->pid_allocated &= ~PIDNS_ADDING;
> + WRITE_ONCE(ns->pid_allocated, ns->pid_allocated & ~PIDNS_ADDING);
> spin_unlock(&pidmap_lock);
> }
>
> diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
> index 127a5fd..53b0793 100644
> --- a/kernel/pid_namespace.c
> +++ b/kernel/pid_namespace.c
> @@ -270,7 +270,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
> */
> for (;;) {
> set_current_state(TASK_IDLE | TASK_FREEZABLE);
> - if (pid_ns->pid_allocated == init_pids)
> + if (READ_ONCE(pid_ns->pid_allocated) == init_pids)
> break;
> schedule();
> }

Reviewed-by: Oleg Nesterov <oleg@xxxxxxxxxx>