mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [RFC PATCH v4 00/14] Namespace for namespace roots
@ 2026-11-19 22:42 Jarkko Sakkinen
  2026-11-19 22:42 ` [RFC PATCH v4 01/14] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
                   ` (13 more replies)
  0 siblings, 14 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:42 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

OVERVIEW
========

A root namespace (rootns) is a kernel object backed by a file descriptor
that binds together:

1. A full set of detached namespaces owned by a fresh user namespace.
2. A dedicated PID namespace for spawning processes into, signaling
   members, and polling or waiting on PID 1 exit.
3. An initially empty mount namespace (CLONE_EMPTY_MNTNS) populated
   directly in its target user namespace before going live, without
   inheriting host mounts or cloning staged trees, while still allowing
   new mounts to be attached at runtime.

Work on this feature started in 2025 from David Howells' container object
patch set [1], which I turned into a namespace for namespace roots and
rebuilt around that premise.

While the patch set is manually written, the original motivation came
from isolating LLM agents. Running untrusted agent workloads made it
clear that OCI runtimes need to minimize their live configuration
surface.

Assembling mounts, credentials, and namespaces inside helper processes
with a half-configured container is what I see as the main challenge,
and the existential debate around namespaces and container objects is an
unfocused discussion topic.

[1] https://lore.kernel.org/all/155059610368.17079.2220554006494174417.stgit@warthog.procyon.org.uk/

IMPLEMENTATION
==============

rootns() allocates a rootns instance backed by a pollable anonymous
inode fd, creating a fresh owning user namespace and a full set of
detached namespaces: empty mount (CLONE_EMPTY_MNTNS), PID, UTS, IPC,
network, cgroup, and time. ioctl(rootnsfd, ROOTNS_GET_NSFD, nstype)
returns nsfs file descriptors for individual member namespaces when
standalone namespace operations are needed.

Superblocks are configured directly in the target user namespace via
fsopen(), FSCONFIG_SET_ROOTNS, and fsmount(), allowing unprivileged
callers to assemble FS_USERNS_MOUNT filesystems without holding
CAP_SYS_ADMIN in their own user namespace or entering the target user
namespace first. move_mount(..., MOVE_MOUNT_T_MNTNS) operates on any
non-anonymous mount namespace fd: on an empty mount namespace it installs
"/" onto the nullfs root once, and it attaches relative submounts both
before entry and into live mount namespaces.

Once "/" is installed, processes are spawned into the rootns via clone3()
with CLONE_INTO_ROOTNS and struct clone_args.rootns, without mutating the
caller in place. Pairing CLONE_INTO_ROOTNS with CLONE_VFORK and opening
the target binary via openat2(..., RESOLVE_IN_ROOT) on the retained "/"
mount fd allows spawning with execveat() directly into the target root.

The first entrant becomes PID 1; once it exits and
zap_pid_ns_processes() reaps all members, poll() reports EPOLLHUP and
ioctl(rootnsfd, ROOTNS_WAIT, &args) returns init's exit status.
ioctl(rootnsfd, ROOTNS_KILL, sig) walks pid_ns->idr under tasklist_lock
to signal member thread groups, and dedicated LSM hooks mediate rootns
allocation, teardown, process entry, and signal delivery.

CHANGES
=======

v4:
- A single syscall API (and shenanigans e.g., in fsconfig).
- I use a similar API model as I used in SGX driver, as like enclaves,
  containers are "closures". Instead of /dev/sgx_enclave like device
  file, anon inode is used.
- Consolidate rootns_create(), rootns_wait(), and rootns_kill() into a
  single rootns() system call plus ROOTNS_WAIT and ROOTNS_KILL ioctls,
  dropping rusage from ROOTNS_WAIT.
- LSM: lbs_rootns security blob management and security_rootns_alloc(),
  security_rootns_free(), security_rootns_clone(), and
  security_rootns_kill() LSM hooks wired into bpf_lsm.
- Disallow CLONE_VM with CLONE_INTO_ROOTNS across time namespaces, require
  CAP_SYS_CHROOT, preserve caller umask, reset dumpability on user
  namespace transitions, and fix ROOTNS_WAIT, FSCONFIG_SET_ROOTNS,
  fsmount(), and MOVE_MOUNT_T_MNTNS locking and permission checks
  (Sashiko).
- Rewrite selftests/rootns in Python. I used similar structure as I've
  used in selftests/tpm2. This "along the lines" mimics Cells style
  container manager. Rootns is a quite typical no policy solution and
  Cells is a managed solution, and they are at the far ends, which can
  also be witnessed from the patch set sizes.

  The question really is where we want to draw the borderline. I'm
  neither favoring nor supporting any possible solution because I don't
  know. I'm just saying where they live as a software stack.
- Update documentation and architecture syscall tables for rootns().

v3:
- The patch set size increased predominantly because the coverage of
  kselftest had to widened to cover the introduced changes.
- Replace MOVE_MOUNT_T_ROOTNS_ROOT with MOVE_MOUNT_T_MNTNS targeting
  mnt_ns nsfs fds, and add ioctl(ROOTNS_GET_NSFD) to open member
  namespace fds (Andy Lutomirski).
- Allow unprivileged fsopen(), FSCONFIG_SET_ROOTNS, and fsmount() to
  configure and mount FS_USERNS_MOUNT filesystems directly in the target
  user namespace without entering it first (Andy Lutomirski).
- Fix locking, refcounting, credential/dumpability/timens setup,
  pivot_root() lookup, and cross-userns mount checks across copy_rootns(),
  CLONE_INTO_ROOTNS, rootns_kill(), FSCONFIG_SET_ROOTNS, and move_mount()
  (Sashiko).
- Mark PowerPC rootns syscalls nospu (Sashiko).
- Update documentation and kselftests.

v2:
- Drop rootns provenance tracking (rootns_id and rootns_may_setns()) and
  rely on user_namespace ownership for setns() isolation (Andy
  Lutomirski).
- Replace the rootns_enter() system call with clone3(CLONE_INTO_ROOTNS)
  and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3), allowing
  CLONE_VM | CLONE_VFORK and compatible per-child clone3() flags (Andy
  Lutomirski).
- Drop the spurious task_no_new_privs() check in may_enter_rootns_creds()
  (Andy Lutomirski).
- Update documentation, Kconfig, syscall tables, and kselftests for
  CLONE_INTO_ROOTNS.

VERSIONS
========

v3: https://lore.kernel.org/linux-fsdevel/20261118193539.240065-1-jarkko@kernel.org/
v2: https://lore.kernel.org/linux-fsdevel/20261117231352.3816603-1-jarkko@kernel.org/
v1: https://lore.kernel.org/linux-fsdevel/20261117050841.3289652-1-jarkko@kernel.org/


Cc: linux-api@vger.kernel.org
Cc: linux-arch@vger.kernel.org
Cc: linux-doc@vger.kernel.org
Cc: linux-fsdevel@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: linux-kselftest@vger.kernel.org
Cc: linux-mm@kvack.org
Cc: linux-security-module@vger.kernel.org
Cc: Albert Ou <aou@eecs.berkeley.edu>
Cc: Alexander Gordeev <agordeev@linux.ibm.com>
Cc: Alexander Viro <viro@zeniv.linux.org.uk>
Cc: Alexandre Ghiti <alex@ghiti.fr>
Cc: Andreas Larsson <andreas@gaisler.com>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Andy Lutomirski <luto@amacapital.net>
Cc: Andy Lutomirski <luto@kernel.org>
Cc: Anna-Maria Behnsen <anna-maria@linutronix.de>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Ben Segall <bsegall@google.com>
Cc: Borislav Petkov <bp@alien8.de>
Cc: Casey Schaufler <casey@schaufler-ca.com>
Cc: Catalin Marinas <catalin.marinas@arm.com>
Cc: Christian Borntraeger <borntraeger@linux.ibm.com>
Cc: Christian Brauner <brauner@kernel.org>
Cc: "Christophe Leroy (CS GROUP)" <chleroy@kernel.org>
Cc: Chris Zankel <chris@zankel.net>
Cc: Dave Hansen <dave.hansen@linux.intel.com>
Cc: David Hildenbrand <david@kernel.org>
Cc: David Howells <dhowells@redhat.com>
Cc: Davidlohr Bueso <dave@stgolabs.net>
Cc: "David S. Miller" <davem@davemloft.net>
Cc: Dietmar Eggemann <dietmar.eggemann@arm.com>
Cc: Frederic Weisbecker <frederic@kernel.org>
Cc: Geert Uytterhoeven <geert@linux-m68k.org>
Cc: Hallgrimur H. Gunnarsson <halg@google.com>
Cc: Heiko Carstens <hca@linux.ibm.com>
Cc: Helge Deller <deller@gmx.de>
Cc: "H. Peter Anvin" <hpa@zytor.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: "James E.J. Bottomley" <James.Bottomley@HansenPartnership.com>
Cc: Jan Kara <jack@suse.cz>
Cc: Jarkko Sakkinen <jarkko@kernel.org>
Cc: John Johansen <john.johansen@canonical.com>
Cc: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
Cc: Jonathan Corbet <corbet@lwn.net>
Cc: Josef Bacik <josef@toxicpanda.com>
Cc: Juri Lelli <juri.lelli@redhat.com>
Cc: Kees Cook <kees@kernel.org>
Cc: K Prateek Nayak <kprateek.nayak@amd.com>
Cc: "Liam R. Howlett" <liam@infradead.org>
Cc: Lorenzo Stoakes <ljs@kernel.org>
Cc: Madhavan Srinivasan <maddy@linux.ibm.com>
Cc: Magnus Lindholm <linmag7@gmail.com>
Cc: Manfred Spraul <manfred@colorfullife.com>
Cc: Mark Rutland <mark.rutland@arm.com>
Cc: Matt Turner <mattst88@gmail.com>
Cc: Max Filippov <jcmvbkbc@gmail.com>
Cc: Mel Gorman <mgorman@suse.de>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Michal Hocko <mhocko@suse.com>
Cc: Michal Simek <monstr@monstr.eu>
Cc: Mike Rapoport <rppt@kernel.org>
Cc: Neal Gompa <neal@gompa.dev>
Cc: Nicholas Piggin <npiggin@gmail.com>
Cc: Palmer Dabbelt <palmer@dabbelt.com>
Cc: Paul Moore <paul@paul-moore.com>
Cc: Paul Walmsley <pjw@kernel.org>
Cc: Pavel Tikhomirov <ptikhomirov@virtuozzo.com>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Randy Dunlap <rdunlap@infradead.org>
Cc: Richard Henderson <richard.henderson@linaro.org>
Cc: Rich Felker <dalias@libc.org>
Cc: "Ritesh Harjani (IBM)" <ritesh.list@gmail.com>
Cc: Russell King <linux@armlinux.org.uk>
Cc: Serge Hallyn <sergeh@kernel.org>
Cc: Shrikanth Hegde <sshegde@linux.ibm.com>
Cc: Shuah Khan <skhan@linuxfoundation.org>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Sven Schnelle <svens@linux.ibm.com>
Cc: Thomas Bogendoerfer <tsbogend@alpha.franken.de>
Cc: Thomas Gleixner <tglx@kernel.org>
Cc: Valentin Schneider <vschneid@redhat.com>
Cc: Vasily Gorbik <gor@linux.ibm.com>
Cc: Vincent Guittot <vincent.guittot@linaro.org>
Cc: Vincenzo Frascino <vincenzo.frascino@arm.com>
Cc: Vlastimil Babka <vbabka@kernel.org>
Cc: Will Deacon <will@kernel.org>
Cc: Yoshinori Sato <ysato@users.sourceforge.jp>
Cc: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>

Jarkko Sakkinen (14):
  nsproxy: Pass nsproxy to create_new_namespaces()
  rootns: Add core infrastructure for root namespaces
  rootns: Track init lifecycle via copy_process() and pid_namespace
  rootns: Add rootns() system call
  rootns: Add ROOTNS_WAIT ioctl
  rootns: Add ROOTNS_KILL ioctl
  fork: Support CLONE_INTO_ROOTNS in clone3()
  fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
  fs: Support MOVE_MOUNT_T_MNTNS in move_mount()
  security: Add rootns LSM hooks
  arch: Wire up rootns() system call
  docs: Document root namespace uAPI
  selftests/rootns: Add root namespace test suite
  MAINTAINERS: Add entry for ROOT NAMESPACE

 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    1 +
 Documentation/userspace-api/rootns.rst        |   56 +
 MAINTAINERS                                   |   11 +
 arch/alpha/kernel/syscalls/syscall.tbl        |    1 +
 arch/arm/tools/syscall.tbl                    |    1 +
 arch/arm64/tools/syscall_32.tbl               |    1 +
 arch/m68k/kernel/syscalls/syscall.tbl         |    1 +
 arch/microblaze/kernel/syscalls/syscall.tbl   |    1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl     |    1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl     |    1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl     |    1 +
 arch/parisc/kernel/syscalls/syscall.tbl       |    1 +
 arch/powerpc/kernel/syscalls/syscall.tbl      |    1 +
 arch/s390/kernel/syscalls/syscall.tbl         |    1 +
 arch/sh/kernel/syscalls/syscall.tbl           |    1 +
 arch/sparc/kernel/syscalls/syscall.tbl        |    1 +
 arch/x86/entry/syscalls/syscall_32.tbl        |    1 +
 arch/x86/entry/syscalls/syscall_64.tbl        |    1 +
 arch/xtensa/kernel/syscalls/syscall.tbl       |    1 +
 fs/devpts/inode.c                             |    2 +
 fs/filesystems.c                              |   15 +
 fs/fs_context.c                               |   21 +-
 fs/fsopen.c                                   |  139 +-
 fs/internal.h                                 |    6 +
 fs/namespace.c                                |  272 +++-
 fs/nsfs.c                                     |   64 +
 fs/proc/root.c                                |   18 +
 include/linux/cred.h                          |    4 +-
 include/linux/fs_context.h                    |    6 +
 include/linux/lsm_hook_defs.h                 |    7 +
 include/linux/lsm_hooks.h                     |    3 +
 include/linux/mnt_namespace.h                 |    2 +
 include/linux/nsfs.h                          |    2 +
 include/linux/nsproxy.h                       |    9 +-
 include/linux/pid_namespace.h                 |    4 +
 include/linux/rootns.h                        |   92 ++
 include/linux/sched/task.h                    |    8 +
 include/linux/security.h                      |   30 +
 include/linux/syscalls.h                      |    1 +
 include/linux/time_namespace.h                |   13 +
 include/linux/user_namespace.h                |    7 +
 include/uapi/asm-generic/unistd.h             |    6 +-
 include/uapi/linux/mount.h                    |    4 +-
 include/uapi/linux/rootns.h                   |   83 ++
 include/uapi/linux/sched.h                    |    5 +
 init/Kconfig                                  |    9 +
 ipc/mqueue.c                                  |   13 +
 kernel/Makefile                               |    2 +
 kernel/bpf/bpf_lsm.c                          |   10 +
 kernel/cred.c                                 |   32 +-
 kernel/fork.c                                 |   95 +-
 kernel/nsproxy.c                              |   41 +-
 kernel/pid_namespace.c                        |    2 +
 kernel/rootns.c                               |  581 +++++++++
 kernel/sys_ni.c                               |    3 +
 kernel/user_namespace.c                       |   12 +-
 scripts/syscall.tbl                           |    1 +
 security/lsm_init.c                           |    6 +
 security/security.c                           |   86 ++
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1076 +++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1161 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   11 +
 66 files changed, 3977 insertions(+), 88 deletions(-)
 create mode 100644 Documentation/userspace-api/rootns.rst
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh

