pid_namespace: make init creation more flexible
Subsystems (6)
Pavel Tikhomirov
reviewerv4 cover pid_namespace: make init creation more flexible
The first patch properly annotates accesses to ->child_reaper with _ONCE macroses, to protect unlocked accesses from possible cpu/compiler optimization problems.
The second patch makes sure that the init is always a first process in the pid namespace, previously this was only checked for set_tid case.
The third patch allows to join pid namespace before pid namespace init is created, that allows to create pid namespace by one process and then create pid namespace init from another process after setns(). Please see the detailed description in the patch commit message. It depends on the second patch.
The forth and the final patch is a comprehansive test, that tests both basic usecase of creating pid namespace and init separately, and a more specific usecase which shows how we can improve clone3(set_tid) usability after this change.
This change is generally useful as it makes clone3(set_tid) more universal, and let's it work in all the cases evenly. Also it is highly useful to CRIU to handle nested containers.
v2: Use *_ONCE for ->child_reaper accesses atomicity, and avoid taking task_list lock for reading it. Rebase to master.
v3: Separate *_ONCE change and "init is first" checks into separate commits.
v4: Update second patch commit message. Include Oleg's review tags.
This series is also available here:
https://github.com/Snorch/linux/commits/allow-creating-pid-namespace-init-after-setns-v4/
Pavel Tikhomirov (4):
pid_namespace: avoid optimization of accesses to ->child_reaper
pid: check init is created first after idr alloc
pid_namespace: allow opening pid_for_children before init was created
selftests: Add tests for creating pidns init via setns
kernel/exit.c | 3 +- kernel/fork.c | 5 +- kernel/pid.c | 17 +- kernel/pid_namespace.c | 9 - .../selftests/pid_namespace/.gitignore | 1 + .../testing/selftests/pid_namespace/Makefile | 2 +- .../pid_namespace/pidns_init_via_setns.c | 238 ++++++++++++++++++ 7 files changed, 256 insertions(+), 19 deletions(-) create mode 100644 tools/testing/selftests/pid_namespace/pidns_init_via_setns.c
Signature · 1 line
2.53.0
Pavel Tikhomirov
reviewerPATCH v4 1/4 pid_namespace: avoid optimization of accesses to ->child_reaper
To avoid potential problems related to cpu/compiler optimizations around ->child_reaper, let's use WRITE_ONCE (additional to task_list lock) everywhere we write it and use READ_ONCE where we read it without explicit lock. Note: It also pairs with existing READ_ONCE with no lock in nsfs_fh_to_dentry().
Also let's add ASSERT_EXCLUSIVE_WRITER before write to identify to KCSAN that we don't expect any concurrent ->child_reaper modifications, and those must be detected.
--
v3: Split from main commit. Add ASSERT_EXCLUSIVE_WRITER.
--- kernel/exit.c | 3 ++- kernel/fork.c | 5 ++++- kernel/pid.c | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-)
kernel/exit.c +2 -1
@@ -608,7 +608,8 @@ static struct task_struct *find_child_reaper(struct task_struct *father, reaper =find_alive_thread (father);if (reaper) { - pid_ns->child_reaper = reaper; +ASSERT_EXCLUSIVE_WRITER (pid_ns->child_reaper); +WRITE_ONCE (pid_ns->child_reaper, reaper);return reaper; }
kernel/fork.c +4 -1
@@ -2423,7 +2423,10 @@ __latent_entropy struct task_struct *copy_process(init_task_pid (p,PIDTYPE_SID ,task_session (current));if (is_child_reaper (pid)) { -ns_of_pid (pid)->child_reaper = p; +struct pid_namespace *ns =ns_of_pid (pid); + +ASSERT_EXCLUSIVE_WRITER (ns->child_reaper); +WRITE_ONCE (ns->child_reaper, p); p->signal->flags |=SIGNAL_UNKILLABLE ; } p->signal->shared_pending.signal = delayed.signal;
kernel/pid.c +1 -1
@@ -219,7 +219,7 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid,* Also fail if a PID != 1 is requested and * no PID 1 exists. */ -if (tid !=1 && !tmp->child_reaper) +if (tid !=1 && !READ_ONCE (tmp->child_reaper)) goto out_abort; retval = -EPERM ;if (!checkpoint_restore_ns_capable (tmp->user_ns))
Signature · 1 line
2.53.0
Pavel Tikhomirov
reviewerPATCH v4 2/4 pid: check init is created first after idr alloc
In reply to Pavel TikhomirovThis moves the condition (tid != 1 && !tmp->child_reaper) to after idr alloc, so it not only covers that first process in pid namespace has pid 1 in case of clone3(set_tid) requesting wrong pid, but also if idr itself gives wrong pid for some reason.
This could've been the case before this patch, when creating first process the alloc_pid()->pidfs_add_pid() code path fails, so that the idr->idr_next is non zero anymore and next process calling to alloc_pid(), will get 2 as a pid from idr_alloc_cyclic(). Though thanks to PIDNS_ADDING logic, free_pid() disables further pid allocation in this case and it does not lead to any real problem.
Note: This is also a preparation for the next patch in the series, which will introduce an ability of creating init from the task different to the task which had created the pid namespace. Needed to make sure that init is always first, even in this new case.
--
v3: Split from main commit. Merge two checks of ->child_reaper into one.
v4: Update commit message about PIDNS_ADDING.
--- kernel/pid.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
kernel/pid.c +10 -7
@@ -215,12 +215,6 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid, retval = -EINVAL ;if (tid <1 || tid >= pid_max[ns->level - i]) goto out_abort; -/* -* Also fail if a PID != 1 is requested and -* no PID 1 exists. -*/ -if (tid !=1 && !READ_ONCE (tmp->child_reaper)) - goto out_abort; retval = -EPERM ;if (!checkpoint_restore_ns_capable (tmp->user_ns)) goto out_abort;
@@ -296,9 +290,18 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid, pid->numbers[i].nr = nr; pid->numbers[i].ns = tmp; - tmp = tmp->parent; i--; retried_preload = false; + +/* +* PID 1 (init) must be created first. +*/ +if (!READ_ONCE (tmp->child_reaper) && nr !=1 ) { + retval = -EINVAL ; + goto out_free; + } + + tmp = tmp->parent; }/*
Signature · 1 line
2.53.0
Re: [PATCH v4 2/4] pid: check init is created first after idr alloc
Quoted 13 lines · Pavel Tikhomirov
This moves the condition (tid != 1 && !tmp->child_reaper) to after idr alloc, so it not only covers that first process in pid namespace has pid 1 in case of
clone3(set_tid)requesting wrong pid, but also if idr itself gives wrong pid for some reason.This could've been the case before this patch, when creating first process the alloc_pid()->pidfs_add_pid() code path fails, so that the
idr->idr_nextis non zero anymore and next process calling toalloc_pid(), will get 2 as a pid fromidr_alloc_cyclic(). Though thanks toPIDNS_ADDINGlogic,free_pid()disables further pid allocation in this case and it does not lead to any real problem.
Quoted 8 lines
Note: This is also a preparation for the next patch in the series, which will introduce an ability of creating init from the task different to the task which had created the pid namespace. Needed to make sure that init is always first, even in this new case.
Suggested-by Oleg Nesterov <[email protected]>Signed-off-by Oleg Nesterov <[email protected]>Signed-off-by Pavel Tikhomirov <[email protected]>
Thanks,
Andrei
Pavel Tikhomirov
reviewerPATCH v4 3/4 pid_namespace: allow opening pid_for_children before init was created
In reply to Pavel TikhomirovThis effectively gives us an ability to create the pid namespace init as a child of the process (setns-ed to the pid namespace) different to the process which created the pid namespace itself.
Original problem:
There is a cool set_tid feature in clone3() syscall, it allows you to create process with desired pids on multiple pid namespace levels. Which is useful to restore processes in CRIU for nested pid namespace case.
In nested container case we can potentially see this kind of pid/user namespace tree:
Process
┌─────────┐
User NS0 ──▶ Pid NS0 ──▶ Pid p0 │
│ │ │ │
▼ ▼ │ │
User NS1 ──▶ Pid NS1 ──▶ Pid p1 │
│ │ │ │
... ... │ ... │
│ │ │ │
▼ ▼ │ │
User NSn ──▶ Pid NSn ──▶ Pid pn │
└─────────┘
So to create the "Process" and set pids {p0, p1, ... pn} for it on all pid namespace levels we can use clone3() syscall set_tid feature, BUT the syscall does not allow you to set pid on pid namespace levels you don't have permission to. So basically you have to be in "User NS0" when creating the "Process" to actually be able to set pids on all levels.
It is ok for almost any process, but with pid namespace init this does not work, as currently we can only create pid namespace init and the pid namespace itself simultaneously, so to make "Pid NSn" owned by "User NSn" we have to be in the "User NSn".
We can't possibly be in "User NS0" and "User NSn" at the same time, hence the problem.
Alternative solution:
Yes, for the case of pid namespace init we can use old and gold /proc/sys/kernel/ns_last_pid interface on the levels lower than n. But it is much more complicated and introduces tons of extra code to do. It would be nice to make clone3() set_tid interface also aplicable to this corner case.
Implementation:
Now when anyone can setns to the pid namespace before the creation of init, and thus multiple processes can fork children to the pid namespace, it is important that we enforce the first process created is always pid namespace init. (Note that this was done by the previous preparational patch as a standalon useful change.) We only allow other processes after the init sets pid_namespace->child_reaper.
--
v2: Use *_ONCE for ->child_reaper accesses atomicity, and avoid taking task_list lock for reading it. Rebase to master, and thus remove now excess pidns_ready variable.
v3: Separate *_ONCE change and "init is first" checks into separate commits.
Note: I didn't find anything in copy_process() around setting the ->child_reaper which can influence the pid namespace, so it looks like the pid namespace is fully setup at the point when init sets ->child_reaper to receive more processes. Thus tasklist lock looks excess in pidns_for_children_get()'s ->child_reaper check and it should be safe not to have it in the corresponding check in alloc_pid() (introduced earlier in this series).
--- kernel/pid_namespace.c | 9 --------- 1 file changed, 9 deletions(-)
kernel/pid_namespace.c +0 -9
@@ -369,15 +369,6 @@ static struct ns_common *pidns_for_children_get(struct task_struct *task) }task_unlock (task); -if (ns) { -read_lock (&tasklist_lock); -if (!ns->child_reaper) { -put_pid_ns (ns); - ns =NULL ; - } -read_unlock (&tasklist_lock); - } -return ns ? &ns->ns :NULL ; }
Signature · 1 line
2.53.0
Re: [PATCH v4 3/4] pid_namespace: allow opening pid_for_children before init was created
Quoted 58 lines · Pavel Tikhomirov
This effectively gives us an ability to create the pid namespace init as a child of the process (setns-ed to the pid namespace) different to the process which created the pid namespace itself.
Original problem:
There is a cool
set_tidfeature inclone3()syscall, it allows you to create process with desired pids on multiple pid namespace levels. Which is useful to restore processes in CRIU for nested pid namespace case.In nested container case we can potentially see this kind of pid/user namespace tree:
Process
┌─────────┐
User NS0 ──▶ Pid NS0 ──▶ Pid p0 │
│ │ │ │
▼ ▼ │ │
User NS1 ──▶ Pid NS1 ──▶ Pid p1 │
│ │ │ │
... ... │ ... │
│ │ │ │
▼ ▼ │ │
User NSn ──▶ Pid NSn ──▶ Pid pn │
└─────────┘So to create the "Process" and set pids {p0, p1, ... pn} for it on all pid namespace levels we can use
clone3()syscallset_tidfeature, BUT the syscall does not allow you to set pid on pid namespace levels you don't have permission to. So basically you have to be in "User NS0" when creating the "Process" to actually be able to set pids on all levels.It is ok for almost any process, but with pid namespace init this does not work, as currently we can only create pid namespace init and the pid namespace itself simultaneously, so to make "Pid NSn" owned by "User NSn" we have to be in the "User NSn".
We can't possibly be in "User NS0" and "User NSn" at the same time, hence the problem.
Alternative solution:
Yes, for the case of pid namespace init we can use old and gold
/proc/sys/kernel/ns_last_pidinterface on the levels lower than n. But it is much more complicated and introduces tons of extra code to do. It would be nice to makeclone3()set_tidinterface also aplicable to this corner case.Implementation:
Now when anyone can setns to the pid namespace before the creation of init, and thus multiple processes can fork children to the pid namespace, it is important that we enforce the first process created is always pid namespace init. (Note that this was done by the previous preparational patch as a standalon useful change.) We only allow other processes after the init sets
pid_namespace->child_reaper.
Quoted 2 lines
Reviewed-by Oleg Nesterov <[email protected]>Signed-off-by Pavel Tikhomirov <[email protected]>
Thanks,
Andrei
Pavel Tikhomirov
reviewerPATCH v4 4/4 selftests: Add tests for creating pidns init via setns
In reply to Pavel TikhomirovFirst testcase "pidns_init_via_setns" checks that a process can become Pid 1 (init) in a new Pid namespace created via unshare() and joined via setns().
Second testcase "pidns_init_via_setns_set_tid" checks that during this process we can use clone3() + set_tid and set the pid in both the new and old pid namespaces (owned by different user namespaces).
--- .../selftests/pid_namespace/.gitignore | 1 + .../testing/selftests/pid_namespace/Makefile | 2 +- .../pid_namespace/pidns_init_via_setns.c | 238 ++++++++++++++++++ 3 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/pid_namespace/pidns_init_via_setns.c
tools/testing/selftests/pid_namespace/.gitignore +1 -0
@@ -1,2 +1,3 @@ pid_max +pidns_init_via_setns regression_enomem
tools/testing/selftests/pid_namespace/Makefile +1 -1
@@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 CFLAGS += -g $(KHDR_INCLUDES) -TEST_GEN_PROGS = regression_enomem pid_max +TEST_GEN_PROGS = regression_enomem pid_max pidns_init_via_setns LOCAL_HDRS += $(selfdir)/pidfd/pidfd.h
tools/testing/selftests/pid_namespace/pidns_init_via_setns.c new file +238 -0
238 lines not on this page · raw message
Signature · 1 line
2.53.0
cover pid: make sub-init creation retryable
In reply to Pavel TikhomirovAndrew,
On top of Pavel's series but but doesn't depend on it. Can be applied before or after.
Oleg.
---
kernel/fork.c | 6 +++++- kernel/pid.c | 18 +++++++++++------- 2 files changed, 16 insertions(+), 8 deletions(-)
PATCH 1/2 pid: make sub-init creation retryable
Currently we allow only one attempt to create init in a new namespace. If the first fork() fails after alloc_pid() succeeds, free_pid() clears PIDNS_ADDING and thus disables further PID allocations.
Nowadays this looks like an unnecessary limitation. The original reason to handle "case PIDNS_ADDING" in free_pid() is gone, most probably after commit 69879c01a0c3 ("proc: Remove the now unnecessary internal mount of proc").
Change free_pid() to keep ns->pid_allocated == PIDNS_ADDING, and change alloc_pid() to reset the cursor early, right after taking pidmap_lock.
Test-case:
#define _GNU_SOURCE
#include <linux/sched.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <assert.h>
#include <sched.h>
#include <errno.h>
int main(void)
{
struct clone_args args = {
.exit_signal = SIGCHLD,
.flags = CLONE_PIDFD,
.pidfd = 0,
};
unsigned long pidfd;
int pid;
assert(unshare(CLONE_NEWPID) == 0);
pid = syscall(__NR_clone3, &args, sizeof(args));
assert(pid == -1 && errno == EFAULT);
args.pidfd = (unsigned long)&pidfd;
pid = syscall(__NR_clone3, &args, sizeof(args));
if (pid)
assert(pid > 0 && wait(NULL) == pid);
else
assert(getpid() == 1);
return 0;
}--- kernel/pid.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-)
kernel/pid.c +6 -7
@@ -131,9 +131,8 @@ void free_pid(struct pid *pid)wake_up_process (ns->child_reaper);break ;case PIDNS_ADDING : -/* Handle a fork failure of the first process */ -WARN_ON (ns->child_reaper); - ns->pid_allocated =0 ; +/* Only possible if the 1st fork fails */ +WARN_ON (READ_ONCE (ns->child_reaper));break ; }
@@ -230,6 +229,10 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid, retried_preload = false;idr_preload (GFP_KERNEL );spin_lock (&pidmap_lock); +/* For the case when the previous attempt to create init failed */ +if (ns->pid_allocated ==PIDNS_ADDING ) +idr_set_cursor (&ns->idr,0 ); +for (tmp = ns, i = ns->level; i >=0 ;) {int tid = set_tid[ns->level - i];
@@ -341,10 +344,6 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid,idr_remove (&upid->ns->idr, upid->nr); } -/* On failure to allocate the first pid, reset the state */ -if (ns->pid_allocated ==PIDNS_ADDING ) -idr_set_cursor (&ns->idr,0 ); -spin_unlock (&pidmap_lock);idr_preload_end ();
Signature · 1 line
2.52.0
Re: [PATCH 1/2] pid: make sub-init creation retryable
Quoted 48 lines · Oleg Nesterov
Currently we allow only one attempt to create init in a new namespace. If the first
fork()fails afteralloc_pid()succeeds,free_pid()clearsPIDNS_ADDINGand thus disables further PID allocations.Nowadays this looks like an unnecessary limitation. The original reason to handle "case
PIDNS_ADDING" infree_pid()is gone, most probably after commit69879c01a0c3("proc: Remove the now unnecessary internal mount of proc").Change
free_pid()to keepns->pid_allocated==PIDNS_ADDING, and changealloc_pid()to reset the cursor early, right after takingpidmap_lock.Test-case:
#define _GNU_SOURCE #include <linux/sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <assert.h> #include <sched.h> #include <errno.h> int main(void) { struct clone_args args = { .exit_signal = SIGCHLD, .flags = CLONE_PIDFD, .pidfd = 0, }; unsigned long pidfd; int pid; assert(unshare(CLONE_NEWPID) == 0); pid = syscall(__NR_clone3, &args, sizeof(args)); assert(pid == -1 && errno == EFAULT); args.pidfd = (unsigned long)&pidfd; pid = syscall(__NR_clone3, &args, sizeof(args)); if (pid) assert(pid > 0 && wait(NULL) == pid); else assert(getpid() == 1); return 0; }
Quoted 1 line
Signed-off-by Oleg Nesterov <[email protected]>
Thanks,
Andrei
PATCH 2/2 pid: document the PIDNS_ADDING checks in alloc_pid() and copy_process()
In reply to Oleg NesterovBoth copy_process() and alloc_pid() do the same PIDNS_ADDING check. The reasons for these checks, and the fact that both are necessary, are not immediately obvious. Add the comments.
--- kernel/fork.c | 6 +++++- kernel/pid.c | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-)
kernel/fork.c +5 -1
@@ -2392,7 +2392,11 @@ __latent_entropy struct task_struct *copy_process(rseq_fork (p, clone_flags); -/* Don't start children in a dying pid namespace */ +/* +* If zap_pid_ns_processes() was called after alloc_pid(), the new +* 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 ))) { retval = -ENOMEM ; goto bad_fork_core_free;
kernel/pid.c +5 -0
@@ -317,6 +317,11 @@ struct pid *alloc_pid(struct pid_namespace *ns, pid_t *arg_set_tid,* * This can't be done earlier because we need to preserve other * error conditions. +* +* We need this even if copy_process() does the same check. If two +* or more tasks from parent namespace try to inject a child into a +* dead namespace, one of free_pid() calls from the copy_process() +* error path may try to wakeup the possibly freed ns->child_reaper. */ retval = -ENOMEM ;if (unlikely (!(ns->pid_allocated &PIDNS_ADDING )))
Signature · 1 line
2.52.0