--
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 01/14] nsproxy: Pass nsproxy to create_new_namespaces()
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
@ 2026-11-19 22:42 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 02/14] rootns: Add core infrastructure for root namespaces Jarkko Sakkinen
                   ` (12 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:42 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

create_new_namespaces() takes a struct task_struct pointer even though
it only reads tsk->nsproxy, preventing callers outside kernel/nsproxy.c
from constructing a child nsproxy without mutating a task.

Expose create_new_namespaces() and pass the source struct nsproxy
pointer directly so root namespace creation can allocate a detached
namespace set from current->nsproxy.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/nsproxy.h |  5 +++++
 kernel/nsproxy.c        | 32 ++++++++++++++++----------------
 2 files changed, 21 insertions(+), 16 deletions(-)

diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f092..cacbbbe3f1ce 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct user_namespace;
 
 /*
  * A structure to contain pointers to all per-process
@@ -92,6 +93,10 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *
  */
 
+struct nsproxy *create_new_namespaces(u64 flags,
+				      struct nsproxy *ns,
+				      struct user_namespace *user_ns,
+				      struct fs_struct *new_fs);
 int copy_namespaces(u64 flags, struct task_struct *tsk);
 void switch_cred_namespaces(const struct cred *old, const struct cred *new);
 void exit_nsproxy_namespaces(struct task_struct *tsk);
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 2dcf105e8ee2..8a3c6d4e94e2 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -85,9 +85,10 @@ void deactivate_nsproxy(struct nsproxy *ns)
  * Return the newly created nsproxy.  Do not attach this to the task,
  * leave it to the caller to do proper locking and attach it to task.
  */
-static struct nsproxy *create_new_namespaces(u64 flags,
-	struct task_struct *tsk, struct user_namespace *user_ns,
-	struct fs_struct *new_fs)
+struct nsproxy *create_new_namespaces(u64 flags,
+				      struct nsproxy *ns,
+				      struct user_namespace *user_ns,
+				      struct fs_struct *new_fs)
 {
 	struct nsproxy *new_nsp;
 	int err;
@@ -96,52 +97,51 @@ static struct nsproxy *create_new_namespaces(u64 flags,
 	if (!new_nsp)
 		return ERR_PTR(-ENOMEM);
 
-	new_nsp->mnt_ns = copy_mnt_ns(flags, tsk->nsproxy->mnt_ns,
-				      user_ns, new_fs);
+	new_nsp->mnt_ns = copy_mnt_ns(flags, ns->mnt_ns, user_ns, new_fs);
 	if (IS_ERR(new_nsp->mnt_ns)) {
 		err = PTR_ERR(new_nsp->mnt_ns);
 		goto out_ns;
 	}
 
-	new_nsp->uts_ns = copy_utsname(flags, user_ns, tsk->nsproxy->uts_ns);
+	new_nsp->uts_ns = copy_utsname(flags, user_ns, ns->uts_ns);
 	if (IS_ERR(new_nsp->uts_ns)) {
 		err = PTR_ERR(new_nsp->uts_ns);
 		goto out_uts;
 	}
 
-	new_nsp->ipc_ns = copy_ipcs(flags, user_ns, tsk->nsproxy->ipc_ns);
+	new_nsp->ipc_ns = copy_ipcs(flags, user_ns, ns->ipc_ns);
 	if (IS_ERR(new_nsp->ipc_ns)) {
 		err = PTR_ERR(new_nsp->ipc_ns);
 		goto out_ipc;
 	}
 
 	new_nsp->pid_ns_for_children =
-		copy_pid_ns(flags, user_ns, tsk->nsproxy->pid_ns_for_children);
+		copy_pid_ns(flags, user_ns, ns->pid_ns_for_children);
 	if (IS_ERR(new_nsp->pid_ns_for_children)) {
 		err = PTR_ERR(new_nsp->pid_ns_for_children);
 		goto out_pid;
 	}
 
 	new_nsp->cgroup_ns = copy_cgroup_ns(flags, user_ns,
-					    tsk->nsproxy->cgroup_ns);
+					    ns->cgroup_ns);
 	if (IS_ERR(new_nsp->cgroup_ns)) {
 		err = PTR_ERR(new_nsp->cgroup_ns);
 		goto out_cgroup;
 	}
 
-	new_nsp->net_ns = copy_net_ns(flags, user_ns, tsk->nsproxy->net_ns);
+	new_nsp->net_ns = copy_net_ns(flags, user_ns, ns->net_ns);
 	if (IS_ERR(new_nsp->net_ns)) {
 		err = PTR_ERR(new_nsp->net_ns);
 		goto out_net;
 	}
 
 	new_nsp->time_ns_for_children = copy_time_ns(flags, user_ns,
-					tsk->nsproxy->time_ns_for_children);
+					ns->time_ns_for_children);
 	if (IS_ERR(new_nsp->time_ns_for_children)) {
 		err = PTR_ERR(new_nsp->time_ns_for_children);
 		goto out_time;
 	}
-	new_nsp->time_ns = get_time_ns(tsk->nsproxy->time_ns);
+	new_nsp->time_ns = get_time_ns(ns->time_ns);
 
 	return new_nsp;
 
@@ -192,7 +192,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
 		(CLONE_NEWIPC | CLONE_SYSVSEM))
 		return -EINVAL;
 
-	new_ns = create_new_namespaces(flags, tsk, user_ns, tsk->fs);
+	new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
 	if (IS_ERR(new_ns))
 		return  PTR_ERR(new_ns);
 
@@ -231,7 +231,7 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags,
 		flags |= CLONE_EMPTY_MNTNS;
 	}
 
-	*new_nsp = create_new_namespaces(flags, current, user_ns,
+	*new_nsp = create_new_namespaces(flags, current->nsproxy, user_ns,
 					 new_fs ? new_fs : current->fs);
 	if (IS_ERR(*new_nsp)) {
 		err = PTR_ERR(*new_nsp);
@@ -289,7 +289,7 @@ int exec_task_namespaces(void)
 	if (tsk->nsproxy->time_ns_for_children == tsk->nsproxy->time_ns)
 		return 0;
 
-	new = create_new_namespaces(0, tsk, current_user_ns(), tsk->fs);
+	new = create_new_namespaces(0, tsk->nsproxy, current_user_ns(), tsk->fs);
 	if (IS_ERR(new))
 		return PTR_ERR(new);
 
@@ -356,7 +356,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)
 	struct task_struct *me = current;
 
 	nsset->flags = flags;
-	nsset->nsproxy = create_new_namespaces(0, me, current_user_ns(), me->fs);
+	nsset->nsproxy = create_new_namespaces(0, me->nsproxy, current_user_ns(), me->fs);
 	if (IS_ERR(nsset->nsproxy))
 		return PTR_ERR(nsset->nsproxy);
 
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 02/14] rootns: Add core infrastructure for root namespaces
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
  2026-11-19 22:42 ` [RFC PATCH v4 01/14] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 03/14] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
                   ` (11 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Linux namespaces can be created and entered individually, but userspace
orchestrators lack a single kernel object that binds a full detached
namespace set and an init process behind a pollable file descriptor.

Add struct rootns, its lifecycle states, reference counting, uAPI
creation flags, ROOTNS_GET_NSFD ioctl, and anonymous inode file
operations under CONFIG_ROOTNS. Drop active and passive namespace
references on final release, send SIGKILL to the rootns init thread
group on close when ROOTNS_KILL_ON_CLOSE is set, report EPOLLHUP from
poll() once the rootns reaches ROOTNS_DEAD, and allow holders with
CAP_SYS_ADMIN in the rootns user namespace to open member nsfs fds.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/nsfs.c                   |  64 +++++++++++++
 include/linux/nsfs.h        |   2 +
 include/linux/rootns.h      |  60 ++++++++++++
 include/uapi/linux/rootns.h |  44 +++++++++
 init/Kconfig                |   9 ++
 kernel/Makefile             |   2 +
 kernel/rootns.c             | 185 ++++++++++++++++++++++++++++++++++++
 7 files changed, 366 insertions(+)
 create mode 100644 include/linux/rootns.h
 create mode 100644 include/uapi/linux/rootns.h
 create mode 100644 kernel/rootns.c

diff --git a/fs/nsfs.c b/fs/nsfs.c
index 8179d69da038..1de51cd47508 100644
--- a/fs/nsfs.c
+++ b/fs/nsfs.c
@@ -711,3 +711,67 @@ void nsproxy_ns_active_put(struct nsproxy *ns)
 	ns_ref_active_put(ns->time_ns);
 	ns_ref_active_put(ns->time_ns_for_children);
 }
+
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+			   unsigned long nstype)
+{
+	struct ns_common *ns = NULL;
+
+	switch (nstype) {
+	case CLONE_NEWNS:
+		if (ns_ref_get(nsp->mnt_ns))
+			ns = to_ns_common(nsp->mnt_ns);
+		break;
+#ifdef CONFIG_CGROUPS
+	case CLONE_NEWCGROUP:
+		if (ns_ref_get(nsp->cgroup_ns))
+			ns = to_ns_common(nsp->cgroup_ns);
+		break;
+#endif
+#ifdef CONFIG_UTS_NS
+	case CLONE_NEWUTS:
+		if (ns_ref_get(nsp->uts_ns))
+			ns = to_ns_common(nsp->uts_ns);
+		break;
+#endif
+#ifdef CONFIG_IPC_NS
+	case CLONE_NEWIPC:
+		if (ns_ref_get(nsp->ipc_ns))
+			ns = to_ns_common(nsp->ipc_ns);
+		break;
+#endif
+#ifdef CONFIG_USER_NS
+	case CLONE_NEWUSER:
+		if (ns_ref_get(user_ns))
+			ns = to_ns_common(user_ns);
+		break;
+#endif
+#ifdef CONFIG_PID_NS
+	case CLONE_NEWPID:
+		if (ns_ref_get(nsp->pid_ns_for_children))
+			ns = to_ns_common(nsp->pid_ns_for_children);
+		break;
+#endif
+#ifdef CONFIG_NET_NS
+	case CLONE_NEWNET:
+		if (ns_ref_get(nsp->net_ns))
+			ns = to_ns_common(nsp->net_ns);
+		break;
+#endif
+	case CLONE_NEWTIME:
+#ifdef CONFIG_TIME_NS
+		if (ns_ref_get(nsp->time_ns))
+			ns = to_ns_common(nsp->time_ns);
+		break;
+#else
+		return -EOPNOTSUPP;
+#endif
+	default:
+		return -EINVAL;
+	}
+
+	if (!ns)
+		return -ESRCH;
+
+	return open_namespace(ns);
+}
diff --git a/include/linux/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fec..bfba790ee1a7 100644
--- a/include/linux/nsfs.h
+++ b/include/linux/nsfs.h
@@ -39,5 +39,7 @@ void nsfs_init(void);
 
 void nsproxy_ns_active_get(struct nsproxy *ns);
 void nsproxy_ns_active_put(struct nsproxy *ns);
+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,
+			   unsigned long nstype);
 
 #endif /* _LINUX_NSFS_H */
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
new file mode 100644
index 000000000000..3f59415efadb
--- /dev/null
+++ b/include/linux/rootns.h
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ */
+
+#ifndef _LINUX_ROOTNS_H
+#define _LINUX_ROOTNS_H
+
+#include <linux/refcount.h>
+#include <linux/spinlock.h>
+#include <linux/wait.h>
+
+struct file;
+struct nsproxy;
+struct pid;
+struct user_namespace;
+
+enum rootns_state {
+	ROOTNS_INIT	= 0,
+	ROOTNS_FORKING	= 1,
+	ROOTNS_RUNNING	= 2,
+	ROOTNS_DEAD	= 3,
+};
+
+/*
+ * The rootns object.
+ */
+struct rootns {
+	refcount_t		usage;
+	int			exit_code;	/* The exit code of 'init' */
+	struct user_namespace	*user_ns;	/* Owning user namespace */
+	struct nsproxy		*ns;		/* This rootns's namespaces */
+	struct pid		*init_pid;	/* The 'init' task's TGID (pid ref) */
+	spinlock_t		lock;		/* Guards rootns lifecycle state */
+	wait_queue_head_t	waitq;		/* Someone waiting for init to exit waits here */
+	unsigned int		flags;		/* Validated rootns() flags */
+	enum rootns_state	state;		/* Root namespace lifecycle state */
+};
+
+#ifdef CONFIG_ROOTNS
+struct rootns *get_rootns(struct rootns *c);
+void put_rootns(struct rootns *c);
+bool is_rootns_file(struct file *file);
+#else
+static inline struct rootns *get_rootns(struct rootns *c)
+{
+	return NULL;
+}
+
+static inline void put_rootns(struct rootns *c)
+{
+}
+
+static inline bool is_rootns_file(struct file *file)
+{
+	return false;
+}
+#endif /* CONFIG_ROOTNS */
+
+#endif /* _LINUX_ROOTNS_H */
diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
new file mode 100644
index 000000000000..bd643bdfb43c
--- /dev/null
+++ b/include/uapi/linux/rootns.h
@@ -0,0 +1,44 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ * Copyright (C) 2026 Opinsys Oy
+ */
+
+#ifndef _UAPI_LINUX_ROOTNS_H
+#define _UAPI_LINUX_ROOTNS_H
+
+#include <linux/ioctl.h>
+
+/**
+ * enum rootns_flags - Flags for rootns()
+ * @ROOTNS_KILL_ON_CLOSE: Send %SIGKILL to rootns init on final fd release.
+ * @ROOTNS_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.
+ * @ROOTNS_ALL_FLAGS: Mask of all valid flags accepted by rootns().
+ *
+ * Every root namespace allocates a full set of detached namespaces owned
+ * by a fresh user namespace.
+ */
+enum rootns_flags {
+	ROOTNS_KILL_ON_CLOSE	= 0x00000001,
+	ROOTNS_CLOSE_ON_EXEC	= 0x00000002,
+	ROOTNS_ALL_FLAGS	= 0x00000003,
+};
+
+#define ROOTNS_IOCTL_MAGIC	0xB9
+
+/**
+ * DOC: ROOTNS_GET_NSFD
+ *
+ * ``ioctl(rootnsfd, ROOTNS_GET_NSFD, nstype)`` opens an ``nsfs`` file
+ * descriptor (with ``O_CLOEXEC``) for the member namespace identified by
+ * ``nstype`` (one of ``CLONE_NEWNS``, ``CLONE_NEWCGROUP``,
+ * ``CLONE_NEWUTS``, ``CLONE_NEWIPC``, ``CLONE_NEWUSER``, ``CLONE_NEWPID``,
+ * ``CLONE_NEWNET``, or ``CLONE_NEWTIME``).
+ *
+ * Requires ``CAP_SYS_ADMIN`` in the ``rootns`` user namespace. Opening
+ * ``CLONE_NEWPID`` additionally requires running in an ancestor active PID
+ * namespace and that ``rootns`` init is running.
+ */
+#define ROOTNS_GET_NSFD		_IO(ROOTNS_IOCTL_MAGIC, 0x01)
+
+#endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/init/Kconfig b/init/Kconfig
index c8a7cfa60a6e..ed93dd11e6ac 100644
--- a/init/Kconfig
+++ b/init/Kconfig
@@ -1281,6 +1281,15 @@ config NET_NS
 	  Allow user space to create what appear to be multiple instances
 	  of the network stack.
 
+config ROOTNS
+	bool "Root namespace"
+	depends on USER_NS && PID_NS && UTS_NS && IPC_NS && NET_NS && CGROUPS
+	help
+	  Allow user space to create and manage isolated root namespaces
+	  with their own mount tree, user namespace, namespace set, and init
+	  process lifecycle via rootns(), rootns ioctls, and clone3() with
+	  CLONE_INTO_ROOTNS.
+
 endif # NAMESPACES
 
 config CHECKPOINT_RESTORE
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c..7074d2664ce7 100644
--- a/kernel/Makefile
+++ b/kernel/Makefile
@@ -152,6 +152,8 @@ KCOV_INSTRUMENT_kstack_erase.o := n
 
 obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o
 
+obj-$(CONFIG_ROOTNS) += rootns.o
+
 $(obj)/configs.o: $(obj)/config_data.gz
 
 # .config is small, so it is compressed with gzip rather than the image compressor.
diff --git a/kernel/rootns.c b/kernel/rootns.c
new file mode 100644
index 000000000000..3bbf7677080e
--- /dev/null
+++ b/kernel/rootns.c
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.
+ */
+
+/**
+ * DOC: Overview
+ *
+ * A root namespace binds a full set of detached namespaces, an initially empty
+ * mount namespace, an owning user namespace, and an init process behind a
+ * pollable control file descriptor:
+ *
+ * 1. ``rootns()`` allocates a detached ``rootns`` with a fresh user namespace
+ *    and dedicated mount (``CLONE_EMPTY_MNTNS``), PID, UTS, IPC, network,
+ *    cgroup, and time namespaces, returning its control fd.
+ *
+ * 2. Userspace configures superblocks via ``FSCONFIG_SET_ROOTNS``, retrieves
+ *    the mount namespace fd via ``ioctl(rootnsfd, ROOTNS_GET_NSFD,
+ *    CLONE_NEWNS)``, and installs ``"/"`` and relative submounts via
+ *    ``MOVE_MOUNT_T_MNTNS``.
+ *
+ * 3. ``clone3()`` with ``CLONE_INTO_ROOTNS`` spawns processes into the
+ *    ``rootns``; the first call commits PID 1 while concurrent bootstrap
+ *    callers wait killably.
+ *
+ * 4. ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` signals all member thread groups.
+ *    When PID 1 exits, the PID namespace zaps and reaps all remaining tasks,
+ *    ``poll()`` reports ``EPOLLHUP``, and ``ioctl(rootnsfd, ROOTNS_WAIT,
+ *    &args)`` returns init's exit status.
+ */
+
+#include <linux/poll.h>
+#include <linux/wait.h>
+#include <uapi/linux/wait.h>
+#include <linux/file.h>
+#include <linux/fs.h>
+#include <linux/anon_inodes.h>
+#include <linux/rootns.h>
+#include <linux/sched/signal.h>
+#include <linux/sched/task.h>
+#include <linux/slab.h>
+#include <linux/syscalls.h>
+#include <linux/uaccess.h>
+#include <linux/mnt_namespace.h>
+#include <linux/nsproxy.h>
+#include <linux/ns_common.h>
+#include <linux/nsfs.h>
+#include <linux/pid.h>
+#include <linux/pid_namespace.h>
+#include <linux/time_namespace.h>
+#include <linux/user_namespace.h>
+#include <linux/compat.h>
+#include <linux/idr.h>
+#include <uapi/linux/rootns.h>
+
+/*
+ * Get a reference to a rootns.
+ */
+struct rootns *get_rootns(struct rootns *c)
+{
+	refcount_inc(&c->usage);
+	return c;
+}
+
+/*
+ * Drop a reference on a rootns and clear it if it is no longer in use.
+ */
+void put_rootns(struct rootns *c)
+{
+	if (!c || !refcount_dec_and_test(&c->usage))
+		return;
+
+	if (c->ns)
+		put_nsproxy(c->ns);
+	if (c->init_pid)
+		put_pid(c->init_pid);
+	if (c->user_ns) {
+		ns_ref_active_put(c->user_ns);
+		put_user_ns(c->user_ns);
+	}
+	kfree(c);
+}
+
+/*
+ * Allow the user to poll for the rootns dying.
+ */
+static __poll_t rootns_poll(struct file *file, poll_table *wait)
+{
+	struct rootns *rootns = file->private_data;
+	__poll_t mask = 0;
+
+	poll_wait(file, &rootns->waitq, wait);
+
+	if (READ_ONCE(rootns->state) == ROOTNS_DEAD)
+		mask |= EPOLLHUP;
+
+	return mask;
+}
+
+static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
+{
+	if (nstype > UINT_MAX)
+		return -EINVAL;
+	if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	if (nstype == CLONE_NEWPID) {
+		if (!pidns_is_ancestor(rootns->ns->pid_ns_for_children,
+				       task_active_pid_ns(current)))
+			return -EXDEV;
+		if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)
+			return -ESRCH;
+	}
+
+	return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
+}
+
+static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
+{
+	struct rootns *rootns = file->private_data;
+
+	switch (cmd) {
+	case ROOTNS_GET_NSFD:
+		return rootns_get_nsfd(rootns, arg);
+	default:
+		return -ENOIOCTLCMD;
+	}
+}
+
+#ifdef CONFIG_COMPAT
+static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
+				unsigned long arg)
+{
+	switch (cmd) {
+	case ROOTNS_GET_NSFD:
+		return rootns_ioctl(file, cmd, arg);
+	default:
+		return -ENOIOCTLCMD;
+	}
+}
+#endif
+
+static int __rootns_kill(struct rootns *rootns, int sig, bool priv)
+{
+	struct pid *pid = NULL;
+	int ret;
+
+	scoped_guard(spinlock, &rootns->lock) {
+		if (rootns->state == ROOTNS_RUNNING)
+			pid = get_pid(rootns->init_pid);
+	}
+	if (!pid)
+		return -ESRCH;
+
+	ret = kill_pid(pid, sig, priv);
+	put_pid(pid);
+	return ret;
+}
+
+static int rootns_release(struct inode *inode, struct file *file)
+{
+	struct rootns *rootns = file->private_data;
+
+	if (rootns->flags & ROOTNS_KILL_ON_CLOSE)
+		__rootns_kill(rootns, SIGKILL, true);
+	put_rootns(rootns);
+	return 0;
+}
+
+static const struct file_operations rootns_fops = {
+	.poll		= rootns_poll,
+	.unlocked_ioctl	= rootns_ioctl,
+#ifdef CONFIG_COMPAT
+	.compat_ioctl	= rootns_compat_ioctl,
+#endif
+	.release	= rootns_release,
+};
+
+/*
+ * Returns true if the file is a rootns.
+ */
+bool is_rootns_file(struct file *file)
+{
+	return file->f_op == &rootns_fops;
+}
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 03/14] rootns: Track init lifecycle via copy_process() and pid_namespace
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
  2026-11-19 22:42 ` [RFC PATCH v4 01/14] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 02/14] rootns: Add core infrastructure for root namespaces Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 04/14] rootns: Add rootns() system call Jarkko Sakkinen
                   ` (10 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

A root namespace needs to record its init thread group's PID when
bootstrapped and capture its exit status once all processes in the root
namespace have terminated, without serializing normal fork() and exit()
paths inside the container.

Commit the bootstrap child reaper, bind pid_ns->rootns, and wake waiters
in copy_rootns() after attach_pid(PIDTYPE_PID), and invoke exit_rootns()
from zap_pid_ns_processes() after the root namespace's PID namespace has
killed and reaped all member tasks.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/pid_namespace.h |  4 ++++
 include/linux/rootns.h        | 15 ++++++++++++++
 kernel/fork.c                 |  3 +++
 kernel/pid_namespace.c        |  2 ++
 kernel/rootns.c               | 38 +++++++++++++++++++++++++++++++++++
 5 files changed, 62 insertions(+)

diff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b..6fd959f4d0d4 100644
--- a/include/linux/pid_namespace.h
+++ b/include/linux/pid_namespace.h
@@ -15,6 +15,7 @@
 #define MAX_PID_NS_LEVEL 32
 
 struct fs_pin;
+struct rootns;
 
 #if defined(CONFIG_SYSCTL) && defined(CONFIG_MEMFD_CREATE)
 /* modes for vm.memfd_noexec sysctl */
@@ -45,6 +46,9 @@ struct pid_namespace {
 	struct user_namespace *user_ns;
 	struct ucounts *ucounts;
 	int reboot;	/* group exit code if this pidns was rebooted */
+#ifdef CONFIG_ROOTNS
+	struct rootns *rootns;
+#endif
 	struct ns_common ns;
 	struct work_struct	work;
 } __randomize_layout;
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index 3f59415efadb..0557ce75195d 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -13,6 +13,8 @@
 struct file;
 struct nsproxy;
 struct pid;
+struct pid_namespace;
+struct task_struct;
 struct user_namespace;
 
 enum rootns_state {
@@ -41,6 +43,9 @@ struct rootns {
 struct rootns *get_rootns(struct rootns *c);
 void put_rootns(struct rootns *c);
 bool is_rootns_file(struct file *file);
+void copy_rootns(struct task_struct *tsk, struct pid *pid,
+		 struct rootns *rootns);
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
 #else
 static inline struct rootns *get_rootns(struct rootns *c)
 {
@@ -55,6 +60,16 @@ static inline bool is_rootns_file(struct file *file)
 {
 	return false;
 }
+
+static inline void copy_rootns(struct task_struct *tsk, struct pid *pid,
+			       struct rootns *rootns)
+{
+}
+
+static inline void exit_rootns(struct pid_namespace *pid_ns,
+			       struct task_struct *tsk)
+{
+}
 #endif /* CONFIG_ROOTNS */
 
 #endif /* _LINUX_ROOTNS_H */
diff --git a/kernel/fork.c b/kernel/fork.c
index 5efceb8d58a7..08fc28ad1eed 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -83,6 +83,7 @@
 #include <linux/fs_struct.h>
 #include <linux/magic.h>
 #include <linux/perf_event.h>
+#include <linux/rootns.h>
 #include <linux/posix-timers.h>
 #include <linux/user-return-notifier.h>
 #include <linux/oom.h>
@@ -2576,6 +2577,8 @@ __latent_entropy struct task_struct *copy_process(
 					  &p->signal->thread_head);
 		}
 		attach_pid(p, PIDTYPE_PID);
+		if (thread_group_leader(p))
+			copy_rootns(p, pid, NULL);
 		nr_threads++;
 	}
 	total_forks++;
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e70..081c27aa85bd 100644
--- a/kernel/pid_namespace.c
+++ b/kernel/pid_namespace.c
@@ -24,6 +24,7 @@
 #include <linux/sched/signal.h>
 #include <linux/idr.h>
 #include <linux/nstree.h>
+#include <linux/rootns.h>
 #include <uapi/linux/wait.h>
 #include "pid_sysctl.h"
 
@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
 		current->signal->group_exit_code = pid_ns->reboot;
 
 	acct_exit_ns(pid_ns);
+	exit_rootns(pid_ns, me);
 	return;
 }
 
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 3bbf7677080e..bde7cf4baebe 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -183,3 +183,41 @@ bool is_rootns_file(struct file *file)
 {
 	return file->f_op == &rootns_fops;
 }
+
+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)
+{
+	if (likely(!c || !is_child_reaper(pid)))
+		return;
+
+	scoped_guard(spinlock, &c->lock) {
+		if (c->state != ROOTNS_FORKING)
+			return;
+		ns_of_pid(pid)->rootns = get_rootns(c);
+		WRITE_ONCE(c->init_pid, get_pid(pid));
+		WRITE_ONCE(c->state, ROOTNS_RUNNING);
+	}
+	wake_up_all(&c->waitq);
+}
+
+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
+{
+	struct rootns *c = pid_ns->rootns;
+	struct task_struct *leader;
+	int status;
+
+	if (!c)
+		return;
+
+	leader = tsk->group_leader;
+	status = (tsk->signal->flags & SIGNAL_GROUP_EXIT) ?
+		 tsk->signal->group_exit_code : leader->exit_code;
+
+	scoped_guard(spinlock, &c->lock) {
+		c->exit_code = status;
+		WRITE_ONCE(c->state, ROOTNS_DEAD);
+	}
+
+	pid_ns->rootns = NULL;
+	wake_up_poll(&c->waitq, EPOLLHUP);
+	put_rootns(c);
+}
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 04/14] rootns: Add rootns() system call
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (2 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 03/14] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 05/14] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
                   ` (9 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Setting up an isolated namespace environment from a multithreaded
manager process currently requires helper processes to call unshare()
and pass file descriptors back over sockets.

Add the rootns() system call to allocate a detached rootns instance
owning a fresh user namespace alongside dedicated empty mount
(CLONE_EMPTY_MNTNS), PID, UTS, IPC, network, cgroup, and time
namespaces, and return its control file descriptor. Finalize the nsproxy
time namespace and pin active references for the lifetime of the rootns.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/syscalls.h       |   1 +
 include/linux/time_namespace.h |  13 ++++
 kernel/rootns.c                | 106 +++++++++++++++++++++++++++++++++
 kernel/sys_ni.c                |   3 +
 4 files changed, 123 insertions(+)

diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h
index 552d9710a0d5..7e630b612ef2 100644
--- a/include/linux/syscalls.h
+++ b/include/linux/syscalls.h
@@ -1006,6 +1006,7 @@ asmlinkage long sys_lsm_get_self_attr(unsigned int attr, struct lsm_ctx __user *
 asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *ctx,
 				      u32 size, u32 flags);
 asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);
+asmlinkage long sys_rootns(unsigned int flags);
 
 /*
  * Architecture-specific system calls
diff --git a/include/linux/time_namespace.h b/include/linux/time_namespace.h
index 58bd9728df58..bdc185543893 100644
--- a/include/linux/time_namespace.h
+++ b/include/linux/time_namespace.h
@@ -60,6 +60,15 @@ static inline void put_time_ns(struct time_namespace *ns)
 		free_time_ns(ns);
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+	if (nsproxy->time_ns != nsproxy->time_ns_for_children) {
+		get_time_ns(nsproxy->time_ns_for_children);
+		put_time_ns(nsproxy->time_ns);
+		nsproxy->time_ns = nsproxy->time_ns_for_children;
+	}
+}
+
 void proc_timens_show_offsets(struct task_struct *p, struct seq_file *m);
 
 struct proc_timens_offset {
@@ -125,6 +134,10 @@ static inline void put_time_ns(struct time_namespace *ns)
 {
 }
 
+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)
+{
+}
+
 static inline
 struct time_namespace *copy_time_ns(u64 flags,
 				    struct user_namespace *user_ns,
diff --git a/kernel/rootns.c b/kernel/rootns.c
index bde7cf4baebe..d9ef68d603a2 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -221,3 +221,109 @@ void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)
 	wake_up_poll(&c->waitq, EPOLLHUP);
 	put_rootns(c);
 }
+
+static struct user_namespace *create_rootns_user_ns(void)
+{
+	struct user_namespace *user_ns;
+	struct cred *new;
+	int ret;
+
+	new = prepare_creds();
+	if (!new)
+		return ERR_PTR(-ENOMEM);
+
+	ret = create_user_ns(new);
+	if (ret < 0) {
+		abort_creds(new);
+		return ERR_PTR(ret);
+	}
+
+	user_ns = get_user_ns(new->user_ns);
+	abort_creds(new);
+	return user_ns;
+}
+
+/*
+ * Create a new rootns.
+ */
+static struct rootns *create_rootns(unsigned int flags)
+{
+	u64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |
+			  CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |
+			  CLONE_NEWNET |
+			  (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);
+	struct user_namespace *user_ns;
+	struct nsproxy *ns;
+	struct rootns *c;
+	int ret;
+
+	c = kzalloc_obj(*c, GFP_KERNEL);
+	if (!c)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&c->waitq);
+	spin_lock_init(&c->lock);
+	refcount_set(&c->usage, 1);
+	c->flags = flags;
+
+	user_ns = create_rootns_user_ns();
+	if (IS_ERR(user_ns)) {
+		ret = PTR_ERR(user_ns);
+		goto err_put;
+	}
+	c->user_ns = user_ns;
+	ns_ref_active_get(user_ns);
+
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
+		ret = -EPERM;
+		goto err_put;
+	}
+
+	ns = create_new_namespaces(clone_flags, current->nsproxy, user_ns,
+				   NULL);
+	if (IS_ERR(ns)) {
+		ret = PTR_ERR(ns);
+		goto err_put;
+	}
+
+	timens_activate_nsproxy(ns);
+	c->ns = ns;
+	nsproxy_ns_active_get(ns);
+
+	return c;
+
+err_put:
+	put_rootns(c);
+	return ERR_PTR(ret);
+}
+
+/**
+ * sys_rootns - Create a detached root namespace
+ * @flags: Combination of &enum rootns_flags values
+ *
+ * Allocate a detached root namespace owning a fresh user namespace and
+ * dedicated empty mount, PID, UTS, IPC, network, cgroup, and time namespaces.
+ *
+ * Return: Control file descriptor on success, negative error code on failure.
+ */
+SYSCALL_DEFINE1(rootns, unsigned int, flags)
+{
+	struct rootns *c;
+	int fd;
+
+	if (flags & ~ROOTNS_ALL_FLAGS)
+		return -EINVAL;
+	if (unlikely(!current->nsproxy))
+		return -EOPNOTSUPP;
+
+	c = create_rootns(flags);
+	if (IS_ERR(c))
+		return PTR_ERR(c);
+
+	fd = anon_inode_getfd("rootns", &rootns_fops, c,
+			      O_RDWR | (flags & ROOTNS_CLOSE_ON_EXEC ? O_CLOEXEC : 0));
+	if (fd < 0)
+		put_rootns(c);
+
+	return fd;
+}
diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c
index c8be0abaa407..9fba98f15a20 100644
--- a/kernel/sys_ni.c
+++ b/kernel/sys_ni.c
@@ -398,3 +398,6 @@ COND_SYSCALL(rseq_slice_yield);
 
 COND_SYSCALL(uretprobe);
 COND_SYSCALL(uprobe);
+
+/* kernel/rootns.c */
+COND_SYSCALL(rootns);
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 05/14] rootns: Add ROOTNS_WAIT ioctl
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (3 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 04/14] rootns: Add rootns() system call Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 06/14] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
                   ` (8 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

wait4() and waitid() only allow a parent or subreaper to collect exit
status, so an external manager holding a rootns file descriptor cannot
wait on a rootns init process forked by another process or observe exit
status multiple times across observers.

Add the ROOTNS_WAIT ioctl and struct rootns_wait_args to wait freezably
and interruptibly on a rootns file descriptor until its init thread group
exits and report the recorded wait status. Return the init TGID
translated into the caller's active PID namespace, 0 for WNOHANG while
running, or -ECHILD if init was never started or is not visible to the
caller.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/uapi/linux/rootns.h | 26 ++++++++++++++++++++++
 kernel/rootns.c             | 44 +++++++++++++++++++++++++++++++++++++
 2 files changed, 70 insertions(+)

diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
index bd643bdfb43c..3fd215185398 100644
--- a/include/uapi/linux/rootns.h
+++ b/include/uapi/linux/rootns.h
@@ -8,6 +8,7 @@
 #define _UAPI_LINUX_ROOTNS_H
 
 #include <linux/ioctl.h>
+#include <linux/types.h>
 
 /**
  * enum rootns_flags - Flags for rootns()
@@ -24,6 +25,16 @@ enum rootns_flags {
 	ROOTNS_ALL_FLAGS	= 0x00000003,
 };
 
+/**
+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT
+ * @flags: Wait options (0 or %WNOHANG).
+ * @status: Output wait status of rootns init in waitpid(2) format.
+ */
+struct rootns_wait_args {
+	__u32 flags;
+	__s32 status;
+};
+
 #define ROOTNS_IOCTL_MAGIC	0xB9
 
 /**
@@ -41,4 +52,19 @@ enum rootns_flags {
  */
 #define ROOTNS_GET_NSFD		_IO(ROOTNS_IOCTL_MAGIC, 0x01)
 
+/**
+ * DOC: ROOTNS_WAIT
+ *
+ * ``ioctl(rootnsfd, ROOTNS_WAIT, &args)`` waits interruptibly (unless
+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches
+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init
+ * into ``args.status``.
+ *
+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if
+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with
+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in
+ * the caller's active PID namespace.
+ */
+#define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/kernel/rootns.c b/kernel/rootns.c
index d9ef68d603a2..5f03b6ba4a54 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -115,6 +115,45 @@ static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)
 	return nsproxy_open_namespace(rootns->ns, rootns->user_ns, nstype);
 }
 
+static long rootns_wait(struct rootns *rootns, void __user *uarg)
+{
+	struct pid_namespace *pid_ns = task_active_pid_ns(current);
+	struct rootns_wait_args args;
+	long ret;
+
+	if (!uarg)
+		return -EINVAL;
+	if (copy_from_user(&args, uarg, sizeof(args)))
+		return -EFAULT;
+	if (args.flags & ~WNOHANG)
+		return -EINVAL;
+	if (READ_ONCE(rootns->state) == ROOTNS_INIT)
+		return -ECHILD;
+
+	if (!(args.flags & WNOHANG)) {
+		ret = wait_event_freezable(rootns->waitq,
+					   READ_ONCE(rootns->state) == ROOTNS_DEAD ||
+					   READ_ONCE(rootns->state) == ROOTNS_INIT);
+		if (ret)
+			return ret;
+	}
+
+	scoped_guard(spinlock, &rootns->lock) {
+		if (rootns->state == ROOTNS_INIT)
+			return -ECHILD;
+		if (rootns->state != ROOTNS_DEAD)
+			return 0;
+		ret = pid_nr_ns(rootns->init_pid, pid_ns);
+		if (ret <= 0)
+			return -ECHILD;
+		args.status = rootns->exit_code;
+	}
+
+	if (copy_to_user(uarg, &args, sizeof(args)))
+		return -EFAULT;
+	return ret;
+}
+
 static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct rootns *rootns = file->private_data;
@@ -122,6 +161,8 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	switch (cmd) {
 	case ROOTNS_GET_NSFD:
 		return rootns_get_nsfd(rootns, arg);
+	case ROOTNS_WAIT:
+		return rootns_wait(rootns, (void __user *)arg);
 	default:
 		return -ENOIOCTLCMD;
 	}
@@ -132,6 +173,8 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
 				unsigned long arg)
 {
 	switch (cmd) {
+	case ROOTNS_WAIT:
+		return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
 	case ROOTNS_GET_NSFD:
 		return rootns_ioctl(file, cmd, arg);
 	default:
@@ -327,3 +370,4 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 
 	return fd;
 }
+
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 06/14] rootns: Add ROOTNS_KILL ioctl
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (4 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 05/14] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3() Jarkko Sakkinen
                   ` (7 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Signaling every process inside a container from userspace via /proc is
racy against concurrent fork() calls.

Add the ROOTNS_KILL ioctl to require an ancestor active PID namespace,
walk the root namespace's PID namespace IDR under tasklist_lock, and
deliver a validated signal once to each thread group including in-flight
forks, aggregating per-process delivery results.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/uapi/linux/rootns.h | 13 ++++++++++
 kernel/rootns.c             | 52 +++++++++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+)

diff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
index 3fd215185398..acd91d895c63 100644
--- a/include/uapi/linux/rootns.h
+++ b/include/uapi/linux/rootns.h
@@ -67,4 +67,17 @@ struct rootns_wait_args {
  */
 #define ROOTNS_WAIT		_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)
 
+/**
+ * DOC: ROOTNS_KILL
+ *
+ * ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` walks the target root namespace's PID
+ * namespace IDR under ``tasklist_lock`` and delivers ``sig`` (or ``0`` for a
+ * permission check) once to each member thread group.
+ *
+ * Returns ``0`` if at least one thread group was signaled, or ``-1`` with
+ * ``errno`` set to ``EXDEV`` if the caller's active PID namespace is not an
+ * ancestor or ``ESRCH`` if the ``rootns`` is not running or has no members.
+ */
+#define ROOTNS_KILL		_IO(ROOTNS_IOCTL_MAGIC, 0x03)
+
 #endif /* _UAPI_LINUX_ROOTNS_H */
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 5f03b6ba4a54..ce012a07e982 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -154,6 +154,53 @@ static long rootns_wait(struct rootns *rootns, void __user *uarg)
 	return ret;
 }
 
+static int rootns_kill_members(struct rootns *rootns, int sig)
+{
+	struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;
+	bool any_success = false;
+	bool any_other = false;
+	bool any_perm = false;
+	int other_err = 0;
+	struct pid *pid;
+	int nr;
+
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+	if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)
+		return -ESRCH;
+
+	scoped_guard(rcu) {
+		read_lock(&tasklist_lock);
+		idr_for_each_entry(&pid_ns->idr, pid, nr) {
+			struct task_struct *task = pid_task(pid, PIDTYPE_TGID);
+			int err;
+
+			if (!task)
+				continue;
+
+			err = group_send_sig_info(sig, SEND_SIG_NOINFO, task,
+						  PIDTYPE_MAX);
+			if (!err) {
+				any_success = true;
+			} else if (err == -EPERM) {
+				any_perm = true;
+			} else if (err != -ESRCH && !any_other) {
+				any_other = true;
+				other_err = err;
+			}
+		}
+		read_unlock(&tasklist_lock);
+	}
+
+	if (any_success)
+		return 0;
+	if (any_other)
+		return other_err;
+	if (any_perm)
+		return -EPERM;
+	return -ESRCH;
+}
+
 static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct rootns *rootns = file->private_data;
@@ -163,6 +210,10 @@ static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 		return rootns_get_nsfd(rootns, arg);
 	case ROOTNS_WAIT:
 		return rootns_wait(rootns, (void __user *)arg);
+	case ROOTNS_KILL:
+		if (arg > INT_MAX || !valid_signal(arg))
+			return -EINVAL;
+		return rootns_kill_members(rootns, arg);
 	default:
 		return -ENOIOCTLCMD;
 	}
@@ -176,6 +227,7 @@ static long rootns_compat_ioctl(struct file *file, unsigned int cmd,
 	case ROOTNS_WAIT:
 		return rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
 	case ROOTNS_GET_NSFD:
+	case ROOTNS_KILL:
 		return rootns_ioctl(file, cmd, arg);
 	default:
 		return -ENOIOCTLCMD;
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3()
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (5 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 06/14] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 08/14] fs: Support FSCONFIG_SET_ROOTNS in fsconfig() Jarkko Sakkinen
                   ` (6 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Multithreaded userspace daemons cannot call setns(CLONE_NEWUSER) or
safely mutate process-wide filesystem state in place before spawning a
child into a target namespace set.

Add CLONE_INTO_ROOTNS and struct clone_args.rootns (CLONE_ARGS_SIZE_VER3)
to spawn a child process directly into a rootns whose root mount has
been installed. Transition the rootns from ROOTNS_INIT through
ROOTNS_FORKING to ROOTNS_RUNNING for the first process so it becomes
PID 1, serialize concurrent entrants on waitq until bootstrap resolves,
and admit subsequent callers into the running PID namespace until
teardown begins.

Derive child credentials from current, require CAP_SYS_ADMIN and
CAP_SYS_CHROOT in the target user namespace and an ancestor active PID
namespace, preserve caller umask, reset dumpability across user namespace
transitions, commit time namespace vvar mappings after copy_process()
succeeds, and look up the live mount namespace root. Restrict companion
flags to CLONE_VFORK, CLONE_PIDFD, CLONE_PIDFD_AUTOKILL, CLONE_AUTOREAP,
CLONE_CLEAR_SIGHAND, CLONE_INTO_CGROUP, and CLONE_NNP.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/namespace.c                 |  16 ++++
 include/linux/cred.h           |   4 +-
 include/linux/mnt_namespace.h  |   2 +
 include/linux/nsproxy.h        |   4 +-
 include/linux/rootns.h         |  14 ++++
 include/linux/sched/task.h     |   8 ++
 include/linux/user_namespace.h |   7 ++
 include/uapi/linux/sched.h     |   5 ++
 kernel/cred.c                  |  32 +++++++-
 kernel/fork.c                  |  94 ++++++++++++++++++++---
 kernel/nsproxy.c               |  11 ++-
 kernel/rootns.c                | 136 +++++++++++++++++++++++++++++++++
 kernel/user_namespace.c        |  12 ++-
 13 files changed, 327 insertions(+), 18 deletions(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index aecd05ac0170..781380945d78 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -6708,6 +6708,22 @@ static void mntns_put(struct ns_common *ns)
 	put_mnt_ns(to_mnt_ns(ns));
 }
 
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root)
+{
+	int err;
+
+	err = vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt,
+			      "/", LOOKUP_DOWN, root);
+	if (err)
+		return err;
+	if (root->mnt == &mnt_ns->root->mnt) {
+		path_put(root);
+		*root = (struct path){};
+		return -ENOENT;
+	}
+	return 0;
+}
+
 static int mntns_install(struct nsset *nsset, struct ns_common *ns)
 {
 	struct nsproxy *nsproxy = nsset->nsproxy;
diff --git a/include/linux/cred.h b/include/linux/cred.h
index 49c26af37349..9849366fd44b 100644
--- a/include/linux/cred.h
+++ b/include/linux/cred.h
@@ -19,6 +19,7 @@
 
 struct cred;
 struct inode;
+struct rootns;
 
 extern struct task_struct init_task;
 
@@ -152,7 +153,8 @@ struct cred {
 
 extern void __put_cred(struct cred *);
 extern void exit_creds(struct task_struct *);
-extern int copy_creds(struct task_struct *, u64);
+int copy_creds(struct task_struct *tsk, u64 clone_flags,
+	       struct rootns *rootns);
 extern const struct cred *get_task_cred(struct task_struct *);
 extern struct cred *cred_alloc_blank(void);
 extern struct cred *prepare_creds(void);
diff --git a/include/linux/mnt_namespace.h b/include/linux/mnt_namespace.h
index 0acd1089d149..98188d1f7428 100644
--- a/include/linux/mnt_namespace.h
+++ b/include/linux/mnt_namespace.h
@@ -8,6 +8,7 @@
 
 struct mnt_namespace;
 struct fs_struct;
+struct path;
 struct user_namespace;
 struct ns_common;
 
@@ -15,6 +16,7 @@ extern struct mnt_namespace init_mnt_ns;
 
 extern struct mnt_namespace *copy_mnt_ns(u64, struct mnt_namespace *,
 		struct user_namespace *, struct fs_struct *);
+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root);
 extern void put_mnt_ns(struct mnt_namespace *ns);
 DEFINE_FREE(put_mnt_ns, struct mnt_namespace *, if (!IS_ERR_OR_NULL(_T)) put_mnt_ns(_T))
 extern struct ns_common *from_mnt_ns(struct mnt_namespace *);
diff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h
index cacbbbe3f1ce..26b3b788cc90 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -12,6 +12,7 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct rootns;
 struct user_namespace;
 
 /*
@@ -97,7 +98,8 @@ struct nsproxy *create_new_namespaces(u64 flags,
 				      struct nsproxy *ns,
 				      struct user_namespace *user_ns,
 				      struct fs_struct *new_fs);
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns);
 void switch_cred_namespaces(const struct cred *old, const struct cred *new);
 void exit_nsproxy_namespaces(struct task_struct *tsk);
 void get_cred_namespaces(struct task_struct *tsk);
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index 0557ce75195d..802fc76bb66e 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -11,6 +11,7 @@
 #include <linux/wait.h>
 
 struct file;
+struct kernel_clone_args;
 struct nsproxy;
 struct pid;
 struct pid_namespace;
@@ -46,6 +47,8 @@ bool is_rootns_file(struct file *file);
 void copy_rootns(struct task_struct *tsk, struct pid *pid,
 		 struct rootns *rootns);
 void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);
+int rootns_prepare_fork(struct kernel_clone_args *args);
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p);
 #else
 static inline struct rootns *get_rootns(struct rootns *c)
 {
@@ -70,6 +73,17 @@ static inline void exit_rootns(struct pid_namespace *pid_ns,
 			       struct task_struct *tsk)
 {
 }
+
+static inline int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+	return -EINVAL;
+}
+
+static inline int rootns_finish_fork(struct kernel_clone_args *args,
+				     struct task_struct *p)
+{
+	return 0;
+}
 #endif /* CONFIG_ROOTNS */
 
 #endif /* _LINUX_ROOTNS_H */
diff --git a/include/linux/sched/task.h b/include/linux/sched/task.h
index 90ed5bc3c7af..e0c4e8ab02f1 100644
--- a/include/linux/sched/task.h
+++ b/include/linux/sched/task.h
@@ -16,6 +16,8 @@ struct task_struct;
 struct rusage;
 union thread_union;
 struct css_set;
+struct file;
+struct rootns;
 
 /* All the bits taken by the old clone syscall. */
 #define CLONE_LEGACY_FLAGS 0xffffffffULL
@@ -39,11 +41,17 @@ struct kernel_clone_args {
 	/* Number of elements in *set_tid */
 	size_t set_tid_size;
 	int cgroup;
+	int rootns_fd;
 	int idle;
 	int (*fn)(void *);
 	void *fn_arg;
 	struct cgroup *cgrp;
 	struct css_set *cset;
+#ifdef CONFIG_ROOTNS
+	struct file *rootns_file;
+	struct rootns *rootns;
+	bool rootns_bootstrapping;
+#endif
 	unsigned int kill_seq;
 };
 
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d..3600a903442e 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -184,6 +184,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)
 }
 
 extern int create_user_ns(struct cred *new);
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);
 extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);
 extern void __put_user_ns(struct user_namespace *ns);
 
@@ -226,6 +227,12 @@ static inline int create_user_ns(struct cred *new)
 	return -EINVAL;
 }
 
+static inline int install_user_ns_cred(struct cred *cred,
+				       struct user_namespace *user_ns)
+{
+	return -EINVAL;
+}
+
 static inline int unshare_userns(unsigned long unshare_flags,
 				 struct cred **new_cred)
 {
diff --git a/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba89428..405cfc954ae1 100644
--- a/include/uapi/linux/sched.h
+++ b/include/uapi/linux/sched.h
@@ -40,6 +40,7 @@
 #define CLONE_NNP		(1ULL << 35) /* Set no_new_privs on child. */
 #define CLONE_PIDFD_AUTOKILL	(1ULL << 36) /* Kill child when clone pidfd closes. */
 #define CLONE_EMPTY_MNTNS	(1ULL << 37) /* Create an empty mount namespace. */
+#define CLONE_INTO_ROOTNS	(1ULL << 38) /* Clone into a specific root namespace. */
 
 /*
  * cloning flags intersect with CSIGNAL so can be used with unshare and clone3
@@ -94,6 +95,8 @@
  *                kernel's limit of nested PID namespaces.
  * @cgroup:       If CLONE_INTO_CGROUP is specified set this to
  *                a file descriptor for the cgroup.
+ * @rootns:       If CLONE_INTO_ROOTNS is specified set this to
+ *                a file descriptor for the root namespace.
  *
  * The structure is versioned by size and thus extensible.
  * New struct members must go at the end of the struct and
@@ -111,12 +114,14 @@ struct clone_args {
 	__aligned_u64 set_tid;
 	__aligned_u64 set_tid_size;
 	__aligned_u64 cgroup;
+	__aligned_u64 rootns;
 };
 #endif
 
 #define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */
 #define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */
 #define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */
+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */
 
 /*
  * Scheduling policies
diff --git a/kernel/cred.c b/kernel/cred.c
index d01df40a9a38..48a8852dab4a 100644
--- a/kernel/cred.c
+++ b/kernel/cred.c
@@ -12,13 +12,16 @@
 #include <linux/slab.h>
 #include <linux/sched.h>
 #include <linux/sched/coredump.h>
+#include <linux/sched/exec_state.h>
 #include <linux/key.h>
 #include <linux/keyctl.h>
 #include <linux/init_task.h>
+#include <linux/rootns.h>
 #include <linux/security.h>
 #include <linux/binfmts.h>
 #include <linux/cn_proc.h>
 #include <linux/uidgid.h>
+#include <linux/user_namespace.h>
 
 #if 0
 #define kdebug(FMT, ...)						\
@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)
 	return new;
 }
 
+static bool cred_cap_issubset(const struct cred *set,
+			      const struct cred *subset);
+
 /*
  * Copy credentials for the new process created by fork()
  *
@@ -260,7 +266,8 @@ struct cred *prepare_exec_creds(void)
  * The new process gets the current process's subjective credentials as its
  * objective and subjective credentials
  */
-int copy_creds(struct task_struct *p, u64 clone_flags)
+int copy_creds(struct task_struct *p, u64 clone_flags,
+	       struct rootns *rootns)
 {
 	struct cred *new;
 	int ret;
@@ -287,6 +294,29 @@ int copy_creds(struct task_struct *p, u64 clone_flags)
 	if (!new)
 		return -ENOMEM;
 
+	if (rootns) {
+		const struct cred *old = current_cred();
+
+		if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+		    !ns_capable(rootns->user_ns, CAP_SYS_CHROOT)) {
+			ret = -EPERM;
+			goto error_put;
+		}
+		if (new->user_ns != rootns->user_ns) {
+			ret = install_user_ns_cred(new, rootns->user_ns);
+			if (ret < 0)
+				goto error_put;
+		}
+		if (!cred_cap_issubset(old, new) ||
+		    old->user_ns != new->user_ns) {
+			struct task_exec_state *exec_state;
+
+			exec_state = rcu_dereference_protected(p->exec_state, true);
+			if (exec_state != &init_task_exec_state)
+				WRITE_ONCE(exec_state->dumpable, suid_dumpable);
+		}
+	}
+
 	if (clone_flags & CLONE_NEWUSER) {
 		ret = create_user_ns(new);
 		if (ret < 0)
diff --git a/kernel/fork.c b/kernel/fork.c
index 08fc28ad1eed..ac0497ff410c 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -65,6 +65,7 @@
 #include <linux/rcupdate.h>
 #include <linux/ptrace.h>
 #include <linux/mount.h>
+#include <linux/mnt_namespace.h>
 #include <linux/audit.h>
 #include <linux/memcontrol.h>
 #include <linux/ftrace.h>
@@ -1616,7 +1617,7 @@ static int copy_exec_state(u64 clone_flags, struct task_struct *tsk)
 	struct task_exec_state *exec_state;
 
 	/* CLONE_VM siblings refcount-share the parent's exec_state. */
-	if (clone_flags & CLONE_VM) {
+	if ((clone_flags & (CLONE_VM | CLONE_INTO_ROOTNS)) == CLONE_VM) {
 		exec_state = rcu_dereference_protected(current->exec_state, true);
 		refcount_inc(&exec_state->count);
 		rcu_assign_pointer(tsk->exec_state, exec_state);
@@ -1632,8 +1633,30 @@ enum copy_fs_flags_t {
 	COPY_FS_IDLE	= (1 << 1),
 };
 
+#ifdef CONFIG_ROOTNS
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+	return args->rootns;
+}
+
+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)
+{
+	return args->rootns_bootstrapping;
+}
+#else
+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)
+{
+	return NULL;
+}
+
+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)
+{
+	return false;
+}
+#endif
+
 static int copy_fs(u64 clone_flags, struct task_struct *tsk,
-		   enum copy_fs_flags_t flags)
+		   enum copy_fs_flags_t flags, struct rootns *rootns)
 {
 	struct fs_struct *fs;
 
@@ -1649,7 +1672,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 		if (current->nsproxy->mnt_ns != &init_mnt_ns)
 			return -EINVAL;
 		fs = userspace_init_fs;
-	} else if (flags & COPY_FS_IDLE) {
+	} else if (flags & COPY_FS_IDLE || rootns) {
 		fs = &init_fs;
 	} else {
 		fs = current->fs;
@@ -1671,6 +1694,21 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,
 	tsk->real_fs = tsk->fs = copy_fs_struct(fs);
 	if (!tsk->fs)
 		return -ENOMEM;
+	if (rootns) {
+		struct path root __free(path_put) = {};
+		int err;
+
+		err = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
+		if (err) {
+			free_fs_struct(tsk->fs);
+			tsk->real_fs = NULL;
+			tsk->fs = NULL;
+			return err;
+		}
+		tsk->fs->umask = READ_ONCE(current->fs->umask);
+		set_fs_root(tsk->fs, &root);
+		set_fs_pwd(tsk->fs, &root);
+	}
 	return 0;
 }
 
@@ -2186,7 +2224,7 @@ __latent_entropy struct task_struct *copy_process(
 #ifdef CONFIG_PROVE_LOCKING
 	DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
 #endif
-	retval = copy_creds(p, clone_flags);
+	retval = copy_creds(p, clone_flags, clone_args_rootns(args));
 	if (retval < 0)
 		goto bad_fork_free;
 
@@ -2317,7 +2355,8 @@ __latent_entropy struct task_struct *copy_process(
 		goto bad_fork_cleanup_semundo;
 	retval = copy_fs(clone_flags, p,
 			 (args->umh ? COPY_FS_UMH : 0) |
-			 (args->idle ? COPY_FS_IDLE : 0));
+			 (args->idle ? COPY_FS_IDLE : 0),
+			 clone_args_rootns(args));
 	if (retval)
 		goto bad_fork_cleanup_semundo;
 	retval = copy_sighand(clone_flags, p);
@@ -2329,7 +2368,7 @@ __latent_entropy struct task_struct *copy_process(
 	retval = copy_mm(clone_flags, p);
 	if (retval)
 		goto bad_fork_cleanup_signal;
-	retval = copy_namespaces(clone_flags, p);
+	retval = copy_namespaces(clone_flags, p, clone_args_rootns(args));
 	if (retval)
 		goto bad_fork_cleanup_mm;
 	retval = copy_io(clone_flags, p);
@@ -2510,6 +2549,12 @@ __latent_entropy struct task_struct *copy_process(
 		goto bad_fork_core_free;
 	}
 
+	if (unlikely(clone_args_rootns_bootstrapping(args) &&
+		     !is_child_reaper(pid))) {
+		retval = -EBUSY;
+		goto bad_fork_core_free;
+	}
+
 	/* Let kill terminate clone/fork in the middle */
 	if (fatal_signal_pending(current)) {
 		retval = -EINTR;
@@ -2578,7 +2623,7 @@ __latent_entropy struct task_struct *copy_process(
 		}
 		attach_pid(p, PIDTYPE_PID);
 		if (thread_group_leader(p))
-			copy_rootns(p, pid, NULL);
+			copy_rootns(p, pid, clone_args_rootns(args));
 		nr_threads++;
 	}
 	total_forks++;
@@ -2780,6 +2825,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
 	if (!valid_signal(args->exit_signal))
 		return -EINVAL;
 
+	if (unlikely(clone_flags & CLONE_INTO_ROOTNS)) {
+		int err = rootns_prepare_fork(args);
+
+		if (err)
+			return err;
+	}
+
 	/*
 	 * Determine whether and which event to report to ptracer.  When
 	 * called from kernel_thread or CLONE_UNTRACED is explicitly
@@ -2801,6 +2853,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)
 	p = copy_process(NULL, trace, NUMA_NO_NODE, args);
 	add_latent_entropy();
 
+	if (unlikely(clone_flags & CLONE_INTO_ROOTNS)) {
+		int err = rootns_finish_fork(args, p);
+
+		if (err)
+			return err;
+	}
+
 	if (IS_ERR(p))
 		return PTR_ERR(p);
 
@@ -2958,7 +3017,9 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 		     CLONE_ARGS_SIZE_VER1);
 	BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
 		     CLONE_ARGS_SIZE_VER2);
-	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
+	BUILD_BUG_ON(offsetofend(struct clone_args, rootns) !=
+		     CLONE_ARGS_SIZE_VER3);
+	BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);
 
 	if (unlikely(usize > PAGE_SIZE))
 		return -E2BIG;
@@ -2988,6 +3049,10 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 	    (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
 		return -EINVAL;
 
+	if ((args.flags & CLONE_INTO_ROOTNS) &&
+	    (args.rootns > INT_MAX || usize < CLONE_ARGS_SIZE_VER3))
+		return -EINVAL;
+
 	*kargs = (struct kernel_clone_args){
 		.flags		= args.flags,
 		.pidfd		= u64_to_user_ptr(args.pidfd),
@@ -2999,6 +3064,7 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,
 		.tls		= args.tls,
 		.set_tid_size	= args.set_tid_size,
 		.cgroup		= args.cgroup,
+		.rootns_fd	= args.rootns,
 	};
 
 	if (args.set_tid &&
@@ -3039,13 +3105,19 @@ static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
 	return true;
 }
 
+#define CLONE_INTO_ROOTNS_FLAGS \
+	(CLONE_INTO_ROOTNS | CLONE_VFORK | CLONE_PIDFD | \
+	 CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP | CLONE_AUTOREAP | \
+	 CLONE_NNP | CLONE_PIDFD_AUTOKILL)
+
 static bool clone3_args_valid(struct kernel_clone_args *kargs)
 {
 	/* Verify that no unknown flags are passed along. */
 	if (kargs->flags &
 	    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND |
 	      CLONE_INTO_CGROUP | CLONE_AUTOREAP | CLONE_NNP |
-	      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS))
+	      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS |
+	      CLONE_INTO_ROOTNS))
 		return false;
 
 	/*
@@ -3063,6 +3135,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)
 	    kargs->exit_signal)
 		return false;
 
+	if ((kargs->flags & CLONE_INTO_ROOTNS) &&
+	    (kargs->flags & ~CLONE_INTO_ROOTNS_FLAGS))
+		return false;
+
 	if (!clone3_stack_valid(kargs))
 		return false;
 
diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c
index 8a3c6d4e94e2..78a1e1fb2cfd 100644
--- a/kernel/nsproxy.c
+++ b/kernel/nsproxy.c
@@ -13,6 +13,7 @@
 #include <linux/export.h>
 #include <linux/nsproxy.h>
 #include <linux/ns/ns_common_types.h>
+#include <linux/rootns.h>
 #include <linux/init_task.h>
 #include <linux/mnt_namespace.h>
 #include <linux/utsname.h>
@@ -166,12 +167,18 @@ struct nsproxy *create_new_namespaces(u64 flags,
  * called from clone.  This now handles copy for nsproxy and all
  * namespaces therein.
  */
-int copy_namespaces(u64 flags, struct task_struct *tsk)
+int copy_namespaces(u64 flags, struct task_struct *tsk,
+		    struct rootns *rootns)
 {
 	struct nsproxy *old_ns = tsk->nsproxy;
 	struct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);
 	struct nsproxy *new_ns;
 
+	if (rootns) {
+		get_nsproxy(rootns->ns);
+		tsk->nsproxy = rootns->ns;
+		return 0;
+	}
 	if (likely(!(flags & (CLONE_NS_ALL & ~CLONE_NEWUSER)))) {
 		if ((flags & CLONE_VM) ||
 		    likely(old_ns->time_ns_for_children == old_ns->time_ns)) {
@@ -192,7 +199,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)
 		(CLONE_NEWIPC | CLONE_SYSVSEM))
 		return -EINVAL;
 
-	new_ns = create_new_namespaces(flags, tsk->nsproxy, user_ns, tsk->fs);
+	new_ns = create_new_namespaces(flags, old_ns, user_ns, tsk->fs);
 	if (IS_ERR(new_ns))
 		return  PTR_ERR(new_ns);
 
diff --git a/kernel/rootns.c b/kernel/rootns.c
index ce012a07e982..865689eed69c 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -34,6 +34,7 @@
 #include <uapi/linux/wait.h>
 #include <linux/file.h>
 #include <linux/fs.h>
+#include <linux/fs_struct.h>
 #include <linux/anon_inodes.h>
 #include <linux/rootns.h>
 #include <linux/sched/signal.h>
@@ -423,3 +424,138 @@ SYSCALL_DEFINE1(rootns, unsigned int, flags)
 	return fd;
 }
 
+/**
+ * DOC: CLONE_INTO_ROOTNS
+ *
+ * Passing ``CLONE_INTO_ROOTNS`` in ``struct clone_args.flags`` (with
+ * ``size >= CLONE_ARGS_SIZE_VER3``) spawns the child process into the root
+ * namespace identified by ``struct clone_args.rootns``.
+ *
+ * Once ``"/"`` is mounted in the root namespace's mount namespace, the first
+ * caller transitions the ``rootns`` from ``ROOTNS_INIT`` through
+ * ``ROOTNS_FORKING`` to ``ROOTNS_RUNNING`` as PID 1 of its PID namespace
+ * while concurrent bootstrap callers wait killably. Subsequent callers join
+ * the running PID namespace until teardown begins.
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target
+ * user namespace (and ``CAP_SYS_CHROOT`` in its current user namespace when
+ * chrooted) and run in an ancestor active PID namespace. The child inherits
+ * the caller's credentials and switches to the target user namespace.
+ *
+ * ``CLONE_INTO_ROOTNS`` may be combined with the following ``CLONE_*`` flags:
+ *
+ * - ``CLONE_VFORK``
+ * - ``CLONE_PIDFD``
+ * - ``CLONE_PIDFD_AUTOKILL``
+ * - ``CLONE_AUTOREAP``
+ * - ``CLONE_CLEAR_SIGHAND``
+ * - ``CLONE_INTO_CGROUP``
+ * - ``CLONE_NNP``
+ *
+ * Returns ``-EBADF`` if ``rootns`` is not an open file descriptor, ``-EINVAL``
+ * for unsupported flags, invalid argument size, or non-``rootns`` file
+ * descriptors, ``-ENOENT`` before ``"/"`` is installed, ``-EXDEV`` if the
+ * caller's active PID namespace is not an ancestor, ``-EPERM`` without
+ * required capabilities, ``-EBUSY`` if the PID
+ * namespace already has an external init process, and ``-ESRCH`` once teardown
+ * has started.
+ */
+int rootns_prepare_fork(struct kernel_clone_args *args)
+{
+	struct file *file __free(fput) = fget(args->rootns_fd);
+	struct path root __free(path_put) = {};
+	struct pid_namespace *pid_ns;
+	bool bootstrapping = false;
+	struct rootns *rootns;
+	int ret;
+
+	if (!file)
+		return -EBADF;
+	if (!is_rootns_file(file))
+		return -EINVAL;
+
+	rootns = file->private_data;
+	if (!ns_capable(rootns->user_ns, CAP_SYS_ADMIN) ||
+	    !ns_capable(rootns->user_ns, CAP_SYS_CHROOT))
+		return -EPERM;
+	if (current_chrooted() && !ns_capable(current_user_ns(), CAP_SYS_CHROOT))
+		return -EPERM;
+
+	pid_ns = rootns->ns->pid_ns_for_children;
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+
+	ret = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
+	if (ret)
+		return ret;
+
+	for (;;) {
+		bool wait = false;
+
+		scoped_guard(spinlock, &rootns->lock) {
+			switch (rootns->state) {
+			case ROOTNS_INIT:
+				if (READ_ONCE(pid_ns->child_reaper))
+					return -EBUSY;
+				if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+					return -ESRCH;
+				WRITE_ONCE(rootns->state, ROOTNS_FORKING);
+				bootstrapping = true;
+				break;
+			case ROOTNS_FORKING:
+				wait = true;
+				break;
+			case ROOTNS_RUNNING:
+				if (!(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+					return -ESRCH;
+				break;
+			case ROOTNS_DEAD:
+				return -ESRCH;
+			}
+		}
+		if (!wait)
+			break;
+
+		ret = wait_event_killable(rootns->waitq,
+					  READ_ONCE(rootns->state) != ROOTNS_FORKING);
+		if (ret)
+			return ret;
+	}
+
+	args->rootns_file = no_free_ptr(file);
+	args->rootns = rootns;
+	args->rootns_bootstrapping = bootstrapping;
+	return 0;
+}
+
+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)
+{
+	struct file *file __free(fput) = args->rootns_file;
+	struct rootns *rootns = args->rootns;
+	struct pid_namespace *pid_ns = rootns->ns->pid_ns_for_children;
+	int ret;
+
+	args->rootns_file = NULL;
+	args->rootns = NULL;
+	if (!IS_ERR(p)) {
+		if (current->nsproxy->time_ns != rootns->ns->time_ns)
+			timens_commit(p, rootns->ns->time_ns);
+		return 0;
+	}
+
+	ret = PTR_ERR(p);
+	if (args->rootns_bootstrapping) {
+		scoped_guard(spinlock, &rootns->lock) {
+			if (rootns->state == ROOTNS_FORKING)
+				WRITE_ONCE(rootns->state, ROOTNS_INIT);
+		}
+		wake_up_all(&rootns->waitq);
+		if (ret == -EINVAL && !args->set_tid_size)
+			ret = -EBUSY;
+	}
+	if ((ret == -ENOMEM || ret == -EBUSY) &&
+	    !(READ_ONCE(pid_ns->pid_allocated) & PIDNS_ADDING))
+		return -ESRCH;
+
+	return ret;
+}
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbace..3bea86647191 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -1372,6 +1372,13 @@ static void userns_put(struct ns_common *ns)
 	put_user_ns(to_user_ns(ns));
 }
 
+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)
+{
+	put_user_ns(cred->user_ns);
+	set_cred_user_ns(cred, get_user_ns(user_ns));
+	return set_cred_ucounts(cred);
+}
+
 static int userns_install(struct nsset *nsset, struct ns_common *ns)
 {
 	struct user_namespace *user_ns = to_user_ns(ns);
@@ -1397,10 +1404,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)
 	if (!cred)
 		return -EINVAL;
 
-	put_user_ns(cred->user_ns);
-	set_cred_user_ns(cred, get_user_ns(user_ns));
-
-	if (set_cred_ucounts(cred) < 0)
+	if (install_user_ns_cred(cred, user_ns) < 0)
 		return -EINVAL;
 
 	return 0;
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 08/14] fs: Support FSCONFIG_SET_ROOTNS in fsconfig()
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (6 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3() Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 09/14] fs: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
                   ` (5 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

fsopen() and fsmount() gate on CAP_SYS_ADMIN in the caller's current
mount namespace and initialize filesystem contexts from current's user,
network, PID, and IPC namespaces, preventing an unprivileged external
manager from creating superblocks and detached mounts for an unentered
root namespace.

Add FSCONFIG_SET_ROOTNS so callers holding CAP_SYS_ADMIN in the target
rootns user namespace can bind a newly opened fs_context to that rootns
once before offering parameters. Allow unprivileged callers to open
FS_USERNS_MOUNT contexts in FS_CONTEXT_AWAITING_NS without module
autoloading until FSCONFIG_SET_ROOTNS authorizes and initializes the
context, keep devpts pty_reserve restricted to host mounts, enforce
mount_too_revealing() for unprivileged callers in init_mnt_ns, and wire
->set_rootns() for proc and mqueue.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/devpts/inode.c          |   2 +
 fs/filesystems.c           |  15 ++++
 fs/fs_context.c            |  21 ++++--
 fs/fsopen.c                | 139 ++++++++++++++++++++++++++++++++++---
 fs/internal.h              |   6 ++
 fs/namespace.c             |  38 ++++++++--
 fs/proc/root.c             |  18 +++++
 include/linux/fs_context.h |   6 ++
 include/uapi/linux/mount.h |   1 +
 ipc/mqueue.c               |  13 ++++
 10 files changed, 241 insertions(+), 18 deletions(-)

diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb..db5a5c7a07db 100644
--- a/fs/devpts/inode.c
+++ b/fs/devpts/inode.c
@@ -434,6 +434,8 @@ static int devpts_init_fs_context(struct fs_context *fc)
 	fsi->mount_opts.max     = NR_UNIX98_PTY_MAX;
 
 	if (fc->purpose == FS_CONTEXT_FOR_MOUNT &&
+	    !fc->rootns_bound &&
+	    fc->user_ns == &init_user_ns &&
 	    current->nsproxy->mnt_ns == init_task.nsproxy->mnt_ns)
 		fsi->mount_opts.reserve = true;
 
diff --git a/fs/filesystems.c b/fs/filesystems.c
index 3083d904df9b..9429844bf6bf 100644
--- a/fs/filesystems.c
+++ b/fs/filesystems.c
@@ -18,6 +18,7 @@
 #include <linux/uaccess.h>
 #include <linux/fs_parser.h>
 #include <linux/rculist.h>
+#include "internal.h"
 
 /*
  * Read-mostly filesystem drivers list.
@@ -390,6 +391,20 @@ static struct file_system_type *__get_fs_type(const char *name, int len)
 	return fs;
 }
 
+struct file_system_type *get_fs_type_noload(const char *name)
+{
+	struct file_system_type *fs;
+	const char *dot = strchr(name, '.');
+	int len = dot ? dot - name : strlen(name);
+
+	fs = __get_fs_type(name, len);
+	if (dot && fs && !(fs->fs_flags & FS_HAS_SUBTYPE)) {
+		put_filesystem(fs);
+		fs = NULL;
+	}
+	return fs;
+}
+
 struct file_system_type *get_fs_type(const char *name)
 {
 	struct file_system_type *fs;
diff --git a/fs/fs_context.c b/fs/fs_context.c
index a50584df97be..cd004750b99c 100644
--- a/fs/fs_context.c
+++ b/fs/fs_context.c
@@ -249,6 +249,7 @@ EXPORT_SYMBOL(generic_parse_monolithic);
  * @sb_flags: Filesystem/superblock flags (SB_*)
  * @sb_flags_mask: Applicable members of @sb_flags
  * @purpose: The purpose that this configuration shall be used for.
+ * @init: Whether to initialise the filesystem context immediately.
  *
  * Open a filesystem and create a mount context.  The mount context is
  * initialised with the supplied flags and, if a submount/automount from
@@ -259,7 +260,8 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,
 				      struct dentry *reference,
 				      unsigned int sb_flags,
 				      unsigned int sb_flags_mask,
-				      enum fs_context_purpose purpose)
+				      enum fs_context_purpose purpose,
+				      bool init)
 {
 	struct fs_context *fc;
 	int ret = -ENOMEM;
@@ -292,6 +294,9 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,
 		break;
 	}
 
+	if (!init)
+		return fc;
+
 	ret = fc->fs_type->init_fs_context(fc);
 	if (ret < 0)
 		goto err_fc;
@@ -307,10 +312,16 @@ struct fs_context *fs_context_for_mount(struct file_system_type *fs_type,
 					unsigned int sb_flags)
 {
 	return alloc_fs_context(fs_type, NULL, sb_flags, 0,
-					FS_CONTEXT_FOR_MOUNT);
+				FS_CONTEXT_FOR_MOUNT, true);
 }
 EXPORT_SYMBOL(fs_context_for_mount);
 
+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type)
+{
+	return alloc_fs_context(fs_type, NULL, 0, 0,
+				FS_CONTEXT_FOR_MOUNT, false);
+}
+
 struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,
 					unsigned int sb_flags,
 					unsigned int sb_flags_mask)
@@ -320,7 +331,8 @@ struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,
 		return ERR_PTR(-EINVAL);
 
 	return alloc_fs_context(dentry->d_sb->s_type, dentry, sb_flags,
-				sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE);
+				sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE,
+				true);
 }
 
 /**
@@ -337,7 +349,8 @@ struct fs_context *fs_context_for_submount(struct file_system_type *type,
 	struct fs_context *fc;
 	int ret;
 
-	fc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT);
+	fc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT,
+			      true);
 	if (IS_ERR(fc))
 		return fc;
 
diff --git a/fs/fsopen.c b/fs/fsopen.c
index 70024870fefa..85b31af68a4d 100644
--- a/fs/fsopen.c
+++ b/fs/fsopen.c
@@ -13,9 +13,14 @@
 #include <linux/security.h>
 #include <linux/anon_inodes.h>
 #include <linux/namei.h>
+#include <linux/capability.h>
+#include <linux/nsproxy.h>
+#include <linux/rootns.h>
+#include <linux/user_namespace.h>
 #include <linux/file.h>
 #include <uapi/linux/mount.h>
 #include <linux/audit.h>
+#include <net/net_namespace.h>
 #include "internal.h"
 #include "mount.h"
 
@@ -41,6 +46,94 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,
 	return p;
 }
 
+/**
+ * DOC: FSCONFIG_SET_ROOTNS
+ *
+ * ``fsconfig(fsfd, FSCONFIG_SET_ROOTNS, NULL, NULL, rootnsfd)`` binds a newly
+ * opened filesystem context to ``rootnsfd`` once before any parameters are
+ * supplied (subsequent calls fail with ``-EBUSY``).
+ *
+ * The caller must hold ``CAP_SYS_ADMIN`` in the target ``rootns`` user
+ * namespace, allowing unprivileged callers to configure ``FS_USERNS_MOUNT``
+ * filesystems without entering the user namespace first.
+ *
+ * The context is initialized against the ``rootns`` network namespace,
+ * ``fc->user_ns`` is delegated to the ``rootns`` user namespace for
+ * ``FS_USERNS_MOUNT`` and ``FS_USERNS_DELEGATABLE`` filesystems when the
+ * mounter ``fsuid``/``fsgid`` map into it or the caller lacks
+ * ``CAP_SYS_ADMIN`` in its own user namespace, and ``proc`` and ``mqueue``
+ * contexts bind to the target ``rootns`` PID and IPC namespaces.
+ */
+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)
+{
+	struct user_namespace *user_ns;
+	struct rootns *c;
+	int ret;
+
+	if (!is_rootns_file(param->file))
+		return -EINVAL;
+
+	c = param->file->private_data;
+	user_ns = c->user_ns;
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	if (fc->need_free && fc->ops && fc->ops->free)
+		fc->ops->free(fc);
+	fc->need_free = false;
+	fc->fs_private = NULL;
+	fc->s_fs_info = NULL;
+	fc->ops = NULL;
+	fc->sb_flags = 0;
+	fc->global = false;
+	security_free_mnt_opts(&fc->security);
+
+	if (fc->log.prefix && strcmp(fc->fs_type->name, fc->log.prefix)) {
+		struct file_system_type *orig;
+
+		orig = get_fs_type_noload(fc->log.prefix);
+		if (!orig) {
+			fc->phase = FS_CONTEXT_FAILED;
+			return -ENODEV;
+		}
+		put_filesystem(fc->fs_type);
+		fc->fs_type = orig;
+	}
+
+	put_net(fc->net_ns);
+	fc->net_ns = get_net(c->ns->net_ns);
+	put_user_ns(fc->user_ns);
+	if ((fc->fs_type->fs_flags & (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE)) &&
+	    ((kuid_has_mapping(user_ns, fc->cred->fsuid) &&
+	      kgid_has_mapping(user_ns, fc->cred->fsgid)) ||
+	     !ns_capable(fc->cred->user_ns, CAP_SYS_ADMIN)))
+		fc->user_ns = get_user_ns(user_ns);
+	else
+		fc->user_ns = get_user_ns(fc->cred->user_ns);
+
+	fc->rootns_bound = true;
+	fc->rootns_mnt_id = c->ns->mnt_ns->ns.ns_id;
+
+	ret = fc->fs_type->init_fs_context(fc);
+	if (ret < 0) {
+		fc->rootns_bound = false;
+		fc->phase = FS_CONTEXT_FAILED;
+		return ret;
+	}
+	fc->need_free = true;
+
+	if (fc->ops->set_rootns) {
+		ret = fc->ops->set_rootns(fc, c);
+		if (ret < 0) {
+			fc->rootns_bound = false;
+			fc->phase = FS_CONTEXT_FAILED;
+			return ret;
+		}
+	}
+	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	return 0;
+}
+
 /*
  * Allow the user to read back any error, warning or informational messages.
  * Only one message is returned for each read(2) call.
@@ -123,9 +216,11 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 	struct file_system_type *fs_type;
 	struct fs_context *fc;
 	const char *fs_name;
+	bool priv;
 	int ret;
 
-	if (!may_mount())
+	priv = may_mount();
+	if (!priv && !IS_ENABLED(CONFIG_ROOTNS))
 		return -EPERM;
 
 	if (flags & ~FSOPEN_CLOEXEC)
@@ -137,17 +232,23 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)
 
 	audit_log_fsopen(fs_name);
 
-	fs_type = get_fs_type(fs_name);
+	fs_type = priv ? get_fs_type(fs_name) : get_fs_type_noload(fs_name);
 	kfree(fs_name);
 	if (!fs_type)
-		return -ENODEV;
+		return priv ? -ENODEV : -EPERM;
 
-	fc = fs_context_for_mount(fs_type, 0);
+	if (!priv && !(fs_type->fs_flags & FS_USERNS_MOUNT)) {
+		put_filesystem(fs_type);
+		return -EPERM;
+	}
+
+	fc = priv ? fs_context_for_mount(fs_type, 0) :
+		    fs_context_for_unpriv_mount(fs_type);
 	put_filesystem(fs_type);
 	if (IS_ERR(fc))
 		return PTR_ERR(fc);
 
-	fc->phase = FS_CONTEXT_CREATE_PARAMS;
+	fc->phase = priv ? FS_CONTEXT_CREATE_NS : FS_CONTEXT_AWAITING_NS;
 
 	ret = fscontext_alloc_log(fc);
 	if (ret < 0)
@@ -222,7 +323,8 @@ static int vfs_cmd_create(struct fs_context *fc, bool exclusive)
 	struct super_block *sb;
 	int ret;
 
-	if (fc->phase != FS_CONTEXT_CREATE_PARAMS)
+	if (fc->phase != FS_CONTEXT_CREATE_NS &&
+	    fc->phase != FS_CONTEXT_CREATE_PARAMS)
 		return -EBUSY;
 
 	if (!mount_capable(fc))
@@ -291,6 +393,8 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,
 	ret = finish_clean_context(fc);
 	if (ret)
 		return ret;
+	if (fc->phase == FS_CONTEXT_AWAITING_NS && cmd != FSCONFIG_SET_ROOTNS)
+		return -EPERM;
 	switch (cmd) {
 	case FSCONFIG_CMD_CREATE:
 		return vfs_cmd_create(fc, false);
@@ -298,9 +402,17 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,
 		return vfs_cmd_create(fc, true);
 	case FSCONFIG_CMD_RECONFIGURE:
 		return vfs_cmd_reconfigure(fc);
+	case FSCONFIG_SET_ROOTNS:
+		if (fc->phase != FS_CONTEXT_AWAITING_NS &&
+		    fc->phase != FS_CONTEXT_CREATE_NS)
+			return -EBUSY;
+		return fsconfig_set_rootns(fc, param);
+
 	default:
-		if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
-		    fc->phase != FS_CONTEXT_RECONF_PARAMS)
+		if (fc->phase == FS_CONTEXT_CREATE_NS)
+			fc->phase = FS_CONTEXT_CREATE_PARAMS;
+		else if (fc->phase != FS_CONTEXT_CREATE_PARAMS &&
+			 fc->phase != FS_CONTEXT_RECONF_PARAMS)
 			return -EBUSY;
 
 		return vfs_parse_fs_param(fc, param);
@@ -390,6 +502,10 @@ SYSCALL_DEFINE5(fsconfig,
 		if (!_key || _value || aux < 0)
 			return -EINVAL;
 		break;
+	case FSCONFIG_SET_ROOTNS:
+		if (_key || _value || aux < 0)
+			return -EINVAL;
+		break;
 	case FSCONFIG_CMD_CREATE:
 	case FSCONFIG_CMD_CREATE_EXCL:
 	case FSCONFIG_CMD_RECONFIGURE:
@@ -457,6 +573,12 @@ SYSCALL_DEFINE5(fsconfig,
 			goto out_key;
 		param.dirfd = aux;
 		break;
+	case FSCONFIG_SET_ROOTNS:
+		ret = -EBADF;
+		param.file = fget(aux);
+		if (!param.file)
+			goto out_key;
+		break;
 	default:
 		break;
 	}
@@ -482,6 +604,7 @@ SYSCALL_DEFINE5(fsconfig,
 			putname(param.name);
 		break;
 	case FSCONFIG_SET_FD:
+	case FSCONFIG_SET_ROOTNS:
 		if (param.file)
 			fput(param.file);
 		break;
diff --git a/fs/internal.h b/fs/internal.h
index 3f2fbac40f8e..d6815bf6ea9b 100644
--- a/fs/internal.h
+++ b/fs/internal.h
@@ -40,12 +40,18 @@ int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,
  */
 extern void __init chrdev_init(void);
 
+/*
+ * filesystems.c
+ */
+struct file_system_type *get_fs_type_noload(const char *name);
+
 /*
  * fs_context.c
  */
 extern int parse_monolithic_mount_data(struct fs_context *, void *);
 extern void vfs_clean_context(struct fs_context *fc);
 extern int finish_clean_context(struct fs_context *fc);
+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type);
 
 /*
  * namei.c
diff --git a/fs/namespace.c b/fs/namespace.c
index 781380945d78..dfe0ee9ecdcd 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -4614,16 +4614,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	struct vfsmount *new_mnt;
 	struct mount *mnt;
 	unsigned int mnt_flags = 0;
+	bool priv;
 	long ret;
 
 	if ((flags & ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)
 		return -EINVAL;
 
+	priv = may_mount();
 	if ((flags & FSMOUNT_NAMESPACE) &&
 	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
 		return -EPERM;
 
-	if (!(flags & FSMOUNT_NAMESPACE) && !may_mount())
+	if (!(flags & FSMOUNT_NAMESPACE) && !IS_ENABLED(CONFIG_ROOTNS) &&
+	    !priv)
 		return -EPERM;
 
 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
@@ -4658,6 +4661,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 	if (ret)
 		return ret;
 
+	if (fc->rootns_bound) {
+		if (flags & FSMOUNT_NAMESPACE)
+			return -EINVAL;
+		if (!ns_capable(fc->user_ns, CAP_SYS_ADMIN))
+			return -EPERM;
+	} else if (!(flags & FSMOUNT_NAMESPACE) && !priv) {
+		return -EPERM;
+	}
+
 	/* There must be a valid superblock or we can't mount it */
 	ret = -EINVAL;
 	if (!fc->root)
@@ -4699,9 +4711,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 		return FD_ADD((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
 			      open_new_namespace(&new_path, MOUNT_COPY_NEW));
 
-	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
+	ns = alloc_mnt_ns(priv ? current->nsproxy->mnt_ns->user_ns :
+			  fc->user_ns, true);
 	if (IS_ERR(ns))
 		return PTR_ERR(ns);
+	if (!priv)
+		ns->seq_origin = fc->rootns_mnt_id;
 	mnt = real_mount(new_path.mnt);
 	ns->root = mnt;
 	ns->nr_mounts = 1;
@@ -6582,6 +6597,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 				const struct super_block *sb,
 				int *new_mnt_flags)
 {
+	bool foreign_ns = !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN);
 	int new_flags = *new_mnt_flags;
 	struct mount *mnt;
 
@@ -6611,6 +6627,11 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 		/* Don't miss readonly hidden in the superblock flags */
 		if (sb_rdonly(mnt->mnt.mnt_sb))
 			mnt_flags |= MNT_LOCK_READONLY;
+		if (foreign_ns) {
+			if (mnt_flags & MNT_READONLY)
+				mnt_flags |= MNT_LOCK_READONLY;
+			mnt_flags |= MNT_LOCK_ATIME;
+		}
 
 		/* Verify the mount flags are equal to or more permissive
 		 * than the proposed new mount.
@@ -6629,7 +6650,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,
 		list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
 			struct inode *inode = child->mnt_mountpoint->d_inode;
 			/* Only worry about locked mounts */
-			if (!(child->mnt.mnt_flags & MNT_LOCKED))
+			if (!foreign_ns && !(child->mnt.mnt_flags & MNT_LOCKED))
 				continue;
 			/* Is the directory permanently empty? */
 			if (!is_empty_dir_inode(inode))
@@ -6650,13 +6671,18 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags
 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
 	unsigned long s_iflags;
 
-	if (ns->user_ns == &init_user_ns)
-		return false;
-
 	/* Can this filesystem be too revealing? */
 	if (!(sb->s_type->fs_flags & FS_USERNS_MOUNT_RESTRICTED))
 		return false;
 
+	if (ns->user_ns == &init_user_ns &&
+	    ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN))
+		return false;
+
+	if (!ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN) &&
+	    current_chrooted())
+		return true;
+
 	s_iflags = sb->s_iflags;
 	if ((s_iflags & required_iflags) != required_iflags) {
 		WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
diff --git a/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a..323296b03089 100644
--- a/fs/proc/root.c
+++ b/fs/proc/root.c
@@ -15,6 +15,8 @@
 #include <linux/sched/stat.h>
 #include <linux/module.h>
 #include <linux/bitops.h>
+#include <linux/nsproxy.h>
+#include <linux/rootns.h>
 #include <linux/user_namespace.h>
 #include <linux/fs_context.h>
 #include <linux/mount.h>
@@ -323,6 +325,21 @@ static int proc_get_tree(struct fs_context *fc)
 	return get_tree_nodev(fc, proc_fill_super);
 }
 
+static int proc_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct proc_fs_context *ctx = fc->fs_private;
+	struct pid_namespace *target = rootns->ns->pid_ns_for_children;
+
+	if (!pidns_is_ancestor(target, task_active_pid_ns(current)))
+		return invalfc(fc, "cannot set pidns to non-descendant pidns");
+
+	put_pid_ns(ctx->pid_ns);
+	ctx->pid_ns = get_pid_ns(target);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->pid_ns->user_ns);
+	return 0;
+}
+
 static void proc_fs_context_free(struct fs_context *fc)
 {
 	struct proc_fs_context *ctx = fc->fs_private;
@@ -334,6 +351,7 @@ static void proc_fs_context_free(struct fs_context *fc)
 static const struct fs_context_operations proc_fs_context_ops = {
 	.free		= proc_fs_context_free,
 	.parse_param	= proc_parse_param,
+	.set_rootns	= proc_set_rootns,
 	.get_tree	= proc_get_tree,
 	.reconfigure	= proc_reconfigure,
 };
diff --git a/include/linux/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5..42648bec5cfa 100644
--- a/include/linux/fs_context.h
+++ b/include/linux/fs_context.h
@@ -21,6 +21,7 @@ struct file_system_type;
 struct mnt_namespace;
 struct net;
 struct pid_namespace;
+struct rootns;
 struct super_block;
 struct user_namespace;
 struct vfsmount;
@@ -36,6 +37,8 @@ enum fs_context_purpose {
  * Userspace usage phase for fsopen/fspick.
  */
 enum fs_context_phase {
+	FS_CONTEXT_AWAITING_NS,		/* Unprivileged context awaiting target ns */
+	FS_CONTEXT_CREATE_NS,		/* Set namespaces for sb creation */
 	FS_CONTEXT_CREATE_PARAMS,	/* Loading params for sb creation */
 	FS_CONTEXT_CREATING,		/* A superblock is being created */
 	FS_CONTEXT_AWAITING_MOUNT,	/* Superblock created, awaiting fsmount() */
@@ -101,6 +104,7 @@ struct fs_context {
 	const char		*source;	/* The source name (eg. dev path) */
 	void			*security;	/* LSM options */
 	void			*s_fs_info;	/* Proposed s_fs_info */
+	u64			rootns_mnt_id;	/* Target rootns mnt_ns ID */
 	unsigned int		sb_flags;	/* Proposed superblock flags (SB_*) */
 	unsigned int		sb_flags_mask;	/* Superblock flags that were changed */
 	unsigned int		s_iflags;	/* OR'd with sb->s_iflags */
@@ -110,6 +114,7 @@ struct fs_context {
 	bool			global:1;	/* Goes into &init_user_ns */
 	bool			oldapi:1;	/* Coming from mount(2) */
 	bool			exclusive:1;    /* create new superblock, reject existing one */
+	bool			rootns_bound:1;	/* Bound via FSCONFIG_SET_ROOTNS */
 };
 
 struct fs_context_operations {
@@ -117,6 +122,7 @@ struct fs_context_operations {
 	int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
 	int (*parse_param)(struct fs_context *fc, struct fs_parameter *param);
 	int (*parse_monolithic)(struct fs_context *fc, void *data);
+	int (*set_rootns)(struct fs_context *fc, struct rootns *rootns);
 	int (*get_tree)(struct fs_context *fc);
 	int (*reconfigure)(struct fs_context *fc);
 };
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index ac865edac517..cb55cfcfc92e 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -105,6 +105,7 @@ enum fsconfig_command {
 	FSCONFIG_CMD_CREATE	= 6,	/* Create new or reuse existing superblock */
 	FSCONFIG_CMD_RECONFIGURE = 7,	/* Invoke superblock reconfiguration */
 	FSCONFIG_CMD_CREATE_EXCL = 8,	/* Create new superblock, fail if reusing existing superblock */
+	FSCONFIG_SET_ROOTNS	= 9,	/* Set a rootns, supplied by fd */
 };
 
 /*
diff --git a/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c44..f94e9b566bd0 100644
--- a/ipc/mqueue.c
+++ b/ipc/mqueue.c
@@ -32,6 +32,7 @@
 #include <linux/mutex.h>
 #include <linux/nsproxy.h>
 #include <linux/pid.h>
+#include <linux/rootns.h>
 #include <linux/ipc_namespace.h>
 #include <linux/user_namespace.h>
 #include <linux/slab.h>
@@ -400,6 +401,17 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 	return ERR_PTR(ret);
 }
 
+static int mqueue_set_rootns(struct fs_context *fc, struct rootns *rootns)
+{
+	struct mqueue_fs_context *ctx = fc->fs_private;
+
+	put_ipc_ns(ctx->ipc_ns);
+	ctx->ipc_ns = get_ipc_ns(rootns->ns->ipc_ns);
+	put_user_ns(fc->user_ns);
+	fc->user_ns = get_user_ns(ctx->ipc_ns->user_ns);
+	return 0;
+}
+
 static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)
 {
 	struct inode *inode;
@@ -1613,6 +1625,7 @@ static const struct super_operations mqueue_super_ops = {
 
 static const struct fs_context_operations mqueue_fs_context_ops = {
 	.free		= mqueue_fs_context_free,
+	.set_rootns	= mqueue_set_rootns,
 	.get_tree	= mqueue_get_tree,
 };
 
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 09/14] fs: Support MOVE_MOUNT_T_MNTNS in move_mount()
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (7 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 08/14] fs: Support FSCONFIG_SET_ROOTNS in fsconfig() Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 10/14] security: Add rootns LSM hooks Jarkko Sakkinen
                   ` (4 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

move_mount() currently resolves target paths only against the caller's
filesystem view or anonymous mount fds, preventing an external manager
from populating an empty mount namespace or hot-mounting into an
existing container's mount namespace without entering it first.

Add MOVE_MOUNT_T_MNTNS to attach detached anonymous mount trees into a
target mount namespace nsfs file descriptor. Installing "/" attaches the
initial root mount onto the nullfs root of an empty mount namespace at
most once, while relative target paths resolve with LOOKUP_IN_ROOT
beneath the live mount namespace root and reject root-mount aliases
under namespace_lock().

Check CAP_SYS_ADMIN in the target mount namespace's owning user
namespace instead of caller may_mount(), check nsfs mount loops against
the destination mount namespace, and lock moved mount trees inside
attach_recursive_mnt() when crossing user namespace boundaries.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 fs/namespace.c             | 218 +++++++++++++++++++++++++++++++------
 include/uapi/linux/mount.h |   3 +-
 2 files changed, 184 insertions(+), 37 deletions(-)

diff --git a/fs/namespace.c b/fs/namespace.c
index dfe0ee9ecdcd..36ed48c3f646 100644
--- a/fs/namespace.c
+++ b/fs/namespace.c
@@ -2202,7 +2202,8 @@ struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)
 	return to_mnt_ns(get_proc_ns(dentry->d_inode));
 }
 
-static bool mnt_ns_loop(struct dentry *dentry)
+static bool mnt_ns_loop_target(struct dentry *dentry,
+			       struct mnt_namespace *target_mnt_ns)
 {
 	/* Could bind mounting the mount namespace inode cause a
 	 * mount namespace loop?
@@ -2212,7 +2213,12 @@ static bool mnt_ns_loop(struct dentry *dentry)
 	if (!mnt_ns)
 		return false;
 
-	return current->nsproxy->mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+	return target_mnt_ns->ns.ns_id >= mnt_ns->ns.ns_id;
+}
+
+static bool mnt_ns_loop(struct dentry *dentry)
+{
+	return mnt_ns_loop_target(dentry, current->nsproxy->mnt_ns);
 }
 
 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
@@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struct dentry *dentry)
  *
  * locks: mount_locked_reader || namespace_shared && pinned(subtree)
  */
-static bool check_for_nsfs_mounts(struct mount *subtree)
+static bool check_for_nsfs_mounts(struct mount *subtree,
+				  struct mnt_namespace *target_mnt_ns)
 {
 	for (struct mount *p = subtree; p; p = next_mnt(p, subtree))
-		if (mnt_ns_loop(p->mnt.mnt_root))
+		if (mnt_ns_loop_target(p->mnt.mnt_root, target_mnt_ns))
 			return false;
 	return true;
 }
@@ -2464,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)
 		if (!anon_ns_root(old_mnt))
 			return ERR_PTR(-EINVAL);
 
-		if (!check_for_nsfs_mounts(old_mnt))
+		if (!check_for_nsfs_mounts(old_mnt, current->nsproxy->mnt_ns))
 			return ERR_PTR(-EINVAL);
 	}
 
@@ -2564,12 +2571,15 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
 enum mnt_tree_flags_t {
 	MNT_TREE_BENEATH = BIT(0),
 	MNT_TREE_PROPAGATION = BIT(1),
+	MNT_TREE_MNTNS = BIT(2),
+	MNT_TREE_MNTNS_INIT = BIT(3),
 };
 
 /**
  * attach_recursive_mnt - attach a source mount tree
  * @source_mnt: mount tree to be attached
  * @dest:	the context for mounting at the place where the tree should go
+ * @move_mntns:	whether @source_mnt is attached via MOVE_MOUNT_T_MNTNS
  *
  *  NOTE: in the table below explains the semantics when a source mount
  *  of a given type is attached to a destination mount of a given type.
@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {
  *         Otherwise a negative error code is returned.
  */
 static int attach_recursive_mnt(struct mount *source_mnt,
-				const struct pinned_mountpoint *dest)
+				const struct pinned_mountpoint *dest,
+				bool move_mntns)
 {
 	struct mount *dest_mnt = dest->parent;
 	struct mountpoint *dest_mp = dest->mp;
@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	struct user_namespace *user_ns = ns->user_ns;
 	struct pinned_mountpoint root = {};
 	struct mountpoint *shorter = NULL;
+	struct mnt_namespace *src_ns;
 	struct mount *child, *p;
 	struct mount *top;
 	struct hlist_node *n;
@@ -2662,6 +2674,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 		user_ns = current->nsproxy->mnt_ns->user_ns;
 	else
 		user_ns = ns->user_ns;
+	src_ns = moving ? NULL : source_mnt->mnt_ns;
 
 	/*
 	 * Preallocate a mountpoint in case the new mounts need to be
@@ -2694,6 +2707,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,
 	if (err)
 		goto out_cleanup_ids;
 
+	if (move_mntns && src_ns && src_ns->user_ns != user_ns) {
+		lock_mnt_tree(source_mnt);
+		if (list_empty(&source_mnt->mnt_expire))
+			source_mnt->mnt.mnt_flags |= MNT_LOCKED;
+	}
+
 	if (IS_MNT_SHARED(dest_mnt)) {
 		for (p = source_mnt; p; p = next_mnt(p, source_mnt))
 			set_mnt_shared(p);
@@ -2937,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)
 	      d_is_dir(mnt->mnt.mnt_root))
 		return -ENOTDIR;
 
-	return attach_recursive_mnt(mnt, mp);
+	return attach_recursive_mnt(mnt, mp, false);
 }
 
 static int may_change_propagation(const struct mount *m)
@@ -3131,7 +3150,7 @@ static int do_loopback(const struct path *path, const char *old_name,
 		return PTR_ERR(mnt);
 
 	/* the copy may carry mount namespace files from below the source */
-	if (recurse && !check_for_nsfs_mounts(mnt))
+	if (recurse && !check_for_nsfs_mounts(mnt, current->nsproxy->mnt_ns))
 		err = -EINVAL;
 	else
 		err = graft_tree(mnt, &mp);
@@ -3776,9 +3795,11 @@ static inline bool may_use_mount(struct mount *mnt)
 
 static int do_move_mount(const struct path *old_path,
 			 const struct path *new_path,
-			 enum mnt_tree_flags_t flags)
+			 enum mnt_tree_flags_t flags,
+			 struct mnt_namespace *target_mnt_ns)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	struct mnt_namespace *dest_mnt_ns;
 	int err;
 	bool beneath = flags & MNT_TREE_BENEATH;
 
@@ -3792,7 +3813,23 @@ static int do_move_mount(const struct path *old_path,
 	if (IS_ERR(mp.parent))
 		return PTR_ERR(mp.parent);
 
-	if (check_mnt(old)) {
+	if (flags & MNT_TREE_MNTNS) {
+		if (!anon_ns_root(old) || old->mnt_ns == mp.parent->mnt_ns ||
+		    mp.parent->mnt_ns != target_mnt_ns)
+			return -EINVAL;
+		if (flags & MNT_TREE_MNTNS_INIT) {
+			if (mp.parent != target_mnt_ns->root)
+				return -EBUSY;
+		} else if (mp.mp->m_dentry == mp.parent->mnt.mnt_root) {
+			const struct mount *m = mp.parent;
+
+			while (m != target_mnt_ns->root && mnt_has_parent(m) &&
+			       m->mnt_mountpoint == m->mnt_parent->mnt.mnt_root)
+				m = m->mnt_parent;
+			if (m == target_mnt_ns->root)
+				return beneath ? -EINVAL : -EBUSY;
+		}
+	} else if (check_mnt(old)) {
 		/* if the source is in our namespace... */
 		/* ... it should be detachable from parent */
 		if (!mnt_has_parent(old) || IS_MNT_LOCKED(old))
@@ -3840,12 +3877,14 @@ static int do_move_mount(const struct path *old_path,
 	 */
 	if (IS_MNT_SHARED(mp.parent) && tree_contains_unbindable(old))
 		return -EINVAL;
-	if (!check_for_nsfs_mounts(old))
+	dest_mnt_ns = is_anon_ns(mp.parent->mnt_ns) ?
+		      current->nsproxy->mnt_ns : mp.parent->mnt_ns;
+	if (!check_for_nsfs_mounts(old, dest_mnt_ns))
 		return -ELOOP;
 	if (mount_is_ancestor(old, mp.parent))
 		return -ELOOP;
 
-	return attach_recursive_mnt(old, &mp);
+	return attach_recursive_mnt(old, &mp, flags & MNT_TREE_MNTNS);
 }
 
 static int do_move_mount_old(const struct path *path, const char *old_name)
@@ -3860,7 +3899,7 @@ static int do_move_mount_old(const struct path *path, const char *old_name)
 	if (err)
 		return err;
 
-	return do_move_mount(&old_path, path, 0);
+	return do_move_mount(&old_path, path, 0, NULL);
 }
 
 /*
@@ -4740,7 +4779,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
 
 static inline int vfs_move_mount(const struct path *from_path,
 				 const struct path *to_path,
-				 enum mnt_tree_flags_t mflags)
+				 enum mnt_tree_flags_t mflags,
+				 struct mnt_namespace *target_mnt_ns)
 {
 	int ret;
 
@@ -4751,7 +4791,123 @@ static inline int vfs_move_mount(const struct path *from_path,
 	if (mflags & MNT_TREE_PROPAGATION)
 		return do_set_group(from_path, to_path);
 
-	return do_move_mount(from_path, to_path, mflags);
+	return do_move_mount(from_path, to_path, mflags, target_mnt_ns);
+}
+
+static int lookup_move_mount_from(int from_dfd,
+				  const char __user *from_pathname,
+				  unsigned int flags, struct path *from_path)
+{
+	unsigned int uflags = 0;
+	unsigned int lflags = 0;
+
+	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
+		uflags = AT_EMPTY_PATH;
+
+	CLASS(filename_maybe_null, from_name)(from_pathname, uflags);
+	if (!from_name && from_dfd >= 0) {
+		CLASS(fd_raw, f_from)(from_dfd);
+		if (fd_empty(f_from))
+			return -EBADF;
+
+		*from_path = fd_file(f_from)->f_path;
+		path_get(from_path);
+		return 0;
+	}
+
+	if (flags & MOVE_MOUNT_F_SYMLINKS)
+		lflags |= LOOKUP_FOLLOW;
+	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
+		lflags |= LOOKUP_AUTOMOUNT;
+	return filename_lookup(from_dfd, from_name, lflags, from_path, NULL);
+}
+
+/**
+ * DOC: MOVE_MOUNT_T_MNTNS
+ *
+ * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target
+ * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:
+ *
+ * 1. ``to_pathname`` of ``"/"`` attaches the initial root mount onto the
+ *    ``nullfs`` root of an empty mount namespace at most once.
+ *
+ * 2. Relative ``to_pathname`` values resolve beneath the live root of the
+ *    target mount namespace.
+ *
+ * Capability is checked against ``CAP_SYS_ADMIN`` in the target mount
+ * namespace's owning user namespace, and source trees crossing user namespace
+ * boundaries are locked with ``MNT_LOCKED`` and locked mount flags.
+ */
+static int move_mount_mntns(int from_dfd, const char __user *from_pathname,
+			    int to_dfd, const char __user *to_pathname,
+			    unsigned int flags, enum mnt_tree_flags_t mflags)
+{
+	struct path from_path __free(path_put) = {};
+	struct path to_path __free(path_put) = {};
+	struct mnt_namespace *target_mnt_ns;
+	unsigned int lflags;
+	struct ns_common *ns;
+	bool is_root;
+	int ret;
+
+	CLASS(filename_maybe_null, to_name)(to_pathname, AT_EMPTY_PATH);
+	if (IS_ERR(to_name))
+		return PTR_ERR(to_name);
+	if (!to_name)
+		return -EINVAL;
+
+	CLASS(fd, f_mntns)(to_dfd);
+	if (fd_empty(f_mntns))
+		return -EBADF;
+	if (!proc_ns_file(fd_file(f_mntns)))
+		return -EINVAL;
+
+	ns = get_proc_ns(file_inode(fd_file(f_mntns)));
+	if (ns->ns_type != CLONE_NEWNS)
+		return -EINVAL;
+
+	target_mnt_ns = to_mnt_ns(ns);
+	if (is_anon_ns(target_mnt_ns))
+		return -EINVAL;
+	if (!ns_capable(target_mnt_ns->user_ns, CAP_SYS_ADMIN))
+		return -EPERM;
+
+	is_root = to_name->name[0] == '/' && to_name->name[1] == '\0';
+	if (is_root) {
+		if (flags & MOVE_MOUNT_BENEATH)
+			return -EINVAL;
+
+		to_path.mnt = mntget(&target_mnt_ns->root->mnt);
+		to_path.dentry = dget(target_mnt_ns->root->mnt.mnt_root);
+		mflags |= MNT_TREE_MNTNS_INIT;
+	} else {
+		struct path mntns_root __free(path_put) = {};
+
+		if (to_name->name[0] == '/')
+			return -EINVAL;
+
+		ret = mnt_ns_get_root(target_mnt_ns, &mntns_root);
+		if (ret)
+			return ret;
+
+		lflags = LOOKUP_IN_ROOT;
+		if (flags & MOVE_MOUNT_T_SYMLINKS)
+			lflags |= LOOKUP_FOLLOW;
+		if (flags & MOVE_MOUNT_T_AUTOMOUNTS)
+			lflags |= LOOKUP_AUTOMOUNT;
+		ret = filename_lookup(AT_FDCWD, to_name, lflags, &to_path,
+				      &mntns_root);
+		if (ret)
+			return ret;
+	}
+
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
+	if (ret)
+		return ret;
+
+	return vfs_move_mount(&from_path, &to_path, mflags | MNT_TREE_MNTNS,
+			      target_mnt_ns);
 }
 
 /*
@@ -4773,7 +4929,7 @@ SYSCALL_DEFINE5(move_mount,
 	enum mnt_tree_flags_t mflags = 0;
 	int ret = 0;
 
-	if (!may_mount())
+	if (!(flags & MOVE_MOUNT_T_MNTNS) && !may_mount())
 		return -EPERM;
 
 	if (flags & ~MOVE_MOUNT__MASK)
@@ -4786,6 +4942,13 @@ SYSCALL_DEFINE5(move_mount,
 	if (flags & MOVE_MOUNT_SET_GROUP)	mflags |= MNT_TREE_PROPAGATION;
 	if (flags & MOVE_MOUNT_BENEATH)		mflags |= MNT_TREE_BENEATH;
 
+	if (unlikely(flags & MOVE_MOUNT_T_MNTNS)) {
+		if (flags & (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))
+			return -EINVAL;
+		return move_mount_mntns(from_dfd, from_pathname,
+					to_dfd, to_pathname, flags, mflags);
+	}
+
 	uflags = 0;
 	if (flags & MOVE_MOUNT_T_EMPTY_PATH)
 		uflags = AT_EMPTY_PATH;
@@ -4809,29 +4972,12 @@ SYSCALL_DEFINE5(move_mount,
 			return ret;
 	}
 
-	uflags = 0;
-	if (flags & MOVE_MOUNT_F_EMPTY_PATH)
-		uflags = AT_EMPTY_PATH;
-
-	CLASS(filename_maybe_null,from_name)(from_pathname, uflags);
-	if (!from_name && from_dfd >= 0) {
-		CLASS(fd_raw, f_from)(from_dfd);
-		if (fd_empty(f_from))
-			return -EBADF;
-
-		return vfs_move_mount(&fd_file(f_from)->f_path, &to_path, mflags);
-	}
-
-	lflags = 0;
-	if (flags & MOVE_MOUNT_F_SYMLINKS)
-		lflags |= LOOKUP_FOLLOW;
-	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)
-		lflags |= LOOKUP_AUTOMOUNT;
-	ret = filename_lookup(from_dfd, from_name, lflags, &from_path, NULL);
+	ret = lookup_move_mount_from(from_dfd, from_pathname, flags,
+				     &from_path);
 	if (ret)
 		return ret;
 
-	return vfs_move_mount(&from_path, &to_path, mflags);
+	return vfs_move_mount(&from_path, &to_path, mflags, NULL);
 }
 
 /*
diff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index cb55cfcfc92e..7fa93de08ceb 100644
--- a/include/uapi/linux/mount.h
+++ b/include/uapi/linux/mount.h
@@ -75,9 +75,10 @@
 #define MOVE_MOUNT_T_SYMLINKS		0x00000010 /* Follow symlinks on to path */
 #define MOVE_MOUNT_T_AUTOMOUNTS		0x00000020 /* Follow automounts on to path */
 #define MOVE_MOUNT_T_EMPTY_PATH		0x00000040 /* Empty to path permitted */
+#define MOVE_MOUNT_T_MNTNS		0x00000080 /* Resolve to_dfd as mntns fd */
 #define MOVE_MOUNT_SET_GROUP		0x00000100 /* Set sharing group instead */
 #define MOVE_MOUNT_BENEATH		0x00000200 /* Mount beneath top mount */
-#define MOVE_MOUNT__MASK		0x00000377
+#define MOVE_MOUNT__MASK		0x000003f7
 
 /*
  * fsopen() flags.
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 10/14] security: Add rootns LSM hooks
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (8 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 09/14] fs: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 11/14] arch: Wire up rootns() system call Jarkko Sakkinen
                   ` (3 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Security modules need visibility into root namespace creation, teardown,
process entry, and container-wide signal delivery so policies and BPF LSM
programs can attach per-rootns security state and mediate operations on
rootns file descriptors.

Add lbs_rootns and rootns->security blob management alongside
security_rootns_alloc(), security_rootns_free(), security_rootns_clone(),
and security_rootns_kill(), and register the new hooks in bpf_lsm.c's
sleepable and untrusted hook sets.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 include/linux/lsm_hook_defs.h |  7 +++
 include/linux/lsm_hooks.h     |  3 ++
 include/linux/rootns.h        |  3 ++
 include/linux/security.h      | 30 ++++++++++++
 kernel/bpf/bpf_lsm.c          | 10 ++++
 kernel/rootns.c               | 44 +++++++++++++-----
 security/lsm_init.c           |  6 +++
 security/security.c           | 86 +++++++++++++++++++++++++++++++++++
 8 files changed, 177 insertions(+), 12 deletions(-)

diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb..2cb90ddedc14 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -480,3 +480,10 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)
 LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)
 LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,
 	 enum lsm_integrity_type type, const void *value, size_t size)
+
+#ifdef CONFIG_ROOTNS
+LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)
+LSM_HOOK(void, LSM_RET_VOID, rootns_free, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_clone, struct rootns *rootns)
+LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)
+#endif /* CONFIG_ROOTNS */
diff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h
index 13621e9e233e..217a59d428b1 100644
--- a/include/linux/lsm_hooks.h
+++ b/include/linux/lsm_hooks.h
@@ -121,6 +121,9 @@ struct lsm_blob_sizes {
 	unsigned int lbs_bpf_map;
 	unsigned int lbs_bpf_prog;
 	unsigned int lbs_bpf_token;
+#ifdef CONFIG_ROOTNS
+	unsigned int lbs_rootns;
+#endif
 };
 
 /*
diff --git a/include/linux/rootns.h b/include/linux/rootns.h
index 802fc76bb66e..795a79584231 100644
--- a/include/linux/rootns.h
+++ b/include/linux/rootns.h
@@ -31,6 +31,9 @@ enum rootns_state {
 struct rootns {
 	refcount_t		usage;
 	int			exit_code;	/* The exit code of 'init' */
+#ifdef CONFIG_SECURITY
+	void			*security;	/* LSM security blob */
+#endif
 	struct user_namespace	*user_ns;	/* Owning user namespace */
 	struct nsproxy		*ns;		/* This rootns's namespaces */
 	struct pid		*init_pid;	/* The 'init' task's TGID (pid ref) */
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab5470..995292f1c92e 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -84,6 +84,7 @@ struct audit_krule;
 struct ns_common;
 struct user_namespace;
 struct timezone;
+struct rootns;
 
 enum lsm_event {
 	LSM_POLICY_CHANGE,
@@ -2469,4 +2470,33 @@ static inline void security_initramfs_populated(void)
 }
 #endif /* CONFIG_SECURITY */
 
+#ifdef CONFIG_ROOTNS
+#ifdef CONFIG_SECURITY
+int security_rootns_alloc(struct rootns *rootns, unsigned int flags);
+void security_rootns_free(struct rootns *rootns);
+int security_rootns_clone(struct rootns *rootns);
+int security_rootns_kill(struct rootns *rootns, int sig);
+#else
+static inline int security_rootns_alloc(struct rootns *rootns,
+					unsigned int flags)
+{
+	return 0;
+}
+
+static inline void security_rootns_free(struct rootns *rootns)
+{
+}
+
+static inline int security_rootns_clone(struct rootns *rootns)
+{
+	return 0;
+}
+
+static inline int security_rootns_kill(struct rootns *rootns, int sig)
+{
+	return 0;
+}
+#endif /* CONFIG_SECURITY */
+#endif /* CONFIG_ROOTNS */
+
 #endif /* ! __LINUX_SECURITY_H */
diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922..bbcf1433fdc2 100644
--- a/kernel/bpf/bpf_lsm.c
+++ b/kernel/bpf/bpf_lsm.c
@@ -16,6 +16,7 @@
 #include <linux/btf_ids.h>
 #include <linux/ima.h>
 #include <linux/bpf-cgroup.h>
+#include <linux/rootns.h>
 
 /* For every LSM hook that allows attachment of BPF programs, declare a nop
  * function where a BPF program can be attached. Notably, we qualify each with
@@ -404,6 +405,11 @@ BTF_ID(func, bpf_lsm_task_setscheduler)
 BTF_ID(func, bpf_lsm_userns_create)
 BTF_ID(func, bpf_lsm_bdev_alloc_security)
 BTF_ID(func, bpf_lsm_bdev_setintegrity)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_clone)
+BTF_ID(func, bpf_lsm_rootns_kill)
+#endif /* CONFIG_ROOTNS */
 BTF_SET_END(sleepable_lsm_hooks)
 
 BTF_SET_START(untrusted_lsm_hooks)
@@ -420,6 +426,10 @@ BTF_ID(func, bpf_lsm_sk_free_security)
 BTF_ID(func, bpf_lsm_task_free)
 BTF_ID(func, bpf_lsm_bdev_alloc_security)
 BTF_ID(func, bpf_lsm_bdev_free_security)
+#ifdef CONFIG_ROOTNS
+BTF_ID(func, bpf_lsm_rootns_alloc)
+BTF_ID(func, bpf_lsm_rootns_free)
+#endif /* CONFIG_ROOTNS */
 BTF_SET_END(untrusted_lsm_hooks)
 
 bool bpf_lsm_is_sleepable_hook(u32 btf_id)
diff --git a/kernel/rootns.c b/kernel/rootns.c
index 865689eed69c..3733a249feca 100644
--- a/kernel/rootns.c
+++ b/kernel/rootns.c
@@ -52,6 +52,7 @@
 #include <linux/user_namespace.h>
 #include <linux/compat.h>
 #include <linux/idr.h>
+#include <linux/security.h>
 #include <uapi/linux/rootns.h>
 
 /*
@@ -63,14 +64,8 @@ struct rootns *get_rootns(struct rootns *c)
 	return c;
 }
 
-/*
- * Drop a reference on a rootns and clear it if it is no longer in use.
- */
-void put_rootns(struct rootns *c)
+static void free_rootns(struct rootns *c)
 {
-	if (!c || !refcount_dec_and_test(&c->usage))
-		return;
-
 	if (c->ns)
 		put_nsproxy(c->ns);
 	if (c->init_pid)
@@ -82,6 +77,18 @@ void put_rootns(struct rootns *c)
 	kfree(c);
 }
 
+/*
+ * Drop a reference on a rootns and clear it if it is no longer in use.
+ */
+void put_rootns(struct rootns *c)
+{
+	if (!c || !refcount_dec_and_test(&c->usage))
+		return;
+
+	security_rootns_free(c);
+	free_rootns(c);
+}
+
 /*
  * Allow the user to poll for the rootns dying.
  */
@@ -163,6 +170,7 @@ static int rootns_kill_members(struct rootns *rootns, int sig)
 	bool any_perm = false;
 	int other_err = 0;
 	struct pid *pid;
+	int ret;
 	int nr;
 
 	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
@@ -170,6 +178,10 @@ static int rootns_kill_members(struct rootns *rootns, int sig)
 	if (READ_ONCE(rootns->state) != ROOTNS_RUNNING)
 		return -ESRCH;
 
+	ret = security_rootns_kill(rootns, sig);
+	if (ret)
+		return ret;
+
 	scoped_guard(rcu) {
 		read_lock(&tasklist_lock);
 		idr_for_each_entry(&pid_ns->idr, pid, nr) {
@@ -365,31 +377,35 @@ static struct rootns *create_rootns(unsigned int flags)
 	user_ns = create_rootns_user_ns();
 	if (IS_ERR(user_ns)) {
 		ret = PTR_ERR(user_ns);
-		goto err_put;
+		goto err_free;
 	}
 	c->user_ns = user_ns;
 	ns_ref_active_get(user_ns);
 
 	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
 		ret = -EPERM;
-		goto err_put;
+		goto err_free;
 	}
 
 	ns = create_new_namespaces(clone_flags, current->nsproxy, user_ns,
 				   NULL);
 	if (IS_ERR(ns)) {
 		ret = PTR_ERR(ns);
-		goto err_put;
+		goto err_free;
 	}
 
 	timens_activate_nsproxy(ns);
 	c->ns = ns;
 	nsproxy_ns_active_get(ns);
 
+	ret = security_rootns_alloc(c, flags);
+	if (ret < 0)
+		goto err_free;
+
 	return c;
 
-err_put:
-	put_rootns(c);
+err_free:
+	free_rootns(c);
 	return ERR_PTR(ret);
 }
 
@@ -485,6 +501,10 @@ int rootns_prepare_fork(struct kernel_clone_args *args)
 	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
 		return -EXDEV;
 
+	ret = security_rootns_clone(rootns);
+	if (ret)
+		return ret;
+
 	ret = mnt_ns_get_root(rootns->ns->mnt_ns, &root);
 	if (ret)
 		return ret;
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46..56b515b20812 100644
--- a/security/lsm_init.c
+++ b/security/lsm_init.c
@@ -316,6 +316,9 @@ static void __init lsm_prepare(struct lsm_info *lsm)
 	lsm_blob_size_update(&blobs->lbs_bpf_map, &blob_sizes.lbs_bpf_map);
 	lsm_blob_size_update(&blobs->lbs_bpf_prog, &blob_sizes.lbs_bpf_prog);
 	lsm_blob_size_update(&blobs->lbs_bpf_token, &blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_ROOTNS
+	lsm_blob_size_update(&blobs->lbs_rootns, &blob_sizes.lbs_rootns);
+#endif
 }
 
 /**
@@ -460,6 +463,9 @@ int __init security_init(void)
 		lsm_pr("blob(bpf_map) size %d\n", blob_sizes.lbs_bpf_map);
 		lsm_pr("blob(bpf_prog) size %d\n", blob_sizes.lbs_bpf_prog);
 		lsm_pr("blob(bpf_token) size %d\n", blob_sizes.lbs_bpf_token);
+#ifdef CONFIG_ROOTNS
+		lsm_pr("blob(rootns) size %d\n", blob_sizes.lbs_rootns);
+#endif
 	}
 
 	if (blob_sizes.lbs_file)
diff --git a/security/security.c b/security/security.c
index 4727b8347fc4..919d4bb63701 100644
--- a/security/security.c
+++ b/security/security.c
@@ -30,6 +30,7 @@
 #include <linux/overflow.h>
 #include <linux/perf_event.h>
 #include <linux/fs.h>
+#include <linux/rootns.h>
 #include <net/flow.h>
 #include <net/sock.h>
 
@@ -395,6 +396,22 @@ static int lsm_ns_alloc(struct ns_common *ns)
 	return lsm_blob_alloc(&ns->ns_security, blob_sizes.lbs_ns, GFP_KERNEL);
 }
 
+#ifdef CONFIG_ROOTNS
+/**
+ * lsm_rootns_alloc - allocate a composite rootns blob
+ * @rootns: the rootns that needs a blob
+ *
+ * Allocate the rootns blob for all the modules
+ *
+ * Return: Returns 0, or -ENOMEM if memory can't be allocated.
+ */
+static int lsm_rootns_alloc(struct rootns *rootns)
+{
+	return lsm_blob_alloc(&rootns->security, blob_sizes.lbs_rootns,
+			      GFP_KERNEL);
+}
+#endif /* CONFIG_ROOTNS */
+
 /**
  * lsm_fill_user_ctx - Fill a user space lsm_ctx structure
  * @uctx: a userspace LSM context to be filled
@@ -5795,3 +5812,72 @@ void security_initramfs_populated(void)
 {
 	call_void_hook(initramfs_populated);
 }
+
+#ifdef CONFIG_ROOTNS
+/**
+ * security_rootns_alloc() - Check creation of a new rootns and init LSM blob
+ * @rootns: the new rootns
+ * @flags: creation flags passed to rootns()
+ *
+ * Check whether a new rootns may be created and initialize its LSM security
+ * blob.
+ *
+ * Return: Returns 0 on success, negative error code on failure.
+ */
+int security_rootns_alloc(struct rootns *rootns, unsigned int flags)
+{
+	int rc;
+
+	rc = lsm_rootns_alloc(rootns);
+	if (unlikely(rc))
+		return rc;
+
+	rc = call_int_hook(rootns_alloc, rootns, flags);
+	if (unlikely(rc))
+		security_rootns_free(rootns);
+
+	return rc;
+}
+
+/**
+ * security_rootns_free() - Release LSM security data from a rootns
+ * @rootns: the rootns being freed
+ *
+ * Release security data attached to @rootns before the structure is freed.
+ */
+void security_rootns_free(struct rootns *rootns)
+{
+	call_void_hook(rootns_free, rootns);
+	kfree(rootns->security);
+	rootns->security = NULL;
+}
+
+/**
+ * security_rootns_clone() - Check permission to spawn a task into a rootns
+ * @rootns: the target rootns
+ *
+ * Check permission before spawning a child process into @rootns via
+ * clone3(CLONE_INTO_ROOTNS).
+ *
+ * Return: Returns 0 if permission is granted, negative error code on failure.
+ */
+int security_rootns_clone(struct rootns *rootns)
+{
+	return call_int_hook(rootns_clone, rootns);
+}
+
+/**
+ * security_rootns_kill() - Check permission to signal a rootns
+ * @rootns: the target rootns
+ * @sig: signal number to deliver (or 0 for permission check)
+ *
+ * Check permission before broadcasting @sig to member thread groups in @rootns
+ * via ioctl(ROOTNS_KILL).
+ *
+ * Return: Returns 0 if permission is granted, negative error code on failure.
+ */
+int security_rootns_kill(struct rootns *rootns, int sig)
+{
+	return call_int_hook(rootns_kill, rootns, sig);
+}
+#endif /* CONFIG_ROOTNS */
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 11/14] arch: Wire up rootns() system call
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (9 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 10/14] security: Add rootns LSM hooks Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 12/14] docs: Document root namespace uAPI Jarkko Sakkinen
                   ` (2 subsequent siblings)
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Now that the core root namespace lifecycle and VFS mount-tree
installation are in place, expose rootns() (473, 583 on Alpha) across
all architecture system call tables and asm-generic unistd.h.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 arch/alpha/kernel/syscalls/syscall.tbl      | 1 +
 arch/arm/tools/syscall.tbl                  | 1 +
 arch/arm64/tools/syscall_32.tbl             | 1 +
 arch/m68k/kernel/syscalls/syscall.tbl       | 1 +
 arch/microblaze/kernel/syscalls/syscall.tbl | 1 +
 arch/mips/kernel/syscalls/syscall_n32.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_n64.tbl   | 1 +
 arch/mips/kernel/syscalls/syscall_o32.tbl   | 1 +
 arch/parisc/kernel/syscalls/syscall.tbl     | 1 +
 arch/powerpc/kernel/syscalls/syscall.tbl    | 1 +
 arch/s390/kernel/syscalls/syscall.tbl       | 1 +
 arch/sh/kernel/syscalls/syscall.tbl         | 1 +
 arch/sparc/kernel/syscalls/syscall.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_32.tbl      | 1 +
 arch/x86/entry/syscalls/syscall_64.tbl      | 1 +
 arch/xtensa/kernel/syscalls/syscall.tbl     | 1 +
 include/uapi/asm-generic/unistd.h           | 6 +++++-
 scripts/syscall.tbl                         | 1 +
 18 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df..ea790cceb67a 100644
--- a/arch/alpha/kernel/syscalls/syscall.tbl
+++ b/arch/alpha/kernel/syscalls/syscall.tbl
@@ -512,3 +512,4 @@
 580	common	listns				sys_listns
 581	common	rseq_slice_yield		sys_rseq_slice_yield
 582	common	fchroot				sys_fchroot
+583	common	rootns				sys_rootns
diff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl
index 55717ed32c27..531b2a2dce72 100644
--- a/arch/arm/tools/syscall.tbl
+++ b/arch/arm/tools/syscall.tbl
@@ -487,3 +487,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl
index df2d1d82fb3c..8ef224c0dd42 100644
--- a/arch/arm64/tools/syscall_32.tbl
+++ b/arch/arm64/tools/syscall_32.tbl
@@ -484,3 +484,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl
index ba7a4d8903d0..77239262dc26 100644
--- a/arch/m68k/kernel/syscalls/syscall.tbl
+++ b/arch/m68k/kernel/syscalls/syscall.tbl
@@ -472,3 +472,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl
index 76d7cbe2a133..df53332ce4a5 100644
--- a/arch/microblaze/kernel/syscalls/syscall.tbl
+++ b/arch/microblaze/kernel/syscalls/syscall.tbl
@@ -478,3 +478,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl
index 9ae88e4eac61..84db40158bf0 100644
--- a/arch/mips/kernel/syscalls/syscall_n32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl
@@ -411,3 +411,4 @@
 470	n32	listns				sys_listns
 471	n32	rseq_slice_yield		sys_rseq_slice_yield
 472	n32	fchroot				sys_fchroot
+473	n32	rootns				sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl
index 83dc93a0712f..9e874a958503 100644
--- a/arch/mips/kernel/syscalls/syscall_n64.tbl
+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl
@@ -387,3 +387,4 @@
 470	n64	listns				sys_listns
 471	n64	rseq_slice_yield		sys_rseq_slice_yield
 472	n64	fchroot				sys_fchroot
+473	n64	rootns				sys_rootns
diff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl
index 9c62429c9b7b..592c2225f4ce 100644
--- a/arch/mips/kernel/syscalls/syscall_o32.tbl
+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl
@@ -460,3 +460,4 @@
 470	o32	listns				sys_listns
 471	o32	rseq_slice_yield		sys_rseq_slice_yield
 472	o32	fchroot				sys_fchroot
+473	o32	rootns				sys_rootns
diff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl
index 88adc4016cce..93f8539bd179 100644
--- a/arch/parisc/kernel/syscalls/syscall.tbl
+++ b/arch/parisc/kernel/syscalls/syscall.tbl
@@ -471,3 +471,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl
index cfbb70039ff0..7e12f74a27c1 100644
--- a/arch/powerpc/kernel/syscalls/syscall.tbl
+++ b/arch/powerpc/kernel/syscalls/syscall.tbl
@@ -563,3 +563,4 @@
 470	common	listns				sys_listns
 471	nospu	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	nospu	rootns				sys_rootns
diff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl
index 1b45e68a217b..ab303fbb86f3 100644
--- a/arch/s390/kernel/syscalls/syscall.tbl
+++ b/arch/s390/kernel/syscalls/syscall.tbl
@@ -399,3 +399,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl
index ace068dff0de..e92778075bcb 100644
--- a/arch/sh/kernel/syscalls/syscall.tbl
+++ b/arch/sh/kernel/syscalls/syscall.tbl
@@ -476,3 +476,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl
index 5b9fe0e8140f..20d6c572d3f1 100644
--- a/arch/sparc/kernel/syscalls/syscall.tbl
+++ b/arch/sparc/kernel/syscalls/syscall.tbl
@@ -518,3 +518,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl
index 2c172ef48dfd..98cb11b717e5 100644
--- a/arch/x86/entry/syscalls/syscall_32.tbl
+++ b/arch/x86/entry/syscalls/syscall_32.tbl
@@ -478,3 +478,4 @@
 470	i386	listns			sys_listns
 471	i386	rseq_slice_yield	sys_rseq_slice_yield
 472	i386	fchroot			sys_fchroot
+473	i386	rootns			sys_rootns
diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl
index d5b6045b0090..674fa2b4b238 100644
--- a/arch/x86/entry/syscalls/syscall_64.tbl
+++ b/arch/x86/entry/syscalls/syscall_64.tbl
@@ -397,6 +397,7 @@
 470	common	listns			sys_listns
 471	common	rseq_slice_yield	sys_rseq_slice_yield
 472	common	fchroot			sys_fchroot
+473	common	rootns			sys_rootns
 
 #
 # Due to a historical design error, certain syscalls are numbered differently
diff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl
index d354bb231796..82b7344a099c 100644
--- a/arch/xtensa/kernel/syscalls/syscall.tbl
+++ b/arch/xtensa/kernel/syscalls/syscall.tbl
@@ -443,3 +443,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736..25902ed39d79 100644
--- a/include/uapi/asm-generic/unistd.h
+++ b/include/uapi/asm-generic/unistd.h
@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)
 #define __NR_fchroot 472
 __SYSCALL(__NR_fchroot, sys_fchroot)
 
+/* kernel/rootns.c */
+#define __NR_rootns 473
+__SYSCALL(__NR_rootns, sys_rootns)
+
 #undef __NR_syscalls
-#define __NR_syscalls 473
+#define __NR_syscalls 474
 
 /*
  * 32 bit systems traditionally used different
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0ab531605120..b6d1b033f49a 100644
--- a/scripts/syscall.tbl
+++ b/scripts/syscall.tbl
@@ -413,3 +413,4 @@
 470	common	listns				sys_listns
 471	common	rseq_slice_yield		sys_rseq_slice_yield
 472	common	fchroot				sys_fchroot
+473	common	rootns				sys_rootns
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 12/14] docs: Document root namespace uAPI
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (10 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 11/14] arch: Wire up rootns() system call Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 13/14] selftests/rootns: Add root namespace test suite Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 14/14] MAINTAINERS: Add entry for ROOT NAMESPACE Jarkko Sakkinen
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Userspace container managers need a clear specification of rootns state
transitions, control ioctls, mount-tree construction, credential rules,
and process creation semantics.

Add Documentation/userspace-api/rootns.rst to include the kernel-doc
sections, ioctl descriptions, and system call reference from
kernel/rootns.c, include/uapi/linux/rootns.h, fs/fsopen.c, and
fs/namespace.c, and register the rootns ioctl magic in ioctl-number.rst.

Co-developed-by: David Howells <dhowells@redhat.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 Documentation/userspace-api/index.rst         |  1 +
 .../userspace-api/ioctl/ioctl-number.rst      |  1 +
 Documentation/userspace-api/rootns.rst        | 56 +++++++++++++++++++
 3 files changed, 58 insertions(+)
 create mode 100644 Documentation/userspace-api/rootns.rst

diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a8..56d0ac4eb087 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -17,6 +17,7 @@ System calls
    :maxdepth: 1
 
    unshare
+   rootns
    futex2
    ebpf/index
    ioctl/index
diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index dbe462040999..d8dc926ea283 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -385,6 +385,7 @@ Code  Seq#    Include File                                             Comments
 0xB8  01-02  uapi/misc/mrvl_cn10k_dpi.h                                Marvell CN10K DPI driver
 0xB8  all    uapi/linux/mshv.h                                         Microsoft Hyper-V /dev/mshv driver
                                                                        <mailto:linux-hyperv@vger.kernel.org>
+0xB9  00-0F  uapi/linux/rootns.h                                       Root namespace uAPI
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:pasha.tatashin@soleen.com>
 0xC0  00-0F  linux/usb/iowarrior.h
diff --git a/Documentation/userspace-api/rootns.rst b/Documentation/userspace-api/rootns.rst
new file mode 100644
index 000000000000..5326fd2eeb21
--- /dev/null
+++ b/Documentation/userspace-api/rootns.rst
@@ -0,0 +1,56 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================
+Root namespace uAPI
+===================
+
+Overview
+========
+
+.. kernel-doc:: kernel/rootns.c
+   :doc: Overview
+
+Flags
+=====
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+   :identifiers: rootns_flags
+
+Ioctls
+======
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+   :doc: ROOTNS_GET_NSFD
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+   :identifiers: rootns_wait_args
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+   :doc: ROOTNS_WAIT
+
+.. kernel-doc:: include/uapi/linux/rootns.h
+   :doc: ROOTNS_KILL
+
+System calls
+============
+
+.. kernel-doc:: kernel/rootns.c
+   :identifiers: sys_rootns
+
+Process creation
+================
+
+.. kernel-doc:: kernel/rootns.c
+   :doc: CLONE_INTO_ROOTNS
+
+Filesystem configuration
+========================
+
+.. kernel-doc:: fs/fsopen.c
+   :doc: FSCONFIG_SET_ROOTNS
+
+Mount tree installation
+=======================
+
+.. kernel-doc:: fs/namespace.c
+   :doc: MOVE_MOUNT_T_MNTNS
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 13/14] selftests/rootns: Add root namespace test suite
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (11 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 12/14] docs: Document root namespace uAPI Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  2026-11-19 22:43 ` [RFC PATCH v4 14/14] MAINTAINERS: Add entry for ROOT NAMESPACE Jarkko Sakkinen
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Verify the root namespace and mount-namespace configuration uAPI and
security invariants across privileged, unprivileged, and edge-case
scenarios.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/rootns/Makefile       |    5 +
 tools/testing/selftests/rootns/config         |   10 +
 .../testing/selftests/rootns/rootns_cells.py  | 1076 +++++++++++++++
 tools/testing/selftests/rootns/rootns_test.py | 1161 +++++++++++++++++
 tools/testing/selftests/rootns/test_smoke.sh  |   11 +
 6 files changed, 2264 insertions(+)
 create mode 100644 tools/testing/selftests/rootns/Makefile
 create mode 100644 tools/testing/selftests/rootns/config
 create mode 100755 tools/testing/selftests/rootns/rootns_cells.py
 create mode 100755 tools/testing/selftests/rootns/rootns_test.py
 create mode 100755 tools/testing/selftests/rootns/test_smoke.sh

diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04..7c44f93e57a4 100644
--- a/tools/testing/selftests/Makefile
+++ b/tools/testing/selftests/Makefile
@@ -117,6 +117,7 @@ TARGETS += rdma
 TARGETS += resctrl
 TARGETS += riscv
 TARGETS += rlimits
+TARGETS += rootns
 TARGETS += rseq
 TARGETS += rtc
 TARGETS += rust
diff --git a/tools/testing/selftests/rootns/Makefile b/tools/testing/selftests/rootns/Makefile
new file mode 100644
index 000000000000..62629d112e12
--- /dev/null
+++ b/tools/testing/selftests/rootns/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../lib.mk
+
+TEST_PROGS := test_smoke.sh
+TEST_PROGS_EXTENDED := rootns_cells.py rootns_test.py
diff --git a/tools/testing/selftests/rootns/config b/tools/testing/selftests/rootns/config
new file mode 100644
index 000000000000..21b1aecc003b
--- /dev/null
+++ b/tools/testing/selftests/rootns/config
@@ -0,0 +1,10 @@
+CONFIG_CGROUPS=y
+CONFIG_IPC_NS=y
+CONFIG_NET_NS=y
+CONFIG_PID_NS=y
+CONFIG_PROC_FS=y
+CONFIG_ROOTNS=y
+CONFIG_TIME_NS=y
+CONFIG_TMPFS=y
+CONFIG_USER_NS=y
+CONFIG_UTS_NS=y
diff --git a/tools/testing/selftests/rootns/rootns_cells.py b/tools/testing/selftests/rootns/rootns_cells.py
new file mode 100755
index 000000000000..b690ed71a521
--- /dev/null
+++ b/tools/testing/selftests/rootns/rootns_cells.py
@@ -0,0 +1,1076 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+from __future__ import annotations
+
+import argparse
+from collections.abc import Callable, Mapping, Sequence
+import ctypes
+from dataclasses import asdict, dataclass, field
+import errno
+import json
+import os
+import platform
+import selectors
+import signal
+import socket
+import sys
+from types import TracebackType
+from typing import Any, Final, NoReturn
+
+ROOTNS_KILL_ON_CLOSE: Final[int] = 0x00000001
+ROOTNS_CLOSE_ON_EXEC: Final[int] = 0x00000002
+ROOTNS_ALL_FLAGS: Final[int] = 0x00000003
+ROOTNS_IOCTL_MAGIC: Final[int] = 0xB9
+
+CLONE_NEWTIME: Final[int] = 0x00000080
+CLONE_VM: Final[int] = 0x00000100
+CLONE_FS: Final[int] = 0x00000200
+CLONE_FILES: Final[int] = 0x00000400
+CLONE_SIGHAND: Final[int] = 0x00000800
+CLONE_PIDFD: Final[int] = 0x00001000
+CLONE_VFORK: Final[int] = 0x00004000
+CLONE_PARENT: Final[int] = 0x00008000
+CLONE_THREAD: Final[int] = 0x00010000
+CLONE_NEWNS: Final[int] = 0x00020000
+CLONE_SYSVSEM: Final[int] = 0x00040000
+CLONE_NEWCGROUP: Final[int] = 0x02000000
+CLONE_NEWUTS: Final[int] = 0x04000000
+CLONE_NEWIPC: Final[int] = 0x08000000
+CLONE_NEWUSER: Final[int] = 0x10000000
+CLONE_NEWPID: Final[int] = 0x20000000
+CLONE_NEWNET: Final[int] = 0x40000000
+
+CLONE_CLEAR_SIGHAND: Final[int] = 1 << 32
+CLONE_INTO_CGROUP: Final[int] = 1 << 33
+CLONE_AUTOREAP: Final[int] = 1 << 34
+CLONE_NNP: Final[int] = 1 << 35
+CLONE_PIDFD_AUTOKILL: Final[int] = 1 << 36
+CLONE_EMPTY_MNTNS: Final[int] = 1 << 37
+CLONE_INTO_ROOTNS: Final[int] = 1 << 38
+
+CLONE_ARGS_SIZE_VER2: Final[int] = 88
+CLONE_ARGS_SIZE_VER3: Final[int] = 96
+
+AT_FDCWD: Final[int] = -100
+AT_EMPTY_PATH: Final[int] = 0x1000
+AT_RECURSIVE: Final[int] = 0x8000
+MNT_DETACH: Final[int] = 2
+MS_REC: Final[int] = 0x4000
+MS_PRIVATE: Final[int] = 1 << 18
+
+OPEN_TREE_CLONE: Final[int] = 1 << 0
+OPEN_TREE_CLOEXEC: Final[int] = os.O_CLOEXEC
+
+MOVE_MOUNT_F_EMPTY_PATH: Final[int] = 0x00000004
+MOVE_MOUNT_T_EMPTY_PATH: Final[int] = 0x00000040
+MOVE_MOUNT_T_MNTNS: Final[int] = 0x00000080
+MOVE_MOUNT_SET_GROUP: Final[int] = 0x00000100
+MOVE_MOUNT_BENEATH: Final[int] = 0x00000200
+
+FSOPEN_CLOEXEC: Final[int] = 0x00000001
+FSMOUNT_CLOEXEC: Final[int] = 0x00000001
+
+FSCONFIG_SET_FLAG: Final[int] = 0
+FSCONFIG_SET_STRING: Final[int] = 1
+FSCONFIG_CMD_CREATE: Final[int] = 6
+FSCONFIG_SET_ROOTNS: Final[int] = 9
+
+MOUNT_ATTR_RDONLY: Final[int] = 0x00000001
+MOUNT_ATTR_NOSUID: Final[int] = 0x00000002
+MOUNT_ATTR_NODEV: Final[int] = 0x00000004
+
+RESOLVE_IN_ROOT: Final[int] = 0x10
+
+PR_GET_DUMPABLE: Final[int] = 3
+PR_SET_DUMPABLE: Final[int] = 4
+PR_GET_NO_NEW_PRIVS: Final[int] = 39
+
+NSIO: Final[int] = 0xB7
+
+HOST_RUNTIME_ENTRIES: Final[tuple[str, ...]] = (
+    "usr",
+    "bin",
+    "sbin",
+    "lib",
+    "lib32",
+    "lib64",
+    "libx32",
+    "etc",
+    "opt",
+    "nix",
+)
+
+_WIDE_IOC_ARCHS: Final[tuple[str, ...]] = (
+    "ppc",
+    "ppc64",
+    "ppc64le",
+    "powerpc",
+    "sparc",
+    "sparc64",
+    "alpha",
+)
+
+
+def _is_wide_ioc_arch() -> bool:
+    mach = platform.machine().lower()
+    return mach in _WIDE_IOC_ARCHS or mach.startswith("mips")
+
+
+def _ioc(direction: int, magic: int, nr: int, size: int) -> int:
+    sizebits = 13 if _is_wide_ioc_arch() else 14
+    typeshift = 8
+    sizeshift = 16
+    dirshift = sizeshift + sizebits
+    return (
+        (direction << dirshift)
+        | (magic << typeshift)
+        | nr
+        | (size << sizeshift)
+    )
+
+
+def _io(magic: int, nr: int) -> int:
+    return _ioc(0, magic, nr, 0)
+
+
+def _iowr(magic: int, nr: int, size: int) -> int:
+    rw = 6 if _is_wide_ioc_arch() else 3
+    return _ioc(rw, magic, nr, size)
+
+
+class RootnsWaitArgs(ctypes.Structure):
+    flags: int
+    status: int
+    _fields_ = [
+        ("flags", ctypes.c_uint32),
+        ("status", ctypes.c_int32),
+    ]
+
+
+class CloneArgs(ctypes.Structure):
+    flags: int
+    pidfd: int
+    child_tid: int
+    parent_tid: int
+    exit_signal: int
+    stack: int
+    stack_size: int
+    tls: int
+    set_tid: int
+    set_tid_size: int
+    cgroup: int
+    rootns: int
+    _fields_ = [
+        ("flags", ctypes.c_uint64),
+        ("pidfd", ctypes.c_uint64),
+        ("child_tid", ctypes.c_uint64),
+        ("parent_tid", ctypes.c_uint64),
+        ("exit_signal", ctypes.c_uint64),
+        ("stack", ctypes.c_uint64),
+        ("stack_size", ctypes.c_uint64),
+        ("tls", ctypes.c_uint64),
+        ("set_tid", ctypes.c_uint64),
+        ("set_tid_size", ctypes.c_uint64),
+        ("cgroup", ctypes.c_uint64),
+        ("rootns", ctypes.c_uint64),
+    ]
+
+
+class OpenHow(ctypes.Structure):
+    flags: int
+    mode: int
+    resolve: int
+    _fields_ = [
+        ("flags", ctypes.c_uint64),
+        ("mode", ctypes.c_uint64),
+        ("resolve", ctypes.c_uint64),
+    ]
+
+
+ROOTNS_GET_NSFD: Final[int] = _io(ROOTNS_IOCTL_MAGIC, 0x01)
+ROOTNS_WAIT: Final[int] = _iowr(
+    ROOTNS_IOCTL_MAGIC, 0x02, ctypes.sizeof(RootnsWaitArgs)
+)
+ROOTNS_KILL: Final[int] = _io(ROOTNS_IOCTL_MAGIC, 0x03)
+
+NS_GET_USERNS: Final[int] = _io(NSIO, 0x01)
+NS_GET_PARENT: Final[int] = _io(NSIO, 0x02)
+NS_GET_NSTYPE: Final[int] = _io(NSIO, 0x03)
+
+
+def _syscall_numbers() -> dict[str, int]:
+    mach = platform.machine().lower()
+    if mach == "alpha":
+        base = 110
+    elif mach.startswith("mips"):
+        base = 5000 if ctypes.sizeof(ctypes.c_void_p) == 8 else 4000
+    else:
+        base = 0
+
+    nums: dict[str, int] = {
+        "open_tree": base + 428,
+        "move_mount": base + 429,
+        "fsopen": base + 430,
+        "fsconfig": base + 431,
+        "fsmount": base + 432,
+        "pidfd_open": base + 434,
+        "clone3": base + 435,
+        "openat2": base + 437,
+        "rootns": base + 473,
+    }
+    legacy: dict[str, dict[str, int]] = {
+        "x86_64": {"pivot_root": 155, "umount2": 166, "execveat": 322},
+        "i386": {"pivot_root": 217, "umount2": 52, "execveat": 358},
+        "i686": {"pivot_root": 217, "umount2": 52, "execveat": 358},
+        "aarch64": {"pivot_root": 41, "umount2": 39, "execveat": 281},
+        "riscv64": {"pivot_root": 41, "umount2": 39, "execveat": 281},
+        "loongarch64": {"pivot_root": 41, "umount2": 39, "execveat": 281},
+        "s390x": {"pivot_root": 217, "umount2": 52, "execveat": 354},
+        "ppc64le": {"pivot_root": 203, "umount2": 52, "execveat": 362},
+        "ppc64": {"pivot_root": 203, "umount2": 52, "execveat": 362},
+        "armv7l": {"pivot_root": 218, "umount2": 52, "execveat": 387},
+    }
+    nums.update(legacy.get(mach, legacy["x86_64"]))
+    return nums
+
+
+NR: Final[dict[str, int]] = _syscall_numbers()
+LIBC: Final[ctypes.CDLL] = ctypes.CDLL(None, use_errno=True)
+LIBC.syscall.restype = ctypes.c_long
+
+
+@dataclass(frozen=True)
+class WaitResult:
+    pid: int
+    status: int = 0
+
+    @property
+    def exit_code(self) -> int | None:
+        if self.pid <= 0:
+            return None
+        return os.waitstatus_to_exitcode(self.status)
+
+
+@dataclass(frozen=True)
+class CellInfo:
+    name: str
+    state: str
+    init_pid: int | None = None
+    exit_code: int | None = None
+
+
+@dataclass(frozen=True)
+class SpawnInfo:
+    pid: int
+    state: str
+
+
+def _os_err() -> NoReturn:
+    err = ctypes.get_errno()
+    raise OSError(err, os.strerror(err))
+
+
+def _cstr(val: str | bytes) -> bytes:
+    if isinstance(val, bytes):
+        return val
+    return os.fsencode(val)
+
+
+def syscall(nr: int, *args: Any) -> int:
+    ret: int = LIBC.syscall(ctypes.c_long(nr), *args)
+    if ret < 0:
+        _os_err()
+    return int(ret)
+
+
+def raw_ioctl(fd: int, cmd: int, arg: int = 0) -> int:
+    ret: int = LIBC.ioctl(
+        ctypes.c_int(fd), ctypes.c_ulong(cmd), ctypes.c_ulong(arg)
+    )
+    if ret < 0:
+        _os_err()
+    return int(ret)
+
+
+def rootns(
+    flags: int = ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC,
+) -> int:
+    return syscall(NR["rootns"], ctypes.c_uint(flags))
+
+
+def rootns_get_nsfd(cfd: int, nstype: int) -> int:
+    return raw_ioctl(cfd, ROOTNS_GET_NSFD, nstype)
+
+
+def rootns_wait(cfd: int, flags: int = 0) -> WaitResult:
+    args = RootnsWaitArgs(flags=flags, status=0)
+    pid = raw_ioctl(cfd, ROOTNS_WAIT, ctypes.addressof(args))
+    return WaitResult(pid=pid, status=int(args.status))
+
+
+def rootns_kill(cfd: int, sig: int) -> None:
+    mask = (1 << (ctypes.sizeof(ctypes.c_ulong) * 8)) - 1
+    raw_ioctl(cfd, ROOTNS_KILL, sig & mask)
+
+
+def fsopen(fsname: str | bytes, flags: int = FSOPEN_CLOEXEC) -> int:
+    return syscall(
+        NR["fsopen"], ctypes.c_char_p(_cstr(fsname)), ctypes.c_uint(flags)
+    )
+
+
+def fsconfig(
+    fsfd: int,
+    cmd: int,
+    key: str | bytes | None = None,
+    value: str | bytes | None = None,
+    aux: int = 0,
+) -> None:
+    k_ptr = (
+        ctypes.c_char_p(_cstr(key)) if key is not None else ctypes.c_void_p(0)
+    )
+    v_ptr = (
+        ctypes.c_char_p(_cstr(value))
+        if value is not None
+        else ctypes.c_void_p(0)
+    )
+    syscall(
+        NR["fsconfig"],
+        ctypes.c_int(fsfd),
+        ctypes.c_uint(cmd),
+        k_ptr,
+        v_ptr,
+        ctypes.c_int(aux),
+    )
+
+
+def fsmount(
+    fsfd: int, flags: int = FSMOUNT_CLOEXEC, attr_flags: int = 0
+) -> int:
+    return syscall(
+        NR["fsmount"],
+        ctypes.c_int(fsfd),
+        ctypes.c_uint(flags),
+        ctypes.c_uint(attr_flags),
+    )
+
+
+def open_tree(dfd: int, path: str | bytes, flags: int) -> int:
+    return syscall(
+        NR["open_tree"],
+        ctypes.c_int(dfd),
+        ctypes.c_char_p(_cstr(path)),
+        ctypes.c_uint(flags),
+    )
+
+
+def move_mount(
+    from_dfd: int,
+    from_path: str | bytes,
+    to_dfd: int,
+    to_path: str | bytes,
+    flags: int,
+) -> None:
+    syscall(
+        NR["move_mount"],
+        ctypes.c_int(from_dfd),
+        ctypes.c_char_p(_cstr(from_path)),
+        ctypes.c_int(to_dfd),
+        ctypes.c_char_p(_cstr(to_path)),
+        ctypes.c_uint(flags),
+    )
+
+
+def openat2(
+    dfd: int,
+    path: str | bytes,
+    flags: int,
+    mode: int = 0,
+    resolve: int = 0,
+) -> int:
+    how = OpenHow(flags=flags, mode=mode, resolve=resolve)
+    return syscall(
+        NR["openat2"],
+        ctypes.c_int(dfd),
+        ctypes.c_char_p(_cstr(path)),
+        ctypes.byref(how),
+        ctypes.c_size_t(ctypes.sizeof(how)),
+    )
+
+
+def execveat(
+    dfd: int,
+    path: str | bytes,
+    argv: Sequence[str],
+    envp: Mapping[str, str] | Sequence[str] | None = None,
+    flags: int = 0,
+) -> NoReturn:
+    c_argv = (ctypes.c_char_p * (len(argv) + 1))(
+        *[_cstr(a) for a in argv], None
+    )
+    if envp is None:
+        env_items = [f"{k}={v}" for k, v in os.environ.items()]
+    elif isinstance(envp, Mapping):
+        env_items = [f"{k}={v}" for k, v in envp.items()]
+    else:
+        env_items = list(envp)
+    c_envp = (ctypes.c_char_p * (len(env_items) + 1))(
+        *[_cstr(e) for e in env_items], None
+    )
+    syscall(
+        NR["execveat"],
+        ctypes.c_int(dfd),
+        ctypes.c_char_p(_cstr(path)),
+        c_argv,
+        c_envp,
+        ctypes.c_int(flags),
+    )
+    _os_err()
+
+
+def pidfd_open(pid: int, flags: int = 0) -> int:
+    return syscall(NR["pidfd_open"], ctypes.c_int(pid), ctypes.c_uint(flags))
+
+
+def pivot_root(new_root: str | bytes, put_old: str | bytes) -> None:
+    syscall(
+        NR["pivot_root"],
+        ctypes.c_char_p(_cstr(new_root)),
+        ctypes.c_char_p(_cstr(put_old)),
+    )
+
+
+def umount2(target: str | bytes, flags: int = 0) -> None:
+    syscall(NR["umount2"], ctypes.c_char_p(_cstr(target)), ctypes.c_int(flags))
+
+
+def make_mount_private(target: str | bytes = "/") -> None:
+    ret: int = LIBC.mount(
+        ctypes.c_char_p(b"none"),
+        ctypes.c_char_p(_cstr(target)),
+        ctypes.c_void_p(0),
+        ctypes.c_ulong(MS_REC | MS_PRIVATE),
+        ctypes.c_void_p(0),
+    )
+    if ret < 0:
+        _os_err()
+
+
+def setns(fd: int, nstype: int = 0) -> None:
+    ret: int = LIBC.setns(ctypes.c_int(fd), ctypes.c_int(nstype))
+    if ret < 0:
+        _os_err()
+
+
+def unshare(flags: int) -> None:
+    ret: int = LIBC.unshare(ctypes.c_int(flags))
+    if ret < 0:
+        _os_err()
+
+
+def setgroups_empty() -> None:
+    ret: int = LIBC.setgroups(ctypes.c_size_t(0), ctypes.c_void_p(0))
+    if ret < 0:
+        _os_err()
+
+
+def prctl(
+    option: int,
+    arg2: int = 0,
+    arg3: int = 0,
+    arg4: int = 0,
+    arg5: int = 0,
+) -> int:
+    ret: int = LIBC.prctl(
+        ctypes.c_int(option),
+        ctypes.c_ulong(arg2),
+        ctypes.c_ulong(arg3),
+        ctypes.c_ulong(arg4),
+        ctypes.c_ulong(arg5),
+    )
+    if ret < 0:
+        _os_err()
+    return int(ret)
+
+
+def clone3_raw(args: CloneArgs, size: int | None = None) -> int:
+    actual_size = ctypes.sizeof(args) if size is None else size
+    sys.stdout.flush()
+    sys.stderr.flush()
+    return syscall(
+        NR["clone3"], ctypes.byref(args), ctypes.c_size_t(actual_size)
+    )
+
+
+def clone_into_rootns(
+    cfd: int,
+    extra_flags: int = 0,
+    exit_signal: int = int(signal.SIGCHLD),
+) -> tuple[int, int]:
+    pidfd_cell = ctypes.c_int(-1)
+    args = CloneArgs()
+    args.flags = CLONE_INTO_ROOTNS | extra_flags
+    args.exit_signal = exit_signal
+    args.rootns = cfd & 0xFFFFFFFFFFFFFFFF
+    if extra_flags & CLONE_PIDFD:
+        args.pidfd = ctypes.addressof(pidfd_cell)
+    pid = clone3_raw(args)
+    return pid, int(pidfd_cell.value)
+
+
+def run_in_rootns(
+    cfd: int,
+    fn: Callable[[], int | None],
+    extra_flags: int = 0,
+) -> int:
+    pid, _ = clone_into_rootns(cfd, extra_flags=extra_flags)
+    if pid == 0:
+        try:
+            os.close(cfd)
+            rc = fn()
+            os._exit(0 if rc is None else int(rc))
+        except BaseException:
+            os._exit(126)
+    return pid
+
+
+def make_rootns_mount(
+    cfd: int,
+    fstype: str,
+    attr_flags: int = 0,
+    options: Mapping[str, str | None] | None = None,
+) -> int:
+    fsfd = fsopen(fstype, FSOPEN_CLOEXEC)
+    try:
+        fsconfig(fsfd, FSCONFIG_SET_ROOTNS, aux=cfd)
+        if options:
+            for k, v in options.items():
+                if v is None:
+                    fsconfig(fsfd, FSCONFIG_SET_FLAG, key=k)
+                else:
+                    fsconfig(fsfd, FSCONFIG_SET_STRING, key=k, value=str(v))
+        fsconfig(fsfd, FSCONFIG_CMD_CREATE)
+        return fsmount(fsfd, FSMOUNT_CLOEXEC, attr_flags)
+    finally:
+        os.close(fsfd)
+
+
+@dataclass
+class Cell:
+    name: str
+    flags: int = ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC
+    cfd: int = field(init=False, default=-1)
+    mntns_fd: int = field(init=False, default=-1)
+    root_dfd: int = field(init=False, default=-1)
+    init_pid: int | None = field(init=False, default=None)
+    exit_status: int | None = field(init=False, default=None)
+
+    def __post_init__(self) -> None:
+        self.cfd = rootns(self.flags)
+        self.mntns_fd = rootns_get_nsfd(self.cfd, CLONE_NEWNS)
+
+    def __enter__(self) -> Cell:
+        return self
+
+    def __exit__(
+        self,
+        exc_type: type[BaseException] | None,
+        exc: BaseException | None,
+        tb: TracebackType | None,
+    ) -> None:
+        self.close()
+
+    def setup_rootfs(
+        self,
+        dirs: Sequence[str] = ("proc", "tmp", "mnt"),
+        mount_procfs: bool = True,
+        host_runtime: bool = False,
+    ) -> None:
+        rootfd = make_rootns_mount(self.cfd, "tmpfs")
+        bind_dirs: list[str] = []
+        try:
+            for d in dirs:
+                os.mkdir(d, 0o755, dir_fd=rootfd)
+            if host_runtime:
+                for entry in HOST_RUNTIME_ENTRIES:
+                    host_path = f"/{entry}"
+                    if os.path.islink(host_path):
+                        os.symlink(
+                            os.readlink(host_path), entry, dir_fd=rootfd
+                        )
+                    elif os.path.isdir(host_path):
+                        os.mkdir(entry, 0o755, dir_fd=rootfd)
+                        bind_dirs.append(entry)
+            move_mount(
+                rootfd,
+                "",
+                self.mntns_fd,
+                "/",
+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,
+            )
+            self.root_dfd = rootfd
+            rootfd = -1
+        finally:
+            if rootfd >= 0:
+                os.close(rootfd)
+        for entry in bind_dirs:
+            self.bind_mount(f"/{entry}", entry)
+        if mount_procfs and "proc" in dirs:
+            self.mount_fs("proc", "proc")
+
+    def mount_fs(
+        self,
+        fstype: str,
+        target: str,
+        attr_flags: int = 0,
+        options: Mapping[str, str | None] | None = None,
+    ) -> None:
+        mfd = make_rootns_mount(
+            self.cfd, fstype, attr_flags=attr_flags, options=options
+        )
+        try:
+            move_mount(
+                mfd,
+                "",
+                self.mntns_fd,
+                target.lstrip("/"),
+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,
+            )
+        finally:
+            os.close(mfd)
+
+    def bind_mount(self, host_src: str, target: str) -> None:
+        mfd = open_tree(
+            AT_FDCWD,
+            host_src,
+            OPEN_TREE_CLONE | AT_RECURSIVE | OPEN_TREE_CLOEXEC,
+        )
+        try:
+            move_mount(
+                mfd,
+                "",
+                self.mntns_fd,
+                target.lstrip("/"),
+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,
+            )
+        finally:
+            os.close(mfd)
+
+    def spawn(
+        self,
+        argv: Sequence[str],
+        env: Mapping[str, str] | None = None,
+        resolve_in_root: bool = True,
+    ) -> int:
+        bin_fd = -1
+        if resolve_in_root and self.root_dfd >= 0:
+            bin_fd = openat2(
+                self.root_dfd,
+                argv[0],
+                os.O_RDONLY | os.O_CLOEXEC,
+                resolve=RESOLVE_IN_ROOT,
+            )
+        try:
+            pid, _ = clone_into_rootns(
+                self.cfd, extra_flags=CLONE_AUTOREAP, exit_signal=0
+            )
+            if pid == 0:
+                try:
+                    os.close(self.cfd)
+                    os.close(self.mntns_fd)
+                    if self.root_dfd >= 0:
+                        os.close(self.root_dfd)
+                    if bin_fd >= 0:
+                        execveat(bin_fd, "", argv, env, AT_EMPTY_PATH)
+                    if env is None:
+                        os.execv(argv[0], list(argv))
+                    else:
+                        os.execve(argv[0], list(argv), dict(env))
+                except BaseException:
+                    os._exit(127)
+            if self.init_pid is None:
+                self.init_pid = pid
+            return pid
+        finally:
+            if bin_fd >= 0:
+                os.close(bin_fd)
+
+    def kill(self, sig: int = int(signal.SIGTERM)) -> None:
+        rootns_kill(self.cfd, sig)
+
+    def wait(self, nohang: bool = False) -> WaitResult:
+        res = rootns_wait(self.cfd, os.WNOHANG if nohang else 0)
+        if res.pid > 0:
+            self.exit_status = res.status
+        return res
+
+    @property
+    def status_str(self) -> str:
+        if self.init_pid is None:
+            return "created"
+        if self.exit_status is None:
+            return "running"
+        return "exited"
+
+    def info(self) -> CellInfo:
+        code = (
+            os.waitstatus_to_exitcode(self.exit_status)
+            if self.exit_status is not None
+            else None
+        )
+        return CellInfo(
+            name=self.name,
+            state=self.status_str,
+            init_pid=self.init_pid,
+            exit_code=code,
+        )
+
+    def close(self) -> None:
+        for attr in ("root_dfd", "mntns_fd", "cfd"):
+            fd: int = getattr(self, attr, -1)
+            if fd >= 0:
+                try:
+                    os.close(fd)
+                except OSError:
+                    pass
+                setattr(self, attr, -1)
+
+
+class CellService:
+    def __init__(self, sock_path: str) -> None:
+        self.sock_path = sock_path
+        self.sel = selectors.DefaultSelector()
+        self.cells: dict[str, Cell] = {}
+        self.running = True
+        if os.path.exists(sock_path):
+            os.unlink(sock_path)
+        self.srv = socket.socket(
+            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC
+        )
+        self.srv.bind(sock_path)
+        self.srv.listen(16)
+        self.srv.setblocking(False)
+        self.sel.register(self.srv, selectors.EVENT_READ, self._on_accept)
+
+    def _reap_children(self) -> None:
+        while True:
+            try:
+                pid, _ = os.waitpid(-1, os.WNOHANG)
+                if pid == 0:
+                    break
+            except ChildProcessError:
+                break
+
+    def _on_cell_event(self, cell: Cell) -> None:
+        try:
+            res = cell.wait(nohang=True)
+            if res.pid > 0:
+                try:
+                    self.sel.unregister(cell.cfd)
+                except KeyError:
+                    pass
+        except OSError:
+            pass
+        self._reap_children()
+
+    def _on_accept(self) -> None:
+        conn, _ = self.srv.accept()
+        with conn:
+            data = b""
+            while not data.endswith(b"\n"):
+                chunk = conn.recv(4096)
+                if not chunk:
+                    break
+                data += chunk
+            if not data:
+                return
+            try:
+                req: dict[str, Any] = json.loads(data.decode("utf-8"))
+                resp: dict[str, Any] = {
+                    "ok": True,
+                    "result": self._dispatch(req),
+                }
+            except Exception as exc:
+                resp = {
+                    "ok": False,
+                    "error": str(exc),
+                    "errno": getattr(exc, "errno", None),
+                }
+            conn.sendall((json.dumps(resp) + "\n").encode("utf-8"))
+
+    def _dispatch(self, req: Mapping[str, Any]) -> Any:
+        op = str(req["op"])
+        if op == "ping":
+            return "pong"
+        if op == "shutdown":
+            self.running = False
+            return "bye"
+        if op == "list":
+            self._reap_children()
+            return [asdict(c.info()) for c in self.cells.values()]
+
+        name = str(req["name"])
+        if op == "create":
+            if name in self.cells:
+                raise OSError(errno.EEXIST, f"cell {name} already exists")
+            cell = Cell(name)
+            try:
+                host_runtime = req.get("mode", "host") == "host"
+                cell.setup_rootfs(
+                    mount_procfs=bool(req.get("proc", True)),
+                    host_runtime=host_runtime,
+                )
+            except Exception:
+                cell.close()
+                raise
+            self.cells[name] = cell
+            self.sel.register(
+                cell.cfd,
+                selectors.EVENT_READ,
+                lambda c=cell: self._on_cell_event(c),
+            )
+            return asdict(cell.info())
+
+        cell_opt = self.cells.get(name)
+        if cell_opt is None:
+            raise OSError(errno.ENOENT, f"unknown cell {name}")
+        cell = cell_opt
+
+        if op in ("start", "exec"):
+            pid = cell.spawn(
+                list(req["argv"]),
+                resolve_in_root=bool(req.get("resolve_in_root", True)),
+            )
+            return asdict(SpawnInfo(pid=pid, state=cell.status_str))
+        if op == "mount":
+            if req.get("bind"):
+                cell.bind_mount(str(req["source"]), str(req["target"]))
+            else:
+                cell.mount_fs(
+                    str(req["source"]),
+                    str(req["target"]),
+                    options=req.get("options"),
+                )
+            return str(req["target"])
+        if op == "kill":
+            cell.kill(int(req.get("sig", int(signal.SIGTERM))))
+            return name
+        if op == "wait":
+            res = cell.wait(nohang=bool(req.get("nohang", False)))
+            self._reap_children()
+            return asdict(res)
+        if op == "destroy":
+            try:
+                self.sel.unregister(cell.cfd)
+            except KeyError:
+                pass
+            cell.close()
+            del self.cells[name]
+            self._reap_children()
+            return name
+        raise ValueError(f"unsupported op {op}")
+
+    def serve_forever(self) -> None:
+        try:
+            while self.running:
+                for key, _ in self.sel.select(timeout=0.2):
+                    cb: Callable[[], None] = key.data
+                    cb()
+                self._reap_children()
+        finally:
+            self.close()
+
+    def close(self) -> None:
+        for cell in list(self.cells.values()):
+            try:
+                self.sel.unregister(cell.cfd)
+            except KeyError:
+                pass
+            cell.close()
+        self.cells.clear()
+        try:
+            self.sel.unregister(self.srv)
+        except KeyError:
+            pass
+        self.srv.close()
+        self.sel.close()
+        if os.path.exists(self.sock_path):
+            os.unlink(self.sock_path)
+        self._reap_children()
+
+
+@dataclass(frozen=True)
+class CellClient:
+    sock_path: str
+
+    def call(self, **req: Any) -> Any:
+        with socket.socket(
+            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC
+        ) as s:
+            s.connect(self.sock_path)
+            s.sendall((json.dumps(req) + "\n").encode("utf-8"))
+            data = b""
+            while not data.endswith(b"\n"):
+                chunk = s.recv(4096)
+                if not chunk:
+                    break
+                data += chunk
+        resp: dict[str, Any] = json.loads(data.decode("utf-8"))
+        if not resp["ok"]:
+            err = resp.get("errno")
+            if err is not None:
+                raise OSError(int(err), str(resp["error"]))
+            raise RuntimeError(str(resp["error"]))
+        return resp["result"]
+
+    def ping(self) -> str:
+        return str(self.call(op="ping"))
+
+    def shutdown(self) -> str:
+        return str(self.call(op="shutdown"))
+
+    def list_cells(self) -> list[CellInfo]:
+        items: list[dict[str, Any]] = self.call(op="list")
+        return [CellInfo(**item) for item in items]
+
+    def create(
+        self, name: str, mode: str = "host", proc: bool = True
+    ) -> CellInfo:
+        data: dict[str, Any] = self.call(
+            op="create", name=name, mode=mode, proc=proc
+        )
+        return CellInfo(**data)
+
+    def start(
+        self,
+        name: str,
+        argv: Sequence[str],
+        resolve_in_root: bool = True,
+    ) -> SpawnInfo:
+        data: dict[str, Any] = self.call(
+            op="start",
+            name=name,
+            argv=list(argv),
+            resolve_in_root=resolve_in_root,
+        )
+        return SpawnInfo(**data)
+
+    def exec_cmd(
+        self,
+        name: str,
+        argv: Sequence[str],
+        resolve_in_root: bool = True,
+    ) -> SpawnInfo:
+        data: dict[str, Any] = self.call(
+            op="exec",
+            name=name,
+            argv=list(argv),
+            resolve_in_root=resolve_in_root,
+        )
+        return SpawnInfo(**data)
+
+    def mount(
+        self,
+        name: str,
+        source: str,
+        target: str,
+        bind: bool = False,
+        options: Mapping[str, str | None] | None = None,
+    ) -> str:
+        return str(
+            self.call(
+                op="mount",
+                name=name,
+                source=source,
+                target=target,
+                bind=bind,
+                options=dict(options) if options is not None else None,
+            )
+        )
+
+    def kill(self, name: str, sig: int = int(signal.SIGTERM)) -> str:
+        return str(self.call(op="kill", name=name, sig=sig))
+
+    def wait(self, name: str, nohang: bool = False) -> WaitResult:
+        data: dict[str, Any] = self.call(op="wait", name=name, nohang=nohang)
+        return WaitResult(pid=int(data["pid"]), status=int(data["status"]))
+
+    def destroy(self, name: str) -> str:
+        return str(self.call(op="destroy", name=name))
+
+
+def _cli() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--sock", default="/tmp/rootns-cells.sock")
+    sub = parser.add_subparsers(dest="cmd", required=True)
+    sub.add_parser("daemon")
+    sub.add_parser("ps")
+    sub.add_parser("shutdown")
+
+    p_create = sub.add_parser("create")
+    p_create.add_argument("name")
+    p_create.add_argument("--mode", choices=("host", "tmpfs"), default="host")
+
+    for cname in ("start", "exec"):
+        p_run = sub.add_parser(cname)
+        p_run.add_argument("name")
+        p_run.add_argument("argv", nargs=argparse.REMAINDER)
+
+    p_mnt = sub.add_parser("mount")
+    p_mnt.add_argument("name")
+    p_mnt.add_argument("source")
+    p_mnt.add_argument("target")
+    p_mnt.add_argument("--bind", action="store_true")
+
+    p_kill = sub.add_parser("kill")
+    p_kill.add_argument("name")
+    p_kill.add_argument("-s", "--sig", type=int, default=int(signal.SIGTERM))
+
+    p_wait = sub.add_parser("wait")
+    p_wait.add_argument("name")
+
+    p_rm = sub.add_parser("destroy")
+    p_rm.add_argument("name")
+
+    args = parser.parse_args()
+    if args.cmd == "daemon":
+        CellService(args.sock).serve_forever()
+        return
+
+    client = CellClient(args.sock)
+    if args.cmd == "ps":
+        print(json.dumps([asdict(c) for c in client.list_cells()], indent=2))
+    elif args.cmd == "shutdown":
+        print(json.dumps(client.shutdown()))
+    elif args.cmd == "create":
+        print(json.dumps(asdict(client.create(args.name, mode=args.mode))))
+    elif args.cmd in ("start", "exec"):
+        argv = (
+            args.argv[1:]
+            if args.argv and args.argv[0] == "--"
+            else list(args.argv)
+        )
+        fn = client.start if args.cmd == "start" else client.exec_cmd
+        print(json.dumps(asdict(fn(args.name, argv))))
+    elif args.cmd == "mount":
+        print(
+            json.dumps(
+                client.mount(
+                    args.name, args.source, args.target, bind=args.bind
+                )
+            )
+        )
+    elif args.cmd == "kill":
+        print(json.dumps(client.kill(args.name, args.sig)))
+    elif args.cmd == "wait":
+        res = client.wait(args.name)
+        print(json.dumps({"pid": res.pid, "exit_code": res.exit_code}))
+    elif args.cmd == "destroy":
+        print(json.dumps(client.destroy(args.name)))
+
+
+if __name__ == "__main__":
+    _cli()
diff --git a/tools/testing/selftests/rootns/rootns_test.py b/tools/testing/selftests/rootns/rootns_test.py
new file mode 100755
index 000000000000..7594b7a40c0c
--- /dev/null
+++ b/tools/testing/selftests/rootns/rootns_test.py
@@ -0,0 +1,1161 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2026 Opinsys Oy
+
+from __future__ import annotations
+
+import ctypes
+from dataclasses import dataclass
+import errno
+import os
+import select
+import shutil
+import signal
+import socket
+import sys
+import tempfile
+import time
+from typing import Final
+import unittest
+
+import rootns_cells as rc
+
+PYTHON_BIN: Final[str] = os.path.realpath(sys.executable)
+SKIP_EXIT: Final[int] = 77
+SKIP_ERRNOS: Final[tuple[int, ...]] = (
+    errno.ENOSYS,
+    errno.EPERM,
+    errno.EACCES,
+    errno.EINVAL,
+    errno.ENOSPC,
+)
+
+
+@dataclass(frozen=True)
+class Payload:
+    code: str
+
+    def argv(self) -> list[str]:
+        return [PYTHON_BIN, "-S", "-c", self.code]
+
+
+WAIT_MOUNT_PAYLOAD: Final[Payload] = Payload(
+    """\
+import os
+import sys
+import time
+
+if os.getpid() != 1:
+    sys.exit(1)
+deadline = time.monotonic() + 5.0
+while time.monotonic() < deadline:
+    if os.path.ismount("/mnt") and os.path.exists("/mnt/done"):
+        with open("/mnt/done", "rb") as f:
+            sys.exit(0 if f.read() == b"ok\\n" else 2)
+    time.sleep(0.02)
+sys.exit(3)
+"""
+)
+
+WRITE_MOUNT_PAYLOAD: Final[Payload] = Payload(
+    """\
+import os
+import sys
+
+if not os.path.ismount("/mnt"):
+    sys.exit(1)
+with open("/mnt/done.tmp", "wb") as f:
+    f.write(b"ok\\n")
+os.replace("/mnt/done.tmp", "/mnt/done")
+"""
+)
+
+PAUSE_PAYLOAD: Final[Payload] = Payload(
+    """\
+import signal
+
+signal.pause()
+"""
+)
+
+
+@dataclass(frozen=True)
+class ProbeResult:
+    supported: bool
+    reason: str = ""
+
+
+@dataclass
+class SyncPipe:
+    r_fd: int
+    w_fd: int
+
+    @classmethod
+    def create(cls) -> SyncPipe:
+        r_fd, w_fd = os.pipe2(os.O_CLOEXEC)
+        return cls(r_fd=r_fd, w_fd=w_fd)
+
+    def close_read(self) -> None:
+        if self.r_fd >= 0:
+            os.close(self.r_fd)
+            self.r_fd = -1
+
+    def close_write(self) -> None:
+        if self.w_fd >= 0:
+            os.close(self.w_fd)
+            self.w_fd = -1
+
+    def close(self) -> None:
+        self.close_read()
+        self.close_write()
+
+    def read_bytes(self, n: int = 1) -> bytes:
+        return os.read(self.r_fd, n)
+
+    def write_bytes(self, data: bytes = b"1") -> None:
+        os.write(self.w_fd, data)
+
+    def wait_in_child(self, exit_code: int = 0) -> int:
+        self.close_write()
+        self.read_bytes()
+        self.close_read()
+        return exit_code
+
+
+@dataclass(frozen=True)
+class NsTypeCase:
+    name: str
+    nstype: int
+
+
+@dataclass(frozen=True)
+class BadCloneCase:
+    name: str
+    flags: int
+    exit_signal: int = int(signal.SIGCHLD)
+    expected_errno: int = errno.EINVAL
+
+
+@dataclass(frozen=True)
+class SignalCase:
+    name: str
+    sig: int
+    expected_errno: int
+
+
+NS_TYPE_CASES: Final[tuple[NsTypeCase, ...]] = (
+    NsTypeCase("mnt", rc.CLONE_NEWNS),
+    NsTypeCase("cgroup", rc.CLONE_NEWCGROUP),
+    NsTypeCase("uts", rc.CLONE_NEWUTS),
+    NsTypeCase("ipc", rc.CLONE_NEWIPC),
+    NsTypeCase("user", rc.CLONE_NEWUSER),
+    NsTypeCase("net", rc.CLONE_NEWNET),
+    NsTypeCase("time", rc.CLONE_NEWTIME),
+)
+
+BAD_CLONE_CASES: Final[tuple[BadCloneCase, ...]] = (
+    BadCloneCase("newns", rc.CLONE_NEWNS),
+    BadCloneCase("newpid", rc.CLONE_NEWPID),
+    BadCloneCase("newuser", rc.CLONE_NEWUSER),
+    BadCloneCase("empty_mntns", rc.CLONE_EMPTY_MNTNS),
+    BadCloneCase("fs", rc.CLONE_FS),
+    BadCloneCase(
+        "thread",
+        rc.CLONE_THREAD | rc.CLONE_SIGHAND | rc.CLONE_VM,
+        exit_signal=0,
+    ),
+    BadCloneCase("parent", rc.CLONE_PARENT, exit_signal=0),
+    BadCloneCase("sysvsem", rc.CLONE_SYSVSEM),
+    BadCloneCase("vm", rc.CLONE_VM),
+    BadCloneCase("vm_vfork", rc.CLONE_VM | rc.CLONE_VFORK),
+)
+
+BAD_SIGNAL_CASES: Final[tuple[SignalCase, ...]] = (
+    SignalCase("negative", -1, errno.EINVAL),
+    SignalCase("out_of_range", 9999, errno.EINVAL),
+    SignalCase("empty_rootns", 0, errno.ESRCH),
+)
+
+
+def _pause_forever() -> int:
+    signal.pause()
+    return 0
+
+
+def _reap_exit_code(pid: int) -> int:
+    _, status = os.waitpid(pid, 0)
+    if os.WIFEXITED(status):
+        return os.WEXITSTATUS(status)
+    if os.WIFSIGNALED(status):
+        return 128 + os.WTERMSIG(status)
+    return 255
+
+
+def _drop_to_uid(uid: int) -> None:
+    try:
+        rc.setgroups_empty()
+    except OSError as exc:
+        if exc.errno != errno.EPERM:
+            raise
+    os.setresgid(uid, uid, uid)
+    os.setresuid(uid, uid, uid)
+    rc.prctl(rc.PR_SET_DUMPABLE, 1)
+
+
+def _write_ugid_map(pid: int, host_uid: int, host_gid: int) -> None:
+    try:
+        with open(f"/proc/{pid}/setgroups", "wb") as f:
+            f.write(b"deny\n")
+    except OSError:
+        pass
+    with open(f"/proc/{pid}/uid_map", "wb") as f:
+        f.write(f"0 {host_uid} 1\n".encode())
+    with open(f"/proc/{pid}/gid_map", "wb") as f:
+        f.write(f"0 {host_gid} 1\n".encode())
+
+
+def _probe_pre_idmap_mkdir() -> ProbeResult:
+    try:
+        cfd = rc.rootns()
+    except OSError as exc:
+        if exc.errno in SKIP_ERRNOS:
+            return ProbeResult(False, f"rootns() unavailable: {exc}")
+        raise
+    try:
+        try:
+            mfd = rc.make_rootns_mount(cfd, "tmpfs")
+        except OSError as exc:
+            return ProbeResult(False, f"tmpfs mount unavailable: {exc}")
+        try:
+            os.mkdir("probe", 0o755, dir_fd=mfd)
+            return ProbeResult(True)
+        except OSError as exc:
+            if exc.errno == errno.EOVERFLOW:
+                return ProbeResult(
+                    False, "pre-idmap submount setup requires mapped userns"
+                )
+            raise
+        finally:
+            os.close(mfd)
+    finally:
+        os.close(cfd)
+
+
+def _send_fd(sock: socket.socket, fd: int) -> None:
+    sock.sendmsg(
+        [b"F"], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ctypes.c_int(fd))]
+    )
+
+
+def _recv_fd(sock: socket.socket) -> int:
+    _, ancdata, _, _ = sock.recvmsg(
+        1, socket.CMSG_SPACE(ctypes.sizeof(ctypes.c_int))
+    )
+    for cmsg_lvl, cmsg_type, cmsg_data in ancdata:
+        if cmsg_lvl == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
+            buf = cmsg_data[: ctypes.sizeof(ctypes.c_int)]
+            return int(ctypes.c_int.from_buffer_copy(buf).value)
+    raise RuntimeError("missing SCM_RIGHTS fd")
+
+
+def _create_rootns_as_uid(uid: int) -> tuple[int, int]:
+    s_parent, s_child = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM)
+    pid = os.fork()
+    if pid == 0:
+        s_parent.close()
+        try:
+            _drop_to_uid(uid)
+            cfd = rc.rootns()
+            _send_fd(s_child, cfd)
+            os.close(cfd)
+            os._exit(0)
+        except OSError as exc:
+            if exc.errno in SKIP_ERRNOS:
+                os._exit(SKIP_EXIT)
+            os._exit(1)
+        finally:
+            s_child.close()
+    s_child.close()
+    try:
+        rlist, _, _ = select.select([s_parent], [], [], 5.0)
+        cfd = _recv_fd(s_parent) if rlist else -1
+    finally:
+        s_parent.close()
+    code = _reap_exit_code(pid)
+    return code, cfd
+
+
+class CellServiceTest(unittest.TestCase):
+    tmpdir: str
+    sock_path: str
+    daemon_pid: int
+    client: rc.CellClient
+
+    def setUp(self) -> None:
+        probe = _probe_pre_idmap_mkdir()
+        if not probe.supported:
+            self.skipTest(probe.reason)
+        self.tmpdir = tempfile.mkdtemp(prefix="rootns-cells-")
+        self.sock_path = os.path.join(self.tmpdir, "cells.sock")
+        self.daemon_pid = os.fork()
+        if self.daemon_pid == 0:
+            try:
+                rc.CellService(self.sock_path).serve_forever()
+                os._exit(0)
+            except BaseException:
+                os._exit(1)
+        self.client = rc.CellClient(self.sock_path)
+        for _ in range(50):
+            if os.path.exists(self.sock_path):
+                try:
+                    if self.client.ping() == "pong":
+                        break
+                except OSError:
+                    pass
+            time.sleep(0.05)
+        else:
+            self.fail("CellService daemon failed to start")
+
+    def tearDown(self) -> None:
+        daemon_pid = getattr(self, "daemon_pid", 0)
+        if daemon_pid > 0:
+            try:
+                self.client.shutdown()
+            except Exception:
+                os.kill(daemon_pid, signal.SIGKILL)
+            _reap_exit_code(daemon_pid)
+        tmpdir = getattr(self, "tmpdir", "")
+        if tmpdir:
+            shutil.rmtree(tmpdir, ignore_errors=True)
+
+    def test_cell_lifecycle_exec_and_hot_mount(self) -> None:
+        info = self.client.create("alpha", mode="host")
+        self.assertEqual(info.state, "created")
+        self.assertEqual(
+            self.client.list_cells(),
+            [rc.CellInfo(name="alpha", state="created")],
+        )
+
+        started = self.client.start("alpha", WAIT_MOUNT_PAYLOAD.argv())
+        self.assertEqual(started.state, "running")
+
+        self.client.mount("alpha", "tmpfs", "/mnt")
+        self.client.exec_cmd("alpha", WRITE_MOUNT_PAYLOAD.argv())
+
+        res = self.client.wait("alpha")
+        self.assertGreater(res.pid, 0)
+        self.assertEqual(res.exit_code, 0)
+
+        self.client.destroy("alpha")
+        self.assertEqual(self.client.list_cells(), [])
+
+    def test_cell_broadcast_kill(self) -> None:
+        self.client.create("killme", mode="host")
+        self.client.start("killme", PAUSE_PAYLOAD.argv())
+        self.client.exec_cmd("killme", PAUSE_PAYLOAD.argv())
+
+        self.client.kill("killme", int(signal.SIGKILL))
+        res = self.client.wait("killme")
+        self.assertEqual(res.exit_code, -int(signal.SIGKILL))
+        self.client.destroy("killme")
+
+
+class RootnsUapiTest(unittest.TestCase):
+    probe: ProbeResult
+    cell: rc.Cell | None
+
+    def setUp(self) -> None:
+        self.probe = _probe_pre_idmap_mkdir()
+        self.cell = None
+        if self.probe.supported:
+            self.cell = rc.Cell("test")
+            self.cell.setup_rootfs(
+                dirs=("proc", "tmp", "mnt"), mount_procfs=True
+            )
+
+    def tearDown(self) -> None:
+        if self.cell is not None:
+            self.cell.close()
+
+    def _require_cell(self) -> rc.Cell:
+        if not self.probe.supported or self.cell is None:
+            self.skipTest(self.probe.reason)
+        return self.cell
+
+    def test_create_flags(self) -> None:
+        self._require_cell()
+        with self.assertRaises(OSError) as cm:
+            rc.rootns((~rc.ROOTNS_ALL_FLAGS) & 0xFFFFFFFF)
+        self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+    def test_get_nsfd(self) -> None:
+        try:
+            cfd = rc.rootns()
+        except OSError as exc:
+            if exc.errno in SKIP_ERRNOS:
+                self.skipTest(f"rootns() unavailable: {exc}")
+            raise
+        try:
+            for case in NS_TYPE_CASES:
+                with self.subTest(ns=case.name):
+                    nsfd = rc.rootns_get_nsfd(cfd, case.nstype)
+                    try:
+                        self.assertEqual(
+                            rc.raw_ioctl(nsfd, rc.NS_GET_NSTYPE), case.nstype
+                        )
+                    finally:
+                        os.close(nsfd)
+
+            with self.assertRaises(OSError) as cm:
+                rc.rootns_get_nsfd(cfd, rc.CLONE_NEWPID)
+            self.assertEqual(cm.exception.errno, errno.ESRCH)
+
+            with self.assertRaises(OSError) as cm:
+                rc.rootns_get_nsfd(cfd, 0)
+            self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+            mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)
+            rootfd = rc.make_rootns_mount(cfd, "tmpfs")
+            rc.move_mount(
+                rootfd,
+                "",
+                mntns_fd,
+                "/",
+                rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+            )
+            os.close(rootfd)
+            os.close(mntns_fd)
+
+            hold = SyncPipe.create()
+            pid = rc.run_in_rootns(cfd, hold.wait_in_child)
+            hold.close_read()
+            try:
+                nsfd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWPID)
+                try:
+                    self.assertEqual(
+                        rc.raw_ioctl(nsfd, rc.NS_GET_NSTYPE), rc.CLONE_NEWPID
+                    )
+                finally:
+                    os.close(nsfd)
+            finally:
+                hold.close_write()
+                self.assertEqual(_reap_exit_code(pid), 0)
+        finally:
+            os.close(cfd)
+
+    def test_wait_poll_and_clone_dead(self) -> None:
+        cell = self._require_cell()
+        cfd = cell.cfd
+
+        with self.assertRaises(OSError) as cm:
+            rc.raw_ioctl(cfd, rc.ROOTNS_WAIT, 0)
+        self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+        with self.assertRaises(OSError) as cm:
+            rc.rootns_wait(cfd, (~os.WNOHANG) & 0xFFFFFFFF)
+        self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+        for wait_flags in (0, os.WNOHANG):
+            with self.assertRaises(OSError) as cm:
+                rc.rootns_wait(cfd, wait_flags)
+            self.assertEqual(cm.exception.errno, errno.ECHILD)
+
+        hold = SyncPipe.create()
+        pid = rc.run_in_rootns(cfd, lambda: hold.wait_in_child(42))
+        hold.close_read()
+
+        self.assertEqual(
+            rc.rootns_wait(cfd, os.WNOHANG), rc.WaitResult(0, 0)
+        )
+        poller = select.poll()
+        poller.register(cfd, select.POLLIN)
+        self.assertEqual(poller.poll(0), [])
+
+        hold.close_write()
+        events = poller.poll(5000)
+        self.assertTrue(any(ev & select.POLLHUP for _, ev in events))
+
+        res = rc.rootns_wait(cfd, os.WNOHANG)
+        self.assertEqual(res.pid, pid)
+        self.assertEqual(res.exit_code, 42)
+        self.assertEqual(_reap_exit_code(pid), 42)
+
+        with self.assertRaises(OSError) as cm:
+            rc.clone_into_rootns(cfd)
+        self.assertEqual(cm.exception.errno, errno.ESRCH)
+
+    def test_kill_ioctl_and_kill_on_close(self) -> None:
+        cell = self._require_cell()
+        cfd = cell.cfd
+
+        for case in BAD_SIGNAL_CASES:
+            with self.subTest(sig=case.name):
+                with self.assertRaises(OSError) as cm:
+                    rc.rootns_kill(cfd, case.sig)
+                self.assertEqual(cm.exception.errno, case.expected_errno)
+
+        ready = SyncPipe.create()
+        hold = SyncPipe.create()
+
+        def init_proc() -> int:
+            ready.close()
+            hold.close()
+            signal.pause()
+            return 0
+
+        def member_proc() -> int:
+            ready.close_read()
+            hold.close_read()
+            os.setsid()
+            gc = os.fork()
+            if gc == 0:
+                ready.write_bytes(b"r")
+                ready.close_write()
+                signal.pause()
+                os._exit(0)
+            ready.close_write()
+            signal.pause()
+            return 0
+
+        pid1 = rc.run_in_rootns(cfd, init_proc)
+        pid2 = rc.run_in_rootns(cfd, member_proc)
+        ready.close_write()
+        hold.close_write()
+
+        self.assertEqual(ready.read_bytes(), b"r")
+        ready.close_read()
+
+        rc.rootns_kill(cfd, 0)
+        rc.rootns_kill(cfd, int(signal.SIGKILL))
+        self.assertEqual(hold.read_bytes(), b"")
+        hold.close_read()
+
+        self.assertEqual(_reap_exit_code(pid2), 128 + int(signal.SIGKILL))
+        self.assertEqual(_reap_exit_code(pid1), 128 + int(signal.SIGKILL))
+
+        with rc.Cell(
+            "koc", flags=rc.ROOTNS_KILL_ON_CLOSE | rc.ROOTNS_CLOSE_ON_EXEC
+        ) as cell2:
+            cell2.setup_rootfs(mount_procfs=False)
+            pid_koc = rc.run_in_rootns(cell2.cfd, _pause_forever)
+        self.assertEqual(_reap_exit_code(pid_koc), 128 + int(signal.SIGKILL))
+
+    def test_proc_submount_and_nested_namespaces(self) -> None:
+        cell = self._require_cell()
+        cell.mount_fs("tmpfs", "mnt")
+
+        def inside() -> int:
+            if os.getpid() != 1:
+                return 1
+            pids = [e for e in os.listdir("/proc") if e.isdigit()]
+            if pids != ["1"]:
+                return 2
+            with open("/mnt/hello", "wb") as f:
+                f.write(b"ok")
+            rc.unshare(rc.CLONE_NEWUTS | rc.CLONE_NEWIPC | rc.CLONE_NEWNET)
+            return 0
+
+        pid = rc.run_in_rootns(cell.cfd, inside)
+        res = cell.wait()
+        self.assertEqual(res.pid, pid)
+        self.assertEqual(res.exit_code, 0)
+        self.assertEqual(_reap_exit_code(pid), 0)
+
+    def test_setns_owner_vs_foreign(self) -> None:
+        cell = self._require_cell()
+        hold = SyncPipe.create()
+        pid = rc.run_in_rootns(cell.cfd, hold.wait_in_child)
+        hold.close_read()
+        try:
+            uts_fd = os.open(
+                f"/proc/{pid}/ns/uts", os.O_RDONLY | os.O_CLOEXEC
+            )
+            try:
+                w1 = os.fork()
+                if w1 == 0:
+                    try:
+                        rc.setns(uts_fd, rc.CLONE_NEWUTS)
+                        os._exit(0)
+                    except BaseException:
+                        os._exit(1)
+                self.assertEqual(_reap_exit_code(w1), 0)
+
+                if os.geteuid() == 0:
+                    w2 = os.fork()
+                    if w2 == 0:
+                        try:
+                            _drop_to_uid(1000)
+                        except OSError:
+                            os._exit(0)
+                        try:
+                            rc.setns(uts_fd, rc.CLONE_NEWUTS)
+                            os._exit(2)
+                        except OSError as exc:
+                            os._exit(0 if exc.errno == errno.EPERM else 3)
+                    self.assertEqual(_reap_exit_code(w2), 0)
+            finally:
+                os.close(uts_fd)
+        finally:
+            hold.close_write()
+            _reap_exit_code(pid)
+
+    def test_mount_and_fsconfig_validation(self) -> None:
+        self._require_cell()
+        cfd = rc.rootns()
+        mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)
+        try:
+            with self.assertRaises(OSError) as cm:
+                rc.move_mount(
+                    rc.AT_FDCWD, "/", mntns_fd, "/", rc.MOVE_MOUNT_T_MNTNS
+                )
+            self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+            m1 = rc.make_rootns_mount(cfd, "tmpfs")
+            try:
+                rc.move_mount(
+                    m1,
+                    "",
+                    mntns_fd,
+                    "/",
+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                )
+            finally:
+                os.close(m1)
+
+            m2 = rc.make_rootns_mount(cfd, "tmpfs")
+            try:
+                for alias in ("/", "."):
+                    with self.assertRaises(OSError) as cm:
+                        rc.move_mount(
+                            m2,
+                            "",
+                            mntns_fd,
+                            alias,
+                            rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                        )
+                    self.assertEqual(cm.exception.errno, errno.EBUSY)
+                with self.assertRaises(OSError) as cm:
+                    rc.move_mount(
+                        m2,
+                        "",
+                        mntns_fd,
+                        ".",
+                        rc.MOVE_MOUNT_F_EMPTY_PATH
+                        | rc.MOVE_MOUNT_T_MNTNS
+                        | rc.MOVE_MOUNT_BENEATH,
+                    )
+                self.assertEqual(cm.exception.errno, errno.EINVAL)
+            finally:
+                os.close(m2)
+
+            fsfd = rc.fsopen("tmpfs")
+            try:
+                rc.fsconfig(fsfd, rc.FSCONFIG_SET_ROOTNS, aux=cfd)
+                with self.assertRaises(OSError) as cm:
+                    rc.fsconfig(fsfd, rc.FSCONFIG_SET_ROOTNS, aux=cfd)
+                self.assertEqual(cm.exception.errno, errno.EBUSY)
+            finally:
+                os.close(fsfd)
+
+            bad_proc = rc.fsopen("proc")
+            try:
+                w_nonanc = os.fork()
+                if w_nonanc == 0:
+                    try:
+                        rc.unshare(rc.CLONE_NEWPID)
+                        inner = os.fork()
+                        if inner == 0:
+                            try:
+                                rc.fsconfig(
+                                    bad_proc, rc.FSCONFIG_SET_ROOTNS, aux=cfd
+                                )
+                                os._exit(1)
+                            except OSError as exc:
+                                if exc.errno != errno.EINVAL:
+                                    os._exit(2)
+                            try:
+                                rc.fsconfig(bad_proc, rc.FSCONFIG_CMD_CREATE)
+                                os._exit(3)
+                            except OSError as exc:
+                                os._exit(0 if exc.errno == errno.EBUSY else 4)
+                        os._exit(_reap_exit_code(inner))
+                    except BaseException:
+                        os._exit(5)
+                self.assertEqual(_reap_exit_code(w_nonanc), 0)
+            finally:
+                os.close(bad_proc)
+
+            cfd_lock = rc.rootns()
+            lock_mntns = rc.rootns_get_nsfd(cfd_lock, rc.CLONE_NEWNS)
+            try:
+                rfd = rc.make_rootns_mount(cfd_lock, "tmpfs")
+                os.mkdir("host_sub", 0o755, dir_fd=rfd)
+                sfd = rc.open_tree(
+                    rc.AT_FDCWD,
+                    "/tmp",
+                    rc.OPEN_TREE_CLONE
+                    | rc.AT_RECURSIVE
+                    | rc.OPEN_TREE_CLOEXEC,
+                )
+                rc.move_mount(
+                    sfd, "", rfd, "host_sub", rc.MOVE_MOUNT_F_EMPTY_PATH
+                )
+                os.close(sfd)
+                rc.move_mount(
+                    rfd,
+                    "",
+                    lock_mntns,
+                    "/",
+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                )
+                os.close(rfd)
+
+                def try_umount_locked() -> int:
+                    try:
+                        rc.umount2("/host_sub", rc.MNT_DETACH)
+                        return 1
+                    except OSError as exc:
+                        return 0 if exc.errno == errno.EINVAL else 2
+
+                p_lock = rc.run_in_rootns(cfd_lock, try_umount_locked)
+                self.assertEqual(_reap_exit_code(p_lock), 0)
+            finally:
+                os.close(lock_mntns)
+                os.close(cfd_lock)
+
+            if os.geteuid() == 0:
+                code, u_cfd = _create_rootns_as_uid(1000)
+                if code == 0 and u_cfd >= 0:
+                    try:
+                        u_mntns = rc.rootns_get_nsfd(u_cfd, rc.CLONE_NEWNS)
+                        m_root = rc.make_rootns_mount(u_cfd, "tmpfs")
+                        rc.move_mount(
+                            m_root,
+                            "",
+                            u_mntns,
+                            "/",
+                            rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                        )
+                        os.close(m_root)
+
+                        attacker = os.fork()
+                        if attacker == 0:
+                            try:
+                                _drop_to_uid(2000)
+                            except OSError:
+                                os._exit(0)
+                            fsfd2 = rc.fsopen("tmpfs")
+                            try:
+                                rc.fsconfig(
+                                    fsfd2, rc.FSCONFIG_SET_ROOTNS, aux=u_cfd
+                                )
+                                os._exit(1)
+                            except OSError as exc:
+                                if exc.errno != errno.EPERM:
+                                    os._exit(2)
+                            finally:
+                                os.close(fsfd2)
+                            try:
+                                rc.clone_into_rootns(u_cfd)
+                                os._exit(3)
+                            except OSError as exc:
+                                if exc.errno != errno.EPERM:
+                                    os._exit(4)
+                            os._exit(0)
+                        self.assertEqual(_reap_exit_code(attacker), 0)
+                        os.close(u_mntns)
+                    finally:
+                        os.close(u_cfd)
+        finally:
+            os.close(mntns_fd)
+            os.close(cfd)
+
+    def test_clone_flags_and_pidns_ancestry(self) -> None:
+        cell = self._require_cell()
+        cfd = cell.cfd
+
+        empty_cfd = rc.rootns()
+        try:
+            with self.assertRaises(OSError) as cm:
+                rc.clone_into_rootns(empty_cfd, rc.CLONE_VFORK)
+            self.assertEqual(cm.exception.errno, errno.ENOENT)
+        finally:
+            os.close(empty_cfd)
+
+        args = rc.CloneArgs(
+            flags=rc.CLONE_INTO_ROOTNS,
+            exit_signal=int(signal.SIGCHLD),
+            rootns=cfd,
+        )
+        with self.assertRaises(OSError) as cm:
+            rc.clone3_raw(args, size=rc.CLONE_ARGS_SIZE_VER2)
+        self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+        for case in BAD_CLONE_CASES:
+            with self.subTest(flag=case.name):
+                with self.assertRaises(OSError) as cm:
+                    rc.clone_into_rootns(
+                        cfd,
+                        extra_flags=case.flags,
+                        exit_signal=case.exit_signal,
+                    )
+                self.assertEqual(cm.exception.errno, case.expected_errno)
+
+        allowed = (
+            rc.CLONE_VFORK
+            | rc.CLONE_PIDFD
+            | rc.CLONE_CLEAR_SIGHAND
+            | rc.CLONE_NNP
+        )
+        old_umask = os.umask(0o077)
+        try:
+            rc.prctl(rc.PR_SET_DUMPABLE, 1)
+            pid, pidfd = rc.clone_into_rootns(cfd, extra_flags=allowed)
+            if pid == 0:
+                cur_umask = os.umask(0o022)
+                dumpable = rc.prctl(rc.PR_GET_DUMPABLE)
+                ok = (
+                    os.getpid() == 1
+                    and rc.prctl(rc.PR_GET_NO_NEW_PRIVS) == 1
+                    and cur_umask == 0o077
+                    and dumpable != 1
+                )
+                os._exit(0 if ok else 1)
+        finally:
+            os.umask(old_umask)
+        self.assertGreaterEqual(pidfd, 0)
+        os.close(pidfd)
+        self.assertEqual(_reap_exit_code(pid), 0)
+
+        with rc.Cell("exdev") as cell2:
+            cell2.setup_rootfs(mount_procfs=False)
+            w = os.fork()
+            if w == 0:
+                try:
+                    rc.unshare(rc.CLONE_NEWPID)
+                    inner = os.fork()
+                    if inner == 0:
+                        try:
+                            rc.clone_into_rootns(cell2.cfd)
+                            os._exit(1)
+                        except OSError as exc:
+                            os._exit(0 if exc.errno == errno.EXDEV else 2)
+                    os._exit(_reap_exit_code(inner))
+                except BaseException:
+                    os._exit(3)
+            self.assertEqual(_reap_exit_code(w), 0)
+
+    def test_concurrent_bootstrap(self) -> None:
+        cell = self._require_cell()
+        cfd = cell.cfd
+        start = SyncPipe.create()
+        ready = SyncPipe.create()
+        init_gate = SyncPipe.create()
+        peer_gate = SyncPipe.create()
+
+        workers: list[int] = []
+        for idx in range(4):
+            wpid = os.fork()
+            if wpid == 0:
+                start.close_write()
+                ready.close_read()
+                init_gate.close_write()
+                peer_gate.close_write()
+                start.read_bytes()
+                start.close_read()
+
+                def entrant(worker_idx: int = idx) -> int:
+                    my_pid = os.getpid()
+                    ready.write_bytes(bytes([worker_idx, my_pid]))
+                    ready.close_write()
+                    gate = init_gate if my_pid == 1 else peer_gate
+                    gate.read_bytes()
+                    init_gate.close_read()
+                    peer_gate.close_read()
+                    return 0
+
+                cpid = rc.run_in_rootns(cfd, entrant)
+                ready.close_write()
+                init_gate.close_read()
+                peer_gate.close_read()
+                os._exit(0 if _reap_exit_code(cpid) == 0 else 1)
+            workers.append(wpid)
+
+        start.close_read()
+        ready.close_write()
+        init_gate.close_read()
+        peer_gate.close_read()
+        start.close_write()
+
+        seen_pids: set[int] = set()
+        init_idx = -1
+        for _ in range(4):
+            msg = ready.read_bytes(2)
+            self.assertEqual(len(msg), 2)
+            if msg[1] == 1:
+                init_idx = msg[0]
+            seen_pids.add(msg[1])
+        ready.close_read()
+
+        self.assertEqual(seen_pids, {1, 2, 3, 4})
+        self.assertGreaterEqual(init_idx, 0)
+
+        peer_gate.close_write()
+        for i, wpid in enumerate(workers):
+            if i != init_idx:
+                self.assertEqual(_reap_exit_code(wpid), 0)
+        init_gate.close_write()
+        self.assertEqual(_reap_exit_code(workers[init_idx]), 0)
+
+        res = cell.wait()
+        self.assertGreater(res.pid, 0)
+        self.assertEqual(res.exit_code, 0)
+
+    def test_pivot_root_and_standalone_mntns_hot_mount(self) -> None:
+        cell = self._require_cell()
+        go = SyncPipe.create()
+        ready = SyncPipe.create()
+        hold = SyncPipe.create()
+
+        def init_pivot() -> int:
+            go.close_write()
+            ready.close_read()
+            hold.close_write()
+            if go.read_bytes() != b"g":
+                return 1
+            go.close_read()
+            tfd = rc.fsopen("tmpfs")
+            rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)
+            mfd = rc.fsmount(tfd)
+            os.close(tfd)
+            os.mkdir("old_root", 0o755, dir_fd=mfd)
+            os.mkdir("sub", 0o755, dir_fd=mfd)
+            pfd = os.open(
+                "pivoted",
+                os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,
+                0o644,
+                dir_fd=mfd,
+            )
+            os.close(pfd)
+            rc.move_mount(
+                mfd, "", rc.AT_FDCWD, "/mnt", rc.MOVE_MOUNT_F_EMPTY_PATH
+            )
+            os.close(mfd)
+            os.chdir("/mnt")
+            rc.pivot_root(".", "old_root")
+            os.chdir("/")
+            rc.umount2("/old_root", rc.MNT_DETACH)
+            ready.write_bytes(b"p")
+            ready.close_write()
+            hold.read_bytes()
+            hold.close_read()
+            return 0
+
+        pid1 = rc.run_in_rootns(cell.cfd, init_pivot)
+        go.close_read()
+        ready.close_write()
+        hold.close_read()
+        try:
+            _write_ugid_map(pid1, os.geteuid(), os.getegid())
+            go.write_bytes(b"g")
+            go.close_write()
+
+            self.assertEqual(ready.read_bytes(), b"p")
+            ready.close_read()
+
+            cell.mount_fs("tmpfs", "sub")
+
+            pid2 = rc.run_in_rootns(
+                cell.cfd,
+                lambda: (
+                    0
+                    if os.path.exists("/pivoted") and os.path.ismount("/sub")
+                    else 1
+                ),
+            )
+            self.assertEqual(_reap_exit_code(pid2), 0)
+        finally:
+            hold.close_write()
+            self.assertEqual(_reap_exit_code(pid1), 0)
+
+        ext_ready = SyncPipe.create()
+        ext_hold = SyncPipe.create()
+        plain_pid = os.fork()
+        if plain_pid == 0:
+            ext_ready.close_read()
+            ext_hold.close_write()
+            try:
+                rc.unshare(rc.CLONE_NEWNS)
+                rc.make_mount_private("/")
+                tfd = rc.fsopen("tmpfs")
+                rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)
+                mfd = rc.fsmount(tfd)
+                os.close(tfd)
+                rc.move_mount(
+                    mfd, "", rc.AT_FDCWD, "/tmp", rc.MOVE_MOUNT_F_EMPTY_PATH
+                )
+                os.close(mfd)
+                os.mkdir("/tmp/target", 0o755)
+                ext_ready.write_bytes(b"r")
+                ext_ready.close_write()
+                ext_hold.read_bytes()
+                ext_hold.close_read()
+                os._exit(0 if os.path.ismount("/tmp/target") else 2)
+            except BaseException:
+                os._exit(1)
+        ext_ready.close_write()
+        ext_hold.close_read()
+        try:
+            self.assertEqual(ext_ready.read_bytes(), b"r")
+            ext_ready.close_read()
+            ext_mntns = os.open(
+                f"/proc/{plain_pid}/ns/mnt", os.O_RDONLY | os.O_CLOEXEC
+            )
+            try:
+                tfd = rc.fsopen("tmpfs")
+                rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)
+                mfd = rc.fsmount(tfd)
+                os.close(tfd)
+                with self.assertRaises(OSError) as cm:
+                    rc.move_mount(
+                        mfd,
+                        "",
+                        ext_mntns,
+                        "tmp/..",
+                        rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                    )
+                self.assertEqual(cm.exception.errno, errno.EBUSY)
+                with self.assertRaises(OSError) as cm:
+                    rc.move_mount(
+                        mfd,
+                        "",
+                        ext_mntns,
+                        "tmp/..",
+                        rc.MOVE_MOUNT_F_EMPTY_PATH
+                        | rc.MOVE_MOUNT_T_MNTNS
+                        | rc.MOVE_MOUNT_BENEATH,
+                    )
+                self.assertEqual(cm.exception.errno, errno.EINVAL)
+                rc.move_mount(
+                    mfd,
+                    "",
+                    ext_mntns,
+                    "tmp/target",
+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                )
+                os.close(mfd)
+            finally:
+                os.close(ext_mntns)
+        finally:
+            ext_hold.close_write()
+        self.assertEqual(_reap_exit_code(plain_pid), 0)
+
+    def test_unprivileged_without_entering_userns(self) -> None:
+        worker = os.fork()
+        if worker == 0:
+            try:
+                if os.geteuid() == 0:
+                    try:
+                        _drop_to_uid(1000)
+                    except OSError as exc:
+                        if exc.errno == errno.EINVAL:
+                            os._exit(SKIP_EXIT)
+                        os._exit(1)
+
+                try:
+                    tfd = rc.fsopen("tmpfs")
+                except OSError as exc:
+                    if exc.errno != errno.EPERM:
+                        os._exit(2)
+                else:
+                    try:
+                        rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)
+                        os._exit(3)
+                    except OSError as exc:
+                        if exc.errno != errno.EPERM:
+                            os._exit(4)
+                    finally:
+                        os.close(tfd)
+
+                try:
+                    cfd = rc.rootns()
+                except OSError as exc:
+                    if exc.errno in SKIP_ERRNOS:
+                        os._exit(SKIP_EXIT)
+                    os._exit(5)
+
+                mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)
+                rootfd = rc.make_rootns_mount(cfd, "tmpfs")
+                rc.move_mount(
+                    rootfd,
+                    "",
+                    mntns_fd,
+                    "/",
+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                )
+                os.close(rootfd)
+
+                go = SyncPipe.create()
+                ack = SyncPipe.create()
+
+                def unpriv_init() -> int:
+                    go.close_write()
+                    ack.close_read()
+                    rc.prctl(rc.PR_SET_DUMPABLE, 1)
+                    ack.write_bytes(b"d")
+                    if go.read_bytes() != b"1":
+                        return 1
+                    os.mkdir("/proc", 0o755)
+                    ack.write_bytes(b"m")
+                    ack.close_write()
+                    if go.read_bytes() != b"2":
+                        return 2
+                    go.close_read()
+                    pids = [e for e in os.listdir("/proc") if e.isdigit()]
+                    return 0 if pids == ["1"] else 3
+
+                pid = rc.run_in_rootns(cfd, unpriv_init)
+                go.close_read()
+                ack.close_write()
+
+                if ack.read_bytes() != b"d":
+                    os._exit(6)
+                _write_ugid_map(pid, os.geteuid(), os.getegid())
+                go.write_bytes(b"1")
+                if ack.read_bytes() != b"m":
+                    os._exit(6)
+                ack.close_read()
+
+                pfd = rc.make_rootns_mount(cfd, "proc")
+                rc.move_mount(
+                    pfd,
+                    "",
+                    mntns_fd,
+                    "proc",
+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,
+                )
+                os.close(pfd)
+                os.close(mntns_fd)
+
+                go.write_bytes(b"2")
+                go.close_write()
+
+                res = rc.rootns_wait(cfd)
+                os.close(cfd)
+                if res.pid != pid or res.exit_code != 0:
+                    os._exit(7)
+                if _reap_exit_code(pid) != 0:
+                    os._exit(8)
+                os._exit(0)
+            except BaseException:
+                os._exit(9)
+
+        code = _reap_exit_code(worker)
+        if code == SKIP_EXIT:
+            self.skipTest("unprivileged rootns unavailable")
+        self.assertEqual(code, 0)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tools/testing/selftests/rootns/test_smoke.sh b/tools/testing/selftests/rootns/test_smoke.sh
new file mode 100755
index 000000000000..2cb23ca2ad29
--- /dev/null
+++ b/tools/testing/selftests/rootns/test_smoke.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+
+# Kselftest framework requirement - SKIP code is 4.
+ksft_skip=4
+
+command -v python3 >/dev/null 2>&1 || exit $ksft_skip
+
+DIR="$(dirname "$(readlink -f "$0")")"
+PYTHONPATH="$DIR${PYTHONPATH:+:$PYTHONPATH}" \
+	python3 -m unittest -v rootns_test 2>&1
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

* [RFC PATCH v4 14/14] MAINTAINERS: Add entry for ROOT NAMESPACE
  2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
                   ` (12 preceding siblings ...)
  2026-11-19 22:43 ` [RFC PATCH v4 13/14] selftests/rootns: Add root namespace test suite Jarkko Sakkinen
@ 2026-11-19 22:43 ` Jarkko Sakkinen
  13 siblings, 0 replies; 15+ messages in thread
From: Jarkko Sakkinen @ 2026-11-19 22:43 UTC (permalink / raw)
  To: linux-fsdevel
  Cc: Jarkko Sakkinen, linux-api, linux-arch, linux-doc, linux-kernel,
	linux-kselftest, linux-mm, linux-security-module, Albert Ou,
	Alexander Gordeev, Alexander Viro, Alexandre Ghiti,
	Andreas Larsson, Andrew Morton, Andy Lutomirski, Andy Lutomirski,
	Anna-Maria Behnsen, Arnd Bergmann, Ben Segall, Borislav Petkov,
	Casey Schaufler, Catalin Marinas, Christian Borntraeger,
	Christian Brauner, Christophe Leroy (CS GROUP),
	Chris Zankel, Dave Hansen, David Hildenbrand, David Howells,
	Davidlohr Bueso, David S. Miller, Dietmar Eggemann,
	Frederic Weisbecker, Geert Uytterhoeven,
	Hallgrimur H. Gunnarsson, Heiko Carstens, Helge Deller,
	H. Peter Anvin, Ingo Molnar, James E.J. Bottomley, Jan Kara,
	John Johansen, John Paul Adrian Glaubitz, Jonathan Corbet,
	Josef Bacik, Juri Lelli, Kees Cook, K Prateek Nayak,
	Liam R. Howlett, Lorenzo Stoakes, Madhavan Srinivasan,
	Magnus Lindholm, Manfred Spraul, Mark Rutland, Matt Turner,
	Max Filippov, Mel Gorman, Michael Ellerman, Michal Hocko,
	Michal Simek, Mike Rapoport, Neal Gompa, Nicholas Piggin,
	Palmer Dabbelt, Paul Moore, Paul Walmsley, Pavel Tikhomirov,
	Peter Zijlstra, Randy Dunlap, Richard Henderson, Rich Felker,
	Ritesh Harjani (IBM),
	Russell King, Serge Hallyn, Shrikanth Hegde, Shuah Khan,
	Steven Rostedt, Suren Baghdasaryan, Sven Schnelle,
	Thomas Bogendoerfer, Thomas Gleixner, Valentin Schneider,
	Vasily Gorbik, Vincent Guittot, Vincenzo Frascino,
	Vlastimil Babka, Will Deacon, Yoshinori Sato, Zygmunt Krynicki

Record maintainership and mailing list routing for the root namespace
subsystem across its uAPI headers, core implementation, documentation,
and selftests.

Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
---
 MAINTAINERS | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 7cbce21ba45a..072be5ec7fd8 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -24533,6 +24533,17 @@ F:	include/linux/mfd/rohm-bd96802.h
 F:	include/linux/mfd/rohm-generic.h
 F:	include/linux/mfd/rohm-shared.h
 
+ROOT NAMESPACE
+M:	David Howells <dhowells@redhat.com>
+M:	Jarkko Sakkinen <jarkko@kernel.org>
+L:	linux-fsdevel@vger.kernel.org
+S:	Maintained
+F:	Documentation/userspace-api/rootns.rst
+F:	include/linux/rootns.h
+F:	include/uapi/linux/rootns.h
+F:	kernel/rootns.c
+F:	tools/testing/selftests/rootns/
+
 ROTATION DRIVER FOR ALLWINNER A83T
 M:	Jernej Skrabec <jernej.skrabec@gmail.com>
 L:	linux-media@vger.kernel.org
-- 
2.47.3


^ permalink raw reply	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2026-11-19 22:44 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-19 22:42 [RFC PATCH v4 00/14] Namespace for namespace roots Jarkko Sakkinen
2026-11-19 22:42 ` [RFC PATCH v4 01/14] nsproxy: Pass nsproxy to create_new_namespaces() Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 02/14] rootns: Add core infrastructure for root namespaces Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 03/14] rootns: Track init lifecycle via copy_process() and pid_namespace Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 04/14] rootns: Add rootns() system call Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 05/14] rootns: Add ROOTNS_WAIT ioctl Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 06/14] rootns: Add ROOTNS_KILL ioctl Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 07/14] fork: Support CLONE_INTO_ROOTNS in clone3() Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 08/14] fs: Support FSCONFIG_SET_ROOTNS in fsconfig() Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 09/14] fs: Support MOVE_MOUNT_T_MNTNS in move_mount() Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 10/14] security: Add rootns LSM hooks Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 11/14] arch: Wire up rootns() system call Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 12/14] docs: Document root namespace uAPI Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 13/14] selftests/rootns: Add root namespace test suite Jarkko Sakkinen
2026-11-19 22:43 ` [RFC PATCH v4 14/14] MAINTAINERS: Add entry for ROOT NAMESPACE Jarkko Sakkinen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®